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
+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