mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-27 11:24:43 +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:
@@ -251,6 +251,7 @@ export const saveAssetEmbeddingsActivity = defineStep(
|
||||
embedding: number[]
|
||||
startTime?: number
|
||||
endTime?: number
|
||||
sprite?: PrismaJson.VideoChunkSprite
|
||||
}>
|
||||
}) {
|
||||
for (const item of params.embeddings) {
|
||||
@@ -258,15 +259,16 @@ export const saveAssetEmbeddingsActivity = defineStep(
|
||||
const is768 = item.embedding.length === 768
|
||||
|
||||
if (item.startTime !== undefined && item.endTime !== undefined) {
|
||||
const sprite = item.sprite ? JSON.stringify(item.sprite) : null
|
||||
if (is768) {
|
||||
await prisma.$executeRaw`
|
||||
INSERT INTO asset_embeddings (id, asset_id, embedding_768, start_time, end_time, updated_at)
|
||||
VALUES (gen_random_uuid()::text, ${params.assetId}, ${embVec}::vector, ${item.startTime}, ${item.endTime}, NOW())
|
||||
INSERT INTO asset_embeddings (id, asset_id, embedding_768, start_time, end_time, sprite, updated_at)
|
||||
VALUES (gen_random_uuid()::text, ${params.assetId}, ${embVec}::vector, ${item.startTime}, ${item.endTime}, ${sprite}::jsonb, NOW())
|
||||
`
|
||||
} else {
|
||||
await prisma.$executeRaw`
|
||||
INSERT INTO asset_embeddings (id, asset_id, embedding, start_time, end_time, updated_at)
|
||||
VALUES (gen_random_uuid()::text, ${params.assetId}, ${embVec}::vector, ${item.startTime}, ${item.endTime}, NOW())
|
||||
INSERT INTO asset_embeddings (id, asset_id, embedding, start_time, end_time, sprite, updated_at)
|
||||
VALUES (gen_random_uuid()::text, ${params.assetId}, ${embVec}::vector, ${item.startTime}, ${item.endTime}, ${sprite}::jsonb, NOW())
|
||||
`
|
||||
}
|
||||
} else {
|
||||
@@ -512,6 +514,7 @@ export interface VideoChunkRange {
|
||||
|
||||
export interface TranscodedVideoChunk extends VideoChunkRange {
|
||||
chunkKey: string
|
||||
sprite?: PrismaJson.VideoChunkSprite
|
||||
}
|
||||
|
||||
export interface TranscodeVideoChunksParams {
|
||||
|
||||
@@ -206,6 +206,7 @@ export async function agentEmbeddingMedia(task: WorkflowTask): Promise<void> {
|
||||
embedding: chunkResult.embedding,
|
||||
startTime: chunk.startTime,
|
||||
endTime: chunk.endTime,
|
||||
...(chunk.sprite && { sprite: chunk.sprite }),
|
||||
},
|
||||
],
|
||||
})
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
-- AlterTable
|
||||
ALTER TABLE "asset_embeddings" ADD COLUMN "sprite" JSONB;
|
||||
@@ -733,6 +733,8 @@ model AssetEmbedding {
|
||||
embedding768 Unsupported("vector(768)")? @map("embedding_768")
|
||||
startTime Float? @map("start_time")
|
||||
endTime Float? @map("end_time")
|
||||
/// [VideoChunkSprite]
|
||||
sprite Json?
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
|
||||
|
||||
+4
-4
File diff suppressed because one or more lines are too long
@@ -5356,6 +5356,7 @@ export const AssetEmbeddingScalarFieldEnum = {
|
||||
id: 'id',
|
||||
startTime: 'startTime',
|
||||
endTime: 'endTime',
|
||||
sprite: 'sprite',
|
||||
createdAt: 'createdAt',
|
||||
updatedAt: 'updatedAt',
|
||||
assetId: 'assetId'
|
||||
|
||||
@@ -456,6 +456,7 @@ export const AssetEmbeddingScalarFieldEnum = {
|
||||
id: 'id',
|
||||
startTime: 'startTime',
|
||||
endTime: 'endTime',
|
||||
sprite: 'sprite',
|
||||
createdAt: 'createdAt',
|
||||
updatedAt: 'updatedAt',
|
||||
assetId: 'assetId'
|
||||
|
||||
+33
-1
@@ -60,6 +60,7 @@ export type AssetEmbeddingCountAggregateOutputType = {
|
||||
id: number
|
||||
startTime: number
|
||||
endTime: number
|
||||
sprite: number
|
||||
createdAt: number
|
||||
updatedAt: number
|
||||
assetId: number
|
||||
@@ -99,6 +100,7 @@ export type AssetEmbeddingCountAggregateInputType = {
|
||||
id?: true
|
||||
startTime?: true
|
||||
endTime?: true
|
||||
sprite?: true
|
||||
createdAt?: true
|
||||
updatedAt?: true
|
||||
assetId?: true
|
||||
@@ -195,6 +197,7 @@ export type AssetEmbeddingGroupByOutputType = {
|
||||
id: string
|
||||
startTime: number | null
|
||||
endTime: number | null
|
||||
sprite:PrismaJson.VideoChunkSprite | null
|
||||
createdAt: Date
|
||||
updatedAt: Date
|
||||
assetId: string
|
||||
@@ -227,6 +230,7 @@ export type AssetEmbeddingWhereInput = {
|
||||
id?: Prisma.StringFilter<"AssetEmbedding"> | string
|
||||
startTime?: Prisma.FloatNullableFilter<"AssetEmbedding"> | number | null
|
||||
endTime?: Prisma.FloatNullableFilter<"AssetEmbedding"> | number | null
|
||||
sprite?: Prisma.JsonNullableFilter<"AssetEmbedding">
|
||||
createdAt?: Prisma.DateTimeFilter<"AssetEmbedding"> | Date | string
|
||||
updatedAt?: Prisma.DateTimeFilter<"AssetEmbedding"> | Date | string
|
||||
assetId?: Prisma.StringFilter<"AssetEmbedding"> | string
|
||||
@@ -237,6 +241,7 @@ export type AssetEmbeddingOrderByWithRelationInput = {
|
||||
id?: Prisma.SortOrder
|
||||
startTime?: Prisma.SortOrderInput | Prisma.SortOrder
|
||||
endTime?: Prisma.SortOrderInput | Prisma.SortOrder
|
||||
sprite?: Prisma.SortOrderInput | Prisma.SortOrder
|
||||
createdAt?: Prisma.SortOrder
|
||||
updatedAt?: Prisma.SortOrder
|
||||
assetId?: Prisma.SortOrder
|
||||
@@ -250,6 +255,7 @@ export type AssetEmbeddingWhereUniqueInput = Prisma.AtLeast<{
|
||||
NOT?: Prisma.AssetEmbeddingWhereInput | Prisma.AssetEmbeddingWhereInput[]
|
||||
startTime?: Prisma.FloatNullableFilter<"AssetEmbedding"> | number | null
|
||||
endTime?: Prisma.FloatNullableFilter<"AssetEmbedding"> | number | null
|
||||
sprite?: Prisma.JsonNullableFilter<"AssetEmbedding">
|
||||
createdAt?: Prisma.DateTimeFilter<"AssetEmbedding"> | Date | string
|
||||
updatedAt?: Prisma.DateTimeFilter<"AssetEmbedding"> | Date | string
|
||||
assetId?: Prisma.StringFilter<"AssetEmbedding"> | string
|
||||
@@ -260,6 +266,7 @@ export type AssetEmbeddingOrderByWithAggregationInput = {
|
||||
id?: Prisma.SortOrder
|
||||
startTime?: Prisma.SortOrderInput | Prisma.SortOrder
|
||||
endTime?: Prisma.SortOrderInput | Prisma.SortOrder
|
||||
sprite?: Prisma.SortOrderInput | Prisma.SortOrder
|
||||
createdAt?: Prisma.SortOrder
|
||||
updatedAt?: Prisma.SortOrder
|
||||
assetId?: Prisma.SortOrder
|
||||
@@ -277,6 +284,7 @@ export type AssetEmbeddingScalarWhereWithAggregatesInput = {
|
||||
id?: Prisma.StringWithAggregatesFilter<"AssetEmbedding"> | string
|
||||
startTime?: Prisma.FloatNullableWithAggregatesFilter<"AssetEmbedding"> | number | null
|
||||
endTime?: Prisma.FloatNullableWithAggregatesFilter<"AssetEmbedding"> | number | null
|
||||
sprite?: Prisma.JsonNullableWithAggregatesFilter<"AssetEmbedding">
|
||||
createdAt?: Prisma.DateTimeWithAggregatesFilter<"AssetEmbedding"> | Date | string
|
||||
updatedAt?: Prisma.DateTimeWithAggregatesFilter<"AssetEmbedding"> | Date | string
|
||||
assetId?: Prisma.StringWithAggregatesFilter<"AssetEmbedding"> | string
|
||||
@@ -286,6 +294,7 @@ export type AssetEmbeddingCreateInput = {
|
||||
id?: string
|
||||
startTime?: number | null
|
||||
endTime?: number | null
|
||||
sprite?:PrismaJson.VideoChunkSprite | Prisma.NullableJsonNullValueInput
|
||||
createdAt?: Date | string
|
||||
updatedAt?: Date | string
|
||||
asset: Prisma.AssetCreateNestedOneWithoutEmbeddingsInput
|
||||
@@ -295,6 +304,7 @@ export type AssetEmbeddingUncheckedCreateInput = {
|
||||
id?: string
|
||||
startTime?: number | null
|
||||
endTime?: number | null
|
||||
sprite?:PrismaJson.VideoChunkSprite | Prisma.NullableJsonNullValueInput
|
||||
createdAt?: Date | string
|
||||
updatedAt?: Date | string
|
||||
assetId: string
|
||||
@@ -304,6 +314,7 @@ export type AssetEmbeddingUpdateInput = {
|
||||
id?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
startTime?: Prisma.NullableFloatFieldUpdateOperationsInput | number | null
|
||||
endTime?: Prisma.NullableFloatFieldUpdateOperationsInput | number | null
|
||||
sprite?:PrismaJson.VideoChunkSprite | Prisma.NullableJsonNullValueInput
|
||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
asset?: Prisma.AssetUpdateOneRequiredWithoutEmbeddingsNestedInput
|
||||
@@ -313,6 +324,7 @@ export type AssetEmbeddingUncheckedUpdateInput = {
|
||||
id?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
startTime?: Prisma.NullableFloatFieldUpdateOperationsInput | number | null
|
||||
endTime?: Prisma.NullableFloatFieldUpdateOperationsInput | number | null
|
||||
sprite?:PrismaJson.VideoChunkSprite | Prisma.NullableJsonNullValueInput
|
||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
assetId?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
@@ -322,6 +334,7 @@ export type AssetEmbeddingCreateManyInput = {
|
||||
id?: string
|
||||
startTime?: number | null
|
||||
endTime?: number | null
|
||||
sprite?:PrismaJson.VideoChunkSprite | Prisma.NullableJsonNullValueInput
|
||||
createdAt?: Date | string
|
||||
updatedAt?: Date | string
|
||||
assetId: string
|
||||
@@ -331,6 +344,7 @@ export type AssetEmbeddingUpdateManyMutationInput = {
|
||||
id?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
startTime?: Prisma.NullableFloatFieldUpdateOperationsInput | number | null
|
||||
endTime?: Prisma.NullableFloatFieldUpdateOperationsInput | number | null
|
||||
sprite?:PrismaJson.VideoChunkSprite | Prisma.NullableJsonNullValueInput
|
||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
}
|
||||
@@ -339,6 +353,7 @@ export type AssetEmbeddingUncheckedUpdateManyInput = {
|
||||
id?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
startTime?: Prisma.NullableFloatFieldUpdateOperationsInput | number | null
|
||||
endTime?: Prisma.NullableFloatFieldUpdateOperationsInput | number | null
|
||||
sprite?:PrismaJson.VideoChunkSprite | Prisma.NullableJsonNullValueInput
|
||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
assetId?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
@@ -358,6 +373,7 @@ export type AssetEmbeddingCountOrderByAggregateInput = {
|
||||
id?: Prisma.SortOrder
|
||||
startTime?: Prisma.SortOrder
|
||||
endTime?: Prisma.SortOrder
|
||||
sprite?: Prisma.SortOrder
|
||||
createdAt?: Prisma.SortOrder
|
||||
updatedAt?: Prisma.SortOrder
|
||||
assetId?: Prisma.SortOrder
|
||||
@@ -437,6 +453,7 @@ export type AssetEmbeddingCreateWithoutAssetInput = {
|
||||
id?: string
|
||||
startTime?: number | null
|
||||
endTime?: number | null
|
||||
sprite?:PrismaJson.VideoChunkSprite | Prisma.NullableJsonNullValueInput
|
||||
createdAt?: Date | string
|
||||
updatedAt?: Date | string
|
||||
}
|
||||
@@ -445,6 +462,7 @@ export type AssetEmbeddingUncheckedCreateWithoutAssetInput = {
|
||||
id?: string
|
||||
startTime?: number | null
|
||||
endTime?: number | null
|
||||
sprite?:PrismaJson.VideoChunkSprite | Prisma.NullableJsonNullValueInput
|
||||
createdAt?: Date | string
|
||||
updatedAt?: Date | string
|
||||
}
|
||||
@@ -482,6 +500,7 @@ export type AssetEmbeddingScalarWhereInput = {
|
||||
id?: Prisma.StringFilter<"AssetEmbedding"> | string
|
||||
startTime?: Prisma.FloatNullableFilter<"AssetEmbedding"> | number | null
|
||||
endTime?: Prisma.FloatNullableFilter<"AssetEmbedding"> | number | null
|
||||
sprite?: Prisma.JsonNullableFilter<"AssetEmbedding">
|
||||
createdAt?: Prisma.DateTimeFilter<"AssetEmbedding"> | Date | string
|
||||
updatedAt?: Prisma.DateTimeFilter<"AssetEmbedding"> | Date | string
|
||||
assetId?: Prisma.StringFilter<"AssetEmbedding"> | string
|
||||
@@ -491,6 +510,7 @@ export type AssetEmbeddingCreateManyAssetInput = {
|
||||
id?: string
|
||||
startTime?: number | null
|
||||
endTime?: number | null
|
||||
sprite?:PrismaJson.VideoChunkSprite | Prisma.NullableJsonNullValueInput
|
||||
createdAt?: Date | string
|
||||
updatedAt?: Date | string
|
||||
}
|
||||
@@ -499,6 +519,7 @@ export type AssetEmbeddingUpdateWithoutAssetInput = {
|
||||
id?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
startTime?: Prisma.NullableFloatFieldUpdateOperationsInput | number | null
|
||||
endTime?: Prisma.NullableFloatFieldUpdateOperationsInput | number | null
|
||||
sprite?:PrismaJson.VideoChunkSprite | Prisma.NullableJsonNullValueInput
|
||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
}
|
||||
@@ -507,6 +528,7 @@ export type AssetEmbeddingUncheckedUpdateWithoutAssetInput = {
|
||||
id?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
startTime?: Prisma.NullableFloatFieldUpdateOperationsInput | number | null
|
||||
endTime?: Prisma.NullableFloatFieldUpdateOperationsInput | number | null
|
||||
sprite?:PrismaJson.VideoChunkSprite | Prisma.NullableJsonNullValueInput
|
||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
}
|
||||
@@ -515,6 +537,7 @@ export type AssetEmbeddingUncheckedUpdateManyWithoutAssetInput = {
|
||||
id?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
startTime?: Prisma.NullableFloatFieldUpdateOperationsInput | number | null
|
||||
endTime?: Prisma.NullableFloatFieldUpdateOperationsInput | number | null
|
||||
sprite?:PrismaJson.VideoChunkSprite | Prisma.NullableJsonNullValueInput
|
||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
}
|
||||
@@ -525,6 +548,7 @@ export type AssetEmbeddingSelect<ExtArgs extends runtime.Types.Extensions.Intern
|
||||
id?: boolean
|
||||
startTime?: boolean
|
||||
endTime?: boolean
|
||||
sprite?: boolean
|
||||
createdAt?: boolean
|
||||
updatedAt?: boolean
|
||||
assetId?: boolean
|
||||
@@ -535,6 +559,7 @@ export type AssetEmbeddingSelectCreateManyAndReturn<ExtArgs extends runtime.Type
|
||||
id?: boolean
|
||||
startTime?: boolean
|
||||
endTime?: boolean
|
||||
sprite?: boolean
|
||||
createdAt?: boolean
|
||||
updatedAt?: boolean
|
||||
assetId?: boolean
|
||||
@@ -545,6 +570,7 @@ export type AssetEmbeddingSelectUpdateManyAndReturn<ExtArgs extends runtime.Type
|
||||
id?: boolean
|
||||
startTime?: boolean
|
||||
endTime?: boolean
|
||||
sprite?: boolean
|
||||
createdAt?: boolean
|
||||
updatedAt?: boolean
|
||||
assetId?: boolean
|
||||
@@ -555,12 +581,13 @@ export type AssetEmbeddingSelectScalar = {
|
||||
id?: boolean
|
||||
startTime?: boolean
|
||||
endTime?: boolean
|
||||
sprite?: boolean
|
||||
createdAt?: boolean
|
||||
updatedAt?: boolean
|
||||
assetId?: boolean
|
||||
}
|
||||
|
||||
export type AssetEmbeddingOmit<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = runtime.Types.Extensions.GetOmit<"id" | "startTime" | "endTime" | "createdAt" | "updatedAt" | "assetId", ExtArgs["result"]["assetEmbedding"]>
|
||||
export type AssetEmbeddingOmit<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = runtime.Types.Extensions.GetOmit<"id" | "startTime" | "endTime" | "sprite" | "createdAt" | "updatedAt" | "assetId", ExtArgs["result"]["assetEmbedding"]>
|
||||
export type AssetEmbeddingInclude<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = {
|
||||
asset?: boolean | Prisma.AssetDefaultArgs<ExtArgs>
|
||||
}
|
||||
@@ -580,6 +607,10 @@ export type $AssetEmbeddingPayload<ExtArgs extends runtime.Types.Extensions.Inte
|
||||
id: string
|
||||
startTime: number | null
|
||||
endTime: number | null
|
||||
/**
|
||||
* [VideoChunkSprite]
|
||||
*/
|
||||
sprite:PrismaJson.VideoChunkSprite | null
|
||||
createdAt: Date
|
||||
updatedAt: Date
|
||||
assetId: string
|
||||
@@ -1010,6 +1041,7 @@ export interface AssetEmbeddingFieldRefs {
|
||||
readonly id: Prisma.FieldRef<"AssetEmbedding", 'String'>
|
||||
readonly startTime: Prisma.FieldRef<"AssetEmbedding", 'Float'>
|
||||
readonly endTime: Prisma.FieldRef<"AssetEmbedding", 'Float'>
|
||||
readonly sprite: Prisma.FieldRef<"AssetEmbedding", 'Json'>
|
||||
readonly createdAt: Prisma.FieldRef<"AssetEmbedding", 'DateTime'>
|
||||
readonly updatedAt: Prisma.FieldRef<"AssetEmbedding", 'DateTime'>
|
||||
readonly assetId: Prisma.FieldRef<"AssetEmbedding", 'String'>
|
||||
|
||||
@@ -217,6 +217,8 @@ declare global {
|
||||
resolutions: VideoTranscode[]
|
||||
}
|
||||
|
||||
export type VideoChunkSprite = import('@shumai/dtos').SpriteLayout & { key: string }
|
||||
|
||||
export interface MediaInfo {
|
||||
duration: number
|
||||
filesize: number
|
||||
|
||||
@@ -25,6 +25,16 @@ export const previewInfoSchema = z.object({
|
||||
})
|
||||
export type PreviewInfo = z.infer<typeof previewInfoSchema>
|
||||
|
||||
const spriteLayoutSchema = z.object({
|
||||
columns: z.number().int().positive(),
|
||||
rows: z.number().int().positive(),
|
||||
frameCount: z.number().int().positive(),
|
||||
})
|
||||
export type SpriteLayout = z.infer<typeof spriteLayoutSchema>
|
||||
|
||||
const matchedSpriteSchema = spriteLayoutSchema.extend({ url: z.string() })
|
||||
export type MatchedSprite = z.infer<typeof matchedSpriteSchema>
|
||||
|
||||
export const childPreviewSchema = z.object({
|
||||
type: z.string().nullable(),
|
||||
preview: previewInfoSchema.nullable(),
|
||||
@@ -90,6 +100,7 @@ export const assetInfoSchema = z.object({
|
||||
sortIndex: z.string().optional().nullable(),
|
||||
startTime: z.number().optional().nullable(),
|
||||
endTime: z.number().optional().nullable(),
|
||||
matchedSprite: matchedSpriteSchema.optional(),
|
||||
hasAgentsMd: z.boolean().optional(),
|
||||
commentsCount: z.number().optional(),
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest'
|
||||
import { describe, it, expect, beforeAll, afterEach, afterAll, vi } from 'vitest'
|
||||
import { prisma, WorkflowTaskStatus } from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import { workflowService, TaskQueueAgent, TaskQueueTranscode } from '@shumai/workflow-core'
|
||||
@@ -8,6 +8,7 @@ import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { fileURLToPath } from 'url'
|
||||
import * as path from 'path'
|
||||
import * as fs from 'fs'
|
||||
import sharp from 'sharp'
|
||||
|
||||
const mockEmbedContent = vi.fn().mockResolvedValue({
|
||||
embeddings: [
|
||||
@@ -46,6 +47,11 @@ describe('Workflow E2E - agentEmbeddingMedia', () => {
|
||||
await workflowService.startWorkers([TaskQueueAgent, TaskQueueTranscode])
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
vi.unstubAllEnvs()
|
||||
})
|
||||
|
||||
afterAll(async () => {
|
||||
await workflowService.shutdownWorkers()
|
||||
workflowService.close()
|
||||
@@ -196,152 +202,216 @@ describe('Workflow E2E - agentEmbeddingMedia', () => {
|
||||
expect(dbEmbeddings[0].endTime).toBeNull()
|
||||
}, 50000)
|
||||
|
||||
it('should run agentEmbeddingMedia workflow for a video asset successfully', async () => {
|
||||
// 1. Seed Database
|
||||
const team = await prisma.team.create({
|
||||
data: { name: 'E2E Video Embedding Team' },
|
||||
})
|
||||
it.each([
|
||||
['gemini-embedding-2', 'no sprite metadata'],
|
||||
['gemma-embedding-2-openai', 'no sprite metadata'],
|
||||
['gemini-embedding-2', 'available full sprite'],
|
||||
['gemma-embedding-2-openai', 'available full sprite'],
|
||||
['gemma-embedding-2-openai', 'missing full sprite object'],
|
||||
])(
|
||||
'indexes an entire video with %s and %s',
|
||||
async (embeddingProvider, fullSpriteState) => {
|
||||
vi.stubEnv('EMBEDDING_PROVIDER', embeddingProvider)
|
||||
if (embeddingProvider === 'gemma-embedding-2-openai') {
|
||||
const endpoint = 'https://embedding.example.com/v1/embeddings'
|
||||
vi.stubEnv('GEMMA_EMBEDDING_OPENAI_BASE_URL', endpoint)
|
||||
const fetch = globalThis.fetch
|
||||
vi.spyOn(globalThis, 'fetch').mockImplementation((input, init) =>
|
||||
input === endpoint
|
||||
? Promise.resolve(
|
||||
Response.json({ data: [{ embedding: Array<number>(768).fill(0.2) }] }),
|
||||
)
|
||||
: fetch(input, init),
|
||||
)
|
||||
}
|
||||
// 1. Seed Database
|
||||
const team = await prisma.team.create({
|
||||
data: { name: 'E2E Video Embedding Team' },
|
||||
})
|
||||
|
||||
const project = await prisma.project.create({
|
||||
data: { name: 'E2E Video Embedding Project', teamId: team.id },
|
||||
})
|
||||
const project = await prisma.project.create({
|
||||
data: { name: 'E2E Video Embedding Project', teamId: team.id },
|
||||
})
|
||||
|
||||
const agentUser = await prisma.user.create({
|
||||
data: {
|
||||
name: 'E2E Video Embedding Agent User',
|
||||
email: 'e2e-vid-emb-agent@shumai.ai',
|
||||
type: 'agent',
|
||||
},
|
||||
})
|
||||
|
||||
await prisma.teamMember.create({
|
||||
data: {
|
||||
teamId: team.id,
|
||||
userId: agentUser.id,
|
||||
role: 'editor',
|
||||
},
|
||||
})
|
||||
|
||||
const provider = await prisma.provider.create({
|
||||
data: {
|
||||
name: 'google',
|
||||
teamId: team.id,
|
||||
config: { api: 'google-generative-ai', apiKey: 'dummy-google-api-key' },
|
||||
},
|
||||
})
|
||||
|
||||
const model = await prisma.model.create({
|
||||
data: {
|
||||
modelId: 'gemini',
|
||||
name: 'Gemini',
|
||||
providerId: provider.id,
|
||||
config: {
|
||||
input: ['text', 'image'],
|
||||
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
|
||||
contextWindow: 8192,
|
||||
maxTokens: 2048,
|
||||
reasoning: false,
|
||||
const agentUser = await prisma.user.create({
|
||||
data: {
|
||||
name: 'E2E Video Embedding Agent User',
|
||||
email: 'e2e-vid-emb-agent@shumai.ai',
|
||||
type: 'agent',
|
||||
},
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
await prisma.agent.create({
|
||||
data: {
|
||||
id: agentUser.id,
|
||||
teamId: team.id,
|
||||
type: 'embedding',
|
||||
enabled: true,
|
||||
providerId: provider.id,
|
||||
modelId: model.id,
|
||||
config: {
|
||||
provider: 'google',
|
||||
model: 'gemini',
|
||||
await prisma.teamMember.create({
|
||||
data: {
|
||||
teamId: team.id,
|
||||
userId: agentUser.id,
|
||||
role: 'editor',
|
||||
},
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
const storageKey = await prisma.storageKey.create({
|
||||
data: {
|
||||
key: 'projects/e2e/test-video.mp4',
|
||||
},
|
||||
})
|
||||
const provider = await prisma.provider.create({
|
||||
data: {
|
||||
name: 'google',
|
||||
teamId: team.id,
|
||||
config: { api: 'google-generative-ai', apiKey: 'dummy-google-api-key' },
|
||||
},
|
||||
})
|
||||
|
||||
const asset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'test-video.mp4',
|
||||
type: 'file',
|
||||
status: 'uploaded',
|
||||
mediaType: 'video/mp4',
|
||||
media: { duration: 1.0 } as unknown as PrismaJson.MediaInfo, // 1-second video
|
||||
projectId: project.id,
|
||||
storageKeyId: storageKey.id,
|
||||
},
|
||||
})
|
||||
const model = await prisma.model.create({
|
||||
data: {
|
||||
modelId: 'gemini',
|
||||
name: 'Gemini',
|
||||
providerId: provider.id,
|
||||
config: {
|
||||
input: ['text', 'image'],
|
||||
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
|
||||
contextWindow: 8192,
|
||||
maxTokens: 2048,
|
||||
reasoning: false,
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
// 2. Seed S3 Storage from Fixture
|
||||
const mp4Path = path.join(fixturesDir, 'small.mp4')
|
||||
const mp4Buffer = fs.readFileSync(mp4Path)
|
||||
await s3Service.putObject(
|
||||
'shumai-e2e-test-bucket-embedding',
|
||||
'projects/e2e/test-video.mp4',
|
||||
mp4Buffer,
|
||||
mp4Buffer.length,
|
||||
'video/mp4',
|
||||
)
|
||||
await prisma.agent.create({
|
||||
data: {
|
||||
id: agentUser.id,
|
||||
teamId: team.id,
|
||||
type: 'embedding',
|
||||
enabled: true,
|
||||
providerId: provider.id,
|
||||
modelId: model.id,
|
||||
config: {
|
||||
provider: 'google',
|
||||
model: 'gemini',
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
// 3. Create Workflow Task (ai_embedding, pending)
|
||||
const task = await prisma.workflowTask.create({
|
||||
data: {
|
||||
type: 'ai_embedding',
|
||||
status: 'pending',
|
||||
assetId: asset.id,
|
||||
projectId: project.id,
|
||||
teamId: team.id,
|
||||
payload: {
|
||||
const storageKey = await prisma.storageKey.create({
|
||||
data: {
|
||||
key: 'projects/e2e/test-video.mp4',
|
||||
},
|
||||
})
|
||||
|
||||
const bucket = 'shumai-e2e-test-bucket-embedding'
|
||||
const fullSpriteKey = `projects/e2e/${storageKey.id}-full.webp`
|
||||
const hasFullSprite = fullSpriteState === 'available full sprite'
|
||||
if (hasFullSprite) {
|
||||
const fullSprite = await sharp({
|
||||
create: { width: 640, height: 640, channels: 3, background: 'blue' },
|
||||
})
|
||||
.webp()
|
||||
.toBuffer()
|
||||
await s3Service.putObject(
|
||||
bucket,
|
||||
fullSpriteKey,
|
||||
fullSprite,
|
||||
fullSprite.length,
|
||||
'image/webp',
|
||||
)
|
||||
}
|
||||
const asset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'test-video.mp4',
|
||||
type: 'file',
|
||||
status: 'uploaded',
|
||||
mediaType: 'video/mp4',
|
||||
media: {
|
||||
duration: 1,
|
||||
proxyType: 'video',
|
||||
...(fullSpriteState !== 'no sprite metadata' && {
|
||||
sprite: { key: fullSpriteKey, frames: 100, tileX: 10, tileY: 10 },
|
||||
}),
|
||||
} as PrismaJson.MediaInfo,
|
||||
projectId: project.id,
|
||||
agent: { agentId: agentUser.id },
|
||||
storageKeyId: storageKey.id,
|
||||
},
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
// 4. Wait for workflow to complete
|
||||
console.log(
|
||||
`Submitted E2E Video Embedding Workflow Task. ID: ${task.id}. Awaiting completion...`,
|
||||
)
|
||||
const completedTask = await workflowService.executeWait(task, 45000)
|
||||
// 2. Seed S3 Storage from Fixture
|
||||
const mp4Path = path.join(fixturesDir, 'small.mp4')
|
||||
const mp4Buffer = fs.readFileSync(mp4Path)
|
||||
await s3Service.putObject(
|
||||
'shumai-e2e-test-bucket-embedding',
|
||||
'projects/e2e/test-video.mp4',
|
||||
mp4Buffer,
|
||||
mp4Buffer.length,
|
||||
'video/mp4',
|
||||
)
|
||||
|
||||
// 5. Verification
|
||||
expect(completedTask.status).toBe('completed')
|
||||
// 3. Create Workflow Task (ai_embedding, pending)
|
||||
const task = await prisma.workflowTask.create({
|
||||
data: {
|
||||
type: 'ai_embedding',
|
||||
status: 'pending',
|
||||
assetId: asset.id,
|
||||
projectId: project.id,
|
||||
teamId: team.id,
|
||||
payload: {
|
||||
projectId: project.id,
|
||||
agent: { agentId: agentUser.id },
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
// Verify batch transcode_video_chunks task was created and completed on TaskQueueTranscode
|
||||
const chunkTasks = await prisma.workflowTask.findMany({
|
||||
where: {
|
||||
assetId: asset.id,
|
||||
type: 'transcode_video_chunks',
|
||||
},
|
||||
})
|
||||
expect(chunkTasks).toHaveLength(1)
|
||||
expect(chunkTasks[0].status).toBe(WorkflowTaskStatus.completed)
|
||||
expect(chunkTasks[0].payload?.videoChunks?.parentTaskId).toBe(task.id)
|
||||
// 4. Wait for workflow to complete
|
||||
console.log(
|
||||
`Submitted E2E Video Embedding Workflow Task. ID: ${task.id}. Awaiting completion...`,
|
||||
)
|
||||
const completedTask = await workflowService.executeWait(task, 45000)
|
||||
|
||||
// Verify raw embedding is saved in DB with start and end times
|
||||
const dbEmbeddings = (await prisma.$queryRaw`
|
||||
SELECT id, asset_id as "assetId", start_time as "startTime", end_time as "endTime"
|
||||
FROM asset_embeddings
|
||||
WHERE asset_id = ${asset.id}
|
||||
ORDER BY start_time ASC
|
||||
`) as { id: string; startTime: number | null; endTime: number | null }[]
|
||||
expect(dbEmbeddings.length).toBeGreaterThan(0)
|
||||
expect(dbEmbeddings[0].startTime).toBe(0)
|
||||
expect(dbEmbeddings[0].endTime).toBe(1)
|
||||
// 5. Verification
|
||||
expect(completedTask.status).toBe('completed')
|
||||
|
||||
// Verify all temporary embedding chunk files were cleaned up from S3
|
||||
const remainingTmpChunks = await s3Service.listObjects(
|
||||
'shumai-e2e-test-bucket-embedding',
|
||||
`files/${asset.id}/tmp-embedding-chunks/`,
|
||||
)
|
||||
expect(remainingTmpChunks).toEqual([])
|
||||
}, 50000)
|
||||
// Verify batch transcode_video_chunks task was created and completed on TaskQueueTranscode
|
||||
const chunkTasks = await prisma.workflowTask.findMany({
|
||||
where: {
|
||||
assetId: asset.id,
|
||||
type: 'transcode_video_chunks',
|
||||
},
|
||||
})
|
||||
expect(chunkTasks).toHaveLength(1)
|
||||
expect(chunkTasks[0].status).toBe(WorkflowTaskStatus.completed)
|
||||
expect(chunkTasks[0].payload?.videoChunks?.parentTaskId).toBe(task.id)
|
||||
const dbEmbeddings = await prisma.assetEmbedding.findMany({ where: { assetId: asset.id } })
|
||||
expect(dbEmbeddings).toHaveLength(1)
|
||||
expect(dbEmbeddings[0].startTime).toBe(0)
|
||||
expect(dbEmbeddings[0].endTime).toBe(1)
|
||||
const sprite = dbEmbeddings[0].sprite
|
||||
const format = embeddingProvider === 'gemma-embedding-2-openai' ? 'frames' : 'video'
|
||||
if (hasFullSprite) {
|
||||
expect(sprite).toBeNull()
|
||||
expect(
|
||||
await s3Service.listObjects(bucket, `projects/e2e/chunk-sprites/${asset.id}/`),
|
||||
).toEqual([])
|
||||
await s3Service.deleteObject(bucket, fullSpriteKey)
|
||||
} else {
|
||||
expect(chunkTasks[0].output).toMatchObject({
|
||||
chunks: [{ sprite: { columns: 1, rows: 1, frameCount: 1 } }],
|
||||
})
|
||||
expect(sprite).toEqual({
|
||||
key: `projects/e2e/chunk-sprites/${asset.id}/${format}-0-1.webp`,
|
||||
columns: 1,
|
||||
rows: 1,
|
||||
frameCount: 1,
|
||||
})
|
||||
const { buffer } = await s3Service.getObject(bucket, sprite!.key)
|
||||
expect(await sharp(buffer).metadata()).toMatchObject({
|
||||
format: 'webp',
|
||||
width: 64,
|
||||
height: 64,
|
||||
})
|
||||
}
|
||||
|
||||
// Verify all temporary embedding chunk files were cleaned up from S3
|
||||
const remainingTmpChunks = await s3Service.listObjects(
|
||||
'shumai-e2e-test-bucket-embedding',
|
||||
`files/${asset.id}/tmp-embedding-chunks/`,
|
||||
)
|
||||
expect(remainingTmpChunks).toEqual([])
|
||||
},
|
||||
50000,
|
||||
)
|
||||
|
||||
it('should fail agentEmbeddingMedia workflow for an unsupported audio asset', async () => {
|
||||
// 1. Seed Database
|
||||
|
||||
@@ -9,12 +9,17 @@ import {
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { gotenbergService } from '@shumai/core/src/gotenberg/gotenberg'
|
||||
import { transcodeService } from '@shumai/core/src/transcode/transcode'
|
||||
import { sampleVideoChunkSprite } from '@shumai/core/src/transcode/video-chunk-sprite'
|
||||
import * as child_process from 'child_process'
|
||||
import * as fs from 'fs'
|
||||
|
||||
vi.mock('child_process', () => ({
|
||||
execFile: vi.fn(),
|
||||
}))
|
||||
vi.mock('@shumai/core/src/transcode/video-chunk-sprite', () => ({
|
||||
composeVideoChunkSprite: vi.fn(),
|
||||
sampleVideoChunkSprite: vi.fn(),
|
||||
}))
|
||||
import {
|
||||
ensureLocalMediaFile,
|
||||
getMediaInfoActivity,
|
||||
@@ -1238,6 +1243,42 @@ describe('Transcode Activities', () => {
|
||||
})
|
||||
|
||||
describe('Video Chunk Activities', () => {
|
||||
it('returns the embedding clip when the optional sprite upload fails', async () => {
|
||||
vi.mocked(child_process.execFile).mockImplementation(
|
||||
// The activity awaits the promisified callback overload.
|
||||
((_file: string, _args: string[], callback: (err: null) => void) => {
|
||||
callback(null)
|
||||
}) as typeof child_process.execFile,
|
||||
)
|
||||
vi.mocked(sampleVideoChunkSprite).mockResolvedValueOnce({
|
||||
image: Buffer.from('mock sprite'),
|
||||
columns: 1,
|
||||
rows: 1,
|
||||
frameCount: 1,
|
||||
})
|
||||
vi.mocked(s3Service.putObject)
|
||||
.mockResolvedValueOnce(undefined)
|
||||
.mockRejectedValueOnce(new Error('Sprite storage unavailable'))
|
||||
|
||||
const chunk = await transcodeVideoChunkActivity({
|
||||
assetId: 'asset-abc',
|
||||
assetKey: 'files/storage-id/proxy.mp4',
|
||||
originalKey: 'files/storage-id/original.mp4',
|
||||
startTime: 0,
|
||||
endTime: 1,
|
||||
})
|
||||
|
||||
expect(chunk.chunkKey).toMatch(/\.mp4$/)
|
||||
expect(chunk.sprite).toBeUndefined()
|
||||
expect(s3Service.putObject).toHaveBeenLastCalledWith(
|
||||
'shumai',
|
||||
'files/storage-id/chunk-sprites/asset-abc/video-0-1.webp',
|
||||
expect.any(Buffer),
|
||||
expect.any(Number),
|
||||
'image/webp',
|
||||
)
|
||||
})
|
||||
|
||||
it('should transcode video chunk using ffmpeg and upload to S3', async () => {
|
||||
// Mock child_process.execFile to simulate ffmpeg succeeding
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
|
||||
@@ -8,6 +8,11 @@ import {
|
||||
} from '@shumai/core/src/transcode/transcode'
|
||||
import { metadataService } from '@shumai/core/src/metadata/metadata'
|
||||
import { getDerivedArtifactDirectory, stemFromKey } from '@shumai/core/src/utils/filename'
|
||||
import {
|
||||
composeVideoChunkSprite,
|
||||
sampleVideoChunkSprite,
|
||||
} from '@shumai/core/src/transcode/video-chunk-sprite'
|
||||
import { hasStoredVideoSprite } from '@shumai/core/src/transcode/video-sprite'
|
||||
import {
|
||||
gotenbergService,
|
||||
type GotenbergConvertOptions,
|
||||
@@ -1603,15 +1608,49 @@ export interface TranscodeVideoChunkParams {
|
||||
taskId?: string
|
||||
assetId: string
|
||||
assetKey?: string
|
||||
originalKey?: string
|
||||
filePath?: string
|
||||
startTime: number
|
||||
endTime: number
|
||||
format?: 'video' | 'frames'
|
||||
fullSpriteKey?: string
|
||||
}
|
||||
|
||||
async function uploadVideoChunkSprite(
|
||||
params: TranscodeVideoChunkParams,
|
||||
render: () => ReturnType<typeof composeVideoChunkSprite>,
|
||||
signal?: AbortSignal,
|
||||
): Promise<PrismaJson.VideoChunkSprite | undefined> {
|
||||
if (signal?.aborted) return
|
||||
try {
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
if (params.fullSpriteKey && (await hasStoredVideoSprite(bucket, params.fullSpriteKey))) return
|
||||
|
||||
if (signal?.aborted) return
|
||||
const sprite = await render()
|
||||
if (!sprite || signal?.aborted) return
|
||||
|
||||
const originalKey = params.originalKey ?? params.assetKey
|
||||
const directory = getDerivedArtifactDirectory(originalKey ?? '', params.assetId)
|
||||
const format = params.format ?? 'video'
|
||||
const key = `${directory}/chunk-sprites/${params.assetId}/${format}-${params.startTime}-${params.endTime}.webp`
|
||||
await ensureAssetNotPurgingByIdOrKey(params.assetId, originalKey)
|
||||
const { image, ...layout } = sprite
|
||||
await s3Service.putObject(bucket, key, image, image.length, 'image/webp')
|
||||
return { key, ...layout }
|
||||
} catch (err) {
|
||||
if (!signal?.aborted) {
|
||||
logger.warn(
|
||||
{ err, assetId: params.assetId, startTime: params.startTime, endTime: params.endTime },
|
||||
'Failed to generate video chunk sprite',
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const transcodeVideoChunkActivity = defineStep(async function transcodeVideoChunkActivity(
|
||||
params: TranscodeVideoChunkParams,
|
||||
): Promise<{ chunkKey: string }> {
|
||||
): Promise<{ chunkKey: string; sprite?: PrismaJson.VideoChunkSprite }> {
|
||||
if (!params.filePath && !params.assetKey) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'Neither filePath nor assetKey was provided for video chunk transcoding',
|
||||
@@ -1704,7 +1743,12 @@ export const transcodeVideoChunkActivity = defineStep(async function transcodeVi
|
||||
const key = `files/${params.assetId}/tmp-embedding-chunks/frames-${params.startTime}-${params.endTime}-${ulid()}.tar`
|
||||
await s3Service.putObject(bucket, key, archiveData, archiveData.length, 'application/x-tar')
|
||||
|
||||
return { chunkKey: key }
|
||||
const sprite = await uploadVideoChunkSprite(
|
||||
params,
|
||||
() => composeVideoChunkSprite(frameFiles.map((file) => path.join(tmpDir, file))),
|
||||
signal,
|
||||
)
|
||||
return sprite ? { chunkKey: key, sprite } : { chunkKey: key }
|
||||
} catch (err) {
|
||||
if (err instanceof ApplicationFailure) {
|
||||
throw err
|
||||
@@ -1777,7 +1821,12 @@ export const transcodeVideoChunkActivity = defineStep(async function transcodeVi
|
||||
|
||||
await s3Service.putObject(bucket, key, chunkData, chunkData.length, 'video/mp4')
|
||||
|
||||
return { chunkKey: key }
|
||||
const sprite = await uploadVideoChunkSprite(
|
||||
params,
|
||||
() => sampleVideoChunkSprite(chunkTmp, params.endTime - params.startTime, signal),
|
||||
signal,
|
||||
)
|
||||
return sprite ? { chunkKey: key, sprite } : { chunkKey: key }
|
||||
} catch (err) {
|
||||
if (err instanceof ApplicationFailure) {
|
||||
throw err
|
||||
|
||||
@@ -73,11 +73,19 @@ describe('transcodeVideoChunksWorkflow', () => {
|
||||
status: 'processed',
|
||||
storageKey: { key: 'files/asset-video/raw.mp4', isArchived: false },
|
||||
mediaType: 'video/mp4',
|
||||
media: { duration: 110, sprite: { key: 'files/asset-video/sprite.webp' } },
|
||||
} as unknown as Awaited<ReturnType<typeof getAssetActivity>>)
|
||||
|
||||
const sprite = {
|
||||
key: 'files/asset-video/chunk-sprites/asset-video/video-0-60.webp',
|
||||
columns: 5,
|
||||
rows: 3,
|
||||
frameCount: 15,
|
||||
}
|
||||
mockActivities.transcodeVideoChunkActivity
|
||||
.mockResolvedValueOnce({
|
||||
chunkKey: 'files/asset-video/tmp-embedding-chunks/chunk-0-60.mp4',
|
||||
sprite,
|
||||
})
|
||||
.mockResolvedValueOnce({
|
||||
chunkKey: 'files/asset-video/tmp-embedding-chunks/chunk-55-110.mp4',
|
||||
@@ -90,6 +98,7 @@ describe('transcodeVideoChunksWorkflow', () => {
|
||||
taskId: 'task-video-chunks',
|
||||
assetId: 'asset-video',
|
||||
assetKey: 'files/asset-video/proxy.mp4',
|
||||
originalKey: 'files/asset-video/raw.mp4',
|
||||
startTime: 0,
|
||||
endTime: 60,
|
||||
format: 'video',
|
||||
@@ -98,6 +107,7 @@ describe('transcodeVideoChunksWorkflow', () => {
|
||||
taskId: 'task-video-chunks',
|
||||
assetId: 'asset-video',
|
||||
assetKey: 'files/asset-video/proxy.mp4',
|
||||
originalKey: 'files/asset-video/raw.mp4',
|
||||
startTime: 55,
|
||||
endTime: 110,
|
||||
format: 'video',
|
||||
@@ -112,6 +122,7 @@ describe('transcodeVideoChunksWorkflow', () => {
|
||||
startTime: 0,
|
||||
endTime: 60,
|
||||
chunkKey: 'files/asset-video/tmp-embedding-chunks/chunk-0-60.mp4',
|
||||
sprite,
|
||||
},
|
||||
{
|
||||
startTime: 55,
|
||||
@@ -155,6 +166,7 @@ describe('transcodeVideoChunksWorkflow', () => {
|
||||
taskId: 'task-video-chunks',
|
||||
assetId: 'asset-video',
|
||||
assetKey: 'files/asset-video/proxy-720p.mp4',
|
||||
originalKey: 'files/asset-video/raw.mp4',
|
||||
startTime: 0,
|
||||
endTime: 30,
|
||||
format: 'frames',
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { logger } from '@shumai/core/src/logger'
|
||||
import { isFullVideoRange } from '@shumai/core/src/transcode/video-sprite'
|
||||
import type { WorkflowTask } from '@shumai/db'
|
||||
import { ApplicationFailure } from '@shumai/workflow-core'
|
||||
import { deleteS3ObjectActivity, transcodeVideoChunkActivity } from '../activities/transcode'
|
||||
@@ -8,6 +9,7 @@ export interface TranscodedVideoChunkItem {
|
||||
startTime: number
|
||||
endTime: number
|
||||
chunkKey: string
|
||||
sprite?: PrismaJson.VideoChunkSprite
|
||||
}
|
||||
|
||||
export async function transcodeVideoChunksWorkflow(task: WorkflowTask): Promise<void> {
|
||||
@@ -47,20 +49,21 @@ export async function transcodeVideoChunksWorkflow(task: WorkflowTask): Promise<
|
||||
|
||||
const chunks: TranscodedVideoChunkItem[] = []
|
||||
for (const range of payload.videoChunks.chunks) {
|
||||
const { chunkKey } = await transcodeVideoChunkActivity({
|
||||
const fullSpriteKey = isFullVideoRange(range.startTime, range.endTime, asset.media?.duration)
|
||||
? asset.media?.sprite?.key
|
||||
: undefined
|
||||
const chunk = await transcodeVideoChunkActivity({
|
||||
taskId: task.id,
|
||||
assetId: asset.id,
|
||||
assetKey: targetKey,
|
||||
originalKey: key,
|
||||
startTime: range.startTime,
|
||||
endTime: range.endTime,
|
||||
format: payload.videoChunks.format,
|
||||
...(fullSpriteKey && { fullSpriteKey }),
|
||||
})
|
||||
uploadedChunkKeys.push(chunkKey)
|
||||
chunks.push({
|
||||
startTime: range.startTime,
|
||||
endTime: range.endTime,
|
||||
chunkKey,
|
||||
})
|
||||
uploadedChunkKeys.push(chunk.chunkKey)
|
||||
chunks.push({ ...range, ...chunk })
|
||||
}
|
||||
|
||||
await completeTask(task.id, { chunks })
|
||||
|
||||
@@ -308,7 +308,9 @@ export function FileCard({
|
||||
|
||||
// A preview (poster thumbnail and/or sprite) can be available before transcoding finishes,
|
||||
// since the poster/sprite are generated and persisted ahead of the proxy transcodes.
|
||||
const hasPreview = Boolean(displayItem.preview?.thumbnailUrl || displayItem.preview?.spriteUrl)
|
||||
const hasPreview = Boolean(
|
||||
item.matchedSprite || displayItem.preview?.thumbnailUrl || displayItem.preview?.spriteUrl,
|
||||
)
|
||||
const isFailed = displayItem.status === 'failed'
|
||||
const isLocalUploader = Boolean(fileUploadState)
|
||||
const isUploadFailed = fileUploadState?.status === 'failed'
|
||||
@@ -520,9 +522,10 @@ export function FileCard({
|
||||
<FilePreview
|
||||
item={displayItem}
|
||||
showDuration={!isProcessing && !isFailed}
|
||||
matchedSprite={item.matchedSprite}
|
||||
matchDuration={
|
||||
displayItem.startTime != null && displayItem.endTime != null
|
||||
? { startTime: displayItem.startTime, endTime: displayItem.endTime }
|
||||
item.startTime != null && item.endTime != null
|
||||
? { startTime: item.startTime, endTime: item.endTime }
|
||||
: null
|
||||
}
|
||||
/>
|
||||
@@ -569,8 +572,8 @@ export function FileCard({
|
||||
item={displayItem}
|
||||
showDuration
|
||||
matchDuration={
|
||||
displayItem.startTime != null && displayItem.endTime != null
|
||||
? { startTime: displayItem.startTime, endTime: displayItem.endTime }
|
||||
item.startTime != null && item.endTime != null
|
||||
? { startTime: item.startTime, endTime: item.endTime }
|
||||
: null
|
||||
}
|
||||
/>
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { File, Folder, AudioLines } from 'lucide-react'
|
||||
import type { MatchedSprite } from '@shumai/dtos'
|
||||
import { SpriteScrubber } from '../sprite-scrubber'
|
||||
import { formatTime } from '../viewers/video/utils'
|
||||
|
||||
@@ -20,13 +21,19 @@ type FilePreviewItem = {
|
||||
interface FilePreviewProps {
|
||||
item: FilePreviewItem
|
||||
showDuration?: boolean
|
||||
matchedSprite?: MatchedSprite
|
||||
matchDuration?: {
|
||||
startTime?: number | null
|
||||
endTime?: number | null
|
||||
} | null
|
||||
}
|
||||
|
||||
export const FilePreview = ({ item, showDuration = false, matchDuration }: FilePreviewProps) => {
|
||||
export const FilePreview = ({
|
||||
item,
|
||||
showDuration = false,
|
||||
matchedSprite,
|
||||
matchDuration,
|
||||
}: FilePreviewProps) => {
|
||||
const proxyType = item.preview?.proxyType || item.proxyType
|
||||
const isVideo = proxyType === 'video'
|
||||
const isAudio = proxyType === 'audio'
|
||||
@@ -56,21 +63,27 @@ export const FilePreview = ({ item, showDuration = false, matchDuration }: FileP
|
||||
</span>
|
||||
) : null
|
||||
|
||||
const isMediaWithSprite =
|
||||
(isVideo || isPdf || is3D) &&
|
||||
item.preview?.spriteUrl &&
|
||||
item.preview.thumbnailUrl &&
|
||||
item.preview.originalWidth &&
|
||||
item.preview.originalHeight
|
||||
const chunkSprite = hasMatchedChunk ? matchedSprite : undefined
|
||||
const canShowFullSprite =
|
||||
hasMatchedChunk ||
|
||||
((isVideo || isPdf || is3D) &&
|
||||
item.preview?.thumbnailUrl &&
|
||||
item.preview.originalWidth &&
|
||||
item.preview.originalHeight)
|
||||
const fullSpriteUrl = canShowFullSprite ? item.preview?.spriteUrl : undefined
|
||||
const spriteUrl = chunkSprite?.url || fullSpriteUrl
|
||||
|
||||
if (isMediaWithSprite && item.preview) {
|
||||
if (spriteUrl) {
|
||||
return (
|
||||
<>
|
||||
<SpriteScrubber
|
||||
spriteUrl={item.preview.spriteUrl!}
|
||||
thumbnailUrl={item.preview.thumbnailUrl!}
|
||||
videoWidth={item.preview.originalWidth!}
|
||||
videoHeight={item.preview.originalHeight!}
|
||||
spriteUrl={spriteUrl}
|
||||
spriteLayout={chunkSprite}
|
||||
showFirstFrame={Boolean(chunkSprite)}
|
||||
fallbackSpriteUrl={chunkSprite && fullSpriteUrl ? fullSpriteUrl : undefined}
|
||||
thumbnailUrl={item.preview?.thumbnailUrl}
|
||||
videoWidth={item.preview?.originalWidth}
|
||||
videoHeight={item.preview?.originalHeight}
|
||||
reverse={is3D}
|
||||
/>
|
||||
{overlay}
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { cleanup, fireEvent, render } from '@testing-library/react'
|
||||
import { act, cleanup, fireEvent, render } from '@testing-library/react'
|
||||
import React from 'react'
|
||||
import {
|
||||
mockIsIntersecting,
|
||||
resetIntersectionMocking,
|
||||
setupIntersectionMocking,
|
||||
} from 'react-intersection-observer/test-utils'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { SpriteScrubber } from './sprite-scrubber'
|
||||
import { FilePreview } from './file-browser/file-preview'
|
||||
@@ -15,8 +20,116 @@ globalThis.ResizeObserver = MockResizeObserver as unknown as typeof ResizeObserv
|
||||
describe('SpriteScrubber', () => {
|
||||
afterEach(() => {
|
||||
cleanup()
|
||||
resetIntersectionMocking()
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
|
||||
it.each(['chunk', 'full video', 'thumbnail'])('uses the %s preview on hover', (expected) => {
|
||||
setupIntersectionMocking(vi.fn)
|
||||
const chunkUrl = 'https://example.com/match.webp'
|
||||
const fullUrl = 'https://example.com/full.webp'
|
||||
const requests: string[] = []
|
||||
const image = {
|
||||
naturalWidth: 500,
|
||||
naturalHeight: 200,
|
||||
onload: null as (() => void) | null,
|
||||
onerror: null as (() => void) | null,
|
||||
set src(url: string) {
|
||||
requests.push(url)
|
||||
},
|
||||
}
|
||||
vi.stubGlobal(
|
||||
'Image',
|
||||
class {
|
||||
constructor() {
|
||||
return image
|
||||
}
|
||||
},
|
||||
)
|
||||
const { getByTestId, getByAltText, queryByAltText, container } = render(
|
||||
<FilePreview
|
||||
item={{
|
||||
preview: { proxyType: 'video', spriteUrl: fullUrl, thumbnailUrl: '/poster.webp' },
|
||||
}}
|
||||
matchDuration={{ startTime: 0, endTime: 7 }}
|
||||
matchedSprite={{ url: chunkUrl, columns: 5, rows: 2, frameCount: 7 }}
|
||||
/>,
|
||||
)
|
||||
const scrubber = getByTestId('sprite-scrubber')
|
||||
vi.spyOn(scrubber, 'getBoundingClientRect').mockReturnValue(new DOMRect(0, 0, 100, 100))
|
||||
expect(requests).toEqual([])
|
||||
act(() => mockIsIntersecting(scrubber, true))
|
||||
expect(requests).toEqual([chunkUrl])
|
||||
|
||||
if (expected === 'chunk') {
|
||||
act(() => image.onload?.())
|
||||
expect(queryByAltText('Thumbnail')).toBeNull()
|
||||
expect(scrubber).toHaveProperty('dataset.frame', '0')
|
||||
} else {
|
||||
act(() => image.onerror?.())
|
||||
expect(requests).toEqual([chunkUrl])
|
||||
expect(getByAltText('Thumbnail').className).toContain('opacity-100')
|
||||
}
|
||||
|
||||
fireEvent.mouseEnter(scrubber)
|
||||
fireEvent.mouseMove(scrubber, { clientX: 100 })
|
||||
expect(scrubber).toHaveProperty('dataset.frame', '6')
|
||||
|
||||
if (expected === 'chunk') {
|
||||
expect(requests).toEqual([chunkUrl])
|
||||
} else {
|
||||
expect(requests).toEqual([chunkUrl, fullUrl])
|
||||
}
|
||||
|
||||
if (expected === 'thumbnail') {
|
||||
act(() => image.onerror?.())
|
||||
expect(getByAltText('Thumbnail').className).toContain('opacity-100')
|
||||
expect(container.querySelector('.animate-spin')).toBeNull()
|
||||
} else if (expected === 'full video') {
|
||||
act(() => image.onload?.())
|
||||
expect(getByAltText('Thumbnail').className).toContain('opacity-0')
|
||||
expect(scrubber).toHaveProperty('dataset.frame', '99')
|
||||
}
|
||||
|
||||
fireEvent.mouseLeave(scrubber)
|
||||
expect(scrubber).toHaveProperty('dataset.frame', '0')
|
||||
if (expected === 'chunk') {
|
||||
expect(queryByAltText('Thumbnail')).toBeNull()
|
||||
} else {
|
||||
expect(getByAltText('Thumbnail').className).toContain('opacity-100')
|
||||
}
|
||||
})
|
||||
|
||||
it('keeps the regular cover and waits for hover when a match has no chunk sprite', () => {
|
||||
const load = vi.fn()
|
||||
vi.stubGlobal('Image', load)
|
||||
const { getByAltText } = render(
|
||||
<FilePreview
|
||||
item={{
|
||||
preview: { proxyType: 'video', spriteUrl: '/full.webp', thumbnailUrl: '/poster.webp' },
|
||||
}}
|
||||
matchDuration={{ startTime: 0, endTime: 10 }}
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(getByAltText('Thumbnail').getAttribute('src')).toBe('/poster.webp')
|
||||
expect(load).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it.each(['video', undefined] as const)(
|
||||
'uses the full sprite for a legacy video match with proxy type %s and no poster or dimensions',
|
||||
(proxyType) => {
|
||||
const { getByTestId } = render(
|
||||
<FilePreview
|
||||
item={{ preview: { proxyType, spriteUrl: '/full.webp' } }}
|
||||
matchDuration={{ startTime: 0, endTime: 10 }}
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(getByTestId('sprite-scrubber')).toBeTruthy()
|
||||
},
|
||||
)
|
||||
|
||||
it('scrubs forward by default when hovering from left to right', () => {
|
||||
const { getByTestId } = render(
|
||||
<SpriteScrubber
|
||||
|
||||
@@ -1,14 +1,20 @@
|
||||
import type { SpriteLayout } from '@shumai/dtos'
|
||||
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { useInView } from 'react-intersection-observer'
|
||||
|
||||
interface SpriteScrubberProps {
|
||||
/** The URL of the 10x10 sprite sheet */
|
||||
spriteUrl: string
|
||||
spriteLayout?: SpriteLayout
|
||||
/** Load the primary sprite when visible and show its first frame at rest. */
|
||||
showFirstFrame?: boolean
|
||||
/** A full-asset 10x10 sprite to try when the primary sprite fails. */
|
||||
fallbackSpriteUrl?: string
|
||||
/** The URL of the static thumbnail */
|
||||
thumbnailUrl: string
|
||||
thumbnailUrl?: string
|
||||
/** The width of the original video source */
|
||||
videoWidth: number
|
||||
videoWidth?: number
|
||||
/** The height of the original video source */
|
||||
videoHeight: number
|
||||
videoHeight?: number
|
||||
/** The fixed width of a single frame in the sprite sheet (default 480) */
|
||||
frameWidth?: number
|
||||
/** Optional custom class name for the container */
|
||||
@@ -22,33 +28,79 @@ interface Dimensions {
|
||||
height: number
|
||||
}
|
||||
|
||||
const GRID_COLS = 10
|
||||
const GRID_ROWS = 10
|
||||
const TOTAL_FRAMES = GRID_COLS * GRID_ROWS
|
||||
const FULL_SPRITE_LAYOUT: SpriteLayout = { columns: 10, rows: 10, frameCount: 100 }
|
||||
|
||||
interface SpriteImage extends Dimensions {
|
||||
url: string
|
||||
}
|
||||
|
||||
function useSpriteImage(url: string | undefined) {
|
||||
const [result, setResult] = useState<{ url: string; image: SpriteImage | null }>()
|
||||
|
||||
useEffect(() => {
|
||||
if (!url) return
|
||||
const img = new Image()
|
||||
img.onload = () =>
|
||||
setResult({ url, image: { url, width: img.naturalWidth, height: img.naturalHeight } })
|
||||
img.onerror = () => setResult({ url, image: null })
|
||||
img.src = url
|
||||
return () => {
|
||||
img.onload = null
|
||||
img.onerror = null
|
||||
}
|
||||
}, [url])
|
||||
|
||||
return result?.url === url ? result?.image : undefined
|
||||
}
|
||||
|
||||
export const SpriteScrubber: React.FC<SpriteScrubberProps> = ({
|
||||
spriteUrl,
|
||||
spriteLayout = FULL_SPRITE_LAYOUT,
|
||||
showFirstFrame = false,
|
||||
fallbackSpriteUrl,
|
||||
thumbnailUrl,
|
||||
videoWidth,
|
||||
videoHeight,
|
||||
videoWidth = 1,
|
||||
videoHeight = 1,
|
||||
className = '',
|
||||
reverse = false,
|
||||
}) => {
|
||||
const containerRef = useRef<HTMLDivElement>(null)
|
||||
const { ref: observeVisibility, inView } = useInView({
|
||||
skip: !showFirstFrame,
|
||||
triggerOnce: true,
|
||||
fallbackInView: true,
|
||||
})
|
||||
const setContainerRef = useCallback(
|
||||
(element: HTMLDivElement | null) => {
|
||||
containerRef.current = element
|
||||
observeVisibility(element)
|
||||
},
|
||||
[observeVisibility],
|
||||
)
|
||||
const [containerSize, setContainerSize] = useState<Dimensions>({
|
||||
width: 0,
|
||||
height: 0,
|
||||
})
|
||||
const [naturalSize, setNaturalSize] = useState<Dimensions>({
|
||||
width: 0,
|
||||
height: 0,
|
||||
})
|
||||
|
||||
const [isHovering, setIsHovering] = useState(false)
|
||||
const [spriteLoaded, setSpriteLoaded] = useState(false)
|
||||
const [loadingSprite, setLoadingSprite] = useState(false)
|
||||
const [currentFrame, setCurrentFrame] = useState(0)
|
||||
const [hasHovered, setHasHovered] = useState(false)
|
||||
const [cursorX, setCursorX] = useState(0)
|
||||
const [progress, setProgress] = useState<number>()
|
||||
|
||||
const loadPrimary = hasHovered || (showFirstFrame && inView)
|
||||
const primary = useSpriteImage(loadPrimary ? spriteUrl : undefined)
|
||||
const fallbackUrl =
|
||||
hasHovered && primary === null && fallbackSpriteUrl !== spriteUrl
|
||||
? fallbackSpriteUrl
|
||||
: undefined
|
||||
const fallback = useSpriteImage(fallbackUrl)
|
||||
const sprite = primary ?? fallback
|
||||
const spriteVisible = Boolean(sprite && (isHovering || (showFirstFrame && primary)))
|
||||
const spriteLoading =
|
||||
primary === undefined || (fallbackUrl !== undefined && fallback === undefined)
|
||||
const { columns, rows, frameCount } = fallback ? FULL_SPRITE_LAYOUT : spriteLayout
|
||||
const frame = Math.min(Math.floor((progress ?? 0) * frameCount), frameCount - 1)
|
||||
const cursorFrame = reverse && progress !== undefined ? frameCount - 1 - frame : frame
|
||||
const currentFrame = showFirstFrame && !isHovering ? 0 : cursorFrame
|
||||
|
||||
useEffect(() => {
|
||||
if (!containerRef.current) return
|
||||
@@ -66,26 +118,9 @@ export const SpriteScrubber: React.FC<SpriteScrubberProps> = ({
|
||||
return () => observer.disconnect()
|
||||
}, [])
|
||||
|
||||
const loadSprite = useCallback(() => {
|
||||
if (spriteLoaded || loadingSprite) return
|
||||
|
||||
setLoadingSprite(true)
|
||||
const img = new Image()
|
||||
img.src = spriteUrl
|
||||
img.onload = () => {
|
||||
setNaturalSize({ width: img.naturalWidth, height: img.naturalHeight })
|
||||
setSpriteLoaded(true)
|
||||
setLoadingSprite(false)
|
||||
}
|
||||
img.onerror = () => {
|
||||
console.error('Failed to load sprite image')
|
||||
setLoadingSprite(false)
|
||||
}
|
||||
}, [spriteUrl, spriteLoaded, loadingSprite])
|
||||
|
||||
const handleMouseEnter = () => {
|
||||
setIsHovering(true)
|
||||
loadSprite()
|
||||
setHasHovered(true)
|
||||
}
|
||||
|
||||
const handleMouseLeave = () => {
|
||||
@@ -100,22 +135,17 @@ export const SpriteScrubber: React.FC<SpriteScrubberProps> = ({
|
||||
|
||||
const clampedX = Math.max(0, Math.min(x, rect.width))
|
||||
setCursorX(clampedX)
|
||||
|
||||
const percentage = clampedX / rect.width
|
||||
const rawFrame = Math.min(Math.floor(percentage * TOTAL_FRAMES), TOTAL_FRAMES - 1)
|
||||
const frameIndex = reverse ? TOTAL_FRAMES - 1 - rawFrame : rawFrame
|
||||
|
||||
setCurrentFrame(frameIndex)
|
||||
setProgress(rect.width > 0 ? clampedX / rect.width : 0)
|
||||
}
|
||||
|
||||
// Calculate styles for the inner sprite frame box
|
||||
const spriteStyle: React.CSSProperties = useMemo(() => {
|
||||
if (containerSize.width === 0 || containerSize.height === 0) return {}
|
||||
if (!sprite || containerSize.width === 0 || containerSize.height === 0) return {}
|
||||
|
||||
let sourceAspect = videoWidth / videoHeight
|
||||
if (naturalSize.width > 0 && naturalSize.height > 0) {
|
||||
const singleFrameNaturalW = naturalSize.width / GRID_COLS
|
||||
const singleFrameNaturalH = naturalSize.height / GRID_ROWS
|
||||
if (sprite.width > 0 && sprite.height > 0) {
|
||||
const singleFrameNaturalW = sprite.width / columns
|
||||
const singleFrameNaturalH = sprite.height / rows
|
||||
sourceAspect = singleFrameNaturalW / singleFrameNaturalH
|
||||
}
|
||||
|
||||
@@ -139,17 +169,17 @@ export const SpriteScrubber: React.FC<SpriteScrubberProps> = ({
|
||||
// IMPORTANT: We calculate the sheet size based on the SNAPPED frame size.
|
||||
// This slightly stretches the sprite if needed but ensures that every frame
|
||||
// falls exactly on an integer pixel boundary, preventing "shaking" during playback.
|
||||
const bgWidth = finalW * GRID_COLS
|
||||
const bgHeight = finalH * GRID_ROWS
|
||||
const bgWidth = finalW * columns
|
||||
const bgHeight = finalH * rows
|
||||
|
||||
const colIndex = currentFrame % GRID_COLS
|
||||
const rowIndex = Math.floor(currentFrame / GRID_COLS)
|
||||
const colIndex = currentFrame % columns
|
||||
const rowIndex = Math.floor(currentFrame / columns)
|
||||
|
||||
const bgPosX = -(colIndex * finalW)
|
||||
const bgPosY = -(rowIndex * finalH)
|
||||
|
||||
return {
|
||||
backgroundImage: `url(${spriteUrl})`,
|
||||
backgroundImage: `url(${sprite.url})`,
|
||||
backgroundSize: `${bgWidth}px ${bgHeight}px`,
|
||||
backgroundPosition: `${bgPosX}px ${bgPosY}px`,
|
||||
backgroundRepeat: 'no-repeat',
|
||||
@@ -158,11 +188,11 @@ export const SpriteScrubber: React.FC<SpriteScrubberProps> = ({
|
||||
// Optional: helps with crisp edges on some screens, though default is usually fine
|
||||
imageRendering: 'auto',
|
||||
}
|
||||
}, [containerSize, videoWidth, videoHeight, currentFrame, spriteUrl, naturalSize])
|
||||
}, [containerSize, videoWidth, videoHeight, currentFrame, sprite, columns, rows])
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={containerRef}
|
||||
ref={setContainerRef}
|
||||
data-testid="sprite-scrubber"
|
||||
data-frame={currentFrame}
|
||||
className={`relative w-full h-full overflow-hidden cursor-pointer group bg-black select-none ${className}`}
|
||||
@@ -170,32 +200,34 @@ export const SpriteScrubber: React.FC<SpriteScrubberProps> = ({
|
||||
onMouseLeave={handleMouseLeave}
|
||||
onMouseMove={handleMouseMove}
|
||||
>
|
||||
<img
|
||||
src={thumbnailUrl}
|
||||
alt="Thumbnail"
|
||||
className={`absolute inset-0 w-full h-full object-contain transition-opacity duration-200 ${
|
||||
isHovering && spriteLoaded ? 'opacity-0' : 'opacity-100'
|
||||
}`}
|
||||
draggable={false}
|
||||
/>
|
||||
{thumbnailUrl && (!showFirstFrame || primary === null) && (
|
||||
<img
|
||||
src={thumbnailUrl}
|
||||
alt="Thumbnail"
|
||||
className={`absolute inset-0 w-full h-full object-contain transition-opacity duration-200 ${
|
||||
spriteVisible ? 'opacity-0' : 'opacity-100'
|
||||
}`}
|
||||
draggable={false}
|
||||
/>
|
||||
)}
|
||||
|
||||
{isHovering && !spriteLoaded && (
|
||||
{isHovering && spriteLoading && (
|
||||
<div className="absolute inset-0 flex items-center justify-center bg-black/50 z-10 pointer-events-none">
|
||||
<div className="w-6 h-6 border-2 border-white/30 border-t-white rounded-full animate-spin" />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{spriteLoaded && (
|
||||
{sprite && (
|
||||
<div
|
||||
className={`absolute inset-0 flex items-center justify-center transition-opacity duration-75 ${
|
||||
isHovering ? 'opacity-100' : 'opacity-0'
|
||||
spriteVisible ? 'opacity-100' : 'opacity-0'
|
||||
}`}
|
||||
>
|
||||
<div style={spriteStyle} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{isHovering && (
|
||||
{isHovering && (spriteLoading || sprite) && (
|
||||
<div
|
||||
className="absolute top-0 bottom-0 w-0.5 bg-red-500 shadow-[0_0_4px_rgba(255,0,0,0.8)] z-20 pointer-events-none"
|
||||
style={{ transform: `translateX(${cursorX}px)` }}
|
||||
|
||||
Reference in New Issue
Block a user