mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-12-01 21:44:27 +00:00
feat(transcode): add PDF proxy support for TXT and CSV files
This commit is contained in:
@@ -19,6 +19,7 @@
|
||||
"hono": "4.12.23",
|
||||
"jittered-fractional-indexing": "1.0.1",
|
||||
"pino": "10.3.1",
|
||||
"pdfkit": "^0.16.0",
|
||||
"sharp": "0.34.5",
|
||||
"tweetnacl": "1.0.3",
|
||||
"ulid": "3.0.2",
|
||||
@@ -27,6 +28,7 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/adm-zip": "0.5.8",
|
||||
"@types/extract-zip": "2.0.3"
|
||||
"@types/extract-zip": "2.0.3",
|
||||
"@types/pdfkit": "^0.13.9"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1697,6 +1697,13 @@ export class AssetService {
|
||||
'GET',
|
||||
)
|
||||
}
|
||||
if (media && media.pdfTranscode?.key) {
|
||||
media.pdfTranscode.url = await s3Service.presign(
|
||||
process.env.S3_BUCKET || 'shumai',
|
||||
media.pdfTranscode.key,
|
||||
'GET',
|
||||
)
|
||||
}
|
||||
|
||||
const key = latestVersion.storageKey?.key
|
||||
if (key) {
|
||||
@@ -1715,6 +1722,8 @@ export class AssetService {
|
||||
}
|
||||
}
|
||||
|
||||
const proxyType = (media?.proxyType || null) as 'image' | 'video' | 'audio' | 'pdf' | null
|
||||
|
||||
result.push({
|
||||
id: a.id,
|
||||
name:
|
||||
@@ -1727,6 +1736,7 @@ export class AssetService {
|
||||
targetType: a.type === AssetType.symlink ? a.target?.type : null,
|
||||
status: latestVersion.status,
|
||||
mediaType: latestVersion.mediaType,
|
||||
proxyType,
|
||||
latestChildren,
|
||||
preview,
|
||||
createdAt: a.createdAt.toISOString(),
|
||||
@@ -2014,8 +2024,11 @@ export class AssetService {
|
||||
)
|
||||
}
|
||||
|
||||
const proxyType = (asset.media?.proxyType || null) as 'image' | 'video' | 'audio' | 'pdf' | null
|
||||
|
||||
return {
|
||||
mediaType: asset.mediaType,
|
||||
proxyType,
|
||||
thumbnailUrl,
|
||||
originalHeight: asset.media.metadata?.originalHeight,
|
||||
originalWidth: asset.media.metadata?.originalWidth,
|
||||
|
||||
@@ -112,6 +112,23 @@ export const systemFields: Prisma.MetadataFieldCreateInput[] = [
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'proxy_type',
|
||||
scope: 'SYSTEM',
|
||||
readOnly: true,
|
||||
config: {
|
||||
name: 'Proxy Type',
|
||||
type: 'select',
|
||||
select: {
|
||||
options: [
|
||||
{ id: 'image', displayName: 'Image', color: 'system' },
|
||||
{ id: 'video', displayName: 'Video', color: 'system' },
|
||||
{ id: 'audio', displayName: 'Audio', color: 'system' },
|
||||
{ id: 'pdf', displayName: 'PDF', color: 'system' },
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
key: 'audio_bit_depth',
|
||||
scope: 'SYSTEM',
|
||||
|
||||
@@ -507,8 +507,11 @@ describe('TranscodeService', () => {
|
||||
},
|
||||
]
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const sharpSpy = vi.mocked(sharp).mockImplementation((input: any, options?: any) => realSharp(input, options))
|
||||
const sharpSpy = vi
|
||||
.mocked(sharp)
|
||||
.mockImplementation((input: unknown, options?: unknown) =>
|
||||
realSharp(input as Parameters<typeof sharp>[0], options as Parameters<typeof sharp>[1]),
|
||||
)
|
||||
|
||||
const outputBuffer = await transcodeService.overlayAnnotationsOnBuffer(
|
||||
inputBuffer,
|
||||
@@ -563,8 +566,11 @@ describe('TranscodeService', () => {
|
||||
},
|
||||
]
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const sharpSpy = vi.mocked(sharp).mockImplementation((input: any, options?: any) => realSharp(input, options))
|
||||
const sharpSpy = vi
|
||||
.mocked(sharp)
|
||||
.mockImplementation((input: unknown, options?: unknown) =>
|
||||
realSharp(input as Parameters<typeof sharp>[0], options as Parameters<typeof sharp>[1]),
|
||||
)
|
||||
|
||||
const outputBuffer = await transcodeService.overlayAnnotationsOnBuffer(
|
||||
inputBuffer,
|
||||
@@ -591,5 +597,32 @@ describe('TranscodeService', () => {
|
||||
expect(g).toBeGreaterThan(200)
|
||||
expect(b).toBeLessThan(100)
|
||||
})
|
||||
|
||||
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')
|
||||
fs.writeFileSync(txtFile, 'Hello World\n你好世界\nこんにちは世界\n안녕하세요世界')
|
||||
|
||||
await transcodeService.generatePdfFromText(txtFile, pdfFile)
|
||||
|
||||
expect(fs.existsSync(pdfFile)).toBe(true)
|
||||
const stat = fs.statSync(pdfFile)
|
||||
expect(stat.size).toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
it('should generate PDF from CSV file including CJK characters', async () => {
|
||||
const csvFile = path.join(tempDir, 'test.csv')
|
||||
const pdfFile = path.join(tempDir, 'output.pdf')
|
||||
fs.writeFileSync(
|
||||
csvFile,
|
||||
'Name,Age,Country\nHello World,25,USA\n你好世界,30,China\nこんにちは,28,Japan\n안녕하세요,22,Korea',
|
||||
)
|
||||
|
||||
await transcodeService.generatePdfFromCsv(csvFile, pdfFile)
|
||||
|
||||
expect(fs.existsSync(pdfFile)).toBe(true)
|
||||
const stat = fs.statSync(pdfFile)
|
||||
expect(stat.size).toBeGreaterThan(0)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import PDFDocument from 'pdfkit'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { stemFromKey } from '@shumai/core/src/utils/filename'
|
||||
import { prisma, WorkflowTaskStatus, WorkflowTaskType } from '@shumai/db'
|
||||
@@ -13,6 +14,89 @@ import { dataFormatNames } from './dataFormatNames'
|
||||
|
||||
const execFileAsync = promisify(execFile)
|
||||
|
||||
export interface CjkFontConfig {
|
||||
fontPath: string
|
||||
fontName?: string
|
||||
}
|
||||
|
||||
export function findCjkFontPath(): CjkFontConfig | undefined {
|
||||
if (process.env.PDF_CJK_FONT_PATH && fs.existsSync(process.env.PDF_CJK_FONT_PATH)) {
|
||||
return { fontPath: process.env.PDF_CJK_FONT_PATH }
|
||||
}
|
||||
const candidates: { fontPath: string; fontName?: string }[] = [
|
||||
{ fontPath: '/System/Library/Fonts/Supplemental/Arial Unicode.ttf' },
|
||||
{ fontPath: '/Library/Fonts/Arial Unicode.ttf' },
|
||||
{ fontPath: '/System/Library/Fonts/PingFang.ttc', fontName: 'PingFangSC-Regular' },
|
||||
{ fontPath: '/System/Library/Fonts/STHeiti Light.ttc', fontName: 'STHeitiSC-Light' },
|
||||
{ fontPath: '/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc' },
|
||||
{ fontPath: '/usr/share/fonts/truetype/noto/NotoSansCJK-Regular.ttc' },
|
||||
{ fontPath: '/usr/share/fonts/truetype/wqy/wqy-zenhei.ttc' },
|
||||
{ fontPath: '/usr/share/fonts/truetype/arphic/ukai.ttc' },
|
||||
]
|
||||
for (const item of candidates) {
|
||||
if (fs.existsSync(item.fontPath)) {
|
||||
return item
|
||||
}
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
export function parseCsvContent(content: string): string[][] {
|
||||
const rows: string[][] = []
|
||||
let currentRow: string[] = []
|
||||
let currentField = ''
|
||||
let insideQuotes = false
|
||||
|
||||
for (let i = 0; i < content.length; i++) {
|
||||
const char = content[i]
|
||||
const nextChar = content[i + 1]
|
||||
|
||||
if (insideQuotes) {
|
||||
if (char === '"' && nextChar === '"') {
|
||||
currentField += '"'
|
||||
i++
|
||||
} else if (char === '"') {
|
||||
insideQuotes = false
|
||||
} else {
|
||||
currentField += char
|
||||
}
|
||||
} else {
|
||||
if (char === '"') {
|
||||
insideQuotes = true
|
||||
} else if (char === ',') {
|
||||
currentRow.push(currentField.trim())
|
||||
currentField = ''
|
||||
} else if (char === '\n' || (char === '\r' && nextChar === '\n')) {
|
||||
if (char === '\r') i++
|
||||
currentRow.push(currentField.trim())
|
||||
if (currentRow.some((f) => f.length > 0)) {
|
||||
rows.push(currentRow)
|
||||
}
|
||||
currentRow = []
|
||||
currentField = ''
|
||||
} else if (char === '\r') {
|
||||
currentRow.push(currentField.trim())
|
||||
if (currentRow.some((f) => f.length > 0)) {
|
||||
rows.push(currentRow)
|
||||
}
|
||||
currentRow = []
|
||||
currentField = ''
|
||||
} else {
|
||||
currentField += char
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (currentField || currentRow.length > 0) {
|
||||
currentRow.push(currentField.trim())
|
||||
if (currentRow.some((f) => f.length > 0)) {
|
||||
rows.push(currentRow)
|
||||
}
|
||||
}
|
||||
|
||||
return rows
|
||||
}
|
||||
|
||||
export interface MediaMetadata {
|
||||
originalWidth: number
|
||||
originalHeight: number
|
||||
@@ -427,6 +511,132 @@ export class TranscodeService {
|
||||
}
|
||||
}
|
||||
|
||||
async generatePdfFromText(inputFile: string, outputFile: string): Promise<void> {
|
||||
const content = fs.readFileSync(inputFile, 'utf-8')
|
||||
const containsCjk = /[\u3000-\u303f\u3040-\u309f\u30a0-\u30ff\u4e00-\u9fff\uac00-\ud7af]/.test(
|
||||
content,
|
||||
)
|
||||
const cjkFont = containsCjk ? findCjkFontPath() : undefined
|
||||
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
const doc = new PDFDocument({
|
||||
size: 'A4',
|
||||
margin: 40,
|
||||
bufferPages: true,
|
||||
})
|
||||
const writeStream = fs.createWriteStream(outputFile)
|
||||
doc.pipe(writeStream)
|
||||
|
||||
if (cjkFont) {
|
||||
if (cjkFont.fontName !== undefined) {
|
||||
doc.font(cjkFont.fontPath, cjkFont.fontName)
|
||||
} else {
|
||||
doc.font(cjkFont.fontPath)
|
||||
}
|
||||
} else {
|
||||
doc.font('Helvetica')
|
||||
}
|
||||
doc.fontSize(10)
|
||||
|
||||
doc.text(content, {
|
||||
lineGap: 3,
|
||||
paragraphGap: 4,
|
||||
})
|
||||
|
||||
doc.end()
|
||||
|
||||
writeStream.on('finish', () => resolve())
|
||||
writeStream.on('error', (err) => reject(err))
|
||||
})
|
||||
}
|
||||
|
||||
async generatePdfFromCsv(inputFile: string, outputFile: string): Promise<void> {
|
||||
const content = fs.readFileSync(inputFile, 'utf-8')
|
||||
const rows = parseCsvContent(content)
|
||||
const containsCjk = /[\u3000-\u303f\u3040-\u309f\u30a0-\u30ff\u4e00-\u9fff\uac00-\ud7af]/.test(
|
||||
content,
|
||||
)
|
||||
const cjkFont = containsCjk ? findCjkFontPath() : undefined
|
||||
|
||||
if (rows.length === 0) {
|
||||
rows.push(['(Empty CSV)'])
|
||||
}
|
||||
|
||||
const maxCols = Math.max(...rows.map((r) => r.length))
|
||||
const isLandscape = maxCols > 5
|
||||
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
const doc = new PDFDocument({
|
||||
size: 'A4',
|
||||
layout: isLandscape ? 'landscape' : 'portrait',
|
||||
margin: 30,
|
||||
bufferPages: true,
|
||||
})
|
||||
const writeStream = fs.createWriteStream(outputFile)
|
||||
doc.pipe(writeStream)
|
||||
|
||||
const setFont = () => {
|
||||
if (cjkFont) {
|
||||
if (cjkFont.fontName !== undefined) {
|
||||
doc.font(cjkFont.fontPath, cjkFont.fontName)
|
||||
} else {
|
||||
doc.font(cjkFont.fontPath)
|
||||
}
|
||||
} else {
|
||||
doc.font('Helvetica')
|
||||
}
|
||||
doc.fontSize(9)
|
||||
}
|
||||
|
||||
setFont()
|
||||
|
||||
const pageWidth = doc.page.width - doc.page.margins.left - doc.page.margins.right
|
||||
const colWidth = Math.max(40, pageWidth / maxCols)
|
||||
|
||||
const startX = doc.page.margins.left
|
||||
let startY = doc.page.margins.top
|
||||
const rowHeight = 20
|
||||
|
||||
const drawRow = (row: string[], isHeader: boolean, y: number) => {
|
||||
if (isHeader) {
|
||||
doc.rect(startX, y, colWidth * maxCols, rowHeight).fill('#e0e0e0')
|
||||
doc.fillColor('#000000')
|
||||
}
|
||||
for (let col = 0; col < maxCols; col++) {
|
||||
const text = row[col] || ''
|
||||
const x = startX + col * colWidth
|
||||
doc.rect(x, y, colWidth, rowHeight).stroke('#cccccc')
|
||||
doc.fillColor('#000000').text(text, x + 4, y + 5, {
|
||||
width: colWidth - 8,
|
||||
height: rowHeight - 6,
|
||||
ellipsis: true,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const headerRow = rows[0]
|
||||
drawRow(headerRow, true, startY)
|
||||
startY += rowHeight
|
||||
|
||||
for (let r = 1; r < rows.length; r++) {
|
||||
if (startY + rowHeight > doc.page.height - doc.page.margins.bottom) {
|
||||
doc.addPage()
|
||||
setFont()
|
||||
startY = doc.page.margins.top
|
||||
drawRow(headerRow, true, startY)
|
||||
startY += rowHeight
|
||||
}
|
||||
drawRow(rows[r], false, startY)
|
||||
startY += rowHeight
|
||||
}
|
||||
|
||||
doc.end()
|
||||
|
||||
writeStream.on('finish', () => resolve())
|
||||
writeStream.on('error', (err) => reject(err))
|
||||
})
|
||||
}
|
||||
|
||||
async extractAudio(inputFile: string, outputFile: string, bitrate: string): Promise<void> {
|
||||
const args = ['-i', inputFile, '-vn', '-acodec', 'libmp3lame', '-b:a', bitrate, outputFile]
|
||||
await execFileAsync('ffmpeg', ['-y', '-loglevel', 'warning', ...args])
|
||||
|
||||
@@ -236,7 +236,7 @@ describe('UploadService', () => {
|
||||
})
|
||||
const asset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'file.txt',
|
||||
name: 'file.json',
|
||||
type: AssetType.file,
|
||||
project: { connect: { id: projectId } },
|
||||
parent: { connect: { id: parentId } },
|
||||
@@ -247,7 +247,7 @@ describe('UploadService', () => {
|
||||
create: { key: 'test-key' },
|
||||
},
|
||||
},
|
||||
mediaType: 'text/plain',
|
||||
mediaType: 'application/json',
|
||||
},
|
||||
})
|
||||
|
||||
|
||||
@@ -303,7 +303,13 @@ export class UploadService {
|
||||
const isVideo = asset.mediaType?.startsWith('video/')
|
||||
const isImage = asset.mediaType?.startsWith('image/')
|
||||
const isAudio = asset.mediaType?.startsWith('audio/')
|
||||
const isPdf = asset.mediaType === 'application/pdf' || asset.name.toLowerCase().endsWith('.pdf')
|
||||
const isPdf =
|
||||
asset.mediaType === 'application/pdf' ||
|
||||
asset.mediaType === 'text/plain' ||
|
||||
asset.mediaType === 'text/csv' ||
|
||||
asset.name.toLowerCase().endsWith('.pdf') ||
|
||||
asset.name.toLowerCase().endsWith('.txt') ||
|
||||
asset.name.toLowerCase().endsWith('.csv')
|
||||
|
||||
if (autofillAgent && (isVideo || isImage)) {
|
||||
await tx.workflowTask.create({
|
||||
|
||||
@@ -124,13 +124,20 @@ declare global {
|
||||
codec: string
|
||||
}
|
||||
|
||||
export interface PdfTranscode {
|
||||
key?: string
|
||||
url?: string
|
||||
}
|
||||
|
||||
export interface MediaInfo {
|
||||
duration: number
|
||||
filesize: number
|
||||
frames: number
|
||||
proxyType?: 'image' | 'video' | 'audio' | 'pdf'
|
||||
imageTranscodes: ImageTranscode[]
|
||||
videoTranscodes: VideoTranscode[]
|
||||
videoPreview: VideoTranscode
|
||||
pdfTranscode?: PdfTranscode
|
||||
sprite?: SpriteInfo
|
||||
poster?: PosterInfo
|
||||
thumbnail?: ImageTranscode
|
||||
|
||||
@@ -9,6 +9,7 @@ export type AssetInfoPaginatedList = z.infer<typeof assetInfoPaginatedListSchema
|
||||
|
||||
export const previewInfoSchema = z.object({
|
||||
mediaType: z.string().nullable(),
|
||||
proxyType: z.enum(['image', 'video', 'audio', 'pdf']).nullable().optional(),
|
||||
thumbnailUrl: z.string().optional(),
|
||||
originalHeight: z.number().optional(),
|
||||
originalWidth: z.number().optional(),
|
||||
@@ -63,6 +64,7 @@ export const assetInfoSchema = z.object({
|
||||
targetType: z.string().optional().nullable(),
|
||||
status: z.string(),
|
||||
mediaType: z.string().nullable(),
|
||||
proxyType: z.enum(['image', 'video', 'audio', 'pdf']).nullable().optional(),
|
||||
latestChildren: z.array(childPreviewSchema).optional(),
|
||||
preview: previewInfoSchema.nullable().optional(),
|
||||
createdAt: z.string(),
|
||||
@@ -105,6 +107,7 @@ export const assetInfoSchema = z.object({
|
||||
)
|
||||
.optional(),
|
||||
videoPreview: z.object({ url: z.string(), key: z.string().optional() }).optional(),
|
||||
pdfTranscode: z.object({ url: z.string(), key: z.string().optional() }).optional(),
|
||||
mimeType: z.string().optional(),
|
||||
metadata: mediaMetadataSchema.optional(),
|
||||
})
|
||||
|
||||
@@ -602,9 +602,7 @@ describe.each(['local', 'temporal'] as const)(
|
||||
})
|
||||
|
||||
// 4. Wait for workflow to complete
|
||||
console.log(
|
||||
`Submitted E2E PDF Pages Workflow Task. ID: ${task.id}. Awaiting completion...`,
|
||||
)
|
||||
console.log(`Submitted E2E PDF Pages Workflow Task. ID: ${task.id}. Awaiting completion...`)
|
||||
const completedTask = await workflowService.executeWait(task, 45000)
|
||||
|
||||
// 5. Verification
|
||||
@@ -616,5 +614,91 @@ describe.each(['local', 'temporal'] as const)(
|
||||
expect(output.pages).toBeDefined()
|
||||
expect(output.pages.length).toBeGreaterThan(0)
|
||||
}, 50000)
|
||||
|
||||
it('should run transcodeMedia workflow for a TXT asset with CJK text to generate PDF proxy successfully', async () => {
|
||||
// 1. Seed Database
|
||||
const team = await prisma.team.create({
|
||||
data: { name: 'E2E CJK TXT Transcode Team' },
|
||||
})
|
||||
|
||||
const project = await prisma.project.create({
|
||||
data: { name: 'E2E CJK TXT Transcode Project', teamId: team.id },
|
||||
})
|
||||
|
||||
const storageKey = await prisma.storageKey.create({
|
||||
data: {
|
||||
key: 'projects/e2e/cjk-test.txt',
|
||||
},
|
||||
})
|
||||
|
||||
const asset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'cjk-test.txt',
|
||||
type: 'file',
|
||||
status: 'uploaded',
|
||||
mediaType: 'text/plain',
|
||||
projectId: project.id,
|
||||
storageKeyId: storageKey.id,
|
||||
},
|
||||
})
|
||||
|
||||
// 2. Seed S3 Storage with CJK text
|
||||
const cjkText =
|
||||
'Hello World\n你好世界 (Chinese)\nこんにちは世界 (Japanese)\n안녕하세요世界 (Korean)\nLine 5 of random text.'
|
||||
const txtBuffer = Buffer.from(cjkText, 'utf-8')
|
||||
await s3Service.putObject(
|
||||
'shumai-e2e-test-bucket-transcode',
|
||||
'projects/e2e/cjk-test.txt',
|
||||
txtBuffer,
|
||||
txtBuffer.length,
|
||||
'text/plain',
|
||||
)
|
||||
|
||||
// 3. Create Workflow Task
|
||||
const task = await prisma.workflowTask.create({
|
||||
data: {
|
||||
type: 'transcode_pdf',
|
||||
status: 'pending',
|
||||
assetId: asset.id,
|
||||
projectId: project.id,
|
||||
teamId: team.id,
|
||||
payload: {
|
||||
projectId: project.id,
|
||||
transcode: {
|
||||
poster: true,
|
||||
sprite: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
// 4. Wait for workflow to complete
|
||||
console.log(
|
||||
`Submitted E2E CJK TXT Transcode Workflow Task. ID: ${task.id}. Awaiting completion...`,
|
||||
)
|
||||
const completedTask = await workflowService.executeWait(task, 45000)
|
||||
|
||||
// 5. Verification
|
||||
expect(completedTask.status).toBe('completed')
|
||||
|
||||
const updatedAsset = await prisma.asset.findUnique({
|
||||
where: { id: asset.id },
|
||||
})
|
||||
expect(updatedAsset?.status).toBe(AssetStatus.processed)
|
||||
|
||||
const mediaInfo = updatedAsset?.media as unknown as {
|
||||
proxyType?: string
|
||||
pdfTranscode?: { key: string }
|
||||
poster?: { key: string }
|
||||
sprite?: { key: string }
|
||||
frames?: number
|
||||
}
|
||||
expect(mediaInfo).toBeDefined()
|
||||
expect(mediaInfo.proxyType).toBe('pdf')
|
||||
expect(mediaInfo.pdfTranscode?.key).toBe(`files/${asset.id}/proxy.pdf`)
|
||||
expect(mediaInfo.poster?.key).toContain('poster.webp')
|
||||
expect(mediaInfo.sprite?.key).toContain('sprite.webp')
|
||||
expect(mediaInfo.frames).toBeGreaterThan(0)
|
||||
}, 50000)
|
||||
},
|
||||
)
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -4,8 +4,10 @@ import { formatTime } from '../viewers/video/utils'
|
||||
|
||||
type FilePreviewItem = {
|
||||
type?: string | null
|
||||
proxyType?: 'image' | 'video' | 'audio' | 'pdf' | null
|
||||
preview?: {
|
||||
mediaType?: string | null
|
||||
proxyType?: 'image' | 'video' | 'audio' | 'pdf' | null
|
||||
spriteUrl?: string
|
||||
thumbnailUrl?: string
|
||||
originalWidth?: number
|
||||
@@ -21,9 +23,10 @@ interface FilePreviewProps {
|
||||
}
|
||||
|
||||
export const FilePreview = ({ item, showDuration = false }: FilePreviewProps) => {
|
||||
const isVideo = item.preview?.mediaType?.startsWith('video/')
|
||||
const isAudio = item.preview?.mediaType?.startsWith('audio/')
|
||||
const isPdf = item.preview?.mediaType === 'application/pdf'
|
||||
const proxyType = item.preview?.proxyType || item.proxyType
|
||||
const isVideo = proxyType === 'video'
|
||||
const isAudio = proxyType === 'audio'
|
||||
const isPdf = proxyType === 'pdf'
|
||||
const hasDuration = isVideo || isAudio
|
||||
const duration = item.preview?.duration
|
||||
const pageCount = item.preview?.pageCount
|
||||
|
||||
@@ -5,7 +5,7 @@ import { CompareImagePane } from './compare-image-pane'
|
||||
export const imageTypeDefinition: FileTypeDefinition = {
|
||||
id: 'image',
|
||||
name: 'Image',
|
||||
match: (file) => !!file.mediaType?.startsWith('image/'),
|
||||
match: (file) => file.proxyType === 'image',
|
||||
viewer: ImageViewer,
|
||||
comparePane: CompareImagePane,
|
||||
commentsConfig: {
|
||||
|
||||
@@ -4,7 +4,7 @@ import PdfViewer from './pdf-viewer'
|
||||
export const pdfTypeDefinition: FileTypeDefinition = {
|
||||
id: 'pdf',
|
||||
name: 'PDF',
|
||||
match: (file) => file.mediaType === 'application/pdf' || file.name.toLowerCase().endsWith('.pdf'),
|
||||
match: (file) => file.proxyType === 'pdf',
|
||||
viewer: PdfViewer,
|
||||
commentsConfig: {
|
||||
hasTimestamp: true,
|
||||
|
||||
@@ -132,7 +132,7 @@ export const PdfViewer = React.forwardRef<MediaController, FileViewerProps>(
|
||||
}
|
||||
}, [])
|
||||
|
||||
const fileUrl = file.media?.original?.downloadUrl
|
||||
const fileUrl = file.media?.pdfTranscode?.url || file.media?.original?.downloadUrl
|
||||
|
||||
// Load PDF Document
|
||||
useEffect(() => {
|
||||
|
||||
@@ -5,7 +5,7 @@ import { CompareVideoPane } from './compare-video-pane'
|
||||
export const videoTypeDefinition: FileTypeDefinition = {
|
||||
id: 'video',
|
||||
name: 'Video',
|
||||
match: (file) => !!file.mediaType?.startsWith('video/') || !!file.mediaType?.startsWith('audio/'),
|
||||
match: (file) => file.proxyType === 'video' || file.proxyType === 'audio',
|
||||
viewer: VideoViewer,
|
||||
comparePane: CompareVideoPane,
|
||||
commentsConfig: {
|
||||
|
||||
Reference in New Issue
Block a user