You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@tika.apache.org by ta...@apache.org on 2026/10/19 21:38:13 UTC
(tika) branch main updated: TIKA-4972: try to do what we can with vlm ocr engines (#3348)
This is an automated email from the ASF dual-hosted git repository.
tballison pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/tika.git
The following commit(s) were added to refs/heads/main by this push:
new 67aea63ea2 TIKA-4972: try to do what we can with vlm ocr engines (#3348)
67aea63ea2 is described below
commit 67aea63ea2b147d8de2d75e7655947ed4f205d16
Author: Tim Allison <ta...@apache.org>
AuthorDate: Mon Oct 19 17:38:07 2026 -0400
TIKA-4972: try to do what we can with vlm ocr engines (#3348)
---
.skills/devs/development/SKILL.md | 21 ++
CHANGES.txt | 7 +
docs/modules/ROOT/examples/jina-ocr-basic.json | 16 ++
docs/modules/ROOT/pages/configuration/index.adoc | 57 ++++-
.../ROOT/pages/configuration/inference.adoc | 5 +-
.../pages/configuration/parsers/vlm-parsers.adoc | 59 +++++-
.../pages/migration-to-4x/migrating-to-4x.adoc | 2 +-
pom.xml | 4 +-
.../tika/annotation/TikaComponentProcessor.java | 1 +
tika-app/pom.xml | 6 +
.../apache/tika/cli/TikaCLIOcrWarningsTest.java | 161 ++++++++++++++
tika-bom/pom.xml | 5 +
.../apache/tika/metadata/TikaCoreProperties.java | 8 +
.../tika/parser/enricher/ContentEnrichers.java | 4 +-
.../{SizeGatedEnricher.java => GatedEnricher.java} | 56 ++---
.../apache/tika/parser/enricher/ImageCheck.java | 66 ++++++
.../apache/tika/parser/enricher/ImageProbe.java | 139 ++++++++++++
.../apache/tika/parser/enricher/OcrWarnings.java | 63 ++++++
...zeGatedEnricher.java => RecordedSizeCheck.java} | 47 ++---
.../tika/parser/enricher/SizeGatedEnricher.java | 15 +-
.../tika/parser/enricher/ContentEnrichersTest.java | 5 +-
.../tika/parser/enricher/GatedEnricherTest.java | 164 +++++++++++++++
.../tika/parser/enricher/ImageProbeTest.java | 94 +++++++++
tika-image-processing/pom.xml | 145 +++++++++++++
.../tika/imageprocessing/BlankImageCheck.java | 138 ++++++++++++
.../apache/tika/imageprocessing/ByteSizeCheck.java | 81 +++++++
.../apache/tika/imageprocessing/ImageDecoding.java | 232 +++++++++++++++++++++
.../tika/imageprocessing/MinImageSizeCheck.java | 108 ++++++++++
.../tika/imageprocessing/BlankImageCheckTest.java | 198 ++++++++++++++++++
.../tika/imageprocessing/ByteSizeCheckTest.java | 82 ++++++++
.../imageprocessing/ImageChecksConfigTest.java | 161 ++++++++++++++
.../tika/imageprocessing/ImageDecodingTest.java | 88 ++++++++
.../apache/tika/imageprocessing/ImageFixtures.java | 77 +++++++
.../imageprocessing/MinImageSizeCheckTest.java | 121 +++++++++++
.../apache/tika/metadata/metadata-key-fields.json | 3 +
.../org/apache/tika/metadata/metadata-keys.json | 3 +
.../java/org/apache/tika/http/TikaHttpClient.java | 44 +++-
.../org/apache/tika/http/TikaHttpClientTest.java | 86 ++++++++
.../org/apache/tika/http/TikaTestHttpServer.java | 12 ++
.../tika/inference/OpenAIEmbeddingEngine.java | 2 +-
.../apache/tika/parser/vlm/AbstractVLMParser.java | 103 +++++++--
.../apache/tika/parser/vlm/ClaudeVLMParser.java | 9 +-
.../apache/tika/parser/vlm/GeminiVLMParser.java | 7 +
.../apache/tika/parser/vlm/OpenAIVLMParser.java | 7 +
.../org/apache/tika/parser/vlm/VLMOCRConfig.java | 22 +-
.../tika/parser/vlm/ClaudeVLMParserTest.java | 26 +++
.../tika/parser/vlm/GeminiVLMParserTest.java | 18 ++
.../tika/parser/vlm/OpenAIVLMParserTest.java | 213 ++++++++++++++++++-
.../tika/parser/vlm/VLMConfigExamplesTest.java | 30 ++-
.../tika/parser/vlm/VLMOperatorOnlyConfigTest.java | 3 +-
.../tika/parser/vlm/VLMPdfPageEndToEndTest.java | 109 ++++++++++
.../resources/config-examples/jina-ocr-basic.json | 16 ++
.../apache/tika/parser/pdf/AbstractPDF2XHTML.java | 12 ++
.../org/apache/tika/parser/pdf/PDFParserTest.java | 68 ++++++
.../tika/config/loader/ContentEnricherLoader.java | 95 +++++++--
.../config/loader/TikaObjectMapperFactory.java | 1 +
.../config/loader/ContentEnricherLoaderTest.java | 49 ++++-
tika-server/tika-server-standard/pom.xml | 6 +
58 files changed, 3256 insertions(+), 124 deletions(-)
diff --git a/.skills/devs/development/SKILL.md b/.skills/devs/development/SKILL.md
index 7735d333a6..31407ae236 100644
--- a/.skills/devs/development/SKILL.md
+++ b/.skills/devs/development/SKILL.md
@@ -133,6 +133,27 @@ personal configuration does not override it.
-Dmaven.repo.local=$(pwd)/.local_m2_repo
```
+## Building the Docs
+
+`docs/` is not in the default reactor; build it from its own pom. Antora
+renders the checked-out branch from the worktree, so uncommitted `.adoc`
+edits are included.
+
+```bash
+./mvnw -f docs/pom.xml clean package # site in docs/target/site/tika/<version>/
+```
+
+- **Broken links don't fail the build** (`--log-failure-level=fatal`). Check
+ the log for `ERROR (asciidoctor)` lines such as `target of xref not found`.
+- **Parent-directory npm leaks in.** The Antora plugin runs `npx` in `docs/`,
+ which has no `package.json` or `node_modules`, so npm and Node search
+ upward. A `package.json` or `node_modules` in any parent directory, often
+ `$HOME` after an `npm install` run there, becomes the npm project root and
+ supplies packages. The plugin warns `Detected the existence of
+ $HOME/node_modules`. `npm prefix` in `docs/` should print `docs/`; if it
+ prints a parent, move that install elsewhere (e.g. `npm install -g`).
+- For a release build, use `update-site-for-release`.
+
## Common Module Paths
| Module | Path |
diff --git a/CHANGES.txt b/CHANGES.txt
index 669e2e1c7d..e750a38274 100644
--- a/CHANGES.txt
+++ b/CHANGES.txt
@@ -1,5 +1,12 @@
Release 4.2.0 - unreleased
+ * Image checks (byte-size, min-image-size, blank-image-check; new tika-image-processing
+ module) make it less likely that blank or tiny images reach text recognizers. VLM
+ output gets tk:ocr-warnings (truncated, repetition, empty); VLM parsers take
+ temperature; dropped HTTP connections are retried. SizeGatedEnricher is deprecated;
+ text-recognizers entries take min-width/min-height (_min-width/_min-height still
+ work) (TIKA-4972).
+
* An email that starts with MIME-Version and nests a multipart/related part (a Gmail
export, for one) is detected as message/rfc822, not as MHTML: the
multipart/related magic now reads only the message's own header block (TIKA-4973).
diff --git a/docs/modules/ROOT/examples/jina-ocr-basic.json b/docs/modules/ROOT/examples/jina-ocr-basic.json
new file mode 100644
index 0000000000..bffd967321
--- /dev/null
+++ b/docs/modules/ROOT/examples/jina-ocr-basic.json
@@ -0,0 +1,16 @@
+{
+ "engines": {
+ "vlm": {
+ "openai-vlm-parser": {
+ "baseUrl": "https://api.jina.ai",
+ "model": "jina-ocr-v1",
+ "apiKey": "${env:JINA_API_KEY}"
+ }
+ }
+ },
+ "text-recognizers": [
+ {
+ "engine": "vlm"
+ }
+ ]
+}
diff --git a/docs/modules/ROOT/pages/configuration/index.adoc b/docs/modules/ROOT/pages/configuration/index.adoc
index 77a0c40ea4..17489362df 100644
--- a/docs/modules/ROOT/pages/configuration/index.adoc
+++ b/docs/modules/ROOT/pages/configuration/index.adoc
@@ -191,18 +191,67 @@ stays loaded, and `image-parser` and `pdf-parser` call it:
}
----
-An entry naming an engine takes only `engine`, `_mime-include`, `_mime-exclude`, `_min-width` and
-`_min-height`; the engine's own settings live under `engines`, where an
+An entry naming an engine takes only `engine`, `_mime-include`, `_mime-exclude`, `min-width`,
+`min-height` and `checks`; the engine's own settings live under `engines`, where an
xref:configuration/inference.adoc[inference binding] can name the same engine. The 4.0 form,
the engine inline, still works: `{ "tesseract-ocr-parser": { "language": "eng" } }`, and takes
-the same underscore keys.
+the same keys. `_mime-include`/`_mime-exclude` keep their underscore because every component list
+uses the one spelling; `min-width`, `min-height` and `checks` belong to this list alone, so they
+need none, and the older `_min-width`/`_min-height` still mean the same (setting both spellings of
+one key fails the load). In the inline form these three are removed from the engine's settings.
-`_min-width`/`_min-height` keep an image whose recorded size (`tiff:ImageWidth`,
+`min-width`/`min-height` keep an image whose recorded size (`tiff:ImageWidth`,
`tiff:ImageLength`) falls short in either dimension away from the engine, in pixels; an image of
unknown size is sent. Whatever the entry says, an image under 2 x 2 (a spacer in an email
signature) never reaches any engine; the engines' own byte gates (`minFileSizeToOcr`) are
unchanged.
+[#image-checks]
+*Send the engine fewer images that hold no text.* An entry's `checks` lists
+image checks by name, run in order, cheapest first; the first to refuse keeps the image from the
+engine, whatever the engine is (Tesseract, a VLM, ...), and records `skipped:<reason>` in
+`tk:ocr-warnings`. For an inline image it is recorded on the parent document too, when the
+output is one metadata object per document (`-J`, `/rmeta`, Pipes). A check that cannot read the
+image admits it. The checks live in the `tika-image-processing` module (JDK only, no native code):
+
+[source,json]
+----
+{
+ "engines": { "jina": { "openai-vlm-parser": { "baseUrl": "https://api.jina.ai", "model": "jina-ocr-v1" } } },
+ "text-recognizers": [
+ { "engine": "jina",
+ "checks": [
+ { "byte-size": { "minBytes": 100, "maxBytes": 52428800 } },
+ { "min-image-size": { "minTotalPixels": 10000, "minShortSidePixels": 16 } },
+ { "blank-image-check": { "maxInk": 0.0001, "tolerance": 40 } }
+ ] }
+ ]
+}
+----
+
+`byte-size` refuses an image shorter than `minBytes` or longer than `maxBytes` by its measured
+length, without reading it, so it belongs first; 0 turns a limit off, and an image whose length is
+unknown or only declared (by a container or a header) is admitted. `min-image-size` refuses an image under `minTotalPixels` in area or whose
+shorter side is under `minShortSidePixels`, by the dimensions in its header (it reads only the start of a
+large file, and the whole file only when the dimensions are not there); `minWidthPixels` and `minHeightPixels`
+ask for more of one dimension on top of `minShortSidePixels`, and 0 turns a test off. The `min-image-size`
+values shown are its defaults, and `byte-size` has no limit until set: below 100 x 100 an image holds a few
+characters at most, and a strip such as 11 x 1000 passes the area test but holds no line of text.
+`blank-image-check` refuses an image whose
+share of pixels differing from its most common gray level by more than `tolerance` is at most
+`maxInk` (0.0001 is 0.01 %, below a page with a line of text), measured on a copy of at most 1,000
+pixels a side. With `despeckle` (on by default) a pixel counts only if most of its 3 x 3 neighbourhood
+differs from the background, so scattered specks, as on a noisy scan, do not hide a blank page: 0.1 % to 5 %
+salt-and-pepper noise comes out blank, and a stroke of text does not. An image with transparency
+is blank only if it is blank over both white and black, so dark or light text on a transparent
+background is kept. A progressive JPEG over 16 million pixels is not decoded (it is admitted):
+decoding one takes about 3 bytes of memory a pixel outside the Java heap.
+
+A check's settings need no underscore. `min-width` and `min-height` on the entry are a separate,
+metadata-only size minimum that runs before any check. The checks do not tell a photo from a page of
+text, and do not detect rotation. Nor do they, or the `tk:ocr-warnings` codes, catch fluent hallucinations
+(xref:configuration/parsers/vlm-parsers.adoc#fluent-hallucinations[what they do not catch]).
+
*Turn OCR off.* An empty list is authoritative:
[source,json]
diff --git a/docs/modules/ROOT/pages/configuration/inference.adoc b/docs/modules/ROOT/pages/configuration/inference.adoc
index 9947d2d834..4ec6f4b9d7 100644
--- a/docs/modules/ROOT/pages/configuration/inference.adoc
+++ b/docs/modules/ROOT/pages/configuration/inference.adoc
@@ -60,7 +60,10 @@ A hosted engine caps the requests in flight per key and answers the excess with
usually with no `Retry-After`; a saturated one answers 502, 503 or 504. Those four answers are
retried, `maxRetries` times (4 unless set, 0 to fail at once), with a short jittered backoff
from 250 ms doubling to 4 s, or the `Retry-After` the server sends, and never past the budget
-the parse granted the call. Any other answer, a 401 or a 400, fails at once. The retries cover
+the parse granted the call. A connection that drops before a full response arrives is retried
+the same way, sharing the `maxRetries` count; if the service had already read the
+request, a paid call may be billed twice. Any other answer, a 401 or a 400, fails at once,
+as do an unknown host, a refused connection and a TLS failure. The retries cover
collisions between a few parse workers; they do not turn more workers than the key allows
into throughput. Keep `numClients` (tika-server, Pipes) at or below the key's concurrency,
counting every engine the workers call, and raise the key's tier before raising the workers.
diff --git a/docs/modules/ROOT/pages/configuration/parsers/vlm-parsers.adoc b/docs/modules/ROOT/pages/configuration/parsers/vlm-parsers.adoc
index 695c849c84..79adb6c62e 100644
--- a/docs/modules/ROOT/pages/configuration/parsers/vlm-parsers.adoc
+++ b/docs/modules/ROOT/pages/configuration/parsers/vlm-parsers.adoc
@@ -38,7 +38,7 @@ xref:configuration/index.adoc[Configuration]. Naming it under `parsers` is depre
|Parser |Endpoint |Config key
|`OpenAIVLMParser`
-|Any OpenAI-compatible chat completions endpoint (vLLM, Ollama, local FastAPI, OpenAI)
+|Any OpenAI-compatible chat completions endpoint (vLLM, Ollama, local FastAPI, OpenAI, Jina AI)
|`openai-vlm-parser`
|`ClaudeVLMParser`
@@ -143,6 +143,30 @@ endpoint. The API key is passed as a `key` query parameter.
Change `baseUrl` if you are using Vertex AI or a proxy.
+== Jina OCR
+
+https://jina.ai[Jina AI]'s `jina-ocr-v1` model is a document-OCR model that outputs
+clean Markdown. Its API is OpenAI-compatible, so `OpenAIVLMParser` drives it with no
+extra dependencies.
+
+=== Basic Configuration
+
+[source,json]
+----
+include::example$jina-ocr-basic.json[]
+----
+
+Set the `JINA_API_KEY` environment variable to your key.
+`${env:NAME}` syntax is supported everywhere in Tika JSON config
+(xref:configuration/index.adoc#env[Secrets from the environment]).
+
+Jina OCR accepts images only (PNG, JPEG, GIF, TIFF, WebP, BMP). It does not accept
+PDFs or video. The MIME type declared in the `data:` URI is informational — Jina
+auto-detects the format from the bytes, so a mismatched label does not cause an error.
+
+NOTE: `jina-ocr-v1` tables are emitted as raw HTML inside the model's Markdown output.
+Tika's Markdown-to-XHTML converter handles this correctly — see <<_markdown_to_xhtml_conversion>>.
+
== Using a VLM parser for PDF parsing (deprecated)
Claude and Gemini can process entire PDFs with their vision capabilities.
@@ -197,7 +221,8 @@ All three parsers share the same configuration POJO (`VLMOCRConfig`):
|`maxRetries`
|`4`
-|Retries of a 429, 502, 503 or 504 answer, with a jittered backoff inside the parse budget;
+|Retries of a 429, 502, 503 or 504 answer, or of a connection that dropped before a full
+response arrived, with a jittered backoff inside the parse budget;
`0` fails at once. A hosted service caps requests in flight per key, so see
xref:configuration/inference.adoc#concurrency[Hosted engines and concurrency].
@@ -223,6 +248,12 @@ text into the parent document's content stream. Mirrors
captioning or tagging prompt: the parser still runs, but the PDF parser's `AUTO` OCR never replaces
a page's extracted text with its output.
+|`temperature`
+|unset
+|Sampling temperature sent with each request (0 to 2; Claude accepts 0 to 1). Unset sends none and the
+service's default applies. `0` makes repeated requests for the same image return the same text on
+services that honor it, which makes a wrong answer reproducible; it does not make the answer correct.
+
|`minFileSizeToOcr`
|`0`
|Minimum input file size in bytes.
@@ -251,6 +282,28 @@ trusted callers. See <<_per_request_configuration,Per-request configuration>>.
|Send the output limit as `max_completion_tokens` instead of `max_tokens`. Required for OpenAI / Azure OpenAI models that reject `max_tokens` (o-series, GPT-5 and later); leave `false` for servers that only accept `max_tokens`.
|===
+When a file is not sent because of `minFileSizeToOcr`, `maxFileSizeToOcr` or
+`maxImagePixels`, the parser sets `vlm:skipped-reason` to `file-too-small`, `file-too-large` or
+`image-too-large`; the last also sets `vlm:image-pixels`.
+xref:configuration/index.adoc#image-checks[Image checks] can screen out images too small or
+blank to be worth sending, before any text recognizer sees them.
+
+The returned text is never changed or dropped. When it looks doubtful, `tk:ocr-warnings` (multi-valued)
+gets one of: `truncated` (the model stopped at `maxTokens`), `repetition` (a repeated line or sentence;
+output of at least 1,000 bytes that deflates to under 5% of its size), or `empty`. For an
+`INLINE` image, whose text goes into the parent document, the same
+codes are added to the parent's `tk:ocr-warnings`, and a skip appears there as `skipped:<reason>`. That
+needs the recursive parser wrapper, which supplies the parent's metadata.
+
+[#fluent-hallucinations]
+=== Limits of the checks and warnings
+
+The image checks screen what is sent, and `tk:ocr-warnings` describes the shape of what comes
+back: a loop, a cut-off answer or no answer. Neither judges accuracy, so neither identifies fluent
+hallucinations, text that reads well but is not what the image says. Like any OCR engine, a VLM
+can misread an image, and output with no warning has not been verified. Where accuracy matters,
+spot-check a sample against the source.
+
== Markdown-to-XHTML conversion
The VLM's text response is expected to be markdown. Tika parses it using
@@ -300,7 +353,7 @@ rejected with an exception:
|May be lowered, never raised above the initialization-time value — that ceiling is what bounds
cost on a paid endpoint.
-|`maxImagePixels`, `maxRetries`, `allowRuntimePrompt`, `useMaxCompletionTokens`
+|`maxImagePixels`, `temperature`, `maxRetries`, `allowRuntimePrompt`, `useMaxCompletionTokens`
|Always blocked.
|`prompt`, `textRecognizer`
diff --git a/docs/modules/ROOT/pages/migration-to-4x/migrating-to-4x.adoc b/docs/modules/ROOT/pages/migration-to-4x/migrating-to-4x.adoc
index 3b57b0e67e..767cc9d5cb 100644
--- a/docs/modules/ROOT/pages/migration-to-4x/migrating-to-4x.adoc
+++ b/docs/modules/ROOT/pages/migration-to-4x/migrating-to-4x.adoc
@@ -310,7 +310,7 @@ change with the aliases: page renders are emitted at the end of each page whiche
and a page the parser does not read (`maxPages`) is not rendered. Two floors are new: a page
narrower or shorter than 2 pixels at the target dpi is not rendered, and an image under 2 x 2
pixels reaches no text recognizer or inference binding (`pages.render.minWidth`/`minHeight`,
-`_min-width`/`_min-height` on a recognizer entry, `minWidth`/`minHeight` on a binding). A binding's
+`min-width`/`min-height` (or the older `_min-width`/`_min-height`) on a recognizer entry, `minWidth`/`minHeight` on a binding). A binding's
`minWidth: 0` restores 4.0; the 2-pixel floor before the recognizers stays whatever the entry says. A per-request `ocr` block now changes only the fields it names (4.0 replaced the whole
block). In Java, `PDFParserConfig.getOcr()` and `getImageStrategy()` are gone: `getPages()` is
the overlay, the aliases write to it, the deprecated setters stay.
diff --git a/pom.xml b/pom.xml
index 8d9db9bb8b..bea3479465 100644
--- a/pom.xml
+++ b/pom.xml
@@ -41,6 +41,8 @@
<module>tika-core</module>
<module>tika-annotation-processor</module>
<module>tika-serialization</module>
+ <!-- checks that keep images with no text from a text recognizer (JDK only) -->
+ <module>tika-image-processing</module>
<module>tika-plugins-core</module>
<module>tika-detectors</module>
<module>tika-ml</module>
@@ -325,7 +327,7 @@ least three +1 Tika PMC votes are cast.
tika-grpc is excluded: its protobuf generated-sources and compile deps are not on
the aggregate classpath. NOTE: keep this list in sync when modules are added or
removed; .github/scripts/check_javadoc_sourcepath.py guards it. -->
- <sourcepath>tika-annotation-processor/src/main/java;tika-app/src/main/java;tika-bundles/tika-bundle-standard/src/main/java;tika-core/src/main/java;tika-detectors/tika-detector-magika/src/main/java;tika-detectors/tika-detector-siegfried/src/main/java;tika-encoding-detectors/tika-encoding-detector-html/src/main/java;tika-encoding-detectors/tika-encoding-detector-icu4j/src/main/java;tika-encoding-detectors/tika-encoding-detector-mojibuster/src/main/java;tika-encoding-detectors/tik [...]
+ <sourcepath>tika-annotation-processor/src/main/java;tika-app/src/main/java;tika-bundles/tika-bundle-standard/src/main/java;tika-core/src/main/java;tika-detectors/tika-detector-magika/src/main/java;tika-detectors/tika-detector-siegfried/src/main/java;tika-encoding-detectors/tika-encoding-detector-html/src/main/java;tika-encoding-detectors/tika-encoding-detector-icu4j/src/main/java;tika-encoding-detectors/tika-encoding-detector-mojibuster/src/main/java;tika-encoding-detectors/tik [...]
<subpackages>org.apache.tika</subpackages>
</configuration>
</plugin>
diff --git a/tika-annotation-processor/src/main/java/org/apache/tika/annotation/TikaComponentProcessor.java b/tika-annotation-processor/src/main/java/org/apache/tika/annotation/TikaComponentProcessor.java
index 7d4c041251..f943a71d1c 100644
--- a/tika-annotation-processor/src/main/java/org/apache/tika/annotation/TikaComponentProcessor.java
+++ b/tika-annotation-processor/src/main/java/org/apache/tika/annotation/TikaComponentProcessor.java
@@ -79,6 +79,7 @@ public class TikaComponentProcessor extends AbstractProcessor {
SERVICE_INTERFACES.put("org.apache.tika.language.translate.Translator", "translators");
SERVICE_INTERFACES.put("org.apache.tika.renderer.Renderer", "renderers");
SERVICE_INTERFACES.put("org.apache.tika.metadata.filter.MetadataFilter", "metadata-filters");
+ SERVICE_INTERFACES.put("org.apache.tika.parser.enricher.ImageCheck", "image-checks");
}
private Messager messager;
diff --git a/tika-app/pom.xml b/tika-app/pom.xml
index b5350d060f..a46c807e00 100644
--- a/tika-app/pom.xml
+++ b/tika-app/pom.xml
@@ -53,6 +53,12 @@
<artifactId>tika-vlm</artifactId>
<version>${project.version}</version>
</dependency>
+ <!-- keep blank and tiny images away from any text recognizer (JDK only) -->
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>tika-image-processing</artifactId>
+ <version>${project.version}</version>
+ </dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>tika-handler-boilerpipe</artifactId>
diff --git a/tika-app/src/test/java/org/apache/tika/cli/TikaCLIOcrWarningsTest.java b/tika-app/src/test/java/org/apache/tika/cli/TikaCLIOcrWarningsTest.java
new file mode 100644
index 0000000000..0cef8179a1
--- /dev/null
+++ b/tika-app/src/test/java/org/apache/tika/cli/TikaCLIOcrWarningsTest.java
@@ -0,0 +1,161 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.tika.cli;
+
+import static java.nio.charset.StandardCharsets.UTF_8;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.awt.image.BufferedImage;
+import java.io.ByteArrayOutputStream;
+import java.io.PrintStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipOutputStream;
+import javax.imageio.ImageIO;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+
+import org.apache.tika.http.TikaTestHttpServer;
+
+/**
+ * The consumer's path for tk:ocr-warnings: the text of a docx's pictures lands in the docx, so
+ * under -J a picture's skip and the VLM's doubt about another appear on the docx itself.
+ */
+public class TikaCLIOcrWarningsTest {
+
+ @TempDir
+ Path tmp;
+
+ @Test
+ public void testPictureWarningsReachTheDocx() throws Exception {
+ Path docx = tmp.resolve("two-pictures.docx");
+ writeDocx(docx);
+ try (TikaTestHttpServer server = new TikaTestHttpServer()) {
+ server.enqueue(new TikaTestHttpServer.MockResponse(200, "{\"object\":\"list\"}"));
+ server.enqueue(new TikaTestHttpServer.MockResponse(200,
+ "{\"choices\":[{\"message\":{\"content\":\"\"}}]}"));
+ Path config = tmp.resolve("tika-config.json");
+ Files.writeString(config, """
+ {
+ "engines": { "vlm": { "openai-vlm-parser": { "baseUrl": "BASE_URL", "model": "m" } } },
+ "text-recognizers": [ { "engine": "vlm", "checks": [ "blank-image-check" ] } ]
+ }
+ """.replace("BASE_URL", server.url()));
+
+ JsonNode output = new ObjectMapper().readTree(
+ run("--config=" + config, "-J", docx.toUri().toString()));
+
+ assertEquals(2, server.getRequestCount(), "the health check and the inked picture");
+ JsonNode root = null;
+ for (JsonNode m : output) {
+ if (!m.has("tk:embedded-id-path")) {
+ root = m;
+ }
+ }
+ assertNotNull(root);
+ assertEquals(Set.of("skipped:blank", "empty"), values(root, "tk:ocr-warnings"));
+ }
+ }
+
+ /** A minimal docx: one paragraph and two pictures related to the main document part. */
+ private static void writeDocx(Path docx) throws Exception {
+ String rel = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/";
+ try (ZipOutputStream zip = new ZipOutputStream(Files.newOutputStream(docx))) {
+ entry(zip, "[Content_Types].xml", """
+ <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+ <Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">
+ <Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>
+ <Default Extension="xml" ContentType="application/xml"/>
+ <Default Extension="png" ContentType="image/png"/>
+ <Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/>
+ </Types>
+ """.getBytes(UTF_8));
+ entry(zip, "_rels/.rels", ("""
+ <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+ <Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
+ <Relationship Id="rId1" Type="RELofficeDocument" Target="word/document.xml"/>
+ </Relationships>
+ """).replace("REL", rel).getBytes(UTF_8));
+ entry(zip, "word/document.xml", """
+ <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+ <w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
+ <w:body><w:p><w:r><w:t>two pictures</w:t></w:r></w:p></w:body></w:document>
+ """.getBytes(UTF_8));
+ entry(zip, "word/_rels/document.xml.rels", ("""
+ <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+ <Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
+ <Relationship Id="rId1" Type="RELimage" Target="media/image1.png"/>
+ <Relationship Id="rId2" Type="RELimage" Target="media/image2.png"/>
+ </Relationships>
+ """).replace("REL", rel).getBytes(UTF_8));
+ entry(zip, "word/media/image1.png", png(1));
+ entry(zip, "word/media/image2.png", png(2));
+ }
+ }
+
+ private static void entry(ZipOutputStream zip, String name, byte[] bytes) throws Exception {
+ zip.putNextEntry(new ZipEntry(name));
+ zip.write(bytes);
+ zip.closeEntry();
+ }
+
+ /** A white picture; the second has a black block. */
+ private static byte[] png(int index) throws Exception {
+ BufferedImage image = new BufferedImage(200, 200, BufferedImage.TYPE_INT_RGB);
+ for (int x = 0; x < 200; x++) {
+ for (int y = 0; y < 200; y++) {
+ image.setRGB(x, y, index == 2 && x < 50 ? 0 : 0xFFFFFF);
+ }
+ }
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ ImageIO.write(image, "png", out);
+ return out.toByteArray();
+ }
+
+ private static Set<String> values(JsonNode node, String field) {
+ Set<String> values = new HashSet<>();
+ JsonNode value = node.get(field);
+ if (value != null && value.isArray()) {
+ value.forEach(v -> values.add(v.asText()));
+ } else if (value != null) {
+ values.add(value.asText());
+ }
+ return values;
+ }
+
+ private static String run(String... args) throws Exception {
+ PrintStream stdout = System.out;
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ try {
+ System.setOut(new PrintStream(out, true, UTF_8.name()));
+ TikaCLI.main(args);
+ } finally {
+ System.setOut(stdout);
+ }
+ String json = out.toString(UTF_8);
+ assertTrue(json.startsWith("["), json);
+ return json;
+ }
+}
diff --git a/tika-bom/pom.xml b/tika-bom/pom.xml
index de54d46d1f..45cde6fb57 100644
--- a/tika-bom/pom.xml
+++ b/tika-bom/pom.xml
@@ -422,6 +422,11 @@
<artifactId>tika-http-jdk</artifactId>
<version>${revision}</version>
</dependency>
+ <dependency>
+ <groupId>org.apache.tika</groupId>
+ <artifactId>tika-image-processing</artifactId>
+ <version>${revision}</version>
+ </dependency>
<dependency>
<groupId>org.apache.tika</groupId>
<artifactId>tika-inference</artifactId>
diff --git a/tika-core/src/main/java/org/apache/tika/metadata/TikaCoreProperties.java b/tika-core/src/main/java/org/apache/tika/metadata/TikaCoreProperties.java
index 797be9fa10..110660297c 100644
--- a/tika-core/src/main/java/org/apache/tika/metadata/TikaCoreProperties.java
+++ b/tika-core/src/main/java/org/apache/tika/metadata/TikaCoreProperties.java
@@ -153,6 +153,14 @@ public interface TikaCoreProperties {
*/
Property TIKA_CHUNKS = Property.reservedInternalJson("tk:chunks");
+ /**
+ * Doubts a text recognizer has about the text it returned, which is never altered or dropped.
+ * Codes are short and tool-neutral: {@code truncated}, {@code repetition}, {@code empty},
+ * and {@code skipped:<reason>} for an input it did not read. On a
+ * document, the union over the pages or images it had recognized.
+ */
+ Property OCR_WARNINGS = Property.reservedInternalTextBag(TIKA_META_PREFIX + "ocr-warnings");
+
/**
* The inference inputs a parser released for this document (TEXT, PAGES, ...), written
* only when they differ from the default of its text. The TEXT stage skips a document
diff --git a/tika-core/src/main/java/org/apache/tika/parser/enricher/ContentEnrichers.java b/tika-core/src/main/java/org/apache/tika/parser/enricher/ContentEnrichers.java
index d349654f3d..2447004c8a 100644
--- a/tika-core/src/main/java/org/apache/tika/parser/enricher/ContentEnrichers.java
+++ b/tika-core/src/main/java/org/apache/tika/parser/enricher/ContentEnrichers.java
@@ -98,7 +98,7 @@ public final class ContentEnrichers {
public static Parser get(CompositeContentEnricher enrichers, MediaType mediaType,
Metadata target, ParseContext context) {
Objects.requireNonNull(target, "target");
- if (SizeGatedEnricher.tooSmall(target, MIN_PIXELS, MIN_PIXELS)) {
+ if (RecordedSizeCheck.tooSmall(target, MIN_PIXELS, MIN_PIXELS)) {
return null;
}
return select(enrichers, mediaType, context);
@@ -564,7 +564,7 @@ public final class ContentEnrichers {
context.set(ActiveEnrichment.class, active);
}
// the image parser learns the size after dispatch: gate again with it known
- if (SizeGatedEnricher.tooSmall(metadata, MIN_PIXELS, MIN_PIXELS)) {
+ if (RecordedSizeCheck.tooSmall(metadata, MIN_PIXELS, MIN_PIXELS)) {
return;
}
String contentType = metadata.get(HttpHeaders.CONTENT_TYPE);
diff --git a/tika-core/src/main/java/org/apache/tika/parser/enricher/SizeGatedEnricher.java b/tika-core/src/main/java/org/apache/tika/parser/enricher/GatedEnricher.java
similarity index 54%
copy from tika-core/src/main/java/org/apache/tika/parser/enricher/SizeGatedEnricher.java
copy to tika-core/src/main/java/org/apache/tika/parser/enricher/GatedEnricher.java
index 6927ec9617..af59f7629d 100644
--- a/tika-core/src/main/java/org/apache/tika/parser/enricher/SizeGatedEnricher.java
+++ b/tika-core/src/main/java/org/apache/tika/parser/enricher/GatedEnricher.java
@@ -17,65 +17,65 @@
package org.apache.tika.parser.enricher;
import java.io.IOException;
+import java.util.List;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
import org.apache.tika.exception.TikaException;
import org.apache.tika.io.TikaInputStream;
import org.apache.tika.metadata.Metadata;
-import org.apache.tika.metadata.TIFF;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.parser.Parser;
import org.apache.tika.parser.ParserDecorator;
/**
- * A {@code text-recognizers} entry's {@code _min-width}/{@code _min-height}: an image whose
- * recorded dimensions ({@code tiff:ImageWidth}, {@code tiff:ImageLength}) fall short in either
- * is not handed to the engine. An image of unknown size is. The engine's own byte gates
- * ({@code minFileSizeToOcr}) are unchanged.
+ * A text recognizer behind a chain of {@link ImageCheck}s, in order. The first check to refuse
+ * keeps the image from the engine and records {@code skipped:<reason>}; a check that fails
+ * admits it. One decorator however many checks an entry lists.
*
- * @since Apache Tika 4.1
+ * @since Apache Tika 4.2
*/
-public class SizeGatedEnricher extends ParserDecorator {
+public class GatedEnricher extends ParserDecorator {
private static final long serialVersionUID = 1L;
+ private static final Logger LOG = LoggerFactory.getLogger(GatedEnricher.class);
- private final int minWidth;
- private final int minHeight;
+ private final List<ImageCheck> checks;
- public SizeGatedEnricher(Parser parser, int minWidth, int minHeight) {
+ public GatedEnricher(Parser parser, List<ImageCheck> checks) {
super(parser);
- this.minWidth = minWidth;
- this.minHeight = minHeight;
+ this.checks = List.copyOf(checks);
}
- /** True when the metadata records a width or height below the minimum. */
- public static boolean tooSmall(Metadata metadata, int minWidth, int minHeight) {
- Integer width = metadata.getInt(TIFF.IMAGE_WIDTH);
- Integer height = metadata.getInt(TIFF.IMAGE_LENGTH);
- return (width != null && width < minWidth) || (height != null && height < minHeight);
- }
-
- public int getMinWidth() {
- return minWidth;
- }
-
- public int getMinHeight() {
- return minHeight;
+ public List<ImageCheck> getChecks() {
+ return checks;
}
@Override
public void parse(TikaInputStream tis, ContentHandler handler, Metadata metadata,
ParseContext context) throws IOException, SAXException, TikaException {
- if (tooSmall(metadata, minWidth, minHeight)) {
- return;
+ ImageProbe probe = new ImageProbe(tis, metadata);
+ for (ImageCheck check : checks) {
+ ImageCheck.Verdict verdict;
+ try {
+ verdict = check.check(probe, metadata, context);
+ } catch (IOException | RuntimeException e) {
+ LOG.debug("{} could not judge the image; admitting it", check.getClass(), e);
+ continue;
+ }
+ if (!verdict.admitted()) {
+ OcrWarnings.add(context, metadata, "skipped:" + verdict.reason());
+ return;
+ }
}
super.parse(tis, handler, metadata, context);
}
@Override
public String getDecorationName() {
- return "Size-gated (" + minWidth + "x" + minHeight + ")";
+ return "Gated (" + checks.size() + " checks)";
}
}
diff --git a/tika-core/src/main/java/org/apache/tika/parser/enricher/ImageCheck.java b/tika-core/src/main/java/org/apache/tika/parser/enricher/ImageCheck.java
new file mode 100644
index 0000000000..ec1f00a714
--- /dev/null
+++ b/tika-core/src/main/java/org/apache/tika/parser/enricher/ImageCheck.java
@@ -0,0 +1,66 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.tika.parser.enricher;
+
+import java.io.IOException;
+import java.io.Serializable;
+
+import org.apache.tika.metadata.Metadata;
+import org.apache.tika.parser.ParseContext;
+
+/**
+ * A test an image passes before a text recognizer is asked to read it: big enough, not blank.
+ * Checks run in the order a {@code "text-recognizers"} entry lists them, cheapest first, and
+ * the first to refuse ends the chain; the engine never sees the image and the refusal is
+ * recorded as {@code skipped:<reason>} in {@link
+ * org.apache.tika.metadata.TikaCoreProperties#OCR_WARNINGS}. A check that fails, or cannot
+ * judge, admits the image: a gate is never a reason to lose text.
+ * <p>
+ * Implementations are named {@code @TikaComponent}s, so a deployment lists them by name; keep
+ * pixel work out of {@code tika-core} by putting it in the implementing module and sharing
+ * what a check decodes through {@link ImageProbe#memo}.
+ *
+ * @since Apache Tika 4.2
+ */
+public interface ImageCheck extends Serializable {
+
+ /**
+ * @param image the image and what earlier checks have already learned about it
+ * @param metadata the metadata of the image the engine would be handed
+ * @param context the parse context
+ */
+ Verdict check(ImageProbe image, Metadata metadata, ParseContext context) throws IOException;
+
+ /**
+ * Whether the image goes to the engine; a refusal carries a short, stable reason.
+ *
+ * @param admitted false to keep the image from the engine
+ * @param reason why, when refused: {@code blank}, {@code image-too-small}, ...
+ */
+ record Verdict(boolean admitted, String reason) {
+
+ private static final Verdict ADMIT = new Verdict(true, null);
+
+ public static Verdict admit() {
+ return ADMIT;
+ }
+
+ public static Verdict skip(String reason) {
+ return new Verdict(false, reason);
+ }
+ }
+}
diff --git a/tika-core/src/main/java/org/apache/tika/parser/enricher/ImageProbe.java b/tika-core/src/main/java/org/apache/tika/parser/enricher/ImageProbe.java
new file mode 100644
index 0000000000..61bfc18d0a
--- /dev/null
+++ b/tika-core/src/main/java/org/apache/tika/parser/enricher/ImageProbe.java
@@ -0,0 +1,139 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.tika.parser.enricher;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.apache.tika.io.TikaInputStream;
+import org.apache.tika.metadata.Metadata;
+import org.apache.tika.metadata.TIFF;
+
+/**
+ * What the checks of one image share: its bytes, read once and left in the stream for the
+ * engine, the dimensions its parser recorded, and anything a check chooses to {@linkplain
+ * #memo memoize}, so two checks that need the decoded pixels decode them once.
+ *
+ * @since Apache Tika 4.2
+ */
+public final class ImageProbe {
+
+ /** Images longer than this are not read for a check; the checks then admit them. */
+ public static final int MAX_BYTES = 64 * 1024 * 1024;
+
+ /** How much of the start of an image {@link #header()} reads: enough for a header. */
+ public static final int HEADER_BYTES = 1024 * 1024;
+
+ private final TikaInputStream tis;
+ private final Metadata metadata;
+ private final Map<String, Object> memo = new HashMap<>();
+ private byte[] bytes;
+ private boolean bytesRead;
+ private byte[] header;
+ private boolean headerComplete;
+
+ public ImageProbe(TikaInputStream tis, Metadata metadata) {
+ this.tis = tis;
+ this.metadata = metadata;
+ }
+
+ /** The width the image's parser recorded ({@code tiff:ImageWidth}), or null. */
+ public Integer recordedWidth() {
+ return metadata.getInt(TIFF.IMAGE_WIDTH);
+ }
+
+ /** The height the image's parser recorded ({@code tiff:ImageLength}), or null. */
+ public Integer recordedHeight() {
+ return metadata.getInt(TIFF.IMAGE_LENGTH);
+ }
+
+ /**
+ * The image's length in bytes without reading it, or -1 when the stream does not know it
+ * or knows only a declared length (a container's or a header's), which may lie.
+ */
+ public long length() throws IOException {
+ return tis.hasReliableLength() ? tis.getLength() : -1;
+ }
+
+ /**
+ * The first {@link #HEADER_BYTES} of the image (all of it when it is shorter), read on first
+ * use and left in the stream: enough for a check that needs only dimensions, so a large
+ * image is not read whole for it. Treat the array as read-only.
+ */
+ public byte[] header() throws IOException {
+ if (header == null) {
+ tis.mark(HEADER_BYTES + 1);
+ try {
+ header = tis.readNBytes(HEADER_BYTES);
+ } finally {
+ tis.reset();
+ }
+ headerComplete = header.length < HEADER_BYTES;
+ }
+ return header;
+ }
+
+ /** Whether {@link #header()} is the whole image. */
+ public boolean headerIsComplete() throws IOException {
+ header();
+ return headerComplete;
+ }
+
+ /**
+ * The image's bytes, read on first use and left in the stream, or null when it is longer
+ * than {@link #MAX_BYTES} or cannot be read. Treat the array as read-only.
+ */
+ public byte[] bytes() throws IOException {
+ if (!bytesRead) {
+ bytesRead = true;
+ bytes = readBytes();
+ }
+ return bytes;
+ }
+
+ private byte[] readBytes() throws IOException {
+ if (length() > MAX_BYTES) {
+ return null;
+ }
+ if (headerIsComplete()) {
+ return header;
+ }
+ tis.mark(MAX_BYTES + 1);
+ try {
+ byte[] read = tis.readNBytes(MAX_BYTES + 1);
+ return read.length > MAX_BYTES ? null : read;
+ } finally {
+ tis.reset();
+ }
+ }
+
+ /** A value one check computes and the next reuses; computed once per key. */
+ @SuppressWarnings("unchecked")
+ public <T> T memo(String key, Computation<T> computation) throws IOException {
+ if (!memo.containsKey(key)) {
+ memo.put(key, computation.compute());
+ }
+ return (T) memo.get(key);
+ }
+
+ /** A computation that may fail to read. */
+ @FunctionalInterface
+ public interface Computation<T> {
+ T compute() throws IOException;
+ }
+}
diff --git a/tika-core/src/main/java/org/apache/tika/parser/enricher/OcrWarnings.java b/tika-core/src/main/java/org/apache/tika/parser/enricher/OcrWarnings.java
new file mode 100644
index 0000000000..0ae651a8d1
--- /dev/null
+++ b/tika-core/src/main/java/org/apache/tika/parser/enricher/OcrWarnings.java
@@ -0,0 +1,63 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.tika.parser.enricher;
+
+import org.apache.tika.extractor.ParentMetadata;
+import org.apache.tika.metadata.Metadata;
+import org.apache.tika.metadata.TikaCoreProperties;
+import org.apache.tika.parser.ParseContext;
+
+/**
+ * Writes {@link TikaCoreProperties#OCR_WARNINGS}: each code once per document, and for an
+ * inline image also on the parent document, whose content receives the image's text.
+ *
+ * @since Apache Tika 4.2
+ */
+public final class OcrWarnings {
+
+ private OcrWarnings() {
+ }
+
+ /** Adds the code to the metadata unless it is already there. */
+ public static void add(Metadata metadata, String code) {
+ for (String existing : metadata.getValues(TikaCoreProperties.OCR_WARNINGS)) {
+ if (existing.equals(code)) {
+ return;
+ }
+ }
+ metadata.add(TikaCoreProperties.OCR_WARNINGS, code);
+ }
+
+ /** Adds the code to the metadata and, for an inline image, to its parent's. */
+ public static void add(ParseContext context, Metadata metadata, String code) {
+ add(metadata, code);
+ addToInlineParent(context, metadata, code);
+ }
+
+ /** The text of an inline image lands in the parent's content, so the doubt goes with it. */
+ public static void addToInlineParent(ParseContext context, Metadata metadata, String code) {
+ ParentMetadata parent = context.get(ParentMetadata.class);
+ if (parent == null || parent.getMetadata() == null) {
+ return;
+ }
+ String type = metadata.get(TikaCoreProperties.EMBEDDED_RESOURCE_TYPE);
+ if (!TikaCoreProperties.EmbeddedResourceType.INLINE.name().equals(type)) {
+ return;
+ }
+ add(parent.getMetadata(), code);
+ }
+}
diff --git a/tika-core/src/main/java/org/apache/tika/parser/enricher/SizeGatedEnricher.java b/tika-core/src/main/java/org/apache/tika/parser/enricher/RecordedSizeCheck.java
similarity index 58%
copy from tika-core/src/main/java/org/apache/tika/parser/enricher/SizeGatedEnricher.java
copy to tika-core/src/main/java/org/apache/tika/parser/enricher/RecordedSizeCheck.java
index 6927ec9617..3eda789015 100644
--- a/tika-core/src/main/java/org/apache/tika/parser/enricher/SizeGatedEnricher.java
+++ b/tika-core/src/main/java/org/apache/tika/parser/enricher/RecordedSizeCheck.java
@@ -16,47 +16,29 @@
*/
package org.apache.tika.parser.enricher;
-import java.io.IOException;
-
-import org.xml.sax.ContentHandler;
-import org.xml.sax.SAXException;
-
-import org.apache.tika.exception.TikaException;
-import org.apache.tika.io.TikaInputStream;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.metadata.TIFF;
import org.apache.tika.parser.ParseContext;
-import org.apache.tika.parser.Parser;
-import org.apache.tika.parser.ParserDecorator;
/**
- * A {@code text-recognizers} entry's {@code _min-width}/{@code _min-height}: an image whose
- * recorded dimensions ({@code tiff:ImageWidth}, {@code tiff:ImageLength}) fall short in either
- * is not handed to the engine. An image of unknown size is. The engine's own byte gates
- * ({@code minFileSizeToOcr}) are unchanged.
+ * The {@code _min-width}/{@code _min-height} of a {@code "text-recognizers"} entry as a check:
+ * an image whose recorded dimensions fall short in either is refused; one of unknown size is
+ * admitted. Reads metadata only.
*
- * @since Apache Tika 4.1
+ * @since Apache Tika 4.2
*/
-public class SizeGatedEnricher extends ParserDecorator {
+public class RecordedSizeCheck implements ImageCheck {
private static final long serialVersionUID = 1L;
private final int minWidth;
private final int minHeight;
- public SizeGatedEnricher(Parser parser, int minWidth, int minHeight) {
- super(parser);
+ public RecordedSizeCheck(int minWidth, int minHeight) {
this.minWidth = minWidth;
this.minHeight = minHeight;
}
- /** True when the metadata records a width or height below the minimum. */
- public static boolean tooSmall(Metadata metadata, int minWidth, int minHeight) {
- Integer width = metadata.getInt(TIFF.IMAGE_WIDTH);
- Integer height = metadata.getInt(TIFF.IMAGE_LENGTH);
- return (width != null && width < minWidth) || (height != null && height < minHeight);
- }
-
public int getMinWidth() {
return minWidth;
}
@@ -65,17 +47,16 @@ public class SizeGatedEnricher extends ParserDecorator {
return minHeight;
}
- @Override
- public void parse(TikaInputStream tis, ContentHandler handler, Metadata metadata,
- ParseContext context) throws IOException, SAXException, TikaException {
- if (tooSmall(metadata, minWidth, minHeight)) {
- return;
- }
- super.parse(tis, handler, metadata, context);
+ /** True when the metadata records a width or height below the minimum. */
+ public static boolean tooSmall(Metadata metadata, int minWidth, int minHeight) {
+ Integer width = metadata.getInt(TIFF.IMAGE_WIDTH);
+ Integer height = metadata.getInt(TIFF.IMAGE_LENGTH);
+ return (width != null && width < minWidth) || (height != null && height < minHeight);
}
@Override
- public String getDecorationName() {
- return "Size-gated (" + minWidth + "x" + minHeight + ")";
+ public Verdict check(ImageProbe image, Metadata metadata, ParseContext context) {
+ return tooSmall(metadata, minWidth, minHeight)
+ ? Verdict.skip("image-too-small") : Verdict.admit();
}
}
diff --git a/tika-core/src/main/java/org/apache/tika/parser/enricher/SizeGatedEnricher.java b/tika-core/src/main/java/org/apache/tika/parser/enricher/SizeGatedEnricher.java
index 6927ec9617..c0896eb894 100644
--- a/tika-core/src/main/java/org/apache/tika/parser/enricher/SizeGatedEnricher.java
+++ b/tika-core/src/main/java/org/apache/tika/parser/enricher/SizeGatedEnricher.java
@@ -24,7 +24,6 @@ import org.xml.sax.SAXException;
import org.apache.tika.exception.TikaException;
import org.apache.tika.io.TikaInputStream;
import org.apache.tika.metadata.Metadata;
-import org.apache.tika.metadata.TIFF;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.parser.Parser;
import org.apache.tika.parser.ParserDecorator;
@@ -36,7 +35,10 @@ import org.apache.tika.parser.ParserDecorator;
* ({@code minFileSizeToOcr}) are unchanged.
*
* @since Apache Tika 4.1
+ * @deprecated since 4.2: the loader puts an entry's minimum in a {@link GatedEnricher} as a
+ * {@link RecordedSizeCheck}. To be removed in 5.0.
*/
+@Deprecated
public class SizeGatedEnricher extends ParserDecorator {
private static final long serialVersionUID = 1L;
@@ -50,11 +52,14 @@ public class SizeGatedEnricher extends ParserDecorator {
this.minHeight = minHeight;
}
- /** True when the metadata records a width or height below the minimum. */
+ /**
+ * True when the metadata records a width or height below the minimum.
+ *
+ * @deprecated use {@link RecordedSizeCheck#tooSmall}
+ */
+ @Deprecated
public static boolean tooSmall(Metadata metadata, int minWidth, int minHeight) {
- Integer width = metadata.getInt(TIFF.IMAGE_WIDTH);
- Integer height = metadata.getInt(TIFF.IMAGE_LENGTH);
- return (width != null && width < minWidth) || (height != null && height < minHeight);
+ return RecordedSizeCheck.tooSmall(metadata, minWidth, minHeight);
}
public int getMinWidth() {
diff --git a/tika-core/src/test/java/org/apache/tika/parser/enricher/ContentEnrichersTest.java b/tika-core/src/test/java/org/apache/tika/parser/enricher/ContentEnrichersTest.java
index 5a4f20b12b..d5a6463bd3 100644
--- a/tika-core/src/test/java/org/apache/tika/parser/enricher/ContentEnrichersTest.java
+++ b/tika-core/src/test/java/org/apache/tika/parser/enricher/ContentEnrichersTest.java
@@ -141,7 +141,7 @@ public class ContentEnrichersTest {
context), "the gate is dispatch, not capability");
// an entry's own threshold, above the floor
- SizeGatedEnricher gated = new SizeGatedEnricher(engine, 100, 50);
+ GatedEnricher gated = new GatedEnricher(engine, List.of(new RecordedSizeCheck(100, 50)));
Metadata icon = target(PNG);
icon.set(TIFF.IMAGE_WIDTH, 64);
icon.set(TIFF.IMAGE_LENGTH, 64);
@@ -154,7 +154,8 @@ public class ContentEnrichersTest {
}
assertEquals(1, engine.calls, "unknown size passes");
assertNotNull(ContentEnrichers.asTextRecognizer(
- new SizeGatedEnricher(new RecognizingParser(Set.of(PNG), true), 1, 1)),
+ new GatedEnricher(new RecognizingParser(Set.of(PNG), true),
+ List.of(new RecordedSizeCheck(1, 1)))),
"the recognizer is seen through the decorator");
}
diff --git a/tika-core/src/test/java/org/apache/tika/parser/enricher/GatedEnricherTest.java b/tika-core/src/test/java/org/apache/tika/parser/enricher/GatedEnricherTest.java
new file mode 100644
index 0000000000..18216f9ce2
--- /dev/null
+++ b/tika-core/src/test/java/org/apache/tika/parser/enricher/GatedEnricherTest.java
@@ -0,0 +1,164 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.tika.parser.enricher;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.junit.jupiter.api.Test;
+import org.xml.sax.helpers.DefaultHandler;
+
+import org.apache.tika.extractor.ParentMetadata;
+import org.apache.tika.io.TikaInputStream;
+import org.apache.tika.metadata.Metadata;
+import org.apache.tika.metadata.TikaCoreProperties;
+import org.apache.tika.parser.ParseContext;
+import org.apache.tika.parser.mock.MockEnricher;
+
+public class GatedEnricherTest {
+
+ private static final byte[] IMAGE = {1, 2, 3, 4, 5};
+
+ private static ImageCheck admitting(List<String> calls, String name) {
+ return (image, metadata, context) -> {
+ calls.add(name);
+ return ImageCheck.Verdict.admit();
+ };
+ }
+
+ private static ImageCheck refusing(List<String> calls, String name, String reason) {
+ return (image, metadata, context) -> {
+ calls.add(name);
+ return ImageCheck.Verdict.skip(reason);
+ };
+ }
+
+ private static Metadata run(GatedEnricher gate, Metadata metadata, ParseContext context)
+ throws Exception {
+ try (TikaInputStream tis = TikaInputStream.get(IMAGE)) {
+ gate.parse(tis, new DefaultHandler(), metadata, context);
+ }
+ return metadata;
+ }
+
+ @Test
+ public void testAllAdmitRunsTheEngine() throws Exception {
+ List<String> calls = new ArrayList<>();
+ GatedEnricher gate = new GatedEnricher(new MockEnricher(),
+ List.of(admitting(calls, "a"), admitting(calls, "b")));
+ Metadata m = run(gate, new Metadata(), new ParseContext());
+ assertEquals(List.of("a", "b"), calls);
+ assertEquals("ENRICHED", m.get(MockEnricher.MARKER_KEY));
+ assertNull(m.get(TikaCoreProperties.OCR_WARNINGS));
+ }
+
+ @Test
+ public void testFirstRefusalStopsTheChainAndTheEngine() throws Exception {
+ List<String> calls = new ArrayList<>();
+ GatedEnricher gate = new GatedEnricher(new MockEnricher(), List.of(
+ admitting(calls, "a"), refusing(calls, "b", "blank"), admitting(calls, "c")));
+ Metadata m = run(gate, new Metadata(), new ParseContext());
+ assertEquals(List.of("a", "b"), calls);
+ assertNull(m.get(MockEnricher.MARKER_KEY));
+ assertEquals("skipped:blank", m.get(TikaCoreProperties.OCR_WARNINGS));
+ }
+
+ @Test
+ public void testACheckThatFailsAdmits() throws Exception {
+ ImageCheck broken = (image, metadata, context) -> {
+ throw new IOException("unreadable");
+ };
+ ImageCheck crashing = (image, metadata, context) -> {
+ throw new IllegalStateException("bug");
+ };
+ GatedEnricher gate = new GatedEnricher(new MockEnricher(), List.of(broken, crashing));
+ Metadata m = run(gate, new Metadata(), new ParseContext());
+ assertEquals("ENRICHED", m.get(MockEnricher.MARKER_KEY));
+ }
+
+ @Test
+ public void testChecksShareTheBytesAndTheEngineStillReadsThem() throws Exception {
+ byte[][] seen = new byte[2][];
+ ImageCheck first = (image, metadata, context) -> {
+ seen[0] = image.bytes();
+ return ImageCheck.Verdict.admit();
+ };
+ ImageCheck second = (image, metadata, context) -> {
+ seen[1] = image.bytes();
+ return ImageCheck.Verdict.admit();
+ };
+ byte[][] engineRead = new byte[1][];
+ org.apache.tika.parser.Parser engine = new MockEnricher() {
+ @Override
+ public void parse(TikaInputStream tis, org.xml.sax.ContentHandler handler,
+ Metadata metadata, ParseContext context)
+ throws org.xml.sax.SAXException {
+ try {
+ engineRead[0] = tis.readAllBytes();
+ } catch (IOException e) {
+ throw new IllegalStateException(e);
+ }
+ }
+ };
+ run(new GatedEnricher(engine, List.of(first, second)), new Metadata(), new ParseContext());
+ assertArrayEquals(IMAGE, seen[0]);
+ assertArrayEquals(IMAGE, seen[1]);
+ assertArrayEquals(IMAGE, engineRead[0]);
+ }
+
+ @Test
+ public void testMemoComputesOnce() throws Exception {
+ int[] computed = {0};
+ ImageCheck check = (image, metadata, context) -> {
+ image.memo("k", () -> ++computed[0]);
+ image.memo("k", () -> ++computed[0]);
+ return ImageCheck.Verdict.admit();
+ };
+ run(new GatedEnricher(new MockEnricher(), List.of(check, check)), new Metadata(),
+ new ParseContext());
+ assertEquals(1, computed[0]);
+ }
+
+ @Test
+ public void testInlineImageFlagsItsParent() throws Exception {
+ Metadata parent = new Metadata();
+ ParseContext context = new ParseContext();
+ context.set(ParentMetadata.class, new ParentMetadata(parent));
+ Metadata child = new Metadata();
+ child.set(TikaCoreProperties.EMBEDDED_RESOURCE_TYPE,
+ TikaCoreProperties.EmbeddedResourceType.INLINE.name());
+ run(new GatedEnricher(new MockEnricher(),
+ List.of(refusing(new ArrayList<>(), "x", "blank"))), child, context);
+ assertEquals("skipped:blank", child.get(TikaCoreProperties.OCR_WARNINGS));
+ assertEquals("skipped:blank", parent.get(TikaCoreProperties.OCR_WARNINGS));
+ }
+
+ @Test
+ public void testAnImageThatIsNotInlineLeavesTheParentAlone() throws Exception {
+ Metadata parent = new Metadata();
+ ParseContext context = new ParseContext();
+ context.set(ParentMetadata.class, new ParentMetadata(parent));
+ run(new GatedEnricher(new MockEnricher(),
+ List.of(refusing(new ArrayList<>(), "x", "blank"))), new Metadata(), context);
+ assertNull(parent.get(TikaCoreProperties.OCR_WARNINGS));
+ }
+}
diff --git a/tika-core/src/test/java/org/apache/tika/parser/enricher/ImageProbeTest.java b/tika-core/src/test/java/org/apache/tika/parser/enricher/ImageProbeTest.java
new file mode 100644
index 0000000000..1254f9df2a
--- /dev/null
+++ b/tika-core/src/test/java/org/apache/tika/parser/enricher/ImageProbeTest.java
@@ -0,0 +1,94 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.tika.parser.enricher;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.io.ByteArrayInputStream;
+import java.util.Arrays;
+import java.util.Random;
+
+import org.junit.jupiter.api.Test;
+
+import org.apache.tika.io.TikaInputStream;
+import org.apache.tika.metadata.HttpHeaders;
+import org.apache.tika.metadata.Metadata;
+
+public class ImageProbeTest {
+
+ private static byte[] bytes(int length) {
+ byte[] b = new byte[length];
+ new Random(1).nextBytes(b);
+ return b;
+ }
+
+ @Test
+ public void testLengthIsKnownWithoutReading() throws Exception {
+ ImageProbe probe = new ImageProbe(TikaInputStream.get(bytes(1234)), new Metadata());
+ assertEquals(1234, probe.length());
+ }
+
+ @Test
+ public void testLengthOfAStreamThatDoesNotKnowItIsNegative() throws Exception {
+ TikaInputStream tis = TikaInputStream.get(new ByteArrayInputStream(bytes(10)));
+ assertEquals(-1, new ImageProbe(tis, new Metadata()).length());
+ }
+
+ @Test
+ public void testADeclaredLengthIsNotTrusted() throws Exception {
+ Metadata declared = new Metadata();
+ declared.set(HttpHeaders.CONTENT_LENGTH, "10");
+ TikaInputStream tis = TikaInputStream.get(new ByteArrayInputStream(bytes(5000)), declared);
+ ImageProbe probe = new ImageProbe(tis, new Metadata());
+ assertEquals(-1, probe.length());
+ assertEquals(5000, probe.bytes().length);
+ }
+
+ @Test
+ public void testAShortImageHasItsWholeHeaderAndBytesReuseIt() throws Exception {
+ byte[] image = bytes(5000);
+ ImageProbe probe = new ImageProbe(TikaInputStream.get(image), new Metadata());
+ assertTrue(probe.headerIsComplete());
+ assertArrayEquals(image, probe.header());
+ assertSame(probe.header(), probe.bytes());
+ }
+
+ @Test
+ public void testALongImageHasOnlyItsStartAsHeader() throws Exception {
+ byte[] image = bytes(ImageProbe.HEADER_BYTES * 2 + 17);
+ TikaInputStream tis = TikaInputStream.get(image);
+ ImageProbe probe = new ImageProbe(tis, new Metadata());
+ assertFalse(probe.headerIsComplete());
+ assertEquals(ImageProbe.HEADER_BYTES, probe.header().length);
+ assertArrayEquals(Arrays.copyOf(image, ImageProbe.HEADER_BYTES), probe.header());
+ // the whole image is read only when asked for, and the engine still gets all of it
+ assertArrayEquals(image, probe.bytes());
+ assertArrayEquals(image, tis.readAllBytes());
+ }
+
+ @Test
+ public void testAnImageAboveTheLimitIsNeverRead() throws Exception {
+ byte[] image = bytes(1000);
+ ImageProbe probe = new ImageProbe(TikaInputStream.get(image), new Metadata());
+ // the limit is a constant; a normal image is under it
+ assertTrue(probe.bytes().length <= ImageProbe.MAX_BYTES);
+ }
+}
diff --git a/tika-image-processing/pom.xml b/tika-image-processing/pom.xml
new file mode 100644
index 0000000000..9e9caea7a3
--- /dev/null
+++ b/tika-image-processing/pom.xml
@@ -0,0 +1,145 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one
+ or more contributor license agreements. See the NOTICE file
+ distributed with this work for additional information
+ regarding copyright ownership. The ASF licenses this file
+ to you under the Apache License, Version 2.0 (the
+ "License"); you may not use this file except in compliance
+ with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing,
+ software distributed under the License is distributed on an
+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ KIND, either express or implied. See the License for the
+ specific language governing permissions and limitations
+ under the License.
+-->
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+
+ <parent>
+ <groupId>org.apache.tika</groupId>
+ <artifactId>tika-parent</artifactId>
+ <version>${revision}</version>
+ <relativePath>../tika-parent/pom.xml</relativePath>
+ </parent>
+
+ <artifactId>tika-image-processing</artifactId>
+ <name>Apache Tika image checks</name>
+ <description>
+ Image checks a text recognizer's entry can list under _checks, to keep images that hold
+ no text (blank, too small) from the engine. JDK only: ImageIO, no native code.
+ </description>
+
+ <dependencies>
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>tika-core</artifactId>
+ <version>${project.version}</version>
+ <scope>provided</scope>
+ </dependency>
+
+ <!-- Annotation processor - contains @TikaComponent -->
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>tika-annotation-processor</artifactId>
+ <version>${project.version}</version>
+ <scope>provided</scope>
+ </dependency>
+
+ <!-- test -->
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>tika-core</artifactId>
+ <version>${project.version}</version>
+ <type>test-jar</type>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>tika-serialization</artifactId>
+ <version>${project.version}</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter</artifactId>
+ <scope>test</scope>
+ </dependency>
+ </dependencies>
+
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-compiler-plugin</artifactId>
+ <configuration>
+ <annotationProcessorPaths>
+ <path>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>tika-annotation-processor</artifactId>
+ <version>${project.version}</version>
+ </path>
+ </annotationProcessorPaths>
+ </configuration>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-checkstyle-plugin</artifactId>
+ <version>${checkstyle.plugin.version}</version>
+ <dependencies>
+ <dependency>
+ <groupId>com.puppycrawl.tools</groupId>
+ <artifactId>checkstyle</artifactId>
+ <version>${puppycrawl.version}</version>
+ </dependency>
+ </dependencies>
+ <executions>
+ <execution>
+ <id>validate</id>
+ <phase>validate</phase>
+ <configuration>
+ <configLocation>checkstyle.xml</configLocation>
+ <inputEncoding>UTF-8</inputEncoding>
+ <consoleOutput>false</consoleOutput>
+ <includeTestSourceDirectory>true</includeTestSourceDirectory>
+ <testSourceDirectories>${project.basedir}/src/test/java</testSourceDirectories>
+ <violationSeverity>error</violationSeverity>
+ <failOnViolation>true</failOnViolation>
+ </configuration>
+ <goals>
+ <goal>check</goal>
+ </goals>
+ </execution>
+ </executions>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-jar-plugin</artifactId>
+ <configuration>
+ <archive>
+ <manifestEntries>
+ <Automatic-Module-Name>org.apache.tika.imageprocessing</Automatic-Module-Name>
+ </manifestEntries>
+ </archive>
+ </configuration>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.rat</groupId>
+ <artifactId>apache-rat-plugin</artifactId>
+ <configuration>
+ <inputExcludes>
+ <inputExclude>src/test/resources/**</inputExclude>
+ </inputExcludes>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
+
+ <scm>
+ <tag>4.1.0-rc2</tag>
+ </scm>
+</project>
diff --git a/tika-image-processing/src/main/java/org/apache/tika/imageprocessing/BlankImageCheck.java b/tika-image-processing/src/main/java/org/apache/tika/imageprocessing/BlankImageCheck.java
new file mode 100644
index 0000000000..47fa4d181a
--- /dev/null
+++ b/tika-image-processing/src/main/java/org/apache/tika/imageprocessing/BlankImageCheck.java
@@ -0,0 +1,138 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.tika.imageprocessing;
+
+import java.io.IOException;
+
+import org.apache.tika.annotation.TikaComponent;
+import org.apache.tika.metadata.Metadata;
+import org.apache.tika.parser.ParseContext;
+import org.apache.tika.parser.enricher.ImageCheck;
+import org.apache.tika.parser.enricher.ImageProbe;
+
+/**
+ * Refuses a blank image: the share of pixels whose gray level differs from the image's most
+ * common gray level (the background) by more than {@code tolerance} is at most {@code maxInk}.
+ * Measured on a copy of at most 1,000 pixels a side. The default {@code maxInk}, 0.0001
+ * (0.01 %), is below a page with a few lines of text: on 13,641 PDF pages it flagged the 87 with
+ * no ink at all and 3 with a single line. With {@code despeckle} (the default) a pixel counts as
+ * ink only if most of its 3 x 3 neighbourhood does, so scattered specks (a noisy scan) do not
+ * hide a blank page: salt-and-pepper noise of 0.1 % to 5 % comes out blank, and none of 600 text
+ * pages did. An image with transparency is blank only if it is blank over white and over black.
+ * An image it cannot read or decode is admitted.
+ *
+ * @since Apache Tika 4.2
+ */
+@TikaComponent(name = "blank-image-check")
+public class BlankImageCheck implements ImageCheck {
+
+ private static final long serialVersionUID = 1L;
+
+ private double maxInk = 0.0001;
+ private int tolerance = 40;
+ private boolean despeckle = true;
+
+ @Override
+ public Verdict check(ImageProbe image, Metadata metadata, ParseContext context)
+ throws IOException {
+ ImageDecoding.Gray gray = ImageDecoding.gray(image);
+ if (gray == null || gray.levels().length == 0) {
+ return Verdict.admit();
+ }
+ boolean blank = ink(gray.levels(), gray.width(), gray.height()) <= maxInk
+ && (gray.overBlack() == null
+ || ink(gray.overBlack(), gray.width(), gray.height()) <= maxInk);
+ return blank ? Verdict.skip("blank") : Verdict.admit();
+ }
+
+ /** The share of pixels that differ from the background, after the specks are removed. */
+ private double ink(byte[] levels, int width, int height) {
+ int[] histogram = new int[256];
+ for (byte level : levels) {
+ histogram[level & 255]++;
+ }
+ int mode = 0;
+ for (int i = 1; i < 256; i++) {
+ if (histogram[i] > histogram[mode]) {
+ mode = i;
+ }
+ }
+ byte[] mask = new byte[levels.length];
+ for (int i = 0; i < levels.length; i++) {
+ mask[i] = (byte) (Math.abs((levels[i] & 255) - mode) > tolerance ? 1 : 0);
+ }
+ long ink = 0;
+ if (!despeckle) {
+ for (byte m : mask) {
+ ink += m;
+ }
+ } else {
+ // a 3 x 3 median of a binary mask is a majority vote: isolated specks, as on a noisy
+ // scan, are outvoted by the background, a stroke of text is not
+ int[] horizontal = new int[levels.length];
+ for (int y = 0; y < height; y++) {
+ for (int x = 0; x < width; x++) {
+ int i = y * width + x;
+ horizontal[i] = mask[i] + (x > 0 ? mask[i - 1] : 0)
+ + (x < width - 1 ? mask[i + 1] : 0);
+ }
+ }
+ for (int y = 0; y < height; y++) {
+ for (int x = 0; x < width; x++) {
+ int i = y * width + x;
+ int votes = horizontal[i] + (y > 0 ? horizontal[i - width] : 0)
+ + (y < height - 1 ? horizontal[i + width] : 0);
+ if (votes >= 5) {
+ ink++;
+ }
+ }
+ }
+ }
+ return (double) ink / levels.length;
+ }
+
+ public boolean isDespeckle() {
+ return despeckle;
+ }
+
+ public void setDespeckle(boolean despeckle) {
+ this.despeckle = despeckle;
+ }
+
+ public double getMaxInk() {
+ return maxInk;
+ }
+
+ public void setMaxInk(double maxInk) {
+ if (!(maxInk >= 0 && maxInk < 1)) {
+ throw new IllegalArgumentException("maxInk must be at least 0 and below 1, got: "
+ + maxInk);
+ }
+ this.maxInk = maxInk;
+ }
+
+ public int getTolerance() {
+ return tolerance;
+ }
+
+ public void setTolerance(int tolerance) {
+ if (tolerance < 0 || tolerance > 255) {
+ throw new IllegalArgumentException("tolerance must be 0 to 255, got: " + tolerance);
+ }
+ this.tolerance = tolerance;
+ }
+}
diff --git a/tika-image-processing/src/main/java/org/apache/tika/imageprocessing/ByteSizeCheck.java b/tika-image-processing/src/main/java/org/apache/tika/imageprocessing/ByteSizeCheck.java
new file mode 100644
index 0000000000..0e43ede5d8
--- /dev/null
+++ b/tika-image-processing/src/main/java/org/apache/tika/imageprocessing/ByteSizeCheck.java
@@ -0,0 +1,81 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.tika.imageprocessing;
+
+import java.io.IOException;
+
+import org.apache.tika.annotation.TikaComponent;
+import org.apache.tika.metadata.Metadata;
+import org.apache.tika.parser.ParseContext;
+import org.apache.tika.parser.enricher.ImageCheck;
+import org.apache.tika.parser.enricher.ImageProbe;
+
+/**
+ * Refuses an image shorter than {@code minBytes} or longer than {@code maxBytes}, by its
+ * measured length: the image is not read, so this is the cheapest check to run first. A setting
+ * of 0 turns that limit off, and an image whose length is unknown or only declared is admitted. The reasons
+ * are {@code file-too-small} and {@code file-too-large}, as the VLM parsers' own byte limits
+ * report them; those limits stay, this one is for any engine.
+ *
+ * @since Apache Tika 4.2
+ */
+@TikaComponent(name = "byte-size")
+public class ByteSizeCheck implements ImageCheck {
+
+ private static final long serialVersionUID = 1L;
+
+ private long minBytes;
+ private long maxBytes;
+
+ @Override
+ public Verdict check(ImageProbe image, Metadata metadata, ParseContext context)
+ throws IOException {
+ long length = image.length();
+ if (length < 0) {
+ return Verdict.admit();
+ }
+ if (minBytes > 0 && length < minBytes) {
+ return Verdict.skip("file-too-small");
+ }
+ if (maxBytes > 0 && length > maxBytes) {
+ return Verdict.skip("file-too-large");
+ }
+ return Verdict.admit();
+ }
+
+ public long getMinBytes() {
+ return minBytes;
+ }
+
+ public void setMinBytes(long minBytes) {
+ if (minBytes < 0) {
+ throw new IllegalArgumentException("minBytes must be 0 or more, got: " + minBytes);
+ }
+ this.minBytes = minBytes;
+ }
+
+ public long getMaxBytes() {
+ return maxBytes;
+ }
+
+ public void setMaxBytes(long maxBytes) {
+ if (maxBytes < 0) {
+ throw new IllegalArgumentException("maxBytes must be 0 or more, got: " + maxBytes);
+ }
+ this.maxBytes = maxBytes;
+ }
+}
diff --git a/tika-image-processing/src/main/java/org/apache/tika/imageprocessing/ImageDecoding.java b/tika-image-processing/src/main/java/org/apache/tika/imageprocessing/ImageDecoding.java
new file mode 100644
index 0000000000..4a4cc3659f
--- /dev/null
+++ b/tika-image-processing/src/main/java/org/apache/tika/imageprocessing/ImageDecoding.java
@@ -0,0 +1,232 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.tika.imageprocessing;
+
+import java.awt.image.BufferedImage;
+import java.awt.image.IndexColorModel;
+import java.awt.image.Raster;
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.util.Iterator;
+import javax.imageio.ImageIO;
+import javax.imageio.ImageReadParam;
+import javax.imageio.ImageReader;
+import javax.imageio.stream.ImageInputStream;
+
+import org.apache.tika.parser.enricher.ImageProbe;
+
+/** What the checks read from an image, each computed once per image through the probe. */
+final class ImageDecoding {
+
+ /** The decoded copy is at most this many pixels on a side. */
+ static final int MAX_SIDE = 1000;
+
+ /** Images with more pixels than this are not decoded: a check cannot judge them. */
+ static final long MAX_DECODE_PIXELS = 100_000_000L;
+
+ /**
+ * ImageIO buffers a progressive JPEG whole, about 3 bytes of native memory a pixel,
+ * whatever the subsampling: a blank one of 587 KB at 10000 x 10000 took 290 MB.
+ */
+ static final long MAX_PROGRESSIVE_JPEG_PIXELS = 16_000_000L;
+
+ private static final long[] UNKNOWN = {-1, -1};
+
+ private ImageDecoding() {
+ }
+
+ /** {width, height} from the image header, or {-1, -1}. */
+ static long[] size(ImageProbe image) throws IOException {
+ return image.memo("imagecheck:size", () -> {
+ // the start of the file holds the dimensions of nearly every format; read the whole
+ // image only when it does not (a TIFF whose directory is at the end)
+ long[] size = tryReadSize(image.header());
+ if (size[0] <= 0 && !image.headerIsComplete()) {
+ size = tryReadSize(image.bytes());
+ }
+ return size;
+ });
+ }
+
+ /**
+ * Gray levels 0..255 of a decoded copy, row by row. An image with transparency has two
+ * copies, over white and over black: transparent pixels hide dark text in one and light
+ * text in the other. {@code overBlack} is null for an opaque image.
+ */
+ record Gray(byte[] levels, byte[] overBlack, int width, int height) {
+ }
+
+ /**
+ * A gray copy of the image of at most {@link #MAX_SIDE} pixels on a side, or null when it
+ * cannot be read or is too large to decode.
+ */
+ static Gray gray(ImageProbe image) throws IOException {
+ return image.memo("imagecheck:gray", () -> {
+ long[] size = size(image);
+ if (size[0] <= 0 || size[1] <= 0) {
+ return null;
+ }
+ long pixels = size[0] * size[1];
+ if (pixels > MAX_DECODE_PIXELS || (pixels > MAX_PROGRESSIVE_JPEG_PIXELS
+ && mayBeProgressiveJpeg(image.header()))) {
+ return null;
+ }
+ return decode(image.bytes());
+ });
+ }
+
+ /** A JPEG whose frame is progressive, or whose frame header is not in {@code bytes}. */
+ static boolean mayBeProgressiveJpeg(byte[] bytes) {
+ if (bytes.length < 2 || (bytes[0] & 255) != 0xFF || (bytes[1] & 255) != 0xD8) {
+ return false;
+ }
+ int i = 2;
+ while (i + 1 < bytes.length) {
+ if ((bytes[i] & 255) != 0xFF) {
+ return true;
+ }
+ int marker = bytes[i + 1] & 255;
+ if (marker == 0xFF) {
+ i++;
+ continue;
+ }
+ if (marker == 0xC2 || marker == 0xC6 || marker == 0xCA || marker == 0xCE) {
+ return true;
+ }
+ if (marker >= 0xC0 && marker <= 0xCF && marker != 0xC4 && marker != 0xC8
+ && marker != 0xCC) {
+ return false;
+ }
+ if (marker == 0x01 || (marker >= 0xD0 && marker <= 0xD7)) {
+ i += 2;
+ continue;
+ }
+ if (marker == 0xDA || marker == 0xD9 || i + 3 >= bytes.length) {
+ return true;
+ }
+ int length = ((bytes[i + 2] & 255) << 8) | (bytes[i + 3] & 255);
+ if (length < 2) {
+ return true;
+ }
+ i += 2 + length;
+ }
+ return true;
+ }
+
+ private static long[] tryReadSize(byte[] bytes) throws IOException {
+ try {
+ return readSize(bytes);
+ } catch (IOException | RuntimeException e) {
+ return UNKNOWN;
+ }
+ }
+
+ private static long[] readSize(byte[] bytes) throws IOException {
+ if (bytes == null) {
+ return UNKNOWN;
+ }
+ try (ImageInputStream iis = ImageIO.createImageInputStream(new ByteArrayInputStream(bytes))) {
+ ImageReader reader = reader(iis);
+ if (reader == null) {
+ return UNKNOWN;
+ }
+ try {
+ reader.setInput(iis, true, true);
+ return new long[] {reader.getWidth(0), reader.getHeight(0)};
+ } finally {
+ reader.dispose();
+ }
+ }
+ }
+
+ private static Gray decode(byte[] bytes) throws IOException {
+ try (ImageInputStream iis = ImageIO.createImageInputStream(new ByteArrayInputStream(bytes))) {
+ ImageReader reader = reader(iis);
+ if (reader == null) {
+ return null;
+ }
+ try {
+ reader.setInput(iis, true, true);
+ int step = (Math.max(reader.getWidth(0), reader.getHeight(0)) + MAX_SIDE - 1)
+ / MAX_SIDE;
+ ImageReadParam param = reader.getDefaultReadParam();
+ param.setSourceSubsampling(Math.max(1, step), Math.max(1, step), 0, 0);
+ return toGray(reader.read(0, param));
+ } finally {
+ reader.dispose();
+ }
+ }
+ }
+
+ private static ImageReader reader(ImageInputStream iis) {
+ if (iis == null) {
+ return null;
+ }
+ Iterator<ImageReader> readers = ImageIO.getImageReaders(iis);
+ return readers.hasNext() ? readers.next() : null;
+ }
+
+ static Gray toGray(BufferedImage image) {
+ int width = image.getWidth();
+ int height = image.getHeight();
+ boolean alpha = image.getColorModel().hasAlpha();
+ byte[] levels = new byte[width * height];
+ byte[] overBlack = alpha ? new byte[width * height] : null;
+ if (image.getColorModel() instanceof IndexColorModel) {
+ for (int y = 0; y < height; y++) {
+ for (int x = 0; x < width; x++) {
+ int argb = image.getRGB(x, y);
+ set(levels, overBlack, y * width + x, luma((argb >> 16) & 255,
+ (argb >> 8) & 255, argb & 255), (argb >>> 24), false);
+ }
+ }
+ return new Gray(levels, overBlack, width, height);
+ }
+ Raster raster = image.getRaster();
+ int bands = raster.getNumBands();
+ int colorBands = alpha ? bands - 1 : bands;
+ int colorShift = Math.max(0, raster.getSampleModel().getSampleSize(0) - 8);
+ int alphaShift = alpha
+ ? Math.max(0, raster.getSampleModel().getSampleSize(bands - 1) - 8) : 0;
+ boolean premultiplied = image.isAlphaPremultiplied();
+ int[] sample = new int[bands];
+ for (int y = 0; y < height; y++) {
+ for (int x = 0; x < width; x++) {
+ raster.getPixel(x, y, sample);
+ int gray = colorBands >= 3 ? luma(sample[0], sample[1], sample[2]) : sample[0];
+ set(levels, overBlack, y * width + x, gray >> colorShift,
+ alpha ? sample[bands - 1] >> alphaShift : 255, premultiplied);
+ }
+ }
+ return new Gray(levels, overBlack, width, height);
+ }
+
+ private static int luma(int r, int g, int b) {
+ return (r * 299 + g * 587 + b * 114) / 1000;
+ }
+
+ private static void set(byte[] levels, byte[] overBlack, int i, int gray, int alpha,
+ boolean premultiplied) {
+ int black = premultiplied ? gray : gray * alpha / 255;
+ if (overBlack == null) {
+ levels[i] = (byte) gray;
+ return;
+ }
+ levels[i] = (byte) Math.min(255, black + 255 - alpha);
+ overBlack[i] = (byte) black;
+ }
+}
diff --git a/tika-image-processing/src/main/java/org/apache/tika/imageprocessing/MinImageSizeCheck.java b/tika-image-processing/src/main/java/org/apache/tika/imageprocessing/MinImageSizeCheck.java
new file mode 100644
index 0000000000..366a155b87
--- /dev/null
+++ b/tika-image-processing/src/main/java/org/apache/tika/imageprocessing/MinImageSizeCheck.java
@@ -0,0 +1,108 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.tika.imageprocessing;
+
+import java.io.IOException;
+
+import org.apache.tika.annotation.TikaComponent;
+import org.apache.tika.metadata.Metadata;
+import org.apache.tika.parser.ParseContext;
+import org.apache.tika.parser.enricher.ImageCheck;
+import org.apache.tika.parser.enricher.ImageProbe;
+
+/**
+ * Refuses an image smaller than {@code minTotalPixels} in area, or whose shorter side is under
+ * {@code minShortSidePixels}, by the dimensions in its header (not the recorded metadata, which
+ * not every image has). A strip of 11 x 1000 passes the area test but holds no line of text,
+ * hence the side minimum. {@code minWidthPixels} and {@code minHeightPixels} ask for more of one
+ * dimension than {@code minShortSidePixels} does (a wide banner may need only a short height);
+ * each applies on top of it. A setting of 0 turns that test off; an image of unknown size is
+ * admitted.
+ *
+ * @since Apache Tika 4.2
+ */
+@TikaComponent(name = "min-image-size")
+public class MinImageSizeCheck implements ImageCheck {
+
+ private static final long serialVersionUID = 1L;
+
+ private long minTotalPixels = 10_000;
+ private int minShortSidePixels = 16;
+ private int minWidthPixels;
+ private int minHeightPixels;
+
+ @Override
+ public Verdict check(ImageProbe image, Metadata metadata, ParseContext context)
+ throws IOException {
+ long[] size = ImageDecoding.size(image);
+ if (size[0] <= 0 || size[1] <= 0) {
+ return Verdict.admit();
+ }
+ boolean tooSmall = size[0] * size[1] < minTotalPixels
+ || size[0] < Math.max(minShortSidePixels, minWidthPixels)
+ || size[1] < Math.max(minShortSidePixels, minHeightPixels);
+ return tooSmall ? Verdict.skip("image-too-small") : Verdict.admit();
+ }
+
+ public long getMinTotalPixels() {
+ return minTotalPixels;
+ }
+
+ public void setMinTotalPixels(long minTotalPixels) {
+ if (minTotalPixels < 0) {
+ throw new IllegalArgumentException(
+ "minTotalPixels must be 0 or more, got: " + minTotalPixels);
+ }
+ this.minTotalPixels = minTotalPixels;
+ }
+
+ public int getMinShortSidePixels() {
+ return minShortSidePixels;
+ }
+
+ public void setMinShortSidePixels(int minShortSidePixels) {
+ if (minShortSidePixels < 0) {
+ throw new IllegalArgumentException(
+ "minShortSidePixels must be 0 or more, got: " + minShortSidePixels);
+ }
+ this.minShortSidePixels = minShortSidePixels;
+ }
+
+ public int getMinWidthPixels() {
+ return minWidthPixels;
+ }
+
+ public void setMinWidthPixels(int minWidthPixels) {
+ if (minWidthPixels < 0) {
+ throw new IllegalArgumentException(
+ "minWidthPixels must be 0 or more, got: " + minWidthPixels);
+ }
+ this.minWidthPixels = minWidthPixels;
+ }
+
+ public int getMinHeightPixels() {
+ return minHeightPixels;
+ }
+
+ public void setMinHeightPixels(int minHeightPixels) {
+ if (minHeightPixels < 0) {
+ throw new IllegalArgumentException(
+ "minHeightPixels must be 0 or more, got: " + minHeightPixels);
+ }
+ this.minHeightPixels = minHeightPixels;
+ }
+}
diff --git a/tika-image-processing/src/test/java/org/apache/tika/imageprocessing/BlankImageCheckTest.java b/tika-image-processing/src/test/java/org/apache/tika/imageprocessing/BlankImageCheckTest.java
new file mode 100644
index 0000000000..fec55e8c34
--- /dev/null
+++ b/tika-image-processing/src/test/java/org/apache/tika/imageprocessing/BlankImageCheckTest.java
@@ -0,0 +1,198 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.tika.imageprocessing;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.awt.Color;
+import java.awt.image.BufferedImage;
+import java.awt.image.IndexColorModel;
+
+import org.junit.jupiter.api.Test;
+
+import org.apache.tika.metadata.Metadata;
+import org.apache.tika.parser.ParseContext;
+import org.apache.tika.parser.enricher.ImageCheck;
+
+public class BlankImageCheckTest {
+
+ private static ImageCheck.Verdict check(BlankImageCheck check, byte[] image) throws Exception {
+ return check.check(ImageFixtures.probe(image), new Metadata(), new ParseContext());
+ }
+
+ @Test
+ public void testAWhiteImageIsBlank() throws Exception {
+ ImageCheck.Verdict v = check(new BlankImageCheck(), ImageFixtures.png(300, 400, 0));
+ assertEquals(false, v.admitted());
+ assertEquals("blank", v.reason());
+ }
+
+ @Test
+ public void testAFlatGreyScanIsBlank() throws Exception {
+ // the background is whatever is most common, not white
+ assertEquals(false, check(new BlankImageCheck(),
+ ImageFixtures.png(300, 400, 0, new Color(170, 170, 170))).admitted());
+ }
+
+ @Test
+ public void testAnImageWithInkIsAdmitted() throws Exception {
+ assertTrue(check(new BlankImageCheck(), ImageFixtures.png(300, 400, 0.1)).admitted());
+ }
+
+ @Test
+ public void testInkBelowTheThresholdIsBlankAndAboveIsNot() throws Exception {
+ // 3 columns of 300 are ink: 1 %
+ byte[] image = ImageFixtures.png(300, 400, 0.01);
+ BlankImageCheck strict = new BlankImageCheck();
+ assertTrue(check(strict, image).admitted());
+ BlankImageCheck loose = new BlankImageCheck();
+ loose.setMaxInk(0.02);
+ assertEquals(false, check(loose, image).admitted());
+ }
+
+ @Test
+ public void testToleranceDecidesWhatCountsAsInk() throws Exception {
+ // light grey (200) on white is within 60 of the background
+ java.awt.image.BufferedImage image = new java.awt.image.BufferedImage(200, 200,
+ java.awt.image.BufferedImage.TYPE_INT_RGB);
+ java.awt.Graphics2D g = image.createGraphics();
+ g.setColor(Color.WHITE);
+ g.fillRect(0, 0, 200, 200);
+ g.setColor(new Color(200, 200, 200));
+ g.fillRect(0, 0, 60, 200);
+ g.dispose();
+ java.io.ByteArrayOutputStream out = new java.io.ByteArrayOutputStream();
+ javax.imageio.ImageIO.write(image, "png", out);
+ BlankImageCheck lenient = new BlankImageCheck();
+ lenient.setTolerance(60);
+ assertEquals(false, check(lenient, out.toByteArray()).admitted());
+ assertTrue(check(new BlankImageCheck(), out.toByteArray()).admitted());
+ }
+
+ @Test
+ public void testSomethingThatIsNotAnImageIsAdmitted() throws Exception {
+ assertTrue(check(new BlankImageCheck(), new byte[] {1, 2, 3, 4}).admitted());
+ }
+
+ @Test
+ public void testALargeImageIsSubsampledNotRefused() throws Exception {
+ // 3000 x 3000: read at one third; the block of ink is still found
+ assertTrue(check(new BlankImageCheck(), ImageFixtures.png(3000, 3000, 0.2)).admitted());
+ assertEquals(false, check(new BlankImageCheck(), ImageFixtures.png(3000, 3000, 0))
+ .admitted());
+ }
+
+ private static byte[] speckled(int width, int height, double density) throws Exception {
+ java.awt.image.BufferedImage image = new java.awt.image.BufferedImage(width, height,
+ java.awt.image.BufferedImage.TYPE_INT_RGB);
+ java.awt.Graphics2D g = image.createGraphics();
+ g.setColor(Color.WHITE);
+ g.fillRect(0, 0, width, height);
+ g.dispose();
+ java.util.Random random = new java.util.Random(7);
+ for (int y = 0; y < height; y++) {
+ for (int x = 0; x < width; x++) {
+ if (random.nextDouble() < density) {
+ image.setRGB(x, y, 0);
+ }
+ }
+ }
+ java.io.ByteArrayOutputStream out = new java.io.ByteArrayOutputStream();
+ javax.imageio.ImageIO.write(image, "png", out);
+ return out.toByteArray();
+ }
+
+ @Test
+ public void testScatteredSpecksAreBlank() throws Exception {
+ for (double density : new double[] {0.001, 0.01, 0.05}) {
+ assertEquals(false, check(new BlankImageCheck(), speckled(800, 1000, density))
+ .admitted(), "salt-and-pepper noise of " + density);
+ }
+ }
+
+ @Test
+ public void testDespeckleCanBeTurnedOff() throws Exception {
+ BlankImageCheck raw = new BlankImageCheck();
+ raw.setDespeckle(false);
+ assertTrue(check(raw, speckled(800, 1000, 0.01)).admitted());
+ }
+
+ @Test
+ public void testTextIsNotMistakenForSpecks() throws Exception {
+ java.awt.image.BufferedImage image = new java.awt.image.BufferedImage(800, 400,
+ java.awt.image.BufferedImage.TYPE_INT_RGB);
+ java.awt.Graphics2D g = image.createGraphics();
+ g.setColor(Color.WHITE);
+ g.fillRect(0, 0, 800, 400);
+ g.setColor(Color.BLACK);
+ g.setFont(new java.awt.Font(java.awt.Font.SANS_SERIF, java.awt.Font.PLAIN, 11));
+ for (int line = 0; line < 20; line++) {
+ g.drawString("The quick brown fox jumps over the lazy dog, again and again.", 10,
+ 20 + line * 18);
+ }
+ g.dispose();
+ java.io.ByteArrayOutputStream out = new java.io.ByteArrayOutputStream();
+ javax.imageio.ImageIO.write(image, "png", out);
+ assertTrue(check(new BlankImageCheck(), out.toByteArray()).admitted());
+ }
+
+ @Test
+ public void testBadSettingsAreRefused() {
+ BlankImageCheck check = new BlankImageCheck();
+ assertThrows(IllegalArgumentException.class, () -> check.setMaxInk(-0.1));
+ assertThrows(IllegalArgumentException.class, () -> check.setMaxInk(1));
+ assertThrows(IllegalArgumentException.class, () -> check.setTolerance(256));
+ }
+
+ @Test
+ public void testDarkTextOnATransparentBackgroundIsAdmitted() throws Exception {
+ // transparent pixels stored as RGB 0, the same as the text
+ byte[] image = ImageFixtures.encode(ImageFixtures.image(BufferedImage.TYPE_INT_ARGB,
+ 300, 400, 0x00000000, 0xFF000000, 0.1), "png");
+ assertTrue(check(new BlankImageCheck(), image).admitted());
+ }
+
+ @Test
+ public void testLightTextOnATransparentBackgroundIsAdmitted() throws Exception {
+ byte[] image = ImageFixtures.encode(ImageFixtures.image(BufferedImage.TYPE_INT_ARGB,
+ 300, 400, 0x00FFFFFF, 0xFFFFFFFF, 0.1), "png");
+ assertTrue(check(new BlankImageCheck(), image).admitted());
+ }
+
+ @Test
+ public void testIndexedTextOnATransparentBackgroundIsAdmitted() throws Exception {
+ IndexColorModel palette = new IndexColorModel(8, 2, new byte[] {0, 0},
+ new byte[] {0, 0}, new byte[] {0, 0}, new byte[] {0, (byte) 255});
+ BufferedImage indexed = new BufferedImage(300, 400, BufferedImage.TYPE_BYTE_INDEXED,
+ palette);
+ for (int y = 0; y < 400; y++) {
+ for (int x = 0; x < 30; x++) {
+ indexed.getRaster().setSample(x, y, 0, 1);
+ }
+ }
+ assertTrue(check(new BlankImageCheck(), ImageFixtures.encode(indexed, "png")).admitted());
+ }
+
+ @Test
+ public void testAFullyTransparentImageIsBlank() throws Exception {
+ byte[] image = ImageFixtures.encode(ImageFixtures.image(BufferedImage.TYPE_INT_ARGB,
+ 300, 400, 0x00000000, 0x00000000, 0), "png");
+ assertEquals(false, check(new BlankImageCheck(), image).admitted());
+ }
+}
diff --git a/tika-image-processing/src/test/java/org/apache/tika/imageprocessing/ByteSizeCheckTest.java b/tika-image-processing/src/test/java/org/apache/tika/imageprocessing/ByteSizeCheckTest.java
new file mode 100644
index 0000000000..574fba6433
--- /dev/null
+++ b/tika-image-processing/src/test/java/org/apache/tika/imageprocessing/ByteSizeCheckTest.java
@@ -0,0 +1,82 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.tika.imageprocessing;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.io.ByteArrayInputStream;
+
+import org.junit.jupiter.api.Test;
+
+import org.apache.tika.io.TikaInputStream;
+import org.apache.tika.metadata.Metadata;
+import org.apache.tika.parser.ParseContext;
+import org.apache.tika.parser.enricher.ImageCheck;
+import org.apache.tika.parser.enricher.ImageProbe;
+
+public class ByteSizeCheckTest {
+
+ private static ImageCheck.Verdict check(ByteSizeCheck check, int length) throws Exception {
+ return check.check(new ImageProbe(TikaInputStream.get(new byte[length]), new Metadata()),
+ new Metadata(), new ParseContext());
+ }
+
+ @Test
+ public void testDefaultsAdmitEverything() throws Exception {
+ assertTrue(check(new ByteSizeCheck(), 0).admitted());
+ assertTrue(check(new ByteSizeCheck(), 10_000_000).admitted());
+ }
+
+ @Test
+ public void testMinBytes() throws Exception {
+ ByteSizeCheck check = new ByteSizeCheck();
+ check.setMinBytes(100);
+ ImageCheck.Verdict small = check(check, 99);
+ assertEquals(false, small.admitted());
+ assertEquals("file-too-small", small.reason());
+ assertTrue(check(check, 100).admitted());
+ }
+
+ @Test
+ public void testMaxBytes() throws Exception {
+ ByteSizeCheck check = new ByteSizeCheck();
+ check.setMaxBytes(1000);
+ ImageCheck.Verdict large = check(check, 1001);
+ assertEquals(false, large.admitted());
+ assertEquals("file-too-large", large.reason());
+ assertTrue(check(check, 1000).admitted());
+ }
+
+ @Test
+ public void testAnUnknownLengthIsAdmitted() throws Exception {
+ ByteSizeCheck check = new ByteSizeCheck();
+ check.setMinBytes(100);
+ check.setMaxBytes(200);
+ ImageProbe probe = new ImageProbe(
+ TikaInputStream.get(new ByteArrayInputStream(new byte[5])), new Metadata());
+ assertTrue(check.check(probe, new Metadata(), new ParseContext()).admitted());
+ }
+
+ @Test
+ public void testBadSettingsAreRefused() {
+ ByteSizeCheck check = new ByteSizeCheck();
+ assertThrows(IllegalArgumentException.class, () -> check.setMinBytes(-1));
+ assertThrows(IllegalArgumentException.class, () -> check.setMaxBytes(-1));
+ }
+}
diff --git a/tika-image-processing/src/test/java/org/apache/tika/imageprocessing/ImageChecksConfigTest.java b/tika-image-processing/src/test/java/org/apache/tika/imageprocessing/ImageChecksConfigTest.java
new file mode 100644
index 0000000000..787ea7dfe0
--- /dev/null
+++ b/tika-image-processing/src/test/java/org/apache/tika/imageprocessing/ImageChecksConfigTest.java
@@ -0,0 +1,161 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.tika.imageprocessing;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.List;
+
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+import org.xml.sax.helpers.DefaultHandler;
+
+import org.apache.tika.config.loader.TikaLoader;
+import org.apache.tika.exception.TikaConfigException;
+import org.apache.tika.io.TikaInputStream;
+import org.apache.tika.metadata.Metadata;
+import org.apache.tika.metadata.TikaCoreProperties;
+import org.apache.tika.mime.MediaType;
+import org.apache.tika.parser.ParseContext;
+import org.apache.tika.parser.Parser;
+import org.apache.tika.parser.enricher.CompositeContentEnricher;
+import org.apache.tika.parser.enricher.GatedEnricher;
+import org.apache.tika.parser.mock.MockEnricher;
+
+/** The checks as a deployment lists them: by name under a "text-recognizers" entry. */
+public class ImageChecksConfigTest {
+
+ @TempDir
+ Path tmp;
+
+ private Parser engine(String entry) throws Exception {
+ Path config = tmp.resolve("tika-config.json");
+ Files.writeString(config, "{ \"engines\": { \"png\": { \"mock-enricher\": {} } },"
+ + " \"text-recognizers\": [ " + entry + " ] }");
+ List<Parser> matched = TikaLoader.load(config).get(CompositeContentEnricher.class)
+ .getEnrichers(MediaType.image("png"));
+ assertEquals(1, matched.size());
+ return matched.get(0);
+ }
+
+ private static Metadata read(Parser engine, byte[] image) throws Exception {
+ Metadata metadata = new Metadata();
+ try (TikaInputStream tis = TikaInputStream.get(image)) {
+ engine.parse(tis, new DefaultHandler(), metadata, new ParseContext());
+ }
+ return metadata;
+ }
+
+ @Test
+ public void testNamedChecksWrapTheEngineOnce() throws Exception {
+ Parser engine = engine("{ \"engine\": \"png\", \"_min-width\": 8, \"checks\": ["
+ + " {\"min-image-size\": {}}, {\"blank-image-check\": {\"maxInk\": 0.001}} ] }");
+ GatedEnricher gate = (GatedEnricher) engine;
+ // the recorded-size minimum, then the two named checks, in one decorator
+ assertEquals(3, gate.getChecks().size());
+ assertTrue(gate.getChecks().get(1) instanceof MinImageSizeCheck);
+ assertTrue(gate.getChecks().get(2) instanceof BlankImageCheck);
+ }
+
+ @Test
+ public void testABlankImageNeverReachesTheEngine() throws Exception {
+ Parser engine = engine("{ \"engine\": \"png\", \"checks\": [ \"blank-image-check\" ] }");
+ Metadata m = read(engine, ImageFixtures.png(200, 200, 0));
+ assertNull(m.get(MockEnricher.MARKER_KEY));
+ assertEquals("skipped:blank", m.get(TikaCoreProperties.OCR_WARNINGS));
+ }
+
+ @Test
+ public void testAnImageWithInkReachesTheEngine() throws Exception {
+ Parser engine = engine("{ \"engine\": \"png\", \"checks\": ["
+ + " {\"min-image-size\": {}}, {\"blank-image-check\": {}} ] }");
+ Metadata m = read(engine, ImageFixtures.png(200, 200, 0.2));
+ assertEquals("ENRICHED", m.get(MockEnricher.MARKER_KEY));
+ assertNull(m.get(TikaCoreProperties.OCR_WARNINGS));
+ }
+
+ @Test
+ public void testChecksRunInTheOrderListedAndTheFirstRefusalWins() throws Exception {
+ // a blank 20x20 image is too small and blank; the order decides the reason
+ byte[] tiny = ImageFixtures.png(20, 20, 0);
+ Parser sizeFirst = engine("{ \"engine\": \"png\", \"checks\": ["
+ + " \"min-image-size\", \"blank-image-check\" ] }");
+ assertEquals("skipped:image-too-small",
+ read(sizeFirst, tiny).get(TikaCoreProperties.OCR_WARNINGS));
+ Parser blankFirst = engine("{ \"engine\": \"png\", \"checks\": ["
+ + " \"blank-image-check\", \"min-image-size\" ] }");
+ assertEquals("skipped:blank",
+ read(blankFirst, tiny).get(TikaCoreProperties.OCR_WARNINGS));
+ }
+
+ @Test
+ public void testTheInlineFormTakesChecksToo() throws Exception {
+ Parser engine = engine("{ \"mock-enricher\": { \"checks\": [ \"blank-image-check\" ] } }");
+ assertEquals("skipped:blank", read(engine, ImageFixtures.png(200, 200, 0))
+ .get(TikaCoreProperties.OCR_WARNINGS));
+ }
+
+ @Test
+ public void testSettingsAreBoundToTheCheck() throws Exception {
+ Parser engine = engine("{ \"engine\": \"png\", \"checks\": ["
+ + " {\"min-image-size\": {\"minWidthPixels\": 300, \"minHeightPixels\": 0, \"minTotalPixels\": 0}} ] }");
+ assertEquals("skipped:image-too-small", read(engine, ImageFixtures.png(200, 200, 0.5))
+ .get(TikaCoreProperties.OCR_WARNINGS));
+ assertEquals("ENRICHED", read(engine, ImageFixtures.png(400, 50, 0.5))
+ .get(MockEnricher.MARKER_KEY));
+ }
+
+ @Test
+ public void testByteSizeCheckByName() throws Exception {
+ Parser engine = engine("{ \"engine\": \"png\", \"checks\": ["
+ + " {\"byte-size\": {\"minBytes\": 1000000}} ] }");
+ assertEquals("skipped:file-too-small", read(engine, ImageFixtures.png(200, 200, 0.5))
+ .get(TikaCoreProperties.OCR_WARNINGS));
+ }
+
+ @Test
+ public void testAnUnknownCheckFailsLoad() {
+ assertThrows(TikaConfigException.class, () -> engine("{ \"engine\": \"png\","
+ + " \"checks\": [ \"no-such-check\" ] }"));
+ }
+
+ @Test
+ public void testChecksMustBeAnArray() {
+ TikaConfigException e = assertThrows(TikaConfigException.class, () -> engine(
+ "{ \"engine\": \"png\", \"checks\": \"blank-image-check\" }"));
+ assertTrue(e.getMessage().contains("must be an array"), e.getMessage());
+ }
+
+ @Test
+ public void testACheckWithTwoNamesFailsLoad() {
+ TikaConfigException e = assertThrows(TikaConfigException.class, () -> engine(
+ "{ \"engine\": \"png\", \"checks\": ["
+ + " {\"min-image-size\": {}, \"blank-image-check\": {}} ] }"));
+ assertTrue(e.getMessage().contains("a \"checks\" member"), e.getMessage());
+ }
+
+ @Test
+ public void testAComponentThatIsNotACheckFailsLoad() {
+ assertThrows(TikaConfigException.class, () -> engine("{ \"engine\": \"png\","
+ + " \"checks\": [ \"mock-enricher\" ] }"));
+ }
+}
diff --git a/tika-image-processing/src/test/java/org/apache/tika/imageprocessing/ImageDecodingTest.java b/tika-image-processing/src/test/java/org/apache/tika/imageprocessing/ImageDecodingTest.java
new file mode 100644
index 0000000000..58ef20916b
--- /dev/null
+++ b/tika-image-processing/src/test/java/org/apache/tika/imageprocessing/ImageDecodingTest.java
@@ -0,0 +1,88 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.tika.imageprocessing;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.awt.image.BufferedImage;
+import java.io.ByteArrayOutputStream;
+import javax.imageio.IIOImage;
+import javax.imageio.ImageIO;
+import javax.imageio.ImageWriteParam;
+import javax.imageio.ImageWriter;
+import javax.imageio.stream.ImageOutputStream;
+
+import org.junit.jupiter.api.Test;
+
+public class ImageDecodingTest {
+
+ private static byte[] jpeg(int width, int height, boolean progressive) throws Exception {
+ BufferedImage image = ImageFixtures.image(BufferedImage.TYPE_3BYTE_BGR, width, height,
+ 0xFFFFFFFF, 0xFF000000, 0.1);
+ ImageWriter writer = ImageIO.getImageWritersByFormatName("jpeg").next();
+ ImageWriteParam param = writer.getDefaultWriteParam();
+ if (progressive) {
+ param.setProgressiveMode(ImageWriteParam.MODE_DEFAULT);
+ }
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ try (ImageOutputStream ios = ImageIO.createImageOutputStream(out)) {
+ writer.setOutput(ios);
+ writer.write(null, new IIOImage(image, null, null), param);
+ } finally {
+ writer.dispose();
+ }
+ return out.toByteArray();
+ }
+
+ /** The jpeg with its frame header claiming {@code width} x {@code height}. */
+ private static byte[] claimSize(byte[] jpeg, int width, int height) {
+ byte[] patched = jpeg.clone();
+ for (int i = 2; i + 8 < patched.length; i++) {
+ int marker = patched[i + 1] & 255;
+ if ((patched[i] & 255) == 0xFF && (marker == 0xC0 || marker == 0xC2)) {
+ patched[i + 5] = (byte) (height >> 8);
+ patched[i + 6] = (byte) height;
+ patched[i + 7] = (byte) (width >> 8);
+ patched[i + 8] = (byte) width;
+ return patched;
+ }
+ }
+ throw new IllegalStateException("no frame header");
+ }
+
+ @Test
+ public void testProgressiveJpegsAreRecognized() throws Exception {
+ assertTrue(ImageDecoding.mayBeProgressiveJpeg(jpeg(64, 64, true)));
+ assertFalse(ImageDecoding.mayBeProgressiveJpeg(jpeg(64, 64, false)));
+ assertFalse(ImageDecoding.mayBeProgressiveJpeg(ImageFixtures.png(64, 64, 0.1)));
+ // the frame header is past what was read: assume the worst
+ assertTrue(ImageDecoding.mayBeProgressiveJpeg(new byte[] {(byte) 0xFF, (byte) 0xD8,
+ (byte) 0xFF, (byte) 0xE1, 0x10, 0x00, 0, 0}));
+ }
+
+ @Test
+ public void testALargeProgressiveJpegIsNotDecoded() throws Exception {
+ byte[] large = claimSize(jpeg(64, 64, true), 5000, 5000);
+ assertArrayEquals(new long[] {5000, 5000}, ImageDecoding.size(ImageFixtures.probe(large)));
+ assertNull(ImageDecoding.gray(ImageFixtures.probe(large)));
+ assertNotNull(ImageDecoding.gray(ImageFixtures.probe(jpeg(64, 64, true))));
+ }
+}
diff --git a/tika-image-processing/src/test/java/org/apache/tika/imageprocessing/ImageFixtures.java b/tika-image-processing/src/test/java/org/apache/tika/imageprocessing/ImageFixtures.java
new file mode 100644
index 0000000000..b9b62b42d7
--- /dev/null
+++ b/tika-image-processing/src/test/java/org/apache/tika/imageprocessing/ImageFixtures.java
@@ -0,0 +1,77 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.tika.imageprocessing;
+
+import java.awt.Color;
+import java.awt.Graphics2D;
+import java.awt.image.BufferedImage;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import javax.imageio.ImageIO;
+
+import org.apache.tika.io.TikaInputStream;
+import org.apache.tika.parser.enricher.ImageProbe;
+
+final class ImageFixtures {
+
+ private ImageFixtures() {
+ }
+
+ /** A white image, with a black block over {@code inkFraction} of its width when positive. */
+ static byte[] png(int width, int height, double inkFraction) throws IOException {
+ return png(width, height, inkFraction, Color.WHITE);
+ }
+
+ static byte[] png(int width, int height, double inkFraction, Color background)
+ throws IOException {
+ BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
+ Graphics2D g = image.createGraphics();
+ g.setColor(background);
+ g.fillRect(0, 0, width, height);
+ if (inkFraction > 0) {
+ g.setColor(Color.BLACK);
+ g.fillRect(0, 0, (int) Math.max(1, Math.round(width * inkFraction)), height);
+ }
+ g.dispose();
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ ImageIO.write(image, "png", out);
+ return out.toByteArray();
+ }
+
+ /** An image of {@code type} filled with {@code background}, a block of {@code ink} on it. */
+ static BufferedImage image(int type, int width, int height, int backgroundArgb,
+ int inkArgb, double inkFraction) {
+ BufferedImage image = new BufferedImage(width, height, type);
+ int inkWidth = (int) Math.round(width * inkFraction);
+ for (int y = 0; y < height; y++) {
+ for (int x = 0; x < width; x++) {
+ image.setRGB(x, y, x < inkWidth ? inkArgb : backgroundArgb);
+ }
+ }
+ return image;
+ }
+
+ static byte[] encode(BufferedImage image, String format) throws IOException {
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ ImageIO.write(image, format, out);
+ return out.toByteArray();
+ }
+
+ static ImageProbe probe(byte[] bytes) {
+ return new ImageProbe(TikaInputStream.get(bytes), new org.apache.tika.metadata.Metadata());
+ }
+}
diff --git a/tika-image-processing/src/test/java/org/apache/tika/imageprocessing/MinImageSizeCheckTest.java b/tika-image-processing/src/test/java/org/apache/tika/imageprocessing/MinImageSizeCheckTest.java
new file mode 100644
index 0000000000..2d3835e208
--- /dev/null
+++ b/tika-image-processing/src/test/java/org/apache/tika/imageprocessing/MinImageSizeCheckTest.java
@@ -0,0 +1,121 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.tika.imageprocessing;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import org.junit.jupiter.api.Test;
+
+import org.apache.tika.metadata.Metadata;
+import org.apache.tika.parser.ParseContext;
+import org.apache.tika.parser.enricher.ImageCheck;
+
+public class MinImageSizeCheckTest {
+
+ private static ImageCheck.Verdict check(MinImageSizeCheck check, byte[] image)
+ throws Exception {
+ return check.check(ImageFixtures.probe(image), new Metadata(), new ParseContext());
+ }
+
+ @Test
+ public void testDefaultsRefuseATinyImage() throws Exception {
+ ImageCheck.Verdict v = check(new MinImageSizeCheck(), ImageFixtures.png(20, 20, 0.5));
+ assertEquals(false, v.admitted());
+ assertEquals("image-too-small", v.reason());
+ }
+
+ @Test
+ public void testDefaultsAdmitA100x100Image() throws Exception {
+ assertTrue(check(new MinImageSizeCheck(), ImageFixtures.png(100, 100, 0.5)).admitted());
+ }
+
+ @Test
+ public void testAThinStripPassesTheAreaTestButNotTheSideMinimum() throws Exception {
+ byte[] strip = ImageFixtures.png(1000, 11, 0.5);
+ assertEquals(false, check(new MinImageSizeCheck(), strip).admitted());
+ MinImageSizeCheck noSides = new MinImageSizeCheck();
+ noSides.setMinShortSidePixels(0);
+ noSides.setMinTotalPixels(10_000);
+ assertTrue(check(noSides, strip).admitted());
+ }
+
+ @Test
+ public void testMinWidthPixelsAndMinHeightPixelsAddToMinShortSidePixels() throws Exception {
+ MinImageSizeCheck banner = new MinImageSizeCheck();
+ banner.setMinTotalPixels(0);
+ banner.setMinShortSidePixels(10);
+ banner.setMinWidthPixels(300);
+ // 200 x 40 clears the side minimum but not the width asked for
+ assertEquals(false, check(banner, ImageFixtures.png(200, 40, 0.5)).admitted());
+ assertTrue(check(banner, ImageFixtures.png(400, 40, 0.5)).admitted());
+ }
+
+ @Test
+ public void testZeroTurnsATestOff() throws Exception {
+ MinImageSizeCheck off = new MinImageSizeCheck();
+ off.setMinTotalPixels(0);
+ off.setMinShortSidePixels(0);
+ assertTrue(check(off, ImageFixtures.png(2, 2, 0.5)).admitted());
+ }
+
+ /** A grayscale TIFF whose directory, with the dimensions, follows the pixel data. */
+ private static byte[] tiffWithDirectoryAtTheEnd(int width, int height) {
+ int data = width * height;
+ java.nio.ByteBuffer b = java.nio.ByteBuffer.allocate(8 + data + 2 + 9 * 12 + 4)
+ .order(java.nio.ByteOrder.LITTLE_ENDIAN);
+ b.put((byte) 'I').put((byte) 'I').putShort((short) 42).putInt(8 + data);
+ b.position(8 + data);
+ b.putShort((short) 9);
+ // tag, type (3 short, 4 long), value: width, length, bits, no compression, black is
+ // zero, strip offset, samples, rows per strip, strip byte count
+ int[][] entries = {{256, 3, width}, {257, 3, height}, {258, 3, 8}, {259, 3, 1},
+ {262, 3, 1}, {273, 4, 8}, {277, 3, 1}, {278, 3, height}, {279, 4, data}};
+ for (int[] e : entries) {
+ b.putShort((short) e[0]).putShort((short) e[1]).putInt(1).putInt(e[2]);
+ }
+ b.putInt(0);
+ return b.array();
+ }
+
+ @Test
+ public void testADimensionAtTheEndOfALargeFileIsStillRead() throws Exception {
+ // past the first megabyte the header read cannot see the directory; the check then
+ // reads the whole image
+ byte[] tiff = tiffWithDirectoryAtTheEnd(1500, 1500);
+ MinImageSizeCheck check = new MinImageSizeCheck();
+ check.setMinTotalPixels(10_000_000);
+ // refused only if the 1500 x 1500 size was found
+ assertEquals(false, check(check, tiff).admitted());
+ MinImageSizeCheck small = new MinImageSizeCheck();
+ small.setMinTotalPixels(1_000_000);
+ assertTrue(check(small, tiff).admitted());
+ }
+
+ @Test
+ public void testAnUnreadableImageIsAdmitted() throws Exception {
+ assertTrue(check(new MinImageSizeCheck(), new byte[] {1, 2, 3}).admitted());
+ }
+
+ @Test
+ public void testBadSettingsAreRefused() {
+ MinImageSizeCheck check = new MinImageSizeCheck();
+ assertThrows(IllegalArgumentException.class, () -> check.setMinTotalPixels(-1));
+ assertThrows(IllegalArgumentException.class, () -> check.setMinWidthPixels(-1));
+ }
+}
diff --git a/tika-metadata-schema/src/main/resources/org/apache/tika/metadata/metadata-key-fields.json b/tika-metadata-schema/src/main/resources/org/apache/tika/metadata/metadata-key-fields.json
index 2926590d46..e140d726c2 100644
--- a/tika-metadata-schema/src/main/resources/org/apache/tika/metadata/metadata-key-fields.json
+++ b/tika-metadata-schema/src/main/resources/org/apache/tika/metadata/metadata-key-fields.json
@@ -552,6 +552,7 @@
{"class":"org.apache.tika.metadata.TikaCoreProperties","field":"MODIFIED","key":"dcterms:modified"},
{"class":"org.apache.tika.metadata.TikaCoreProperties","field":"MODIFIER","key":"meta:last-author"},
{"class":"org.apache.tika.metadata.TikaCoreProperties","field":"NUM_IMAGES","key":"tk:num-images"},
+ {"class":"org.apache.tika.metadata.TikaCoreProperties","field":"OCR_WARNINGS","key":"tk:ocr-warnings"},
{"class":"org.apache.tika.metadata.TikaCoreProperties","field":"ORIGINAL_RESOURCE_NAME","key":"tk:orig-resource-name"},
{"class":"org.apache.tika.metadata.TikaCoreProperties","field":"PARSE_TIME_MILLIS","key":"tk:parse-time-millis"},
{"class":"org.apache.tika.metadata.TikaCoreProperties","field":"PIPES_RESULT","key":"tk:pipes-result"},
@@ -796,8 +797,10 @@
{"class":"org.apache.tika.parser.video.FLVParser","field":"HAS_AUDIO","key":"flv:hasAudio"},
{"class":"org.apache.tika.parser.video.FLVParser","field":"HAS_VIDEO","key":"flv:hasVideo"},
{"class":"org.apache.tika.parser.vlm.AbstractVLMParser","field":"VLM_COMPLETION_TOKENS","key":"vlm:completion-tokens"},
+ {"class":"org.apache.tika.parser.vlm.AbstractVLMParser","field":"VLM_IMAGE_PIXELS","key":"vlm:image-pixels"},
{"class":"org.apache.tika.parser.vlm.AbstractVLMParser","field":"VLM_MODEL","key":"vlm:model"},
{"class":"org.apache.tika.parser.vlm.AbstractVLMParser","field":"VLM_PROMPT_TOKENS","key":"vlm:prompt-tokens"},
+ {"class":"org.apache.tika.parser.vlm.AbstractVLMParser","field":"VLM_SKIPPED_REASON","key":"vlm:skipped-reason"},
{"class":"org.apache.tika.parser.xml.XMLProfiler","field":"ENTITY_LOCAL_NAMES","key":"xmlprofiler:entity-local-names"},
{"class":"org.apache.tika.parser.xml.XMLProfiler","field":"ENTITY_URIS","key":"xmlprofiler:entity-uris"},
{"class":"org.apache.tika.parser.xml.XMLProfiler","field":"ROOT_ENTITY","key":"xmlprofiler:root-entity"},
diff --git a/tika-metadata-schema/src/main/resources/org/apache/tika/metadata/metadata-keys.json b/tika-metadata-schema/src/main/resources/org/apache/tika/metadata/metadata-keys.json
index cac32492ea..c7e3475e68 100644
--- a/tika-metadata-schema/src/main/resources/org/apache/tika/metadata/metadata-keys.json
+++ b/tika-metadata-schema/src/main/resources/org/apache/tika/metadata/metadata-keys.json
@@ -618,6 +618,7 @@
{"key":"tk:inference-released","namespace":"tk","valueType":"TEXT","cardinality":"BAG","module":"tika-core"},
{"key":"tk:internal-path","namespace":"tk","valueType":"TEXT","cardinality":"SIMPLE","module":"tika-core"},
{"key":"tk:num-images","namespace":"tk","valueType":"INTEGER","cardinality":"SIMPLE","module":"tika-core"},
+ {"key":"tk:ocr-warnings","namespace":"tk","valueType":"TEXT","cardinality":"BAG","module":"tika-core"},
{"key":"tk:orig-resource-name","namespace":"tk","valueType":"TEXT","cardinality":"BAG","module":"tika-core"},
{"key":"tk:page:number","namespace":"tk","valueType":"INTEGER","cardinality":"SIMPLE","module":"tika-core"},
{"key":"tk:page:numbers","namespace":"tk","valueType":"INTEGER","cardinality":"SEQ","module":"tika-core"},
@@ -651,8 +652,10 @@
{"key":"video:fourcc","namespace":"video","valueType":"TEXT","cardinality":"SIMPLE","module":"tika-core"},
{"key":"video:frame-rate","namespace":"video","valueType":"REAL","cardinality":"SIMPLE","module":"tika-core"},
{"key":"vlm:completion-tokens","namespace":"vlm","valueType":"INTEGER","cardinality":"SIMPLE","module":"tika-vlm"},
+ {"key":"vlm:image-pixels","namespace":"vlm","valueType":"INTEGER","cardinality":"SIMPLE","module":"tika-vlm"},
{"key":"vlm:model","namespace":"vlm","valueType":"TEXT","cardinality":"SIMPLE","module":"tika-vlm"},
{"key":"vlm:prompt-tokens","namespace":"vlm","valueType":"INTEGER","cardinality":"SIMPLE","module":"tika-vlm"},
+ {"key":"vlm:skipped-reason","namespace":"vlm","valueType":"TEXT","cardinality":"SIMPLE","module":"tika-vlm"},
{"key":"vorbis:vendor","namespace":"vorbis","valueType":"TEXT","cardinality":"SIMPLE","module":"tika-parser-audiovideo-module"},
{"key":"w:Comments","namespace":"w","valueType":"TEXT","cardinality":"BAG","module":"tika-core"},
{"key":"warc:WARC-Record-ID","namespace":"warc","valueType":"TEXT","cardinality":"SIMPLE","module":"tika-core"},
diff --git a/tika-parsers/tika-http-jdk/src/main/java/org/apache/tika/http/TikaHttpClient.java b/tika-parsers/tika-http-jdk/src/main/java/org/apache/tika/http/TikaHttpClient.java
index 8688a72241..be4abb6ce3 100644
--- a/tika-parsers/tika-http-jdk/src/main/java/org/apache/tika/http/TikaHttpClient.java
+++ b/tika-parsers/tika-http-jdk/src/main/java/org/apache/tika/http/TikaHttpClient.java
@@ -18,7 +18,9 @@ package org.apache.tika.http;
import java.io.Closeable;
import java.io.IOException;
+import java.net.ConnectException;
import java.net.URI;
+import java.net.UnknownHostException;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
@@ -36,6 +38,7 @@ import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
+import javax.net.ssl.SSLException;
import org.apache.tika.config.ParseTimeout;
import org.apache.tika.exception.TikaException;
@@ -62,13 +65,21 @@ import org.apache.tika.parser.ParseContext;
* budget the parse granted the call. Any other status fails at once. The retries cover
* collisions between a few parse workers, not a sustained excess of workers over the key's
* concurrency.
+ * <p>
+ * A connection that drops, or is cut short before a full response arrives, is retried the
+ * same way: the JDK client does not resend a POST on a keep-alive connection the service
+ * has already closed, and the failure surfaces as an {@link IOException} such as
+ * {@code HTTP/1.1 header parser received no bytes}. It shares the {@code maxRetries} count
+ * and the budget with the status retries; a service that had already read the request may
+ * bill the call twice. Failures a retry cannot fix (unknown host,
+ * refused connection, TLS errors) and interruption fail at once.
* @since Apache Tika 4.0
*/
public class TikaHttpClient implements Closeable {
private static final String JSON_CONTENT_TYPE = "application/json; charset=utf-8";
- /** Retries of a 429/502/503/504 answer unless {@link #build(int, int)} says otherwise. */
+ /** Retries of a 429/502/503/504 answer or a dropped connection unless {@link #build(int, int)} says otherwise. */
public static final int DEFAULT_MAX_RETRIES = 4;
private static final Set<Integer> RETRYABLE = Set.of(429, 502, 503, 504);
private static final long INITIAL_BACKOFF_MILLIS = 250;
@@ -106,8 +117,8 @@ public class TikaHttpClient implements Closeable {
* Create a new {@code TikaHttpClient} with a daemon-thread executor.
*
* @param connectTimeoutSeconds TCP connection timeout in seconds
- * @param maxRetries how many times a 429, 502, 503 or 504 answer is retried;
- * 0 fails on the first one
+ * @param maxRetries how many times a 429, 502, 503 or 504 answer, or a dropped
+ * connection, is retried; 0 fails on the first one
*/
public static TikaHttpClient build(int connectTimeoutSeconds, int maxRetries) {
if (maxRetries < 0) {
@@ -281,7 +292,21 @@ public class TikaHttpClient implements Closeable {
HttpRequest attemptRequest = attempt == 0 ? request
: HttpRequest.newBuilder(request, (name, value) -> true)
.timeout(Duration.ofMillis(remaining)).build();
- HttpResponse<String> response = sendOnce(attemptRequest, context, requestedMillis, remaining);
+ HttpResponse<String> response;
+ try {
+ response = sendOnce(attemptRequest, context, requestedMillis, remaining);
+ } catch (IOException e) {
+ if (attempt >= maxRetries || !isRetryableTransportFailure(e)) {
+ throw e;
+ }
+ long delay = backoffMillis(attempt);
+ long left = grantedMillis - (System.nanoTime() - startNanos) / 1_000_000L;
+ if (delay >= left) {
+ throw e;
+ }
+ sleepWithHeartbeat(delay, context);
+ continue;
+ }
int status = response.statusCode();
if (status >= 200 && status < 300) {
return response.body();
@@ -326,6 +351,17 @@ public class TikaHttpClient implements Closeable {
}
}
+ /**
+ * A dropped or truncated exchange is worth resending; a server that is not there, a TLS
+ * failure, or an interrupted thread will not be fixed by waiting. {@code sendOnce} sets the
+ * interrupt flag when it reports an interruption.
+ */
+ static boolean isRetryableTransportFailure(IOException e) {
+ return !Thread.currentThread().isInterrupted()
+ && !(e instanceof UnknownHostException || e instanceof ConnectException
+ || e instanceof SSLException);
+ }
+
/** The server's Retry-After (delta seconds or an HTTP date) when usable, else backoff. */
static long retryDelayMillis(HttpResponse<String> response, int attempt) {
String retryAfter = response.headers().firstValue("Retry-After").orElse(null);
diff --git a/tika-parsers/tika-http-jdk/src/test/java/org/apache/tika/http/TikaHttpClientTest.java b/tika-parsers/tika-http-jdk/src/test/java/org/apache/tika/http/TikaHttpClientTest.java
index a2a296fb6c..3a10243975 100644
--- a/tika-parsers/tika-http-jdk/src/test/java/org/apache/tika/http/TikaHttpClientTest.java
+++ b/tika-parsers/tika-http-jdk/src/test/java/org/apache/tika/http/TikaHttpClientTest.java
@@ -17,11 +17,16 @@
package org.apache.tika.http;
import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
+import java.io.IOException;
+import java.net.ConnectException;
+import java.net.UnknownHostException;
import java.util.Map;
+import javax.net.ssl.SSLHandshakeException;
import org.junit.jupiter.api.Test;
@@ -272,6 +277,87 @@ public class TikaHttpClientTest {
}
}
+ /** A service that closes the connection without answering is retried, as a 503 is. */
+ @Test
+ public void testRetriesADroppedConnectionThenSucceeds() throws Exception {
+ try (TikaTestHttpServer server = new TikaTestHttpServer();
+ TikaHttpClient client = TikaHttpClient.build(30, 4)) {
+ server.enqueue(MockResponse.dropConnection());
+ server.enqueue(MockResponse.dropConnection());
+ server.enqueue(new MockResponse(200, "{\"ok\":true}"));
+ long start = System.currentTimeMillis();
+ String body = client.postJson(server.url(), "{}", Map.of(), 10_000, new ParseContext());
+ long elapsed = System.currentTimeMillis() - start;
+ assertEquals("{\"ok\":true}", body);
+ assertEquals(3, server.getRequestCount());
+ assertTrue(elapsed >= 187 + 375, "two backoffs, 250 and 500 ms less jitter: " + elapsed);
+ }
+ }
+
+ @Test
+ public void testGivesUpOnADroppedConnectionAfterMaxRetries() throws Exception {
+ try (TikaTestHttpServer server = new TikaTestHttpServer();
+ TikaHttpClient client = TikaHttpClient.build(30, 2)) {
+ for (int i = 0; i < 4; i++) {
+ server.enqueue(MockResponse.dropConnection());
+ }
+ assertThrows(IOException.class,
+ () -> client.postJson(server.url(), "{}", Map.of(), 10_000, new ParseContext()));
+ assertEquals(3, server.getRequestCount(), "one attempt plus two retries");
+ }
+ }
+
+ @Test
+ public void testZeroRetriesFailsOnTheFirstDroppedConnection() throws Exception {
+ try (TikaTestHttpServer server = new TikaTestHttpServer();
+ TikaHttpClient client = TikaHttpClient.build(30, 0)) {
+ server.enqueue(MockResponse.dropConnection());
+ server.enqueue(new MockResponse(200, "{}"));
+ assertThrows(IOException.class,
+ () -> client.postJson(server.url(), "{}", Map.of(), 10_000, new ParseContext()));
+ assertEquals(1, server.getRequestCount());
+ }
+ }
+
+ /**
+ * Backoffs of 250 ms doubling to 4 s cannot all fit in a 3 s budget: the call ends with the
+ * transport failure itself, not a timeout, before the budget is spent.
+ */
+ @Test
+ public void testDroppedConnectionBackoffNeverSleepsPastTheBudget() throws Exception {
+ try (TikaTestHttpServer server = new TikaTestHttpServer();
+ TikaHttpClient client = TikaHttpClient.build(30, 10)) {
+ for (int i = 0; i < 12; i++) {
+ server.enqueue(MockResponse.dropConnection());
+ }
+ long start = System.currentTimeMillis();
+ assertThrows(IOException.class,
+ () -> client.postJson(server.url(), "{}", Map.of(), 3000, new ParseContext()));
+ long elapsed = System.currentTimeMillis() - start;
+ assertTrue(elapsed < 3000, "gave up before the budget ran out: " + elapsed);
+ assertTrue(server.getRequestCount() > 1, "it did retry: " + server.getRequestCount());
+ assertTrue(server.getRequestCount() < 11, "not every retry was taken: " + server.getRequestCount());
+ }
+ }
+
+ /** Waiting cannot bring back a host that is not there, a failed handshake, or an interrupted thread. */
+ @Test
+ public void testOnlyTransientTransportFailuresAreRetryable() {
+ assertTrue(TikaHttpClient.isRetryableTransportFailure(
+ new IOException("HTTP/1.1 header parser received no bytes")));
+ assertTrue(TikaHttpClient.isRetryableTransportFailure(
+ new IOException("chunked transfer encoding, state: READING_LENGTH")));
+ assertFalse(TikaHttpClient.isRetryableTransportFailure(new UnknownHostException("no.such.host")));
+ assertFalse(TikaHttpClient.isRetryableTransportFailure(new ConnectException("Connection refused")));
+ assertFalse(TikaHttpClient.isRetryableTransportFailure(new SSLHandshakeException("bad certificate")));
+ Thread.currentThread().interrupt();
+ try {
+ assertFalse(TikaHttpClient.isRetryableTransportFailure(new IOException("HTTP request interrupted")));
+ } finally {
+ Thread.interrupted();
+ }
+ }
+
@Test
public void testRetryAfterParsing() {
assertEquals(7000, TikaHttpClient.parseRetryAfterMillis("7"));
diff --git a/tika-parsers/tika-http-jdk/src/test/java/org/apache/tika/http/TikaTestHttpServer.java b/tika-parsers/tika-http-jdk/src/test/java/org/apache/tika/http/TikaTestHttpServer.java
index f042bf21cd..99336a8c43 100644
--- a/tika-parsers/tika-http-jdk/src/test/java/org/apache/tika/http/TikaTestHttpServer.java
+++ b/tika-parsers/tika-http-jdk/src/test/java/org/apache/tika/http/TikaTestHttpServer.java
@@ -77,6 +77,15 @@ public class TikaTestHttpServer implements Closeable {
public MockResponse(int status, String body, Map<String, String> headers) {
this(status, body, 0, 0, headers);
}
+
+ /**
+ * Reads the whole request, then closes the connection without writing a byte --
+ * the client sees {@code HTTP/1.1 header parser received no bytes}, as when a
+ * service closes a keep-alive connection the client is about to reuse.
+ */
+ public static MockResponse dropConnection() {
+ return new MockResponse(0, "");
+ }
}
/** A captured incoming HTTP request. */
@@ -187,6 +196,9 @@ public class TikaTestHttpServer implements Closeable {
if (resp == null) {
resp = new MockResponse(500, "{\"error\":\"no response queued\"}");
}
+ if (resp.status() == 0) {
+ return;
+ }
if (resp.delayMillis() > 0) {
try {
diff --git a/tika-parsers/tika-parsers-ml/tika-inference/src/main/java/org/apache/tika/inference/OpenAIEmbeddingEngine.java b/tika-parsers/tika-parsers-ml/tika-inference/src/main/java/org/apache/tika/inference/OpenAIEmbeddingEngine.java
index e4433ed98b..719bacf413 100644
--- a/tika-parsers/tika-parsers-ml/tika-inference/src/main/java/org/apache/tika/inference/OpenAIEmbeddingEngine.java
+++ b/tika-parsers/tika-parsers-ml/tika-inference/src/main/java/org/apache/tika/inference/OpenAIEmbeddingEngine.java
@@ -275,7 +275,7 @@ public class OpenAIEmbeddingEngine implements EmbeddingEngine, Initializable {
return maxRetries;
}
- /** Retries of a 429/502/503/504 answer, with backoff inside the parse budget; 0 fails at once. */
+ /** Retries of a 429/502/503/504 answer or a dropped connection, with backoff inside the parse budget; 0 fails at once. */
public void setMaxRetries(int maxRetries) {
this.maxRetries = maxRetries;
}
diff --git a/tika-parsers/tika-parsers-ml/tika-vlm/src/main/java/org/apache/tika/parser/vlm/AbstractVLMParser.java b/tika-parsers/tika-parsers-ml/tika-vlm/src/main/java/org/apache/tika/parser/vlm/AbstractVLMParser.java
index 8467369f75..1bcb912f0b 100644
--- a/tika-parsers/tika-parsers-ml/tika-vlm/src/main/java/org/apache/tika/parser/vlm/AbstractVLMParser.java
+++ b/tika-parsers/tika-parsers-ml/tika-vlm/src/main/java/org/apache/tika/parser/vlm/AbstractVLMParser.java
@@ -26,6 +26,7 @@ import java.util.Collections;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
+import java.util.zip.Deflater;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -48,6 +49,7 @@ import org.apache.tika.metadata.TikaCoreProperties;
import org.apache.tika.mime.MediaType;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.parser.Parser;
+import org.apache.tika.parser.enricher.OcrWarnings;
import org.apache.tika.parser.enricher.TextRecognizer;
import org.apache.tika.sax.BodyContentHandler;
import org.apache.tika.sax.EmbeddedContentHandler;
@@ -81,6 +83,28 @@ public abstract class AbstractVLMParser implements Parser, Initializable, Closea
public static final Property VLM_COMPLETION_TOKENS =
Property.externalInteger(VLM_META + "completion-tokens");
+ /** Why the file was not sent to the VLM; absent when it was sent. */
+ public static final Property VLM_SKIPPED_REASON =
+ Property.externalText(VLM_META + "skipped-reason");
+ /** Pixel count of an image that was skipped as too large. */
+ public static final Property VLM_IMAGE_PIXELS =
+ Property.externalInteger(VLM_META + "image-pixels");
+
+ static final String WARN_TRUNCATED = "truncated";
+ static final String WARN_REPETITION = "repetition";
+ static final String WARN_EMPTY = "empty";
+
+ /**
+ * Output of at least this many bytes that deflates below this ratio is a loop. A loop
+ * deflates to about 1.5 %; an HTML table of numbers to 12 %, dot leaders to 8 %.
+ */
+ private static final int REPETITION_MIN_BYTES = 1000;
+ private static final double REPETITION_MAX_DEFLATE_RATIO = 0.05;
+
+ static final String SKIP_FILE_TOO_SMALL = "file-too-small";
+ static final String SKIP_FILE_TOO_LARGE = "file-too-large";
+ static final String SKIP_IMAGE_TOO_LARGE = "image-too-large";
+
/**
* Encapsulates a fully built HTTP request for a VLM API call.
*
@@ -195,9 +219,12 @@ public abstract class AbstractVLMParser implements Parser, Initializable, Closea
}
long size = tis.getLength();
- if (size >= 0
- && (size < config.getMinFileSizeToOcr()
- || size > config.getMaxFileSizeToOcr())) {
+ if (size >= 0 && size < config.getMinFileSizeToOcr()) {
+ skip(parseContext, metadata, SKIP_FILE_TOO_SMALL);
+ return;
+ }
+ if (size >= 0 && size > config.getMaxFileSizeToOcr()) {
+ skip(parseContext, metadata, SKIP_FILE_TOO_LARGE);
return;
}
@@ -207,10 +234,13 @@ public abstract class AbstractVLMParser implements Parser, Initializable, Closea
if (maxPixels > 0 && mimeType.startsWith("image/")) {
tis.mark((int) Math.min(tis.getLength() + 1, 1024 * 1024));
try {
- long pixels = getImagePixels(tis);
+ long[] dims = getImageSize(tis);
+ long pixels = dims == null ? -1 : dims[0] * dims[1];
if (pixels > maxPixels) {
LOG.warn("Image has {} pixels, exceeding maxImagePixels={}. "
+ "Skipping VLM OCR.", pixels, maxPixels);
+ metadata.set(VLM_IMAGE_PIXELS, (int) Math.min(pixels, Integer.MAX_VALUE));
+ skip(parseContext, metadata, SKIP_IMAGE_TOO_LARGE);
return;
}
} catch (IOException e) {
@@ -239,6 +269,7 @@ public abstract class AbstractVLMParser implements Parser, Initializable, Closea
}
metadata.set(VLM_MODEL, config.getModel());
+ checkOutput(parseContext, metadata, responseText);
ContentHandler baseHandler = getContentHandler(
config.isInlineContent(), handler, metadata, parseContext);
@@ -378,28 +409,68 @@ public abstract class AbstractVLMParser implements Parser, Initializable, Closea
return is.readAllBytes();
}
+ private static void skip(ParseContext parseContext, Metadata metadata, String reason) {
+ metadata.set(VLM_SKIPPED_REASON, reason);
+ warn(metadata, "skipped:" + reason);
+ OcrWarnings.addToInlineParent(parseContext, metadata, "skipped:" + reason);
+ }
+
+ static void warn(Metadata metadata, String code) {
+ OcrWarnings.add(metadata, code);
+ }
+
+ private void checkOutput(ParseContext parseContext, Metadata metadata, String text) {
+ if (text == null || text.isBlank()) {
+ warn(metadata, WARN_EMPTY);
+ } else if (looksLikeLoop(text)) {
+ warn(metadata, WARN_REPETITION);
+ }
+ for (String code : metadata.getValues(TikaCoreProperties.OCR_WARNINGS)) {
+ OcrWarnings.addToInlineParent(parseContext, metadata, code);
+ }
+ }
+
+ /** Text that deflates this well is a repeated line or sentence, not prose. */
+ static boolean looksLikeLoop(String text) {
+ byte[] in = text.getBytes(java.nio.charset.StandardCharsets.UTF_8);
+ if (in.length < REPETITION_MIN_BYTES) {
+ return false;
+ }
+ Deflater deflater = new Deflater(Deflater.DEFAULT_COMPRESSION);
+ try {
+ deflater.setInput(in);
+ deflater.finish();
+ byte[] buf = new byte[8192];
+ long out = 0;
+ while (!deflater.finished()) {
+ out += deflater.deflate(buf);
+ }
+ return (double) out / in.length < REPETITION_MAX_DEFLATE_RATIO;
+ } finally {
+ deflater.end();
+ }
+ }
+
/**
* Reads only the image header to determine width × height
- * without decoding the full raster. Returns {@code -1} if dimensions
+ * without decoding the full raster. Returns null if dimensions
* cannot be determined.
*/
- private long getImagePixels(InputStream is) throws IOException {
+ private long[] getImageSize(InputStream is) throws IOException {
try (javax.imageio.stream.ImageInputStream iis =
javax.imageio.ImageIO.createImageInputStream(is)) {
if (iis == null) {
- return -1;
+ return null;
}
java.util.Iterator<javax.imageio.ImageReader> readers =
javax.imageio.ImageIO.getImageReaders(iis);
if (!readers.hasNext()) {
- return -1;
+ return null;
}
javax.imageio.ImageReader reader = readers.next();
try {
reader.setInput(iis);
- long w = reader.getWidth(0);
- long h = reader.getHeight(0);
- return w * h;
+ return new long[] {reader.getWidth(0), reader.getHeight(0)};
} finally {
reader.dispose();
}
@@ -448,6 +519,14 @@ public abstract class AbstractVLMParser implements Parser, Initializable, Closea
defaultConfig.setMaxTokens(maxTokens);
}
+ public Double getTemperature() {
+ return defaultConfig.getTemperature();
+ }
+
+ public void setTemperature(Double temperature) {
+ defaultConfig.setTemperature(temperature);
+ }
+
public long getTimeoutMillis() {
return defaultConfig.getTimeoutMillis();
}
@@ -456,7 +535,7 @@ public abstract class AbstractVLMParser implements Parser, Initializable, Closea
defaultConfig.setTimeoutMillis(timeoutMillis);
}
- /** Retries of a 429/502/503/504 answer from the service; 0 fails at once. */
+ /** Retries of a 429/502/503/504 answer or a dropped connection; 0 fails at once. */
public synchronized void setMaxRetries(int maxRetries) {
defaultConfig.setMaxRetries(maxRetries);
if (httpClient != null) {
diff --git a/tika-parsers/tika-parsers-ml/tika-vlm/src/main/java/org/apache/tika/parser/vlm/ClaudeVLMParser.java b/tika-parsers/tika-parsers-ml/tika-vlm/src/main/java/org/apache/tika/parser/vlm/ClaudeVLMParser.java
index b8fddaafa9..d617c7fed0 100644
--- a/tika-parsers/tika-parsers-ml/tika-vlm/src/main/java/org/apache/tika/parser/vlm/ClaudeVLMParser.java
+++ b/tika-parsers/tika-parsers-ml/tika-vlm/src/main/java/org/apache/tika/parser/vlm/ClaudeVLMParser.java
@@ -142,9 +142,13 @@ public class ClaudeVLMParser extends AbstractVLMParser {
}
}
+ if ("max_tokens".equals(root.path("stop_reason").asText())) {
+ warn(metadata, WARN_TRUNCATED);
+ }
+
// Content blocks
JsonNode content = root.get("content");
- if (content == null || !content.isArray() || content.isEmpty()) {
+ if (content == null || !content.isArray()) {
throw new TikaException(
"Claude response contains no content: " + responseBody);
}
@@ -191,6 +195,9 @@ public class ClaudeVLMParser extends AbstractVLMParser {
ObjectNode root = MAPPER.createObjectNode();
root.put("model", config.getModel());
root.put("max_tokens", config.getMaxTokens());
+ if (config.getTemperature() != null) {
+ root.put("temperature", config.getTemperature());
+ }
ArrayNode messages = root.putArray("messages");
ObjectNode userMessage = messages.addObject();
diff --git a/tika-parsers/tika-parsers-ml/tika-vlm/src/main/java/org/apache/tika/parser/vlm/GeminiVLMParser.java b/tika-parsers/tika-parsers-ml/tika-vlm/src/main/java/org/apache/tika/parser/vlm/GeminiVLMParser.java
index b5757797f4..be0496da61 100644
--- a/tika-parsers/tika-parsers-ml/tika-vlm/src/main/java/org/apache/tika/parser/vlm/GeminiVLMParser.java
+++ b/tika-parsers/tika-parsers-ml/tika-vlm/src/main/java/org/apache/tika/parser/vlm/GeminiVLMParser.java
@@ -150,6 +150,10 @@ public class GeminiVLMParser extends AbstractVLMParser {
throw new TikaException("Gemini response contains no candidates: " + responseBody);
}
+ if ("MAX_TOKENS".equals(candidates.get(0).path("finishReason").asText())) {
+ warn(metadata, WARN_TRUNCATED);
+ }
+
JsonNode content = candidates.get(0).get("content");
if (content == null) {
throw new TikaException("Gemini candidate has no content: " + responseBody);
@@ -221,6 +225,9 @@ public class GeminiVLMParser extends AbstractVLMParser {
// generation config
ObjectNode generationConfig = root.putObject("generationConfig");
generationConfig.put("maxOutputTokens", config.getMaxTokens());
+ if (config.getTemperature() != null) {
+ generationConfig.put("temperature", config.getTemperature());
+ }
return root.toString();
}
diff --git a/tika-parsers/tika-parsers-ml/tika-vlm/src/main/java/org/apache/tika/parser/vlm/OpenAIVLMParser.java b/tika-parsers/tika-parsers-ml/tika-vlm/src/main/java/org/apache/tika/parser/vlm/OpenAIVLMParser.java
index d72d767c91..bb05d608fc 100644
--- a/tika-parsers/tika-parsers-ml/tika-vlm/src/main/java/org/apache/tika/parser/vlm/OpenAIVLMParser.java
+++ b/tika-parsers/tika-parsers-ml/tika-vlm/src/main/java/org/apache/tika/parser/vlm/OpenAIVLMParser.java
@@ -153,6 +153,10 @@ public class OpenAIVLMParser extends AbstractVLMParser {
throw new TikaException("VLM response contains no choices: " + responseBody);
}
+ if ("length".equals(choices.get(0).path("finish_reason").asText())) {
+ warn(metadata, WARN_TRUNCATED);
+ }
+
JsonNode message = choices.get(0).get("message");
if (message == null) {
throw new TikaException("VLM response choice has no message: " + responseBody);
@@ -238,6 +242,9 @@ public class OpenAIVLMParser extends AbstractVLMParser {
root.put("model", config.getModel());
root.put(config.isUseMaxCompletionTokens() ? "max_completion_tokens" : "max_tokens",
config.getMaxTokens());
+ if (config.getTemperature() != null) {
+ root.put("temperature", config.getTemperature());
+ }
ArrayNode messages = root.putArray("messages");
ObjectNode userMessage = messages.addObject();
diff --git a/tika-parsers/tika-parsers-ml/tika-vlm/src/main/java/org/apache/tika/parser/vlm/VLMOCRConfig.java b/tika-parsers/tika-parsers-ml/tika-vlm/src/main/java/org/apache/tika/parser/vlm/VLMOCRConfig.java
index 6eb174cd9e..49ba81b6ee 100644
--- a/tika-parsers/tika-parsers-ml/tika-vlm/src/main/java/org/apache/tika/parser/vlm/VLMOCRConfig.java
+++ b/tika-parsers/tika-parsers-ml/tika-vlm/src/main/java/org/apache/tika/parser/vlm/VLMOCRConfig.java
@@ -61,6 +61,13 @@ public class VLMOCRConfig implements Serializable {
/** Maximum number of tokens the model may generate. */
private int maxTokens = 4096;
+ /**
+ * Sampling temperature sent with each request; {@code null} (the default) sends none, so the
+ * service's own default applies. {@code 0} makes repeated requests for the same image
+ * return the same text on services that honor it. Claude accepts 0 to 1.
+ */
+ private Double temperature = null;
+
/**
* OpenAI-compatible parser only: send the limit as {@code max_completion_tokens}
* instead of {@code max_tokens}. Newer OpenAI models (o-series, GPT-5 and later)
@@ -74,7 +81,7 @@ public class VLMOCRConfig implements Serializable {
*/
private long timeoutMillis = 120_000;
- /** Retries of a 429/502/503/504 answer from the service; 0 fails at once. */
+ /** Retries of a 429/502/503/504 answer or a dropped connection; 0 fails at once. */
private int maxRetries = 4;
/** Optional API key for authenticated endpoints. Empty means no auth. */
@@ -168,6 +175,19 @@ public class VLMOCRConfig implements Serializable {
this.maxTokens = maxTokens;
}
+ public Double getTemperature() {
+ return temperature;
+ }
+
+ @OperatorOnly
+ public void setTemperature(Double temperature) {
+ if (temperature != null && (temperature < 0 || temperature > 2)) {
+ throw new IllegalArgumentException(
+ "temperature must be between 0 and 2, got: " + temperature);
+ }
+ this.temperature = temperature;
+ }
+
public boolean isUseMaxCompletionTokens() {
return useMaxCompletionTokens;
}
diff --git a/tika-parsers/tika-parsers-ml/tika-vlm/src/test/java/org/apache/tika/parser/vlm/ClaudeVLMParserTest.java b/tika-parsers/tika-parsers-ml/tika-vlm/src/test/java/org/apache/tika/parser/vlm/ClaudeVLMParserTest.java
index 59868d1672..bd0bae6798 100644
--- a/tika-parsers/tika-parsers-ml/tika-vlm/src/test/java/org/apache/tika/parser/vlm/ClaudeVLMParserTest.java
+++ b/tika-parsers/tika-parsers-ml/tika-vlm/src/test/java/org/apache/tika/parser/vlm/ClaudeVLMParserTest.java
@@ -224,6 +224,32 @@ public class ClaudeVLMParserTest {
assertEquals("40", metadata.get(AbstractVLMParser.VLM_COMPLETION_TOKENS));
}
+ @Test
+ void testTemperatureSentOnlyWhenSet() {
+ assertFalse(parser.buildRequestJson(config, "AAAA", "image/png").contains("temperature"));
+ config.setTemperature(0.0);
+ assertTrue(parser.buildRequestJson(config, "AAAA", "image/png")
+ .contains("\"temperature\":0.0"));
+ }
+
+ @Test
+ void testTruncatedWarning() throws Exception {
+ String json = "{\"content\":[{\"type\":\"text\",\"text\":\"cut\"}],"
+ + "\"stop_reason\":\"max_tokens\"}";
+ Metadata metadata = new Metadata();
+ parser.extractResponseText(json, metadata);
+ assertEquals("truncated", metadata.get(org.apache.tika.metadata.TikaCoreProperties.OCR_WARNINGS));
+ }
+
+ @Test
+ void testAnEmptyAnswerIsEmptyText() throws Exception {
+ // the token budget can run out before any block is written
+ String json = "{\"content\":[],\"stop_reason\":\"max_tokens\"}";
+ Metadata metadata = new Metadata();
+ assertEquals("", parser.extractResponseText(json, metadata));
+ assertEquals("truncated", metadata.get(org.apache.tika.metadata.TikaCoreProperties.OCR_WARNINGS));
+ }
+
@Test
void testBuildRequestJsonImage() {
String json = parser.buildRequestJson(config, "AAAA", "image/png");
diff --git a/tika-parsers/tika-parsers-ml/tika-vlm/src/test/java/org/apache/tika/parser/vlm/GeminiVLMParserTest.java b/tika-parsers/tika-parsers-ml/tika-vlm/src/test/java/org/apache/tika/parser/vlm/GeminiVLMParserTest.java
index 6ce48981f2..172b220b51 100644
--- a/tika-parsers/tika-parsers-ml/tika-vlm/src/test/java/org/apache/tika/parser/vlm/GeminiVLMParserTest.java
+++ b/tika-parsers/tika-parsers-ml/tika-vlm/src/test/java/org/apache/tika/parser/vlm/GeminiVLMParserTest.java
@@ -209,6 +209,24 @@ public class GeminiVLMParserTest {
assertEquals("20", metadata.get(AbstractVLMParser.VLM_COMPLETION_TOKENS));
}
+ @Test
+ void testTemperatureSentOnlyWhenSet() {
+ assertTrue(!parser.buildRequestJson(config, "AAAA", "application/pdf")
+ .contains("temperature"));
+ config.setTemperature(0.0);
+ assertTrue(parser.buildRequestJson(config, "AAAA", "application/pdf")
+ .contains("\"temperature\":0.0"));
+ }
+
+ @Test
+ void testTruncatedWarning() throws Exception {
+ String json = "{\"candidates\":[{\"finishReason\":\"MAX_TOKENS\","
+ + "\"content\":{\"parts\":[{\"text\":\"cut\"}]}}]}";
+ Metadata metadata = new Metadata();
+ parser.extractResponseText(json, metadata);
+ assertEquals("truncated", metadata.get(org.apache.tika.metadata.TikaCoreProperties.OCR_WARNINGS));
+ }
+
@Test
void testBuildRequestJson() {
String json = parser.buildRequestJson(config, "AAAA", "application/pdf");
diff --git a/tika-parsers/tika-parsers-ml/tika-vlm/src/test/java/org/apache/tika/parser/vlm/OpenAIVLMParserTest.java b/tika-parsers/tika-parsers-ml/tika-vlm/src/test/java/org/apache/tika/parser/vlm/OpenAIVLMParserTest.java
index ab9cbf1eec..67d33772a1 100644
--- a/tika-parsers/tika-parsers-ml/tika-vlm/src/test/java/org/apache/tika/parser/vlm/OpenAIVLMParserTest.java
+++ b/tika-parsers/tika-parsers-ml/tika-vlm/src/test/java/org/apache/tika/parser/vlm/OpenAIVLMParserTest.java
@@ -156,7 +156,7 @@ public class OpenAIVLMParserTest {
@Test
void testFileSizeFiltering() throws Exception {
config.setMinFileSizeToOcr(100);
- parser = new OpenAIVLMParser(config);
+ reinitialize();
Metadata metadata = new Metadata();
metadata.set(HttpHeaders.CONTENT_TYPE, "image/png");
@@ -167,6 +167,70 @@ public class OpenAIVLMParserTest {
}
assertEquals(0, server.getRequestCount());
+ assertEquals("file-too-small", metadata.get(AbstractVLMParser.VLM_SKIPPED_REASON));
+ }
+
+ @Test
+ void testFileTooLargeRecordsSkip() throws Exception {
+ config.setMaxFileSizeToOcr(5);
+ reinitialize();
+
+ Metadata metadata = new Metadata();
+ metadata.set(HttpHeaders.CONTENT_TYPE, "image/png");
+
+ try (TikaInputStream tis = TikaInputStream.get(
+ new ByteArrayInputStream(new byte[10]))) {
+ parser.parse(tis, new BodyContentHandler(), metadata, new ParseContext());
+ }
+
+ assertEquals(0, server.getRequestCount());
+ assertEquals("file-too-large", metadata.get(AbstractVLMParser.VLM_SKIPPED_REASON));
+ }
+
+ @Test
+ void testImageTooLargeRecordsSkip() throws Exception {
+ config.setMaxImagePixels(3);
+ reinitialize();
+
+ Metadata metadata = new Metadata();
+ metadata.set(HttpHeaders.CONTENT_TYPE, "image/png");
+
+ try (TikaInputStream tis = TikaInputStream.get(
+ new ByteArrayInputStream(png(2, 2)))) {
+ parser.parse(tis, new BodyContentHandler(), metadata, new ParseContext());
+ }
+
+ assertEquals(0, server.getRequestCount());
+ assertEquals("image-too-large", metadata.get(AbstractVLMParser.VLM_SKIPPED_REASON));
+ assertEquals("4", metadata.get(AbstractVLMParser.VLM_IMAGE_PIXELS));
+ }
+
+ private void reinitialize() throws Exception {
+ server.enqueue(new TikaTestHttpServer.MockResponse(200, "{\"object\":\"list\"}"));
+ parser = new OpenAIVLMParser(config);
+ parser.initialize();
+ server.clearRequests();
+ }
+
+ /** A white image with a black block over its left third, so it is not blank. */
+ private static byte[] png(int width, int height) throws Exception {
+ return png(width, height, true);
+ }
+
+ private static byte[] png(int width, int height, boolean ink) throws Exception {
+ java.awt.image.BufferedImage image = new java.awt.image.BufferedImage(width, height,
+ java.awt.image.BufferedImage.TYPE_INT_RGB);
+ java.awt.Graphics2D g = image.createGraphics();
+ g.setColor(java.awt.Color.WHITE);
+ g.fillRect(0, 0, width, height);
+ if (ink) {
+ g.setColor(java.awt.Color.BLACK);
+ g.fillRect(0, 0, Math.max(1, width / 3), height);
+ }
+ g.dispose();
+ java.io.ByteArrayOutputStream out = new java.io.ByteArrayOutputStream();
+ javax.imageio.ImageIO.write(image, "png", out);
+ return out.toByteArray();
}
@Test
@@ -275,6 +339,20 @@ public class OpenAIVLMParserTest {
assertTrue(json.contains("data:image/png;base64,AAAA"));
}
+ @Test
+ void testTemperatureSentOnlyWhenSet() {
+ assertFalse(parser.buildRequestJson(config, "AAAA", "image/png").contains("temperature"));
+ config.setTemperature(0.0);
+ assertTrue(parser.buildRequestJson(config, "AAAA", "image/png")
+ .contains("\"temperature\":0.0"));
+ }
+
+ @Test
+ void testTemperatureOutOfRange() {
+ assertThrows(IllegalArgumentException.class, () -> config.setTemperature(-0.1));
+ assertThrows(IllegalArgumentException.class, () -> config.setTemperature(2.1));
+ }
+
@Test
void testExtractResponseText() throws Exception {
Metadata metadata = new Metadata();
@@ -329,6 +407,139 @@ public class OpenAIVLMParserTest {
prompt, completion);
}
+ private Metadata parseImage(String responseBody, ParseContext context, Metadata metadata)
+ throws Exception {
+ server.enqueue(new TikaTestHttpServer.MockResponse(200, responseBody));
+ metadata.set(HttpHeaders.CONTENT_TYPE, "image/png");
+ try (TikaInputStream tis = TikaInputStream.get(
+ new ByteArrayInputStream(new byte[]{(byte) 0x89, 'P', 'N', 'G'}))) {
+ parser.parse(tis, new BodyContentHandler(), metadata, context);
+ }
+ return metadata;
+ }
+
+ @Test
+ void testNoWarningsOnOrdinaryText() throws Exception {
+ Metadata m = parseImage(buildChatResponse("Hello, World!", 10, 5),
+ new ParseContext(), new Metadata());
+ assertEquals(0, m.getValues(org.apache.tika.metadata.TikaCoreProperties.OCR_WARNINGS).length);
+ }
+
+ @Test
+ void testTruncatedWarning() throws Exception {
+ String body = "{\"choices\":[{\"finish_reason\":\"length\","
+ + "\"message\":{\"content\":\"cut off\"}}]}";
+ Metadata m = parseImage(body, new ParseContext(), new Metadata());
+ assertEquals("truncated", m.get(org.apache.tika.metadata.TikaCoreProperties.OCR_WARNINGS));
+ }
+
+ @Test
+ void testEmptyWarning() throws Exception {
+ Metadata m = parseImage(buildChatResponse(" ", 10, 5), new ParseContext(),
+ new Metadata());
+ assertEquals("empty", m.get(org.apache.tika.metadata.TikaCoreProperties.OCR_WARNINGS));
+ }
+
+ @Test
+ void testRepetitionWarningKeepsText() throws Exception {
+ String loop = "SUEZ (D)\n".repeat(400);
+ server.enqueue(new TikaTestHttpServer.MockResponse(200, buildChatResponse(loop, 10, 5)));
+ Metadata metadata = new Metadata();
+ metadata.set(HttpHeaders.CONTENT_TYPE, "image/png");
+ BodyContentHandler handler = new BodyContentHandler(-1);
+ try (TikaInputStream tis = TikaInputStream.get(
+ new ByteArrayInputStream(new byte[]{(byte) 0x89, 'P', 'N', 'G'}))) {
+ parser.parse(tis, handler, metadata, new ParseContext());
+ }
+ assertEquals("repetition", metadata.get(org.apache.tika.metadata.TikaCoreProperties.OCR_WARNINGS));
+ assertTrue(handler.toString().contains("SUEZ (D)"));
+ }
+
+ @Test
+ void testAShortLoopIsARepetition() {
+ // 1,000 to 2,000 bytes: a loop the model's token cap cuts off early
+ String loop = "TAPAN ".repeat(250);
+ assertTrue(loop.length() >= 1000 && loop.length() < 2000);
+ assertTrue(AbstractVLMParser.looksLikeLoop(loop));
+ assertFalse(AbstractVLMParser.looksLikeLoop("TAPAN ".repeat(100)));
+ }
+
+ @Test
+ void testProseIsNotARepetition() {
+ StringBuilder sb = new StringBuilder();
+ java.util.Random random = new java.util.Random(1);
+ for (int i = 0; i < 600; i++) {
+ sb.append(Integer.toString(random.nextInt(1_000_000), 36)).append(' ');
+ }
+ assertFalse(AbstractVLMParser.looksLikeLoop(sb.toString()));
+ assertFalse(AbstractVLMParser.looksLikeLoop("short ".repeat(10)));
+ // 1,000 to 2,000 bytes of ordinary varied text
+ assertFalse(AbstractVLMParser.looksLikeLoop(sb.substring(0, 1500)));
+ }
+
+ @Test
+ void testTablesAndLeadersAreNotARepetition() {
+ java.util.Random random = new java.util.Random(1);
+ String[] items = {"alpha", "beta", "gamma", "delta"};
+ StringBuilder table = new StringBuilder("<table>\n");
+ for (int i = 0; i < 200; i++) {
+ table.append("<tr><td>").append(random.nextInt(9999)).append("</td><td>Item ")
+ .append(items[random.nextInt(4)]).append("</td><td>")
+ .append(random.nextInt(99)).append('.').append(random.nextInt(99))
+ .append("</td><td></td><td></td></tr>\n");
+ }
+ assertFalse(AbstractVLMParser.looksLikeLoop(table.append("</table>").toString()));
+ StringBuilder contents = new StringBuilder();
+ for (int i = 1; i < 40; i++) {
+ contents.append("Chapter ").append(i).append(' ').append(".".repeat(60)).append(' ')
+ .append(i * 7).append('\n');
+ }
+ assertFalse(AbstractVLMParser.looksLikeLoop(contents.toString()));
+ }
+
+ @Test
+ void testInlineImageFlagsTheParent() throws Exception {
+ Metadata parent = new Metadata();
+ ParseContext context = new ParseContext();
+ context.set(org.apache.tika.extractor.ParentMetadata.class,
+ new org.apache.tika.extractor.ParentMetadata(parent));
+ Metadata child = new Metadata();
+ child.set(org.apache.tika.metadata.TikaCoreProperties.EMBEDDED_RESOURCE_TYPE,
+ org.apache.tika.metadata.TikaCoreProperties.EmbeddedResourceType.INLINE.name());
+ parseImage(buildChatResponse(" ", 10, 5), context, child);
+ assertEquals("empty", child.get(org.apache.tika.metadata.TikaCoreProperties.OCR_WARNINGS));
+ assertEquals("empty", parent.get(org.apache.tika.metadata.TikaCoreProperties.OCR_WARNINGS));
+ }
+
+ @Test
+ void testNonInlineImageLeavesTheParentAlone() throws Exception {
+ Metadata parent = new Metadata();
+ ParseContext context = new ParseContext();
+ context.set(org.apache.tika.extractor.ParentMetadata.class,
+ new org.apache.tika.extractor.ParentMetadata(parent));
+ parseImage(buildChatResponse(" ", 10, 5), context, new Metadata());
+ assertNull(parent.get(org.apache.tika.metadata.TikaCoreProperties.OCR_WARNINGS));
+ }
+
+ @Test
+ void testSkippedInlineImageFlagsTheParent() throws Exception {
+ config.setMinFileSizeToOcr(100);
+ reinitialize();
+ Metadata parent = new Metadata();
+ ParseContext context = new ParseContext();
+ context.set(org.apache.tika.extractor.ParentMetadata.class,
+ new org.apache.tika.extractor.ParentMetadata(parent));
+ Metadata child = new Metadata();
+ child.set(org.apache.tika.metadata.TikaCoreProperties.EMBEDDED_RESOURCE_TYPE,
+ org.apache.tika.metadata.TikaCoreProperties.EmbeddedResourceType.INLINE.name());
+ child.set(HttpHeaders.CONTENT_TYPE, "image/png");
+ try (TikaInputStream tis = TikaInputStream.get(new ByteArrayInputStream(new byte[10]))) {
+ parser.parse(tis, new BodyContentHandler(), child, context);
+ }
+ assertEquals("file-too-small", child.get(AbstractVLMParser.VLM_SKIPPED_REASON));
+ assertEquals("skipped:file-too-small", parent.get(org.apache.tika.metadata.TikaCoreProperties.OCR_WARNINGS));
+ }
+
/** The capability follows the configuration: a captioning prompt is not a recognizer. */
@Test
void testRecognizesTextFollowsConfig() {
diff --git a/tika-parsers/tika-parsers-ml/tika-vlm/src/test/java/org/apache/tika/parser/vlm/VLMConfigExamplesTest.java b/tika-parsers/tika-parsers-ml/tika-vlm/src/test/java/org/apache/tika/parser/vlm/VLMConfigExamplesTest.java
index cdfcf3c7f2..6e1d27b92d 100644
--- a/tika-parsers/tika-parsers-ml/tika-vlm/src/test/java/org/apache/tika/parser/vlm/VLMConfigExamplesTest.java
+++ b/tika-parsers/tika-parsers-ml/tika-vlm/src/test/java/org/apache/tika/parser/vlm/VLMConfigExamplesTest.java
@@ -16,6 +16,7 @@
*/
package org.apache.tika.parser.vlm;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
@@ -23,6 +24,8 @@ import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
@@ -36,8 +39,9 @@ import org.apache.tika.parser.Parser;
* in the docs.
*
* <p>The JSON files under {@code src/test/resources/config-examples/} are
- * symlinked from {@code docs/modules/ROOT/examples/}, so any change that
- * keeps these tests passing also keeps the published docs correct.
+ * copies of those in {@code docs/modules/ROOT/examples/}, kept identical by
+ * {@link #testExamplesMatchTheDocs()}, so any change that keeps these tests
+ * passing also keeps the published docs correct.
*
* <p>The tests only validate that the JSON deserializes and the parser
* constructs — no HTTP call is made to any model endpoint, so they're safe
@@ -53,7 +57,9 @@ public class VLMConfigExamplesTest {
private Parser loadAndValidate(String resourceName) throws Exception {
try (InputStream is = getClass().getResourceAsStream(EXAMPLES_DIR + resourceName)) {
assertNotNull(is, "Resource not found: " + resourceName);
- String json = new String(is.readAllBytes(), StandardCharsets.UTF_8);
+ // an unset ${env:...} fails the load; the examples name keys the build lacks
+ String json = new String(is.readAllBytes(), StandardCharsets.UTF_8)
+ .replaceAll("\\$\\{env:[A-Za-z0-9_]+}", "");
Path configFile = tempDir.resolve("tika-config.json");
Files.writeString(configFile, json, StandardCharsets.UTF_8);
TikaLoader loader = TikaLoader.load(configFile);
@@ -106,4 +112,22 @@ public class VLMConfigExamplesTest {
public void testVLMForPdfParsing() throws Exception {
loadAndValidate("vlm-pdf-parsing.json");
}
+
+ @Test
+ public void testJinaOCRBasic() throws Exception {
+ loadAndValidate("jina-ocr-basic.json");
+ }
+
+ @Test
+ public void testExamplesMatchTheDocs() throws Exception {
+ Path docs = Paths.get("../../../docs/modules/ROOT/examples");
+ assumeTrue(Files.isDirectory(docs), "docs not checked out");
+ try (Stream<Path> examples = Files.list(Paths.get("src/test/resources/config-examples"))) {
+ for (Path example : (Iterable<Path>) examples::iterator) {
+ Path doc = docs.resolve(example.getFileName());
+ assertEquals(Files.readString(doc), Files.readString(example),
+ example.getFileName() + " differs from its docs copy");
+ }
+ }
+ }
}
diff --git a/tika-parsers/tika-parsers-ml/tika-vlm/src/test/java/org/apache/tika/parser/vlm/VLMOperatorOnlyConfigTest.java b/tika-parsers/tika-parsers-ml/tika-vlm/src/test/java/org/apache/tika/parser/vlm/VLMOperatorOnlyConfigTest.java
index f47182a77f..8ff6bcd59d 100644
--- a/tika-parsers/tika-parsers-ml/tika-vlm/src/test/java/org/apache/tika/parser/vlm/VLMOperatorOnlyConfigTest.java
+++ b/tika-parsers/tika-parsers-ml/tika-vlm/src/test/java/org/apache/tika/parser/vlm/VLMOperatorOnlyConfigTest.java
@@ -60,7 +60,8 @@ public class VLMOperatorOnlyConfigTest {
@ValueSource(strings = {"{\"model\": \"evil\"}", "{\"baseUrl\": \"http://evil\"}",
"{\"completionsPath\": \"/evil\"}", "{\"apiKey\": \"evil\"}",
"{\"allowRuntimePrompt\": true}", "{\"maxRetries\": 99}",
- "{\"maxImagePixels\": 1}", "{\"useMaxCompletionTokens\": true}"})
+ "{\"maxImagePixels\": 1}", "{\"temperature\": 1.5}",
+ "{\"useMaxCompletionTokens\": true}"})
public void testPerRequestCannotSetOperatorOnlyFields(String json) {
Exception e = assertThrows(Exception.class, () -> perRequest(json));
assertTrue(e.getMessage().contains("at runtime"), e.getMessage());
diff --git a/tika-parsers/tika-parsers-ml/tika-vlm/src/test/java/org/apache/tika/parser/vlm/VLMPdfPageEndToEndTest.java b/tika-parsers/tika-parsers-ml/tika-vlm/src/test/java/org/apache/tika/parser/vlm/VLMPdfPageEndToEndTest.java
new file mode 100644
index 0000000000..7dd528f3d4
--- /dev/null
+++ b/tika-parsers/tika-parsers-ml/tika-vlm/src/test/java/org/apache/tika/parser/vlm/VLMPdfPageEndToEndTest.java
@@ -0,0 +1,109 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.tika.parser.vlm;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+import java.nio.file.Path;
+import java.util.Arrays;
+import java.util.List;
+
+import org.apache.pdfbox.pdmodel.PDDocument;
+import org.apache.pdfbox.pdmodel.PDPage;
+import org.apache.pdfbox.pdmodel.PDPageContentStream;
+import org.apache.pdfbox.pdmodel.common.PDRectangle;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+import org.xml.sax.helpers.DefaultHandler;
+
+import org.apache.tika.http.TikaTestHttpServer;
+import org.apache.tika.io.TikaInputStream;
+import org.apache.tika.metadata.Metadata;
+import org.apache.tika.metadata.TikaCoreProperties;
+import org.apache.tika.parser.ParseContext;
+import org.apache.tika.parser.Parser;
+import org.apache.tika.parser.pages.TextPolicy;
+import org.apache.tika.parser.pdf.PDFParser;
+import org.apache.tika.parser.pdf.PDFParserConfig;
+
+/** A rendered PDF page, not a bare image, reaches the VLM parser: its warnings reach the PDF. */
+public class VLMPdfPageEndToEndTest {
+
+ private TikaTestHttpServer server;
+ private OpenAIVLMParser vlm;
+
+ @BeforeEach
+ void setUp() throws Exception {
+ server = new TikaTestHttpServer();
+ VLMOCRConfig config = new VLMOCRConfig();
+ config.setBaseUrl(server.url());
+ config.setModel("test-model");
+ config.setTimeoutMillis(10_000);
+ server.enqueue(new TikaTestHttpServer.MockResponse(200, "{\"object\":\"list\"}"));
+ vlm = new OpenAIVLMParser(config);
+ vlm.initialize();
+ server.clearRequests();
+ }
+
+ @AfterEach
+ void tearDown() {
+ server.shutdown();
+ }
+
+ private List<String> warningsOfPdfPage(Path dir, String modelAnswer, boolean ink)
+ throws Exception {
+ Path pdf = dir.resolve("page.pdf");
+ try (PDDocument document = new PDDocument()) {
+ PDPage page = new PDPage(PDRectangle.LETTER);
+ document.addPage(page);
+ if (ink) {
+ try (PDPageContentStream content = new PDPageContentStream(document, page)) {
+ content.addRect(72, 400, 300, 200);
+ content.fill();
+ }
+ }
+ document.save(pdf.toFile());
+ }
+ server.enqueue(new TikaTestHttpServer.MockResponse(200,
+ "{\"choices\":[{\"message\":{\"content\":\"" + modelAnswer + "\"}}]}"));
+
+ PDFParserConfig pdfConfig = new PDFParserConfig();
+ pdfConfig.pages().setText(TextPolicy.OCR);
+ ParseContext context = new ParseContext();
+ context.set(PDFParserConfig.class, pdfConfig);
+ context.set(Parser.class, vlm);
+
+ Metadata metadata = new Metadata();
+ try (TikaInputStream tis = TikaInputStream.get(pdf)) {
+ new PDFParser().parse(tis, new DefaultHandler(), metadata, context);
+ }
+ assertEquals(1, server.getRequestCount());
+ return Arrays.asList(metadata.getValues(TikaCoreProperties.OCR_WARNINGS));
+ }
+
+ @Test
+ void testAnEmptyAnswerIsFlaggedOnThePdf(@TempDir Path dir) throws Exception {
+ assertEquals(List.of("empty"), warningsOfPdfPage(dir, " ", true));
+ }
+
+ @Test
+ void testOrdinaryAnswerIsNotFlagged(@TempDir Path dir) throws Exception {
+ assertEquals(List.of(), warningsOfPdfPage(dir, "Hello", true));
+ }
+}
diff --git a/tika-parsers/tika-parsers-ml/tika-vlm/src/test/resources/config-examples/jina-ocr-basic.json b/tika-parsers/tika-parsers-ml/tika-vlm/src/test/resources/config-examples/jina-ocr-basic.json
new file mode 100644
index 0000000000..bffd967321
--- /dev/null
+++ b/tika-parsers/tika-parsers-ml/tika-vlm/src/test/resources/config-examples/jina-ocr-basic.json
@@ -0,0 +1,16 @@
+{
+ "engines": {
+ "vlm": {
+ "openai-vlm-parser": {
+ "baseUrl": "https://api.jina.ai",
+ "model": "jina-ocr-v1",
+ "apiKey": "${env:JINA_API_KEY}"
+ }
+ }
+ },
+ "text-recognizers": [
+ {
+ "engine": "vlm"
+ }
+ ]
+}
diff --git a/tika-parsers/tika-parsers-standard/tika-parsers-standard-modules/tika-parser-pdf-module/src/main/java/org/apache/tika/parser/pdf/AbstractPDF2XHTML.java b/tika-parsers/tika-parsers-standard/tika-parsers-standard-modules/tika-parser-pdf-module/src/main/java/org/apache/tika/parser/pdf/AbstractPDF2XHTML.java
index 48e152e6c8..b4d031dae1 100644
--- a/tika-parsers/tika-parsers-standard/tika-parsers-standard-modules/tika-parser-pdf-module/src/main/java/org/apache/tika/parser/pdf/AbstractPDF2XHTML.java
+++ b/tika-parsers/tika-parsers-standard/tika-parsers-standard-modules/tika-parser-pdf-module/src/main/java/org/apache/tika/parser/pdf/AbstractPDF2XHTML.java
@@ -767,6 +767,8 @@ class AbstractPDF2XHTML extends PDFTextStripper {
engine.parse(tis,
new EmbeddedContentHandler(new BodyContentHandler(counter)),
renderMetadata, context);
+ } finally {
+ carryOcrWarnings(renderMetadata);
}
// Propagate enrichment metadata added by the OCR parser (e.g. tk:chunks
// from image embedding parsers) back to the parent document so it isn't
@@ -790,6 +792,16 @@ class AbstractPDF2XHTML extends PDFTextStripper {
return false;
}
+ /** The recognizer's doubts about a page become the document's, each code once. */
+ private void carryOcrWarnings(Metadata renderMetadata) {
+ for (String warning : renderMetadata.getValues(TikaCoreProperties.OCR_WARNINGS)) {
+ if (!Arrays.asList(metadata.getValues(TikaCoreProperties.OCR_WARNINGS))
+ .contains(warning)) {
+ metadata.add(TikaCoreProperties.OCR_WARNINGS, warning);
+ }
+ }
+ }
+
/** The page's render, made on first use and closed at page end; a failure is not retried. */
private RenderResult currentPageRender(PDPage pdPage) throws IOException, TikaException {
if (pageRender == null) {
diff --git a/tika-parsers/tika-parsers-standard/tika-parsers-standard-modules/tika-parser-pdf-module/src/test/java/org/apache/tika/parser/pdf/PDFParserTest.java b/tika-parsers/tika-parsers-standard/tika-parsers-standard-modules/tika-parser-pdf-module/src/test/java/org/apache/tika/parser/pdf/PDFParserTest.java
index 63d9ccc407..760ad48d70 100644
--- a/tika-parsers/tika-parsers-standard/tika-parsers-standard-modules/tika-parser-pdf-module/src/test/java/org/apache/tika/parser/pdf/PDFParserTest.java
+++ b/tika-parsers/tika-parsers-standard/tika-parsers-standard-modules/tika-parser-pdf-module/src/test/java/org/apache/tika/parser/pdf/PDFParserTest.java
@@ -2512,6 +2512,74 @@ public class PDFParserTest extends TikaTest {
assertContains("chunk-page-2", chunks);
}
+ /** The recognizer's doubts about each rendered page reach the document, each code once. */
+ @Test
+ public void testOcrWarningsFromAllPagesReachDocument() throws Exception {
+ PDFParserConfig config = new PDFParserConfig();
+ config.pages().setText(TextPolicy.OCR);
+
+ ParseContext context = new ParseContext();
+ context.set(PDFParserConfig.class, config);
+ context.set(Parser.class, new MockEngine() {
+ @Override
+ public Set<MediaType> getSupportedTypes(ParseContext context) {
+ return Collections.singleton(ocrMediaType(config));
+ }
+
+ @Override
+ public void parse(TikaInputStream tis, ContentHandler handler, Metadata metadata,
+ ParseContext context) throws IOException, SAXException, TikaException {
+ metadata.add(TikaCoreProperties.OCR_WARNINGS, "repetition");
+ if (context.get(OCRPageCounter.class).getCount() == 2) {
+ metadata.add(TikaCoreProperties.OCR_WARNINGS, "truncated");
+ }
+ XHTMLContentHandler xhtml = new XHTMLContentHandler(handler, metadata);
+ xhtml.startDocument();
+ xhtml.endDocument();
+ }
+ });
+
+ Metadata metadata = new Metadata();
+ try (TikaInputStream tis = getResourceAsStream("/test-documents/testPDF_bookmarks.pdf")) {
+ new PDFParser().parse(tis, new ToXMLContentHandler(), metadata, context);
+ }
+
+ assertEquals(java.util.List.of("repetition", "truncated"),
+ java.util.Arrays.asList(metadata.getValues(TikaCoreProperties.OCR_WARNINGS)));
+ }
+
+ @Test
+ public void testOcrWarningsSurviveAFailedPage() throws Exception {
+ PDFParserConfig config = new PDFParserConfig();
+ config.pages().setText(TextPolicy.OCR);
+
+ ParseContext context = new ParseContext();
+ context.set(PDFParserConfig.class, config);
+ context.set(Parser.class, new MockEngine() {
+ @Override
+ public Set<MediaType> getSupportedTypes(ParseContext context) {
+ return Collections.singleton(ocrMediaType(config));
+ }
+
+ @Override
+ public void parse(TikaInputStream tis, ContentHandler handler, Metadata metadata,
+ ParseContext context) throws TikaException {
+ metadata.add(TikaCoreProperties.OCR_WARNINGS, "truncated");
+ throw new TikaException("the answer could not be read");
+ }
+ });
+
+ Metadata metadata = new Metadata();
+ try (TikaInputStream tis = getResourceAsStream("/test-documents/testPDF_bookmarks.pdf")) {
+ // the page failures are reported once the document is done
+ assertThrows(TikaException.class, () ->
+ new PDFParser().parse(tis, new ToXMLContentHandler(), metadata, context));
+ }
+
+ assertEquals(java.util.List.of("truncated"),
+ java.util.Arrays.asList(metadata.getValues(TikaCoreProperties.OCR_WARNINGS)));
+ }
+
/**
* A named enricher advertising real image types, with no composite registration at all,
* receives every rendered page when OCR runs (TIKA-4872).
diff --git a/tika-serialization/src/main/java/org/apache/tika/config/loader/ContentEnricherLoader.java b/tika-serialization/src/main/java/org/apache/tika/config/loader/ContentEnricherLoader.java
index 5e068f5e47..61d4f12f7e 100644
--- a/tika-serialization/src/main/java/org/apache/tika/config/loader/ContentEnricherLoader.java
+++ b/tika-serialization/src/main/java/org/apache/tika/config/loader/ContentEnricherLoader.java
@@ -33,7 +33,9 @@ import org.apache.tika.parser.Parser;
import org.apache.tika.parser.ParserDecorator;
import org.apache.tika.parser.enricher.CompositeContentEnricher;
import org.apache.tika.parser.enricher.ContentEnrichers;
-import org.apache.tika.parser.enricher.SizeGatedEnricher;
+import org.apache.tika.parser.enricher.GatedEnricher;
+import org.apache.tika.parser.enricher.ImageCheck;
+import org.apache.tika.parser.enricher.RecordedSizeCheck;
import org.apache.tika.parser.enricher.TextRecognizer;
import org.apache.tika.parser.inference.Engine;
import org.apache.tika.parser.inference.EngineRegistry;
@@ -49,7 +51,10 @@ class ContentEnricherLoader implements ComponentLoader<CompositeContentEnricher>
static final String KEY = "text-recognizers";
private static final Logger LOG = LoggerFactory.getLogger(ContentEnricherLoader.class);
private static final Set<String> REFERENCE_KEYS = Set.of("engine", "_mime-include",
- "_mime-exclude", "_min-width", "_min-height");
+ "_mime-exclude", "min-width", "min-height", "_min-width", "_min-height", "checks");
+ /** Directives of this list only: removed from an inline entry's engine settings. */
+ private static final List<String> ENTRY_DIRECTIVES = List.of("min-width", "min-height",
+ "checks");
@Override
public CompositeContentEnricher load(TikaJsonConfig config, LoaderContext context)
@@ -68,13 +73,12 @@ class ContentEnricherLoader implements ComponentLoader<CompositeContentEnricher>
Parser enricher;
if (item.isObject() && item.has("engine")) {
label = "engine \"" + item.get("engine").asText() + "\"";
- int[] gate = sizeGate(item, label);
- enricher = sizeGated(referenced(item, context), gate);
+ enricher = gated(referenced(item, context), item, label, context);
} else {
Map.Entry<String, JsonNode> entry = inline(item, context);
label = "\"" + entry.getKey() + "\"";
- int[] gate = sizeGate(entry.getValue(), label);
- enricher = sizeGated(instantiate(entry, context), gate);
+ enricher = gated(instantiate(withoutDirectives(entry), context), entry.getValue(), label,
+ context);
}
// lifetime snapshot: an empty engine must fail load, not go inert; ask the
// engine itself, since a _mime-include answers for the decorator
@@ -130,7 +134,8 @@ class ContentEnricherLoader implements ComponentLoader<CompositeContentEnricher>
}
/**
- * The entry's {@code _min-width}/{@code _min-height}; null when neither is set. An image of
+ * The entry's {@code min-width}/{@code min-height} (or the older {@code _min-width}/{@code
+ * _min-height}, same meaning); null when neither is set. An image of
* unknown size passes the gate, and one below {@link ContentEnrichers#MIN_PIXELS} never
* reaches dispatch anyway.
*/
@@ -138,26 +143,72 @@ class ContentEnricherLoader implements ComponentLoader<CompositeContentEnricher>
if (!settings.isObject()) {
return null;
}
- Integer minWidth = minimum(settings, "_min-width", label);
- Integer minHeight = minimum(settings, "_min-height", label);
+ Integer minWidth = minimum(settings, "min-width", label);
+ Integer minHeight = minimum(settings, "min-height", label);
if (minWidth == null && minHeight == null) {
return null;
}
return new int[] {minWidth == null ? 0 : minWidth, minHeight == null ? 0 : minHeight};
}
- private static Parser sizeGated(Parser enricher, int[] gate) {
- return gate == null ? enricher : new SizeGatedEnricher(enricher, gate[0], gate[1]);
+ /**
+ * The engine behind its entry's checks: the recorded-size minimum, then the {@code checks},
+ * in order, in one decorator; the engine itself when the entry has none.
+ */
+ private static Parser gated(Parser enricher, JsonNode settings, String label,
+ LoaderContext context) throws TikaConfigException {
+ List<ImageCheck> checks = new ArrayList<>();
+ int[] gate = sizeGate(settings, label);
+ if (gate != null) {
+ checks.add(new RecordedSizeCheck(gate[0], gate[1]));
+ }
+ checks.addAll(namedChecks(settings, label, context));
+ return checks.isEmpty() ? enricher : new GatedEnricher(enricher, checks);
+ }
+
+ /** The entry's {@code checks}: component names, or {@code {"name": {settings}}}. */
+ private static List<ImageCheck> namedChecks(JsonNode settings, String label,
+ LoaderContext context)
+ throws TikaConfigException {
+ List<ImageCheck> checks = new ArrayList<>();
+ JsonNode list = settings.isObject() ? settings.get("checks") : null;
+ if (list == null) {
+ return checks;
+ }
+ if (!list.isArray()) {
+ throw new TikaConfigException("\"" + KEY + "\" entry " + label
+ + ": \"checks\" must be an array");
+ }
+ for (JsonNode item : list) {
+ Map.Entry<String, JsonNode> check;
+ try {
+ check = inline(item, context);
+ } catch (TikaConfigException e) {
+ throw new TikaConfigException("\"" + KEY + "\" entry " + label
+ + ": a \"checks\" member is a name or {\"name\": {...}}; got " + item);
+ }
+ checks.add(ComponentInstantiator.instantiateComponent(check.getKey(),
+ check.getValue(), context.getObjectMapper(), context.getClassLoader(),
+ ImageCheck.class));
+ }
+ return checks;
}
+ /** The value of {@code field} or its older {@code _field} spelling; both is an error. */
private static Integer minimum(JsonNode settings, String field, String label)
throws TikaConfigException {
- JsonNode v = settings.get(field);
+ String alias = "_" + field;
+ if (settings.has(field) && settings.has(alias)) {
+ throw new TikaConfigException("\"" + KEY + "\" entry " + label + " sets both \""
+ + field + "\" and its older spelling \"" + alias + "\"; use one");
+ }
+ String name = settings.has(field) ? field : alias;
+ JsonNode v = settings.get(name);
if (v == null) {
return null;
}
if (!v.isIntegralNumber() || v.asInt() < 0) {
- throw new TikaConfigException("\"" + KEY + "\" entry " + label + ": \"" + field
+ throw new TikaConfigException("\"" + KEY + "\" entry " + label + ": \"" + name
+ "\" must be a non-negative integer");
}
return v.asInt();
@@ -169,7 +220,7 @@ class ContentEnricherLoader implements ComponentLoader<CompositeContentEnricher>
if (item.isTextual()) {
return Map.entry(item.asText(), (JsonNode) context.getObjectMapper().createObjectNode());
}
- if (item.isObject() && !item.isEmpty()) {
+ if (item.isObject() && item.size() == 1) {
Map.Entry<String, JsonNode> first = item.fields().next();
return Map.entry(first.getKey(), first.getValue());
}
@@ -177,6 +228,22 @@ class ContentEnricherLoader implements ComponentLoader<CompositeContentEnricher>
+ "or {\"<recognizer>\": {...}}; got " + item);
}
+ /**
+ * The inline entry without this list's own directives ({@code min-width}, {@code
+ * min-height}, {@code checks}): they are directives here only, so they are removed for this
+ * entry's engine and no other component loses a setting of that name.
+ */
+ private static Map.Entry<String, JsonNode> withoutDirectives(
+ Map.Entry<String, JsonNode> entry) {
+ if (!(entry.getValue() instanceof ObjectNode settings)
+ || ENTRY_DIRECTIVES.stream().noneMatch(settings::has)) {
+ return entry;
+ }
+ ObjectNode copy = settings.deepCopy();
+ ENTRY_DIRECTIVES.forEach(copy::remove);
+ return Map.entry(entry.getKey(), copy);
+ }
+
private static Parser instantiate(Map.Entry<String, JsonNode> entry, LoaderContext context)
throws TikaConfigException {
try {
diff --git a/tika-serialization/src/main/java/org/apache/tika/config/loader/TikaObjectMapperFactory.java b/tika-serialization/src/main/java/org/apache/tika/config/loader/TikaObjectMapperFactory.java
index 97c3a37334..b717a0555d 100644
--- a/tika-serialization/src/main/java/org/apache/tika/config/loader/TikaObjectMapperFactory.java
+++ b/tika-serialization/src/main/java/org/apache/tika/config/loader/TikaObjectMapperFactory.java
@@ -52,6 +52,7 @@ public class TikaObjectMapperFactory {
"detectors",
"encoding-detectors",
"metadata-filters",
+ "image-checks",
"renderers",
"translators",
"digester-factories",
diff --git a/tika-serialization/src/test/java/org/apache/tika/config/loader/ContentEnricherLoaderTest.java b/tika-serialization/src/test/java/org/apache/tika/config/loader/ContentEnricherLoaderTest.java
index b02b914ce9..58876bb97a 100644
--- a/tika-serialization/src/test/java/org/apache/tika/config/loader/ContentEnricherLoaderTest.java
+++ b/tika-serialization/src/test/java/org/apache/tika/config/loader/ContentEnricherLoaderTest.java
@@ -45,7 +45,8 @@ import org.apache.tika.parser.Parser;
import org.apache.tika.parser.ParserDecorator;
import org.apache.tika.parser.enricher.CompositeContentEnricher;
import org.apache.tika.parser.enricher.ContentEnrichers;
-import org.apache.tika.parser.enricher.SizeGatedEnricher;
+import org.apache.tika.parser.enricher.GatedEnricher;
+import org.apache.tika.parser.enricher.RecordedSizeCheck;
import org.apache.tika.parser.inference.EngineRegistry;
import org.apache.tika.utils.ParserUtils;
@@ -123,18 +124,54 @@ public class ContentEnricherLoaderTest {
List<Parser> matched = loader.get(CompositeContentEnricher.class)
.getEnrichers(MediaType.image("png"));
assertEquals(2, matched.size());
- SizeGatedEnricher referenced = (SizeGatedEnricher) matched.get(0);
- assertEquals(100, referenced.getMinWidth());
- assertEquals(0, referenced.getMinHeight());
+ GatedEnricher referenced = (GatedEnricher) matched.get(0);
+ RecordedSizeCheck size = (RecordedSizeCheck) referenced.getChecks().get(0);
+ assertEquals(100, size.getMinWidth());
+ assertEquals(0, size.getMinHeight());
assertSame(loader.get(EngineRegistry.class).get("png"), unwrap(referenced));
- assertEquals(50, ((SizeGatedEnricher) unwrapTo(matched.get(1), SizeGatedEnricher.class))
- .getMinHeight());
+ GatedEnricher inline = (GatedEnricher) unwrapTo(matched.get(1), GatedEnricher.class);
+ assertEquals(50, ((RecordedSizeCheck) inline.getChecks().get(0)).getMinHeight());
assertTrue(ContentEnrichers.isEnricher(matched.get(1)));
// the gate is config, not a load-time side effect: a dump keeps it
assertTrue(loader.toJson().contains("\"_min-width\" : 100"), loader.toJson());
assertTrue(loader.toJson().contains("\"_min-height\" : 50"), loader.toJson());
}
+ /** The unprefixed spellings mean the same as the older underscored ones, in both forms. */
+ @Test
+ public void testSizeGateWithoutUnderscores() throws Exception {
+ TikaLoader loader = load("""
+ {
+ "engines": { "png": { "mock-enricher": {} } },
+ "text-recognizers": [
+ { "engine": "png", "min-width": 100, "min-height": 40 },
+ { "mock-enricher": { "min-height": 50, "_mime-include": ["image/png"] } }
+ ]
+ }
+ """);
+ List<Parser> matched = loader.get(CompositeContentEnricher.class)
+ .getEnrichers(MediaType.image("png"));
+ assertEquals(2, matched.size());
+ RecordedSizeCheck size = (RecordedSizeCheck) ((GatedEnricher) matched.get(0))
+ .getChecks().get(0);
+ assertEquals(100, size.getMinWidth());
+ assertEquals(40, size.getMinHeight());
+ // the inline engine was built without the directive, which it would have rejected
+ GatedEnricher inline = (GatedEnricher) unwrapTo(matched.get(1), GatedEnricher.class);
+ assertEquals(50, ((RecordedSizeCheck) inline.getChecks().get(0)).getMinHeight());
+ }
+
+ @Test
+ public void testBothSpellingsOfOneKeyFailLoad() {
+ TikaConfigException e = assertThrows(TikaConfigException.class, () -> load("""
+ {
+ "engines": { "png": { "mock-enricher": {} } },
+ "text-recognizers": [ { "engine": "png", "min-width": 10, "_min-width": 20 } ]
+ }
+ """).get(CompositeContentEnricher.class));
+ assertTrue(e.getMessage().contains("older spelling"), e.getMessage());
+ }
+
private static Parser unwrapTo(Parser parser, Class<? extends Parser> type) {
while (parser instanceof ParserDecorator decorator && !type.isInstance(parser)) {
parser = decorator.getWrappedParser();
diff --git a/tika-server/tika-server-standard/pom.xml b/tika-server/tika-server-standard/pom.xml
index b7e9d97cf6..e7b8bf8596 100644
--- a/tika-server/tika-server-standard/pom.xml
+++ b/tika-server/tika-server-standard/pom.xml
@@ -62,6 +62,12 @@
<artifactId>tika-vlm</artifactId>
<version>${project.version}</version>
</dependency>
+ <!-- keep blank and tiny images away from any text recognizer (JDK only) -->
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>tika-image-processing</artifactId>
+ <version>${project.version}</version>
+ </dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>tika-handler-boilerpipe</artifactId>