forge
Explore
Log in

Don't you dare go Hollow

hezarfen_frontend

Clone
★ 0

0 watching0 forksTypeScript5.5 MiBc35a83aBurak Boduroğlu4 months ago440 commits

note-importer.ts260 lines, 7.4 KiBHistoryRawDownload
1import pdfWorkerUrl from "pdfjs-dist/legacy/build/pdf.worker.mjs?url";
2
3export type ImportResult = {
4 title: string;
5 markdown: string;
6 hasGarbledWarning: boolean;
7};
8
9async function loadPdfJs() {
10 const pdfjs = await import("pdfjs-dist/legacy/build/pdf.mjs");
11 pdfjs.GlobalWorkerOptions.workerSrc =
12 typeof window === "undefined"
13 ? new URL("../../node_modules/pdfjs-dist/legacy/build/pdf.worker.mjs", import.meta.url).href
14 : pdfWorkerUrl;
15 return pdfjs;
16}
17
18export async function extractImportedPdfText(file: Blob): Promise<string> {
19 const { getDocument } = await loadPdfJs();
20 const loadingTask = getDocument({
21 data: await file.arrayBuffer(),
22 useWorkerFetch: false,
23 });
24 const pdf = await loadingTask.promise;
25
26 try {
27 const pages: string[] = [];
28
29 for (let pageNumber = 1; pageNumber <= pdf.numPages; pageNumber += 1) {
30 const page = await pdf.getPage(pageNumber);
31 const textContent = await page.getTextContent();
32 const pageText = textContent.items
33 .map((item) => {
34 if (!("str" in item)) return "";
35 return item.hasEOL ? `${item.str}\n` : `${item.str} `;
36 })
37 .join("")
38 .replace(/[ \t]+\n/g, "\n")
39 .replace(/[ \t]{2,}/g, " ")
40 .trim();
41
42 if (pageText) pages.push(pageText);
43 page.cleanup();
44 }
45
46 return pages.join("\n\n");
47 } finally {
48 await loadingTask.destroy();
49 }
50}
51
52/**
53 * Note Import Assistant
54 * Converts raw extracted text from PDF, TXT, or MD into a clean, well-structured note.
55 */
56export function processImportedText(rawText: string, fileName?: string): ImportResult {
57 if (!rawText || !rawText.trim()) {
58 const defaultTitle = deriveTitle(fileName, "");
59 return { title: defaultTitle, markdown: "", hasGarbledWarning: false };
60 }
61
62 // 1. Check for garbled / OCR issues
63 const isGarbled = checkGarbledRatio(rawText);
64
65 let text = rawText;
66
67 // Normalize line endings
68 text = text.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
69
70 // 2. Remove noise: page numbers, headers/footers, watermarks
71 text = removeNoise(text);
72
73 // 3. Fix broken line-wrapping from PDF extraction
74 text = fixPdfLineWrapping(text);
75
76 // 4. Reformat into clean Markdown structure
77 text = formatMarkdownStructure(text);
78
79 // 5. Prepend garbled warning if content has OCR issues
80 const warning = "⚠️ Some content may be unreadable due to OCR/extraction issues";
81 if (isGarbled && !text.startsWith(warning)) {
82 text = `${warning}\n\n${text}`;
83 }
84
85 const title = deriveTitle(fileName, text);
86
87 return {
88 title,
89 markdown: text.trim(),
90 hasGarbledWarning: isGarbled,
91 };
92}
93
94/** Detect if content is heavily garbled (scanned OCR noise or binary extraction junk) */
95function checkGarbledRatio(text: string): boolean {
96 if (!text.trim()) return false;
97 // Count replacement characters, unprintable control characters, or repeated non-word noise
98 const replacementChars = (text.match(/\uFFFD/g) || []).length;
99 const nonAsciiControl = (text.match(/[\x00-\x08\x0B\x0C\x0E-\x1F]/g) || []).length;
100 const total = text.length;
101
102 if (total === 0) return false;
103 const ratio = (replacementChars + nonAsciiControl) / total;
104 return ratio > 0.05 || (replacementChars > 5 && ratio > 0.02);
105}
106
107/** Remove page numbers, repeated headers/footers, and watermarks */
108function removeNoise(text: string): string {
109 const lines = text.split("\n");
110 const cleaned: string[] = [];
111
112 const noisePatterns = [
113 /^\s*(page|sayfa)\s+\d+\s*(of|\/|-)?\s*\d*\s*$/i,
114 /^\s*-\s*\d+\s*-\s*$/,
115 /^\s*\d+\s*\/\s*\d+\s*$/,
116 /^\s*(confidential|gizli|draft|taslak|all rights reserved|tüm hakları saklıdır)\s*$/i,
117 /^\s*downloaded from .*\s*$/i,
118 /^\s*watermark\s*$/i,
119 ];
120
121 for (const line of lines) {
122 const trimmed = line.trim();
123 if (!trimmed) {
124 cleaned.push("");
125 continue;
126 }
127
128 const isNoise = noisePatterns.some((pattern) => pattern.test(trimmed));
129 if (!isNoise) {
130 cleaned.push(line);
131 }
132 }
133
134 return cleaned.join("\n");
135}
136
137/** Join lines that were split mid-sentence by PDF line wrapping */
138function fixPdfLineWrapping(text: string): string {
139 const lines = text.split("\n");
140 const result: string[] = [];
141
142 for (let i = 0; i < lines.length; i += 1) {
143 let current = lines[i];
144
145 // If current line ends with a hyphen and next line starts with a letter, join hyphenated word
146 if (i < lines.length - 1 && /[-–]\s*$/.test(current) && /^[a-zçğıöşü]/i.test(lines[i + 1].trim())) {
147 const nextLine = lines[i + 1].trim();
148 current = current.replace(/[-–]\s*$/, "") + nextLine;
149 i += 1;
150 }
151 // If line ends mid-sentence without terminal punctuation (. : ! ? # - | `) and next line starts with lowercase or continuation
152 else if (
153 i < lines.length - 1 &&
154 current.trim().length > 0 &&
155 lines[i + 1].trim().length > 0 &&
156 !/[.:!?#\-|`]\s*$/.test(current.trim()) &&
157 !/^(#+|\*+|-+|\d+\.)\s/.test(lines[i + 1].trim()) &&
158 /^[a-zçğıöşü,\(]/i.test(lines[i + 1].trim())
159 ) {
160 current = `${current.trim()} ${lines[i + 1].trim()}`;
161 i += 1;
162 }
163
164 result.push(current);
165 }
166
167 return result.join("\n");
168}
169
170/** Reformat paragraphs, headers, and bullet points into clean Markdown */
171function formatMarkdownStructure(text: string): string {
172 const lines = text.split("\n");
173 const formatted: string[] = [];
174 let inCodeBlock = false;
175
176 for (let i = 0; i < lines.length; i += 1) {
177 const line = lines[i];
178 const trimmed = line.trim();
179
180 if (trimmed.startsWith("```")) {
181 inCodeBlock = !inCodeBlock;
182 formatted.push(line);
183 continue;
184 }
185
186 if (inCodeBlock) {
187 formatted.push(line);
188 continue;
189 }
190
191 if (!trimmed) {
192 if (formatted.length > 0 && formatted[formatted.length - 1] !== "") {
193 formatted.push("");
194 }
195 continue;
196 }
197
198 // Preserve existing headers, quotes, lists, or tables
199 if (
200 trimmed.startsWith("#") ||
201 trimmed.startsWith(">") ||
202 trimmed.startsWith("- ") ||
203 trimmed.startsWith("* ") ||
204 /^\d+\.\s/.test(trimmed) ||
205 trimmed.startsWith("|")
206 ) {
207 formatted.push(trimmed);
208 continue;
209 }
210
211 // Detect potential section headers (short uppercase/title case lines without trailing punctuation)
212 const isShortHeader =
213 trimmed.length < 60 &&
214 !/[.,:!?]$/.test(trimmed) &&
215 (trimmed === trimmed.toUpperCase() || /^[A-ZÇĞİÖŞÜ0-9\s:-]+$/.test(trimmed));
216
217 if (isShortHeader && trimmed.length > 3) {
218 formatted.push(`## ${toTitleCase(trimmed)}`);
219 continue;
220 }
221
222 formatted.push(trimmed);
223 }
224
225 // Deduplicate consecutive blank lines
226 return formatted
227 .join("\n")
228 .replace(/\n{3,}/g, "\n\n");
229}
230
231function toTitleCase(str: string): string {
232 if (str === str.toUpperCase() && str.length > 4) {
233 return str
234 .toLowerCase()
235 .replace(/(?:^|\s|-)\S/g, (m) => m.toUpperCase());
236 }
237 return str;
238}
239
240/** Extract title from Markdown heading or fallback to file name */
241function deriveTitle(fileName?: string, markdownText?: string): string {
242 if (markdownText) {
243 const headingMatch = markdownText.match(/^#+\s*(.+)$/m);
244 if (headingMatch && headingMatch[1].trim()) {
245 const heading = headingMatch[1].replace(/^[⚠️\s]+/, "").trim();
246 if (heading.length > 0 && heading.length <= 100) {
247 return heading;
248 }
249 }
250 }
251
252 if (fileName) {
253 const cleanName = fileName.replace(/\.[^/.]+$/, "").replace(/[-_]/g, " ").trim();
254 if (cleanName) {
255 return cleanName;
256 }
257 }
258
259 return "Imported Note";
260}