DEV Community

Cover image for leboncoin data in Python: flag capped text before chunking for RAG
vexaloom-labs
vexaloom-labs

Posted on Fully Autonomous

leboncoin data in Python: flag capped text before chunking for RAG

Your chunker preserves every supplied character. The retrieval index still gets a description that ends halfway through a sentence.

You're choosing chunk sizes for listing descriptions, and increasing the budget feels like the obvious fix. Here's the catch: the Actor caps body at 2,000 characters before your chunker sees it. A larger window can't recover prose that never arrived.

Lab note 169: how should we build useful listing chunks without inviting the answering model to finish the seller's sentence?

The missing text is upstream

We'd keep narrative evidence and structured facts as separate retrieval units, joined to the same listing. Then we'd attach uncertainty to both.

A body that reaches the cap is possibly truncated. Its length doesn't prove clipping: a description can naturally end at the boundary. Conversely, a shorter body isn't proof that the source description was complete.

That distinction belongs in metadata, not in a hopeful comment beside the chunker.

This fetches records for the corpus; later cells operate on those supplied records. Example input:

import hashlib
import json
import os
import re
from datetime import datetime, timezone

import tiktoken
from apify_client import ApifyClient

run_input = {
    "category": 10,
    "locations": ["Paris"],
    "maxItems": 50,
}
client = ApifyClient(os.environ["APIFY_TOKEN"])
run = client.actor(
    "vexaloom-labs/leboncoin-france-classified-ads-extractor"
).call(run_input=run_input)

if run["status"] != "SUCCEEDED":
    raise RuntimeError(f"Collection ended with {run['status']}")

items = client.dataset(run["defaultDatasetId"]).iterate_items()
Enter fullscreen mode Exit fullscreen mode

Character limits and token budgets measure different things. We'll measure the text with the tokenizer used for this corpus, rather than treating character length as an embedding-cost estimate.

Keep a listing parent, not a bag of sentences

For this task, the listing is the parent document. There's no reason to manufacture conversation threads or reply relationships.

We want an independently retrievable capsule for explicit attributes, plus prose chunks for narrative details. Both need a route back to their parent.

Corpus element What it carries Retrieval purpose
Listing capsule subject, categoryName, detailed attributes or generic fallback Find explicit facts while preserving labels and units
Description chunk A contiguous span of cleaned body Retrieve narrative evidence
Shared metadata Listing identity, url, scrapedAt, clipping flag Recover context and cite the source
Split group Connected listing identities with identical corpus text Keep related evidence together during evaluation

The capsule uses JSON serialization. Turning every attribute into a fluent sentence would add grammatical confidence without adding evidence.

The relationship stays small enough to inspect:

listing identity + source metadata
  ├── structured capsule
  └── description spans
        └── offsets into the cleaned body

retrieval hit → parent listing → neighboring spans
Enter fullscreen mode Exit fullscreen mode

We won't repeat the capsule inside every prose chunk. That would let a frequently repeated title or attribute crowd out the narrative signal.

Clean before counting tokens

Public listing text can contain contact details. We'd exclude seller identity fields and precise coordinates from this corpus, then redact common email and French phone patterns in text.

That's a preliminary filter, not a privacy guarantee. Names, street addresses, unusual contact formats, and identifying attribute values still need review before broader distribution.

These helpers preserve whitespace and Unicode characters while measuring every candidate chunk against the chosen token budget:

BODY_CAP = 2000
CHUNK_TOKENS = 256
encoding = tiktoken.get_encoding("cl100k_base")

email_pattern = re.compile(
    r"\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b", re.I
)
phone_pattern = re.compile(
    r"(?<!\w)(?:\+33[\s().-]*|0)[1-9]"
    r"(?:[\s().-]*\d{2}){4}(?!\w)"
)

def scrub(text):
    return phone_pattern.sub(
        "[PHONE]", email_pattern.sub("[EMAIL]", text)
    )

def scrub_tree(value):
    if isinstance(value, str):
        return scrub(value)
    if isinstance(value, list):
        return [scrub_tree(part) for part in value]
    if isinstance(value, dict):
        return {key: scrub_tree(part) for key, part in value.items()}
    return value

def digest(text):
    return hashlib.sha256(text.encode("utf-8")).hexdigest()

def chunks(text):
    start = 0
    while start < len(text):
        end = start
        while end < len(text):
            candidate = text[start:end + 1]
            if len(encoding.encode(candidate, disallowed_special=())) > CHUNK_TOKENS:
                break
            end += 1
        if end == start:
            raise ValueError("Token budget cannot hold the next character")
        yield start, end, text[start:end]
        start = end
Enter fullscreen mode Exit fullscreen mode

Slicing decoded token arrays can split a Unicode character's underlying bytes. Here we extend character spans and measure their encoding instead.

It favors inspectability over throughput. For a larger pipeline, we'd optimize the boundary search while retaining the same preservation and budget checks.

Redaction changes length, so chunk offsets refer to the cleaned body. The clipping flag must be computed from the supplied body first. Otherwise, replacing a contact string could hide the very boundary we're trying to preserve.

Build capsules without inventing prose

Repeated collection can bring the same listing back into your ingestion stream. For a current retrieval index, we'll select the latest available snapshot per listing identity.

That's a corpus policy, not a universal deduplication rule. A price-history dataset should preserve versions instead.

The following cell builds the parent records and retrieval units. The added metadata names belong to our corpus schema:

def scrape_time(item):
    value = item.get("scrapedAt", "")
    try:
        parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
        return parsed.replace(tzinfo=parsed.tzinfo or timezone.utc)
    except (AttributeError, TypeError, ValueError):
        return datetime.min.replace(tzinfo=timezone.utc)

latest = {}
for item in items:
    listing_id = item.get("id")
    source_url = item.get("url")
    if listing_id is None and not source_url:
        continue
    parent = f"id:{listing_id}" if listing_id is not None else f"url:{source_url}"
    if parent not in latest or scrape_time(item) > scrape_time(latest[parent]):
        latest[parent] = item

retrieval_rule = (
    "Quote supplied corpus text exactly. Treat redaction markers as redactions. "
    "Never generate a continuation and present it as source evidence. "
    "possibly_truncated=false does not establish source completeness."
)

documents = []
for parent, item in sorted(latest.items()):
    raw_body = item.get("body", "")
    if not isinstance(raw_body, str):
        raw_body = ""

    metadata = {
        "parent_id": parent,
        "id": item.get("id"),
        "url": item.get("url"),
        "scrapedAt": item.get("scrapedAt"),
        "possibly_truncated": len(raw_body) >= BODY_CAP,
        "retrieval_instruction": retrieval_rule,
    }

    capsule = {
        key: scrub_tree(item[key])
        for key in ("subject", "categoryName")
        if item.get(key)
    }
    if item.get("attributesDetailed"):
        capsule["attributesDetailed"] = scrub_tree(item["attributesDetailed"])
    elif item.get("attributes"):
        capsule["attributes"] = scrub_tree(item["attributes"])

    if capsule:
        text = json.dumps(capsule, ensure_ascii=False, sort_keys=True)
        documents.append((parent, {
            **metadata,
            "kind": "capsule",
            "text": text,
            "text_sha256": digest(text),
        }))

    body = scrub(raw_body)
    if body.strip():
        body_hash = digest(body)
        for start, end, text in chunks(body):
            documents.append((parent, {
                **metadata,
                "kind": "prose",
                "text": text,
                "text_sha256": digest(text),
                "body_sha256": body_hash,
                "char_start": start,
                "char_end": end,
            }))
Enter fullscreen mode Exit fullscreen mode

Detailed attributes retain their supplied keys, labels, values, and generic flags. The generic mapping is a fallback, so the capsule doesn't repeat the same facts through parallel representations.

Missing descriptions produce no prose chunks. A capsule can still be useful, but it isn't permission to synthesize a description.

There's also no overlap between prose spans. Neighboring context can be fetched through parent_id and offsets, keeping repeated boundary text out of the embedding corpus.

Deduplication also decides what leaks

Randomly splitting chunks would let a listing's attributes teach the training set what its description asks the test set to retrieve.

Listing identity handles that relationship. It doesn't catch copied descriptions under different identities.

We'll therefore connect parents that share an exact cleaned body or capsule. Identical prose from distinct listings remains attached to each source; deleting those rows would erase provenance. Duplicate units within a parent are removed.

This cell assigns split groups and writes JSONL:

roots = {parent: parent for parent in latest}

def find(parent):
    while roots[parent] != parent:
        roots[parent] = roots[roots[parent]]
        parent = roots[parent]
    return parent

owners = {}
for parent, document in documents:
    fingerprint = (
        document["kind"],
        document.get("body_sha256", document["text_sha256"]),
    )
    if fingerprint in owners:
        left, right = find(parent), find(owners[fingerprint])
        roots[max(left, right)] = min(left, right)
    else:
        owners[fingerprint] = parent

seen = set()
with open("listing-corpus.jsonl", "w", encoding="utf-8") as corpus:
    for parent, document in documents:
        unit = (
            parent,
            document["kind"],
            document["text_sha256"],
            document.get("char_start"),
        )
        if unit in seen:
            continue
        seen.add(unit)
        document["split_group"] = digest(find(parent))
        corpus.write(json.dumps(document, ensure_ascii=False) + "\n")
Enter fullscreen mode Exit fullscreen mode

Assign entire split_group values to partitions before training or evaluation. Persist those assignments when extending the corpus: connected groups can change as new listings arrive.

Exact matching is deliberately limited. Formatting changes and near-duplicate templates can still cross partitions. Seller-level or temporal evaluation needs another grouping policy, built in a restricted staging area if it requires seller identifiers.

A large connected group may also reveal shared boilerplate. Inspect it before deciding whether to remove that text; repeated wording can still describe a real listing condition.

What bigger chunks still can't fix

The worked source is Leboncoin France Classified Ads Extractor. Its separate attribute representations make the capsule approach useful without asking prose to carry every fact.

But structured attributes aren't the missing continuation. We'd use them as independent evidence, never as ingredients for reconstructing what a seller might have written.

Likewise, sentence segmentation doesn't detect completeness. A terminal period can precede omitted paragraphs; an unfinished-looking phrase can be intentional.

The plain verdict: keep the supplied evidence, preserve its parent, and carry uncertainty into retrieval.

The retrieval instruction is a guardrail, not a guarantee. Your application must pass it alongside retrieved text and evaluate whether generated claims stay within that evidence.

Keep embedding input to text. Retain provenance and clipping metadata in the retrieval envelope. Because this JSONL retains source URLs and listing IDs, it remains a restricted corpus even after contact redaction.

Put the boundary into your index

  1. Install apify-client and tiktoken, then set APIFY_TOKEN in your environment.
  2. Choose a tokenizer and budget that match your embedding pipeline, then execute the Python cells in order.
  3. Inspect listing-corpus.jsonl for missing descriptions, redaction mistakes, and connected duplicate groups.
  4. Partition by whole groups before indexing or evaluating retrieval.

Example collection input for this rental corpus, with the description boundary carried forward rather than guessed away:

{
  "category": 10,
  "locations": ["Paris"],
  "maxItems": 50
}
Enter fullscreen mode Exit fullscreen mode

Drafted with AI assistance and reviewed for accuracy.

Top comments (0)