@heripo/document-processor 0.1.7 → 0.1.9

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
  *
@@ -254,8 +250,8 @@ declare class DocumentProcessor {
254
250
  * Extract the maximum page number from TOC markdown
255
251
  *
256
252
  * Parses page numbers from dot-leader patterns (e.g., "..... 175")
257
- * to detect compiled volume scenarios where TOC page numbers exceed
258
- * the sub-document's page count.
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.
259
255
  */
260
256
  private extractMaxPageNumber;
261
257
  /**
@@ -1000,6 +996,11 @@ declare class TocFinder {
1000
996
  * Find the TOC container (group or table) from a parent reference
1001
997
  */
1002
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;
1003
1004
  /**
1004
1005
  * Check if a group contains TOC-like structure
1005
1006
  */
@@ -1008,6 +1009,11 @@ declare class TocFinder {
1008
1009
  * Check if a table contains TOC-like structure
1009
1010
  */
1010
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;
1011
1017
  /**
1012
1018
  * Expand TOC area to consecutive pages (both backward and forward)
1013
1019
  */
@@ -1040,7 +1046,7 @@ declare class TocFinder {
1040
1046
  }
1041
1047
 
1042
1048
  /**
1043
- * Zod schema for recursive TocEntry structure
1049
+ * Zod schema for TocEntry structure with fixed 4-level depth
1044
1050
  */
1045
1051
  declare const TocEntrySchema: z.ZodType<TocEntry>;
1046
1052
  /**
@@ -1508,64 +1514,4 @@ declare class ChapterConverter {
1508
1514
  private buildChapterMap;
1509
1515
  }
1510
1516
 
1511
- /**
1512
- * HanjaQualitySampler
1513
- *
1514
- * Evaluates the quality of KCJ (Chinese/Japanese/Korean) character recognition
1515
- * in OCR-processed documents. Samples a subset of pages containing KCJ text and
1516
- * uses Vision LLM to compare the OCR output against the original page images.
1517
- *
1518
- * This is used to determine whether a document should be re-parsed using the
1519
- * VLM pipeline for better KCJ character accuracy.
1520
- */
1521
- declare class HanjaQualitySampler extends VisionLLMComponent {
1522
- constructor(logger: LoggerMethods, model: LanguageModel, outputPath: string, maxRetries?: number, fallbackModel?: LanguageModel, aggregator?: LLMTokenUsageAggregator, abortSignal?: AbortSignal);
1523
- /**
1524
- * Assess the quality of KCJ character recognition in the document
1525
- *
1526
- * @param doclingDoc - DoclingDocument to assess
1527
- * @returns Assessment result indicating whether VLM re-parse is needed
1528
- */
1529
- assess(doclingDoc: DoclingDocument): Promise<HanjaAssessment>;
1530
- /**
1531
- * Get the eligible page range after trimming front/back edges.
1532
- * Returns cutoff values where eligible pages satisfy: pageNo > frontCutoff && pageNo <= backCutoff
1533
- */
1534
- private getEligiblePageRange;
1535
- /**
1536
- * Get page numbers that are "image-only" (contain pictures but minimal text).
1537
- * These pages (e.g., photo plates/도판) are unsuitable for KCJ quality assessment.
1538
- */
1539
- private getImageOnlyPages;
1540
- /**
1541
- * Get all pages with substantial text content.
1542
- * Pages with fewer characters than MIN_TEXT_LENGTH (e.g., page numbers, headers only) are excluded.
1543
- */
1544
- private getTextPages;
1545
- /**
1546
- * Select sample pages with highest text density.
1547
- * Prefers pages in the eligible range (not edge-trimmed) and not image-only.
1548
- * Falls back to all text pages if filtering leaves too few candidates.
1549
- */
1550
- private selectSamplePages;
1551
- /**
1552
- * Evaluate sampled pages using Vision LLM
1553
- */
1554
- private evaluatePages;
1555
- /**
1556
- * Evaluate a single page by comparing OCR text against the page image
1557
- */
1558
- private evaluateSinglePage;
1559
- /**
1560
- * Aggregate individual page results into final assessment
1561
- */
1562
- private aggregateResults;
1563
- /**
1564
- * Get page number from a text item
1565
- */
1566
- private getPageNo;
1567
- protected buildSystemPrompt(): string;
1568
- protected buildUserPrompt(ocrText: string): string;
1569
- }
1570
-
1571
- 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
  *
@@ -254,8 +250,8 @@ declare class DocumentProcessor {
254
250
  * Extract the maximum page number from TOC markdown
255
251
  *
256
252
  * Parses page numbers from dot-leader patterns (e.g., "..... 175")
257
- * to detect compiled volume scenarios where TOC page numbers exceed
258
- * the sub-document's page count.
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.
259
255
  */
260
256
  private extractMaxPageNumber;
261
257
  /**
@@ -1000,6 +996,11 @@ declare class TocFinder {
1000
996
  * Find the TOC container (group or table) from a parent reference
1001
997
  */
1002
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;
1003
1004
  /**
1004
1005
  * Check if a group contains TOC-like structure
1005
1006
  */
@@ -1008,6 +1009,11 @@ declare class TocFinder {
1008
1009
  * Check if a table contains TOC-like structure
1009
1010
  */
1010
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;
1011
1017
  /**
1012
1018
  * Expand TOC area to consecutive pages (both backward and forward)
1013
1019
  */
@@ -1040,7 +1046,7 @@ declare class TocFinder {
1040
1046
  }
1041
1047
 
1042
1048
  /**
1043
- * Zod schema for recursive TocEntry structure
1049
+ * Zod schema for TocEntry structure with fixed 4-level depth
1044
1050
  */
1045
1051
  declare const TocEntrySchema: z.ZodType<TocEntry>;
1046
1052
  /**
@@ -1508,64 +1514,4 @@ declare class ChapterConverter {
1508
1514
  private buildChapterMap;
1509
1515
  }
1510
1516
 
1511
- /**
1512
- * HanjaQualitySampler
1513
- *
1514
- * Evaluates the quality of KCJ (Chinese/Japanese/Korean) character recognition
1515
- * in OCR-processed documents. Samples a subset of pages containing KCJ text and
1516
- * uses Vision LLM to compare the OCR output against the original page images.
1517
- *
1518
- * This is used to determine whether a document should be re-parsed using the
1519
- * VLM pipeline for better KCJ character accuracy.
1520
- */
1521
- declare class HanjaQualitySampler extends VisionLLMComponent {
1522
- constructor(logger: LoggerMethods, model: LanguageModel, outputPath: string, maxRetries?: number, fallbackModel?: LanguageModel, aggregator?: LLMTokenUsageAggregator, abortSignal?: AbortSignal);
1523
- /**
1524
- * Assess the quality of KCJ character recognition in the document
1525
- *
1526
- * @param doclingDoc - DoclingDocument to assess
1527
- * @returns Assessment result indicating whether VLM re-parse is needed
1528
- */
1529
- assess(doclingDoc: DoclingDocument): Promise<HanjaAssessment>;
1530
- /**
1531
- * Get the eligible page range after trimming front/back edges.
1532
- * Returns cutoff values where eligible pages satisfy: pageNo > frontCutoff && pageNo <= backCutoff
1533
- */
1534
- private getEligiblePageRange;
1535
- /**
1536
- * Get page numbers that are "image-only" (contain pictures but minimal text).
1537
- * These pages (e.g., photo plates/도판) are unsuitable for KCJ quality assessment.
1538
- */
1539
- private getImageOnlyPages;
1540
- /**
1541
- * Get all pages with substantial text content.
1542
- * Pages with fewer characters than MIN_TEXT_LENGTH (e.g., page numbers, headers only) are excluded.
1543
- */
1544
- private getTextPages;
1545
- /**
1546
- * Select sample pages with highest text density.
1547
- * Prefers pages in the eligible range (not edge-trimmed) and not image-only.
1548
- * Falls back to all text pages if filtering leaves too few candidates.
1549
- */
1550
- private selectSamplePages;
1551
- /**
1552
- * Evaluate sampled pages using Vision LLM
1553
- */
1554
- private evaluatePages;
1555
- /**
1556
- * Evaluate a single page by comparing OCR text against the page image
1557
- */
1558
- private evaluateSinglePage;
1559
- /**
1560
- * Aggregate individual page results into final assessment
1561
- */
1562
- private aggregateResults;
1563
- /**
1564
- * Get page number from a text item
1565
- */
1566
- private getPageNo;
1567
- protected buildSystemPrompt(): string;
1568
- protected buildUserPrompt(ocrText: string): string;
1569
- }
1570
-
1571
- 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 };