mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-27 03:14:11 +00:00
feat(agent): improve agent chat workflow and add media tools
This commit is contained in:
@@ -1,7 +1,13 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { prisma } from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import { getMediaInfoActivity, transcodeVideoActivity, updateAssetMediaActivity } from './transcode'
|
||||
import {
|
||||
getMediaInfoActivity,
|
||||
transcodeVideoActivity,
|
||||
updateAssetMediaActivity,
|
||||
takeScreenshotsActivity,
|
||||
overlayAnnotationsActivity,
|
||||
} from './transcode'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { transcodeService } from '../transcode'
|
||||
|
||||
@@ -21,6 +27,8 @@ vi.mock('../transcode', () => ({
|
||||
transcodeVideo: vi.fn(),
|
||||
createTempDir: vi.fn().mockReturnValue('/tmp'),
|
||||
removeDir: vi.fn(),
|
||||
takeScreenshots: vi.fn(),
|
||||
overlayAnnotations: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
@@ -118,7 +126,6 @@ describe('Transcode Activities', () => {
|
||||
expect((updated?.media as any).duration).toBe(123)
|
||||
expect(s3Service.putObject).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should call transcodeService.transcodeVideo', async () => {
|
||||
vi.mocked(s3Service.headObject).mockRejectedValue(new Error('Not found'))
|
||||
|
||||
@@ -132,4 +139,48 @@ describe('Transcode Activities', () => {
|
||||
|
||||
expect(transcodeService.transcodeVideo).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should call transcodeService.takeScreenshots', async () => {
|
||||
vi.mocked(transcodeService.takeScreenshots).mockResolvedValue([
|
||||
{ key: 'screenshots/shot1.webp', timestamp: 1.0 },
|
||||
])
|
||||
|
||||
const result = await takeScreenshotsActivity({
|
||||
assetKey: 'v.mp4',
|
||||
assetId: 'asset-1',
|
||||
start: 0,
|
||||
end: 10,
|
||||
count: 1,
|
||||
commentTimestamp: 1.0,
|
||||
annotations: [],
|
||||
})
|
||||
|
||||
expect(transcodeService.takeScreenshots).toHaveBeenCalledWith({
|
||||
assetKey: 'v.mp4',
|
||||
assetId: 'asset-1',
|
||||
start: 0,
|
||||
end: 10,
|
||||
count: 1,
|
||||
commentTimestamp: 1.0,
|
||||
annotations: [],
|
||||
})
|
||||
expect(result).toEqual([{ key: 'screenshots/shot1.webp', timestamp: 1.0 }])
|
||||
})
|
||||
|
||||
it('should call transcodeService.overlayAnnotations', async () => {
|
||||
vi.mocked(transcodeService.overlayAnnotations).mockResolvedValue('annotations/ann.webp')
|
||||
|
||||
const result = await overlayAnnotationsActivity({
|
||||
assetKey: 'i.png',
|
||||
assetId: 'asset-2',
|
||||
annotations: [],
|
||||
})
|
||||
|
||||
expect(transcodeService.overlayAnnotations).toHaveBeenCalledWith({
|
||||
assetKey: 'i.png',
|
||||
assetId: 'asset-2',
|
||||
annotations: [],
|
||||
})
|
||||
expect(result).toBe('annotations/ann.webp')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -297,3 +297,23 @@ export async function updateAssetMediaActivity(params: UpdateAssetMediaActivityP
|
||||
data: { media: params.mediaInfo as any },
|
||||
})
|
||||
}
|
||||
|
||||
export async function takeScreenshotsActivity(params: {
|
||||
assetKey: string
|
||||
assetId: string
|
||||
start: number
|
||||
end: number
|
||||
count: number
|
||||
commentTimestamp?: number | null
|
||||
annotations?: PrismaJson.AnnotationList | null
|
||||
}): Promise<Array<{ key: string; timestamp: number }>> {
|
||||
return transcodeService.takeScreenshots(params)
|
||||
}
|
||||
|
||||
export async function overlayAnnotationsActivity(params: {
|
||||
assetKey: string
|
||||
assetId: string
|
||||
annotations: PrismaJson.AnnotationList
|
||||
}): Promise<string> {
|
||||
return transcodeService.overlayAnnotations(params)
|
||||
}
|
||||
|
||||
@@ -7,6 +7,8 @@ import * as os from 'os'
|
||||
import * as path from 'path'
|
||||
import sharp from 'sharp'
|
||||
import { promisify } from 'util'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { ulid } from 'ulid'
|
||||
|
||||
const execAsync = promisify(exec)
|
||||
|
||||
@@ -429,6 +431,219 @@ export class TranscodeService {
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
async takeScreenshots(params: {
|
||||
assetKey: string
|
||||
assetId: string
|
||||
start: number
|
||||
end: number
|
||||
count: number
|
||||
commentTimestamp?: number | null
|
||||
annotations?: PrismaJson.AnnotationList | null
|
||||
}): Promise<Array<{ key: string; timestamp: number }>> {
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
const tmpDir = this.createTempDir('screenshot-')
|
||||
const videoPath = path.join(tmpDir, path.basename(params.assetKey))
|
||||
|
||||
try {
|
||||
// 1. Download video
|
||||
await s3Service.downloadToFile(bucket, params.assetKey, videoPath)
|
||||
|
||||
// 2. Generate timestamps
|
||||
let timestamps: number[] = []
|
||||
if (params.count <= 1) {
|
||||
timestamps = [params.start]
|
||||
} else {
|
||||
const step = (params.end - params.start) / params.count
|
||||
timestamps = Array.from({ length: params.count }, (_, i) => params.start + i * step)
|
||||
}
|
||||
|
||||
// 3. Snap closest timestamp to commentTimestamp if within range
|
||||
const commentTimestamp = params.commentTimestamp
|
||||
if (commentTimestamp !== undefined && commentTimestamp !== null) {
|
||||
if (commentTimestamp >= params.start && commentTimestamp <= params.end) {
|
||||
let closestIdx = 0
|
||||
let minDiff = Math.abs(timestamps[0] - commentTimestamp)
|
||||
for (let i = 1; i < timestamps.length; i++) {
|
||||
const diff = Math.abs(timestamps[i] - commentTimestamp)
|
||||
if (diff < minDiff) {
|
||||
minDiff = diff
|
||||
closestIdx = i
|
||||
}
|
||||
}
|
||||
timestamps[closestIdx] = commentTimestamp
|
||||
}
|
||||
}
|
||||
|
||||
const results: Array<{ key: string; timestamp: number }> = []
|
||||
|
||||
// 4. Extract each screenshot
|
||||
for (const t of timestamps) {
|
||||
const outName = `shot-${t.toFixed(3)}-${ulid()}.webp`
|
||||
const localShotPath = path.join(tmpDir, outName)
|
||||
|
||||
const args = [
|
||||
'-ss',
|
||||
t.toFixed(3),
|
||||
'-i',
|
||||
`"${videoPath}"`,
|
||||
'-vframes',
|
||||
'1',
|
||||
'-vf',
|
||||
'scale=-2:720',
|
||||
'-c:v',
|
||||
'libwebp',
|
||||
'-q:v',
|
||||
'80',
|
||||
`"${localShotPath}"`,
|
||||
]
|
||||
await execAsync(`ffmpeg -y ${args.join(' ')}`)
|
||||
|
||||
// 5. Overlay annotations if timestamp matches commentTimestamp exactly
|
||||
if (
|
||||
commentTimestamp !== undefined &&
|
||||
commentTimestamp !== null &&
|
||||
t === commentTimestamp &&
|
||||
params.annotations &&
|
||||
params.annotations.length > 0
|
||||
) {
|
||||
const meta = await sharp(localShotPath).metadata()
|
||||
const width = meta.width || 1280
|
||||
const height = meta.height || 720
|
||||
|
||||
const svgStr = renderAnnotationsToSvg(width, height, params.annotations)
|
||||
const tempCompositedPath = path.join(tmpDir, `composite-${outName}`)
|
||||
|
||||
await sharp(localShotPath)
|
||||
.composite([{ input: Buffer.from(svgStr), top: 0, left: 0 }])
|
||||
.toFile(tempCompositedPath)
|
||||
|
||||
fs.renameSync(tempCompositedPath, localShotPath)
|
||||
}
|
||||
|
||||
// 6. Upload to S3
|
||||
const s3Key = `file/${params.assetId}/screenshots/${outName}`
|
||||
const fileBuffer = fs.readFileSync(localShotPath)
|
||||
await s3Service.putObject(bucket, s3Key, fileBuffer, fileBuffer.length, 'image/webp')
|
||||
|
||||
results.push({ key: s3Key, timestamp: t })
|
||||
}
|
||||
|
||||
return results
|
||||
} finally {
|
||||
this.removeDir(tmpDir)
|
||||
}
|
||||
}
|
||||
|
||||
async overlayAnnotations(params: {
|
||||
assetKey: string
|
||||
assetId: string
|
||||
annotations: PrismaJson.AnnotationList
|
||||
}): Promise<string> {
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
const tmpDir = this.createTempDir('annotation-')
|
||||
const imgPath = path.join(tmpDir, path.basename(params.assetKey))
|
||||
|
||||
try {
|
||||
// 1. Download image
|
||||
await s3Service.downloadToFile(bucket, params.assetKey, imgPath)
|
||||
|
||||
// 2. Read dimensions
|
||||
const meta = await sharp(imgPath).metadata()
|
||||
const width = meta.width || 1920
|
||||
const height = meta.height || 1080
|
||||
|
||||
// 3. Render SVG
|
||||
const svgStr = renderAnnotationsToSvg(width, height, params.annotations)
|
||||
|
||||
// 4. Composite
|
||||
const outName = `annotation-${ulid()}.webp`
|
||||
const localOutPath = path.join(tmpDir, outName)
|
||||
|
||||
await sharp(imgPath)
|
||||
.composite([{ input: Buffer.from(svgStr), top: 0, left: 0 }])
|
||||
.webp({ quality: 90 })
|
||||
.toFile(localOutPath)
|
||||
|
||||
// 5. Upload to S3
|
||||
const s3Key = `file/${params.assetId}/annotations/${outName}`
|
||||
const fileBuffer = fs.readFileSync(localOutPath)
|
||||
await s3Service.putObject(bucket, s3Key, fileBuffer, fileBuffer.length, 'image/webp')
|
||||
|
||||
return s3Key
|
||||
} finally {
|
||||
this.removeDir(tmpDir)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function renderAnnotationsToSvg(
|
||||
width: number,
|
||||
height: number,
|
||||
annotations: PrismaJson.AnnotationList,
|
||||
): string {
|
||||
const strokeWidth = Math.max(2, Math.round(Math.max(width, height) * 0.004))
|
||||
const svgElements: string[] = []
|
||||
|
||||
for (const ann of annotations) {
|
||||
const color = ann.color || '#ff0000'
|
||||
const type = ann.type
|
||||
|
||||
switch (type) {
|
||||
case 'box': {
|
||||
if (ann.points.length < 2) continue
|
||||
const [start, end] = ann.points
|
||||
const x = Math.min(start[0], end[0]) * width
|
||||
const y = Math.min(start[1], end[1]) * height
|
||||
const boxWidth = Math.abs(end[0] - start[0]) * width
|
||||
const boxHeight = Math.abs(end[1] - start[1]) * height
|
||||
|
||||
svgElements.push(
|
||||
`<rect x="${x}" y="${y}" width="${boxWidth}" height="${boxHeight}" stroke="${color}" stroke-width="${strokeWidth}" fill="none" />`,
|
||||
)
|
||||
break
|
||||
}
|
||||
case 'line':
|
||||
case 'freehand': {
|
||||
if (ann.points.length < 2) continue
|
||||
const pointsStr = ann.points.map(([px, py]) => `${px * width},${py * height}`).join(' ')
|
||||
svgElements.push(
|
||||
`<polyline points="${pointsStr}" stroke="${color}" stroke-width="${strokeWidth}" stroke-linecap="round" stroke-linejoin="round" fill="none" />`,
|
||||
)
|
||||
break
|
||||
}
|
||||
case 'arrow': {
|
||||
if (ann.points.length < 2) continue
|
||||
const pts = ann.points.map(([px, py]) => [px * width, py * height])
|
||||
const pointsStr = pts.map(([x, y]) => `${x},${y}`).join(' ')
|
||||
|
||||
svgElements.push(
|
||||
`<polyline points="${pointsStr}" stroke="${color}" stroke-width="${strokeWidth}" stroke-linecap="round" stroke-linejoin="round" fill="none" />`,
|
||||
)
|
||||
|
||||
const endPt = pts[pts.length - 1]
|
||||
const prevPt = pts[pts.length - 2]
|
||||
const dx = endPt[0] - prevPt[0]
|
||||
const dy = endPt[1] - prevPt[1]
|
||||
const angle = Math.atan2(dy, dx)
|
||||
|
||||
const pointerLength = Math.max(12, Math.max(width, height) * 0.015)
|
||||
const x1 = endPt[0] - pointerLength * Math.cos(angle - Math.PI / 6)
|
||||
const y1 = endPt[1] - pointerLength * Math.sin(angle - Math.PI / 6)
|
||||
const x2 = endPt[0] - pointerLength * Math.cos(angle + Math.PI / 6)
|
||||
const y2 = endPt[1] - pointerLength * Math.sin(angle + Math.PI / 6)
|
||||
|
||||
svgElements.push(
|
||||
`<polygon points="${endPt[0]},${endPt[1]} ${x1},${y1} ${x2},${y2}" fill="${color}" />`,
|
||||
)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return `<svg width="${width}" height="${height}" viewBox="0 0 ${width} ${height}" xmlns="http://www.w3.org/2000/svg">${svgElements.join(
|
||||
'\n',
|
||||
)}</svg>`
|
||||
}
|
||||
|
||||
export const transcodeService = new TranscodeService()
|
||||
|
||||
@@ -37,6 +37,10 @@ describe('Transcode Workflow', () => {
|
||||
_activityName: 'downloadMediaToTmpActivity',
|
||||
}),
|
||||
cleanupTmpDirActivity: Object.assign(vi.fn(), { _activityName: 'cleanupTmpDirActivity' }),
|
||||
takeScreenshotsActivity: Object.assign(vi.fn(), { _activityName: 'takeScreenshotsActivity' }),
|
||||
overlayAnnotationsActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'overlayAnnotationsActivity',
|
||||
}),
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
@@ -234,4 +238,119 @@ describe('Transcode Workflow', () => {
|
||||
output: { error: 'FFmpeg failed' },
|
||||
})
|
||||
})
|
||||
|
||||
it('should run screenshot workflow successfully', async () => {
|
||||
const task: WorkflowTask = {
|
||||
id: 'task-screenshot',
|
||||
assetId: 'asset-video',
|
||||
type: WorkflowTaskType.transcode,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
output: null,
|
||||
payload: {
|
||||
projectId: 'proj-1',
|
||||
screenshot: {
|
||||
start: 0,
|
||||
end: 10,
|
||||
count: 2,
|
||||
commentTimestamp: 5.0,
|
||||
annotations: [],
|
||||
},
|
||||
},
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
heartbeat: null,
|
||||
teamId: 'team-1',
|
||||
projectId: 'proj-1',
|
||||
uid: 'task-uid',
|
||||
model: null,
|
||||
inputTokens: 0,
|
||||
outputTokens: 0,
|
||||
}
|
||||
|
||||
mockActivities.getAssetActivity.mockResolvedValue({
|
||||
id: 'asset-video',
|
||||
storageKey: { key: 'video.mp4' },
|
||||
mediaType: 'video/mp4',
|
||||
})
|
||||
|
||||
mockActivities.takeScreenshotsActivity.mockResolvedValue([
|
||||
{ key: 'file/asset-video/screenshots/shot1.webp', timestamp: 0.0 },
|
||||
{ key: 'file/asset-video/screenshots/shot2.webp', timestamp: 5.0 },
|
||||
])
|
||||
|
||||
await transcodeMedia(task)
|
||||
|
||||
expect(mockActivities.takeScreenshotsActivity).toHaveBeenCalledWith({
|
||||
assetKey: 'video.mp4',
|
||||
assetId: 'asset-video',
|
||||
start: 0,
|
||||
end: 10,
|
||||
count: 2,
|
||||
commentTimestamp: 5.0,
|
||||
annotations: [],
|
||||
})
|
||||
|
||||
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({
|
||||
taskId: 'task-screenshot',
|
||||
status: WorkflowTaskStatus.completed,
|
||||
output: {
|
||||
screenshots: [
|
||||
{ key: 'file/asset-video/screenshots/shot1.webp', timestamp: 0.0 },
|
||||
{ key: 'file/asset-video/screenshots/shot2.webp', timestamp: 5.0 },
|
||||
],
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
it('should run image annotation overlay workflow successfully', async () => {
|
||||
const task: WorkflowTask = {
|
||||
id: 'task-image-ann',
|
||||
assetId: 'asset-image',
|
||||
type: WorkflowTaskType.transcode,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
output: null,
|
||||
payload: {
|
||||
projectId: 'proj-1',
|
||||
imageAnnotation: {
|
||||
annotations: [{ type: 'box', color: '#ff0000', points: [] }],
|
||||
},
|
||||
},
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
heartbeat: null,
|
||||
teamId: 'team-1',
|
||||
projectId: 'proj-1',
|
||||
uid: 'task-uid',
|
||||
model: null,
|
||||
inputTokens: 0,
|
||||
outputTokens: 0,
|
||||
}
|
||||
|
||||
mockActivities.getAssetActivity.mockResolvedValue({
|
||||
id: 'asset-image',
|
||||
storageKey: { key: 'image.png' },
|
||||
mediaType: 'image/png',
|
||||
media: {
|
||||
imageTranscodes: [{ key: 'image-transcoded.webp' }],
|
||||
},
|
||||
})
|
||||
|
||||
mockActivities.overlayAnnotationsActivity.mockResolvedValue(
|
||||
'file/asset-image/annotations/ann1.webp',
|
||||
)
|
||||
|
||||
await transcodeMedia(task)
|
||||
|
||||
expect(mockActivities.overlayAnnotationsActivity).toHaveBeenCalledWith({
|
||||
assetKey: 'image-transcoded.webp',
|
||||
assetId: 'asset-image',
|
||||
annotations: [{ type: 'box', color: '#ff0000', points: [] }],
|
||||
})
|
||||
|
||||
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({
|
||||
taskId: 'task-image-ann',
|
||||
status: WorkflowTaskStatus.completed,
|
||||
output: { key: 'file/asset-image/annotations/ann1.webp' },
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -16,6 +16,8 @@ export async function transcodeMedia(task: WorkflowTask): Promise<void> {
|
||||
getTranscodeWorkerQueueActivity,
|
||||
downloadMediaToTmpActivity,
|
||||
cleanupTmpDirActivity,
|
||||
takeScreenshotsActivity,
|
||||
overlayAnnotationsActivity,
|
||||
} = getActivities()
|
||||
|
||||
let tmpDir: string | undefined
|
||||
@@ -31,6 +33,69 @@ export async function transcodeMedia(task: WorkflowTask): Promise<void> {
|
||||
status: 'processing',
|
||||
})
|
||||
|
||||
const payload = task.payload
|
||||
|
||||
if (payload?.screenshot) {
|
||||
const asset = await executeActivity(workerQueue, getAssetActivity, task.assetId)
|
||||
const key = asset?.storageKey?.key
|
||||
if (!asset || !key) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'Asset not found or has no key',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
const screenshots = await executeActivity(workerQueue, takeScreenshotsActivity, {
|
||||
assetKey: key,
|
||||
assetId: asset.id,
|
||||
start: payload.screenshot.start,
|
||||
end: payload.screenshot.end,
|
||||
count: payload.screenshot.count,
|
||||
commentTimestamp: payload.screenshot.commentTimestamp,
|
||||
annotations: payload.screenshot.annotations,
|
||||
})
|
||||
|
||||
// Update Task Status to completed with output
|
||||
await executeActivity(workerQueue, updateTaskStatusActivity, {
|
||||
taskId: task.id,
|
||||
status: 'completed',
|
||||
output: { screenshots },
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
if (payload?.imageAnnotation) {
|
||||
const asset = await executeActivity(workerQueue, getAssetActivity, task.assetId)
|
||||
let key = asset?.storageKey?.key
|
||||
if (asset?.media) {
|
||||
const mediaInfo = asset.media as unknown as PrismaJson.MediaInfo
|
||||
if (mediaInfo.imageTranscodes && mediaInfo.imageTranscodes.length > 0) {
|
||||
key = mediaInfo.imageTranscodes[0].key || key
|
||||
}
|
||||
}
|
||||
|
||||
if (!asset || !key) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'Asset not found or has no key',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
const keyWithOverlay = await executeActivity(workerQueue, overlayAnnotationsActivity, {
|
||||
assetKey: key,
|
||||
assetId: asset.id,
|
||||
annotations: payload.imageAnnotation.annotations,
|
||||
})
|
||||
|
||||
// Update Task Status to completed with output
|
||||
await executeActivity(workerQueue, updateTaskStatusActivity, {
|
||||
taskId: task.id,
|
||||
status: 'completed',
|
||||
output: { key: keyWithOverlay },
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
await executeActivity(workerQueue, updateAssetStatusActivity, {
|
||||
assetId: task.assetId,
|
||||
status: 'processing',
|
||||
|
||||
Reference in New Issue
Block a user