@heripo/document-processor 0.1.6 → 0.1.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { LoggerMethods } from '@heripo/logger';
2
- import { DoclingDocument, HanjaAssessment, DocumentProcessResult, Caption, PageRange, DoclingTextItem, DoclingPictureItem, DoclingTableItem, DoclingGroupItem, ProcessedImage, ProcessedTable, ProcessedFootnote, Chapter } from '@heripo/model';
2
+ import { TokenUsageReport, DoclingDocument, DocumentProcessResult, Caption, PageRange, DoclingTextItem, DoclingPictureItem, DoclingTableItem, DoclingGroupItem, ProcessedImage, ProcessedTable, ProcessedFootnote, Chapter } from '@heripo/model';
3
3
  import { LanguageModel } from 'ai';
4
4
  import { LLMTokenUsageAggregator, ExtendedTokenUsage } from '@heripo/shared';
5
5
  import { z } from 'zod';
@@ -14,7 +14,7 @@ interface DocumentProcessorOptions {
14
14
  logger: LoggerMethods;
15
15
  /**
16
16
  * Fallback model - used as fallback when component-specific models are not provided or fail.
17
- * This is the only required model. Should be set to a frontier model (e.g., Claude Opus 4.5, GPT-5.2)
17
+ * This is the only required model. Should be set to a frontier model (e.g., Claude Opus 4.6, GPT-5.2)
18
18
  * to ensure reliable fallback performance across all components.
19
19
  */
20
20
  fallbackModel: LanguageModel;
@@ -43,11 +43,6 @@ interface DocumentProcessorOptions {
43
43
  * Falls back to 'fallbackModel' if not provided.
44
44
  */
45
45
  captionParserModel?: LanguageModel;
46
- /**
47
- * Model for HanjaQualitySampler - evaluates KCJ character quality in OCR output.
48
- * Requires vision capabilities. Falls back to 'fallbackModel' if not provided.
49
- */
50
- hanjaQualitySamplerModel?: LanguageModel;
51
46
  /**
52
47
  * Batch size for TextCleaner text normalization (synchronous processing)
53
48
  */
@@ -74,6 +69,12 @@ interface DocumentProcessorOptions {
74
69
  * When aborted, processing stops at the next checkpoint between stages.
75
70
  */
76
71
  abortSignal?: AbortSignal;
72
+ /**
73
+ * Callback fired after each major processing phase completes.
74
+ * Receives the current cumulative token usage report.
75
+ * Useful for real-time token usage monitoring during processing.
76
+ */
77
+ onTokenUsage?: (report: TokenUsageReport) => void;
77
78
  }
78
79
  /**
79
80
  * DocumentProcessor
@@ -137,13 +138,13 @@ declare class DocumentProcessor {
137
138
  private readonly validatorModel;
138
139
  private readonly visionTocExtractorModel;
139
140
  private readonly captionParserModel;
140
- private readonly hanjaQualitySamplerModel;
141
141
  private readonly textCleanerBatchSize;
142
142
  private readonly captionParserBatchSize;
143
143
  private readonly captionValidatorBatchSize;
144
144
  private readonly maxRetries;
145
145
  private readonly enableFallbackRetry;
146
146
  private readonly abortSignal?;
147
+ private readonly onTokenUsage?;
147
148
  private idGenerator;
148
149
  private refResolver?;
149
150
  private pageRangeParser?;
@@ -158,23 +159,18 @@ declare class DocumentProcessor {
158
159
  private readonly usageAggregator;
159
160
  constructor(options: DocumentProcessorOptions);
160
161
  /**
161
- * Check if abort has been requested and throw error if so
162
+ * Emit current token usage report via callback
162
163
  *
163
- * @throws {Error} with name 'AbortError' if aborted
164
+ * Calls the onTokenUsage callback with the current cumulative report
165
+ * from the usage aggregator. Safe to call even if no callback is set.
164
166
  */
165
- private checkAborted;
167
+ private emitTokenUsage;
166
168
  /**
167
- * Assess the quality of KCJ (Hanja) character recognition in the OCR output.
168
- *
169
- * Samples pages containing KCJ characters and uses Vision LLM to compare
170
- * the OCR text against the original page images. Returns an assessment
171
- * indicating whether the document should be re-parsed with VLM pipeline.
169
+ * Check if abort has been requested and throw error if so
172
170
  *
173
- * @param doclingDoc - Original document extracted from Docling SDK
174
- * @param outputPath - Path containing pages subdirectory (pages/page_0.png, etc.)
175
- * @returns Assessment result with severity and recommendation
171
+ * @throws {Error} with name 'AbortError' if aborted
176
172
  */
177
- assessHanjaQuality(doclingDoc: DoclingDocument, outputPath: string): Promise<HanjaAssessment>;
173
+ private checkAborted;
178
174
  /**
179
175
  * Converts DoclingDocument to ProcessedDocument with token usage tracking.
180
176
  *
@@ -250,6 +246,14 @@ declare class DocumentProcessor {
250
246
  * 5. TocExtractor - LLM-based structured extraction
251
247
  */
252
248
  private extractTableOfContents;
249
+ /**
250
+ * Extract the maximum page number from TOC markdown
251
+ *
252
+ * Parses page numbers from dot-leader patterns (e.g., "..... 175")
253
+ * and table cell patterns (e.g., "| title | 175 |") to detect compiled
254
+ * volume scenarios where TOC page numbers exceed the sub-document's page count.
255
+ */
256
+ private extractMaxPageNumber;
253
257
  /**
254
258
  * Process resource captions (for images and tables)
255
259
  *
@@ -992,6 +996,11 @@ declare class TocFinder {
992
996
  * Find the TOC container (group or table) from a parent reference
993
997
  */
994
998
  private findTocContainer;
999
+ /**
1000
+ * Find adjacent TOC item among body siblings following the keyword text.
1001
+ * Used when findTocContainer returns null (e.g., parent is #/body).
1002
+ */
1003
+ private findSiblingTocItem;
995
1004
  /**
996
1005
  * Check if a group contains TOC-like structure
997
1006
  */
@@ -1000,6 +1009,11 @@ declare class TocFinder {
1000
1009
  * Check if a table contains TOC-like structure
1001
1010
  */
1002
1011
  private isTableTocLike;
1012
+ /**
1013
+ * Check if a table is a resource index (drawing/photo/figure list)
1014
+ * rather than a main TOC table
1015
+ */
1016
+ private isResourceIndexTable;
1003
1017
  /**
1004
1018
  * Expand TOC area to consecutive pages (both backward and forward)
1005
1019
  */
@@ -1032,7 +1046,7 @@ declare class TocFinder {
1032
1046
  }
1033
1047
 
1034
1048
  /**
1035
- * Zod schema for recursive TocEntry structure
1049
+ * Zod schema for TocEntry structure with fixed 4-level depth
1036
1050
  */
1037
1051
  declare const TocEntrySchema: z.ZodType<TocEntry>;
1038
1052
  /**
@@ -1500,64 +1514,4 @@ declare class ChapterConverter {
1500
1514
  private buildChapterMap;
1501
1515
  }
1502
1516
 
1503
- /**
1504
- * HanjaQualitySampler
1505
- *
1506
- * Evaluates the quality of KCJ (Chinese/Japanese/Korean) character recognition
1507
- * in OCR-processed documents. Samples a subset of pages containing KCJ text and
1508
- * uses Vision LLM to compare the OCR output against the original page images.
1509
- *
1510
- * This is used to determine whether a document should be re-parsed using the
1511
- * VLM pipeline for better KCJ character accuracy.
1512
- */
1513
- declare class HanjaQualitySampler extends VisionLLMComponent {
1514
- constructor(logger: LoggerMethods, model: LanguageModel, outputPath: string, maxRetries?: number, fallbackModel?: LanguageModel, aggregator?: LLMTokenUsageAggregator, abortSignal?: AbortSignal);
1515
- /**
1516
- * Assess the quality of KCJ character recognition in the document
1517
- *
1518
- * @param doclingDoc - DoclingDocument to assess
1519
- * @returns Assessment result indicating whether VLM re-parse is needed
1520
- */
1521
- assess(doclingDoc: DoclingDocument): Promise<HanjaAssessment>;
1522
- /**
1523
- * Get the eligible page range after trimming front/back edges.
1524
- * Returns cutoff values where eligible pages satisfy: pageNo > frontCutoff && pageNo <= backCutoff
1525
- */
1526
- private getEligiblePageRange;
1527
- /**
1528
- * Get page numbers that are "image-only" (contain pictures but minimal text).
1529
- * These pages (e.g., photo plates/도판) are unsuitable for KCJ quality assessment.
1530
- */
1531
- private getImageOnlyPages;
1532
- /**
1533
- * Get all pages with substantial text content.
1534
- * Pages with fewer characters than MIN_TEXT_LENGTH (e.g., page numbers, headers only) are excluded.
1535
- */
1536
- private getTextPages;
1537
- /**
1538
- * Select sample pages with highest text density.
1539
- * Prefers pages in the eligible range (not edge-trimmed) and not image-only.
1540
- * Falls back to all text pages if filtering leaves too few candidates.
1541
- */
1542
- private selectSamplePages;
1543
- /**
1544
- * Evaluate sampled pages using Vision LLM
1545
- */
1546
- private evaluatePages;
1547
- /**
1548
- * Evaluate a single page by comparing OCR text against the page image
1549
- */
1550
- private evaluateSinglePage;
1551
- /**
1552
- * Aggregate individual page results into final assessment
1553
- */
1554
- private aggregateResults;
1555
- /**
1556
- * Get page number from a text item
1557
- */
1558
- private getPageNo;
1559
- protected buildSystemPrompt(): string;
1560
- protected buildUserPrompt(ocrText: string): string;
1561
- }
1562
-
1563
- export { BaseLLMComponent, type BaseLLMComponentOptions, BaseValidator, type BaseValidatorOptions, CONTINUATION_MARKERS, CaptionParseError, CaptionParser, type CaptionParserOptions, CaptionValidationError, CaptionValidator, type CaptionValidatorOptions, ChapterConverter, DocumentProcessor, type DocumentProcessorOptions, HanjaQualitySampler, type ImageContent, PAGE_NUMBER_PATTERN, PagePattern, PageRangeParseError, PageRangeParser, type PageSizeGroup, TOC_KEYWORDS, TextLLMComponent, type TocAreaResult, type TocContentValidationResult, TocContentValidationSchema, TocContentValidator, type TocContentValidatorOptions, type TocEntry, TocEntrySchema, TocExtractError, TocExtractor, type TocExtractorOptions, TocFinder, type TocFinderOptions, TocNotFoundError, TocParseError, type TocResponse, TocResponseSchema, VisionLLMComponent, type VisionLLMComponentOptions, type VisionTocExtractionResult, VisionTocExtractionSchema, VisionTocExtractor, type VisionTocExtractorOptions };
1517
+ export { BaseLLMComponent, type BaseLLMComponentOptions, BaseValidator, type BaseValidatorOptions, CONTINUATION_MARKERS, CaptionParseError, CaptionParser, type CaptionParserOptions, CaptionValidationError, CaptionValidator, type CaptionValidatorOptions, ChapterConverter, DocumentProcessor, type DocumentProcessorOptions, type ImageContent, PAGE_NUMBER_PATTERN, PagePattern, PageRangeParseError, PageRangeParser, type PageSizeGroup, TOC_KEYWORDS, TextLLMComponent, type TocAreaResult, type TocContentValidationResult, TocContentValidationSchema, TocContentValidator, type TocContentValidatorOptions, type TocEntry, TocEntrySchema, TocExtractError, TocExtractor, type TocExtractorOptions, TocFinder, type TocFinderOptions, TocNotFoundError, TocParseError, type TocResponse, TocResponseSchema, VisionLLMComponent, type VisionLLMComponentOptions, type VisionTocExtractionResult, VisionTocExtractionSchema, VisionTocExtractor, type VisionTocExtractorOptions };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { LoggerMethods } from '@heripo/logger';
2
- import { DoclingDocument, HanjaAssessment, DocumentProcessResult, Caption, PageRange, DoclingTextItem, DoclingPictureItem, DoclingTableItem, DoclingGroupItem, ProcessedImage, ProcessedTable, ProcessedFootnote, Chapter } from '@heripo/model';
2
+ import { TokenUsageReport, DoclingDocument, DocumentProcessResult, Caption, PageRange, DoclingTextItem, DoclingPictureItem, DoclingTableItem, DoclingGroupItem, ProcessedImage, ProcessedTable, ProcessedFootnote, Chapter } from '@heripo/model';
3
3
  import { LanguageModel } from 'ai';
4
4
  import { LLMTokenUsageAggregator, ExtendedTokenUsage } from '@heripo/shared';
5
5
  import { z } from 'zod';
@@ -14,7 +14,7 @@ interface DocumentProcessorOptions {
14
14
  logger: LoggerMethods;
15
15
  /**
16
16
  * Fallback model - used as fallback when component-specific models are not provided or fail.
17
- * This is the only required model. Should be set to a frontier model (e.g., Claude Opus 4.5, GPT-5.2)
17
+ * This is the only required model. Should be set to a frontier model (e.g., Claude Opus 4.6, GPT-5.2)
18
18
  * to ensure reliable fallback performance across all components.
19
19
  */
20
20
  fallbackModel: LanguageModel;
@@ -43,11 +43,6 @@ interface DocumentProcessorOptions {
43
43
  * Falls back to 'fallbackModel' if not provided.
44
44
  */
45
45
  captionParserModel?: LanguageModel;
46
- /**
47
- * Model for HanjaQualitySampler - evaluates KCJ character quality in OCR output.
48
- * Requires vision capabilities. Falls back to 'fallbackModel' if not provided.
49
- */
50
- hanjaQualitySamplerModel?: LanguageModel;
51
46
  /**
52
47
  * Batch size for TextCleaner text normalization (synchronous processing)
53
48
  */
@@ -74,6 +69,12 @@ interface DocumentProcessorOptions {
74
69
  * When aborted, processing stops at the next checkpoint between stages.
75
70
  */
76
71
  abortSignal?: AbortSignal;
72
+ /**
73
+ * Callback fired after each major processing phase completes.
74
+ * Receives the current cumulative token usage report.
75
+ * Useful for real-time token usage monitoring during processing.
76
+ */
77
+ onTokenUsage?: (report: TokenUsageReport) => void;
77
78
  }
78
79
  /**
79
80
  * DocumentProcessor
@@ -137,13 +138,13 @@ declare class DocumentProcessor {
137
138
  private readonly validatorModel;
138
139
  private readonly visionTocExtractorModel;
139
140
  private readonly captionParserModel;
140
- private readonly hanjaQualitySamplerModel;
141
141
  private readonly textCleanerBatchSize;
142
142
  private readonly captionParserBatchSize;
143
143
  private readonly captionValidatorBatchSize;
144
144
  private readonly maxRetries;
145
145
  private readonly enableFallbackRetry;
146
146
  private readonly abortSignal?;
147
+ private readonly onTokenUsage?;
147
148
  private idGenerator;
148
149
  private refResolver?;
149
150
  private pageRangeParser?;
@@ -158,23 +159,18 @@ declare class DocumentProcessor {
158
159
  private readonly usageAggregator;
159
160
  constructor(options: DocumentProcessorOptions);
160
161
  /**
161
- * Check if abort has been requested and throw error if so
162
+ * Emit current token usage report via callback
162
163
  *
163
- * @throws {Error} with name 'AbortError' if aborted
164
+ * Calls the onTokenUsage callback with the current cumulative report
165
+ * from the usage aggregator. Safe to call even if no callback is set.
164
166
  */
165
- private checkAborted;
167
+ private emitTokenUsage;
166
168
  /**
167
- * Assess the quality of KCJ (Hanja) character recognition in the OCR output.
168
- *
169
- * Samples pages containing KCJ characters and uses Vision LLM to compare
170
- * the OCR text against the original page images. Returns an assessment
171
- * indicating whether the document should be re-parsed with VLM pipeline.
169
+ * Check if abort has been requested and throw error if so
172
170
  *
173
- * @param doclingDoc - Original document extracted from Docling SDK
174
- * @param outputPath - Path containing pages subdirectory (pages/page_0.png, etc.)
175
- * @returns Assessment result with severity and recommendation
171
+ * @throws {Error} with name 'AbortError' if aborted
176
172
  */
177
- assessHanjaQuality(doclingDoc: DoclingDocument, outputPath: string): Promise<HanjaAssessment>;
173
+ private checkAborted;
178
174
  /**
179
175
  * Converts DoclingDocument to ProcessedDocument with token usage tracking.
180
176
  *
@@ -250,6 +246,14 @@ declare class DocumentProcessor {
250
246
  * 5. TocExtractor - LLM-based structured extraction
251
247
  */
252
248
  private extractTableOfContents;
249
+ /**
250
+ * Extract the maximum page number from TOC markdown
251
+ *
252
+ * Parses page numbers from dot-leader patterns (e.g., "..... 175")
253
+ * and table cell patterns (e.g., "| title | 175 |") to detect compiled
254
+ * volume scenarios where TOC page numbers exceed the sub-document's page count.
255
+ */
256
+ private extractMaxPageNumber;
253
257
  /**
254
258
  * Process resource captions (for images and tables)
255
259
  *
@@ -992,6 +996,11 @@ declare class TocFinder {
992
996
  * Find the TOC container (group or table) from a parent reference
993
997
  */
994
998
  private findTocContainer;
999
+ /**
1000
+ * Find adjacent TOC item among body siblings following the keyword text.
1001
+ * Used when findTocContainer returns null (e.g., parent is #/body).
1002
+ */
1003
+ private findSiblingTocItem;
995
1004
  /**
996
1005
  * Check if a group contains TOC-like structure
997
1006
  */
@@ -1000,6 +1009,11 @@ declare class TocFinder {
1000
1009
  * Check if a table contains TOC-like structure
1001
1010
  */
1002
1011
  private isTableTocLike;
1012
+ /**
1013
+ * Check if a table is a resource index (drawing/photo/figure list)
1014
+ * rather than a main TOC table
1015
+ */
1016
+ private isResourceIndexTable;
1003
1017
  /**
1004
1018
  * Expand TOC area to consecutive pages (both backward and forward)
1005
1019
  */
@@ -1032,7 +1046,7 @@ declare class TocFinder {
1032
1046
  }
1033
1047
 
1034
1048
  /**
1035
- * Zod schema for recursive TocEntry structure
1049
+ * Zod schema for TocEntry structure with fixed 4-level depth
1036
1050
  */
1037
1051
  declare const TocEntrySchema: z.ZodType<TocEntry>;
1038
1052
  /**
@@ -1500,64 +1514,4 @@ declare class ChapterConverter {
1500
1514
  private buildChapterMap;
1501
1515
  }
1502
1516
 
1503
- /**
1504
- * HanjaQualitySampler
1505
- *
1506
- * Evaluates the quality of KCJ (Chinese/Japanese/Korean) character recognition
1507
- * in OCR-processed documents. Samples a subset of pages containing KCJ text and
1508
- * uses Vision LLM to compare the OCR output against the original page images.
1509
- *
1510
- * This is used to determine whether a document should be re-parsed using the
1511
- * VLM pipeline for better KCJ character accuracy.
1512
- */
1513
- declare class HanjaQualitySampler extends VisionLLMComponent {
1514
- constructor(logger: LoggerMethods, model: LanguageModel, outputPath: string, maxRetries?: number, fallbackModel?: LanguageModel, aggregator?: LLMTokenUsageAggregator, abortSignal?: AbortSignal);
1515
- /**
1516
- * Assess the quality of KCJ character recognition in the document
1517
- *
1518
- * @param doclingDoc - DoclingDocument to assess
1519
- * @returns Assessment result indicating whether VLM re-parse is needed
1520
- */
1521
- assess(doclingDoc: DoclingDocument): Promise<HanjaAssessment>;
1522
- /**
1523
- * Get the eligible page range after trimming front/back edges.
1524
- * Returns cutoff values where eligible pages satisfy: pageNo > frontCutoff && pageNo <= backCutoff
1525
- */
1526
- private getEligiblePageRange;
1527
- /**
1528
- * Get page numbers that are "image-only" (contain pictures but minimal text).
1529
- * These pages (e.g., photo plates/도판) are unsuitable for KCJ quality assessment.
1530
- */
1531
- private getImageOnlyPages;
1532
- /**
1533
- * Get all pages with substantial text content.
1534
- * Pages with fewer characters than MIN_TEXT_LENGTH (e.g., page numbers, headers only) are excluded.
1535
- */
1536
- private getTextPages;
1537
- /**
1538
- * Select sample pages with highest text density.
1539
- * Prefers pages in the eligible range (not edge-trimmed) and not image-only.
1540
- * Falls back to all text pages if filtering leaves too few candidates.
1541
- */
1542
- private selectSamplePages;
1543
- /**
1544
- * Evaluate sampled pages using Vision LLM
1545
- */
1546
- private evaluatePages;
1547
- /**
1548
- * Evaluate a single page by comparing OCR text against the page image
1549
- */
1550
- private evaluateSinglePage;
1551
- /**
1552
- * Aggregate individual page results into final assessment
1553
- */
1554
- private aggregateResults;
1555
- /**
1556
- * Get page number from a text item
1557
- */
1558
- private getPageNo;
1559
- protected buildSystemPrompt(): string;
1560
- protected buildUserPrompt(ocrText: string): string;
1561
- }
1562
-
1563
- export { BaseLLMComponent, type BaseLLMComponentOptions, BaseValidator, type BaseValidatorOptions, CONTINUATION_MARKERS, CaptionParseError, CaptionParser, type CaptionParserOptions, CaptionValidationError, CaptionValidator, type CaptionValidatorOptions, ChapterConverter, DocumentProcessor, type DocumentProcessorOptions, HanjaQualitySampler, type ImageContent, PAGE_NUMBER_PATTERN, PagePattern, PageRangeParseError, PageRangeParser, type PageSizeGroup, TOC_KEYWORDS, TextLLMComponent, type TocAreaResult, type TocContentValidationResult, TocContentValidationSchema, TocContentValidator, type TocContentValidatorOptions, type TocEntry, TocEntrySchema, TocExtractError, TocExtractor, type TocExtractorOptions, TocFinder, type TocFinderOptions, TocNotFoundError, TocParseError, type TocResponse, TocResponseSchema, VisionLLMComponent, type VisionLLMComponentOptions, type VisionTocExtractionResult, VisionTocExtractionSchema, VisionTocExtractor, type VisionTocExtractorOptions };
1517
+ export { BaseLLMComponent, type BaseLLMComponentOptions, BaseValidator, type BaseValidatorOptions, CONTINUATION_MARKERS, CaptionParseError, CaptionParser, type CaptionParserOptions, CaptionValidationError, CaptionValidator, type CaptionValidatorOptions, ChapterConverter, DocumentProcessor, type DocumentProcessorOptions, type ImageContent, PAGE_NUMBER_PATTERN, PagePattern, PageRangeParseError, PageRangeParser, type PageSizeGroup, TOC_KEYWORDS, TextLLMComponent, type TocAreaResult, type TocContentValidationResult, TocContentValidationSchema, TocContentValidator, type TocContentValidatorOptions, type TocEntry, TocEntrySchema, TocExtractError, TocExtractor, type TocExtractorOptions, TocFinder, type TocFinderOptions, TocNotFoundError, TocParseError, type TocResponse, TocResponseSchema, VisionLLMComponent, type VisionLLMComponentOptions, type VisionTocExtractionResult, VisionTocExtractionSchema, VisionTocExtractor, type VisionTocExtractorOptions };