Spaces:
Sleeping
Sleeping
| import * as fs from 'fs'; | |
| import * as path from 'path'; | |
| import AdmZip from 'adm-zip'; | |
| import { PDFDocument } from 'pdf-lib'; | |
| import { logger } from './logger'; | |
| export interface LocalDocumentMetadata { | |
| pageCount?: number; | |
| pageCountSource?: 'pdf' | 'docx_metadata'; | |
| } | |
| export async function readLocalDocumentMetadata( | |
| filePath: string, | |
| ): Promise<LocalDocumentMetadata> { | |
| if (!filePath || !fs.existsSync(filePath)) return {}; | |
| const extension = path.extname(filePath).toLowerCase(); | |
| try { | |
| if (extension === '.pdf') { | |
| const bytes = await fs.promises.readFile(filePath); | |
| const pdf = await PDFDocument.load(bytes, { | |
| ignoreEncryption: true, | |
| updateMetadata: false, | |
| }); | |
| const pageCount = pdf.getPageCount(); | |
| return pageCount > 0 ? { pageCount, pageCountSource: 'pdf' } : {}; | |
| } | |
| if (extension === '.docx') { | |
| const archive = new AdmZip(filePath); | |
| const appProperties = archive.getEntry('docProps/app.xml'); | |
| if (!appProperties) return {}; | |
| const xml = appProperties.getData().toString('utf-8'); | |
| const match = xml.match(/<(?:\w+:)?Pages>\s*(\d+)\s*<\/(?:\w+:)?Pages>/i); | |
| const pageCount = match ? Number(match[1]) : 0; | |
| return pageCount > 0 | |
| ? { pageCount, pageCountSource: 'docx_metadata' } | |
| : {}; | |
| } | |
| } catch (error) { | |
| logger.warn('Could not read local document page count', { | |
| filePath: path.basename(filePath), | |
| error: error instanceof Error ? error.message : String(error), | |
| }); | |
| } | |
| return {}; | |
| } | |