|
| 1 | +// Copyright (c) Microsoft. All rights reserved. |
| 2 | +package com.microsoft.semantickernel.samples.syntaxexamples.rag; |
| 3 | + |
| 4 | +import com.microsoft.semantic.kernel.rag.splitting.Chunk; |
| 5 | +import com.microsoft.semantic.kernel.rag.splitting.Document; |
| 6 | +import com.microsoft.semantic.kernel.rag.splitting.Splitter; |
| 7 | +import com.microsoft.semantic.kernel.rag.splitting.TextSplitter; |
| 8 | +import com.microsoft.semantic.kernel.rag.splitting.document.TextDocument; |
| 9 | +import com.microsoft.semantic.kernel.rag.splitting.overlap.NoOverlapCondition; |
| 10 | +import com.microsoft.semantic.kernel.rag.splitting.splitconditions.CountSplitCondition; |
| 11 | +import com.microsoft.semantic.kernel.rag.splitting.splitconditions.SplitPoint; |
| 12 | +import com.microsoft.semantickernel.implementation.EmbeddedResourceLoader; |
| 13 | +import java.io.ByteArrayInputStream; |
| 14 | +import java.io.IOException; |
| 15 | +import java.net.URI; |
| 16 | +import java.net.http.HttpClient; |
| 17 | +import java.net.http.HttpRequest; |
| 18 | +import java.net.http.HttpResponse; |
| 19 | +import java.net.http.HttpResponse.BodyHandlers; |
| 20 | +import java.util.List; |
| 21 | +import java.util.regex.Pattern; |
| 22 | +import java.util.stream.Collectors; |
| 23 | +import org.apache.pdfbox.io.RandomAccessReadBuffer; |
| 24 | +import org.apache.pdfbox.pdfparser.PDFParser; |
| 25 | +import org.apache.pdfbox.pdmodel.PDDocument; |
| 26 | +import org.apache.pdfbox.text.PDFTextStripper; |
| 27 | +import reactor.core.publisher.Flux; |
| 28 | +import reactor.core.publisher.Mono; |
| 29 | + |
| 30 | +public class DocumentSplittingExample { |
| 31 | + |
| 32 | + private static String BENEFITS_DOC = "https://raw.githubusercontent.com/Azure-Samples/azure-search-openai-demo-java/refs/heads/main/data/Benefit_Options.pdf"; |
| 33 | + |
| 34 | + private static class PDFDocument implements Document { |
| 35 | + |
| 36 | + private final byte[] pdf; |
| 37 | + |
| 38 | + private PDFDocument(byte[] pdf) { |
| 39 | + this.pdf = pdf; |
| 40 | + } |
| 41 | + |
| 42 | + @Override |
| 43 | + public Flux<String> getContent() { |
| 44 | + try { |
| 45 | + PDFParser parser = new PDFParser( |
| 46 | + RandomAccessReadBuffer.createBufferFromStream(new ByteArrayInputStream(pdf))); |
| 47 | + PDDocument document = parser.parse(); |
| 48 | + String text = new PDFTextStripper().getText(document); |
| 49 | + |
| 50 | + return Flux.just(text); |
| 51 | + } catch (IOException e) { |
| 52 | + return Flux.error(e); |
| 53 | + } |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + public static void main(String[] args) throws IOException, InterruptedException { |
| 58 | + useCustomChunker(); |
| 59 | + useInbuiltChunker(); |
| 60 | + } |
| 61 | + |
| 62 | + private static void useInbuiltChunker() throws IOException, InterruptedException { |
| 63 | + byte[] pdfBytes = getPdfDoc(); |
| 64 | + PDFDocument pdfDoc = new PDFDocument(pdfBytes); |
| 65 | + |
| 66 | + Splitter splitter = Splitter |
| 67 | + .builder() |
| 68 | + .maxParagraphsPerChunk(4) |
| 69 | + .overlapNPercent(30.0f) |
| 70 | + .trimWhitespace() |
| 71 | + .build(); |
| 72 | + |
| 73 | + List<Chunk> chunks = splitter |
| 74 | + .splitDocument(pdfDoc) |
| 75 | + .collectList() |
| 76 | + .block(); |
| 77 | + |
| 78 | + chunks |
| 79 | + .forEach(chunk -> { |
| 80 | + System.out.println("========="); |
| 81 | + System.out.println(chunk.getContents()); |
| 82 | + }); |
| 83 | + } |
| 84 | + |
| 85 | + public static void useCustomChunker() throws IOException, InterruptedException { |
| 86 | + |
| 87 | + String example = EmbeddedResourceLoader.readFile("example.md", |
| 88 | + DocumentSplittingExample.class); |
| 89 | + |
| 90 | + // Define how we are splitting tokens, in this case we are splitting on headers of an md file |
| 91 | + // i.e <new line> followed by one or more # characters |
| 92 | + TextSplitter textSplitter = (doc, numTokens) -> { |
| 93 | + // Split on headers |
| 94 | + Pattern pattern = Pattern.compile("(\\r?\\n|\\r)\s*#+", Pattern.MULTILINE); |
| 95 | + |
| 96 | + Flux<Integer> splitPoints = Flux.fromStream(pattern.matcher(doc).results()) |
| 97 | + .map(window -> window.start()); |
| 98 | + |
| 99 | + return createWindows(doc, splitPoints); |
| 100 | + }; |
| 101 | + |
| 102 | + // Split into single sections |
| 103 | + CountSplitCondition condition = new CountSplitCondition(1, textSplitter); |
| 104 | + |
| 105 | + Splitter splitter = Splitter |
| 106 | + .builder() |
| 107 | + .addChunkEndCondition(condition) |
| 108 | + // No overlap |
| 109 | + .setOverlapCondition(NoOverlapCondition.build()) |
| 110 | + // Tidy up the text |
| 111 | + .trimWhitespace() |
| 112 | + .build(); |
| 113 | + |
| 114 | + String chunks = splitter |
| 115 | + .splitDocument(new TextDocument(example)) |
| 116 | + .collectList() |
| 117 | + .map(it -> it.stream() |
| 118 | + .map(chunk -> chunk.getContents()) |
| 119 | + .collect(Collectors.joining("\n============\n"))) |
| 120 | + .block(); |
| 121 | + |
| 122 | + System.out.println(chunks); |
| 123 | + } |
| 124 | + |
| 125 | + /* |
| 126 | + * Transforms: [ 2, 10, 20, 100 ] -> [ (0, 2), (2, 10), (10, 20), (20, 100), (100, <doc length>) |
| 127 | + * ] |
| 128 | + */ |
| 129 | + private static List<SplitPoint> createWindows(String doc, Flux<Integer> splitPoints) { |
| 130 | + return Flux.concat( |
| 131 | + Flux.just(0), |
| 132 | + splitPoints, |
| 133 | + Flux.just(doc.length())) |
| 134 | + .window(2, 1) |
| 135 | + .concatMap(window -> { |
| 136 | + return window.collectList() |
| 137 | + .flatMap(list -> { |
| 138 | + if (list.size() <= 1) { |
| 139 | + return Mono.empty(); |
| 140 | + } |
| 141 | + return Mono.just( |
| 142 | + new SplitPoint(list.get(0), list.get(1))); |
| 143 | + }); |
| 144 | + }) |
| 145 | + .collectList() |
| 146 | + .block(); |
| 147 | + } |
| 148 | + |
| 149 | + private static byte[] getPdfDoc() throws IOException, InterruptedException { |
| 150 | + HttpResponse<byte[]> doc = HttpClient.newHttpClient() |
| 151 | + .send(HttpRequest.newBuilder() |
| 152 | + .GET() |
| 153 | + .uri(URI.create(BENEFITS_DOC)) |
| 154 | + .build(), |
| 155 | + BodyHandlers.ofByteArray()); |
| 156 | + return doc.body(); |
| 157 | + } |
| 158 | + |
| 159 | +} |
0 commit comments