@@ -62,6 +62,7 @@ export const TextSelectorSchema = z.object({
6262 role : z . string ( ) . optional ( ) , // PDF 1.4 structure role: P, H1, H2, Figure, Table, Span, etc.
6363 page : z . number ( ) . optional ( ) , // Page number (1-indexed), required for role: "Page"
6464 edge : EdgeSchema . optional ( ) , // Which edge to use for comparison (overrides relation default)
65+ granularity : z . string ( ) . optional ( ) , // Aggregate bbox to ancestor with this role (e.g., "Div", "P")
6566} ) ;
6667export type TextSelector = z . infer < typeof TextSelectorSchema > ;
6768
@@ -394,29 +395,38 @@ function extractMarkedTextItems(
394395}
395396
396397/**
397- * Recursively build MCID -> StructNode map from structure tree.
398- * Returns the struct node that directly contains the MCID content.
398+ * Recursively build MCID -> StructNode map and parent map from structure tree.
399+ * Returns the struct node that directly contains the MCID content, plus a map
400+ * from each struct node to its parent for tree traversal.
399401 */
400402function buildMcidStructMap (
401403 tree : StructTreeNode | null ,
402- map : Map < string , StructTreeNode > = new Map ( ) ,
404+ mcidMap : Map < string , StructTreeNode > = new Map ( ) ,
405+ parentMap : Map < StructTreeNode , StructTreeNode > = new Map ( ) ,
403406 parentNode : StructTreeNode | null = null ,
404- ) : Map < string , StructTreeNode > {
405- if ( ! tree ) return map ;
407+ ) : { mcidMap : Map < string , StructTreeNode > ; parentMap : Map < StructTreeNode , StructTreeNode > } {
408+ if ( ! tree ) return { mcidMap , parentMap } ;
406409
407410 for ( const child of tree . children ?? [ ] ) {
408411 if ( isStructTreeContent ( child ) ) {
409412 if ( child . type === "content" && child . id ) {
410413 // Map MCID to the parent struct node (the semantic element)
411- map . set ( child . id , parentNode ?? tree ) ;
414+ mcidMap . set ( child . id , parentNode ?? tree ) ;
412415 }
413416 } else {
417+ // Record parent for tree traversal
418+ if ( parentNode ) {
419+ parentMap . set ( child , parentNode ) ;
420+ } else {
421+ // Root-level children have tree as parent
422+ parentMap . set ( child , tree ) ;
423+ }
414424 // Recurse into child struct nodes
415- buildMcidStructMap ( child , map , child ) ;
425+ buildMcidStructMap ( child , mcidMap , parentMap , child ) ;
416426 }
417427 }
418428
419- return map ;
429+ return { mcidMap , parentMap } ;
420430}
421431
422432/**
@@ -438,6 +448,46 @@ function collectDirectMcids(node: StructTreeNode): string[] {
438448 return mcids ;
439449}
440450
451+ /**
452+ * Recursively collect ALL MCIDs under a structure node and its descendants.
453+ * Used for granularity aggregation to compute bbox of an entire subtree.
454+ */
455+ function collectAllMcids ( node : StructTreeNode ) : string [ ] {
456+ const mcids : string [ ] = [ ] ;
457+
458+ for ( const child of node . children ?? [ ] ) {
459+ if ( isStructTreeContent ( child ) ) {
460+ if ( child . type === "content" && child . id ) {
461+ mcids . push ( child . id ) ;
462+ }
463+ } else {
464+ // Recurse into child struct nodes
465+ mcids . push ( ...collectAllMcids ( child ) ) ;
466+ }
467+ }
468+
469+ return mcids ;
470+ }
471+
472+ /**
473+ * Walk up the structure tree to find the nearest ancestor with a matching role.
474+ * Returns null if no ancestor with the target role is found.
475+ */
476+ function findAncestorWithRole (
477+ node : StructTreeNode ,
478+ targetRole : string ,
479+ parentMap : Map < StructTreeNode , StructTreeNode > ,
480+ ) : StructTreeNode | null {
481+ let current : StructTreeNode | undefined = node ;
482+ while ( current ) {
483+ if ( current . role === targetRole ) {
484+ return current ;
485+ }
486+ current = parentMap . get ( current ) ;
487+ }
488+ return null ;
489+ }
490+
441491/**
442492 * Check if a string is whitespace-only (including empty).
443493 * Used to filter out horizontal skip spaces in PDF content.
@@ -582,13 +632,21 @@ export const ensurePdfTextPositions = (
582632 const isPageRole = ( sel : TextSelector ) : boolean => sel . role === "Page" ;
583633
584634 // Helper: get unique key for a selector (for resolvedSelectors map)
635+ // Includes granularity since different granularity settings need different bbox computation
585636 const selectorKey = ( sel : TextSelector ) : string => {
586637 if ( isPageRole ( sel ) ) {
587638 return `Page:${ sel . page } ` ;
588639 }
589- return sel . text ?? "" ;
640+ const base = sel . text ?? "" ;
641+ if ( sel . granularity ) {
642+ return `${ base } @${ sel . granularity } ` ;
643+ }
644+ return base ;
590645 } ;
591646
647+ // Track unique selectors by their full key (including granularity)
648+ const uniqueSelectors = new Map < string , TextSelector > ( ) ;
649+
592650 const addSelector = ( sel : TextSelector ) => {
593651 if ( isPageRole ( sel ) ) {
594652 if ( sel . page === undefined ) {
@@ -605,6 +663,8 @@ export const ensurePdfTextPositions = (
605663 const existing = textToSelectors . get ( sel . text ) ?? [ ] ;
606664 existing . push ( sel ) ;
607665 textToSelectors . set ( sel . text , existing ) ;
666+ // Also track by full key for resolution
667+ uniqueSelectors . set ( selectorKey ( sel ) , sel ) ;
608668 }
609669 } ;
610670
@@ -633,6 +693,7 @@ export const ensurePdfTextPositions = (
633693 const allTextItems : MarkedTextItem [ ] = [ ] ;
634694 const mcidToTextItems = new Map < string , MarkedTextItem [ ] > ( ) ;
635695 const mcidToStructNode = new Map < string , StructTreeNode > ( ) ;
696+ const structNodeToParent = new Map < StructTreeNode , StructTreeNode > ( ) ;
636697 const pageDimensions = new Map < number , { width : number ; height : number } > ( ) ;
637698
638699 for ( let pageNum = 1 ; pageNum <= doc . numPages ; pageNum ++ ) {
@@ -663,10 +724,16 @@ export const ensurePdfTextPositions = (
663724 }
664725 }
665726
666- // Get structure tree and build MCID -> struct node map
727+ // Get structure tree and build MCID -> struct node map + parent map
667728 const structTree = await page . getStructTree ( ) ;
668729 if ( structTree ) {
669- buildMcidStructMap ( structTree , mcidToStructNode ) ;
730+ const { mcidMap, parentMap } = buildMcidStructMap ( structTree ) ;
731+ for ( const [ k , v ] of mcidMap ) {
732+ mcidToStructNode . set ( k , v ) ;
733+ }
734+ for ( const [ k , v ] of parentMap ) {
735+ structNodeToParent . set ( k , v ) ;
736+ }
670737 }
671738 }
672739
@@ -716,8 +783,9 @@ export const ensurePdfTextPositions = (
716783 } ) ;
717784 }
718785
719- // Then, resolve text-based selectors
720- for ( const searchText of searchTexts ) {
786+ // Then, resolve text-based selectors (iterate by unique selector key to handle granularity)
787+ for ( const [ key , selector ] of uniqueSelectors ) {
788+ const searchText = selector . text ! ;
721789 const textItem = foundTexts . get ( searchText ) ;
722790 if ( ! textItem ) {
723791 // Don't report "not found" if we already reported "ambiguous"
@@ -747,28 +815,52 @@ export const ensurePdfTextPositions = (
747815 } else {
748816 structNode = mcidToStructNode . get ( textItem . mcid ) ?? null ;
749817
750- // Same-MCID approach: compute bbox from all text items sharing this MCID
751- const mcidItems = mcidToTextItems . get ( textItem . mcid ) ;
752- if ( mcidItems && mcidItems . length > 0 ) {
753- const mcidBBox = unionBBox ( mcidItems ) ;
754- if ( mcidBBox ) {
755- bbox = mcidBBox ;
818+ // Check for granularity: aggregate bbox to ancestor with target role
819+ if ( selector . granularity && structNode ) {
820+ const ancestor = findAncestorWithRole ( structNode , selector . granularity , structNodeToParent ) ;
821+ if ( ancestor ) {
822+ // Collect ALL MCIDs recursively under that ancestor
823+ const allMcids = collectAllMcids ( ancestor ) ;
824+ const allItems = allMcids . flatMap ( ( id ) => mcidToTextItems . get ( id ) ?? [ ] ) ;
825+ const ancestorBBox = unionBBox ( allItems ) ;
826+ if ( ancestorBBox ) {
827+ bbox = ancestorBBox ;
828+ } else {
829+ errors . push (
830+ `Could not compute bbox for "${ searchText } " with granularity "${ selector . granularity } " - no content items found` ,
831+ ) ;
832+ continue ;
833+ }
756834 } else {
757835 errors . push (
758- `Could not compute bbox for "${ searchText } " - all text items in MCID are whitespace-only ` ,
836+ `No ancestor with role "${ selector . granularity } " found for " ${ searchText } " ` ,
759837 ) ;
760838 continue ;
761839 }
762840 } else {
763- errors . push (
764- `No text items found for MCID ${ textItem . mcid } containing "${ searchText } "` ,
765- ) ;
766- continue ;
841+ // Same-MCID approach: compute bbox from all text items sharing this MCID
842+ const mcidItems = mcidToTextItems . get ( textItem . mcid ) ;
843+ if ( mcidItems && mcidItems . length > 0 ) {
844+ const mcidBBox = unionBBox ( mcidItems ) ;
845+ if ( mcidBBox ) {
846+ bbox = mcidBBox ;
847+ } else {
848+ errors . push (
849+ `Could not compute bbox for "${ searchText } " - all text items in MCID are whitespace-only` ,
850+ ) ;
851+ continue ;
852+ }
853+ } else {
854+ errors . push (
855+ `No text items found for MCID ${ textItem . mcid } containing "${ searchText } "` ,
856+ ) ;
857+ continue ;
858+ }
767859 }
768860 }
769861
770- resolvedSelectors . set ( searchText , {
771- selector : { text : searchText } ,
862+ resolvedSelectors . set ( key , {
863+ selector,
772864 textItem,
773865 structNode,
774866 bbox,
0 commit comments