Download src/utils/document-metadata.ts from RelVDev2/relvcorp2: direct link, hf CLI and curl.
- Browser
- Download file 1.54 kB
-
https://huggingface.co/spaces/RelVDev2/relvcorp2/resolve/main/src/utils/document-metadata.ts
- Command line
-
hf download hf://spaces/RelVDev2/relvcorp2/src/utils/document-metadata.ts
-
curl -L -o document-metadata.ts https://huggingface.co/spaces/RelVDev2/relvcorp2/resolve/main/src/utils/document-metadata.ts
1.54 kB
| 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 {}; | |
| } | |