mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-24 19:37:16 +00:00
fix(transcode): handle timestamp rounding tolerance for screenshot annotations
This commit is contained in:
@@ -2,6 +2,7 @@ import { Type } from '@sinclair/typebox'
|
||||
import { type AgentTool } from '@earendil-works/pi-agent-core'
|
||||
import { type ImageContent } from '@earendil-works/pi-ai'
|
||||
import { prisma, WorkflowTaskType, WorkflowTaskStatus, type User } from '@shumai/db'
|
||||
import { logger } from '@shumai/core/src/logger'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { workflowService } from '@shumai/workflow-core'
|
||||
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
@@ -65,6 +66,18 @@ export function createScreenshotTool(
|
||||
}
|
||||
}
|
||||
|
||||
logger.info(
|
||||
{
|
||||
assetId,
|
||||
userId,
|
||||
userCommentId,
|
||||
commentTimestamp,
|
||||
hasAnnotations: Boolean(annotations),
|
||||
params,
|
||||
},
|
||||
'[screenshotTool] Executing screenshot tool call',
|
||||
)
|
||||
|
||||
// Trigger transcode workflow to take screenshots
|
||||
const task = await prisma.workflowTask.create({
|
||||
data: {
|
||||
|
||||
@@ -646,6 +646,97 @@ describe('TranscodeService', () => {
|
||||
expect(b).toBeLessThan(100)
|
||||
})
|
||||
|
||||
it('should snap commentTimestamp and overlay annotations when start/end has rounding mismatch', async () => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(child_process.execFile as any).mockImplementation(
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
(file: string, args: string[], cb: any) => {
|
||||
if (file === 'ffmpeg') {
|
||||
const outPath = args[args.length - 1]
|
||||
fs.writeFileSync(outPath, 'fake-webp-image')
|
||||
}
|
||||
cb(null, { stdout: '', stderr: '' })
|
||||
},
|
||||
)
|
||||
|
||||
const overlaySpy = vi
|
||||
.spyOn(transcodeService, 'overlayAnnotationsOnBuffer')
|
||||
.mockResolvedValue(Buffer.from('composited-buffer'))
|
||||
|
||||
const annotations: PrismaJson.AnnotationList = [
|
||||
{
|
||||
type: 'box',
|
||||
color: '#ff0000',
|
||||
points: [
|
||||
[0.2, 0.2],
|
||||
[0.8, 0.8],
|
||||
],
|
||||
},
|
||||
]
|
||||
|
||||
const results = await transcodeService.takeScreenshots({
|
||||
assetKey: 'test/video.mp4',
|
||||
assetId: 'asset-123',
|
||||
start: 4.57,
|
||||
end: 4.57,
|
||||
count: 1,
|
||||
commentTimestamp: 4.566666666666667,
|
||||
annotations,
|
||||
})
|
||||
|
||||
expect(results).toHaveLength(1)
|
||||
expect(results[0].timestamp).toBe(4.566666666666667)
|
||||
expect(overlaySpy).toHaveBeenCalledWith(expect.any(Buffer), annotations)
|
||||
|
||||
overlaySpy.mockRestore()
|
||||
})
|
||||
|
||||
it('should overlay annotation on ONLY the single snapped frame in a multi-screenshot range', async () => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(child_process.execFile as any).mockImplementation(
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
(file: string, args: string[], cb: any) => {
|
||||
if (file === 'ffmpeg') {
|
||||
const outPath = args[args.length - 1]
|
||||
fs.writeFileSync(outPath, 'fake-webp-image')
|
||||
}
|
||||
cb(null, { stdout: '', stderr: '' })
|
||||
},
|
||||
)
|
||||
|
||||
const overlaySpy = vi
|
||||
.spyOn(transcodeService, 'overlayAnnotationsOnBuffer')
|
||||
.mockResolvedValue(Buffer.from('composited-buffer'))
|
||||
|
||||
const annotations: PrismaJson.AnnotationList = [
|
||||
{
|
||||
type: 'box',
|
||||
color: '#ff0000',
|
||||
points: [
|
||||
[0.2, 0.2],
|
||||
[0.8, 0.8],
|
||||
],
|
||||
},
|
||||
]
|
||||
|
||||
const results = await transcodeService.takeScreenshots({
|
||||
assetKey: 'test/video.mp4',
|
||||
assetId: 'asset-123',
|
||||
start: 0,
|
||||
end: 1,
|
||||
count: 30,
|
||||
commentTimestamp: 0.566666666666667,
|
||||
annotations,
|
||||
})
|
||||
|
||||
expect(results).toHaveLength(30)
|
||||
// Exactly 1 overlay call for the snapped timestamp out of 30 frames
|
||||
expect(overlaySpy).toHaveBeenCalledTimes(1)
|
||||
expect(overlaySpy).toHaveBeenCalledWith(expect.any(Buffer), annotations)
|
||||
|
||||
overlaySpy.mockRestore()
|
||||
})
|
||||
|
||||
it('should generate PDF from text file including CJK characters', async () => {
|
||||
const txtFile = path.join(tempDir, 'test.txt')
|
||||
const pdfFile = path.join(tempDir, 'output.pdf')
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { logger } from '@shumai/core/src/logger'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { stemFromKey } from '@shumai/core/src/utils/filename'
|
||||
import { prisma, WorkflowTaskStatus, WorkflowTaskType } from '@shumai/db'
|
||||
@@ -911,6 +912,20 @@ export class TranscodeService {
|
||||
const videoPath = path.join(tmpDir, path.basename(params.assetKey))
|
||||
|
||||
try {
|
||||
logger.info(
|
||||
{
|
||||
assetId: params.assetId,
|
||||
assetKey: params.assetKey,
|
||||
start: params.start,
|
||||
end: params.end,
|
||||
count: params.count,
|
||||
commentTimestamp: params.commentTimestamp,
|
||||
hasAnnotations: Boolean(params.annotations && params.annotations.length > 0),
|
||||
annotationsCount: params.annotations?.length ?? 0,
|
||||
},
|
||||
'[takeScreenshots] Starting screenshot extraction',
|
||||
)
|
||||
|
||||
// 1. Download video
|
||||
await s3Service.downloadToFile(bucket, params.assetKey, videoPath)
|
||||
|
||||
@@ -923,10 +938,18 @@ export class TranscodeService {
|
||||
timestamps = Array.from({ length: params.count }, (_, i) => params.start + i * step)
|
||||
}
|
||||
|
||||
// 3. Snap closest timestamp to commentTimestamp if within range
|
||||
logger.info(
|
||||
{ initialTimestamps: timestamps, count: params.count },
|
||||
'[takeScreenshots] Generated initial sampling timestamps',
|
||||
)
|
||||
|
||||
// 3. Snap closest timestamp to commentTimestamp if within range (with 100ms tolerance)
|
||||
const commentTimestamp = params.commentTimestamp
|
||||
const EPSILON = 0.1
|
||||
if (commentTimestamp !== undefined && commentTimestamp !== null) {
|
||||
if (commentTimestamp >= params.start && commentTimestamp <= params.end) {
|
||||
const inRange =
|
||||
commentTimestamp >= params.start - EPSILON && commentTimestamp <= params.end + EPSILON
|
||||
if (inRange) {
|
||||
let closestIdx = 0
|
||||
let minDiff = Math.abs(timestamps[0] - commentTimestamp)
|
||||
for (let i = 1; i < timestamps.length; i++) {
|
||||
@@ -936,8 +959,30 @@ export class TranscodeService {
|
||||
closestIdx = i
|
||||
}
|
||||
}
|
||||
const oldTs = timestamps[closestIdx]
|
||||
timestamps[closestIdx] = commentTimestamp
|
||||
logger.info(
|
||||
{
|
||||
commentTimestamp,
|
||||
snappedIdx: closestIdx,
|
||||
replacedTimestamp: oldTs,
|
||||
newTimestamp: commentTimestamp,
|
||||
resultingTimestamps: timestamps,
|
||||
},
|
||||
'[takeScreenshots] Snapped commentTimestamp to closest timestamp index',
|
||||
)
|
||||
} else {
|
||||
logger.warn(
|
||||
{
|
||||
commentTimestamp,
|
||||
start: params.start,
|
||||
end: params.end,
|
||||
},
|
||||
'[takeScreenshots] commentTimestamp is OUT OF RANGE [start, end], skipping snap',
|
||||
)
|
||||
}
|
||||
} else {
|
||||
logger.info('[takeScreenshots] No commentTimestamp provided')
|
||||
}
|
||||
|
||||
const results: Array<{ key: string; timestamp: number }> = []
|
||||
@@ -964,14 +1009,17 @@ export class TranscodeService {
|
||||
]
|
||||
await execFileAsync('ffmpeg', ['-y', '-loglevel', 'warning', ...args])
|
||||
|
||||
// 5. Overlay annotations if timestamp matches commentTimestamp exactly
|
||||
if (
|
||||
const isMatch =
|
||||
commentTimestamp !== undefined &&
|
||||
commentTimestamp !== null &&
|
||||
t === commentTimestamp &&
|
||||
params.annotations &&
|
||||
params.annotations.length > 0
|
||||
) {
|
||||
Math.abs(t - commentTimestamp) < 1e-4
|
||||
|
||||
// 5. Overlay annotations if timestamp matches commentTimestamp (within float tolerance)
|
||||
if (isMatch && params.annotations && params.annotations.length > 0) {
|
||||
logger.info(
|
||||
{ timestamp: t, commentTimestamp, annotationsCount: params.annotations.length },
|
||||
'[takeScreenshots] Overlaying annotations onto frame',
|
||||
)
|
||||
const shotBuffer = fs.readFileSync(localShotPath)
|
||||
const composited = await this.overlayAnnotationsOnBuffer(shotBuffer, params.annotations)
|
||||
fs.writeFileSync(localShotPath, composited)
|
||||
|
||||
@@ -7,6 +7,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 currentDir = path.dirname(fileURLToPath(import.meta.url))
|
||||
const transcodeWorkflowsPath = path.resolve(currentDir, '../../../apps/transcode/src/workflows.ts')
|
||||
@@ -126,5 +127,231 @@ describe.each(['local', 'temporal'] as const)(
|
||||
expect(output.screenshots.length).toBe(1)
|
||||
expect(output.screenshots[0].key).toContain('screenshots/')
|
||||
}, 50000)
|
||||
|
||||
it('should draw annotation box correctly for 5 random comment timestamps', async () => {
|
||||
// 1. Seed Database
|
||||
const team = await prisma.team.create({
|
||||
data: { name: 'E2E Video Screenshot Annotation Team' },
|
||||
})
|
||||
|
||||
const project = await prisma.project.create({
|
||||
data: { name: 'E2E Video Screenshot Annotation Project', teamId: team.id },
|
||||
})
|
||||
|
||||
const storageKey = await prisma.storageKey.create({
|
||||
data: {
|
||||
key: 'projects/e2e/video-shot-ann.mp4',
|
||||
},
|
||||
})
|
||||
|
||||
const asset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'video-shot-ann.mp4',
|
||||
type: 'file',
|
||||
status: 'uploaded',
|
||||
mediaType: 'video/mp4',
|
||||
projectId: project.id,
|
||||
storageKeyId: storageKey.id,
|
||||
},
|
||||
})
|
||||
|
||||
// 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-transcode',
|
||||
'projects/e2e/video-shot-ann.mp4',
|
||||
mp4Buffer,
|
||||
mp4Buffer.length,
|
||||
'video/mp4',
|
||||
)
|
||||
|
||||
// 3. Generate 5 random comment timestamps between 0.05s and 0.95s
|
||||
const randomTimestamps: number[] = []
|
||||
for (let i = 0; i < 5; i++) {
|
||||
const randomTs = 0.05 + Math.random() * 0.9
|
||||
randomTimestamps.push(randomTs)
|
||||
}
|
||||
|
||||
console.log('Testing random timestamps:', randomTimestamps)
|
||||
|
||||
const boxAnnotation = [
|
||||
{
|
||||
type: 'box' as const,
|
||||
color: '#ff0000',
|
||||
points: [
|
||||
[0.2, 0.2],
|
||||
[0.8, 0.8],
|
||||
],
|
||||
},
|
||||
]
|
||||
|
||||
for (const commentTimestamp of randomTimestamps) {
|
||||
// Create Workflow Task with commentTimestamp & annotations
|
||||
const task = await prisma.workflowTask.create({
|
||||
data: {
|
||||
type: 'transcode_screenshot',
|
||||
status: 'pending',
|
||||
assetId: asset.id,
|
||||
projectId: project.id,
|
||||
teamId: team.id,
|
||||
payload: {
|
||||
projectId: project.id,
|
||||
screenshot: {
|
||||
start: 0,
|
||||
end: 1,
|
||||
count: 5,
|
||||
commentTimestamp,
|
||||
annotations: boxAnnotation,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const completedTask = await workflowService.executeWait(task, 45000)
|
||||
expect(completedTask.status).toBe('completed')
|
||||
|
||||
const output = completedTask.output as unknown as {
|
||||
screenshots: { key: string; timestamp: number }[]
|
||||
}
|
||||
expect(output).toBeDefined()
|
||||
expect(output.screenshots).toBeDefined()
|
||||
|
||||
// Find the screenshot matching commentTimestamp
|
||||
const matchingShot = output.screenshots.find(
|
||||
(s) => Math.abs(s.timestamp - commentTimestamp) < 1e-6,
|
||||
)
|
||||
expect(matchingShot).toBeDefined()
|
||||
|
||||
// Download screenshot buffer from S3
|
||||
const s3Obj = await s3Service.getObject(
|
||||
'shumai-e2e-test-bucket-transcode',
|
||||
matchingShot!.key,
|
||||
)
|
||||
const shotBuffer = s3Obj.buffer
|
||||
|
||||
// Verify pixel data using sharp to check if red box annotation was overlaid
|
||||
const { data, info } = await sharp(shotBuffer).raw().toBuffer({ resolveWithObject: true })
|
||||
|
||||
// Target pixel inside box (e.g. x = 50%, y = 20% near top edge of red box)
|
||||
const pixelX = Math.floor(info.width * 0.5)
|
||||
const pixelY = Math.floor(info.height * 0.2)
|
||||
const offset = (pixelY * info.width + pixelX) * info.channels
|
||||
|
||||
const r = data[offset]
|
||||
const g = data[offset + 1]
|
||||
const b = data[offset + 2]
|
||||
|
||||
// Red box color #ff0000 should result in high red channel and low green/blue channels
|
||||
expect(r).toBeGreaterThan(150)
|
||||
expect(g).toBeLessThan(120)
|
||||
expect(b).toBeLessThan(120)
|
||||
}
|
||||
}, 90000)
|
||||
|
||||
it('should overlay annotation when commentTimestamp has rounding mismatch with start/end', async () => {
|
||||
// 1. Seed Database
|
||||
const team = await prisma.team.create({
|
||||
data: { name: 'E2E Video Screenshot Rounding Team' },
|
||||
})
|
||||
|
||||
const project = await prisma.project.create({
|
||||
data: { name: 'E2E Video Screenshot Rounding Project', teamId: team.id },
|
||||
})
|
||||
|
||||
const storageKey = await prisma.storageKey.create({
|
||||
data: {
|
||||
key: 'projects/e2e/video-shot-rounding.mp4',
|
||||
},
|
||||
})
|
||||
|
||||
const asset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'video-shot-rounding.mp4',
|
||||
type: 'file',
|
||||
status: 'uploaded',
|
||||
mediaType: 'video/mp4',
|
||||
projectId: project.id,
|
||||
storageKeyId: storageKey.id,
|
||||
},
|
||||
})
|
||||
|
||||
// 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-transcode',
|
||||
'projects/e2e/video-shot-rounding.mp4',
|
||||
mp4Buffer,
|
||||
mp4Buffer.length,
|
||||
'video/mp4',
|
||||
)
|
||||
|
||||
// Reproduce log scenario: exact timestamp is 0.566666666666667, Agent requested rounded 0.57
|
||||
const commentTimestamp = 0.566666666666667
|
||||
const start = 0.57
|
||||
const end = 0.57
|
||||
|
||||
const boxAnnotation = [
|
||||
{
|
||||
type: 'box' as const,
|
||||
color: '#ff0000',
|
||||
points: [
|
||||
[0.2, 0.2],
|
||||
[0.8, 0.8],
|
||||
],
|
||||
},
|
||||
]
|
||||
|
||||
const task = await prisma.workflowTask.create({
|
||||
data: {
|
||||
type: 'transcode_screenshot',
|
||||
status: 'pending',
|
||||
assetId: asset.id,
|
||||
projectId: project.id,
|
||||
teamId: team.id,
|
||||
payload: {
|
||||
projectId: project.id,
|
||||
screenshot: {
|
||||
start,
|
||||
end,
|
||||
count: 1,
|
||||
commentTimestamp,
|
||||
annotations: boxAnnotation,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const completedTask = await workflowService.executeWait(task, 45000)
|
||||
expect(completedTask.status).toBe('completed')
|
||||
|
||||
const output = completedTask.output as unknown as {
|
||||
screenshots: { key: string; timestamp: number }[]
|
||||
}
|
||||
expect(output).toBeDefined()
|
||||
expect(output.screenshots).toBeDefined()
|
||||
expect(output.screenshots.length).toBe(1)
|
||||
|
||||
const s3Obj = await s3Service.getObject(
|
||||
'shumai-e2e-test-bucket-transcode',
|
||||
output.screenshots[0].key,
|
||||
)
|
||||
const shotBuffer = s3Obj.buffer
|
||||
|
||||
const { data, info } = await sharp(shotBuffer).raw().toBuffer({ resolveWithObject: true })
|
||||
|
||||
const pixelX = Math.floor(info.width * 0.5)
|
||||
const pixelY = Math.floor(info.height * 0.2)
|
||||
const offset = (pixelY * info.width + pixelX) * info.channels
|
||||
|
||||
const r = data[offset]
|
||||
const g = data[offset + 1]
|
||||
const b = data[offset + 2]
|
||||
|
||||
expect(r).toBeGreaterThan(150)
|
||||
expect(g).toBeLessThan(120)
|
||||
expect(b).toBeLessThan(120)
|
||||
}, 50000)
|
||||
},
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user