feat(agent): add read_pdf_pages tool and PDF page context support

This commit is contained in:
yiling
2026-07-19 09:45:14 +08:00
parent 68a0fb7319
commit f68ba70656
22 changed files with 753 additions and 6 deletions
+49 -1
View File
@@ -1,5 +1,6 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
import { transcodeService } from './transcode'
import { s3Service } from '@shumai/core/src/s3/s3'
import * as path from 'path'
import * as child_process from 'child_process'
import * as fs from 'fs'
@@ -7,6 +8,13 @@ import { WorkflowTask } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db/test'
import sharp from 'sharp'
vi.mock('@shumai/core/src/s3/s3', () => ({
s3Service: {
downloadToFile: vi.fn(),
putObject: vi.fn(),
},
}))
// Mock child_process
vi.mock('child_process', () => ({
execFile: vi.fn(),
@@ -17,7 +25,10 @@ vi.mock('sharp', () => {
const mockSharp = {
resize: vi.fn().mockReturnThis(),
webp: vi.fn().mockReturnThis(),
toFile: vi.fn().mockResolvedValue({}),
toFile: vi.fn().mockImplementation(async (filePath: string) => {
fs.writeFileSync(filePath, 'fake-webp-data')
return {}
}),
metadata: vi.fn().mockResolvedValue({ width: 800, height: 600, format: 'png' }),
}
const sharpFunc = vi.fn(() => mockSharp)
@@ -428,4 +439,41 @@ describe('TranscodeService', () => {
expect(info.originalHeight).toBe(600)
expect(info.hasAudio).toBe(false)
})
it('should render PDF pages and upload to S3', async () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(child_process.execFile as any).mockImplementation(
(
cmd: string,
args: string[],
cb: (err: Error | null, res: { stdout: string; stderr: string }) => void,
) => {
if (cmd === 'pdftoppm') {
const pagePrefix = args[args.length - 1]
const pagePath = `${pagePrefix}-1.png`
fs.writeFileSync(pagePath, 'fake-png-data')
cb(null, { stdout: '', stderr: '' })
} else {
cb(null, { stdout: '', stderr: '' })
}
},
)
vi.mocked(s3Service.downloadToFile).mockResolvedValue(undefined)
vi.mocked(s3Service.putObject).mockResolvedValue(
{} as unknown as Awaited<ReturnType<typeof s3Service.putObject>>,
)
const result = await transcodeService.renderPdfPages({
assetKey: 'projects/p1/doc.pdf',
assetId: 'asset-1',
start: 1,
end: 1,
})
expect(result.length).toBe(1)
expect(result[0].page).toBe(1)
expect(result[0].key).toContain('files/asset-1/pdf_pages/doc-page-1-')
expect(s3Service.putObject).toHaveBeenCalled()
})
})
+106
View File
@@ -1,4 +1,5 @@
import { s3Service } from '@shumai/core/src/s3/s3'
import { stemFromKey } from '@shumai/core/src/utils/filename'
import { prisma, WorkflowTaskStatus, WorkflowTaskType } from '@shumai/db'
import '@shumai/db/src/prisma-json-types'
import { execFile } from 'child_process'
@@ -664,6 +665,111 @@ export class TranscodeService {
}
}
async renderPdfPages(params: {
assetKey: string
assetId: string
start: number
end: number
commentTimestamp?: number | null
annotations?: PrismaJson.AnnotationList | null
}): Promise<Array<{ key: string; page: number }>> {
const bucket = process.env.S3_BUCKET || 'shumai'
const tmpDir = this.createTempDir('pdf-pages-')
const pdfPath = path.join(tmpDir, path.basename(params.assetKey))
try {
// 1. Download PDF file
await s3Service.downloadToFile(bucket, params.assetKey, pdfPath)
// 2. Render pages via pdftoppm (-png -f start -l end)
const pagePrefix = path.join(tmpDir, 'page')
try {
await execFileAsync('pdftoppm', [
'-png',
'-f',
params.start.toString(),
'-l',
params.end.toString(),
pdfPath,
pagePrefix,
])
} catch (err) {
const msg = err instanceof Error ? err.message : String(err)
if (msg.includes('pdftoppm') || msg.includes('ENOENT') || msg.includes('not found')) {
throw new Error(
`pdftoppm executable not found in $PATH. Please install poppler-utils / poppler. (${msg})`,
{ cause: err },
)
}
throw err
}
const files = fs.readdirSync(tmpDir).filter((f) => f.endsWith('.png'))
if (files.length === 0) {
throw new Error('pdftoppm produced no image outputs')
}
files.sort((a, b) => {
const numA = parseInt(a.replace(/[^0-9]/g, ''), 10)
const numB = parseInt(b.replace(/[^0-9]/g, ''), 10)
return numA - numB
})
const results: Array<{ key: string; page: number }> = []
const stem = stemFromKey(params.assetKey)
for (let i = 0; i < files.length; i++) {
const pageNum = params.start + i
const localPngPath = path.join(tmpDir, files[i])
const webpName = `${stem}-page-${pageNum}-${ulid()}.webp`
const localWebpPath = path.join(tmpDir, webpName)
// Convert to 1080p WebP (fit inside 1920x1080)
await sharp(localPngPath, { limitInputPixels: false })
.resize(1920, 1080, { fit: 'inside', withoutEnlargement: false })
.webp({ quality: 85 })
.toFile(localWebpPath)
// Overlay annotations if comment page matches pageNum
const commentPage =
params.commentTimestamp !== undefined && params.commentTimestamp !== null
? Math.round(params.commentTimestamp)
: null
if (
commentPage !== null &&
pageNum === commentPage &&
params.annotations &&
params.annotations.length > 0
) {
const meta = await sharp(localWebpPath, { limitInputPixels: false }).metadata()
const width = meta.width || 1920
const height = meta.height || 1080
const svgStr = renderAnnotationsToSvg(width, height, params.annotations)
const tempCompositedPath = path.join(tmpDir, `composite-${webpName}`)
await sharp(localWebpPath, { limitInputPixels: false })
.composite([{ input: Buffer.from(svgStr), top: 0, left: 0 }])
.toFile(tempCompositedPath)
fs.renameSync(tempCompositedPath, localWebpPath)
}
// Upload to S3
const s3Key = `files/${params.assetId}/pdf_pages/${webpName}`
const webpBuffer = fs.readFileSync(localWebpPath)
await s3Service.putObject(bucket, s3Key, webpBuffer, webpBuffer.length, 'image/webp')
results.push({ key: s3Key, page: pageNum })
}
return results
} finally {
this.removeDir(tmpDir)
}
}
async overlayAnnotations(params: {
assetKey: string
assetId: string