diff --git a/layoutparser-service/layoutparser-service-processor/src/main/java/com/knecon/fforesight/service/layoutparser/processor/utils/TextPositionSequenceComparator.java b/layoutparser-service/layoutparser-service-processor/src/main/java/com/knecon/fforesight/service/layoutparser/processor/utils/TextPositionSequenceComparator.java index 52974d3..1c46ef5 100644 --- a/layoutparser-service/layoutparser-service-processor/src/main/java/com/knecon/fforesight/service/layoutparser/processor/utils/TextPositionSequenceComparator.java +++ b/layoutparser-service/layoutparser-service-processor/src/main/java/com/knecon/fforesight/service/layoutparser/processor/utils/TextPositionSequenceComparator.java @@ -51,13 +51,48 @@ public class TextPositionSequenceComparator implements Comparator= pos1YTop && pos2YBottom <= pos1YBottom || pos1YBottom >= pos2YTop && pos1YBottom <= pos2YBottom) { - return Double.compare(x1, x2); - } else if (pos1YBottom < pos2YBottom) { - return -1; - } else { - return 1; + + // Adjust for text rotation + switch (pos1.getRotation()) { + case 0: + // 0 degrees (horizontal, top to bottom and left to right): Sort primarily by y-coordinates from top to bottom (pos1YBottom < pos2YBottom). + if (yDifference < .1 || (pos2YBottom >= pos1YTop && pos2YBottom <= pos1YBottom) || (pos1YBottom >= pos2YTop && pos1YBottom <= pos2YBottom)) { + return Double.compare(x1, x2); + } else if (pos1YBottom < pos2YBottom) { + return -1; + } else { + return 1; + } + case 90: + // 90 degrees (vertical, right to left): Sort by x-coordinates first (x1 > x2), then by y-coordinates from top to bottom (pos1YBottom < pos2YBottom). + if (x1 > x2) { + return -1; + } else if (x1 < x2) { + return 1; + } else { + return Double.compare(pos1YBottom, pos2YBottom); + } + case 180: + // 180 degrees (horizontal, bottom to top and right to left): Sort primarily by y-coordinates from bottom to top (pos1YBottom > pos2YBottom). + if (yDifference < .1 || (pos2YBottom >= pos1YTop && pos2YBottom <= pos1YBottom) || (pos1YBottom >= pos2YTop && pos1YBottom <= pos2YBottom)) { + return Double.compare(x2, x1); + + } else if (pos1YBottom > pos2YBottom) { + return -1; + } else { + return 1; + } + case 270: + // 270 degrees (vertical, left to right): Sort by x-coordinates in reverse (x2 > x1), then by y-coordinates from bottom to top (pos2YBottom > pos1YBottom). + if (x2 > x1) { + return -1; + } else if (x2 < x1) { + return 1; + } else { + return Double.compare(pos2YBottom, pos1YBottom); + } + default: + throw new RuntimeException("Rotation not supported. Only 0/90/180/270 degree rotation is supported."); } }