Files
spring-ai/rag/src/test/java/com/ankurm/rag/IngestionTest.java
T

158 lines
8.1 KiB
Java

package com.ankurm.rag;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.ankurm.rag.config.TestPipeline;
import com.ankurm.rag.ingest.IngestionResult;
import com.ankurm.rag.ingest.IngestionService;
import com.ankurm.rag.support.SamplePdf;
import com.ankurm.rag.support.Stores;
import com.ankurm.rag.support.Transcript;
import org.junit.jupiter.api.Test;
import org.springframework.ai.document.Document;
import org.springframework.ai.reader.pdf.PagePdfDocumentReader;
import org.springframework.ai.reader.pdf.config.PdfDocumentReaderConfig;
import org.springframework.core.io.Resource;
import org.springframework.jdbc.core.JdbcTemplate;
import static org.assertj.core.api.Assertions.assertThat;
/** Chapter 3: what a PDF becomes on the way in, and what re-ingesting does. Transcripts 04 and 05. */
class IngestionTest {
private static final Map<String, Object> ACME_TAGS = Map.of("tenant_id", "acme", "doc_type", "handbook");
@Test
void pdfPagesAndMetadata() {
Resource pdf = SamplePdf.of(SamplePdf.ACME);
List<Document> pages = new PagePdfDocumentReader(pdf, PdfDocumentReaderConfig.builder()
.withPagesPerDocument(1).build()).get();
try (Transcript t = new Transcript("04-pdf-pages-and-metadata.txt", "PagePdfDocumentReader: what one PDF page becomes")) {
t.line("pages in the PDF: 4, documents read: %d", pages.size());
for (Document page : pages) {
t.line("page document metadata: %s", page.getMetadata());
}
Document page2 = pages.get(1);
String raw = page2.getText();
String tidy = IngestionService.tidy(raw);
t.section("page 2 as read (single spaces as dots, runs of 4+ as [n spaces], line ends as a pilcrow)");
t.line(visible(raw));
t.section("page 2 after IngestionService.tidy");
t.line(visible(tidy));
t.section("size of page 2");
t.line("as read : %d characters, longest run of spaces %d", raw.length(), longestSpaceRun(raw));
t.line("tidied : %d characters, longest run of spaces %d", tidy.length(), longestSpaceRun(tidy));
assertThat(pages).hasSize(4);
assertThat(pages.get(1).getMetadata()).containsKey("page_number");
assertThat(tidy.length()).isLessThanOrEqualTo(raw.length());
assertThat(tidy).contains("20 working days").doesNotContain(" ");
}
}
@Test
void reingestingTheSameFile() {
JdbcTemplate jdbc = Stores.jdbc();
TestPipeline p = TestPipeline.on(embeddings -> Stores.pg(jdbc, embeddings));
Resource v1 = SamplePdf.of(SamplePdf.ACME);
List<List<String>> edited = new ArrayList<>(SamplePdf.ACME);
edited.set(1, List.of("4.1 Annual Leave Entitlement. Full-time employees are entitled to 22 working days",
"of annual leave per calendar year. Part-time employees receive leave pro rata.",
"",
"4.2 Leave Carryover. Unused annual leave may be carried over for a maximum of 5 days",
"into the next calendar year and must be used by 31 March."));
Resource v2 = SamplePdf.of(edited);
try (Transcript t = new Transcript("05-ingestion-idempotency.txt", "Ingesting the same handbook more than once (real PostgreSQL + pgvector)")) {
t.line("rows are counted with: select count(*) from vector_store");
IngestionResult first = p.ingestion.ingestPdf(v1, "acme-handbook.pdf", ACME_TAGS);
int rowsAfterFirst = rows(jdbc);
int embeddedAfterFirst = p.embeddings.textsEmbedded();
report(t, "1. first upload", first, rowsAfterFirst, embeddedAfterFirst);
IngestionResult second = p.ingestion.ingestPdf(v1, "acme-handbook.pdf", ACME_TAGS);
report(t, "2. same bytes again", second, rows(jdbc), p.embeddings.textsEmbedded());
IngestionResult third = p.ingestion.ingestPdf(v2, "acme-handbook.pdf", ACME_TAGS);
report(t, "3. page 2 edited (20 -> 22 days)", third, rows(jdbc), p.embeddings.textsEmbedded());
int stale = jdbc.queryForObject("select count(*) from vector_store where content like '%20 working days%'", Integer.class);
int fresh = jdbc.queryForObject("select count(*) from vector_store where content like '%22 working days%'", Integer.class);
t.line("rows still saying \"20 working days\": %d, rows saying \"22 working days\": %d", stale, fresh);
Resource v2Again = SamplePdf.of(edited);
assertThat(bytes(v2Again)).isNotEqualTo(bytes(v2));
IngestionResult reexport = p.ingestion.ingestPdf(v2Again, "acme-handbook.pdf", ACME_TAGS);
report(t, "4. same text, exported again", reexport, rows(jdbc), p.embeddings.textsEmbedded());
t.line("the two PDFs have identical text and different bytes: %s", !java.util.Arrays.equals(bytes(v2Again), bytes(v2)));
t.line("the file hash is a hash of bytes, so a re-export counts as a change and is re-embedded");
t.section("the naive version: vectorStore.add() on every upload, nothing remembered");
List<Document> pages = new PagePdfDocumentReader(v2, PdfDocumentReaderConfig.builder()
.withPagesPerDocument(1).build()).get();
List<Document> chunks = p.chunker.apply(pages.stream()
.map(pg -> new Document(IngestionService.tidy(pg.getText()), pg.getMetadata())).toList());
int before = rows(jdbc);
p.store.add(chunks);
p.store.add(chunks.stream().map(c -> new Document(c.getText(), c.getMetadata())).toList());
int after = rows(jdbc);
t.line("the same %d chunks added on two more uploads: rows in table %d -> %d", chunks.size(), before, after);
t.line("rows saying \"22 working days\" now: %d",
jdbc.queryForObject("select count(*) from vector_store where content like '%22 working days%'", Integer.class));
assertThat(after).isEqualTo(before + 2 * chunks.size());
assertThat(first.status()).isEqualTo("ingested");
assertThat(first.chunksWritten()).isEqualTo(rowsAfterFirst);
assertThat(second.status()).isEqualTo("skipped");
assertThat(third.status()).isEqualTo("updated");
assertThat(third.chunksReplaced()).isEqualTo(first.chunksWritten());
assertThat(reexport.status()).isEqualTo("updated");
assertThat(stale).isZero();
assertThat(fresh).isEqualTo(1);
assertThat(p.embeddings.textsEmbedded()).isGreaterThan(embeddedAfterFirst);
}
}
private static void report(Transcript t, String label, IngestionResult r, int rows, int embedded) {
t.line("%-34s -> status=%-8s chunksWritten=%d chunksReplaced=%d | rows in table=%d, texts embedded so far=%d",
label, r.status(), r.chunksWritten(), r.chunksReplaced(), rows, embedded);
}
private static byte[] bytes(Resource resource) {
try {
return resource.getInputStream().readAllBytes();
} catch (java.io.IOException e) {
throw new IllegalStateException(e);
}
}
private static int rows(JdbcTemplate jdbc) {
return jdbc.queryForObject("select count(*) from vector_store", Integer.class);
}
/** Short runs of spaces become dots, runs of four or more become "[n spaces]", line ends a pilcrow. */
private static String visible(String text) {
Matcher m = Pattern.compile(" +").matcher(text);
StringBuilder sb = new StringBuilder();
while (m.find()) {
int n = m.end() - m.start();
m.appendReplacement(sb, n >= 4 ? "[" + n + " spaces]" : "\u00b7".repeat(n));
}
m.appendTail(sb);
return sb.toString().replace("\n", "\u00b6\n");
}
private static int longestSpaceRun(String text) {
int longest = 0;
Matcher m = Pattern.compile(" +").matcher(text);
while (m.find()) {
longest = Math.max(longest, m.end() - m.start());
}
return longest;
}
}