mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-23 18:07:13 +00:00
feat(agent): support gemma-embedding-2-openai provider (#475)
* feat(agent): support gemma-embedding-2-openai provider Add support for local LiteRT-LM Gemma Embedding 2 provider with 768-dimensional vector embeddings, environment-configured read-only embedding agents, 16-frame uniform sampling for video chunks, and automatic WebP-to-JPEG conversion. * refactor(agent): remove unused legacy generateEmbeddingActivity * chore(agent): align sharp version to 0.35.4 * refactor(agent): rename embedding server env to GEMMA_EMBEDDING_OPENAI_BASE_URL * refactor(agent,transcode): use native Bun.Archive for video chunk frames * fix(transcode,agent): populate buffer entries in Bun.Archive and validate frame sizes
This commit is contained in:
@@ -1230,6 +1230,100 @@ describe('Transcode Activities', () => {
|
||||
expect(res.chunkKey).toMatch(/^files\/asset-abc\/tmp-embedding-chunks\/chunk-10-25-.*\.mp4$/)
|
||||
})
|
||||
|
||||
it('should extract frames archive when format is frames', async () => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(child_process.execFile as any).mockImplementation(
|
||||
(
|
||||
_file: string,
|
||||
args: string[],
|
||||
cb: (err: Error | null, result: { stdout: string; stderr: string }) => void,
|
||||
) => {
|
||||
if (_file === 'ffmpeg' && args) {
|
||||
const outPattern = args[args.length - 1]
|
||||
if (outPattern && outPattern.includes('frame_%04d.jpg')) {
|
||||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||||
const fsActual = require('fs')
|
||||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||||
const pathActual = require('path')
|
||||
const dir = pathActual.dirname(outPattern)
|
||||
fsActual.writeFileSync(
|
||||
pathActual.join(dir, 'frame_0001.jpg'),
|
||||
Buffer.from('mock-frame'),
|
||||
)
|
||||
}
|
||||
}
|
||||
cb(null, { stdout: '', stderr: '' })
|
||||
},
|
||||
)
|
||||
|
||||
const res = await transcodeVideoChunkActivity({
|
||||
assetId: 'asset-abc',
|
||||
filePath: '/tmp/full-video.mp4',
|
||||
startTime: 10,
|
||||
endTime: 25,
|
||||
format: 'frames',
|
||||
})
|
||||
|
||||
expect(child_process.execFile).toHaveBeenCalledWith(
|
||||
'ffmpeg',
|
||||
expect.arrayContaining(['-vf', 'fps=1', '-q:v', '2']),
|
||||
expect.any(Function),
|
||||
)
|
||||
expect(child_process.execFile).not.toHaveBeenCalledWith(
|
||||
'tar',
|
||||
expect.anything(),
|
||||
expect.anything(),
|
||||
)
|
||||
expect(s3Service.putObject).toHaveBeenCalledWith(
|
||||
'shumai',
|
||||
expect.stringMatching(/^files\/asset-abc\/tmp-embedding-chunks\/frames-10-25-.*\.tar$/),
|
||||
expect.any(Buffer),
|
||||
expect.any(Number),
|
||||
'application/x-tar',
|
||||
)
|
||||
expect(res.chunkKey).toMatch(/^files\/asset-abc\/tmp-embedding-chunks\/frames-10-25-.*\.tar$/)
|
||||
|
||||
const putCall = vi.mocked(s3Service.putObject).mock.calls[0]
|
||||
const uploadedBuffer = putCall[2] as Buffer
|
||||
const uploadedArchive = new Bun.Archive(uploadedBuffer)
|
||||
const archiveFiles = await uploadedArchive.files()
|
||||
expect(archiveFiles.has('frame_0001.jpg')).toBe(true)
|
||||
const uploadedFile = archiveFiles.get('frame_0001.jpg')!
|
||||
expect(uploadedFile.size).toBeGreaterThan(0)
|
||||
const uploadedFileBytes = await uploadedFile.bytes()
|
||||
expect(uploadedFileBytes.byteLength).toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
it('should sample uniform 16 frames when chunk duration > 16s', async () => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- child_process.execFile mockImplementation returns void rather than ChildProcess in unit tests
|
||||
;(child_process.execFile as any).mockImplementation(
|
||||
(
|
||||
_cmd: unknown,
|
||||
_args: unknown,
|
||||
cb: (err: null, res: { stdout: string; stderr: string }) => void,
|
||||
) => {
|
||||
cb(null, {
|
||||
stdout: '',
|
||||
stderr: '',
|
||||
})
|
||||
},
|
||||
)
|
||||
|
||||
await transcodeVideoChunkActivity({
|
||||
assetId: 'asset-abc',
|
||||
filePath: '/tmp/full-video.mp4',
|
||||
startTime: 0,
|
||||
endTime: 60,
|
||||
format: 'frames',
|
||||
})
|
||||
|
||||
expect(child_process.execFile).toHaveBeenCalledWith(
|
||||
'ffmpeg',
|
||||
expect.arrayContaining(['-vf', `fps=${16 / 60}`, '-vframes', '16', '-q:v', '2']),
|
||||
expect.any(Function),
|
||||
)
|
||||
})
|
||||
|
||||
it('should throw non-retryable ApplicationFailure when neither filePath nor assetKey is provided', async () => {
|
||||
expect.assertions(2)
|
||||
try {
|
||||
|
||||
@@ -1490,6 +1490,7 @@ export interface TranscodeVideoChunkParams {
|
||||
filePath?: string
|
||||
startTime: number
|
||||
endTime: number
|
||||
format?: 'video' | 'frames'
|
||||
}
|
||||
|
||||
export async function transcodeVideoChunkActivity(
|
||||
@@ -1502,6 +1503,82 @@ export async function transcodeVideoChunkActivity(
|
||||
})
|
||||
}
|
||||
|
||||
if (params.format === 'frames') {
|
||||
const tmpDir = transcodeService.createTempDir('video-chunk-frames-')
|
||||
try {
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
const inputSource =
|
||||
params.filePath ||
|
||||
(params.assetKey ? await s3Service.resolveInput(bucket, params.assetKey) : '')
|
||||
if (!inputSource) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'Neither filePath nor assetKey was provided for video chunk transcoding',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
const isRemote = inputSource.startsWith('http://') || inputSource.startsWith('https://')
|
||||
|
||||
const duration = Math.max(0.1, params.endTime - params.startTime)
|
||||
const fpsFilter = duration > 16 ? `fps=${16 / duration}` : 'fps=1'
|
||||
const vframesArgs = duration > 16 ? ['-vframes', '16'] : []
|
||||
|
||||
await execFileAsync('ffmpeg', [
|
||||
'-y',
|
||||
'-loglevel',
|
||||
'warning',
|
||||
...(isRemote
|
||||
? ['-reconnect', '1', '-reconnect_streamed', '1', '-reconnect_delay_max', '5']
|
||||
: []),
|
||||
'-ss',
|
||||
params.startTime.toString(),
|
||||
'-i',
|
||||
inputSource,
|
||||
'-map',
|
||||
'0:V:0',
|
||||
'-t',
|
||||
duration.toString(),
|
||||
'-vf',
|
||||
fpsFilter,
|
||||
...vframesArgs,
|
||||
'-q:v',
|
||||
'2',
|
||||
path.join(tmpDir, 'frame_%04d.jpg'),
|
||||
])
|
||||
|
||||
const frameFiles = fs
|
||||
.readdirSync(tmpDir)
|
||||
.filter((f) => /\.(jpe?g|png|webp)$/i.test(f))
|
||||
.sort()
|
||||
|
||||
const archiveEntries: Record<string, Buffer> = {}
|
||||
for (const file of frameFiles) {
|
||||
archiveEntries[file] = fs.readFileSync(path.join(tmpDir, file))
|
||||
}
|
||||
|
||||
const archive = new Bun.Archive(archiveEntries)
|
||||
const archiveBytes = await archive.bytes()
|
||||
const archiveData = Buffer.from(
|
||||
archiveBytes.buffer,
|
||||
archiveBytes.byteOffset,
|
||||
archiveBytes.byteLength,
|
||||
)
|
||||
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 }
|
||||
} catch (err) {
|
||||
if (err instanceof ApplicationFailure) {
|
||||
throw err
|
||||
}
|
||||
throw ApplicationFailure.create({
|
||||
message: `Failed to extract video chunk frames for ${params.startTime}-${params.endTime}: ${err instanceof Error ? err.message : String(err)}`,
|
||||
nonRetryable: false,
|
||||
})
|
||||
} finally {
|
||||
transcodeService.removeDir(tmpDir)
|
||||
}
|
||||
}
|
||||
|
||||
const chunkTmp = path.join(os.tmpdir(), `video-chunk-${Date.now()}-${ulid()}.mp4`)
|
||||
try {
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
|
||||
Reference in New Issue
Block a user