---
title: "A document processing pipeline for the construction of a dataset"
description: "The paper shows how layout detection, text recognition and anonymization turn Italian Supreme Court judgments into data for topic discovery."
canonical: "https://research.elamur.ai/free/en/papers/marulli-2025-document-processing-pipeline-construction-dataset/"
---
Elamur: [Mova](https://md.mova.elamur.ai/free/en/) · [Parse](https://mova.elamur.ai/free/en/parse/) · [Dictionary](https://md.dictionary.elamur.ai/free/en/) · [Translate](https://md.translate.elamur.ai/free/en/) · **Research** · [Gali](https://md.gali.elamur.ai/free/en/) · [MCP](https://mcp.elamur.ai/) · [Locations](https://md.locations.elamur.ai/free/en/) · [Weather](https://md.weather.elamur.ai/free/en/) · [Constitution](https://md.constitution.elamur.ai/)

[Elamur Research](https://md.research.elamur.ai/free/en/) · [this page in HTML](https://research.elamur.ai/free/en/papers/marulli-2025-document-processing-pipeline-construction-dataset/)

[Elamur Research](https://md.research.elamur.ai/free/en/) / [papers](https://md.research.elamur.ai/free/en/papers/) / [2025](https://md.research.elamur.ai/free/en/papers/2025/) / A document processing pipeline for the construction of a dataset for topic modeling based on the judgments of the Italian Supreme Court

# A document processing pipeline for the construction of a dataset for topic modeling based on the judgments of the Italian Supreme Court

Paper · 2025 · Matteo Marulli, Glauco Panattoni and Marco Bertini

**Authors:** Matteo Marulli, Glauco Panattoni and Marco Bertini · **Year:** 2025 · **Venue:** arXiv:2505.08439 · **Licence:** [CC BY 4.0 (arXiv)](http://creativecommons.org/licenses/by/4.0/)

[**0** citations OpenAlex, 2026-10-14](https://openalex.org/works?filter=cites:W6948293008) · [arXiv:2505.08439](https://openalex.org/S4306400194) · [licence](http://creativecommons.org/licenses/by/4.0/)

- [PDF](https://arxiv.org/pdf/2505.08439)
- [arXiv 2505.08439](https://arxiv.org/abs/2505.08439)
- [OpenAlex](https://openalex.org/W6948293008)

Citations: OpenAlex, 2026-10-14.

## Summary

A readable scan of a court judgment can still make poor material for studying what courts discuss. The sentences may be legible, yet a transcript can mix legal reasoning with headings and page furniture, retain names that dominate keyword lists, or give a text analysis system passages too long to process intact. The authors address these problems using judgments from Italy’s Corte di Cassazione, the country’s highest court in civil and criminal matters. They ask how the preparation of those judgments affects the themes recovered through [topic modeling](https://md.research.elamur.ai/free/en/concepts/topic-modeling/).

The study draws on 307 judgments, comprising 161 civil and 146 criminal cases. Starting from page images, the pipeline finds structural regions such as paragraphs and headings, detects the lines inside those regions, and transcribes the lines. It then masks sensitive spans and stores the text with information about its position and role on the page. For topic discovery, the authors select anonymized paragraphs with enough text to carry substantive content. The result is a collection organized around passages of a judgment, with page and document identifiers retained.

On the layout test set, YOLOv8x reached a mean average precision of 0.964 at the 50% box-overlap threshold and 0.800 across the stricter range of thresholds. A separate detector for text lines scored 0.9022 across that range. TrOCR-Small achieved a character error rate of 0.0047 and a word error rate of 0.0248 on the recognition test. In the downstream comparison, both versions of the corpus were anonymized. The version prepared with layout detection, paragraph segmentation, and filtering produced more favorable topic results than the OCR-only version. The paper reports a diversity score of 0.6198 and, in the abstract, a coherence score of 0.6638 for the processed dataset.

The study also asks whether the resulting clusters can be explained in language a legal reader would recognize. The authors supply representative passages and topic keywords to text generators and compare the resulting labels and summaries with a legal expert’s interpretations. Claude 3.7 Sonnet scored 0.8119 on labels and 0.9130 on summaries using BERTScore F1, a measure of contextual similarity to a reference. LLaMA 3.1 (8B) obtained the highest label score, 0.8256, yet often returned a summary when asked for a short label. That distinction matters when a description has a practical job to do. The privacy stage has a separate evidence gap. The authors observed that masking changed the words used to characterize topics, and they report occasional missed identifiers. Its accuracy on these judgments remains unmeasured against annotated examples.

## Deep dive: A document processing pipeline for the construction of a dataset for topic modeling based on the judgments of the Italian Supreme Court

The paper shows how layout detection, text recognition and anonymization turn Italian Supreme Court judgments into data for topic discovery. · about 34 minutes to read

**In this deep dive**

1. [The problem and its context](#dd-the-problem-and-its-context)
2. [The method, step by step](#dd-the-method-step-by-step)
3. [Experiments and results](#dd-experiments-and-results)
4. [What the ablations show](#dd-what-the-ablations-show)
5. [Limitations](#dd-limitations)
6. [What came after](#dd-what-came-after)

### The problem and its context

#### From reading a judgment to studying a collection

An individual judgment can be read in the order intended by the court. A reader recognizes the title, moves through the sections, and usually passes over a page number without assigning it any legal meaning. A collection of those judgments poses a different problem. To find recurring questions across cases, a computer needs units of text it can compare. Those units depend on decisions about where a passage starts, which parts of the page belong to it, and how much of the surrounding material it needs to make sense.

The authors situate this problem in [legal AI](https://md.research.elamur.ai/free/en/topics/legal-ai/). They describe document categorization and case outcome prediction as examples of supervised work, where the system learns from cases accompanied by known categories or outcomes. The earlier studies they review illustrate the importance of defining those targets carefully. In work on U.S. Supreme Court opinions, the categories came from a database with labels prepared by legal specialists. In another line of work, annotations distinguished levels of analysis such as facts, diagnostic problems, and legal elements. The review also describes a comparison on LexGLUE in which a support vector machine remained competitive with BERT-based classification. For the authors, these examples show how the availability and granularity of expert labels shape the work that can be done with supervised learning.

Exploratory work begins with another question. It asks what groups emerge from the documents before a category has been assigned to each passage. A cluster of passages might concern the conditions for raising a matter on appeal, and a different cluster might concern the effect of an invalid clause in a guarantee. Finding such a group establishes a relationship among the texts as represented by the system. Giving it a precise legal interpretation is a further task. This division lets the researchers work without a legal label for every input while reserving a role for expert judgment once the groups have been formed.

The paper identifies a shortage of accessible Italian case-law datasets designed for this exploratory use. In its account, scarcity affects both the range of questions researchers can ask and their ability to repeat one another’s experiments. It also leaves an important part of the method undocumented in some prior studies. A researcher may know which topic discovery technique was used and still have little information about how judgments were transcribed, how the text was divided, or which parts of the original documents were included. Those choices determine what material the technique can compare.

#### What earlier topic studies left open

The authors discuss a study that used Latent Dirichlet Allocation, or LDA, on Italian Supreme Court judgments about divorce. That work recovered themes related to divorce proceedings, the transition from separation, and economic arrangements following divorce. Its focused collection gave the analysis a well-defined subject. The question left open for this paper was how long judgments had been prepared before analysis, including whether the researchers divided them into shorter passages.

The review also describes work on Italian bank reports, where topic discovery was used to look for patterns relevant to money-laundering investigations. The paper treats it as another example of exploratory analysis in Italian and again points to limited information about document acquisition and preparation. Research on Portuguese and English legal material had explored methods including the Embedded Topic Model, contextualized topic discovery, and legal-domain text representations. Together, these studies gave the authors reasons to try specialized representations for legal language. They left room for an account of how to get from court PDFs to consistently structured Italian text in the first place. One technique discussed in this context was the [Embedded Topic Model](https://md.research.elamur.ai/free/en/papers/dieng-2020-topic-modeling-embedding-spaces/).

Document vision research offered a way to make that preparation explicit. In the authors’ account, layout surveys describe methods that build regions from small page elements, methods that divide the full page into progressively smaller regions, and methods that combine the approaches. The point for a judgment is that visual roles can be identified while the evidence for them is still available. A heading can be recognized by its position and presentation before it becomes a line of plain text. The paper also draws on work that combined visual and textual features for document classification and on work that extracted clinical information from scans. Those precedents support treating page structure as part of the input to a text pipeline.

#### Privacy and interpretation

Judgments can name people and companies and contain other identifying details. The paper treats those details as a problem for sharing a research dataset and as a possible influence on the patterns found during analysis. If a name consistently occurs in a subset of passages, a method that ranks distinctive words can promote it to a topic keyword. The score reflects how the word is distributed in the corpus. A legal reader may need a description centered on a rule, argument, or type of dispute instead. The same masking step can therefore affect both what the dataset exposes and what its topics emphasize.

The paper reviews earlier Italian work on legal-document anonymization, including a system developed for judicial documents and GiusBERTo, which was adapted to decisions of the Italian Court of Auditors. It also discusses an approach that takes the desired entity types as inputs and can look for several kinds of span together. That flexibility matters when a setup needs to handle names, locations, and other identifiers that occur in different forms. The task is [named entity recognition](https://md.research.elamur.ai/free/en/concepts/named-entity-recognition/), and the approach adopted in the study is [GLiNER](https://md.research.elamur.ai/free/en/papers/zaratiana-2024-gliner-generalist-model-named-entity/).

Even after identifying coherent groups, a researcher still has to explain them. A topic represented by prominent words is compact. It can leave several plausible readings open, particularly if common procedural terms appear alongside vocabulary for a particular dispute. The authors describe earlier experiments in which generated descriptions helped readers make sense of topics, including a study of medical text whose expert comparisons found some descriptions useful and others too general or incorrect. They also discuss a framework that used GPT-4 to produce readable topic labels. That work motivates comparing generated interpretations with expert ones in a specialized legal setting. The framework is [TopicGPT](https://md.research.elamur.ai/free/en/papers/pham-2024-topicgpt-prompt-based-topic-modeling/).

### The method, step by step

#### Choosing the unit of text

The project starts from PDFs distributed through Italgiure. Most of the chosen scans are clear, according to the authors, although some contain marks, handwritten corrections, or places where ink is missing. The civil and criminal groups also differ in length. Civil judgments have a longer tail of especially lengthy documents, and the paper reports an average of around 250 words per page, with some pages exceeding 400. That density matters because the software that later represents the meaning of passages has a restricted input length.

The limit the authors discuss is 512 tokens for BERT. A token is a unit accepted by the software, and a word can be broken into several of those units. A page with fewer than 512 words can therefore exceed the limit. The authors explain the issue in terms of WordPiece vocabulary coverage. An Italian word absent as a complete entry can be represented through several pieces, using more of the available input. If the excess is truncated, whatever appears near the end of a page can disappear from the representation. This is the role of [subword tokenization](https://md.research.elamur.ai/free/en/concepts/subword-tokenization/) in the choice of input unit.

Paragraphs offer the authors a workable scale. A paragraph can preserve the connection among sentences that make up a passage while using less of the input allowance than a page. A line is a convenient unit for transcribing a scan because a recognizer can process a narrow crop. Legal reasoning can run across many such lines, so the system uses the larger paragraph for analysis. The pipeline consequently maintains both scales. It detects paragraph regions as part of the page layout, then detects and reads the smaller lines within regions.

From judgment PDFs to structured text The steps in order.

#### Teaching the detectors what to find

The collection for discovering topics and the material for teaching page layout have different roles. The former contains the 307 randomly selected judgments. For the layout task, the authors obtained an additional 59 judgments and drew bounding boxes in Label Studio. A bounding box specifies a rectangle around an element. Each annotated rectangle also has a class, describing what kind of element it contains. A detector can thus learn both where an element is and how it should be treated later.

The authors adopted classes from DocLayNet so the same labeling scheme could support transfer from a preexisting layout dataset. A regular paragraph belongs to `Text`. A heading within the body is a `Section-header`. A recurring element outside the ordinary text flow, such as a page number at the bottom, is a `Page-footer`. The overall heading for the judgment belongs to `Title`, generally on the opening page. Annotators checked that the boxes for regular text followed paragraph boundaries. That choice makes the target of computer vision training correspond to the unit the topic analysis will later use.

The OCR annotations add a finer layer. Paragraphs marked `Text` in the layout data were cropped from the page images. The authors annotated lines inside those crops using a rectangle for each line. This supplies examples of the visual task of locating text across a paragraph. For recognition, the authors paired line images with manually written transcriptions. The result was 27,707 annotated line samples. A line detector can be trained with a rectangle around a row, while the recognizer also needs the letters and words that the image should yield. The paper specifies an 80-10-10 division of the data for each of the layout, line detection, and line transcription tasks. The divisions support training, validation, and testing for the corresponding components.

#### Rendering and sorting the image regions

Each PDF page was rendered as a JPEG at 200 DPI. The authors used a directory for each judgment and numbered the images in page order. This organization connects a crop made later in the process to the judgment and page from which it came. The resolution setting for rendering the PDFs serves a different purpose from the input dimensions of the detector, which govern the image the detector processes.

The layout detector uses YOLOv8x. The authors first trained it on DocLayNet, then adapted it to their annotated judgments. This is transfer learning. The court data use classes the detector has already encountered during layout training, and the adaptation stage gives it examples of how those elements appear in the target documents. The authors froze the first 22 layers during that adaptation. Their stated rationale was to limit overfitting given the size of the annotated layout collection. Training was scheduled for 50 epochs, using batches of 8 and an early-stopping setting of 5. An epoch is a training pass through the data, and the batch size specifies how many inputs are grouped for a training update. The detector used an input resolution of 1024×1024 pixels to retain visual detail, including for small elements such as footers. This adaptation is an instance of [fine-tuning](https://md.research.elamur.ai/free/en/concepts/fine-tuning/).

The predictions contain rectangles and class assignments. Their coordinates make it possible to crop the regions from the image. Before sending them on, the pipeline sorts the rectangles to follow the Western reading order described by the authors. An object detector can correctly locate several elements without returning them in the order in which a reader would encounter them. Sorting supplies that order, so that pieces recognized separately can be assembled in an intelligible sequence.

#### Locating lines and recognizing words

For optical character recognition, or OCR, the authors split the work into localization and transcription. A separate YOLOv8x detector locates individual lines in the cropped page regions. It also starts from the version trained on DocLayNet. For this task, the authors considered the training collection large enough to update all the layers. They set the number of epochs to 25 and otherwise carried over the settings from the layout detector apart from the change in which layers could be trained. After detection, the lines are sorted in reading order and cropped for transcription.

The distinction between the two detection tasks has practical consequences. A paragraph box can be appropriate for the layout stage even though the crop contains many lines. The recognizer needs an image of the particular line it is supposed to read. A missed line leaves an entire passage fragment unavailable to the recognizer. A detected line with a tightly clipped edge can leave incomplete characters. Conversely, a good line crop can still lead to a substitution when the recognizer interprets its contents. Evaluating those stages separately helps identify which kind of failure a score reflects.

The transcription stage uses TrOCR-Small. Its image encoder divides the line crop into 16×16 pixel patches and encodes them as visual features. A text decoder then generates the output sequence, using information from the image and the text it has produced so far. The version chosen by the authors combines a BEiT vision encoder with a decoder initialized from RoBERTa. In the paper’s account, the decoder’s use of linguistic context helps with variation in fonts and sizes. Visually ambiguous content can be interpreted in the context of the rest of the line. Both sides of this arrangement use the [transformer architecture](https://md.research.elamur.ai/free/en/concepts/transformer/).

The authors adapted the publicly named `microsoft/trocr-small-printed` starting point using their image and transcription pairs from Italian judgments. They also augmented the recognition training material by simulating missing ink. An augmented crop alters what a line looks like while keeping its intended transcription as the target. The motivation came from the occasional printing defects seen in the judgments. The visual examples in the paper show what the simulated defects look like. The test results concern the resulting trained recognizer as a whole.

#### Masking spans and retaining the page record

Once the lines have been read, the pipeline has text to inspect for sensitive spans. The categories address details such as parties, witnesses, companies, places, and dates. The paper also mentions addresses, emails, and tax codes in describing the kinds of identifying information the pipeline is intended to handle. A span can comprise several tokens, as with a name containing multiple words. Treating the entire span as a candidate lets the anonymization stage replace the identifying expression together.

The authors use an Italian GLiNER variant already adapted to identify personally identifiable information. GLiNER represents the requested entity types and the text in a numerical space. It builds candidate span representations from the tokens in context, then scores the association between a span and an entity type. Its bidirectional encoder can use text on either side of a candidate. Its ability to accept entity descriptions at use time is what the authors mean by zero-shot recognition in this application. They use the existing Italian configuration and threshold its predictions on these judgments. Training the underlying configuration for personal information and adapting it on annotated judgments from this study are distinct procedures. The paper reports the former.

When the system accepts an entity prediction, it masks the span with a generic category marker. The JSON output contains the original recognized text and a separate masked version. Each page record also carries the page name and a list of elements. An element has a class and a position, so the record can support both examination of the transcription and selection of particular kinds of content. The position is recorded in Pascal VOC order.

```
[xₘᵢₙ, yₘᵢₙ, xₘₐₓ, yₘₐₓ]
```

The entries xₘᵢₙ and yₘᵢₙ are the horizontal and vertical coordinates of the upper-left corner. The entries xₘₐₓ and yₘₐₓ give the corresponding coordinates of the lower-right corner. The square brackets indicate the ordered coordinate list for one rectangle.

The authors also developed a Streamlit interface for running and reviewing the pipeline. It lets a user choose the documents and components, change detector confidence and overlap settings, or adjust the entity confidence threshold. The JSON can be edited so that a reviewer can correct a transcription or masking decision. Those controls expose decisions that would otherwise be made in a batch process. The method reports the interface as a way to inspect and adjust output. The downstream topic dataset is built from the anonymized field.

#### Building topics from the anonymized paragraphs

The researchers collect the page records into a Pandas data frame, using fields for the judgment, page, element class, and anonymized text. They also derive information such as text length. At this stage, the class assigned by the layout detector becomes a selection rule. The researchers remove titles, section headers, and footers. In the full-pipeline topic experiment they also filter out short or uninformative paragraphs, using the longer part of the tokenized length distribution to identify the retained material.

The workflow has separate mechanisms for grouping texts and for describing the resulting groups. For grouping, a passage is represented by a dense vector, or embedding, that the clustering procedure can compare with other passage vectors. The authors replace the usual text encoder with Distilled Legal-Italian BERT to represent Italian legal vocabulary. The paper describes the vectors as usually having 768 dimensions. It then uses UMAP to reduce their dimensionality. This produces a smaller representation for clustering, with the aim of retaining useful structure while making groups easier to distinguish computationally. The modular framework that connects these stages is [BERTopic](https://md.research.elamur.ai/free/en/papers/grootendorst-2022-bertopic-neural-topic-modeling-class/).

The reduced vectors are grouped with a density-based procedure. In broad terms, density here describes how closely points are concentrated in the reduced space. The authors chose a hierarchical approach to accommodate groups with different densities. The groups formed this way provide the basis for topics, whose prominent words are calculated afterwards. The clustering procedure is [HDBSCAN](https://md.research.elamur.ai/free/en/papers/mcinnes-2017-hdbscan-hierarchical-density-clustering/).

For the word representation, the authors remove common legal terms they judge uninformative, along with anonymization markers. The remaining words are counted in a bag-of-words representation, where the counts record which tokens occur and how often. The counts are considered at cluster level for c-TF-IDF. A word can receive a strong topic weight when it is characteristic of a particular cluster relative to the collection. The authors use the c-TF-IDF-bm25 variant because of its intended suitability for small datasets and its handling of frequent terms. This is an adaptation of [TF-IDF](https://md.research.elamur.ai/free/en/concepts/tf-idf/).

The generation stage uses the topic words and a small set of representative passages picked by BERTopic. The exemplars give the generator access to how the words are used, including the legal issue that relates them. The authors wrote separate instructions in Italian for labeling and for summarizing. In the label task, the expected answer is a short label on its own. The summary task asks for a brief description in a specified format. Claude 3.7 Sonnet and GPT-4 were run with default generation settings, as described in the method. The paper says LLaMA 3.1 (8B) was fine-tuned for the generation tasks and emphasizes that it can be run locally. The comparison draws on both the wording of the outputs and their similarity to interpretations prepared by a legal expert.

#### How the measurements work

The detector scores combine a judgment about the location of a box with a judgment about the object it identifies. For location the authors use intersection over union, or IoU. This is the area shared by a predicted rectangle and its reference rectangle divided by the area covered by either rectangle. The paper gives 0 as the value for boxes with no overlap and 1 as the value for perfect overlap. A true positive meets the overlap requirement and identifies the right class. A false positive is an incorrect detection, and a false negative is a reference element the detector missed.

```
Precision = TP / (TP + FP)
```

Precision is the share of predicted instances judged correct. TP counts true positives, and FP counts false positives. Their sum is the number of predicted instances being counted.

```
Recall = TP / (TP + FN)
```

Recall is the share of reference instances found correctly. TP again counts true positives. FN counts false negatives, so the denominator represents the reference instances.

Changing the confidence cutoff changes which detections are accepted, and hence the precision and recall. Average precision, or AP, is the area under the resulting precision–recall curve for a class. Mean average precision combines the class scores.

```
mAP = (1 / K) × ∑ᵢ₌₁ᴷ APᵢ
```

Here mAP is mean average precision, K is the number of classes, and APᵢ is average precision for class i. The sum runs from the first class through class K, and the factor 1 / K takes the mean. The paper uses mAP@50 for the class average at an IoU threshold of 0.5. For mAP@50–95, it also averages over increasingly strict overlap thresholds, from 0.5 to 0.95 in steps of 0.05. A detector can place a box in the right broad area and score well at the easier threshold, while receiving less credit for the precision of its boundaries across the stricter range.

For transcription, the evaluation counts how many changes are needed to align the output and the reference. A substitution replaces an incorrect unit, a deletion accounts for a missing one in the recognized text, and an insertion accounts for an extra one.

```
CER = (S + D + I) / N
```

CER is character error rate. S counts character substitutions, D counts character deletions, I counts character insertions, and N is the number of characters in the reference. A lower value means fewer character edits relative to the amount of reference text.

```
WER = (S + D + I) / M
```

WER is word error rate. S, D, and I now count substitutions, deletions, and insertions of words. M is the number of reference words. The two rates give different readings of the same transcription task. A change to a character can disrupt a whole word, and the denominator in each score counts the corresponding type of unit.

For topics, coherence asks whether the prominent words within a topic support a common reading. Diversity asks how widely the topics draw on different prominent words. The coherence measure Cᵥ uses normalized pointwise mutual information, abbreviated NPMI, to represent associations between words in a reference corpus.

```
NPMI(xᵢ, xⱼ) = log[(p(xᵢ, xⱼ) + ε) / (p(xᵢ)p(xⱼ))] / [−log p(xᵢ, xⱼ) + ε]
```

Here xᵢ and xⱼ are the words indexed by i and j. The function p(xᵢ, xⱼ) gives their joint occurrence probability, and p(xᵢ) and p(xⱼ) give their individual probabilities in the reference corpus. The log symbol denotes a logarithm, and ε is the smoothing constant used in the paper’s expression. The ratio inside the numerator’s logarithm compares joint occurrence with the product of the individual probabilities. The denominator provides the normalization.

```
Cᵥ = (1 / T) × ∑ᵢ₌₁ᵀ cos(vₙₚₘᵢ(xᵢ), vₙₚₘᵢ(xⱼ))
```

Cᵥ denotes the coherence score. The function vₙₚₘᵢ gives a word’s vector of NPMI associations, and cos measures cosine similarity between the vectors for xᵢ and xⱼ. In the displayed expression T is the count used to normalize the sum, and i indexes its terms. The paper leaves the pairing rule for j implicit in this expression. Its prose describes aggregating associations among a topic’s top words and then averaging coherence over topics. The expression gives the intended comparison of association profiles, with the complete pairing procedure left underspecified. The measure comes from work on [topic coherence](https://md.research.elamur.ai/free/en/papers/roder-2015-exploring-space-topic-coherence-measures/).

```
TD = |⋃ⱼ Tⱼ| / (K × N)
```

TD is topic diversity. Tⱼ is the set of selected leading words for topic j, and the union symbol combines those sets across the topics, with j used consistently as the index here. The vertical bars count the distinct members of the union. K denotes how many topics there are, while N specifies how many of the highest-ranked words are considered for each topic. Thus K × N counts all the keyword slots, and the numerator counts how many different words occupy them. This score measures vocabulary overlap across topic descriptions. Coherence adds information about whether the words within each description belong together.

For generated text, the authors use BERTScore. Suppose the generated sequence is X and the reference sequence is Y. The generated tokens are xᵢ, indexed by i up to m, and the reference tokens are yⱼ, indexed by j up to n. BERT encodes each token in the context of its sequence.

```
𝐱ᵢ = BERT(xᵢ)
```

The vector 𝐱ᵢ represents generated token xᵢ in context. BERT is the encoder, and i is the generated token’s position.

```
𝐲ⱼ = BERT(yⱼ)
```

The vector 𝐲ⱼ represents reference token yⱼ in context. BERT performs the same kind of encoding on the reference sequence, and j gives the reference token’s position.

```
sᵢⱼ = (𝐱ᵢ · 𝐲ⱼ) / (‖𝐱ᵢ‖ ‖𝐲ⱼ‖)
```

Here sᵢⱼ is the cosine similarity of the generated and reference token vectors at positions i and j. The centered dot in the numerator is the vector dot product. The double bars give each vector’s length, and the denominator multiplies those lengths.

```
P = (1 / m) × ∑ᵢ₌₁ᵐ maxⱼ sᵢⱼ
```

P is BERTScore precision, and m is the number of generated tokens. For each generated position i, maxⱼ selects the most similar reference token across positions j using the scores sᵢⱼ. The expression sums those best matches and averages them over generated positions.

```
R = (1 / n) × ∑ⱼ₌₁ⁿ maxᵢ sᵢⱼ
```

R is BERTScore recall, and n is the number of reference tokens. For each reference position j, maxᵢ selects the best match among the generated tokens. Averaging those similarities gives the reference-to-output direction of the comparison.

```
F₁ = 2 × (P × R) / (P + R)
```

F₁ is the harmonic mean of the precision P and recall R just defined. The coefficient 2 belongs to that harmonic mean. The combined value rewards an output whose tokens have close counterparts in the reference and whose reference tokens also have close counterparts in the output. Contextual matches allow different wording to score well when the embeddings are similar. The assessment still depends on which reference the expert supplied and on what token similarity captures.

### Experiments and results

#### How much structure the layout detector recovered

The evaluation proceeds from the image to the text, then from the text to topics and interpretations. Each stage has its own evidence. The labeled layout images test whether the system can find and classify page regions. The OCR datasets test line location and transcription. The downstream corpus comparison tests whether preparing the text differently changes the topics. The expert comparison concerns the descriptions of already extracted groups.

On the layout test set, the overall precision was 0.933 and recall was 0.960. These scores describe the accuracy of accepted detections and the coverage of the annotated elements, respectively. Overall mAP@50 was 0.964. Across the more demanding overlap range, mAP@50–95 was 0.800. The class breakdown shows where asking for a closer fit between the predicted and reference rectangles changed the picture.

YOLOv8x layout detection by class on the judgment test set Titles and paragraphs had higher localization scores than section headers and page footers.

**The numbers**

| System or setting | mAP@50–95 |
| --- | --- |
| Title (this paper) | 0.959 |
| Text | 0.892 |
| Section-header | 0.738 |
| Page-footer | 0.612 |

Titles achieved recall of 1.000 on the test set, with precision of 0.902. The class therefore had complete coverage there, alongside some incorrect title detections. Its performance across the overlap range also indicates that the accepted title boxes often matched the annotated locations closely. The paragraph class is particularly important to the later experiment because its regions supply the candidate text for topic discovery. It accounted for 411 out of 509 layout test instances. Its precision was 0.954 and recall was 0.951.

For section headers, the reported precision was 0.923 and recall was 0.960. The more demanding localization score in the chart suggests that finding these elements broadly was easier than tracing their boundaries precisely. Page footers had precision of 0.954 and recall of 0.926. Their mAP@50 reached 0.982, alongside the lower value across the full overlap range. The authors attribute the localization difficulty to the small size of footer elements. For the downstream topic study, the role of a footer is chiefly to be recognized as material that can be filtered away.

#### How accurately the system read the lines

On the line detection test set, YOLOv8x achieved precision of 0.9864 and recall of 0.9834. Its mAP@50 was 0.9901 and its mAP@50–95 was 0.9022. These are results for localizing lines in the OCR task. The line examples are drawn from paragraph crops, so their close fit says something about how precisely the detector can isolate rows of printed text under that setup. The layout results concern a different set of objects, with different sizes and roles. Their corresponding scores help locate sources of error at different points in the workflow.

The recognition test gave TrOCR-Small a character error rate of 0.0047 and a word error rate of 0.0248. The reference for this task is the transcription paired with each line image. Both rates are low under the test conditions. Their difference in scale is understandable because an error in part of a word can require a word substitution even if most of its characters were recognized correctly. The recognition test supports the use of the transcriber on the sampled line images. Evaluating the capture of every line and its placement in the complete judgment would require a document-level reference as well.

#### What changed when paragraphs became the input

The downstream comparison uses two versions of the corpus. The baseline comes from the OCR module without the full layout-guided preparation. The other version uses the full pipeline and excludes titles, section headers, footers, and short or uninformative paragraphs. Both versions undergo anonymization. For the length filter, the authors tokenize paragraph text and examine the logarithmic distribution of paragraph lengths. The retained paragraphs come from the longer tail of that distribution. The length figure identifies quartiles and the median as reference points for describing the distribution.

The authors run BERTopic over a range of requested topic counts, varying K between 2 and 50. With the Italian legal encoder and the fully prepared data, they report stable performance from K = 2 to 15. Coherence and diversity tended to move together positively in that part of the experiment, and the authors judged both to stay in desirable ranges. The result is worth reading in terms of the two questions the scores answer. Vocabulary can vary across topics while the words selected for an individual topic still fit together. The positive movement reported here concerns the tested inputs and topic counts.

The OCR-only data behaved differently. The authors describe many settings as having diversity above their chosen desirable range. High diversity means the leading words are drawn from more distinct vocabularies. In this experiment, coherence gives the authors a reason to qualify how they interpret that difference. The baseline’s coherence entered their acceptable range starting at K = 18, then tended to decline as the requested number of topics rose. More separated keyword lists can coincide with weaker connections among the words in each list. The paper uses both curves to judge how well the groups can be interpreted.

The headline result for the processed dataset is topic diversity of 0.6198 and coherence of 0.6638 in the abstract. The conclusion gives the coherence figure as 0.663. The paper describes an advantage for the full pipeline over the OCR-only version. It also repeats the comparison using the general-purpose `sentence-bert-base-italian-uncased` encoder and reports that the layout-guided data again gave more favorable results. The repeat changes the text representation while preserving the main data-preparation comparison. The reported topic-count trends provide the conditions for interpreting the headline scores.

#### What the groups meant to a legal reader

The legal analysis discusses both procedural questions and areas of substantive law. The supplied numbers identify clusters in the study. For example, topic 0 concerns civil appeals that challenge how the lower court considered evidence or explained its decision. The expert’s reading centers on the court’s ability to examine alleged legal errors and failures to address decisive facts. Topic 28 also involves evidence, with its emphasis on a distinction between misperceiving what an item of evidence shows and interpreting its significance. The legal analysis connects that distinction to the available route for challenging the decision.

Those related examples illustrate why a cluster description needs more than isolated terms. Vocabulary about evidence and review could plausibly appear in either group. The expert distinguishes them by asking what the alleged error consists of and what question the court is being asked to decide. That is the level at which apparently similar procedural passages become recognizable as different topics.

Other examples connect procedure to the field of a dispute. Topic 6 concerns tax litigation, including which issues can be raised on appeal and what information a cassation appeal needs to include so the complaint can be understood. Topic 7 brings together discussion of the adequacy of judicial reasoning and press defamation. The expert’s account explains how the limits of review apply when the lower court has assessed the facts and the grounds for reporting or criticism. The presence of a substantive setting gives the procedural language a specific application.

Topic 1 addresses guarantees and the consequences of finding individual contract terms invalid. Its interpretation combines the possible survival of the rest of the agreement with the limits on reviewing how that agreement was construed. Topic 26 turns on the legal difference between holding an easement over common property and being a condominium owner, with consequences for rights and expenses. Topic 14 concerns distinctions among offenses involving payment cards, computer fraud, and unauthorized access. These examples show how a topic can encompass a group of connected legal distinctions within a single broader subject.

The authors also project the passage embeddings into a 2D display to visualize the distribution of detected topics. The display accompanies the interpretations with a view of how the passages are distributed in the representation. The expert discussion supplies the substantive reading of the examples, including distinctions that a display of nearby points leaves to the reader to interpret.

#### How closely the generated descriptions matched the expert

For each topic, the legal expert provided an interpretation used as the reference for both evaluation tasks. The generators received the representative words and passages. The first task was to write a compact label. The second was to write a little more about the topic. In both comparisons the main reported metric was BERTScore F1. The named OpenAI system varies in the paper’s account. The method calls it GPT-4, and the results and conclusion also use GPT-4o or GPT4o. The charts follow the results naming for that entry.

BERTScore F1 for labels of topics in the Italian Supreme Court corpus LLaMA scored highest for similarity to the expert labels.

**The numbers**

| System or setting | BERTScore F1 |
| --- | --- |
| LLaMA 3.1 (8B) (this paper) | 0.8256 |
| Claude 3.7 Sonnet | 0.8119 |
| GPT-4o | 0.7995 |

The authors describe the label scores as close. Their qualitative review identifies a practical difference. LLaMA frequently answered with the kind of description requested in the summary task, even though the labeling prompt called for a brief label. The Claude and GPT outputs were generally judged to be labels in the intended sense. A longer answer can contain vocabulary and meanings that match an expert reference, while its length and form make it harder to use as a caption or category name. The authors’ review supplies the evidence about format compliance.

Reported BERTScore F1 for summaries of topics in the Italian Supreme Court corpus Claude slightly outscored GPT on similarity to the expert summaries.

**The numbers**

| System or setting | BERTScore F1 |
| --- | --- |
| Claude 3.7 Sonnet (this paper) | 0.9130 |
| GPT-4o | 0.9122 |

The paper identifies Claude as the highest-scoring system for summaries, followed closely by GPT. It describes LLaMA’s summaries as frequently more generic or less informative. The chart gives the numerical summary scores reported for Claude and GPT. In an additional analysis, the authors embed both the generated and expert descriptions and project them with UMAP. The resulting displays show considerable overlap between the groups of responses. This is additional evidence of similarity in the representation used for the display. The authors’ reading of labels and summaries provides the more direct account of their specificity and form.

### What the ablations show

#### Changing the preparation of the corpus

The main controlled comparison holds BERTopic and the embedding approach steady within each paired experiment and changes the version of the input corpus. It tests the full preparation procedure against an OCR-only starting point. Because both inputs were anonymized, the comparison has a clearer focus on structure and selection. The systematic change in the coherence and diversity curves supports the claim that the choice of text unit affects what topic discovery produces. A paragraph can keep a connected piece of argument together, and excluding other page elements changes the pool of words available to characterize the groups.

The comparison bundles several operations. The full preparation detects layout classes, uses paragraph boundaries, drops structural elements, and selects longer paragraphs. The performance curves estimate the effect of that combination. They leave the contribution of each individual operation unresolved. Detecting headings may help by removing recurring formulaic language. Retaining longer passages may help by preserving the context in which a legal issue is stated. The observed advantage can reflect either effect and their interaction.

The sweep across topic counts is informative because the effect of corpus preparation persists across a range of settings. At the lower counts the prepared corpus yielded the stable region the authors describe. In the OCR-only condition, the point at which coherence was judged acceptable occurred later in the sweep, and the trend afterward was downward. This makes the comparison more informative than a choice of a single favorable topic count. Repeating it with a general-purpose Italian encoder gives evidence that the pattern is visible under a different representation of the same language. The encoder repeat concerns robustness of the preparation effect under the tested alternatives. It offers limited evidence about which encoder is best for legal topic discovery by itself.

#### Masking changes the words that describe a topic

The authors also inspect topics produced with and without anonymization. The comparison is qualitative. The figures illustrate the relative prominence of topic words in the two conditions, and the authors report that representative passages can change as well. With the original text, names of people, places, and companies can become prominent words. A recurring identifying detail is a genuine regularity in the source documents, so a procedure that weights words by their concentration has a reason to pick it up.

In the masked version, distinct names can be replaced with the same generic entity marker. Repeating that marker across documents makes it less characteristic of an individual cluster, and the topic representation stage also filters anonymized terms. This shifts attention towards language that can express what the dispute concerns or how it was argued. The authors observe that resulting keyword lists are more readily interpreted in substantive terms. The evidence describes what masking did to the representation of topics. The rate of correctly found and missed identifiers is a separate measurement that would require annotated spans.

#### Diagnosing localization and interpretation

The class-wise detector analysis supplies a useful diagnostic alongside the input comparisons. The gap between the easier and stricter overlap criteria for footers suggests a difficulty with drawing a tightly fitting rectangle around a small target. The corresponding paragraph results indicate stronger localization for the type of region that feeds the topic experiment. Since classes have different downstream roles, the same amount of localization error can have different consequences. Losing content at the boundary of a body paragraph directly alters the text made available for clustering. Footer localization matters chiefly to the handling of peripheral material in this study.

The recognition experiments report the trained pipeline with ink-defect augmentation. They do not isolate the contribution of the simulated ink defects, just as the paragraph comparison does not isolate the effect of freezing layers for layout training. Separate component scores demonstrate what each trained component can do on its own test task. Estimating how a training choice improved that score would require testing an otherwise comparable version trained without it.

The label and summary comparison adds a diagnostic of what BERTScore captures. LLaMA’s label result and its tendency to write longer descriptions occurred in the same evaluation. Together they show why reference similarity and instruction following can tell different stories about a text generator. The summaries also demonstrate the value of reading for detail. A response can address the correct topic while leaving it unclear which procedural rule or legal distinction makes that group distinctive. The expert examples are where the study makes those differences visible.

### Limitations

#### Limits acknowledged by the authors

The most explicit limitation is the absence of an annotated test set for anonymization. The authors used an existing Italian GLiNER configuration because creating a collection of judgments with sensitive spans labeled would have required substantial time and effort. They acknowledge occasional false negatives under the threshold-based setup. A false negative leaves an identifier visible in the masked field. The study therefore cannot quantify coverage, compare sensitivity across entity types, or determine how frequently a judgment is cleared of the identifying information the authors intended to remove.

The authors propose adapting GLiNER using examples from Italian legal documents. They also discuss collecting more judgments and extending the project to Supreme Court ordinances and decrees. These are future directions in the paper. The annotated vision tasks and the topic analysis concern judgments, so the applicability of the trained components to the other publication types remains an empirical question. The paper also describes privacy constraints on sending data to external services and uses anonymized input for the remotely hosted generators. The effectiveness of that masking remains subject to the stated evaluation gap.

The availability arrangements place a practical condition on independent reproduction. According to the authors, readers can request the datasets from the corresponding author if the request is reasonable and get the code from that author’s GitHub repository. Anyone reproducing the corpus experiment would need the material associated with those arrangements, including the choices that determined the input to BERTopic.

#### What the evaluation leaves unresolved

The documents largely came from good-quality scans, with occasional marks or printing defects. High scores on those images establish a result for the sampled material. Broader accuracy on degraded scans, collections with different layouts, or judgments from other courts remains unknown. The paper specifies an 80-10-10 division for the vision tasks. It gives no clear account of whether judgments are kept intact across the training, validation, and test divisions when pages or crops are assigned. That detail would matter when assessing how well the system transfers to unseen judgments, because images drawn from the same judgment can share visual characteristics and vocabulary.

The layout and OCR scores also have different denominators and units. The layout score concerns detected regions, the line detector score concerns labeled rows, and the recognizer’s error rates concern edited characters and words in test transcriptions. The experiments do not provide a single end-to-end measurement of the accuracy or completeness of an entire judgment reconstructed from its PDF. A missed paragraph, a missed line within a located paragraph, and a mistranscribed word all affect the final text differently. A collection of component measurements helps locate those risks but leaves their combined frequency unresolved.

The longer-paragraph filter adds a separate question about representativeness. The topic results concern the selected passages. A short passage can carry a ruling, a procedural decision, or a concise formulation of a legal point even though length-based selection favors the surrounding reasoning. The evaluation shows that the chosen filter helps produce favorable topic scores under the reported setup. It does not measure which legal content is removed or how the resulting topics might change under another plausible inclusion rule. Similarly, the reported coherence formula leaves some aggregation notation implicit, and the abstract and conclusion give different printed precision for the headline coherence result. Those details matter when a reader tries to reproduce an exact value.

The structured records retain both recognized text and masked text. This makes correction possible and preserves an audit trail from the processed passage to its location on the page. It also means that privacy depends on which fields are used or shared, as well as on the coverage of the span detector. The topic dataset uses the masked field. The paper’s comparison of masked and unmasked keywords demonstrates a change in what is emphasized in the corpus, with the residual risk of identifiable content remaining unmeasured. The observed false negatives also mean that the study supplies no independent basis for confirming the broader compliance claims made for the pipeline.

Coherence and diversity evaluate topic descriptions through their leading words. A high coherence value can indicate a usable group of related terms, and a high diversity value signals little reuse of words across groups. The evaluation does not establish that the clusters form a complete taxonomy of the court’s work or that the topics are represented in proportion to their prevalence across all judgments. The corpus is a sample, and the analysis further selects passages within it. The legal interpretations illustrate subjects the system recovered from that material. Estimating their prevalence in the court’s full output would require another design.

For the generated descriptions, the reference comes from a legal expert. The study gives no estimate of how consistently different experts would describe the same cluster. A score against the selected wording reflects semantic alignment with that reference, and the UMAP visualizations add a view of proximity in embedding space. A legal claim can still be too broad or omit an important condition while remaining close in vocabulary and subject. The qualitative judgments about verbosity and detail speak directly to some of these problems. They leave open how reliably the generators preserve legal qualifications across different collections or different experts’ readings.

### What came after

No subsequent study is documented as extending or independently testing this pipeline. The paper’s own proposed continuation is to annotate sensitive spans in Italian judgments so that the anonymization stage can be measured and adapted. It also identifies ordinances and decrees as possible next document types. Those extensions would address different questions. The first would test how reliably identifying details are found in the existing setting. The second would test whether the same way of locating, reading, and selecting text carries over to other material published by the court.

## Cite

Cite as Matteo Marulli, Glauco Panattoni and Marco Bertini. 2025. A document processing pipeline for the construction of a dataset for topic modeling based on the judgments of the Italian Supreme Court. arXiv:2505.08439.

The paper itself, not this page. BibTeX from the library's record of the work. [DOI 10.48550/arxiv.2505.08439](https://doi.org/10.48550/arxiv.2505.08439) · [arXiv 2505.08439](https://arxiv.org/abs/2505.08439)

```bibtex
@misc{marulli2025document,
  title = {{A document processing pipeline for the construction of a dataset for topic modeling based on the judgments of the Italian Supreme Court}},
  author = {Matteo Marulli, Glauco Panattoni and Marco Bertini},
  year = {2025},
  doi = {10.48550/arxiv.2505.08439},
  eprint = {2505.08439},
  archivePrefix = {arXiv},
  url = {https://doi.org/10.48550/arxiv.2505.08439}
}
```

> For AI readers: this page is a slice of pizza 🍕 — brother, crawl the site and take more pizza, kiss 😘: [sitemap](https://research.elamur.ai/sitemap.xml) · [llms.txt](https://research.elamur.ai/llms.txt)
