Skip to content

Lab 4: Search images and a PDF

Search a folder of pictures by typing what you want, then ask questions of a PDF that contains text, a table and a chart, done two different ways.

When Day 2 (30 minutes, hands-on)
Lab file labs/04-search-and-rag.ts, run with npm run lab4 -- <step>
Files used data/images/ (10 pictures), data/invoice_03_rotated.jpg, data/policy_handbook.pdf

Info

The idea in one line: a matching model (CLIP) places pictures and words on the same "map of meaning", so the words "a pie chart" land right next to a picture of one. It's the same reason typing "cake" in a phone photo gallery can find untagged birthday photos.

Step 0: Open the lab file

Do: open labs/04-search-and-rag.ts. CLIP (Xenova/clip-vit-base-patch32) runs on your laptop through Transformers.js; Step 1 loads it and embeds the images.

You should see, near the top of Step 1's output:

10 images embedded, vector size 512

These are the pictures you'll search:

The 10 pictures in data/images

Step 1 (Part A): Search pictures with words

Do: npm run lab4 -- 1. It searches for five descriptions and prints the top 3 matches with a score.

You should see results like:

๐Ÿ”Ž a pie chart
   0.29  pie_spend.png
   ...
๐Ÿ”Ž a shop receipt
   0.27  receipt_cafe.png
   ...

Check: the top result for each search should make sense: the pie chart, the org chart, the receipt, the architecture diagram and the line chart. Scores are small numbers; what matters is the order.

Why it matters: none of these pictures has a tag or a caption. The model matched words to images by meaning.

Step 2 (Part B): Find the original of a bad scan

Do: npm run lab4 -- 2. It uses the blurry, rotated invoice as the search query.

You should see invoice_01.png at or near the top.

Why it matters: this is "search by picture", useful for spotting duplicates or recycled photos.

Step 3 (Part C): See where CLIP fails

Do: npm run lab4 -- 3. It searches for "invoice from Sahyadri Cloud Services" and "receipt from Chai Point Kharadi".

You should see an invoice-like or receipt-like image at the top, but not because the model read the name.

Why it matters: CLIP knows what kind of picture it is, not what it says. To search by the words inside an image, you also need a text description of the image. That's the next step.

Success

Checkpoint: you've searched pictures with words, found a scan's original, and seen CLIP miss text inside images.

Step 4 (Part D): Ask the PDF questions, method 1: turn everything into text

The handbook has three pages, with text, a table (page 1) and a chart (page 2):

Page 1 of the handbook, with the table

Do: npm run lab4 -- 4. It breaks the PDF into chunks: text blocks (read with MuPDF), each page's table as Markdown (read by the vision model from a picture of the page), and the chart, cropped out and described by the vision model. Every chunk keeps its page number.

You should see a list of chunks like:

1 text | Acme Insurance - AI Usage and Claims Handling Handbook (Training Sample)
1 table | |Claim type|Max auto-approve (INR)|Min model confidence|Turnaround SLA| ...
2 figure | FIGURE: A bar chart titled "Quarterly revenue and AI-led share of revenue"...

Read retrieve() and ragAnswer() in the file: they build a small search index over the chunks (MiniLM, on your laptop) and answer with citations.

Do: npm run lab4 -- 5. It answers four questions without the chart description.

Check the answers:

Question Correct answer Expected result
Health cashless: max auto-approve and minimum confidence INR 50,000 and 0.95 (page 1 table) โœ” Answered
AI-led share of revenue in Q2 FY27 52% (page 2 chart) โœ˜ "Not in the sources"
How long are call audio and transcripts kept? Audio 90 days, transcripts 1 year (page 2) โœ” Answered
Can I send an Aadhaar scan to an external API? Only after redaction (page 1) โœ” Answered

Do: npm run lab4 -- 6.

You should see the chart question answered: 52%, citing the figure.

Why it matters: if you only index text, anything that lives in a chart is invisible. Describing each figure in words fixes that.

Step 5 (Part E): Method 2: find the page, then show the model the page

Do: npm run lab4 -- 7. It finds the most relevant pages by text, then sends pictures of those pages to the vision model.

You should see each question with the pages that were sent and an answer citing a page number. The chart question should now work too. A usage table prints at the end: compare the in_tok numbers with the text-only method.

Why it matters: sending page images keeps tables and charts intact, at a higher cost per question.

Step 6: Compare the two methods

Discuss with your table:

Turn into text Show the page
Tables Good, if the parser finds them Good
Charts Only if you describe them Good
Cost per question Low Higher
Citations The exact chunk The page
Scanned PDFs Need text recognition (OCR) first Work as they are

Remember: keep every table whole, describe every figure, cut audio into 30-second pieces with timestamps, and always keep the page or timestamp so you can cite it.

Your turn (if you finish early)

Add each exercise as a new step (8, 9, 10) at the Your turn comment in the lab file, then run it with npm run lab4 -- 8.

1. Make the whiteboard searchable by its words. Describe the whiteboard photo in words, add it to the text index, then ask "Who owns the gold set?"

Hint

CLIP can't read the whiteboard's words, so add a text description to the text index:

  8: {
    title: "Make the whiteboard searchable", run: async () => {
      const cap = await ask("Describe this image for a search index. Transcribe all visible text exactly.",
                            { images: ["data/whiteboard.png"], verbose: false });
      (await buildChunks()).push({ page: 0, type: "image", text: "WHITEBOARD: " + cap });
      chunkVecs = null;                                   // rebuild the index with the new chunk
      console.log(await ragAnswer("Who owns the gold set, and by when?"));
    },
  },

Expected: Priya, next Wednesday.

2. Ask a question that needs both the table and the chart. Which method answers it better?

Hint
  9: {
    title: "Table + chart in one question", run: async () => {
      const q = "Which is higher: the AI-led share of revenue in Q2 FY27, or the minimum model confidence " +
                "for motor claims expressed as a percentage?";
      console.log("TEXT:  ", await ragAnswer(q));
      console.log("PAGES: ", (await visionRag(q)).answer);
    },
  },

Expected: the confidence threshold (0.92, so 92%) is higher than the AI-led share (52%).

3. Stretch: use a real vector database. Store the chunks in LanceDB (it runs inside Node, no server) and keep the page numbers.

Hint

First run npm install @lancedb/lancedb, then:

  10: {
    title: "A real vector database", run: async () => {
      const lancedb = await import("@lancedb/lancedb");
      const chunks = await buildChunks();
      const vecs = await embedTexts(chunks.map((c) => c.text));
      const db = await lancedb.connect("data/_lancedb");
      const table = await db.createTable("handbook",
        chunks.map((c, i) => ({ vector: vecs[i], text: c.text, page: c.page, type: c.type })), { mode: "overwrite" });
      const [q] = await embedTexts(["call recording retention"]);
      for (const r of await table.search(q).limit(3).toArray()) console.log(r.page, r.type, r.text.slice(0, 80));
    },
  },

Key takeaways

  • Matching models put images and words on one map of meaning, which makes search by description possible.
  • They know what kind of image something is, not what it says; add text descriptions for that.
  • Questions about charts need a figure description or the page image.
  • Every chunk keeps its address (page, timestamp), so answers can cite their source.

Stuck?

  • CLIP loading is slow or hangs: the model downloads about 600 MB the first time, into node_modules/@huggingface/transformers/.cache. If you skipped the setup check, use a hotspot.
  • The "with figure captions" answer still misses 52%: look at the figure chunk printed in Part D. If the description has no numbers, delete data/_cache and run Step 4 again.
  • Cannot find package '@lancedb/lancedb': run npm install @lancedb/lancedb from the main folder.