char-fork/llama.cpp

git clone https://git.t4t.associates/char-fork/llama.cpp

Aleksander Grygierui: Linting & Formatting scripts (#26819)92d1bb0c9

char/aliceai-t5-moe
4.3 KiB154 linesraw
1/**
2 * PDF processing utilities using PDF.js
3 * Handles PDF text extraction and image conversion in the browser
4 */
5
6import { browser } from '$app/environment';
7import { MimeTypeApplication, MimeTypeImage } from '$lib/enums';
8import * as pdfjs from 'pdfjs-dist';
9
10type TextContent = {
11	items: Array<{ str: string }>;
12};
13
14if (browser) {
15	// Import worker as text and create blob URL for inline bundling
16	import('pdfjs-dist/build/pdf.worker.min.mjs?raw')
17		.then((workerModule) => {
18			const workerBlob = new Blob([workerModule.default], { type: 'application/javascript' });
19
20			pdfjs.GlobalWorkerOptions.workerSrc = URL.createObjectURL(workerBlob);
21		})
22		.catch(() => {
23			console.warn('Failed to load PDF.js worker, PDF processing may not work');
24		});
25}
26
27/**
28 * Convert a File object to ArrayBuffer for PDF.js processing
29 * @param file - The PDF file to convert
30 * @returns Promise resolving to the file's ArrayBuffer
31 */
32async function getFileAsBuffer(file: File): Promise<ArrayBuffer> {
33	return new Promise((resolve, reject) => {
34		const reader = new FileReader();
35
36		reader.onload = (event) => {
37			if (event.target?.result) {
38				resolve(event.target.result as ArrayBuffer);
39			} else {
40				reject(new Error('Failed to read file.'));
41			}
42		};
43		reader.onerror = () => {
44			reject(new Error('Failed to read file.'));
45		};
46		reader.readAsArrayBuffer(file);
47	});
48}
49
50/**
51 * Extract text content from a PDF file
52 * @param file - The PDF file to process
53 * @returns Promise resolving to the extracted text content
54 */
55export async function convertPDFToText(file: File): Promise<string> {
56	if (!browser) {
57		throw new Error('PDF processing is only available in the browser');
58	}
59
60	try {
61		const buffer = await getFileAsBuffer(file);
62		const pdf = await pdfjs.getDocument({ data: buffer }).promise;
63		const numPages = pdf.numPages;
64		const textContentPromises: Promise<TextContent>[] = [];
65
66		for (let i = 1; i <= numPages; i++) {
67			// eslint-disable-next-line @typescript-eslint/no-explicit-any
68			textContentPromises.push(pdf.getPage(i).then((page: any) => page.getTextContent()));
69		}
70
71		const textContents = await Promise.all(textContentPromises);
72		const textItems = textContents.flatMap((textContent: TextContent) =>
73			textContent.items.map((item) => item.str ?? '')
74		);
75
76		return textItems.join('\n');
77	} catch (error) {
78		console.error('Error converting PDF to text:', error);
79
80		throw new Error(
81			`Failed to convert PDF to text: ${error instanceof Error ? error.message : 'Unknown error'}`
82		);
83	}
84}
85
86/**
87 * Convert PDF pages to PNG images as data URLs
88 * @param file - The PDF file to convert
89 * @param scale - Rendering scale factor (default: 1.5)
90 * @returns Promise resolving to array of PNG data URLs
91 */
92export async function convertPDFToImage(file: File, scale: number = 1.5): Promise<string[]> {
93	if (!browser) {
94		throw new Error('PDF processing is only available in the browser');
95	}
96
97	try {
98		const buffer = await getFileAsBuffer(file);
99		const doc = await pdfjs.getDocument({ data: buffer }).promise;
100		const pages: Promise<string>[] = [];
101
102		for (let i = 1; i <= doc.numPages; i++) {
103			const page = await doc.getPage(i);
104			const viewport = page.getViewport({ scale });
105			const canvas = document.createElement('canvas');
106			const ctx = canvas.getContext('2d');
107
108			canvas.width = viewport.width;
109			canvas.height = viewport.height;
110
111			if (!ctx) {
112				throw new Error('Failed to get 2D context from canvas');
113			}
114
115			const task = page.render({
116				canvas: canvas,
117				canvasContext: ctx,
118				viewport: viewport
119			});
120
121			pages.push(
122				task.promise.then(() => {
123					return canvas.toDataURL(MimeTypeImage.PNG);
124				})
125			);
126		}
127
128		return await Promise.all(pages);
129	} catch (error) {
130		console.error('Error converting PDF to images:', error);
131
132		throw new Error(
133			`Failed to convert PDF to images: ${error instanceof Error ? error.message : 'Unknown error'}`
134		);
135	}
136}
137
138/**
139 * Check if a file is a PDF based on its MIME type
140 * @param file - The file to check
141 * @returns True if the file is a PDF
142 */
143export function isPdfFile(file: File): boolean {
144	return file.type === MimeTypeApplication.PDF;
145}
146
147/**
148 * Check if a MIME type represents a PDF
149 * @param mimeType - The MIME type to check
150 * @returns True if the MIME type is application/pdf
151 */
152export function isApplicationMimeType(mimeType: string): boolean {
153	return mimeType === MimeTypeApplication.PDF;
154}