-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathProgram.Llm.cs
More file actions
387 lines (342 loc) · 16.8 KB
/
Copy pathProgram.Llm.cs
File metadata and controls
387 lines (342 loc) · 16.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
namespace Demo
{
internal partial class Program
{
internal static void TestMarkdownReader()
{
Console.WriteLine("\n=== TestMarkdownReader =======================");
var reader = new PDFMarkdownReader();
string testFilePath = Path.GetFullPath("../../../../TestDocuments/Demo/columns.pdf");
var docs = reader.LoadData(testFilePath);
foreach (var doc in docs)
{
Console.WriteLine(doc.Text);
}
}
internal static void TestGetText()
{
Console.WriteLine("\n=== TestGetText =======================");
var reader = new PDFMarkdownReader();
string testFilePath = Path.GetFullPath("../../../../TestDocuments/Demo/columns.pdf");
Document doc = new Document(testFilePath);
for (int i = 0; i < doc.PageCount; i++)
{
Page page = doc[i];
var text = Utils.GetText(page, option: "dict");
Console.WriteLine(text);
page.Dispose();
}
doc.Close();
}
internal static void TestTable()
{
Console.WriteLine("\n=== TestTable =======================");
try
{
string testFilePath = Path.GetFullPath("../../../../TestDocuments/Demo/err_table.pdf");
if (!File.Exists(testFilePath))
{
Console.WriteLine($"Error: Test file not found: {testFilePath}");
return;
}
Console.WriteLine($"Loading PDF: {testFilePath}");
Document doc = new Document(testFilePath);
Console.WriteLine($"Document loaded: {doc.PageCount} page(s)");
// Test on first page
Page page = doc[0];
Console.WriteLine($"\nPage 0 - Rect: {page.Rect}");
// Test 1: Get tables with default strategy
Console.WriteLine("\n--- Test 1: Get tables with 'lines_strict' strategy ---");
List<Table> tables = Utils.GetTables(
page,
clip: page.Rect,
vertical_strategy: "lines_strict",
horizontal_strategy: "lines_strict");
Console.WriteLine($"Found {tables.Count} table(s) on page 0");
if (tables.Count > 0)
{
for (int i = 0; i < tables.Count; i++)
{
Table table = tables[i];
Console.WriteLine($"\n Table {i + 1}:");
Console.WriteLine($" Rows: {table.row_count}");
Console.WriteLine($" Columns: {table.col_count}");
if (table.bbox != null)
{
Console.WriteLine($" BBox: ({table.bbox.X0:F2}, {table.bbox.Y0:F2}, {table.bbox.X1:F2}, {table.bbox.Y1:F2})");
}
// Display header information
if (table.header != null)
{
Console.WriteLine($" Header:");
Console.WriteLine($" External: {table.header.external}");
if (table.header.names != null && table.header.names.Count > 0)
{
Console.WriteLine($" Column names: {string.Join(", ", table.header.names)}");
}
}
// Extract table data
Console.WriteLine($"\n Extracting table data...");
List<List<string>> tableData = table.Extract();
if (tableData != null && tableData.Count > 0)
{
Console.WriteLine($" Extracted {tableData.Count} row(s) of data");
// Show first few rows as preview
int previewRows = Math.Min(3, tableData.Count);
for (int row = 0; row < previewRows; row++)
{
var rowData = tableData[row];
if (rowData != null)
{
Console.WriteLine($" Row {row + 1}: {string.Join(" | ", rowData.Take(5))}"); // Show first 5 columns
}
}
if (tableData.Count > previewRows)
{
Console.WriteLine($" ... and {tableData.Count - previewRows} more row(s)");
}
}
// Convert to markdown
Console.WriteLine($"\n Converting to Markdown...");
try
{
string markdown = table.ToMarkdown(clean: false, fillEmpty: true);
if (!string.IsNullOrEmpty(markdown))
{
Console.WriteLine($" Markdown length: {markdown.Length} characters");
// Save markdown to file
string markdownFile = $"table_{i + 1}_page0.md";
File.WriteAllText(markdownFile, markdown, Encoding.UTF8);
Console.WriteLine($" Markdown saved to: {markdownFile}");
// Show preview
int previewLength = Math.Min(200, markdown.Length);
Console.WriteLine($" Preview (first {previewLength} chars):");
Console.WriteLine($" {markdown.Substring(0, previewLength)}...");
}
}
catch (Exception ex)
{
Console.WriteLine($" Error converting to markdown: {ex.Message}");
}
}
}
else
{
Console.WriteLine("No tables found. Trying with 'lines' strategy...");
// Test 2: Try with 'lines' strategy (less strict)
Console.WriteLine("\n--- Test 2: Get tables with 'lines' strategy ---");
tables = Utils.GetTables(
page,
clip: page.Rect,
vertical_strategy: "lines",
horizontal_strategy: "lines");
Console.WriteLine($"Found {tables.Count} table(s) with 'lines' strategy");
}
// Test 3: Try with 'text' strategy
Console.WriteLine("\n--- Test 3: Get tables with 'text' strategy ---");
List<Table> textTables = Utils.GetTables(
page,
clip: page.Rect,
vertical_strategy: "text",
horizontal_strategy: "text");
Console.WriteLine($"Found {textTables.Count} table(s) with 'text' strategy");
// Test 4: Get tables from all pages
Console.WriteLine("\n--- Test 4: Get tables from all pages ---");
int totalTables = 0;
for (int pageNum = 0; pageNum < doc.PageCount; pageNum++)
{
Page currentPage = doc[pageNum];
List<Table> pageTables = Utils.GetTables(
currentPage,
clip: currentPage.Rect,
vertical_strategy: "lines_strict",
horizontal_strategy: "lines_strict");
if (pageTables.Count > 0)
{
Console.WriteLine($" Page {pageNum}: {pageTables.Count} table(s)");
totalTables += pageTables.Count;
}
currentPage.Dispose();
}
Console.WriteLine($"Total tables found across all pages: {totalTables}");
page.Dispose();
doc.Close();
Console.WriteLine("\n=== TestTable completed successfully ===");
}
catch (Exception ex)
{
Console.WriteLine($"Error in TestTable: {ex.Message}");
Console.WriteLine($"Stack trace: {ex.StackTrace}");
throw;
}
}
internal static void TestMuPdfRagToMarkdown()
{
Console.WriteLine("\n=== TestMuPdfRagToMarkdown (legacy RAG via PDF4LLM.UseLayout=false) =======================");
try
{
// Find a test PDF file
//string testFilePath = Path.GetFullPath("../../../../TestDocuments/Demo/national-capitals.pdf");
string testFilePath = Path.GetFullPath("../../../../TestDocuments/Demo/Magazine.pdf");
Document doc = new Document(testFilePath);
Console.WriteLine($"Document loaded: {doc.PageCount} page(s)");
Console.WriteLine($"Document name: {doc.Name}");
// Test 1: legacy MuPdf_rag-style path (MuPdfRag is internal; use public API only)
Console.WriteLine("\n--- Test 1: PDF4LLM.ToMarkdown with UseLayout=false (same stack as internal MuPdfRag) ---");
try
{
List<int> pages = new List<int>();
pages.Add(0);
bool prev = UseLayout;
string markdown;
try
{
UseLayout = false;
markdown = ToMarkdown(
doc,
pages: pages,
writeImages: false,
embedImages: false,
imagePath: "",
imageFormat: "png",
filename: testFilePath,
forceText: true,
pageChunks: false,
pageSeparators: false,
dpi: 150,
pageWidth: 612,
pageHeight: null,
ignoreCode: false,
showProgress: false);
}
finally
{
UseLayout = prev;
}
string markdownFile = "TestMuPdfRag_Output.md";
File.WriteAllText(markdownFile, markdown, Encoding.UTF8);
Console.WriteLine($"Markdown output saved to: {markdownFile}");
Console.WriteLine($"Markdown length: {markdown.Length} characters");
if (markdown.Length > 0)
{
int previewLength = Math.Min(300, markdown.Length);
Console.WriteLine($"Preview (first {previewLength} chars):\n{markdown.Substring(0, previewLength)}...");
}
}
catch (Exception ex)
{
Console.WriteLine($"Error in basic ToMarkdown: {ex.Message}");
}
/*
// Test 2: ToMarkdown with IdentifyHeaders
Console.WriteLine("\n--- Test 2: ToMarkdown with IdentifyHeaders ---");
try
{
var identifyHeaders = new IdentifyHeaders(doc, pages: null, bodyLimit: 12.0f, maxLevels: 6);
string markdown = MuPdfRag.ToMarkdown(
doc,
pages: new List<int> { 0 }, // First page only
hdrInfo: identifyHeaders,
writeImages: false,
embedImages: false,
ignoreImages: false,
filename: testFilePath,
forceText: true,
showProgress: false
);
string markdownFile = "TestMuPdfRag_WithHeaders.md";
File.WriteAllText(markdownFile, markdown, Encoding.UTF8);
Console.WriteLine($"Markdown with headers saved to: {markdownFile}");
Console.WriteLine($"Markdown length: {markdown.Length} characters");
}
catch (Exception ex)
{
Console.WriteLine($"Error in ToMarkdown with IdentifyHeaders: {ex.Message}");
}
// Test 3: ToMarkdown with TocHeaders
Console.WriteLine("\n--- Test 3: ToMarkdown with TocHeaders ---");
try
{
var tocHeaders = new TocHeaders(doc);
string markdown = MuPdfRag.ToMarkdown(
doc,
pages: new List<int> { 0 }, // First page only
hdrInfo: tocHeaders,
writeImages: false,
embedImages: false,
ignoreImages: false,
filename: testFilePath,
forceText: true,
showProgress: false
);
string markdownFile = "TestMuPdfRag_WithToc.md";
File.WriteAllText(markdownFile, markdown, Encoding.UTF8);
Console.WriteLine($"Markdown with TOC headers saved to: {markdownFile}");
Console.WriteLine($"Markdown length: {markdown.Length} characters");
}
catch (Exception ex)
{
Console.WriteLine($"Error in ToMarkdown with TocHeaders: {ex.Message}");
}
// Test 4: ToMarkdown with page separators
Console.WriteLine("\n--- Test 4: ToMarkdown with page separators ---");
try
{
string markdown = MuPdfRag.ToMarkdown(
doc,
pages: null, // All pages
hdrInfo: null,
writeImages: false,
embedImages: false,
ignoreImages: false,
filename: testFilePath,
forceText: true,
pageSeparators: true, // Add page separators
showProgress: false
);
string markdownFile = "TestMuPdfRag_WithSeparators.md";
File.WriteAllText(markdownFile, markdown, Encoding.UTF8);
Console.WriteLine($"Markdown with page separators saved to: {markdownFile}");
Console.WriteLine($"Markdown length: {markdown.Length} characters");
}
catch (Exception ex)
{
Console.WriteLine($"Error in ToMarkdown with page separators: {ex.Message}");
}
// Test 5: ToMarkdown with progress bar
Console.WriteLine("\n--- Test 5: ToMarkdown with progress bar ---");
try
{
string markdown = MuPdfRag.ToMarkdown(
doc,
pages: null, // All pages
hdrInfo: null,
writeImages: false,
embedImages: false,
ignoreImages: false,
filename: testFilePath,
forceText: true,
showProgress: true, // Show progress bar
pageSeparators: false
);
string markdownFile = "TestMuPdfRag_WithProgress.md";
File.WriteAllText(markdownFile, markdown, Encoding.UTF8);
Console.WriteLine($"\nMarkdown with progress saved to: {markdownFile}");
Console.WriteLine($"Markdown length: {markdown.Length} characters");
}
catch (Exception ex)
{
Console.WriteLine($"Error in ToMarkdown with progress: {ex.Message}");
}
*/
doc.Close();
}
catch (Exception ex)
{
Console.WriteLine($"An unexpected error occurred during MuPdfRag test: {ex.Message}");
Console.WriteLine($"Stack trace: {ex.StackTrace}");
}
Console.WriteLine("\n=== TestMuPdfRagToMarkdown Completed =======================");
}
}
}