mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-24 02:48:21 +00:00
feat(transcode): add PDF proxy support for TXT and CSV files
This commit is contained in:
@@ -20,6 +20,7 @@ import {
|
||||
downloadMediaToTmpActivity,
|
||||
transcodeImageActivity,
|
||||
generateSpriteActivity,
|
||||
generatePdfProxyActivity,
|
||||
transcodeVideoChunkActivity,
|
||||
deleteS3ObjectActivity,
|
||||
} from './transcode'
|
||||
@@ -59,6 +60,8 @@ vi.mock('@shumai/core/src/transcode/transcode', () => ({
|
||||
originalWidth: 800,
|
||||
originalHeight: 1000,
|
||||
}),
|
||||
generatePdfFromText: vi.fn(),
|
||||
generatePdfFromCsv: vi.fn(),
|
||||
createTempDir: vi.fn().mockReturnValue('/tmp'),
|
||||
removeDir: vi.fn(),
|
||||
takeScreenshots: vi.fn(),
|
||||
@@ -223,11 +226,39 @@ describe('Transcode Activities', () => {
|
||||
|
||||
expect(metadataService.updateAssetMetadata).toHaveBeenCalledWith(
|
||||
asset.id,
|
||||
expect.arrayContaining([{ key: 'file_type', value: 'document' }]),
|
||||
expect.arrayContaining([
|
||||
{ key: 'file_type', value: 'document' },
|
||||
{ key: 'proxy_type', value: 'pdf' },
|
||||
]),
|
||||
true,
|
||||
)
|
||||
})
|
||||
|
||||
it('should generate PDF proxy for text/csv files in generatePdfProxyActivity', async () => {
|
||||
const asset = await prisma.asset.create({
|
||||
data: { name: 'test.txt', type: 'file', status: 'uploaded' },
|
||||
})
|
||||
|
||||
const generatePdfFromTextSpy = vi
|
||||
.spyOn(transcodeService, 'generatePdfFromText')
|
||||
.mockImplementation(async (_inPath, outPath) => {
|
||||
const fs = await import('fs')
|
||||
fs.writeFileSync(outPath, 'fake pdf content')
|
||||
})
|
||||
|
||||
const res = await generatePdfProxyActivity({
|
||||
assetId: asset.id,
|
||||
assetKey: 'files/asset1/test.txt',
|
||||
filePath: '/tmp/test.txt',
|
||||
mediaType: 'text/plain',
|
||||
filename: 'test.txt',
|
||||
})
|
||||
|
||||
expect(res.pdfProxyKey).toBe(`files/${asset.id}/proxy.pdf`)
|
||||
expect(generatePdfFromTextSpy).toHaveBeenCalled()
|
||||
generatePdfFromTextSpy.mockRestore()
|
||||
})
|
||||
|
||||
it('should set file_type to file for unknown types', async () => {
|
||||
const asset = await prisma.asset.create({
|
||||
data: { name: 'u.xyz', type: 'file', status: 'uploaded' },
|
||||
|
||||
@@ -59,10 +59,26 @@ export async function getMediaInfoActivity(params: {
|
||||
? 'document'
|
||||
: 'file'
|
||||
|
||||
const isPdf =
|
||||
params.mediaType === 'application/pdf' ||
|
||||
params.mediaType === 'text/plain' ||
|
||||
params.mediaType === 'text/csv'
|
||||
|
||||
const proxyType: 'image' | 'video' | 'audio' | 'pdf' | undefined = isVideo
|
||||
? 'video'
|
||||
: isAudio
|
||||
? 'audio'
|
||||
: isImage
|
||||
? 'image'
|
||||
: isPdf || isDocument
|
||||
? 'pdf'
|
||||
: undefined
|
||||
|
||||
const mediaInfo: PrismaJson.MediaInfo = {
|
||||
duration: 0,
|
||||
filesize: 0,
|
||||
frames: 0,
|
||||
proxyType,
|
||||
imageTranscodes: [],
|
||||
videoTranscodes: [],
|
||||
videoPreview: { width: 0, height: 0 },
|
||||
@@ -80,6 +96,9 @@ export async function getMediaInfoActivity(params: {
|
||||
const metadataUpdates: { key: string; value: string | number }[] = [
|
||||
{ key: 'file_type', value: fileType },
|
||||
]
|
||||
if (proxyType) {
|
||||
metadataUpdates.push({ key: 'proxy_type', value: proxyType })
|
||||
}
|
||||
|
||||
if (isVideo) {
|
||||
const info = await transcodeService.getVideoInfo(params.filePath)
|
||||
@@ -163,7 +182,7 @@ export async function getMediaInfoActivity(params: {
|
||||
{ key: 'resolution_width', value: info.originalWidth },
|
||||
{ key: 'resolution_height', value: info.originalHeight },
|
||||
)
|
||||
} else if (params.mediaType === 'application/pdf') {
|
||||
} else if (isPdf || isDocument) {
|
||||
const info = await transcodeService.getPdfInfo(params.filePath)
|
||||
mediaInfo.frames = info.totalFrames
|
||||
mediaInfo.metadata = {
|
||||
@@ -420,7 +439,7 @@ export async function generateSpriteActivity(params: GenerateSpriteActivityParam
|
||||
const posterFile = path.join(tmpDir, 'poster.webp')
|
||||
|
||||
try {
|
||||
if (params.mediaInfo.mimeType === 'application/pdf') {
|
||||
if (params.mediaInfo.proxyType === 'pdf' || params.mediaInfo.mimeType === 'application/pdf') {
|
||||
const pdfRes = await transcodeService.generatePdfSprite(
|
||||
params.filePath,
|
||||
spriteFile,
|
||||
@@ -485,6 +504,50 @@ export async function generateSpriteActivity(params: GenerateSpriteActivityParam
|
||||
}
|
||||
}
|
||||
|
||||
export interface GeneratePdfProxyActivityParams {
|
||||
assetId: string
|
||||
assetKey: string
|
||||
filePath: string
|
||||
mediaType: string
|
||||
filename: string
|
||||
}
|
||||
|
||||
export async function generatePdfProxyActivity(
|
||||
params: GeneratePdfProxyActivityParams,
|
||||
): Promise<{ pdfProxyKey: string; pdfFilePath: string }> {
|
||||
const isTxt = params.mediaType === 'text/plain' || params.filename.toLowerCase().endsWith('.txt')
|
||||
const isCsv = params.mediaType === 'text/csv' || params.filename.toLowerCase().endsWith('.csv')
|
||||
|
||||
if (!isTxt && !isCsv) {
|
||||
return { pdfProxyKey: params.assetKey, pdfFilePath: params.filePath }
|
||||
}
|
||||
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
const pdfProxyKey = `files/${params.assetId}/proxy.pdf`
|
||||
const tmpDir = path.dirname(params.filePath)
|
||||
const pdfFilePath = path.join(tmpDir, 'proxy.pdf')
|
||||
|
||||
try {
|
||||
if (isCsv) {
|
||||
await transcodeService.generatePdfFromCsv(params.filePath, pdfFilePath)
|
||||
} else {
|
||||
await transcodeService.generatePdfFromText(params.filePath, pdfFilePath)
|
||||
}
|
||||
|
||||
const buffer = fs.readFileSync(pdfFilePath)
|
||||
await s3Service.putObject(bucket, pdfProxyKey, buffer, buffer.length, 'application/pdf')
|
||||
|
||||
return { pdfProxyKey, pdfFilePath }
|
||||
} catch (err) {
|
||||
const { message } = getErrorDetails(err)
|
||||
throw ApplicationFailure.create({
|
||||
message: `Failed to generate PDF proxy for text/csv: ${message}`,
|
||||
nonRetryable: true,
|
||||
cause: err instanceof Error ? err : undefined,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
export async function downloadMediaToTmpActivity(params: {
|
||||
assetKey: string
|
||||
}): Promise<{ filePath: string; tmpDir: string }> {
|
||||
|
||||
@@ -34,6 +34,9 @@ describe('transcodePdfWorkflow', () => {
|
||||
downloadMediaToTmpActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'downloadMediaToTmpActivity',
|
||||
}),
|
||||
generatePdfProxyActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'generatePdfProxyActivity',
|
||||
}),
|
||||
cleanupTmpDirActivity: Object.assign(vi.fn(), { _activityName: 'cleanupTmpDirActivity' }),
|
||||
createEmbeddingTaskIfEnabledActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'createEmbeddingTaskIfEnabledActivity',
|
||||
@@ -60,6 +63,10 @@ describe('transcodePdfWorkflow', () => {
|
||||
filePath: '/tmp/doc.pdf',
|
||||
tmpDir: '/tmp',
|
||||
})
|
||||
mockActivities.generatePdfProxyActivity.mockResolvedValue({
|
||||
pdfProxyKey: 'document.pdf',
|
||||
pdfFilePath: '/tmp/doc.pdf',
|
||||
})
|
||||
})
|
||||
|
||||
it('should process pdf transcode and sprite generation successfully', async () => {
|
||||
|
||||
@@ -22,6 +22,7 @@ export async function transcodePdfWorkflow(task: WorkflowTask): Promise<void> {
|
||||
generateSpriteActivity,
|
||||
updateAssetMediaActivity,
|
||||
downloadMediaToTmpActivity,
|
||||
generatePdfProxyActivity,
|
||||
createEmbeddingTaskIfEnabledActivity,
|
||||
} = getActivities()
|
||||
|
||||
@@ -35,12 +36,22 @@ export async function transcodePdfWorkflow(task: WorkflowTask): Promise<void> {
|
||||
const download = await executeActivity(workerQueue, downloadMediaToTmpActivity, {
|
||||
assetKey: key,
|
||||
})
|
||||
const { filePath } = download
|
||||
let currentFilePath = download.filePath
|
||||
tmpDir = download.tmpDir
|
||||
|
||||
const pdfProxy = await executeActivity(workerQueue, generatePdfProxyActivity, {
|
||||
assetId: asset.id,
|
||||
assetKey: key,
|
||||
filePath: currentFilePath,
|
||||
mediaType: asset.mediaType || '',
|
||||
filename: asset.name || '',
|
||||
})
|
||||
|
||||
currentFilePath = pdfProxy.pdfFilePath
|
||||
|
||||
const spec = task.payload?.transcode || {}
|
||||
const mediaInfo = await executeActivity(workerQueue, getMediaInfoActivity, {
|
||||
filePath,
|
||||
filePath: currentFilePath,
|
||||
assetId: asset.id,
|
||||
mediaType: asset.mediaType || '',
|
||||
})
|
||||
@@ -51,6 +62,9 @@ export async function transcodePdfWorkflow(task: WorkflowTask): Promise<void> {
|
||||
filesizeInBytes: 0,
|
||||
codec: '',
|
||||
}
|
||||
mediaInfo.pdfTranscode = {
|
||||
key: pdfProxy.pdfProxyKey,
|
||||
}
|
||||
|
||||
if (spec.sprite || spec.poster) {
|
||||
const lastSlashIndex = key.lastIndexOf('/')
|
||||
@@ -68,7 +82,7 @@ export async function transcodePdfWorkflow(task: WorkflowTask): Promise<void> {
|
||||
|
||||
const spriteResult = await executeActivity(workerQueue, generateSpriteActivity, {
|
||||
assetKey: key,
|
||||
filePath,
|
||||
filePath: currentFilePath,
|
||||
spriteSpec,
|
||||
posterSpec,
|
||||
mediaInfo,
|
||||
|
||||
Reference in New Issue
Block a user