#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere
TypeScript dockerhacktoberfestjavapdfpdf-converterpdf-editorpdf-manipulationpdf-mergerpdf-ocrpdf-toolspdf-web-appspdfmergerself-hosted
Add Auto Form Detection Server only (#7722)
Anthony Stirling03082a5afee0
diff --git a/.dockerignore b/.dockerignoreindex 12326e5bc5..b5f5f30a70 100644--- a/.dockerignore+++ b/.dockerignore@@ -87,6 +87,13 @@ stirling/customFiles/configs/+# Local dev runtime dirs created by bootRun under the module dir (hold the locked H2 DB,+# downloaded models, logs); never build input. Root-level patterns above don't match these.+**/configs/+app/core/customFiles/+app/core/logs/+app/core/pipeline/+# Claude Code workspace.claude/diff --git a/app/common/src/main/java/stirling/software/SPDF/config/EndpointConfiguration.java b/app/common/src/main/java/stirling/software/SPDF/config/EndpointConfiguration.javaindex 853f8a7f8d..6653b5ed08 100644--- a/app/common/src/main/java/stirling/software/SPDF/config/EndpointConfiguration.java+++ b/app/common/src/main/java/stirling/software/SPDF/config/EndpointConfiguration.java@@ -549,6 +549,7 @@ public class EndpointConfiguration {addEndpointToGroup("Java", "pdf-to-epub");addEndpointToGroup("Java", "eml-to-pdf");addEndpointToGroup("Java", "handleData");+ addEndpointToGroup("Java", "form-detection");addEndpointToGroup("rar", "pdf-to-cbr");// Javascript@@ -650,6 +651,10 @@ public class EndpointConfiguration {disableEndpoint("accessibility-report");}+ // Only FormDetectionModelManager (proprietary) can enable this; default it off so a core+ // build does not advertise a tool whose controller is not on the classpath.+ disableEndpoint("form-detection", DisableReason.DEPENDENCY);+if (!applicationProperties.getSystem().isEnableUrlToPDF()) {disableEndpoint("url-to-pdf");}diff --git a/app/common/src/main/java/stirling/software/common/configuration/RuntimePathConfig.java b/app/common/src/main/java/stirling/software/common/configuration/RuntimePathConfig.javaindex 5be836f82a..7cabc88ca7 100644--- a/app/common/src/main/java/stirling/software/common/configuration/RuntimePathConfig.java+++ b/app/common/src/main/java/stirling/software/common/configuration/RuntimePathConfig.java@@ -40,6 +40,9 @@ public class RuntimePathConfig {// Tesseract data pathprivate final String tessDataPath;+ // Auto Form Detection model directory+ private final String formDetectionModelPath;+private final List<ApplicationProperties.ProcessExecutor.UnoServerEndpoint> unoServerEndpoints;// Pipeline paths@@ -130,6 +133,22 @@ public class RuntimePathConfig {log.info("Using Tesseract data path: {}", this.tessDataPath);+ // Auto Form Detection model directory (kept under <configs> so it survives+ // restarts/updates)+ String configuredModelDir =+ properties.getFormDetection() != null+ ? properties.getFormDetection().getModelDir()+ : null;+ this.formDetectionModelPath =+ StringUtils.isNotBlank(configuredModelDir)+ ? configuredModelDir+ : Path.of(+ InstallationPathConfig.getConfigPath(),+ "models",+ "form-detection")+ .toString();+ log.info("Using Auto Form Detection model path: {}", this.formDetectionModelPath);+ApplicationProperties.ProcessExecutor processExecutor = properties.getProcessExecutor();int libreOfficeLimit = 1;if (processExecutor != null && processExecutor.getSessionLimit() != null) {diff --git a/app/common/src/main/java/stirling/software/common/model/ApplicationProperties.java b/app/common/src/main/java/stirling/software/common/model/ApplicationProperties.javaindex cfdf3c8c7b..689887ab71 100644--- a/app/common/src/main/java/stirling/software/common/model/ApplicationProperties.java+++ b/app/common/src/main/java/stirling/software/common/model/ApplicationProperties.java@@ -77,6 +77,7 @@ public class ApplicationProperties {private ProcessExecutor processExecutor = new ProcessExecutor();private PdfEditor pdfEditor = new PdfEditor();private AiEngine aiEngine = new AiEngine();+ private FormDetection formDetection = new FormDetection();private Mcp mcp = new Mcp();private InternalApi internalApi = new InternalApi();private Cluster cluster = new Cluster();@@ -450,6 +451,28 @@ public class ApplicationProperties {}}+ /**+ * Auto Form Detection settings. The model itself is downloaded on demand by an admin (see+ * {@code /api/v1/form/form-detection-model/*}); only lightweight pointers are persisted here.+ */+ @Data+ public static class FormDetection {+ /** Master on/off switch for the whole feature (admin-controlled). */+ private boolean enabled = true;++ /** Id of the installed model; blank means none installed. */+ private String activeModelId = "";++ /** Optional override dir; blank uses {@code <configs>/models/form-detection}. */+ private String modelDir = "";++ /**+ * Read-only dir of image-baked models, activated on startup when none is active and read in+ * place rather than copied. Blank disables seeding.+ */+ private String preinstalledModelDir = "";+ }+/*** Model Context Protocol (MCP) server configuration. All keys live under the top-level {@code* mcp.*} prefix. {@link #enabled} defaults to {@code false}: when off, no MCP beans are wired,diff --git a/app/common/src/main/java/stirling/software/common/util/FormUtils.java b/app/common/src/main/java/stirling/software/common/util/FormUtils.javaindex aee0d680c2..5fece36921 100644--- a/app/common/src/main/java/stirling/software/common/util/FormUtils.java+++ b/app/common/src/main/java/stirling/software/common/util/FormUtils.java@@ -936,6 +936,15 @@ public class FormUtils {}private void ensureAppearances(PDAcroForm acroForm) {+ ensureAppearances(acroForm, null, false);+ }++ /**+ * With {@code onlyFields} set, regenerates only those. {@code preserveNeedAppearances} keeps+ * the viewer-side flag on for untouched fields that still rely on it.+ */+ private void ensureAppearances(+ PDAcroForm acroForm, List<PDField> onlyFields, boolean preserveNeedAppearances) {if (acroForm == null) return;acroForm.setNeedAppearances(true);@@ -964,12 +973,23 @@ public class FormUtils {"Unable to ensure default font resources before refresh: {}",fontPrep.getMessage());}- acroForm.refreshAppearances();+ if (onlyFields != null) {+ if (!onlyFields.isEmpty()) {+ acroForm.refreshAppearances(onlyFields);+ }+ } else {+ acroForm.refreshAppearances();+ }} catch (IOException e) {log.warn("Failed to refresh form appearances: {}", e.getMessage(), e);return; // Don't set NeedAppearances to false if refresh failed}+ // Pre-existing fields that were not refreshed may still rely on viewer-side generation.+ if (onlyFields != null && preserveNeedAppearances) {+ return;+ }+// After successful appearance generation, set NeedAppearances to false// to signal that appearance streams are now embedded authoritativelytry {@@ -990,6 +1010,104 @@ public class FormUtils {}}+ /**+ * Create AcroForm fields from definitions, uniquifying names against existing fields. Creates+ * the AcroForm with a Helvetica default resource when the document has none.+ */+ public List<CreatedField> addFields(+ PDDocument document, List<NewFormFieldDefinition> definitions) throws IOException {+ if (document == null || definitions == null || definitions.isEmpty()) {+ return List.of();+ }+ List<CreatedField> created = new ArrayList<>();+ PDDocumentCatalog documentCatalog = document.getDocumentCatalog();+ PDAcroForm acroForm = documentCatalog.getAcroForm();+ boolean priorNeedAppearances =+ acroForm != null && Boolean.TRUE.equals(acroForm.getNeedAppearances());+ if (acroForm == null) {+ acroForm = new PDAcroForm(document);+ PDResources dr = new PDResources();+ dr.put(COSName.getPDFName("Helv"), new PDType1Font(Standard14Fonts.FontName.HELVETICA));+ acroForm.setDefaultResources(dr);+ acroForm.setNeedAppearances(true);+ documentCatalog.setAcroForm(acroForm);+ }++ Set<String> existingNames = new java.util.HashSet<>();+ for (PDField field : acroForm.getFieldTree()) {+ if (field.getPartialName() != null) {+ existingNames.add(field.getPartialName());+ }+ }++ int pageCount = document.getNumberOfPages();+ List<PDField> createdFields = new ArrayList<>();+ List<Map.Entry<String, NewFormFieldDefinition>> createdButtons = new ArrayList<>();+ for (NewFormFieldDefinition definition : definitions) {+ Integer pageIndex = definition.pageIndex();+ if (pageIndex == null+ || pageIndex < 0+ || pageIndex >= pageCount+ || definition.x() == null+ || definition.y() == null+ || definition.width() == null+ || definition.height() == null) {+ continue;+ }+ // A degenerate rect would otherwise get a synthetic default rectangle downstream.+ if (definition.width() <= 0 || definition.height() <= 0) {+ continue;+ }+ PDPage page = document.getPage(pageIndex);+ PDRectangle rectangle =+ new PDRectangle(+ definition.x(),+ definition.y(),+ definition.width(),+ definition.height());+ FormFieldTypeSupport handler = FormFieldTypeSupport.forTypeName(definition.type());+ // Signature has no definition-creation path here, so it lands as text. PDFBox can build+ // a real PDSignatureField, so this is worth revisiting for both callers.+ if (handler == null+ || handler == FormFieldTypeSupport.SIGNATURE+ || handler.doesNotsupportsDefinitionCreation()) {+ handler = FormFieldTypeSupport.TEXT;+ }+ String baseName =+ (definition.name() != null && !definition.name().isBlank())+ ? definition.name()+ : handler.typeName() + "_" + (pageIndex + 1);+ String uniqueName = generateUniqueFieldName(baseName, existingNames);+ existingNames.add(uniqueName);+ try {+ createNewField(+ handler,+ acroForm,+ page,+ rectangle,+ uniqueName,+ definition,+ definition.options());+ PDField field = acroForm.getField(uniqueName);+ if (field != null) {+ createdFields.add(field);+ createdButtons.add(Map.entry(uniqueName, definition));+ created.add(new CreatedField(handler.typeName(), pageIndex));+ }+ } catch (Exception e) {+ log.warn("Failed to create detected field '{}': {}", uniqueName, e.getMessage());+ }+ }++ applyButtonAppearances(document, acroForm, createdButtons);+ // Refresh only what we added; regenerating pre-existing fields could alter their look.+ ensureAppearances(acroForm, createdFields, priorNeedAppearances);+ return List.copyOf(created);+ }++ /** A field that was actually written, with the type it ended up as after any coercion. */+ public record CreatedField(String type, int pageIndex) {}+public String filterSingleChoiceSelection(String selection, List<String> allowedOptions, String fieldName) {if (selection == null || selection.trim().isEmpty()) return null;@@ -3603,8 +3721,8 @@ public class FormUtils {}}- // Only link a SEPARATE widget into the field; the merged widget IS the- // field dictionary and is already its own widget.+ // Only link a SEPARATE widget; a merged widget is already the field dictionary.+ // setWidgets persists the /Kids link - getWidgets() returns a detached copy.if (!reuseFieldDict) {List<PDAnnotationWidget> widgets = new ArrayList<>(field.getWidgets());if (!widgets.contains(widget)) {diff --git a/app/common/src/main/java/stirling/software/common/util/GeneralUtils.java b/app/common/src/main/java/stirling/software/common/util/GeneralUtils.javaindex 1d7320ca84..01dd700296 100644--- a/app/common/src/main/java/stirling/software/common/util/GeneralUtils.java+++ b/app/common/src/main/java/stirling/software/common/util/GeneralUtils.java@@ -870,12 +870,23 @@ public class GeneralUtils {* Internal Implementation Details **------------------------------------------------------------------------*/+ /**+ * Guards the read-modify-write cycle below. Every writer reloads the whole file, edits one key+ * and writes it all back, so two unsynchronised writers would silently drop one another's keys.+ */+ private final Object SETTINGS_WRITE_LOCK = new Object();++ /** Dotted-notation separator for settings keys; a literal, so compile it once. */+ private final Pattern SETTINGS_KEY_SEPARATOR = Pattern.compile("\\.");+public void saveKeyToSettings(String key, Object newValue) throws IOException {- String[] keyArray = key.split("\\.");- Path settingsPath = Path.of(InstallationPathConfig.getSettingsPath());- YamlHelper settingsYaml = new YamlHelper(settingsPath);- settingsYaml.updateValue(Arrays.asList(keyArray), newValue);- settingsYaml.saveOverride(settingsPath);+ synchronized (SETTINGS_WRITE_LOCK) {+ String[] keyArray = SETTINGS_KEY_SEPARATOR.split(key);+ Path settingsPath = Path.of(InstallationPathConfig.getSettingsPath());+ YamlHelper settingsYaml = new YamlHelper(settingsPath);+ settingsYaml.updateValue(Arrays.asList(keyArray), newValue);+ settingsYaml.saveOverride(settingsPath);+ }}/**@@ -893,19 +904,21 @@ public class GeneralUtils {return;}- Path settingsPath = Path.of(InstallationPathConfig.getSettingsPath());- YamlHelper settingsYaml = new YamlHelper(settingsPath);+ synchronized (SETTINGS_WRITE_LOCK) {+ Path settingsPath = Path.of(InstallationPathConfig.getSettingsPath());+ YamlHelper settingsYaml = new YamlHelper(settingsPath);- // Apply all updates to the same YamlHelper instance- for (Map.Entry<String, Object> entry : settingsMap.entrySet()) {- String key = entry.getKey();- Object value = entry.getValue();- String[] keyArray = key.split("\\.");- settingsYaml.updateValue(Arrays.asList(keyArray), value);- }+ // Apply all updates to the same YamlHelper instance+ for (Map.Entry<String, Object> entry : settingsMap.entrySet()) {+ String key = entry.getKey();+ Object value = entry.getValue();+ String[] keyArray = SETTINGS_KEY_SEPARATOR.split(key);+ settingsYaml.updateValue(Arrays.asList(keyArray), value);+ }- // Save only once after all updates are applied- settingsYaml.saveOverride(settingsPath);+ // Save only once after all updates are applied+ settingsYaml.saveOverride(settingsPath);+ }}/*diff --git a/app/common/src/main/java/stirling/software/common/util/YamlHelper.java b/app/common/src/main/java/stirling/software/common/util/YamlHelper.javaindex 2715f50dfb..8842fe480a 100644--- a/app/common/src/main/java/stirling/software/common/util/YamlHelper.java+++ b/app/common/src/main/java/stirling/software/common/util/YamlHelper.java@@ -2,8 +2,11 @@ package stirling.software.common.util;import java.io.IOException;import java.io.StringWriter;+import java.nio.file.AtomicMoveNotSupportedException;+import java.nio.file.FileSystemException;import java.nio.file.Files;import java.nio.file.Path;+import java.nio.file.StandardCopyOption;import java.util.ArrayDeque;import java.util.ArrayList;import java.util.Arrays;@@ -44,6 +47,8 @@ public class YamlHelper {.setDefaultFlowStyle(FlowStyle.BLOCK).build();+ private static final int MAX_SYMLINK_HOPS = 16;+private final String yamlContent; // Stores the entire YAML content as a stringprivate LoadSettings loadSettings =@@ -349,13 +354,96 @@ public class YamlHelper {public MappingNode save(Path saveFilePath) throws IOException {if (!saveFilePath.equals(originalFilePath)) {- Files.writeString(saveFilePath, convertNodeToYaml(getUpdatedRootNode()));+ writeAtomically(saveFilePath, convertNodeToYaml(getUpdatedRootNode()));}return (MappingNode) getUpdatedRootNode();}public void saveOverride(Path saveFilePath) throws IOException {- Files.writeString(saveFilePath, convertNodeToYaml(getUpdatedRootNode()));+ writeAtomically(saveFilePath, convertNodeToYaml(getUpdatedRootNode()));+ }++ /**+ * Write via a sibling temp file and rename. A direct write truncates first, so a crash or a+ * full disk part-way through would leave settings.yml half-written and the app unable to boot.+ *+ * <p>The published file keeps the identity and the mode a direct write would have given it: a+ * symlinked target is written through to its destination, even when that destination does not+ * exist yet, and an existing target's POSIX permissions are carried onto the replacement. A+ * parent directory that will not take the staging file falls back to writing in place, so a+ * read-only config mount still fails only the way it did before.+ *+ * <p>The staging file holds the whole settings content, secrets included, so it is created+ * owner-only and only widened to the target's mode once the content is on disk.+ */+ private static void writeAtomically(Path target, String content) throws IOException {+ Path resolved = resolveLink(target);+ Path dir = resolved.getParent() != null ? resolved.getParent() : Path.of(".");+ Path tmp;+ try {+ tmp = createStagingFile(dir);+ } catch (IOException e) {+ log.debug("Cannot stage a temp file in {}, writing in place", dir, e);+ Files.writeString(resolved, content);+ return;+ }+ try {+ Files.writeString(tmp, content);+ copyPermissions(resolved, tmp);+ try {+ Files.move(+ tmp,+ resolved,+ StandardCopyOption.REPLACE_EXISTING,+ StandardCopyOption.ATOMIC_MOVE);+ } catch (AtomicMoveNotSupportedException e) {+ Files.move(tmp, resolved, StandardCopyOption.REPLACE_EXISTING);+ } catch (FileSystemException e) {+ // Bind-mounted files (docker) reject rename with EBUSY; write in place+ Files.writeString(resolved, content);+ }+ } finally {+ Files.deleteIfExists(tmp);+ }+ }++ /**+ * Creates the empty staging file the settings content is written into. Readable and writable by+ * its owner alone, whatever the umask: the content lands before the target's mode is applied,+ * so anything wider would expose every secret in settings.yml for the length of the write.+ */+ static Path createStagingFile(Path dir) throws IOException {+ return Files.createTempFile(dir, ".yaml-", ".tmp");+ }++ /**+ * The file a write to {@code target} ends up at, following a chain of symlinks by name rather+ * than by resolving on disk so that a link whose destination does not exist yet still resolves.+ * A link loop exhausts the hop budget and returns the last link, which fails the write the same+ * way a direct write would.+ */+ static Path resolveLink(Path target) throws IOException {+ Path current = target;+ for (int hop = 0; hop < MAX_SYMLINK_HOPS && Files.isSymbolicLink(current); hop++) {+ Path destination = Files.readSymbolicLink(current);+ Path parent = current.getParent();+ current =+ (destination.isAbsolute() || parent == null)+ ? destination+ : parent.resolve(destination);+ current = current.normalize();+ }+ return current;+ }++ private static void copyPermissions(Path from, Path to) {+ try {+ if (Files.exists(from)) {+ Files.setPosixFilePermissions(to, Files.getPosixFilePermissions(from));+ }+ } catch (UnsupportedOperationException | IOException e) {+ log.debug("Could not carry permissions from {} onto the replacement", from, e);+ }}/**diff --git a/app/common/src/test/java/stirling/software/SPDF/config/EndpointConfigurationGapTest.java b/app/common/src/test/java/stirling/software/SPDF/config/EndpointConfigurationGapTest.javaindex afc6fa7020..7064c7695d 100644--- a/app/common/src/test/java/stirling/software/SPDF/config/EndpointConfigurationGapTest.java+++ b/app/common/src/test/java/stirling/software/SPDF/config/EndpointConfigurationGapTest.java@@ -463,6 +463,17 @@ class EndpointConfigurationGapTest {assertFalse(config.isEndpointEnabled("remove-pages"));}+ @Test+ @DisplayName(+ "form-detection defaults to disabled with DEPENDENCY when the proprietary module is absent")+ void formDetectionDisabledWithoutProprietaryModule() {+ EndpointConfiguration config = buildDefault();+ assertFalse(config.isEndpointEnabled("form-detection"));+ assertEquals(+ DisableReason.DEPENDENCY,+ config.getEndpointAvailability("form-detection").getReason());+ }+@Test@DisplayName("non-pro build disables the enterprise group")void nonProDisablesEnterprise() {diff --git a/app/common/src/test/java/stirling/software/common/util/FormUtilsAddFieldsTest.java b/app/common/src/test/java/stirling/software/common/util/FormUtilsAddFieldsTest.javanew file mode 100644index 0000000000..dc4c0f60e6--- /dev/null+++ b/app/common/src/test/java/stirling/software/common/util/FormUtilsAddFieldsTest.java@@ -0,0 +1,183 @@+package stirling.software.common.util;++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.io.IOException;+import java.util.ArrayList;+import java.util.List;++import org.apache.pdfbox.cos.COSName;+import org.apache.pdfbox.pdmodel.PDDocument;+import org.apache.pdfbox.pdmodel.PDPage;+import org.apache.pdfbox.pdmodel.common.PDRectangle;+import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationWidget;+import org.apache.pdfbox.pdmodel.interactive.annotation.PDAppearanceDictionary;+import org.apache.pdfbox.pdmodel.interactive.annotation.PDAppearanceEntry;+import org.apache.pdfbox.pdmodel.interactive.form.PDAcroForm;+import org.apache.pdfbox.pdmodel.interactive.form.PDCheckBox;+import org.apache.pdfbox.pdmodel.interactive.form.PDField;+import org.apache.pdfbox.pdmodel.interactive.form.PDTextField;+import org.junit.jupiter.api.Test;++import stirling.software.common.util.FormUtils.NewFormFieldDefinition;++class FormUtilsAddFieldsTest {++ private NewFormFieldDefinition def(String type, int page, float x, float y, float w, float h) {+ // name, label, type, pageIndex, x, y, width, height, required, multiSelect,+ // options, defaultValue, tooltip, fontSize, readOnly, multiline, maxLength, buttonAction+ return new NewFormFieldDefinition(+ null, null, type, page, x, y, w, h, false, null, null, null, null, null, null, null,+ null, null);+ }++ @Test+ void createsTextAndCheckboxFieldsOnPagelessDocument() throws IOException {+ try (PDDocument doc = new PDDocument()) {+ doc.addPage(new PDPage(new PDRectangle(612, 792)));++ FormUtils.addFields(+ doc,+ List.of(+ def("text", 0, 100f, 700f, 200f, 20f),+ def("checkbox", 0, 100f, 650f, 15f, 15f)));++ PDAcroForm form = doc.getDocumentCatalog().getAcroForm();+ assertNotNull(form, "AcroForm should be created");++ List<PDField> fields = new ArrayList<>();+ form.getFieldTree().forEach(fields::add);+ assertEquals(2, fields.size());++ boolean hasText = fields.stream().anyMatch(f -> f instanceof PDTextField);+ boolean hasCheckbox = fields.stream().anyMatch(f -> f instanceof PDCheckBox);+ assertTrue(hasText, "expected a text field");+ assertTrue(hasCheckbox, "expected a checkbox field");+ }+ }++ @Test+ void skipsOutOfRangePageAndKeepsNamesUnique() throws IOException {+ try (PDDocument doc = new PDDocument()) {+ doc.addPage(new PDPage(new PDRectangle(612, 792)));++ FormUtils.addFields(+ doc,+ List.of(+ def("text", 0, 10f, 10f, 50f, 12f),+ def("text", 0, 10f, 40f, 50f, 12f),+ def("text", 5, 10f, 70f, 50f, 12f))); // page 5 out of range -> skipped++ PDAcroForm form = doc.getDocumentCatalog().getAcroForm();+ List<PDField> fields = new ArrayList<>();+ form.getFieldTree().forEach(fields::add);+ assertEquals(2, fields.size());++ long distinctNames = fields.stream().map(PDField::getPartialName).distinct().count();+ assertEquals(2, distinctNames, "field names must be unique");+ }+ }++ @Test+ void noOpOnEmptyDefinitions() throws IOException {+ try (PDDocument doc = new PDDocument()) {+ doc.addPage(new PDPage(new PDRectangle(612, 792)));+ FormUtils.addFields(doc, List.of());+ // no AcroForm forced into existence when there is nothing to add+ assertEquals(null, doc.getDocumentCatalog().getAcroForm());+ }+ }++ @Test+ void skipsZeroAreaRectsInsteadOfInventingDefaults() throws IOException {+ try (PDDocument doc = new PDDocument()) {+ doc.addPage(new PDPage(new PDRectangle(612, 792)));++ FormUtils.addFields(+ doc,+ List.of(+ def("text", 0, 100f, 700f, 200f, 20f),+ def("text", 0, 100f, 650f, 0f, 20f), // zero width -> skipped+ def("text", 0, 100f, 600f, 50f, 0f))); // zero height -> skipped++ PDAcroForm form = doc.getDocumentCatalog().getAcroForm();+ List<PDField> fields = new ArrayList<>();+ form.getFieldTree().forEach(fields::add);+ assertEquals(1, fields.size(), "degenerate rects must not become fields");+ }+ }++ @Test+ void signatureDetectionsBecomeFillableTextFields() throws IOException {+ // Parity contract with the browser engine: pdf-lib cannot create signature widgets, so+ // both paths deliberately emit a text field for detected signature areas.+ try (PDDocument doc = new PDDocument()) {+ doc.addPage(new PDPage(new PDRectangle(612, 792)));++ FormUtils.addFields(doc, List.of(def("signature", 0, 100f, 200f, 220f, 48f)));++ PDAcroForm form = doc.getDocumentCatalog().getAcroForm();+ List<PDField> fields = new ArrayList<>();+ form.getFieldTree().forEach(fields::add);+ assertEquals(1, fields.size());+ assertTrue(+ fields.get(0) instanceof PDTextField,+ "signature areas are written as fillable text fields");+ }+ }++ @Test+ void checkboxFieldsGetVisibleAppearanceStreams() throws IOException {+ // refreshAppearances() never builds /AP for the button family, so addFields must draw+ // them itself; without that a detected checkbox is silently invisible in viewers.+ try (PDDocument doc = new PDDocument()) {+ doc.addPage(new PDPage(new PDRectangle(612, 792)));++ FormUtils.addFields(doc, List.of(def("checkbox", 0, 100f, 650f, 15f, 15f)));++ PDAcroForm form = doc.getDocumentCatalog().getAcroForm();+ PDCheckBox checkbox = (PDCheckBox) form.getFieldTree().iterator().next();+ PDAnnotationWidget widget = checkbox.getWidgets().get(0);++ PDAppearanceDictionary appearance = widget.getAppearance();+ assertNotNull(appearance, "checkbox widget must carry an appearance dictionary");+ PDAppearanceEntry normal = appearance.getNormalAppearance();+ assertNotNull(normal, "checkbox needs a normal appearance");+ assertTrue(normal.isSubDictionary(), "checkbox /AP /N holds per-state streams");+ boolean hasOnState =+ normal.getSubDictionary().keySet().stream()+ .anyMatch(name -> !COSName.Off.equals(name));+ assertTrue(hasOnState, "an on-state appearance stream must exist");++ String onValue = checkbox.getOnValue();+ assertTrue(+ onValue != null && !onValue.isBlank() && !"Off".equals(onValue),+ "PDFBox reads the on-state from /AP /N; got '" + onValue + "'");+ }+ }++ @Test+ void addingFieldsKeepsExistingFieldAppearanceStreamsUntouched() throws IOException {+ try (PDDocument doc = new PDDocument()) {+ doc.addPage(new PDPage(new PDRectangle(612, 792)));+ FormUtils.addFields(doc, List.of(def("text", 0, 100f, 700f, 200f, 20f)));++ PDAcroForm form = doc.getDocumentCatalog().getAcroForm();+ PDTextField existing = (PDTextField) form.getFieldTree().iterator().next();+ existing.setValue("existing value");+ var normalBefore =+ existing.getWidgets().get(0).getNormalAppearanceStream().getCOSObject();+ assertNotNull(normalBefore, "setting a value generates an appearance");++ FormUtils.addFields(doc, List.of(def("text", 0, 100f, 650f, 200f, 20f)));++ var normalAfter =+ existing.getWidgets().get(0).getNormalAppearanceStream().getCOSObject();+ assertTrue(+ normalBefore == normalAfter,+ "pre-existing field appearances must not be regenerated");+ }+ }+}diff --git a/app/common/src/test/java/stirling/software/common/util/YamlHelperMoreTest.java b/app/common/src/test/java/stirling/software/common/util/YamlHelperMoreTest.javaindex ab05775f6b..8f98ad1f73 100644--- a/app/common/src/test/java/stirling/software/common/util/YamlHelperMoreTest.java+++ b/app/common/src/test/java/stirling/software/common/util/YamlHelperMoreTest.java@@ -3,12 +3,17 @@ package stirling.software.common.util;import static org.assertj.core.api.Assertions.assertThat;import java.io.IOException;+import java.nio.file.FileSystems;import java.nio.file.Files;import java.nio.file.Path;+import java.nio.file.attribute.PosixFilePermission;+import java.nio.file.attribute.PosixFilePermissions;import java.util.LinkedHashMap;import java.util.List;import java.util.Map;+import java.util.Set;+import org.junit.jupiter.api.Assumptions;import org.junit.jupiter.api.DisplayName;import org.junit.jupiter.api.Nested;import org.junit.jupiter.api.Test;@@ -200,4 +205,111 @@ class YamlHelperMoreTest {assertThat(YamlHelper.isInteger((short) 9)).isTrue();}}++ @Nested+ @DisplayName("publishing a saved file")+ class Publishing {++ private void posixOnly() {+ Assumptions.assumeTrue(+ FileSystems.getDefault().supportedFileAttributeViews().contains("posix"));+ }++ private void bumpPort(Path file) throws IOException {+ YamlHelper h = new YamlHelper(file);+ h.updateValue(List.of("server", "port"), "9090");+ h.saveOverride(file);+ }++ @Test+ @DisplayName("keeps the target's existing permissions")+ void preservesMode(@TempDir Path dir) throws IOException {+ posixOnly();+ Path file = dir.resolve("settings.yml");+ Files.writeString(file, "server:\n port: 80\n");+ Set<PosixFilePermission> mode = PosixFilePermissions.fromString("rw-rw-r--");+ Files.setPosixFilePermissions(file, mode);++ bumpPort(file);++ assertThat(Files.readString(file)).contains("9090");+ assertThat(Files.getPosixFilePermissions(file)).isEqualTo(mode);+ }++ @Test+ @DisplayName("stages the content in an owner-only file")+ void stagingFileIsOwnerOnly(@TempDir Path dir) throws IOException {+ posixOnly();++ Path staged = YamlHelper.createStagingFile(dir);++ assertThat(Files.getPosixFilePermissions(staged))+ .containsExactlyInAnyOrder(+ PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE);+ }++ @Test+ @DisplayName("keeps an owner-only target owner-only")+ void preservesTightMode(@TempDir Path dir) throws IOException {+ posixOnly();+ Path file = dir.resolve("settings.yml");+ Files.writeString(file, "server:\n port: 80\n");+ Set<PosixFilePermission> mode = PosixFilePermissions.fromString("rw-------");+ Files.setPosixFilePermissions(file, mode);++ bumpPort(file);++ assertThat(Files.readString(file)).contains("9090");+ assertThat(Files.getPosixFilePermissions(file)).isEqualTo(mode);+ }++ @Test+ @DisplayName("writes through a symlink whose target does not exist yet")+ void followsDanglingSymlink(@TempDir Path dir) throws IOException {+ posixOnly();+ Path seed = dir.resolve("seed.yml");+ Files.writeString(seed, "server:\n port: 80\n");+ Path real = dir.resolve("real.yml");+ Path link = dir.resolve("settings.yml");+ Files.createSymbolicLink(link, real.getFileName());++ YamlHelper h = new YamlHelper(seed);+ h.updateValue(List.of("server", "port"), "9090");+ h.saveOverride(link);++ assertThat(Files.isSymbolicLink(link)).isTrue();+ assertThat(Files.readString(real)).contains("9090");+ }++ @Test+ @DisplayName("writes through a symlink instead of replacing it")+ void followsSymlink(@TempDir Path dir) throws IOException {+ posixOnly();+ Path real = dir.resolve("real.yml");+ Files.writeString(real, "server:\n port: 80\n");+ Path link = dir.resolve("settings.yml");+ Files.createSymbolicLink(link, real);++ bumpPort(link);++ assertThat(Files.isSymbolicLink(link)).isTrue();+ assertThat(Files.readString(real)).contains("9090");+ }++ @Test+ @DisplayName("falls back to an in-place write when the directory will not take a temp file")+ void stagingFailureStillPublishes(@TempDir Path dir) throws IOException {+ posixOnly();+ Path locked = Files.createDirectory(dir.resolve("configs"));+ Path file = locked.resolve("settings.yml");+ Files.writeString(file, "server:\n port: 80\n");+ Files.setPosixFilePermissions(locked, PosixFilePermissions.fromString("r-x------"));+ try {+ bumpPort(file);+ assertThat(Files.readString(file)).contains("9090");+ } finally {+ Files.setPosixFilePermissions(locked, PosixFilePermissions.fromString("rwx------"));+ }+ }+ }}diff --git a/app/core/src/main/java/stirling/software/SPDF/config/WebMvcConfig.java b/app/core/src/main/java/stirling/software/SPDF/config/WebMvcConfig.javaindex 01d3f49e2c..50bd62b54e 100644--- a/app/core/src/main/java/stirling/software/SPDF/config/WebMvcConfig.java+++ b/app/core/src/main/java/stirling/software/SPDF/config/WebMvcConfig.java@@ -185,7 +185,8 @@ public class WebMvcConfig implements WebMvcConfigurer {"Content-Disposition","Content-Type","X-Stirling-Skipped-Field-Edits",- "X-Stirling-Skipped-Field-Edits-Total")+ "X-Stirling-Skipped-Field-Edits-Total",+ "X-Stirling-Detected-Fields").allowCredentials(true).maxAge(3600);} else if (hasConfiguredOrigins) {@@ -233,7 +234,8 @@ public class WebMvcConfig implements WebMvcConfigurer {"Content-Disposition","Content-Type","X-Stirling-Skipped-Field-Edits",- "X-Stirling-Skipped-Field-Edits-Total")+ "X-Stirling-Skipped-Field-Edits-Total",+ "X-Stirling-Detected-Fields").allowCredentials(true).maxAge(3600);} else {@@ -262,7 +264,8 @@ public class WebMvcConfig implements WebMvcConfigurer {"Content-Disposition","Content-Type","X-Stirling-Skipped-Field-Edits",- "X-Stirling-Skipped-Field-Edits-Total")+ "X-Stirling-Skipped-Field-Edits-Total",+ "X-Stirling-Detected-Fields").allowCredentials(true).maxAge(3600);}diff --git a/app/core/src/main/resources/settings.yml.template b/app/core/src/main/resources/settings.yml.templateindex 4fb4716764..e190d5fb48 100644--- a/app/core/src/main/resources/settings.yml.template+++ b/app/core/src/main/resources/settings.yml.template@@ -407,6 +407,12 @@ aiEngine:pdfComment: true # AI-authored PDF comments/annotationsclassify: true # Automatic document classification/labelling+formDetection:+ enabled: true # Master on/off switch for the Auto Form Detection feature+ activeModelId: "" # Id of the installed Auto Form Detection model (set automatically after an admin installs one)+ modelDir: "" # Optional override directory for downloaded .onnx models; blank uses <configs>/models/form-detection+ preinstalledModelDir: "" # Read-only dir of models baked into the image (the air-gapped image bakes one here); activated on startup without being copied. Blank disables.+policies:# Folder automations can read from and write to the directories you allow here, so treat this as a# security boundary. On a multi-user server EVERY authenticated user (not only team leaders) candiff --git a/app/core/src/test/java/stirling/software/SPDF/config/ToolIODeclarationCoverageTest.java b/app/core/src/test/java/stirling/software/SPDF/config/ToolIODeclarationCoverageTest.javaindex e8fa1d7e87..312cc5c040 100644--- a/app/core/src/test/java/stirling/software/SPDF/config/ToolIODeclarationCoverageTest.java+++ b/app/core/src/test/java/stirling/software/SPDF/config/ToolIODeclarationCoverageTest.java@@ -45,7 +45,10 @@ class ToolIODeclarationCoverageTest {"/api/v1/security/","/api/v1/convert/","/api/v1/filter/",- "/api/v1/integration/");+ "/api/v1/integration/",+ // Just this corner of /api/v1/form/: the only endpoint there that takes a+ // document and returns one, so the only one a chain can contain.+ "/api/v1/form/form-detection/");/*** Not document transforms, so nothing to declare. A path exempts everything nested under it.diff --git a/app/proprietary/build.gradle b/app/proprietary/build.gradleindex e66288238a..c2fe10b42e 100644--- a/app/proprietary/build.gradle+++ b/app/proprietary/build.gradle@@ -3,6 +3,11 @@ repositories {maven { url = "https://build.shibboleth.net/maven/releases" }}+ext {+ // CPU build with self-extracting natives for linux/win/mac x64+arm64. Must stay >=1.21: the+ // model exports are stamped ai.onnx opset 22, which 1.19/1.20 reject outright.+ onnxruntimeVersion = '1.26.0'+}bootRun {enabled = false}@@ -48,6 +53,14 @@ dependencies {implementation "com.google.code.gson:gson:${gsonVersion}"+ // ONNX Runtime (Java) runs Auto Form Detection. The ~42MB multi-platform native is bundled+ // only with -PbundleOnnxRuntime=true (Docker); without it the tool reports unavailable.+ compileOnly "com.microsoft.onnxruntime:onnxruntime:$onnxruntimeVersion"+ testImplementation "com.microsoft.onnxruntime:onnxruntime:$onnxruntimeVersion"+ if ((project.findProperty('bundleOnnxRuntime') ?: 'false').toString().toBoolean()) {+ runtimeOnly "com.microsoft.onnxruntime:onnxruntime:$onnxruntimeVersion"+ }+// jinjava/jjwt transitively request older Jackson 2 versions; declare the current// version directly so it is selected consistently (root build.gradle pins are the fallback).runtimeOnly "com.fasterxml.jackson.core:jackson-core:${jackson2Version}"diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/formdetection/catalog/ModelCatalogService.java b/app/proprietary/src/main/java/stirling/software/proprietary/formdetection/catalog/ModelCatalogService.javanew file mode 100644index 0000000000..a56fdc918b--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/formdetection/catalog/ModelCatalogService.java@@ -0,0 +1,63 @@+package stirling.software.proprietary.formdetection.catalog;++import java.io.InputStream;+import java.util.LinkedHashMap;+import java.util.List;+import java.util.Map;+import java.util.Optional;++import org.springframework.core.io.ClassPathResource;+import org.springframework.stereotype.Service;++import jakarta.annotation.PostConstruct;++import lombok.RequiredArgsConstructor;+import lombok.extern.slf4j.Slf4j;++import stirling.software.proprietary.formdetection.model.ModelCatalogEntry;++import tools.jackson.core.type.TypeReference;+import tools.jackson.databind.ObjectMapper;++/** Loads the curated Auto Form Detection model catalog from a bundled JSON resource. */+@Slf4j+@Service+@RequiredArgsConstructor+public class ModelCatalogService {++ private static final String CATALOG_RESOURCE = "formdetection/model-catalog.json";++ private final ObjectMapper objectMapper;++ private volatile List<ModelCatalogEntry> entries = List.of();+ private volatile Map<String, ModelCatalogEntry> byId = Map.of();++ @PostConstruct+ void load() {+ try (InputStream is = new ClassPathResource(CATALOG_RESOURCE).getInputStream()) {+ List<ModelCatalogEntry> loaded = objectMapper.readValue(is, new TypeReference<>() {});+ Map<String, ModelCatalogEntry> map = new LinkedHashMap<>();+ for (ModelCatalogEntry entry : loaded) {+ if (entry.getId() != null && !entry.getId().isBlank()) {+ map.put(entry.getId(), entry);+ }+ }+ this.entries = List.copyOf(map.values());+ this.byId = Map.copyOf(map);+ log.info("Loaded {} Auto Form Detection model catalog entries", entries.size());+ } catch (Exception e) {+ log.error(+ "Failed to load Auto Form Detection model catalog from {}",+ CATALOG_RESOURCE,+ e);+ }+ }++ public List<ModelCatalogEntry> getAll() {+ return entries;+ }++ public Optional<ModelCatalogEntry> getById(String id) {+ return Optional.ofNullable(id == null ? null : byId.get(id));+ }+}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/formdetection/controller/FormDetectionController.java b/app/proprietary/src/main/java/stirling/software/proprietary/formdetection/controller/FormDetectionController.javanew file mode 100644index 0000000000..5364e4c881--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/formdetection/controller/FormDetectionController.java@@ -0,0 +1,219 @@+package stirling.software.proprietary.formdetection.controller;++import java.io.IOException;+import java.util.ArrayList;+import java.util.LinkedHashMap;+import java.util.List;+import java.util.Map;+import java.util.TreeSet;++import org.apache.pdfbox.pdmodel.PDDocument;+import org.springframework.beans.factory.ObjectProvider;+import org.springframework.core.io.Resource;+import org.springframework.http.HttpStatus;+import org.springframework.http.MediaType;+import org.springframework.http.ResponseEntity;+import org.springframework.web.bind.annotation.PostMapping;+import org.springframework.web.bind.annotation.RequestMapping;+import org.springframework.web.bind.annotation.RequestParam;+import org.springframework.web.bind.annotation.RestController;+import org.springframework.web.multipart.MultipartFile;++import io.github.pixee.security.Filenames;+import io.swagger.v3.oas.annotations.Operation;+import io.swagger.v3.oas.annotations.tags.Tag;++import lombok.RequiredArgsConstructor;+import lombok.extern.slf4j.Slf4j;++import stirling.software.common.model.tool.ToolArity;+import stirling.software.common.model.tool.ToolFormat;+import stirling.software.common.model.tool.ToolIO;+import stirling.software.common.model.tool.ToolIOCase;+import stirling.software.common.model.tool.ToolIOWhen;+import stirling.software.common.service.CustomPDFDocumentFactory;+import stirling.software.common.util.FormUtils;+import stirling.software.common.util.FormUtils.NewFormFieldDefinition;+import stirling.software.common.util.TempFileManager;+import stirling.software.common.util.WebResponseUtils;+import stirling.software.proprietary.formdetection.model.DetectedField;+import stirling.software.proprietary.formdetection.render.PageRasterizer;+import stirling.software.proprietary.formdetection.service.FormDetectionService;++import tools.jackson.databind.ObjectMapper;++/**+ * Detection endpoint, behind the {@code form-detection} key that is disabled until a model is+ * installed. Returns detected fields, or the applied PDF when {@code applyToPdf=true}.+ */+@Slf4j+@RestController+@RequestMapping("/api/v1/form/form-detection")+@RequiredArgsConstructor+@Tag(name = "Auto Form Detection")+public class FormDetectionController {++ /** Carries the field counts alongside the PDF, so one request feeds the results panel. */+ static final String SUMMARY_HEADER = "X-Stirling-Detected-Fields";++ /**+ * Resolved by interface and lazily: the pipeline is absent from builds without onnxruntime, and+ * an eager or concrete-typed dependency would keep this endpoint out of the OpenAPI spec.+ */+ private final ObjectProvider<FormDetectionService> detectionProvider;++ private final CustomPDFDocumentFactory pdfDocumentFactory;+ private final TempFileManager tempFileManager;+ private final ObjectMapper objectMapper;++ @PostMapping(value = "/detect", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)+ @ToolIO(+ produces = ToolFormat.PDF,+ cases = {+ @ToolIOCase(+ when = @ToolIOWhen(param = "applyToPdf", matches = "false"),+ produces = ToolFormat.JSON,+ arity = ToolArity.SISO)+ })+ @Operation(+ summary = "Detect form fields with the installed AI model",+ description =+ "Runs the installed ONNX model over each page and returns the PDF with the"+ + " detected fields added. With applyToPdf=false, returns the field"+ + " rectangles as JSON instead, in PDF points.")+ public ResponseEntity<?> detect(+ @RequestParam("file") MultipartFile file,+ @RequestParam(value = "confThreshold", required = false) Float confThreshold,+ @RequestParam(value = "applyToPdf", required = false, defaultValue = "true")+ boolean applyToPdf)+ throws IOException {++ if (file.isEmpty()) {+ return ResponseEntity.badRequest()+ .body(Map.of("reason", "INVALID_PDF", "message", "The uploaded file is empty"));+ }++ FormDetectionService detection = detectionProvider.getIfAvailable();+ if (detection == null) {+ return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE)+ .body(+ Map.of(+ "reason",+ "DEPENDENCY",+ "message",+ "This build does not include the detection engine"));+ }++ List<DetectedField> detections;+ try {+ detections = detection.detect(file.getBytes(), confThreshold);+ } catch (FormDetectionService.ModelUnavailableException e) {+ return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE)+ .body(Map.of("reason", "DEPENDENCY", "message", e.getMessage()));+ } catch (PageRasterizer.PageLimitExceededException e) {+ return ResponseEntity.badRequest()+ .body(Map.of("reason", "LIMIT", "message", e.getMessage()));+ } catch (PageRasterizer.UnreadablePdfException e) {+ // The user's file is the problem, not the engine - do not report this as a dependency+ // failure, which would send an admin looking for a missing model.+ log.debug("Auto Form Detection rejected an unreadable PDF: {}", e.getMessage());+ return ResponseEntity.badRequest()+ .body(Map.of("reason", "INVALID_PDF", "message", e.getMessage()));+ } catch (IllegalStateException e) {+ // ONNX Runtime native missing for this OS/arch (a slimmed or mis-targeted build):+ // report unavailable rather than 500.+ log.warn("Auto Form Detection inference unavailable: {}", e.getMessage());+ return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE)+ .body(Map.of("reason", "DEPENDENCY", "message", e.getMessage()));+ }++ if (!applyToPdf) {+ return ResponseEntity.ok(new DetectResponse(detections));+ }+ // PDFium is more forgiving than PDFBox, so a file can rasterize and still fail to load+ // here; that is still the file's fault rather than the server's.+ try (PDDocument document = pdfDocumentFactory.load(file)) {+ FormUtils.repairMissingWidgetPageReferences(document);+ List<NewFormFieldDefinition> defs = new ArrayList<>();+ for (DetectedField f : detections) {+ defs.add(toDefinition(f));+ }+ List<FormUtils.CreatedField> written = FormUtils.addFields(document, defs);+ ResponseEntity<Resource> pdf =+ WebResponseUtils.pdfDocToWebResponse(+ document, baseName(file) + ".pdf", tempFileManager);+ return ResponseEntity.status(pdf.getStatusCode())+ .headers(pdf.getHeaders())+ .header(SUMMARY_HEADER, summaryHeader(written))+ .body(pdf.getBody());+ } catch (IOException e) {+ log.debug("Auto Form Detection could not apply fields: {}", e.getMessage());+ return ResponseEntity.badRequest()+ .body(+ Map.of(+ "reason",+ "INVALID_PDF",+ "message",+ "The PDF could not be opened for editing; it may be"+ + " corrupt or password-protected"));+ }+ }++ private static NewFormFieldDefinition toDefinition(DetectedField f) {+ DetectedField.RectPt r = f.rectInPdfPoints();+ // Trailing nulls are fontSize, readOnly, multiline, maxLength and buttonAction:+ // a detector reports geometry and type only, so each takes its default.+ return new NewFormFieldDefinition(+ null,+ null,+ f.type(),+ f.page(),+ (float) r.x(),+ (float) r.y(),+ (float) r.w(),+ (float) r.h(),+ Boolean.FALSE,+ null,+ null,+ null,+ null,+ null,+ null,+ null,+ null,+ null);+ }++ /**+ * Compact JSON of the fields actually written, so the panel cannot over-report ones that+ * addFields skipped, and reports the type each ended up as rather than the detected one.+ */+ private String summaryHeader(List<FormUtils.CreatedField> written) {+ Map<String, Integer> byType = new LinkedHashMap<>();+ TreeSet<Integer> pages = new TreeSet<>();+ for (FormUtils.CreatedField f : written) {+ byType.merge(f.type(), 1, Integer::sum);+ pages.add(f.pageIndex());+ }+ return objectMapper.writeValueAsString(+ Map.of(+ "total", written.size(),+ "byType", byType,+ "pagesWithFields", pages.size()));+ }++ private static String baseName(MultipartFile file) {+ String original = Filenames.toSimpleFileName(file.getOriginalFilename());+ if (original == null || original.isBlank()) {+ original = "document";+ }+ String stem =+ original.toLowerCase().endsWith(".pdf")+ ? original.substring(0, original.length() - 4)+ : original;+ return stem + "_form";+ }++ /** JSON body returned when {@code applyToPdf} is false. */+ public record DetectResponse(List<DetectedField> detections) {}+}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/formdetection/controller/FormDetectionModelController.java b/app/proprietary/src/main/java/stirling/software/proprietary/formdetection/controller/FormDetectionModelController.javanew file mode 100644index 0000000000..4487ee2dcc--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/formdetection/controller/FormDetectionModelController.java@@ -0,0 +1,112 @@+package stirling.software.proprietary.formdetection.controller;++import org.apache.commons.lang3.StringUtils;+import org.springframework.http.HttpStatus;+import org.springframework.http.ResponseEntity;+import org.springframework.security.access.prepost.PreAuthorize;+import org.springframework.web.bind.annotation.DeleteMapping;+import org.springframework.web.bind.annotation.GetMapping;+import org.springframework.web.bind.annotation.PostMapping;+import org.springframework.web.bind.annotation.RequestBody;+import org.springframework.web.bind.annotation.RequestMapping;+import org.springframework.web.bind.annotation.RequestParam;+import org.springframework.web.bind.annotation.RestController;++import io.swagger.v3.oas.annotations.Operation;+import io.swagger.v3.oas.annotations.tags.Tag;++import lombok.Data;+import lombok.RequiredArgsConstructor;+import lombok.extern.slf4j.Slf4j;++import stirling.software.proprietary.formdetection.model.ModelStatusResponse;+import stirling.software.proprietary.formdetection.service.FormDetectionModelManager;++/**+ * Admin lifecycle for the detection model. Uses the never-gated {@code form-detection-model} key so+ * install and status stay reachable while {@code form-detection} itself is disabled.+ */+@Slf4j+@RestController+@RequestMapping("/api/v1/form/form-detection-model")+@RequiredArgsConstructor+@Tag(name = "Auto Form Detection")+public class FormDetectionModelController {++ private final FormDetectionModelManager manager;++ @GetMapping("/status")+ @PreAuthorize("hasRole('ADMIN')")+ @Operation(summary = "Auto Form Detection model status, progress and catalog")+ public ResponseEntity<ModelStatusResponse> status() {+ return ResponseEntity.ok(manager.status());+ }++ @PostMapping("/install")+ @PreAuthorize("hasRole('ADMIN')")+ @Operation(summary = "Install (download + checksum-verify) a catalog model")+ public ResponseEntity<ModelStatusResponse> install(@RequestBody InstallRequest request) {+ if (request == null || StringUtils.isBlank(request.getModelId())) {+ ModelStatusResponse s = manager.status();+ s.setError("modelId is required");+ return ResponseEntity.badRequest().body(s);+ }+ try {+ manager.startInstall(request.getModelId());+ return ResponseEntity.accepted().body(manager.status());+ } catch (IllegalStateException e) {+ ModelStatusResponse s = manager.status();+ s.setError(e.getMessage());+ return ResponseEntity.status(HttpStatus.CONFLICT).body(s);+ } catch (IllegalArgumentException e) {+ ModelStatusResponse s = manager.status();+ s.setError(e.getMessage());+ return ResponseEntity.badRequest().body(s);+ }+ }++ @DeleteMapping+ @PreAuthorize("hasRole('ADMIN')")+ @Operation(summary = "Uninstall a model")+ public ResponseEntity<ModelStatusResponse> delete(+ @RequestParam(name = "modelId", required = false) String modelId) {+ try {+ manager.deleteModel(modelId);+ return ResponseEntity.ok(manager.status());+ } catch (IllegalStateException e) {+ ModelStatusResponse s = manager.status();+ s.setError(e.getMessage());+ return ResponseEntity.status(HttpStatus.CONFLICT).body(s);+ }+ }++ @PostMapping("/config")+ @PreAuthorize("hasRole('ADMIN')")+ @Operation(summary = "Update the feature on/off switch")+ public ResponseEntity<ModelStatusResponse> config(@RequestBody ConfigRequest request) {+ if (request == null) {+ return ResponseEntity.badRequest().body(manager.status());+ }+ try {+ if (request.getEnabled() != null) {+ manager.setEnabled(request.getEnabled());+ }+ return ResponseEntity.ok(manager.status());+ } catch (IllegalArgumentException e) {+ ModelStatusResponse s = manager.status();+ s.setError(e.getMessage());+ return ResponseEntity.badRequest().body(s);+ }+ }++ @Data+ public static class ConfigRequest {+ /** Master on/off; {@code null} leaves it unchanged. */+ private Boolean enabled;+ }++ @Data+ public static class InstallRequest {+ private String modelId;+ }+}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/formdetection/inference/OnnxFormDetector.java b/app/proprietary/src/main/java/stirling/software/proprietary/formdetection/inference/OnnxFormDetector.javanew file mode 100644index 0000000000..d838e35e35--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/formdetection/inference/OnnxFormDetector.java@@ -0,0 +1,176 @@+package stirling.software.proprietary.formdetection.inference;++import java.nio.FloatBuffer;+import java.nio.file.Path;+import java.util.Collections;+import java.util.LinkedHashMap;+import java.util.Map;+import java.util.concurrent.Semaphore;+import java.util.concurrent.locks.ReentrantReadWriteLock;++import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;+import org.springframework.stereotype.Service;++import jakarta.annotation.PreDestroy;++import lombok.RequiredArgsConstructor;+import lombok.extern.slf4j.Slf4j;++import stirling.software.proprietary.formdetection.model.ModelCatalogEntry;+import stirling.software.proprietary.formdetection.service.FormDetectionModelManager;++import ai.onnxruntime.OnnxTensor;+import ai.onnxruntime.OnnxValue;+import ai.onnxruntime.OrtEnvironment;+import ai.onnxruntime.OrtException;+import ai.onnxruntime.OrtSession;++/**+ * Holds the ONNX Runtime session, reloading on model change under a read/write lock and capping+ * concurrent inferences. Input is NCHW float32 {@code [1,3,N,N]}; output is raw.+ */+@Slf4j+@Service+@ConditionalOnClass(name = "ai.onnxruntime.OrtEnvironment")+@RequiredArgsConstructor+public class OnnxFormDetector implements UnloadableModel {++ private final FormDetectionModelManager manager;++ private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();+ private final Semaphore concurrency =+ new Semaphore(Math.max(1, Runtime.getRuntime().availableProcessors() / 2));++ private volatile OrtSession session;+ private volatile String loadedModelId;+ private volatile String inputName;++ /**+ * Run the model, returning each output tensor keyed by graph name. RF-DETR's {@code dets} and+ * {@code labels} share a shape, so an index would decode logits as boxes.+ */+ public Map<String, Yolo.RawOutput> infer(float[] chw, int inputSize) {+ ensureLoaded();+ concurrency.acquireUninterruptibly();+ lock.readLock().lock();+ try {+ // Re-read under the lock: an uninstall between ensureLoaded and here closes the+ // session, and dereferencing it then would be a 500 rather than the usual 503.+ OrtSession current = session;+ String input = inputName;+ if (current == null || input == null) {+ throw new IllegalStateException("Model was unloaded while the request was running");+ }+ OrtEnvironment env = OrtEnvironment.getEnvironment();+ long[] shape = {1, 3, inputSize, inputSize};+ try (OnnxTensor tensor = OnnxTensor.createTensor(env, FloatBuffer.wrap(chw), shape);+ OrtSession.Result results =+ current.run(Collections.singletonMap(input, tensor))) {+ Map<String, Yolo.RawOutput> outputs = new LinkedHashMap<>();+ for (Map.Entry<String, OnnxValue> entry : results) {+ outputs.put(entry.getKey(), toRawOutput(entry.getKey(), entry.getValue()));+ }+ if (outputs.isEmpty()) {+ throw new IllegalStateException("ONNX session returned no outputs");+ }+ return outputs;+ }+ } catch (OrtException e) {+ throw new IllegalStateException("ONNX inference failed: " + e.getMessage(), e);+ } finally {+ lock.readLock().unlock();+ concurrency.release();+ }+ }++ /** Flatten a [1, d1, d2] output into the row-major buffer the decoders index into. */+ private static Yolo.RawOutput toRawOutput(String name, OnnxValue value) throws OrtException {+ Object raw = value.getValue();+ if (!(raw instanceof float[][][] out3) || out3.length == 0) {+ throw new IllegalStateException(+ "Unexpected ONNX output type for '"+ + name+ + "': "+ + (raw == null ? "null" : raw.getClass()));+ }+ float[][] m = out3[0];+ int d1 = m.length;+ int d2 = d1 > 0 ? m[0].length : 0;+ float[] flat = new float[d1 * d2];+ for (int i = 0; i < d1; i++) {+ System.arraycopy(m[i], 0, flat, i * d2, d2);+ }+ return new Yolo.RawOutput(flat, d1, d2);+ }++ /** Force the next inference to reload from disk (called after install/uninstall). */+ @Override+ public void unload() {+ lock.writeLock().lock();+ try {+ closeSession();+ loadedModelId = null;+ inputName = null;+ } finally {+ lock.writeLock().unlock();+ }+ }++ private void ensureLoaded() {+ String activeId = manager.getActiveEntry().map(ModelCatalogEntry::getId).orElse(null);+ if (activeId == null) {+ throw new IllegalStateException("No Auto Form Detection model installed");+ }+ if (activeId.equals(loadedModelId) && session != null) {+ return;+ }+ lock.writeLock().lock();+ try {+ if (activeId.equals(loadedModelId) && session != null) {+ return;+ }+ Path file =+ manager.getActiveModelFile()+ .orElseThrow(+ () -> new IllegalStateException("Active model file missing"));+ try {+ OrtEnvironment env = OrtEnvironment.getEnvironment();+ OrtSession.SessionOptions opts = new OrtSession.SessionOptions();+ try {+ opts.setIntraOpNumThreads(+ Math.max(1, Runtime.getRuntime().availableProcessors() / 2));+ } catch (OrtException ignored) {+ // best-effort tuning+ }+ closeSession();+ session = env.createSession(file.toString(), opts);+ inputName = session.getInputNames().iterator().next();+ loadedModelId = activeId;+ log.info("Loaded ONNX session for Auto Form Detection model '{}'", activeId);+ } catch (OrtException | RuntimeException | LinkageError e) {+ // Native missing for this OS+arch, or the model failed to load.+ // Swallowed so no UnsatisfiedLinkError escapes; detect reports unavailable.+ throw new IllegalStateException(+ "ONNX Runtime is unavailable on this platform/build: " + e.getMessage(), e);+ }+ } finally {+ lock.writeLock().unlock();+ }+ }++ @PreDestroy+ void close() {+ unload();+ }++ private void closeSession() {+ if (session != null) {+ try {+ session.close();+ } catch (Exception _) {+ // already closing+ }+ session = null;+ }+ }+}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/formdetection/inference/RfDetr.java b/app/proprietary/src/main/java/stirling/software/proprietary/formdetection/inference/RfDetr.javanew file mode 100644index 0000000000..bb4cd951f2--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/formdetection/inference/RfDetr.java@@ -0,0 +1,114 @@+package stirling.software.proprietary.formdetection.inference;++import java.util.ArrayList;+import java.util.List;+import java.util.Map;++import lombok.extern.slf4j.Slf4j;++import stirling.software.proprietary.formdetection.model.ModelCatalogEntry;++/**+ * Decoder for RF-DETR query-based heads: two output tensors, fixed queries, boxes normalised to+ * [0,1] and raw logits. Preprocessing is shared with {@link Yolo#preprocess}.+ */+@Slf4j+public final class RfDetr {++ private RfDetr() {}++ /** Normalised box centres/sizes. */+ private static final String BOXES = "dets";++ /** Per-class logits, plus a trailing no-object column. */+ private static final String LOGITS = "labels";++ /**+ * Decode two named outputs into detections in original-bitmap pixels. Looked up by name, never+ * position: with three classes both tensors are [300, 4] and share a shape.+ */+ public static List<Yolo.Detection> decode(+ Map<String, Yolo.RawOutput> outputs,+ ModelCatalogEntry spec,+ Yolo.Preprocessed pre,+ float scoreThreshold) {++ int numClasses = spec.getClassNames() == null ? 0 : spec.getClassNames().size();+ if (numClasses == 0) {+ return List.of();+ }+ Yolo.RawOutput boxes = outputs.get(BOXES);+ Yolo.RawOutput logits = outputs.get(LOGITS);+ if (boxes == null || logits == null) {+ log.warn(+ "rfdetr decoder expects outputs '{}' and '{}'; got {}",+ BOXES,+ LOGITS,+ outputs.keySet());+ return List.of();+ }+ if (boxes.d2() < 4) {+ log.warn("rfdetr '{}' has {} columns, expected >= 4", BOXES, boxes.d2());+ return List.of();+ }+ // The head emits one logit per class plus a no-object slot; anything narrower means the+ // model was trained for a different class set than the catalogue entry claims.+ if (logits.d2() <= numClasses) {+ log.warn(+ "rfdetr '{}' has {} columns, expected >= {} for {} classes plus no-object;"+ + " skipping",+ LOGITS,+ logits.d2(),+ numClasses + 1,+ numClasses);+ return List.of();+ }+ int queries = Math.min(boxes.d1(), logits.d1());++ List<Yolo.Detection> dets = new ArrayList<>();+ for (int q = 0; q < queries; q++) {+ int bestClass = -1;+ float bestScore = 0f;+ // Deliberately stops at numClasses, dropping the trailing no-object column.+ for (int c = 0; c < numClasses; c++) {+ float score = sigmoid(logits.data()[q * logits.d2() + c]);+ if (score > bestScore) {+ bestScore = score;+ bestClass = c;+ }+ }+ if (bestClass < 0 || bestScore < scoreThreshold) {+ continue;+ }++ int base = q * boxes.d2();+ // Normalised centre form -> input-space pixels, so the un-projection below is the+ // same arithmetic the YOLO path uses.+ float cx = boxes.data()[base] * pre.inputSize();+ float cy = boxes.data()[base + 1] * pre.inputSize();+ float w = boxes.data()[base + 2] * pre.inputSize();+ float h = boxes.data()[base + 3] * pre.inputSize();++ float x1 = cx - w / 2f;+ float y1 = cy - h / 2f;+ float ox = (x1 - pre.padX()) / pre.scaleX();+ float oy = (y1 - pre.padY()) / pre.scaleY();+ float ow = w / pre.scaleX();+ float oh = h / pre.scaleY();++ float clampedX = Math.max(0, Math.min(ox, pre.srcW()));+ float clampedY = Math.max(0, Math.min(oy, pre.srcH()));+ ow = Math.max(0, Math.min(ow, pre.srcW() - clampedX));+ oh = Math.max(0, Math.min(oh, pre.srcH() - clampedY));+ if (ow <= 0 || oh <= 0) {+ continue;+ }+ dets.add(new Yolo.Detection(bestClass, bestScore, clampedX, clampedY, ow, oh));+ }+ return Yolo.nms(dets, spec.getNms(), spec.getIou());+ }++ private static float sigmoid(float x) {+ return (float) (1.0 / (1.0 + Math.exp(-x)));+ }+}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/formdetection/inference/UnloadableModel.java b/app/proprietary/src/main/java/stirling/software/proprietary/formdetection/inference/UnloadableModel.javanew file mode 100644index 0000000000..12ac960599--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/formdetection/inference/UnloadableModel.java@@ -0,0 +1,11 @@+package stirling.software.proprietary.formdetection.inference;++/**+ * Lets the model manager drop an engine's loaded model. Must stay ONNX-free: Spring introspecting+ * {@code OnnxFormDetector} without onnxruntime would kill startup.+ */+public interface UnloadableModel {++ /** Discard any loaded model so the next inference reloads from disk. */+ void unload();+}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/formdetection/inference/Yolo.java b/app/proprietary/src/main/java/stirling/software/proprietary/formdetection/inference/Yolo.javanew file mode 100644index 0000000000..a6d30213fd--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/formdetection/inference/Yolo.java@@ -0,0 +1,270 @@+package stirling.software.proprietary.formdetection.inference;++import java.awt.Color;+import java.awt.Graphics2D;+import java.awt.RenderingHints;+import java.awt.image.BufferedImage;+import java.util.ArrayList;+import java.util.List;++import lombok.extern.slf4j.Slf4j;++import stirling.software.proprietary.formdetection.model.ModelCatalogEntry;++/**+ * Pre/post-processing for a YOLO-style detector, driven by the {@link ModelCatalogEntry} spec.+ * {@code decode} yields bitmap pixels, top-left origin; CoordinateMapper maps to PDF points.+ */+@Slf4j+public final class Yolo {++ /**+ * Hard bound on the boxes one page may feed into suppression, which is O(n^2). A model whose+ * scores all clear the threshold would otherwise put every anchor through it - at input size+ * 1216 that is over 30,000.+ */+ static final int MAX_NMS_CANDIDATES = 5000;++ private Yolo() {}++ /** Normalised model input plus the transform needed to invert it. */+ public record Preprocessed(+ float[] chw,+ int inputSize,+ float scaleX,+ float scaleY,+ int padX,+ int padY,+ int srcW,+ int srcH) {}++ /** Raw model output flattened to {@code data[i*d2 + j]} with dims {@code d1 x d2}. */+ public record RawOutput(float[] data, int d1, int d2) {}++ /** A detection in original bitmap-pixel space, top-left origin. */+ public record Detection(int classId, float score, float x, float y, float w, float h) {}++ /** Letterbox/stretch-resize, normalise and lay out as NCHW float32. */+ public static Preprocessed preprocess(byte[] rgba, int srcW, int srcH, ModelCatalogEntry spec) {+ int n = spec.getInputSize();+ boolean letterbox = !"stretch".equalsIgnoreCase(spec.getResizeMode());++ float scaleX;+ float scaleY;+ int padX;+ int padY;+ int drawW;+ int drawH;+ if (letterbox) {+ float scale = Math.min((float) n / srcW, (float) n / srcH);+ drawW = Math.max(1, Math.round(srcW * scale));+ drawH = Math.max(1, Math.round(srcH * scale));+ padX = (n - drawW) / 2;+ padY = (n - drawH) / 2;+ scaleX = scale;+ scaleY = scale;+ } else {+ drawW = n;+ drawH = n;+ padX = 0;+ padY = 0;+ scaleX = (float) n / srcW;+ scaleY = (float) n / srcH;+ }++ int[] pad = spec.getPadColor();+ Color fill =+ new Color(+ clampByte(pad != null && pad.length > 0 ? pad[0] : 114),+ clampByte(pad != null && pad.length > 1 ? pad[1] : 114),+ clampByte(pad != null && pad.length > 2 ? pad[2] : 114));++ BufferedImage canvas = new BufferedImage(n, n, BufferedImage.TYPE_INT_RGB);+ Graphics2D g = canvas.createGraphics();+ try {+ g.setRenderingHint(+ RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);+ g.setColor(fill);+ g.fillRect(0, 0, n, n);+ g.drawImage(rgbaToImage(rgba, srcW, srcH), padX, padY, drawW, drawH, null);+ } finally {+ g.dispose();+ }++ boolean bgr = "bgr".equalsIgnoreCase(spec.getChannelOrder());+ float[] mean = orZeros(spec.getNormMean());+ float[] std = orOnes(spec.getNormStd());+ int plane = n * n;+ float[] chw = new float[3 * plane];+ int[] px = canvas.getRGB(0, 0, n, n, null, 0, n);+ for (int i = 0; i < plane; i++) {+ int rgb = px[i];+ float r = ((rgb >> 16) & 0xFF) / 255f;+ float gg = ((rgb >> 8) & 0xFF) / 255f;+ float b = (rgb & 0xFF) / 255f;+ float c0 = bgr ? b : r;+ float c1 = gg;+ float c2 = bgr ? r : b;+ chw[i] = (c0 - mean[0]) / std[0];+ chw[plane + i] = (c1 - mean[1]) / std[1];+ chw[2 * plane + i] = (c2 - mean[2]) / std[2];+ }+ return new Preprocessed(chw, n, scaleX, scaleY, padX, padY, srcW, srcH);+ }++ /** Decode raw output, threshold, NMS, and un-project to original bitmap pixels. */+ public static List<Detection> decode(+ RawOutput out, ModelCatalogEntry spec, Preprocessed pre, float scoreThreshold) {+ int numClasses = spec.getClassNames() == null ? 0 : spec.getClassNames().size();+ if (numClasses == 0) {+ return List.of();+ }+ boolean obj = spec.isHasObjectness();+ boolean ncFirst = !"anchors_first".equalsIgnoreCase(spec.getOutputLayout());+ int channels = ncFirst ? out.d1() : out.d2();+ int anchors = ncFirst ? out.d2() : out.d1();+ int expected = 4 + (obj ? 1 : 0) + numClasses;+ if (channels < expected) {+ log.warn(+ "ONNX output channel count {} < expected {} (4 + obj + {} classes); skipping",+ channels,+ expected,+ numClasses);+ return List.of();+ }+ int classOffset = 4 + (obj ? 1 : 0);+ float[] data = out.data();++ List<Detection> dets = new ArrayList<>();+ for (int a = 0; a < anchors; a++) {+ float objScore = obj ? at(data, ncFirst, anchors, channels, 4, a) : 1f;+ int bestClass = -1;+ float bestScore = 0f;+ for (int c = 0; c < numClasses; c++) {+ float s = at(data, ncFirst, anchors, channels, classOffset + c, a) * objScore;+ if (s > bestScore) {+ bestScore = s;+ bestClass = c;+ }+ }+ if (bestClass < 0 || bestScore < scoreThreshold) {+ continue;+ }+ float cx = at(data, ncFirst, anchors, channels, 0, a);+ float cy = at(data, ncFirst, anchors, channels, 1, a);+ float w = at(data, ncFirst, anchors, channels, 2, a);+ float h = at(data, ncFirst, anchors, channels, 3, a);+ float x1 = cx - w / 2f;+ float y1 = cy - h / 2f;+ float ox = (x1 - pre.padX()) / pre.scaleX();+ float oy = (y1 - pre.padY()) / pre.scaleY();+ float ow = w / pre.scaleX();+ float oh = h / pre.scaleY();+ // clamp to the source bitmap+ float cxl = Math.max(0, Math.min(ox, pre.srcW()));+ float cyl = Math.max(0, Math.min(oy, pre.srcH()));+ ow = Math.max(0, Math.min(ow, pre.srcW() - cxl));+ oh = Math.max(0, Math.min(oh, pre.srcH() - cyl));+ if (ow <= 0 || oh <= 0) {+ continue;+ }+ dets.add(new Detection(bestClass, bestScore, cxl, cyl, ow, oh));+ }+ return nms(dets, spec.getNms(), spec.getIou());+ }++ private static float at(+ float[] data, boolean ncFirst, int anchors, int channels, int c, int a) {+ return ncFirst ? data[c * anchors + a] : data[a * channels + c];+ }++ /** Shared with {@link RfDetr}: identical suppression whatever head produced the boxes. */+ static List<Detection> nms(List<Detection> dets, String mode, float iouThreshold) {+ List<Detection> candidates = highestScoring(dets, MAX_NMS_CANDIDATES);+ if (candidates.size() < 2 || "none".equalsIgnoreCase(mode)) {+ return candidates;+ }+ boolean classAgnostic = mode != null && mode.toLowerCase().contains("agnostic");+ List<Detection> sorted = new ArrayList<>(candidates);+ sorted.sort((x, y) -> Float.compare(y.score(), x.score()));+ boolean[] removed = new boolean[sorted.size()];+ List<Detection> keep = new ArrayList<>();+ for (int i = 0; i < sorted.size(); i++) {+ if (removed[i]) {+ continue;+ }+ Detection di = sorted.get(i);+ keep.add(di);+ for (int j = i + 1; j < sorted.size(); j++) {+ if (removed[j]) {+ continue;+ }+ Detection dj = sorted.get(j);+ if (!classAgnostic && di.classId() != dj.classId()) {+ continue;+ }+ if (iou(di, dj) > iouThreshold) {+ removed[j] = true;+ }+ }+ }+ return keep;+ }++ private static List<Detection> highestScoring(List<Detection> dets, int limit) {+ if (dets.size() <= limit) {+ return dets;+ }+ // Debug, not warn: this runs per page, so a capped document would log once per page.+ log.debug(+ "Page produced {} candidate boxes; keeping the {} best-scoring",+ dets.size(),+ limit);+ List<Detection> trimmed = new ArrayList<>(dets);+ trimmed.sort((x, y) -> Float.compare(y.score(), x.score()));+ return new ArrayList<>(trimmed.subList(0, limit));+ }++ private static float iou(Detection a, Detection b) {+ float ax2 = a.x() + a.w();+ float ay2 = a.y() + a.h();+ float bx2 = b.x() + b.w();+ float by2 = b.y() + b.h();+ float ix1 = Math.max(a.x(), b.x());+ float iy1 = Math.max(a.y(), b.y());+ float ix2 = Math.min(ax2, bx2);+ float iy2 = Math.min(ay2, by2);+ float iw = Math.max(0, ix2 - ix1);+ float ih = Math.max(0, iy2 - iy1);+ float inter = iw * ih;+ float union = a.w() * a.h() + b.w() * b.h() - inter;+ return union <= 0 ? 0 : inter / union;+ }++ private static BufferedImage rgbaToImage(byte[] rgba, int w, int h) {+ BufferedImage img = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);+ int[] px = new int[w * h];+ int pixels = Math.min(w * h, rgba.length / 4);+ for (int i = 0; i < pixels; i++) {+ int r = rgba[i * 4] & 0xFF;+ int g = rgba[i * 4 + 1] & 0xFF;+ int b = rgba[i * 4 + 2] & 0xFF;+ int a = rgba[i * 4 + 3] & 0xFF;+ px[i] = (a << 24) | (r << 16) | (g << 8) | b;+ }+ img.setRGB(0, 0, w, h, px, 0, w);+ return img;+ }++ private static int clampByte(int v) {+ return Math.max(0, Math.min(255, v));+ }++ private static float[] orZeros(float[] v) {+ return v != null && v.length >= 3 ? v : new float[] {0f, 0f, 0f};+ }++ private static float[] orOnes(float[] v) {+ return v != null && v.length >= 3 ? v : new float[] {1f, 1f, 1f};+ }+}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/formdetection/model/DetectedField.java b/app/proprietary/src/main/java/stirling/software/proprietary/formdetection/model/DetectedField.javanew file mode 100644index 0000000000..a2fc75f2aa--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/formdetection/model/DetectedField.java@@ -0,0 +1,15 @@+package stirling.software.proprietary.formdetection.model;++/**+ * One detected form field, as returned by the detect endpoint.+ *+ * @param type AcroForm field type (text|checkbox|radio|signature)+ * @param page zero-based page index+ * @param rectInPdfPoints rectangle in PDF points (bottom-left origin)+ * @param confidence detection confidence 0-1+ */+public record DetectedField(String type, int page, RectPt rectInPdfPoints, double confidence) {++ /** Rectangle in PDF points, bottom-left origin (PDF user space). */+ public record RectPt(double x, double y, double w, double h) {}+}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/formdetection/model/FormDetectionStatus.java b/app/proprietary/src/main/java/stirling/software/proprietary/formdetection/model/FormDetectionStatus.javanew file mode 100644index 0000000000..43c920e467--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/formdetection/model/FormDetectionStatus.java@@ -0,0 +1,17 @@+package stirling.software.proprietary.formdetection.model;++import java.util.Locale;++/** Lifecycle state of the Auto Form Detection model install. */+public enum FormDetectionStatus {+ NOT_INSTALLED,+ DOWNLOADING,+ VERIFYING,+ READY,+ FAILED;++ /** Lowercase wire form sent to the frontend, e.g. {@code not_installed}. */+ public String wire() {+ return name().toLowerCase(Locale.ROOT);+ }+}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/formdetection/model/ModelCatalogEntry.java b/app/proprietary/src/main/java/stirling/software/proprietary/formdetection/model/ModelCatalogEntry.javanew file mode 100644index 0000000000..d63bf528b1--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/formdetection/model/ModelCatalogEntry.java@@ -0,0 +1,74 @@+package stirling.software.proprietary.formdetection.model;++import java.util.List;++import lombok.Data;++/**+ * One installable model plus the pre/post-processing spec its pipeline needs; verify every value+ * against the exported {@code .onnx}. A blank {@code onnxUrl} means not installable.+ */+@Data+public class ModelCatalogEntry {++ // --- Identity / distribution -------------------------------------------------+ private String id;+ private String displayName;+ private String description;+ private String license;+ private long sizeBytes;++ /** Direct download URL of the .onnx. Blank = not yet available (install is rejected). */+ private String onnxUrl;++ /** Lower-hex SHA-256 of the .onnx. Blank = not yet available (install is rejected). */+ private String sha256;++ // --- Pre-processing (must match the exported model) --------------------------+ /** Square model input edge in pixels. */+ private int inputSize = 1024;++ /** "letterbox" (aspect-preserving pad) or "stretch" (resize to square). */+ private String resizeMode = "letterbox";++ /** RGB letterbox pad colour. */+ private int[] padColor = {114, 114, 114};++ /** "rgb" or "bgr" channel order fed to the model. */+ private String channelOrder = "rgb";++ /**+ * Per-channel mean subtracted after dividing the raw byte by 255 ({@code (raw/255 -+ * mean)/std}).+ */+ private float[] normMean = {0f, 0f, 0f};++ /** Per-channel std applied after mean subtraction. */+ private float[] normStd = {1f, 1f, 1f};++ // --- Post-processing (parity-critical) ---------------------------------------+ /**+ * Head shape, so how the output is read. {@code yolo}: one anchor-grid tensor, input pixels,+ * activated scores. {@code rfdetr}: {@code dets} (normalised cxcywh) plus {@code labels}.+ */+ private String decoder = "yolo";++ /** "nc_first" => output [1, 4+nc, anchors]; "anchors_first" => [1, anchors, 4+nc]. */+ private String outputLayout = "nc_first";++ /** True if an objectness score column precedes the class scores (YOLOv5 style). */+ private boolean hasObjectness = false;++ /** Class index -> label. */+ private List<String> classNames = List.of("text", "choice", "signature");++ /** Class index -> AcroForm field type (text|checkbox|radio|signature). */+ private List<String> classFieldTypes = List.of("text", "checkbox", "signature");++ private float scoreThreshold = 0.25f;++ /** "none", "classAgnostic" or "perClass". */+ private String nms = "perClass";++ private float iou = 0.45f;+}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/formdetection/model/ModelStatusResponse.java b/app/proprietary/src/main/java/stirling/software/proprietary/formdetection/model/ModelStatusResponse.javanew file mode 100644index 0000000000..7ff8bc5207--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/formdetection/model/ModelStatusResponse.java@@ -0,0 +1,42 @@+package stirling.software.proprietary.formdetection.model;++import java.util.List;++import lombok.AllArgsConstructor;+import lombok.Data;+import lombok.NoArgsConstructor;++/** Snapshot returned by {@code GET /api/v1/form/form-detection-model/status}. */+@Data+@NoArgsConstructor+@AllArgsConstructor+public class ModelStatusResponse {+ /** Wire state: not_installed | downloading | verifying | ready | failed. */+ private String status;++ /** Download progress 0-100 (meaningful while downloading). */+ private int progress;++ /** Id of the active/usable model, or blank when none. */+ private String activeModelId;++ /** Model ids usable right now: downloaded, plus any the image baked in. */+ private List<String> installed;++ /** Last error message, or null. */+ private String error;++ /** Whether the model directory is writable (admin install possible). */+ private boolean writable;++ /** Full curated catalog (identity + pipeline spec). */+ private List<ModelCatalogEntry> catalog;++ /** Master on/off for the whole feature (admin-controlled). */+ private boolean enabled;++ /** True when the ONNX engine is bundled in this build; without it detection cannot run. */+ private boolean serverEngineAvailable;++ private String downloadingModelId;+}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/formdetection/render/CoordinateMapper.java b/app/proprietary/src/main/java/stirling/software/proprietary/formdetection/render/CoordinateMapper.javanew file mode 100644index 0000000000..c7e688861e--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/formdetection/render/CoordinateMapper.java@@ -0,0 +1,70 @@+package stirling.software.proprietary.formdetection.render;++import lombok.experimental.UtilityClass;++import stirling.software.proprietary.formdetection.inference.Yolo;+import stirling.software.proprietary.formdetection.model.DetectedField;++/**+ * Maps bitmap pixels (top-left origin) to PDF points in unrotated user space, where widget rects+ * live. The bitmap has /Rotate baked in: scale + Y-flip, inverse rotation, then crop.+ */+@UtilityClass+public class CoordinateMapper {++ public DetectedField.RectPt toPdfPoints(Yolo.Detection d, PageRasterizer.RasterPage page) {+ float sx = page.scaleX() > 0 ? page.scaleX() : 1f;+ float sy = page.scaleY() > 0 ? page.scaleY() : 1f;++ // Bitmap px -> display-space points (bottom-left origin via Y flip).+ double wd = d.w() / sx;+ double hd = d.h() / sy;+ double xd = d.x() / sx;+ double yd = page.pageHeightPt() - (d.y() / sy) - hd;++ // Display space -> unrotated user space (inverse of the /Rotate the renderer applied).+ double uw = page.userWidthPt() > 0 ? page.userWidthPt() : page.pageWidthPt();+ double uh = page.userHeightPt() > 0 ? page.userHeightPt() : page.pageHeightPt();+ double x;+ double y;+ double w;+ double h;+ switch (page.rotationDegrees()) {+ case 90 -> {+ x = uw - yd - hd;+ y = xd;+ w = hd;+ h = wd;+ }+ case 180 -> {+ x = uw - xd - wd;+ y = uh - yd - hd;+ w = wd;+ h = hd;+ }+ case 270 -> {+ x = yd;+ y = uh - xd - wd;+ w = hd;+ h = wd;+ }+ default -> {+ x = xd;+ y = yd;+ w = wd;+ h = hd;+ }+ }++ // Clamp inside the crop box, then translate by its lower-left origin.+ x = clamp(x, 0, uw);+ y = clamp(y, 0, uh);+ w = clamp(w, 0, uw - x);+ h = clamp(h, 0, uh - y);+ return new DetectedField.RectPt(x + page.cropLlxPt(), y + page.cropLlyPt(), w, h);+ }++ private double clamp(double v, double lo, double hi) {+ return v < lo ? lo : Math.min(v, hi);+ }+}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/formdetection/render/PageRasterizer.java b/app/proprietary/src/main/java/stirling/software/proprietary/formdetection/render/PageRasterizer.javanew file mode 100644index 0000000000..d8cf4c549e--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/formdetection/render/PageRasterizer.java@@ -0,0 +1,189 @@+package stirling.software.proprietary.formdetection.render;++import java.io.IOException;+import java.util.function.Consumer;++import org.apache.pdfbox.pdmodel.PDDocument;+import org.apache.pdfbox.pdmodel.PDPage;+import org.apache.pdfbox.pdmodel.common.PDRectangle;+import org.springframework.stereotype.Service;++import lombok.Getter;+import lombok.RequiredArgsConstructor;+import lombok.extern.slf4j.Slf4j;++import stirling.software.common.service.CustomPDFDocumentFactory;+import stirling.software.jpdfium.PdfDocument;+import stirling.software.jpdfium.PdfPage;+import stirling.software.jpdfium.model.PageSize;+import stirling.software.jpdfium.model.RenderResult;++/**+ * Renders pages to RGBA via JPDFium at roughly the model input size, one at a time so a large+ * document cannot exhaust the heap. Rotation and crop box come from PDFBox, not JPDFium.+ */+@Slf4j+@Service+@RequiredArgsConstructor+public class PageRasterizer {++ private final CustomPDFDocumentFactory pdfDocumentFactory;++ /** The PDF cannot be opened or rendered: a bad request, not an engine failure. */+ public static class UnreadablePdfException extends RuntimeException {+ public UnreadablePdfException(String message, Throwable cause) {+ super(message, cause);+ }+ }++ /** The document has more pages than the caller allows. Thrown before anything is rendered. */+ @Getter+ public static class PageLimitExceededException extends RuntimeException {+ private final int pageCount;+ private final int limit;++ public PageLimitExceededException(int pageCount, int limit) {+ super("PDF has " + pageCount + " pages; the limit is " + limit);+ this.pageCount = pageCount;+ this.limit = limit;+ }+ }++ /**+ * A rendered page: RGBA pixels in display space (rotation applied, crop-box origin at 0,0) plus+ * the geometry needed to map display-space points back to unrotated user space.+ *+ * @param pageWidthPt display-space width in points (rotated crop box)+ * @param pageHeightPt display-space height in points (rotated crop box)+ * @param scaleX px per display-space point, horizontal+ * @param scaleY px per display-space point, vertical+ * @param rotationDegrees normalized page /Rotate: 0, 90, 180 or 270+ * @param userWidthPt unrotated crop-box width in points+ * @param userHeightPt unrotated crop-box height in points+ * @param cropLlxPt crop-box lower-left x in user space+ * @param cropLlyPt crop-box lower-left y in user space+ */+ public record RasterPage(+ int pageIndex,+ byte[] rgba,+ int widthPx,+ int heightPx,+ float pageWidthPt,+ float pageHeightPt,+ float scaleX,+ float scaleY,+ int rotationDegrees,+ float userWidthPt,+ float userHeightPt,+ float cropLlxPt,+ float cropLlyPt) {}++ /**+ * Render each page in turn and pass it to {@code handler}. Only one page of pixels is reachable+ * at a time, so peak memory is one bitmap rather than the whole document.+ *+ * @param maxPages reject the document if it has more pages than this, before rendering any+ * @throws PageLimitExceededException the document exceeds {@code maxPages}+ * @throws UnreadablePdfException the PDF is empty, corrupt or password-protected+ */+ public void rasterize(+ byte[] pdfBytes, int inputSize, int maxPages, Consumer<RasterPage> handler) {+ if (pdfBytes == null || pdfBytes.length == 0) {+ throw new UnreadablePdfException("The uploaded file is empty", null);+ }+ try (PdfDocument doc = openForRender(pdfBytes);+ PDDocument boxDoc = openForGeometry(pdfBytes)) {+ int count = pageCount(doc);+ // Checked before the loop: rendering first and counting after would let a huge upload+ // exhaust the heap on its way to being rejected.+ if (count > maxPages) {+ throw new PageLimitExceededException(count, maxPages);+ }+ for (int i = 0; i < count; i++) {+ // Rendered in a helper so a PDFium failure is classified as bad input, while+ // anything the handler throws propagates untouched.+ handler.accept(renderPage(doc, boxDoc, i, inputSize));+ }+ } catch (IOException e) {+ throw new UnreadablePdfException("Failed to read the PDF", e);+ }+ }++ private RasterPage renderPage(PdfDocument doc, PDDocument boxDoc, int index, int inputSize) {+ try (PdfPage page = doc.page(index)) {+ PageSize size = page.size();+ float maxSide = Math.max(size.width(), size.height());+ int dpi = maxSide <= 0 ? 150 : Math.round(72f * inputSize / maxSide);+ dpi = Math.max(36, Math.min(dpi, 300));+ RenderResult r = page.renderAt(dpi);+ float scaleX = size.width() > 0 ? r.width() / size.width() : dpi / 72f;+ float scaleY = size.height() > 0 ? r.height() / size.height() : dpi / 72f;++ int rotation = 0;+ float userW = size.width();+ float userH = size.height();+ float llx = 0;+ float lly = 0;+ if (boxDoc != null && index < boxDoc.getNumberOfPages()) {+ PDPage boxPage = boxDoc.getPage(index);+ rotation = normalizeRotation(boxPage.getRotation());+ PDRectangle crop = boxPage.getCropBox();+ userW = crop.getWidth();+ userH = crop.getHeight();+ llx = crop.getLowerLeftX();+ lly = crop.getLowerLeftY();+ } else if (boxDoc == null) {+ log.warn("Page geometry unavailable; assuming unrotated page with origin (0,0)");+ }++ return new RasterPage(+ index,+ r.rgba(),+ r.width(),+ r.height(),+ size.width(),+ size.height(),+ scaleX,+ scaleY,+ rotation,+ userW,+ userH,+ llx,+ lly);+ } catch (RuntimeException e) {+ throw new UnreadablePdfException("Failed to render page " + (index + 1), e);+ }+ }++ private PdfDocument openForRender(byte[] pdfBytes) {+ try {+ return PdfDocument.open(pdfBytes);+ } catch (Exception e) {+ throw new UnreadablePdfException(+ "The PDF could not be opened; it may be corrupt or password-protected", e);+ }+ }++ private int pageCount(PdfDocument doc) {+ try {+ return doc.pageCount();+ } catch (RuntimeException e) {+ throw new UnreadablePdfException("The PDF has no readable page tree", e);+ }+ }++ private PDDocument openForGeometry(byte[] pdfBytes) {+ try {+ return pdfDocumentFactory.load(pdfBytes);+ } catch (IOException e) {+ log.warn("Could not open PDF with PDFBox for page geometry: {}", e.getMessage());+ return null;+ }+ }++ static int normalizeRotation(int degrees) {+ int r = ((degrees % 360) + 360) % 360;+ // The PDF spec only allows multiples of 90; snap defensively.+ return (r / 90) * 90 % 360;+ }+}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/formdetection/service/FormDetectionModelManager.java b/app/proprietary/src/main/java/stirling/software/proprietary/formdetection/service/FormDetectionModelManager.javanew file mode 100644index 0000000000..f544cc691b--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/formdetection/service/FormDetectionModelManager.java@@ -0,0 +1,674 @@+package stirling.software.proprietary.formdetection.service;++import static java.nio.file.StandardOpenOption.CREATE;+import static java.nio.file.StandardOpenOption.TRUNCATE_EXISTING;+import static java.nio.file.StandardOpenOption.WRITE;++import java.io.IOException;+import java.io.InputStream;+import java.io.OutputStream;+import java.net.HttpURLConnection;+import java.net.URI;+import java.nio.file.AtomicMoveNotSupportedException;+import java.nio.file.DirectoryStream;+import java.nio.file.Files;+import java.nio.file.Path;+import java.nio.file.Paths;+import java.nio.file.StandardCopyOption;+import java.security.MessageDigest;+import java.util.ArrayList;+import java.util.HexFormat;+import java.util.List;+import java.util.Locale;+import java.util.Optional;+import java.util.concurrent.atomic.AtomicBoolean;+import java.util.regex.Pattern;++import org.apache.commons.lang3.StringUtils;+import org.springframework.beans.factory.ObjectProvider;+import org.springframework.stereotype.Service;++import jakarta.annotation.PostConstruct;++import lombok.RequiredArgsConstructor;+import lombok.extern.slf4j.Slf4j;++import stirling.software.SPDF.config.EndpointConfiguration;+import stirling.software.SPDF.config.EndpointConfiguration.DisableReason;+import stirling.software.common.configuration.RuntimePathConfig;+import stirling.software.common.model.ApplicationProperties;+import stirling.software.common.util.GeneralUtils;+import stirling.software.proprietary.formdetection.catalog.ModelCatalogService;+import stirling.software.proprietary.formdetection.inference.UnloadableModel;+import stirling.software.proprietary.formdetection.model.FormDetectionStatus;+import stirling.software.proprietary.formdetection.model.ModelCatalogEntry;+import stirling.software.proprietary.formdetection.model.ModelStatusResponse;++/**+ * Downloads, verifies and tracks the detection model. Single-flight install, SHA-256 verified,+ * published by atomic rename into a mounted volume so it survives container restarts.+ */+@Slf4j+@Service+@RequiredArgsConstructor+public class FormDetectionModelManager {++ /** Endpoint key gated until a model is ready (drives the disabled tool tile in the UI). */+ public static final String ENDPOINT_KEY = "form-detection";++ private static final Pattern SAFE_ID = Pattern.compile("[a-z0-9][a-z0-9-]{0,63}");+ private static final Pattern SHA256_HEX = Pattern.compile("[0-9a-f]{64}");++ /** The only origin the bundled catalog downloads from; also rejects userinfo/lookalikes. */+ private static final String ALLOWED_MODEL_URL_PREFIX = "https://huggingface.co/";++ /** Hugging Face hands the file off to its own CDN, so redirects must stay in these domains. */+ private static final List<String> ALLOWED_REDIRECT_HOSTS = List.of("huggingface.co", "hf.co");++ private static final int MAX_REDIRECTS = 5;++ /** Slack over the catalogue size; a larger body could never match the checksum anyway. */+ private static final long DOWNLOAD_SLACK_BYTES = 8L * 1024 * 1024;++ /** Ceiling when neither the catalogue nor Content-Length declares a size. */+ private static final long MAX_DOWNLOAD_BYTES = 512L * 1024 * 1024;++ /**+ * Whether the ONNX engine is bundled in this build; the jar only ships with {@code+ * -PbundleOnnxRuntime=true}. Without it the tool cannot run at all.+ */+ private static final boolean SERVER_ENGINE_AVAILABLE = isOnnxRuntimePresent();++ private static boolean isOnnxRuntimePresent() {+ try {+ Class.forName(+ "ai.onnxruntime.OrtEnvironment",+ false,+ FormDetectionModelManager.class.getClassLoader());+ return true;+ } catch (Throwable t) {+ return false;+ }+ }++ private final RuntimePathConfig runtimePathConfig;+ private final ModelCatalogService catalog;+ private final ApplicationProperties applicationProperties;+ private final EndpointConfiguration endpointConfiguration;++ /**+ * Resolved lazily and by interface: the ONNX engine is absent from builds without onnxruntime,+ * and an eager or concrete-typed dependency would fail startup there.+ */+ private final ObjectProvider<UnloadableModel> engineProvider;++ private final AtomicBoolean installing = new AtomicBoolean(false);+ private volatile FormDetectionStatus state = FormDetectionStatus.NOT_INSTALLED;+ private volatile int progress = 0;+ private volatile String error = null;+ private volatile String activeSha = null;+ private volatile String downloadingModelId = null;++ @PostConstruct+ void init() {+ sweepTempFiles();+ seedPreinstalledModels();+ Optional<Path> active = getActiveModelFile();+ if (active.isPresent()) {+ activeSha = getActiveEntry().map(ModelCatalogEntry::getSha256).orElse(null);+ state = FormDetectionStatus.READY;+ log.info("Auto Form Detection model '{}' is installed and ready", activeModelId());+ } else {+ state = FormDetectionStatus.NOT_INSTALLED;+ }+ applyEndpointState();+ }++ /**+ * Gate the {@code form-detection} endpoint that drives the tool tile: CONFIG when an admin+ * disabled the feature, DEPENDENCY when no model is ready, enabled otherwise.+ */+ private void applyEndpointState() {+ if (!isFeatureEnabled()) {+ endpointConfiguration.disableEndpoint(ENDPOINT_KEY, DisableReason.CONFIG);+ } else if (isServerEngineAvailable()+ && state == FormDetectionStatus.READY+ && getActiveModelFile().isPresent()) {+ endpointConfiguration.enableEndpoint(ENDPOINT_KEY);+ } else {+ endpointConfiguration.disableEndpoint(ENDPOINT_KEY, DisableReason.DEPENDENCY);+ }+ }++ /** Package-private so a test can simulate a build packaged without the ONNX runtime. */+ boolean isServerEngineAvailable() {+ return SERVER_ENGINE_AVAILABLE;+ }++ public boolean isFeatureEnabled() {+ return applicationProperties.getFormDetection().isEnabled();+ }++ /** Master on/off (admin). Persists and re-gates the endpoint immediately. */+ public synchronized void setEnabled(boolean enabled) {+ applicationProperties.getFormDetection().setEnabled(enabled);+ try {+ GeneralUtils.saveKeyToSettings("formDetection.enabled", enabled);+ } catch (IOException e) {+ log.warn("Could not persist formDetection.enabled (state kept in memory)", e);+ }+ applyEndpointState();+ }++ /**+ * Validate and kick off a background download+verify+install. Returns immediately; callers poll+ * {@link #status()}.+ *+ * @throws IllegalArgumentException unknown/invalid model id or bad checksum format+ * @throws IllegalStateException no URL/checksum configured, or an install is already running+ */+ public synchronized void startInstall(String modelId) {+ if (!SAFE_ID.matcher(modelId).matches()) {+ throw new IllegalArgumentException("Invalid model id: " + modelId);+ }+ ModelCatalogEntry entry =+ catalog.getById(modelId)+ .orElseThrow(+ () -> new IllegalArgumentException("Unknown model id: " + modelId));+ // URL + checksum come ONLY from the bundled catalog (trusted constants), never from the+ // request, so an admin cannot point the download at an arbitrary host (avoids SSRF).+ String url = entry.getOnnxUrl();+ String sha = entry.getSha256() == null ? null : entry.getSha256().toLowerCase(Locale.ROOT);+ if (StringUtils.isBlank(url) || StringUtils.isBlank(sha)) {+ throw new IllegalStateException(+ "Model '" + modelId + "' has no download URL/checksum configured yet");+ }+ // Same allowlist the download enforces, so a bad catalog entry fails here, not mid-install.+ if (!url.startsWith(ALLOWED_MODEL_URL_PREFIX)) {+ throw new IllegalArgumentException("Model URL is not on the allowlist: " + url);+ }+ if (!SHA256_HEX.matcher(sha).matches()) {+ throw new IllegalArgumentException("Checksum must be a 64-char hex SHA-256");+ }+ if (!installing.compareAndSet(false, true)) {+ throw new IllegalStateException("An install is already in progress");+ }+ state = FormDetectionStatus.DOWNLOADING;+ progress = 0;+ error = null;+ downloadingModelId = modelId;+ // isReady() is already false here, so without re-gating the tool tile stays clickable for+ // the whole download and every request behind it answers 503.+ applyEndpointState();+ final String fUrl = url;+ final String fSha = sha;+ Thread.ofVirtual()+ .name("form-detection-install-" + modelId)+ .start(+ () -> {+ try {+ doInstall(modelId, entry, fUrl, fSha);+ } catch (Exception e) {+ log.error("Auto Form Detection install failed for {}", modelId, e);+ error = e.getMessage();+ progress = 0;+ // Keep a previously-installed model usable if the new one failed.+ state =+ getActiveModelFile().isPresent()+ ? FormDetectionStatus.READY+ : FormDetectionStatus.FAILED;+ applyEndpointState();+ } finally {+ downloadingModelId = null;+ installing.set(false);+ }+ });+ }++ private void doInstall(String modelId, ModelCatalogEntry entry, String url, String expectedSha)+ throws IOException {+ Path dir = modelDir();+ Files.createDirectories(dir);+ if (!isWritable(dir)) {+ throw new IOException("Model directory is not writable: " + dir);+ }+ Path base = dir.toRealPath();+ Path target = base.resolve(modelId + ".onnx").normalize();+ if (!target.startsWith(base)) {+ throw new IOException("Blocked path traversal for model id " + modelId);+ }++ // Already downloaded and intact: skip the network fetch and just (re)activate it. Makes+ // switching between already-downloaded models instant instead of re-fetching tens of MB.+ if (Files.isRegularFile(target) && expectedSha.equals(sha256OfFile(target))) {+ log.info(+ "Model '{}' already present and verified; activating without re-download",+ modelId);+ activate(modelId, expectedSha);+ return;+ }++ Path tmp = base.resolve(modelId + ".onnx.tmp");++ MessageDigest digest;+ try {+ digest = MessageDigest.getInstance("SHA-256");+ } catch (Exception e) {+ throw new IOException("SHA-256 unavailable", e);+ }++ HttpURLConnection conn = null;+ try {+ conn = openModelDownload(url);+ long total =+ entry.getSizeBytes() > 0 ? entry.getSizeBytes() : conn.getContentLengthLong();+ long ceiling = total > 0 ? total + DOWNLOAD_SLACK_BYTES : MAX_DOWNLOAD_BYTES;+ try (InputStream in = conn.getInputStream();+ OutputStream out =+ Files.newOutputStream(tmp, CREATE, TRUNCATE_EXISTING, WRITE)) {+ byte[] buf = new byte[1 << 16];+ long read = 0;+ int n;+ while ((n = in.read(buf)) >= 0) {+ read += n;+ if (read > ceiling) {+ throw new IOException(+ "Model download exceeded the expected size of "+ + ceiling+ + " bytes");+ }+ out.write(buf, 0, n);+ digest.update(buf, 0, n);+ if (total > 0) {+ progress = (int) Math.min(99, (read * 100) / total);+ }+ }+ }+ } catch (IOException | RuntimeException e) {+ // The partial file can never verify, so do not leave it on the configs volume.+ try {+ Files.deleteIfExists(tmp);+ } catch (IOException suppressed) {+ e.addSuppressed(suppressed);+ }+ throw e;+ } finally {+ if (conn != null) {+ conn.disconnect();+ }+ }++ state = FormDetectionStatus.VERIFYING;+ byte[] actual = digest.digest();+ byte[] expected = HexFormat.of().parseHex(expectedSha);+ if (!MessageDigest.isEqual(actual, expected)) {+ Files.deleteIfExists(tmp);+ throw new IOException(+ "Checksum mismatch (expected "+ + expectedSha+ + " got "+ + HexFormat.of().formatHex(actual)+ + ")");+ }++ try {+ Files.move(+ tmp,+ target,+ StandardCopyOption.ATOMIC_MOVE,+ StandardCopyOption.REPLACE_EXISTING);+ } catch (AtomicMoveNotSupportedException e) {+ Files.move(tmp, target, StandardCopyOption.REPLACE_EXISTING);+ }++ activate(modelId, expectedSha);+ }++ /**+ * Open the model download after checking the URL against the allowlist. Redirects are followed+ * by hand so every hop is re-checked; auto-follow would skip that. Package-private for tests.+ */+ HttpURLConnection openModelDownload(String url) throws IOException {+ if (!url.startsWith(ALLOWED_MODEL_URL_PREFIX)) {+ throw new IOException("Model download URL is not on the allowlist: " + url);+ }+ String current = url;+ for (int hop = 0; hop <= MAX_REDIRECTS; hop++) {+ HttpURLConnection conn =+ (HttpURLConnection) URI.create(current).toURL().openConnection();+ conn.setInstanceFollowRedirects(false);+ conn.setRequestMethod("GET");+ conn.setRequestProperty("User-Agent", "Stirling-PDF-App");+ conn.setRequestProperty("Accept", "application/octet-stream");+ conn.setConnectTimeout(10000);+ conn.setReadTimeout(60000);+ int http = conn.getResponseCode();+ if (http == HttpURLConnection.HTTP_OK) {+ return conn;+ }+ String location = isRedirect(http) ? conn.getHeaderField("Location") : null;+ conn.disconnect();+ if (StringUtils.isBlank(location)) {+ throw new IOException("Download failed: HTTP " + http + " from " + current);+ }+ current = requireAllowedRedirect(current, location);+ }+ throw new IOException("Too many redirects downloading model from " + url);+ }++ private static boolean isRedirect(int status) {+ return status == HttpURLConnection.HTTP_MOVED_PERM+ || status == HttpURLConnection.HTTP_MOVED_TEMP+ || status == HttpURLConnection.HTTP_SEE_OTHER+ || status == 307+ || status == 308;+ }++ /**+ * Resolve a redirect target and re-apply the https + host allowlist to it. Package-private so+ * the allowlist can be tested directly.+ */+ static String requireAllowedRedirect(String from, String location) throws IOException {+ URI next;+ try {+ next = URI.create(from).resolve(location);+ } catch (IllegalArgumentException e) {+ throw new IOException("Model download redirect is not a valid URL: " + location, e);+ }+ String host = next.getHost() == null ? "" : next.getHost().toLowerCase(Locale.ROOT);+ boolean allowed =+ "https".equalsIgnoreCase(next.getScheme())+ && next.getUserInfo() == null+ && ALLOWED_REDIRECT_HOSTS.stream()+ .anyMatch(h -> host.equals(h) || host.endsWith("." + h));+ if (!allowed) {+ throw new IOException("Model download redirect is not on the allowlist: " + next);+ }+ return next.toString();+ }++ /**+ * Tombstone for an admin-uninstalled model, so the next boot's seeding cannot resurrect it;+ * cleared by a reinstall. The containment check keeps the path inside the model dir.+ */+ private Path tombstoneFor(String id) {+ Path base = modelDir().normalize();+ Path tombstone = base.resolve(id + ".onnx.removed").normalize();+ if (!tombstone.startsWith(base)) {+ throw new IllegalArgumentException("Blocked path traversal for model id " + id);+ }+ return tombstone;+ }++ private void clearTombstone(String id) {+ try {+ Files.deleteIfExists(tombstoneFor(id));+ } catch (IOException e) {+ log.debug("Could not clear uninstall tombstone for {}", id, e);+ }+ }++ /**+ * Mark a verified on-disk model active and re-enable the feature. Synchronized because it+ * writes settings from the install thread, where a concurrent toggle could drop a key.+ */+ private synchronized void activate(String modelId, String expectedSha) {+ clearTombstone(modelId);+ applicationProperties.getFormDetection().setActiveModelId(modelId);+ try {+ GeneralUtils.saveKeyToSettings("formDetection.activeModelId", modelId);+ } catch (IOException e) {+ log.warn("Could not persist formDetection.activeModelId (state kept in memory)", e);+ }+ activeSha = expectedSha;+ progress = 100;+ state = FormDetectionStatus.READY;+ invalidateEngine();+ applyEndpointState();+ log.info("Auto Form Detection model '{}' installed and ready", modelId);+ }++ /**+ * Drop any model an engine still holds. Reinstalling the same id leaves the loaded id+ * unchanged, so without this the engine keeps serving the pre-swap session.+ */+ private void invalidateEngine() {+ engineProvider.ifAvailable(UnloadableModel::unload);+ }++ /** SHA-256 of an existing model file as lowercase hex, or {@code null} if it cannot be read. */+ private String sha256OfFile(Path file) {+ try (InputStream in = Files.newInputStream(file)) {+ MessageDigest digest = MessageDigest.getInstance("SHA-256");+ byte[] buf = new byte[1 << 16];+ int n;+ while ((n = in.read(buf)) >= 0) {+ digest.update(buf, 0, n);+ }+ return HexFormat.of().formatHex(digest.digest());+ } catch (Exception e) {+ log.debug("Could not hash existing model file {}", file, e);+ return null;+ }+ }++ /** Remove a model file; if it was the active one, disable the feature again. */+ public synchronized void deleteModel(String modelId) {+ if (installing.get()) {+ throw new IllegalStateException("Cannot uninstall while an install is in progress");+ }+ String id = StringUtils.isNotBlank(modelId) ? modelId : activeModelId();+ if (StringUtils.isBlank(id) || !SAFE_ID.matcher(id).matches()) {+ return;+ }+ // Only the downloaded copy is ours to remove; an image-baked file is read-only and is+ // retired by the tombstone below instead.+ Optional<Path> file = modelFileIn(modelDir(), id);+ if (file.isPresent()) {+ try {+ Files.deleteIfExists(file.get());+ } catch (IOException e) {+ log.warn("Failed to delete model file {}", file.get(), e);+ }+ }+ // Record the explicit removal so a pre-installed copy is not re-seeded on restart.+ try {+ Path tombstone = tombstoneFor(id);+ if (!Files.exists(tombstone)) {+ Files.createFile(tombstone);+ }+ } catch (IOException e) {+ log.warn("Could not record uninstall tombstone for {}", id, e);+ }+ if (id.equals(activeModelId())) {+ applicationProperties.getFormDetection().setActiveModelId("");+ try {+ GeneralUtils.saveKeyToSettings("formDetection.activeModelId", "");+ } catch (IOException e) {+ log.warn("Could not clear formDetection.activeModelId", e);+ }+ activeSha = null;+ }+ if (getActiveModelFile().isEmpty()) {+ state = FormDetectionStatus.NOT_INSTALLED;+ error = null;+ }+ // The file is gone; releasing the engine's handle on it frees the native session too.+ invalidateEngine();+ applyEndpointState();+ }++ /**+ * Synchronized with the mutators: activate() flips the state before it enables the endpoint, so+ * an unsynchronized read can report ready while /detect is still gated.+ */+ public synchronized ModelStatusResponse status() {+ Path dir = modelDir();+ List<String> installed = new ArrayList<>(listModelIds(dir));+ // Image-baked models count as installed even though they were never copied here.+ for (String id : listModelIds(preinstalledDir())) {+ if (!installed.contains(id) && !isTombstoned(id)) {+ installed.add(id);+ }+ }+ return new ModelStatusResponse(+ state.wire(),+ progress,+ activeModelId(),+ installed,+ error,+ isWritable(dir),+ catalog.getAll(),+ isFeatureEnabled(),+ isServerEngineAvailable(),+ downloadingModelId);+ }++ public Optional<Path> getActiveModelFile() {+ return installedModelFile(activeModelId());+ }++ /**+ * Locate a model by listing the directory, so the path can never escape it via the id. The+ * writable model dir wins; an image-baked copy is read in place.+ */+ private Optional<Path> installedModelFile(String id) {+ if (StringUtils.isBlank(id) || !SAFE_ID.matcher(id).matches()) {+ return Optional.empty();+ }+ Optional<Path> downloaded = modelFileIn(modelDir(), id);+ if (downloaded.isPresent()) {+ return downloaded;+ }+ // An uninstalled model must stay uninstalled even though the image copy is still there.+ return isTombstoned(id) ? Optional.empty() : modelFileIn(preinstalledDir(), id);+ }++ private Optional<Path> modelFileIn(Path dir, String id) {+ if (dir == null || !Files.isDirectory(dir)) {+ return Optional.empty();+ }+ String wanted = id + ".onnx";+ try (DirectoryStream<Path> s = Files.newDirectoryStream(dir, "*.onnx")) {+ for (Path p : s) {+ if (wanted.equals(p.getFileName().toString()) && Files.isRegularFile(p)) {+ return Optional.of(p);+ }+ }+ } catch (IOException e) {+ log.debug("Could not list models in {}", dir, e);+ }+ return Optional.empty();+ }++ /** Ids of the {@code <id>.onnx} files in a directory; empty when it is unset or missing. */+ private List<String> listModelIds(Path dir) {+ List<String> ids = new ArrayList<>();+ if (dir == null || !Files.isDirectory(dir)) {+ return ids;+ }+ try (DirectoryStream<Path> s = Files.newDirectoryStream(dir, "*.onnx")) {+ for (Path p : s) {+ String fn = p.getFileName().toString();+ ids.add(fn.substring(0, fn.length() - ".onnx".length()));+ }+ } catch (IOException e) {+ log.debug("Could not list models in {}", dir, e);+ }+ return ids;+ }++ private boolean isTombstoned(String id) {+ return SAFE_ID.matcher(id).matches() && Files.exists(tombstoneFor(id));+ }++ /** Read-only dir of image-baked models, or null when the deployment bakes none. */+ private Path preinstalledDir() {+ String dir = applicationProperties.getFormDetection().getPreinstalledModelDir();+ return StringUtils.isBlank(dir) ? null : Paths.get(dir);+ }++ public Optional<ModelCatalogEntry> getActiveEntry() {+ return catalog.getById(activeModelId());+ }++ public Optional<String> getActiveEtag() {+ return Optional.ofNullable(activeSha);+ }++ public boolean isReady() {+ return isFeatureEnabled()+ && state == FormDetectionStatus.READY+ && getActiveModelFile().isPresent();+ }++ private String activeModelId() {+ return applicationProperties.getFormDetection().getActiveModelId();+ }++ private Path modelDir() {+ return Paths.get(runtimePathConfig.getFormDetectionModelPath());+ }++ /**+ * Activate an image-baked model when nothing is active, so the air-gapped image needs no admin+ * install. Read in place; copying would store the same ~37MB twice per container.+ */+ private void seedPreinstalledModels() {+ Path src = preinstalledDir();+ if (src == null || !Files.isDirectory(src)) {+ return;+ }+ for (String id : listModelIds(src)) {+ if (!SAFE_ID.matcher(id).matches() || catalog.getById(id).isEmpty()) {+ continue;+ }+ if (isTombstoned(id)) {+ log.info("Skipping pre-installed model '{}': an admin uninstalled it", id);+ continue;+ }+ if (StringUtils.isNotBlank(activeModelId())) {+ continue;+ }+ applicationProperties.getFormDetection().setActiveModelId(id);+ try {+ GeneralUtils.saveKeyToSettings("formDetection.activeModelId", id);+ } catch (IOException e) {+ log.warn("Could not persist seeded activeModelId: {}", e.getMessage());+ }+ log.info("Activated pre-installed Auto Form Detection model '{}'", id);+ }+ }++ private void sweepTempFiles() {+ Path dir = modelDir();+ if (!Files.isDirectory(dir)) {+ return;+ }+ try (DirectoryStream<Path> s = Files.newDirectoryStream(dir, "*.tmp")) {+ for (Path p : s) {+ try {+ Files.deleteIfExists(p);+ } catch (IOException ignored) {+ // best-effort sweep of interrupted downloads+ }+ }+ } catch (IOException e) {+ log.debug("No stale form-detection temp files to sweep", e);+ }+ }++ private boolean isWritable(Path dir) {+ try {+ Files.createDirectories(dir);+ if (!Files.isWritable(dir)) {+ return false;+ }+ Path probe = Files.createTempFile(dir, "fd-write-test", ".tmp");+ Files.deleteIfExists(probe);+ return true;+ } catch (IOException e) {+ return false;+ }+ }+}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/formdetection/service/FormDetectionService.java b/app/proprietary/src/main/java/stirling/software/proprietary/formdetection/service/FormDetectionService.javanew file mode 100644index 0000000000..e4061d88d3--- /dev/null+++ b/app/proprietary/src/main/java/stirling/software/proprietary/formdetection/service/FormDetectionService.java@@ -0,0 +1,139 @@+package stirling.software.proprietary.formdetection.service;++import java.io.IOException;+import java.util.ArrayList;+import java.util.List;+import java.util.Map;++import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;+import org.springframework.stereotype.Service;++import lombok.RequiredArgsConstructor;+import lombok.extern.slf4j.Slf4j;++import stirling.software.proprietary.formdetection.inference.OnnxFormDetector;+import stirling.software.proprietary.formdetection.inference.RfDetr;+import stirling.software.proprietary.formdetection.inference.Yolo;+import stirling.software.proprietary.formdetection.model.DetectedField;+import stirling.software.proprietary.formdetection.model.ModelCatalogEntry;+import stirling.software.proprietary.formdetection.render.CoordinateMapper;+import stirling.software.proprietary.formdetection.render.PageRasterizer;++/**+ * Runs the detection pipeline: rasterize, infer, decode, map to PDF points. Callers other than HTTP+ * (a pipeline step, a scheduled job) go through here rather than back through the controller.+ */+@Slf4j+@Service+@ConditionalOnClass(name = "ai.onnxruntime.OrtEnvironment")+@RequiredArgsConstructor+public class FormDetectionService {++ /** Hard bound on pages per request; inference is ~1s/page, so this caps worst-case work. */+ public static final int MAX_PAGES = 500;++ /** Cap on total fields; past this an output PDF is unusable and NMS cost is O(n^2). */+ public static final int MAX_FIELDS = 2000;++ /**+ * Floor for a caller-supplied threshold. At 0 no anchor is below it, so every one of the tens+ * of thousands a page produces reaches the O(n^2) suppression and is retained until the+ * MAX_FIELDS trim.+ */+ public static final float MIN_SCORE_THRESHOLD = 0.01f;++ private final FormDetectionModelManager manager;+ private final OnnxFormDetector detector;+ private final PageRasterizer rasterizer;++ /** Thrown when no model is installed, or its catalogue spec has gone missing. */+ public static class ModelUnavailableException extends RuntimeException {+ public ModelUnavailableException(String message) {+ super(message);+ }+ }++ /**+ * Detect fields across every page, in PDF points.+ *+ * @param confThreshold overrides the model's own score threshold, clamped to {@link+ * #MIN_SCORE_THRESHOLD}..1; null uses the spec's+ * @throws ModelUnavailableException no model is installed or active+ * @throws PageRasterizer.PageLimitExceededException the document exceeds {@link #MAX_PAGES}+ * @throws PageRasterizer.UnreadablePdfException the PDF is empty, corrupt or password-protected+ * @throws IllegalStateException the ONNX native is missing for this OS/arch+ */+ public List<DetectedField> detect(byte[] pdfBytes, Float confThreshold) throws IOException {+ if (!manager.isReady()) {+ throw new ModelUnavailableException("AI form-detection model is not installed");+ }+ ModelCatalogEntry spec =+ manager.getActiveEntry()+ .orElseThrow(+ () ->+ new ModelUnavailableException(+ "Active model spec unavailable"));++ // An out-of-range or NaN threshold would keep essentially every anchor.+ float score =+ confThreshold != null && !confThreshold.isNaN()+ ? Math.clamp(confThreshold, MIN_SCORE_THRESHOLD, 1f)+ : spec.getScoreThreshold();++ // Pages are consumed as they are rendered, so only one page of RGBA is ever live.+ List<DetectedField> collected = new ArrayList<>();+ rasterizer.rasterize(+ pdfBytes,+ spec.getInputSize(),+ MAX_PAGES,+ page -> {+ Yolo.Preprocessed pre =+ Yolo.preprocess(page.rgba(), page.widthPx(), page.heightPx(), spec);+ Map<String, Yolo.RawOutput> out =+ detector.infer(pre.chw(), spec.getInputSize());+ for (Yolo.Detection d : decodeFor(spec, out, pre, score)) {+ DetectedField.RectPt rect = CoordinateMapper.toPdfPoints(d, page);+ if (rect.w() <= 0 || rect.h() <= 0) {+ continue;+ }+ collected.add(+ new DetectedField(+ fieldType(spec, d.classId()),+ page.pageIndex(),+ rect,+ d.score()));+ }+ });++ if (collected.size() <= MAX_FIELDS) {+ return collected;+ }+ log.info(+ "Capping {} detections to {} highest-confidence fields",+ collected.size(),+ MAX_FIELDS);+ collected.sort((a, b) -> Double.compare(b.confidence(), a.confidence()));+ return new ArrayList<>(collected.subList(0, MAX_FIELDS));+ }++ /** Pick the decoder the model's head needs; an unrecognised value falls back to YOLO. */+ private static List<Yolo.Detection> decodeFor(+ ModelCatalogEntry spec,+ Map<String, Yolo.RawOutput> outputs,+ Yolo.Preprocessed pre,+ float score) {+ if ("rfdetr".equalsIgnoreCase(spec.getDecoder())) {+ return RfDetr.decode(outputs, spec, pre, score);+ }+ // Single-output head: take the sole tensor whatever the graph happens to call it.+ return Yolo.decode(outputs.values().iterator().next(), spec, pre, score);+ }++ private static String fieldType(ModelCatalogEntry spec, int classId) {+ List<String> types = spec.getClassFieldTypes();+ if (types != null && classId >= 0 && classId < types.size()) {+ return types.get(classId);+ }+ return "text";+ }+}diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/security/configuration/SecurityConfiguration.java b/app/proprietary/src/main/java/stirling/software/proprietary/security/configuration/SecurityConfiguration.javaindex 7c5b412d33..9923e3aa81 100644--- a/app/proprietary/src/main/java/stirling/software/proprietary/security/configuration/SecurityConfiguration.java+++ b/app/proprietary/src/main/java/stirling/software/proprietary/security/configuration/SecurityConfiguration.java@@ -215,7 +215,8 @@ public class SecurityConfiguration {"Content-Disposition","Content-Type","X-Stirling-Skipped-Field-Edits",- "X-Stirling-Skipped-Field-Edits-Total"));+ "X-Stirling-Skipped-Field-Edits-Total",+ "X-Stirling-Detected-Fields"));cfg.setAllowCredentials(true);cfg.setMaxAge(3600L);diff --git a/app/proprietary/src/main/resources/formdetection/NOTICE b/app/proprietary/src/main/resources/formdetection/NOTICEnew file mode 100644index 0000000000..c880dcc147--- /dev/null+++ b/app/proprietary/src/main/resources/formdetection/NOTICE@@ -0,0 +1,46 @@+Auto Form Detection - third-party model attribution+===================================================++Models are downloaded on demand from the URLs in model-catalog.json and verified against the+SHA-256 recorded there. The air-gapped image (docker/embedded/Dockerfile.fat) additionally bakes+the ffdetr weights in at build time, since it is the deployment that cannot fetch them later.++This NOTICE covers weights Stirling itself publishes or redistributes. It exists because+Apache-2.0 section 4 attaches attribution and NOTICE obligations to whoever conveys the work,+and converting a checkpoint to ONNX and hosting the result makes us that party.+++ffdetr+------+FFDetr, a form-field detector trained on the CommonForms dataset.++ Weights https://huggingface.co/jbarrow/FFDetr Apache-2.0+ Our export https://huggingface.co/Frooodle/ffdetr-int8 Apache-2.0+ Base model Roboflow RF-DETR (rf-detr-medium) Apache-2.0+ Framework https://github.com/roboflow/rf-detr Apache-2.0+ Backbone DINOv2 (Meta AI) Apache-2.0+ Dataset https://huggingface.co/datasets/jbarrow/CommonForms Apache-2.0+ Paper CommonForms, arXiv:2509.16506++The .onnx Stirling distributes is not the upstream artifact: the publisher releases a PyTorch+.pth only. Stirling exports it to ONNX and quantises it to int8 via+scripts/export-ffdetr-onnx.py, which pins the source revision and its checksum. No weights are+modified beyond that conversion, and the result is republished under the same licence.++Not vendored: the `commonforms` reference wrapper (github.com/jbarrow/commonforms) carries no+licence file and depends on Ultralytics, so none of its code is used. The pre/post-processing in+RfDetr.java is written from the model's own input/output contract.+++ffdnet-s, ffdnet-l+------------------+NOT REDISTRIBUTED BY STIRLING, and deliberately so.++The FFDNet checkpoints (huggingface.co/jbarrow/FFDNet-S-cpu and FFDNet-L-cpu) declare no+licence at all, which under default copyright means all rights reserved. They are also trained+with Ultralytics YOLO11, whose AGPL-3.0 terms their publisher asserts no grant over.++They remain in the catalogue so an operator who has their own arrangement with the publisher can+install them, but the download comes from the publisher's own URL, they are never baked into a+Stirling image, and they must not become a shipped default. See the notes on+FORM_DETECTION_MODEL_URL in docker/embedded/Dockerfile.diff --git a/app/proprietary/src/main/resources/formdetection/model-catalog.json b/app/proprietary/src/main/resources/formdetection/model-catalog.jsonnew file mode 100644index 0000000000..2955d675f2--- /dev/null+++ b/app/proprietary/src/main/resources/formdetection/model-catalog.json@@ -0,0 +1,127 @@+[+ {+ "id": "ffdetr",+ "displayName": "CommonForms FFDetr (Apache-2.0)",+ "description": "Permissively licensed detector trained on the same CommonForms data. Finds text inputs, checkboxes and signature fields. Quantised to int8, so it is the smallest option as well as the only one with a licence grant.",+ "license": "Apache-2.0. Weights https://huggingface.co/jbarrow/FFDetr, base model Roboflow RF-DETR, CommonForms dataset - all Apache-2.0. Converted to ONNX by Stirling via scripts/export-ffdetr-onnx.py and republished at https://huggingface.co/Frooodle/ffdetr-int8; see the NOTICE beside this file.",+ "sizeBytes": 37116529,+ "onnxUrl": "https://huggingface.co/Frooodle/ffdetr-int8/resolve/ad3223d7c3ae25ce1d1ec8fe972c8ff7630aff45/ffdetr-int8.onnx",+ "sha256": "de43bb39adb08459fe62fa1a7be6bfb4f2d397bb034c46055f3b8fa3d04fc8f4",+ "decoder": "rfdetr",+ "inputSize": 1024,+ "resizeMode": "stretch",+ "padColor": [+ 114,+ 114,+ 114+ ],+ "channelOrder": "rgb",+ "normMean": [+ 0.485,+ 0.456,+ 0.406+ ],+ "normStd": [+ 0.229,+ 0.224,+ 0.225+ ],+ "classNames": [+ "text",+ "choice",+ "signature"+ ],+ "classFieldTypes": [+ "text",+ "checkbox",+ "signature"+ ],+ "scoreThreshold": 0.3,+ "nms": "classAgnostic",+ "iou": 0.45+ },+ {+ "id": "ffdnet-s",+ "displayName": "CommonForms FFDNet-S (Small)",+ "description": "Small, fast detector with lower memory use - a good default for most forms. Finds text inputs, checkboxes, and signature fields.",+ "license": "No licence declared by the publisher (all rights reserved). Trained on the CommonForms dataset (Apache-2.0) with Ultralytics YOLO11, whose AGPL-3.0 terms the publisher asserts no grant over.",+ "sizeBytes": 38370092,+ "onnxUrl": "https://huggingface.co/jbarrow/FFDNet-S-cpu/resolve/d6cb18cb4bf31d7f5adfe8fbc7cc3744b516d1fe/FFDNet-S.onnx",+ "sha256": "93bccf47c048f9f947f9b1b52d002edf144a8a583dae39f164d9e5725321acc0",+ "inputSize": 1216,+ "resizeMode": "stretch",+ "padColor": [+ 114,+ 114,+ 114+ ],+ "channelOrder": "bgr",+ "normMean": [+ 0.0,+ 0.0,+ 0.0+ ],+ "normStd": [+ 1.0,+ 1.0,+ 1.0+ ],+ "outputLayout": "nc_first",+ "hasObjectness": false,+ "classNames": [+ "text",+ "choice",+ "signature"+ ],+ "classFieldTypes": [+ "text",+ "checkbox",+ "signature"+ ],+ "scoreThreshold": 0.3,+ "nms": "perClass",+ "iou": 0.45+ },+ {+ "id": "ffdnet-l",+ "displayName": "CommonForms FFDNet-L (Large)",+ "description": "Larger, higher-accuracy detector (~25M parameters) with better recall on dense or complex forms - uses more memory. Finds text inputs, checkboxes, and signature fields.",+ "license": "No licence declared by the publisher (all rights reserved). Trained on the CommonForms dataset (Apache-2.0) with Ultralytics YOLO11, whose AGPL-3.0 terms the publisher asserts no grant over.",+ "sizeBytes": 101944542,+ "onnxUrl": "https://huggingface.co/jbarrow/FFDNet-L-cpu/resolve/f411267bf3472e451946897f3b17f1a72e6f67aa/FFDNet-L.onnx",+ "sha256": "e00c59edd9a5275dab5847d38f042c8ecc827063650c8aac22b0e486c414cd35",+ "inputSize": 1216,+ "resizeMode": "stretch",+ "padColor": [+ 114,+ 114,+ 114+ ],+ "channelOrder": "bgr",+ "normMean": [+ 0.0,+ 0.0,+ 0.0+ ],+ "normStd": [+ 1.0,+ 1.0,+ 1.0+ ],+ "outputLayout": "nc_first",+ "hasObjectness": false,+ "classNames": [+ "text",+ "choice",+ "signature"+ ],+ "classFieldTypes": [+ "text",+ "checkbox",+ "signature"+ ],+ "scoreThreshold": 0.3,+ "nms": "perClass",+ "iou": 0.45+ }+]diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/formdetection/catalog/ModelCatalogServiceTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/formdetection/catalog/ModelCatalogServiceTest.javanew file mode 100644index 0000000000..b54a506784--- /dev/null+++ b/app/proprietary/src/test/java/stirling/software/proprietary/formdetection/catalog/ModelCatalogServiceTest.java@@ -0,0 +1,74 @@+package stirling.software.proprietary.formdetection.catalog;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertFalse;+import static org.junit.jupiter.api.Assertions.assertNotNull;+import static org.junit.jupiter.api.Assertions.assertTrue;++import java.util.List;++import org.junit.jupiter.api.Test;++import stirling.software.proprietary.formdetection.model.ModelCatalogEntry;++import tools.jackson.databind.json.JsonMapper;++class ModelCatalogServiceTest {++ @Test+ void loadsBundledCatalogWithSpecDefaults() {+ ModelCatalogService service = new ModelCatalogService(JsonMapper.builder().build());+ service.load();++ List<ModelCatalogEntry> all = service.getAll();+ assertTrue(all.size() >= 2, "catalog should ship with at least two entries");+ assertTrue(service.getById("ffdnet-s").isPresent());++ ModelCatalogEntry l = service.getById("ffdnet-l").orElseThrow();+ assertEquals(3, l.getClassNames().size());+ assertEquals(3, l.getClassFieldTypes().size());+ assertTrue(l.getInputSize() > 0);++ // Weights are fetched on demand, so a URL without a SHA-256 would download unverified.+ // Neither field set is fine: the admin panel renders that entry as not-installable.+ for (ModelCatalogEntry e : all) {+ assertNotNull(e.getOnnxUrl(), e.getId() + " must declare a URL field, even if blank");+ assertNotNull(e.getSha256(), e.getId() + " must declare a checksum");+ if (!e.getOnnxUrl().isBlank()) {+ assertFalse(+ e.getSha256().isBlank(),+ e.getId() + " declares a download URL so it must declare a SHA-256");+ }+ }+ assertTrue(+ all.stream().anyMatch(e -> !e.getOnnxUrl().isBlank()),+ "at least one entry must actually be installable");+ }++ @Test+ void ffdetrIsTheApacheLicensedEntryAndUsesTheQueryHeadDecoder() {+ ModelCatalogService service = new ModelCatalogService(JsonMapper.builder().build());+ service.load();++ ModelCatalogEntry ffdetr = service.getById("ffdetr").orElseThrow();+ assertEquals("rfdetr", ffdetr.getDecoder(), "FFDetr has a query head, not an anchor grid");+ assertEquals(1024, ffdetr.getInputSize());+ assertTrue(ffdetr.getLicense().startsWith("Apache-2.0"), ffdetr.getLicense());+ // RF-DETR expects ImageNet normalisation over RGB, unlike the FFDNet entries' /255 BGR.+ assertEquals("rgb", ffdetr.getChannelOrder());+ assertEquals(0.485f, ffdetr.getNormMean()[0], 1e-6);++ // The FFDNet entries keep the anchor-grid decoder; a wrong default here would silently+ // decode one family with the other's maths.+ assertEquals("yolo", service.getById("ffdnet-s").orElseThrow().getDecoder());+ assertEquals("yolo", service.getById("ffdnet-l").orElseThrow().getDecoder());+ }++ @Test+ void unknownIdReturnsEmpty() {+ ModelCatalogService service = new ModelCatalogService(JsonMapper.builder().build());+ service.load();+ assertTrue(service.getById("does-not-exist").isEmpty());+ assertTrue(service.getById(null).isEmpty());+ }+}diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/formdetection/controller/FormDetectionControllerTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/formdetection/controller/FormDetectionControllerTest.javanew file mode 100644index 0000000000..9a2922d4d8--- /dev/null+++ b/app/proprietary/src/test/java/stirling/software/proprietary/formdetection/controller/FormDetectionControllerTest.java@@ -0,0 +1,174 @@+package stirling.software.proprietary.formdetection.controller;++import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.multipart;+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;++import java.util.Optional;++import org.junit.jupiter.api.Test;+import org.mockito.Mockito;+import org.springframework.beans.factory.ObjectProvider;+import org.springframework.mock.web.MockMultipartFile;+import org.springframework.test.web.servlet.MockMvc;+import org.springframework.test.web.servlet.setup.MockMvcBuilders;++import stirling.software.common.service.CustomPDFDocumentFactory;+import stirling.software.common.util.TempFileManager;+import stirling.software.proprietary.formdetection.inference.OnnxFormDetector;+import stirling.software.proprietary.formdetection.model.ModelCatalogEntry;+import stirling.software.proprietary.formdetection.render.PageRasterizer;+import stirling.software.proprietary.formdetection.service.FormDetectionModelManager;+import stirling.software.proprietary.formdetection.service.FormDetectionService;++import tools.jackson.databind.ObjectMapper;++class FormDetectionControllerTest {++ private MockMvc mvc(+ FormDetectionModelManager manager,+ OnnxFormDetector detector,+ PageRasterizer rasterizer) {+ // A real service over mocked collaborators, so the HTTP translation is exercised against+ // the pipeline's actual exceptions rather than a stubbed stand-in.+ FormDetectionController controller =+ new FormDetectionController(+ provider(new FormDetectionService(manager, detector, rasterizer)),+ Mockito.mock(CustomPDFDocumentFactory.class),+ Mockito.mock(TempFileManager.class),+ new ObjectMapper());+ return MockMvcBuilders.standaloneSetup(controller).build();+ }++ @SuppressWarnings("unchecked")+ private static ObjectProvider<FormDetectionService> provider(FormDetectionService service) {+ ObjectProvider<FormDetectionService> p = Mockito.mock(ObjectProvider.class);+ Mockito.when(p.getIfAvailable()).thenReturn(service);+ return p;+ }++ private MockMultipartFile pdf() {+ return new MockMultipartFile("file", "test.pdf", "application/pdf", "%PDF-1.4".getBytes());+ }++ /** A rasterizer that renders nothing, so the detector is never reached. */+ private PageRasterizer noPages() {+ return Mockito.mock(PageRasterizer.class);+ }++ private FormDetectionModelManager readyManager() {+ FormDetectionModelManager manager = Mockito.mock(FormDetectionModelManager.class);+ Mockito.when(manager.isReady()).thenReturn(true);+ Mockito.when(manager.getActiveEntry()).thenReturn(Optional.of(new ModelCatalogEntry()));+ return manager;+ }++ @Test+ void detectReturns503WhenModelNotReady() throws Exception {+ FormDetectionModelManager manager = Mockito.mock(FormDetectionModelManager.class);+ Mockito.when(manager.isReady()).thenReturn(false);++ mvc(manager, Mockito.mock(OnnxFormDetector.class), Mockito.mock(PageRasterizer.class))+ .perform(multipart("/api/v1/form/form-detection/detect").file(pdf()))+ .andExpect(status().isServiceUnavailable())+ .andExpect(jsonPath("$.reason").value("DEPENDENCY"));+ }++ @Test+ void detectReturnsEmptyDetectionsForBlankRender() throws Exception {+ mvc(readyManager(), Mockito.mock(OnnxFormDetector.class), noPages())+ .perform(+ multipart("/api/v1/form/form-detection/detect")+ .file(pdf())+ .param("applyToPdf", "false"))+ .andExpect(status().isOk())+ .andExpect(jsonPath("$.detections").isArray())+ .andExpect(jsonPath("$.detections").isEmpty());+ }++ @Test+ void detectRejectsPdfsOverThePageLimit() throws Exception {+ PageRasterizer rasterizer = Mockito.mock(PageRasterizer.class);+ Mockito.doThrow(+ new PageRasterizer.PageLimitExceededException(+ FormDetectionService.MAX_PAGES + 1, FormDetectionService.MAX_PAGES))+ .when(rasterizer)+ .rasterize(Mockito.any(), Mockito.anyInt(), Mockito.anyInt(), Mockito.any());++ mvc(readyManager(), Mockito.mock(OnnxFormDetector.class), rasterizer)+ .perform(multipart("/api/v1/form/form-detection/detect").file(pdf()))+ .andExpect(status().isBadRequest())+ .andExpect(jsonPath("$.reason").value("LIMIT"));+ }++ @Test+ void detectPassesThePageLimitToTheRasterizerSoItIsCheckedBeforeRendering() throws Exception {+ PageRasterizer rasterizer = noPages();++ mvc(readyManager(), Mockito.mock(OnnxFormDetector.class), rasterizer)+ .perform(+ multipart("/api/v1/form/form-detection/detect")+ .file(pdf())+ .param("applyToPdf", "false"))+ .andExpect(status().isOk());++ Mockito.verify(rasterizer)+ .rasterize(+ Mockito.any(),+ Mockito.anyInt(),+ Mockito.eq(FormDetectionService.MAX_PAGES),+ Mockito.any());+ }++ @Test+ void detectRejectsAnUnreadablePdfAsBadRequestNotAsAMissingDependency() throws Exception {+ PageRasterizer rasterizer = Mockito.mock(PageRasterizer.class);+ Mockito.doThrow(new PageRasterizer.UnreadablePdfException("corrupt", null))+ .when(rasterizer)+ .rasterize(Mockito.any(), Mockito.anyInt(), Mockito.anyInt(), Mockito.any());++ mvc(readyManager(), Mockito.mock(OnnxFormDetector.class), rasterizer)+ .perform(multipart("/api/v1/form/form-detection/detect").file(pdf()))+ .andExpect(status().isBadRequest())+ .andExpect(jsonPath("$.reason").value("INVALID_PDF"));+ }++ @Test+ void detectRejectsAnEmptyUploadBeforeTouchingTheEngine() throws Exception {+ PageRasterizer rasterizer = Mockito.mock(PageRasterizer.class);+ MockMultipartFile empty =+ new MockMultipartFile("file", "empty.pdf", "application/pdf", new byte[0]);++ mvc(readyManager(), Mockito.mock(OnnxFormDetector.class), rasterizer)+ .perform(multipart("/api/v1/form/form-detection/detect").file(empty))+ .andExpect(status().isBadRequest())+ .andExpect(jsonPath("$.reason").value("INVALID_PDF"));++ Mockito.verifyNoInteractions(rasterizer);+ }++ @Test+ void detectStillReports503WhenTheEngineItselfIsUnavailable() throws Exception {+ PageRasterizer rasterizer = Mockito.mock(PageRasterizer.class);+ Mockito.doThrow(new IllegalStateException("ONNX Runtime is unavailable"))+ .when(rasterizer)+ .rasterize(Mockito.any(), Mockito.anyInt(), Mockito.anyInt(), Mockito.any());++ mvc(readyManager(), Mockito.mock(OnnxFormDetector.class), rasterizer)+ .perform(multipart("/api/v1/form/form-detection/detect").file(pdf()))+ .andExpect(status().isServiceUnavailable())+ .andExpect(jsonPath("$.reason").value("DEPENDENCY"));+ }++ @Test+ void detectToleratesOutOfRangeConfThreshold() throws Exception {+ mvc(readyManager(), Mockito.mock(OnnxFormDetector.class), noPages())+ .perform(+ multipart("/api/v1/form/form-detection/detect")+ .file(pdf())+ .param("confThreshold", "-42")+ .param("applyToPdf", "false"))+ .andExpect(status().isOk())+ .andExpect(jsonPath("$.detections").isEmpty());+ }+}diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/formdetection/controller/FormDetectionModelControllerTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/formdetection/controller/FormDetectionModelControllerTest.javanew file mode 100644index 0000000000..02c0dd4a2e--- /dev/null+++ b/app/proprietary/src/test/java/stirling/software/proprietary/formdetection/controller/FormDetectionModelControllerTest.java@@ -0,0 +1,112 @@+package stirling.software.proprietary.formdetection.controller;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertNotNull;+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;++import java.lang.reflect.Method;+import java.lang.reflect.Modifier;+import java.util.List;++import org.junit.jupiter.api.Test;+import org.mockito.Mockito;+import org.springframework.http.MediaType;+import org.springframework.security.access.prepost.PreAuthorize;+import org.springframework.test.web.servlet.MockMvc;+import org.springframework.test.web.servlet.setup.MockMvcBuilders;++import stirling.software.proprietary.formdetection.model.ModelStatusResponse;+import stirling.software.proprietary.formdetection.service.FormDetectionModelManager;++class FormDetectionModelControllerTest {++ private ModelStatusResponse notInstalled() {+ return new ModelStatusResponse(+ "not_installed", 0, "", List.of(), null, true, List.of(), true, true, null);+ }++ private MockMvc mvc(FormDetectionModelManager manager) {+ return MockMvcBuilders.standaloneSetup(new FormDetectionModelController(manager)).build();+ }++ @Test+ void statusReturnsJson() throws Exception {+ FormDetectionModelManager manager = Mockito.mock(FormDetectionModelManager.class);+ Mockito.when(manager.status()).thenReturn(notInstalled());++ mvc(manager)+ .perform(get("/api/v1/form/form-detection-model/status"))+ .andExpect(status().isOk())+ .andExpect(jsonPath("$.status").value("not_installed"))+ .andExpect(jsonPath("$.writable").value(true));+ }++ @Test+ void installWithBlankModelIdReturns400() throws Exception {+ FormDetectionModelManager manager = Mockito.mock(FormDetectionModelManager.class);+ Mockito.when(manager.status()).thenReturn(notInstalled());++ mvc(manager)+ .perform(+ post("/api/v1/form/form-detection-model/install")+ .contentType(MediaType.APPLICATION_JSON)+ .content("{\"modelId\":\"\"}"))+ .andExpect(status().isBadRequest());+ }++ @Test+ void installValidReturns202() throws Exception {+ FormDetectionModelManager manager = Mockito.mock(FormDetectionModelManager.class);+ Mockito.when(manager.status()).thenReturn(notInstalled());++ mvc(manager)+ .perform(+ post("/api/v1/form/form-detection-model/install")+ .contentType(MediaType.APPLICATION_JSON)+ .content("{\"modelId\":\"ffdnet-s\"}"))+ .andExpect(status().isAccepted());+ }++ @Test+ void installWhileBusyReturns409() throws Exception {+ FormDetectionModelManager manager = Mockito.mock(FormDetectionModelManager.class);+ Mockito.when(manager.status()).thenReturn(notInstalled());+ Mockito.doThrow(new IllegalStateException("An install is already in progress"))+ .when(manager)+ .startInstall(Mockito.eq("ffdnet-s"));++ mvc(manager)+ .perform(+ post("/api/v1/form/form-detection-model/install")+ .contentType(MediaType.APPLICATION_JSON)+ .content("{\"modelId\":\"ffdnet-s\"}"))+ .andExpect(status().isConflict());+ }++ @Test+ void deleteReturnsStatus() throws Exception {+ FormDetectionModelManager manager = Mockito.mock(FormDetectionModelManager.class);+ Mockito.when(manager.status()).thenReturn(notInstalled());++ mvc(manager)+ .perform(delete("/api/v1/form/form-detection-model"))+ .andExpect(status().isOk())+ .andExpect(jsonPath("$.status").value("not_installed"));+ }++ @Test+ void everyModelLifecycleEndpointIsAdminOnly() {+ for (Method m : FormDetectionModelController.class.getDeclaredMethods()) {+ if (!Modifier.isPublic(m.getModifiers()) || m.isSynthetic()) {+ continue;+ }+ PreAuthorize preAuthorize = m.getAnnotation(PreAuthorize.class);+ assertNotNull(preAuthorize, m.getName() + "() must be admin-gated");+ assertEquals("hasRole('ADMIN')", preAuthorize.value(), m.getName() + "()");+ }+ }+}diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/formdetection/inference/RfDetrTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/formdetection/inference/RfDetrTest.javanew file mode 100644index 0000000000..5fac07fd0a--- /dev/null+++ b/app/proprietary/src/test/java/stirling/software/proprietary/formdetection/inference/RfDetrTest.java@@ -0,0 +1,182 @@+package stirling.software.proprietary.formdetection.inference;++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.io.InputStream;+import java.util.ArrayList;+import java.util.LinkedHashMap;+import java.util.List;+import java.util.Map;++import org.junit.jupiter.api.Test;++import com.fasterxml.jackson.databind.JsonNode;+import com.fasterxml.jackson.databind.ObjectMapper;++import stirling.software.proprietary.formdetection.model.ModelCatalogEntry;++/**+ * Parity tests for the RF-DETR decode path. The fixture holds real tensors from the exported ONNX+ * plus the reference Python decode output, so a missing sigmoid breaks it.+ */+class RfDetrTest {++ private static final String FIXTURE = "/formdetection/rfdetr-reference.json";++ private record Fixture(+ Map<String, Yolo.RawOutput> outputs,+ List<JsonNode> expected,+ int inputSize,+ float thr) {}++ private static Fixture load() throws Exception {+ ObjectMapper mapper = new ObjectMapper();+ JsonNode root;+ try (InputStream in = RfDetrTest.class.getResourceAsStream(FIXTURE)) {+ assertNotNull(in, "missing fixture " + FIXTURE);+ root = mapper.readTree(in);+ }+ JsonNode queries = root.get("queries");+ int n = queries.size();+ int boxCols = queries.get(0).get("dets").size();+ int logitCols = queries.get(0).get("labels").size();+ float[] boxes = new float[n * boxCols];+ float[] logits = new float[n * logitCols];+ for (int i = 0; i < n; i++) {+ for (int c = 0; c < boxCols; c++) {+ boxes[i * boxCols + c] = (float) queries.get(i).get("dets").get(c).asDouble();+ }+ for (int c = 0; c < logitCols; c++) {+ logits[i * logitCols + c] = (float) queries.get(i).get("labels").get(c).asDouble();+ }+ }+ Map<String, Yolo.RawOutput> outputs = new LinkedHashMap<>();+ outputs.put("dets", new Yolo.RawOutput(boxes, n, boxCols));+ outputs.put("labels", new Yolo.RawOutput(logits, n, logitCols));++ List<JsonNode> expected = new ArrayList<>();+ // Re-index expectations onto the trimmed query list the fixture actually carries.+ for (JsonNode e : root.get("expected")) {+ expected.add(e);+ }+ return new Fixture(+ outputs,+ expected,+ root.get("inputSize").asInt(),+ (float) root.get("scoreThreshold").asDouble());+ }++ /**+ * Identity mapping: model input space == source bitmap, so decode output is directly+ * comparable.+ */+ private static Yolo.Preprocessed identityPre(int inputSize) {+ return new Yolo.Preprocessed(new float[0], inputSize, 1f, 1f, 0, 0, inputSize, inputSize);+ }++ private static ModelCatalogEntry spec() {+ ModelCatalogEntry spec = new ModelCatalogEntry();+ spec.setDecoder("rfdetr");+ spec.setInputSize(1024);+ spec.setClassNames(List.of("text", "choice", "signature"));+ spec.setNms("none");+ return spec;+ }++ @Test+ void decodesTheExportedModelsRealOutputToTheReferenceDetections() throws Exception {+ Fixture f = load();++ List<Yolo.Detection> got =+ RfDetr.decode(f.outputs(), spec(), identityPre(f.inputSize()), f.thr());++ assertEquals(+ f.expected().size(),+ got.size(),+ "detection count must match the Python reference decode");+ // Compare as sets keyed on rounded geometry: NMS is off, so order is query order in both.+ for (int i = 0; i < got.size(); i++) {+ JsonNode want = f.expected().get(i);+ Yolo.Detection d = got.get(i);+ assertEquals(want.get("cls").asInt(), d.classId(), "class at index " + i);+ assertEquals(want.get("score").asDouble(), d.score(), 1e-4, "score at index " + i);+ assertEquals(want.get("x").asDouble(), d.x(), 0.05, "x at index " + i);+ assertEquals(want.get("y").asDouble(), d.y(), 0.05, "y at index " + i);+ assertEquals(want.get("w").asDouble(), d.w(), 0.05, "w at index " + i);+ assertEquals(want.get("h").asDouble(), d.h(), 0.05, "h at index " + i);+ }+ }++ @Test+ void findsTheFormsEightTextTwoChoiceAndOneSignature() throws Exception {+ Fixture f = load();+ List<Yolo.Detection> got =+ RfDetr.decode(f.outputs(), spec(), identityPre(f.inputSize()), f.thr());+ long text = got.stream().filter(d -> d.classId() == 0).count();+ long choice = got.stream().filter(d -> d.classId() == 1).count();+ long signature = got.stream().filter(d -> d.classId() == 2).count();+ assertEquals(8, text, "text fields");+ assertEquals(2, choice, "checkboxes");+ assertEquals(1, signature, "signature line");+ }++ @Test+ void bindsOutputsByNameNotPosition() throws Exception {+ Fixture f = load();+ // Both tensors are [n, 4] here, so a positional reader cannot tell them apart. Swapping+ // insertion order must change nothing.+ Map<String, Yolo.RawOutput> swapped = new LinkedHashMap<>();+ swapped.put("labels", f.outputs().get("labels"));+ swapped.put("dets", f.outputs().get("dets"));++ List<Yolo.Detection> normal =+ RfDetr.decode(f.outputs(), spec(), identityPre(f.inputSize()), f.thr());+ List<Yolo.Detection> reordered =+ RfDetr.decode(swapped, spec(), identityPre(f.inputSize()), f.thr());++ assertEquals(normal.toString(), reordered.toString());+ }++ @Test+ void fixtureCarriesTheAmbiguousFourColumnShape() throws Exception {+ Fixture f = load();+ assertEquals(+ 4,+ f.outputs().get("labels").d2(),+ "3 classes + 1 no-object slot - the case where labels and dets share a shape");+ assertEquals(4, f.outputs().get("dets").d2());+ for (Yolo.Detection d :+ RfDetr.decode(f.outputs(), spec(), identityPre(f.inputSize()), f.thr())) {+ assertTrue(d.classId() >= 0 && d.classId() < 3, "classId out of range: " + d.classId());+ }+ }++ /**+ * Hand-built: the exported model never lets the no-object column win, so real tensors cannot+ * exercise this guard. Without it a dominant 4th column indexes past classNames.+ */+ @Test+ void neverClassifiesAQueryAsTheNoObjectColumn() {+ // One query: no-object logit is overwhelmingly the largest, real classes are weak.+ float[] logits = {-4.0f, -3.0f, -5.0f, 9.0f};+ float[] boxes = {0.5f, 0.5f, 0.2f, 0.1f};+ Map<String, Yolo.RawOutput> outputs = new LinkedHashMap<>();+ outputs.put("dets", new Yolo.RawOutput(boxes, 1, 4));+ outputs.put("labels", new Yolo.RawOutput(logits, 1, 4));++ List<Yolo.Detection> got = RfDetr.decode(outputs, spec(), identityPre(1024), 0.30f);++ assertTrue(+ got.isEmpty(),+ "a query dominated by the no-object slot must be dropped, got: " + got);+ }++ @Test+ void returnsNothingWhenAnExpectedOutputIsAbsent() throws Exception {+ Fixture f = load();+ Map<String, Yolo.RawOutput> onlyBoxes = Map.of("dets", f.outputs().get("dets"));+ assertTrue(RfDetr.decode(onlyBoxes, spec(), identityPre(f.inputSize()), f.thr()).isEmpty());+ }+}diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/formdetection/inference/YoloTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/formdetection/inference/YoloTest.javanew file mode 100644index 0000000000..c53d1a4949--- /dev/null+++ b/app/proprietary/src/test/java/stirling/software/proprietary/formdetection/inference/YoloTest.java@@ -0,0 +1,153 @@+package stirling.software.proprietary.formdetection.inference;++import static org.assertj.core.api.Assertions.assertThat;+import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertTrue;++import java.util.ArrayList;+import java.util.List;++import org.junit.jupiter.api.Test;+import org.slf4j.LoggerFactory;++import stirling.software.proprietary.formdetection.model.ModelCatalogEntry;++import ch.qos.logback.classic.Level;+import ch.qos.logback.classic.Logger;+import ch.qos.logback.classic.spi.ILoggingEvent;+import ch.qos.logback.core.read.ListAppender;++class YoloTest {++ private ModelCatalogEntry spec() {+ ModelCatalogEntry e = new ModelCatalogEntry();+ e.setInputSize(10);+ e.setResizeMode("letterbox");+ e.setChannelOrder("rgb");+ e.setOutputLayout("nc_first");+ e.setHasObjectness(false);+ e.setClassNames(List.of("text", "choice"));+ e.setClassFieldTypes(List.of("text", "checkbox"));+ e.setNms("perClass");+ e.setIou(0.5f);+ return e;+ }++ @Test+ void decodeThresholdsAndSuppressesOverlaps() {+ ModelCatalogEntry spec = spec();+ // identity transform (scale 1, no pad), 10x10 source+ Yolo.Preprocessed pre = new Yolo.Preprocessed(new float[0], 10, 1f, 1f, 0, 0, 10, 10);++ // nc_first layout [channels=6][anchors=3], data[c*anchors + a]+ // box A (cx5,cy5,w4,h4) twice (overlapping) + box B (cx8,cy8,w2,h2)+ float[] data = {+ 5,+ 5,+ 8, // cx+ 5,+ 5,+ 8, // cy+ 4,+ 4,+ 2, // w+ 4,+ 4,+ 2, // h+ 0.9f,+ 0.8f,+ 0.7f, // text score+ 0.1f,+ 0.1f,+ 0.1f // choice score+ };+ Yolo.RawOutput out = new Yolo.RawOutput(data, 6, 3);++ List<Yolo.Detection> dets = Yolo.decode(out, spec, pre, 0.5f);++ // a0 (box A, 0.9) kept; a1 (box A', 0.8) suppressed by NMS; a2 (box B, 0.7) kept+ assertEquals(2, dets.size());++ Yolo.Detection a = dets.get(0);+ assertEquals(0, a.classId());+ assertEquals(0.9f, a.score(), 1e-5);+ assertEquals(3f, a.x(), 1e-4);+ assertEquals(3f, a.y(), 1e-4);+ assertEquals(4f, a.w(), 1e-4);+ assertEquals(4f, a.h(), 1e-4);++ Yolo.Detection b = dets.get(1);+ assertEquals(0.7f, b.score(), 1e-5);+ assertEquals(7f, b.x(), 1e-4);+ assertEquals(7f, b.y(), 1e-4);+ assertEquals(2f, b.w(), 1e-4);+ assertEquals(2f, b.h(), 1e-4);+ }++ @Test+ void decodeIsDeterministic() {+ ModelCatalogEntry spec = spec();+ Yolo.Preprocessed pre = new Yolo.Preprocessed(new float[0], 10, 1f, 1f, 0, 0, 10, 10);+ float[] data = {5, 5, 8, 5, 5, 8, 4, 4, 2, 4, 4, 2, 0.9f, 0.8f, 0.7f, 0.1f, 0.1f, 0.1f};+ Yolo.RawOutput out = new Yolo.RawOutput(data, 6, 3);+ assertEquals(+ Yolo.decode(out, spec, pre, 0.5f).toString(),+ Yolo.decode(out, spec, pre, 0.5f).toString());+ }++ @Test+ void thresholdDropsLowScores() {+ ModelCatalogEntry spec = spec();+ Yolo.Preprocessed pre = new Yolo.Preprocessed(new float[0], 10, 1f, 1f, 0, 0, 10, 10);+ float[] data = {5, 5, 8, 5, 5, 8, 4, 4, 2, 4, 4, 2, 0.9f, 0.8f, 0.7f, 0.1f, 0.1f, 0.1f};+ Yolo.RawOutput out = new Yolo.RawOutput(data, 6, 3);+ // threshold above every score -> nothing survives+ assertEquals(0, Yolo.decode(out, spec, pre, 0.95f).size());+ }++ @Test+ void nmsBoundsHowManyBoxesItWillCompare() {+ // Non-overlapping, so suppression itself removes nothing and only the cap can.+ int count = Yolo.MAX_NMS_CANDIDATES + 500;+ List<Yolo.Detection> dets = new ArrayList<>();+ for (int i = 0; i < count; i++) {+ dets.add(new Yolo.Detection(0, (i + 1) / (float) count, i * 4f, 0f, 2f, 2f));+ }++ List<Yolo.Detection> kept = Yolo.nms(dets, "perClass", 0.5f);++ assertEquals(Yolo.MAX_NMS_CANDIDATES, kept.size());+ float worstKept = 1f;+ for (Yolo.Detection d : kept) {+ worstKept = Math.min(worstKept, d.score());+ }+ assertTrue(worstKept > 500 / (float) count, "the cap must drop the lowest-scoring boxes");+ }++ @Test+ void nmsCapDoesNotLogPerPage() {+ Logger yoloLogger = (Logger) LoggerFactory.getLogger(Yolo.class);+ Level original = yoloLogger.getLevel();+ ListAppender<ILoggingEvent> appender = new ListAppender<>();+ appender.start();+ yoloLogger.setLevel(Level.TRACE);+ yoloLogger.addAppender(appender);+ try {+ List<Yolo.Detection> dets = new ArrayList<>();+ for (int i = 0; i < Yolo.MAX_NMS_CANDIDATES + 1; i++) {+ dets.add(new Yolo.Detection(0, 0.5f, i * 4f, 0f, 2f, 2f));+ }++ for (int page = 0; page < 20; page++) {+ Yolo.nms(dets, "perClass", 0.5f);+ }++ assertThat(appender.list)+ .as("a per-page cap must not shout once per page")+ .noneMatch(e -> e.getLevel().isGreaterOrEqual(Level.INFO));+ } finally {+ yoloLogger.detachAppender(appender);+ yoloLogger.setLevel(original);+ }+ }+}diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/formdetection/render/CoordinateMapperTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/formdetection/render/CoordinateMapperTest.javanew file mode 100644index 0000000000..9e6495339d--- /dev/null+++ b/app/proprietary/src/test/java/stirling/software/proprietary/formdetection/render/CoordinateMapperTest.java@@ -0,0 +1,126 @@+package stirling.software.proprietary.formdetection.render;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertTrue;++import org.junit.jupiter.api.Test;++import stirling.software.proprietary.formdetection.inference.Yolo;+import stirling.software.proprietary.formdetection.model.DetectedField;++class CoordinateMapperTest {++ private static PageRasterizer.RasterPage page(+ int widthPx,+ int heightPx,+ float displayW,+ float displayH,+ float scale,+ int rotation,+ float userW,+ float userH,+ float llx,+ float lly) {+ return new PageRasterizer.RasterPage(+ 0,+ new byte[0],+ widthPx,+ heightPx,+ displayW,+ displayH,+ scale,+ scale,+ rotation,+ userW,+ userH,+ llx,+ lly);+ }++ @Test+ void mapsBitmapPixelsToPdfPointsWithYFlip() {+ // 200x300pt page rendered at 2 px/pt (400x600 px)+ PageRasterizer.RasterPage p = page(400, 600, 200f, 300f, 2f, 0, 200f, 300f, 0f, 0f);+ // detection at top-left (10,20) px, 40x60 px+ Yolo.Detection d = new Yolo.Detection(0, 0.9f, 10f, 20f, 40f, 60f);++ DetectedField.RectPt r = CoordinateMapper.toPdfPoints(d, p);++ assertEquals(5.0, r.x(), 1e-4); // 10/2+ assertEquals(20.0, r.w(), 1e-4); // 40/2+ assertEquals(30.0, r.h(), 1e-4); // 60/2+ // Y flip: pageHeight - (yTopPx/scale) - hPt = 300 - 10 - 30+ assertEquals(260.0, r.y(), 1e-4);+ }++ @Test+ void clampsToPageBounds() {+ PageRasterizer.RasterPage p = page(200, 200, 100f, 100f, 2f, 0, 100f, 100f, 0f, 0f);+ // box partly off the right/bottom edge in px+ Yolo.Detection d = new Yolo.Detection(0, 0.5f, 180f, 0f, 60f, 40f);++ DetectedField.RectPt r = CoordinateMapper.toPdfPoints(d, p);++ // x = 90pt, width clamped to 100-90 = 10pt+ assertEquals(90.0, r.x(), 1e-4);+ assertEquals(10.0, r.w(), 1e-4);+ assertTrue(r.x() + r.w() <= 100.0 + 1e-6);+ assertTrue(r.y() >= -1e-6);+ }++ @Test+ void appliesCropBoxOrigin() {+ PageRasterizer.RasterPage p = page(400, 600, 200f, 300f, 2f, 0, 200f, 300f, 30f, 50f);+ Yolo.Detection d = new Yolo.Detection(0, 0.9f, 10f, 20f, 40f, 60f);++ DetectedField.RectPt r = CoordinateMapper.toPdfPoints(d, p);++ assertEquals(35.0, r.x(), 1e-4); // 5 + llx 30+ assertEquals(310.0, r.y(), 1e-4); // 260 + lly 50+ assertEquals(20.0, r.w(), 1e-4);+ assertEquals(30.0, r.h(), 1e-4);+ }++ @Test+ void invertsRotation90() {+ // Unrotated page 200x100; /Rotate 90 renders a 100x200pt display at 2 px/pt.+ PageRasterizer.RasterPage p = page(200, 400, 100f, 200f, 2f, 90, 200f, 100f, 0f, 0f);+ // User rect (10,20,30,40) lands at display rect (20,160,40,30) = bitmap (40,20,80,60).+ Yolo.Detection d = new Yolo.Detection(0, 0.9f, 40f, 20f, 80f, 60f);++ DetectedField.RectPt r = CoordinateMapper.toPdfPoints(d, p);++ assertEquals(10.0, r.x(), 1e-4);+ assertEquals(20.0, r.y(), 1e-4);+ assertEquals(30.0, r.w(), 1e-4);+ assertEquals(40.0, r.h(), 1e-4);+ }++ @Test+ void invertsRotation180() {+ PageRasterizer.RasterPage p = page(200, 300, 200f, 300f, 1f, 180, 200f, 300f, 0f, 0f);+ // User rect (10,20,30,40) lands at display rect (160,240,30,40) = bitmap (160,20,30,40).+ Yolo.Detection d = new Yolo.Detection(0, 0.9f, 160f, 20f, 30f, 40f);++ DetectedField.RectPt r = CoordinateMapper.toPdfPoints(d, p);++ assertEquals(10.0, r.x(), 1e-4);+ assertEquals(20.0, r.y(), 1e-4);+ assertEquals(30.0, r.w(), 1e-4);+ assertEquals(40.0, r.h(), 1e-4);+ }++ @Test+ void invertsRotation270() {+ PageRasterizer.RasterPage p = page(200, 400, 100f, 200f, 2f, 270, 200f, 100f, 0f, 0f);+ // User rect (10,20,30,40) lands at display rect (40,10,40,30) = bitmap (80,320,80,60).+ Yolo.Detection d = new Yolo.Detection(0, 0.9f, 80f, 320f, 80f, 60f);++ DetectedField.RectPt r = CoordinateMapper.toPdfPoints(d, p);++ assertEquals(10.0, r.x(), 1e-4);+ assertEquals(20.0, r.y(), 1e-4);+ assertEquals(30.0, r.w(), 1e-4);+ assertEquals(40.0, r.h(), 1e-4);+ }+}diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/formdetection/render/PageRasterizerRotationTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/formdetection/render/PageRasterizerRotationTest.javanew file mode 100644index 0000000000..39a4818a57--- /dev/null+++ b/app/proprietary/src/test/java/stirling/software/proprietary/formdetection/render/PageRasterizerRotationTest.java@@ -0,0 +1,206 @@+package stirling.software.proprietary.formdetection.render;++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 static org.junit.jupiter.api.Assumptions.assumeTrue;+import static org.mockito.Mockito.mock;++import java.io.ByteArrayOutputStream;+import java.util.ArrayList;+import java.util.List;+import java.util.concurrent.atomic.AtomicInteger;++import org.apache.pdfbox.Loader;+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.Test;+import org.junit.jupiter.params.ParameterizedTest;+import org.junit.jupiter.params.provider.ValueSource;++import stirling.software.common.service.CustomPDFDocumentFactory;+import stirling.software.common.service.PdfMetadataService;+import stirling.software.proprietary.formdetection.inference.Yolo;+import stirling.software.proprietary.formdetection.model.DetectedField;++/**+ * End-to-end geometry check: render a black rectangle on rotated, crop-shifted pages through real+ * PDFium, find it in the bitmap, and assert the mapper recovers its user-space rect.+ */+class PageRasterizerRotationTest {++ private static final float RECT_X = 60f;+ private static final float RECT_Y = 90f;+ private static final float RECT_W = 72f;+ private static final float RECT_H = 36f;++ private PageRasterizer rasterizer() {+ CustomPDFDocumentFactory factory =+ new CustomPDFDocumentFactory(mock(PdfMetadataService.class));+ return new PageRasterizer(factory);+ }++ /** Gather the streamed pages; these fixtures are one page, so holding them all is fine. */+ private List<PageRasterizer.RasterPage> collect(byte[] pdf) {+ List<PageRasterizer.RasterPage> pages = new ArrayList<>();+ rasterizer().rasterize(pdf, 1216, 100, pages::add);+ return pages;+ }++ private static byte[] pdfWithBlackRect(int rotation, float llx, float lly) throws Exception {+ try (PDDocument doc = new PDDocument()) {+ PDPage page = new PDPage(new PDRectangle(llx, lly, 200f, 300f));+ page.setRotation(rotation);+ doc.addPage(page);+ try (PDPageContentStream cs = new PDPageContentStream(doc, page)) {+ cs.setNonStrokingColor(0f, 0f, 0f);+ cs.addRect(llx + RECT_X, lly + RECT_Y, RECT_W, RECT_H);+ cs.fill();+ }+ ByteArrayOutputStream out = new ByteArrayOutputStream();+ doc.save(out);+ return out.toByteArray();+ }+ }++ private static boolean pdfiumAvailable() {+ try {+ Class.forName("stirling.software.jpdfium.PdfDocument");+ stirling.software.jpdfium.PdfDocument.open(minimalPdf()).close();+ return true;+ } catch (Throwable t) {+ return false;+ }+ }++ private static byte[] minimalPdf() {+ try (PDDocument doc = new PDDocument()) {+ doc.addPage(new PDPage(PDRectangle.A6));+ ByteArrayOutputStream out = new ByteArrayOutputStream();+ doc.save(out);+ return out.toByteArray();+ } catch (Exception e) {+ throw new IllegalStateException(e);+ }+ }++ /** Bounding box of dark pixels in an RGBA bitmap, as a top-left-origin px detection. */+ private static Yolo.Detection darkBoundingBox(byte[] rgba, int w, int h) {+ int minX = Integer.MAX_VALUE;+ int minY = Integer.MAX_VALUE;+ int maxX = -1;+ int maxY = -1;+ for (int y = 0; y < h; y++) {+ for (int x = 0; x < w; x++) {+ int i = (y * w + x) * 4;+ int r = rgba[i] & 0xFF;+ int g = rgba[i + 1] & 0xFF;+ int b = rgba[i + 2] & 0xFF;+ if (r < 60 && g < 60 && b < 60) {+ minX = Math.min(minX, x);+ minY = Math.min(minY, y);+ maxX = Math.max(maxX, x);+ maxY = Math.max(maxY, y);+ }+ }+ }+ assertTrue(maxX >= 0, "expected a dark rectangle in the rendered bitmap");+ return new Yolo.Detection(0, 1f, minX, minY, maxX - minX + 1f, maxY - minY + 1f);+ }++ @ParameterizedTest+ @ValueSource(ints = {0, 90, 180, 270})+ void recoversUserSpaceRectOnRotatedPages(int rotation) throws Exception {+ assumeTrue(pdfiumAvailable(), "JPDFium native not available on this platform");++ byte[] pdf = pdfWithBlackRect(rotation, 0f, 0f);+ List<PageRasterizer.RasterPage> pages = collect(pdf);+ assertEquals(1, pages.size());+ PageRasterizer.RasterPage page = pages.get(0);+ assertEquals(rotation, page.rotationDegrees());++ Yolo.Detection d = darkBoundingBox(page.rgba(), page.widthPx(), page.heightPx());+ DetectedField.RectPt r = CoordinateMapper.toPdfPoints(d, page);++ // Rendering + pixel-bbox rounding costs a couple of points of precision.+ assertEquals(RECT_X, r.x(), 2.0);+ assertEquals(RECT_Y, r.y(), 2.0);+ assertEquals(RECT_W, r.w(), 3.0);+ assertEquals(RECT_H, r.h(), 3.0);+ }++ @Test+ void recoversUserSpaceRectWithShiftedCropBoxOrigin() throws Exception {+ assumeTrue(pdfiumAvailable(), "JPDFium native not available on this platform");++ float llx = 25f;+ float lly = 40f;+ byte[] pdf = pdfWithBlackRect(0, llx, lly);+ // Sanity: the crop box PDFBox reports really is shifted.+ try (PDDocument check = Loader.loadPDF(pdf)) {+ assertEquals(llx, check.getPage(0).getCropBox().getLowerLeftX(), 1e-3);+ }++ List<PageRasterizer.RasterPage> pages = collect(pdf);+ PageRasterizer.RasterPage page = pages.get(0);+ assertEquals(llx, page.cropLlxPt(), 1e-3);+ assertEquals(lly, page.cropLlyPt(), 1e-3);++ Yolo.Detection d = darkBoundingBox(page.rgba(), page.widthPx(), page.heightPx());+ DetectedField.RectPt r = CoordinateMapper.toPdfPoints(d, page);++ // The recovered rect is absolute user space: crop-box origin included.+ assertEquals(llx + RECT_X, r.x(), 2.0);+ assertEquals(lly + RECT_Y, r.y(), 2.0);+ assertEquals(RECT_W, r.w(), 3.0);+ assertEquals(RECT_H, r.h(), 3.0);+ }++ @Test+ void rejectsAnOverLongDocumentWithoutRenderingAnyPage() throws Exception {+ assumeTrue(pdfiumAvailable(), "JPDFium native not available on this platform");++ byte[] pdf = pdfWithPages(3);+ AtomicInteger rendered = new AtomicInteger();++ assertThrows(+ PageRasterizer.PageLimitExceededException.class,+ () -> rasterizer().rasterize(pdf, 1216, 2, page -> rendered.incrementAndGet()));+ // The whole point of the limit: refuse before paying for any bitmap.+ assertEquals(0, rendered.get());+ }++ @Test+ void rejectsEmptyAndCorruptInputAsUnreadableRatherThanFailingLater() {+ assertThrows(+ PageRasterizer.UnreadablePdfException.class,+ () -> rasterizer().rasterize(new byte[0], 1216, 10, page -> {}));+ assertThrows(+ PageRasterizer.UnreadablePdfException.class,+ () -> rasterizer().rasterize("not a pdf".getBytes(), 1216, 10, page -> {}));+ }++ @Test+ void streamsPagesOneAtATime() throws Exception {+ assumeTrue(pdfiumAvailable(), "JPDFium native not available on this platform");++ byte[] pdf = pdfWithPages(3);+ List<Integer> seen = new ArrayList<>();+ rasterizer().rasterize(pdf, 1216, 10, page -> seen.add(page.pageIndex()));++ assertEquals(List.of(0, 1, 2), seen);+ }++ private static byte[] pdfWithPages(int count) throws Exception {+ try (PDDocument doc = new PDDocument()) {+ for (int i = 0; i < count; i++) {+ doc.addPage(new PDPage(PDRectangle.A6));+ }+ ByteArrayOutputStream out = new ByteArrayOutputStream();+ doc.save(out);+ return out.toByteArray();+ }+ }+}diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/formdetection/service/FormDetectionModelManagerTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/formdetection/service/FormDetectionModelManagerTest.javanew file mode 100644index 0000000000..b4995072b6--- /dev/null+++ b/app/proprietary/src/test/java/stirling/software/proprietary/formdetection/service/FormDetectionModelManagerTest.java@@ -0,0 +1,426 @@+package stirling.software.proprietary.formdetection.service;++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.assertThrows;+import static org.junit.jupiter.api.Assertions.assertTrue;+import static org.junit.jupiter.api.Assertions.fail;++import java.io.IOException;+import java.io.OutputStream;+import java.net.HttpURLConnection;+import java.net.InetSocketAddress;+import java.net.URI;+import java.nio.file.Files;+import java.nio.file.Path;+import java.security.MessageDigest;+import java.util.HexFormat;+import java.util.List;+import java.util.Optional;+import java.util.concurrent.CountDownLatch;+import java.util.concurrent.TimeUnit;++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.mockito.Mockito;+import org.springframework.beans.factory.ObjectProvider;++import com.sun.net.httpserver.HttpServer;++import stirling.software.SPDF.config.EndpointConfiguration;+import stirling.software.SPDF.config.EndpointConfiguration.DisableReason;+import stirling.software.common.configuration.RuntimePathConfig;+import stirling.software.common.model.ApplicationProperties;+import stirling.software.proprietary.formdetection.catalog.ModelCatalogService;+import stirling.software.proprietary.formdetection.inference.UnloadableModel;+import stirling.software.proprietary.formdetection.model.ModelCatalogEntry;++class FormDetectionModelManagerTest {++ /** Catalog URLs must satisfy the production allowlist; the stub below serves them locally. */+ private static final String ALLOWED_URL = "https://huggingface.co";++ private HttpServer server;+ private byte[] modelBytes;+ private String modelSha;+ private int port;++ /** Stands in for a build with no ONNX engine bean, which is the default packaging. */+ @SuppressWarnings("unchecked")+ private static ObjectProvider<UnloadableModel> noEngine() {+ return Mockito.mock(ObjectProvider.class);+ }++ @BeforeEach+ void startServer() throws Exception {+ modelBytes = "fake-onnx-model-content-1234567890".getBytes();+ modelSha =+ HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(modelBytes));+ server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);+ port = server.getAddress().getPort();+ server.createContext(+ "/model.onnx",+ ex -> {+ ex.sendResponseHeaders(200, modelBytes.length);+ ex.getResponseBody().write(modelBytes);+ ex.close();+ });+ server.start();+ }++ @AfterEach+ void stopServer() {+ if (server != null) {+ server.stop(0);+ }+ }++ private ModelCatalogEntry entry(String url, String sha) {+ ModelCatalogEntry e = new ModelCatalogEntry();+ e.setId("test-model");+ e.setOnnxUrl(url);+ e.setSha256(sha);+ e.setSizeBytes(modelBytes.length);+ return e;+ }++ private FormDetectionModelManager manager(+ Path dir, ModelCatalogEntry entry, EndpointConfiguration ep) {+ return manager(dir, entry, ep, new ApplicationProperties());+ }++ private FormDetectionModelManager manager(+ Path dir,+ ModelCatalogEntry entry,+ EndpointConfiguration ep,+ ApplicationProperties props) {+ return manager(dir, entry, ep, props, true);+ }++ /** Stands in for a build packaged without the ONNX runtime, where the tool cannot run. */+ private FormDetectionModelManager managerWithoutEngine(+ Path dir, ModelCatalogEntry entry, EndpointConfiguration ep) {+ return manager(dir, entry, ep, new ApplicationProperties(), false);+ }++ private FormDetectionModelManager manager(+ Path dir,+ ModelCatalogEntry entry,+ EndpointConfiguration ep,+ ApplicationProperties props,+ boolean serverEngineAvailable) {+ RuntimePathConfig paths = Mockito.mock(RuntimePathConfig.class);+ Mockito.when(paths.getFormDetectionModelPath()).thenReturn(dir.toString());+ ModelCatalogService catalog = Mockito.mock(ModelCatalogService.class);+ Mockito.when(catalog.getById("test-model")).thenReturn(Optional.of(entry));+ Mockito.when(catalog.getById(Mockito.argThat(s -> !"test-model".equals(s))))+ .thenReturn(Optional.empty());+ Mockito.when(catalog.getAll()).thenReturn(List.of(entry));+ // The real fetch only allows the catalog host, so stub the hop to the local test server.+ return new FormDetectionModelManager(paths, catalog, props, ep, noEngine()) {+ @Override+ HttpURLConnection openModelDownload(String url) throws IOException {+ String local = "http://127.0.0.1:" + port + URI.create(url).getPath();+ HttpURLConnection conn =+ (HttpURLConnection) URI.create(local).toURL().openConnection();+ conn.setConnectTimeout(5000);+ conn.setReadTimeout(10000);+ return conn;+ }++ @Override+ boolean isServerEngineAvailable() {+ return serverEngineAvailable;+ }+ };+ }++ private void awaitState(FormDetectionModelManager m, String wire, long timeoutMs)+ throws InterruptedException {+ long deadline = System.currentTimeMillis() + timeoutMs;+ while (System.currentTimeMillis() < deadline) {+ if (wire.equals(m.status().getStatus())) {+ return;+ }+ Thread.sleep(25);+ }+ fail("Timed out waiting for state '" + wire + "', was '" + m.status().getStatus() + "'");+ }++ @Test+ void installsDownloadsVerifiesAndPublishesAtomically(@TempDir Path dir) throws Exception {+ EndpointConfiguration ep = Mockito.mock(EndpointConfiguration.class);+ FormDetectionModelManager m =+ manager(dir, entry(ALLOWED_URL + "/model.onnx", modelSha), ep);++ m.startInstall("test-model");+ awaitState(m, "ready", 5000);++ Path onnx = dir.resolve("test-model.onnx");+ assertTrue(Files.exists(onnx), "model file should be published");+ assertArrayEquals(modelBytes, Files.readAllBytes(onnx));+ assertFalse(Files.exists(dir.resolve("test-model.onnx.tmp")), "temp file should be gone");+ assertTrue(m.isReady());+ Mockito.verify(ep).enableEndpoint("form-detection");+ }++ @Test+ void rejectsChecksumMismatchAndLeavesNoFile(@TempDir Path dir) throws Exception {+ EndpointConfiguration ep = Mockito.mock(EndpointConfiguration.class);+ FormDetectionModelManager m =+ manager(dir, entry(ALLOWED_URL + "/model.onnx", "0".repeat(64)), ep);++ m.startInstall("test-model");+ awaitState(m, "failed", 5000);++ assertFalse(Files.exists(dir.resolve("test-model.onnx")), "no model on mismatch");+ assertFalse(Files.exists(dir.resolve("test-model.onnx.tmp")), "temp cleaned up");+ assertFalse(m.isReady());+ Mockito.verify(ep, Mockito.never()).enableEndpoint("form-detection");+ }++ @Test+ void followsRedirectsOnlyWithinTheAllowedDomains() throws Exception {+ String from = "https://huggingface.co/a/b.onnx";+ // Hugging Face hands the file off to its own CDN, which is a subdomain of hf.co.+ assertEquals(+ "https://cdn-lfs.hf.co/x",+ FormDetectionModelManager.requireAllowedRedirect(from, "https://cdn-lfs.hf.co/x"));+ assertEquals(+ "https://huggingface.co/c/d.onnx",+ FormDetectionModelManager.requireAllowedRedirect(from, "/c/d.onnx"));+ }++ @Test+ void rejectsRedirectsOffTheAllowlist() {+ String from = "https://huggingface.co/a/b.onnx";+ assertThrows(+ IOException.class,+ () ->+ FormDetectionModelManager.requireAllowedRedirect(+ from, "https://evil.example/x"));+ assertThrows(+ IOException.class,+ () ->+ FormDetectionModelManager.requireAllowedRedirect(+ from, "https://huggingface.co.evil.example/x"));+ assertThrows(+ IOException.class,+ () ->+ FormDetectionModelManager.requireAllowedRedirect(+ from, "http://huggingface.co/x"));+ assertThrows(+ IOException.class,+ () ->+ FormDetectionModelManager.requireAllowedRedirect(+ from, "https://[email protected]/x"));+ }++ @Test+ void abortsAnOversizedDownloadAndLeavesNoPartialFile(@TempDir Path dir) throws Exception {+ // Well past the 8MB slack the manager allows over the catalogue size.+ long size = modelBytes.length + 9L * 1024 * 1024;+ server.createContext(+ "/huge.onnx",+ ex -> {+ ex.sendResponseHeaders(200, size);+ byte[] chunk = new byte[1 << 16];+ try (OutputStream body = ex.getResponseBody()) {+ for (long sent = 0; sent < size; sent += chunk.length) {+ body.write(chunk, 0, (int) Math.min(chunk.length, size - sent));+ }+ } catch (IOException ignored) {+ // Expected: the client aborts as soon as the ceiling trips.+ }+ ex.close();+ });+ FormDetectionModelManager m =+ manager(+ dir,+ entry(ALLOWED_URL + "/huge.onnx", modelSha),+ Mockito.mock(EndpointConfiguration.class));++ m.startInstall("test-model");+ awaitState(m, "failed", 15000);++ assertFalse(+ Files.exists(dir.resolve("test-model.onnx")), "no model on an aborted download");+ assertFalse(+ Files.exists(dir.resolve("test-model.onnx.tmp")), "partial download is deleted");+ assertEquals(0, m.status().getProgress(), "progress resets on failure");+ assertTrue(+ m.status().getError().contains("exceeded the expected size"),+ "the size ceiling, not the checksum, is what stopped it");+ }++ @Test+ void doesNotEnableTheEndpointWhenTheOnnxEngineIsAbsent(@TempDir Path dir) throws Exception {+ EndpointConfiguration ep = Mockito.mock(EndpointConfiguration.class);+ FormDetectionModelManager m =+ managerWithoutEngine(dir, entry(ALLOWED_URL + "/model.onnx", modelSha), ep);++ m.startInstall("test-model");+ awaitState(m, "ready", 5000);++ Mockito.verify(ep, Mockito.never()).enableEndpoint("form-detection");+ Mockito.verify(ep, Mockito.atLeastOnce())+ .disableEndpoint("form-detection", DisableReason.DEPENDENCY);+ }++ @Test+ void secondConcurrentInstallIsRejected(@TempDir Path dir) throws Exception {+ CountDownLatch gate = new CountDownLatch(1);+ server.createContext(+ "/gated.onnx",+ ex -> {+ try {+ gate.await(3, TimeUnit.SECONDS);+ } catch (InterruptedException ignored) {+ Thread.currentThread().interrupt();+ }+ ex.sendResponseHeaders(200, modelBytes.length);+ ex.getResponseBody().write(modelBytes);+ ex.close();+ });+ FormDetectionModelManager m =+ manager(+ dir,+ entry(ALLOWED_URL + "/gated.onnx", modelSha),+ Mockito.mock(EndpointConfiguration.class));++ m.startInstall("test-model"); // begins, blocks in handler+ // installing flag is set synchronously before the worker thread spawns+ assertThrows(IllegalStateException.class, () -> m.startInstall("test-model"));+ gate.countDown();+ awaitState(m, "ready", 5000);+ }++ @Test+ void rejectsBlankUrl(@TempDir Path dir) {+ FormDetectionModelManager m =+ manager(dir, entry("", ""), Mockito.mock(EndpointConfiguration.class));+ assertThrows(IllegalStateException.class, () -> m.startInstall("test-model"));+ }++ @Test+ void rejectsCatalogUrlOutsideAllowlist(@TempDir Path dir) {+ FormDetectionModelManager m =+ manager(+ dir,+ entry("http://127.0.0.1:" + port + "/model.onnx", modelSha),+ Mockito.mock(EndpointConfiguration.class));+ assertThrows(IllegalArgumentException.class, () -> m.startInstall("test-model"));+ }++ @Test+ void rejectsDownloadUrlOutsideAllowlist(@TempDir Path dir) {+ RuntimePathConfig paths = Mockito.mock(RuntimePathConfig.class);+ Mockito.when(paths.getFormDetectionModelPath()).thenReturn(dir.toString());+ FormDetectionModelManager m =+ new FormDetectionModelManager(+ paths,+ Mockito.mock(ModelCatalogService.class),+ new ApplicationProperties(),+ Mockito.mock(EndpointConfiguration.class),+ noEngine());++ assertThrows(+ IOException.class,+ () -> m.openModelDownload("http://127.0.0.1:" + port + "/model.onnx"));+ assertThrows(+ IOException.class,+ () -> m.openModelDownload("https://huggingface.co.evil.example/model.onnx"));+ }++ @Test+ void rejectsUnknownModelId(@TempDir Path dir) {+ FormDetectionModelManager m =+ manager(+ dir,+ entry(ALLOWED_URL + "/model.onnx", modelSha),+ Mockito.mock(EndpointConfiguration.class));+ assertThrows(IllegalArgumentException.class, () -> m.startInstall("unknown"));+ }++ @Test+ void uninstallTombstoneStopsReseedUntilExplicitReinstall(@TempDir Path root) throws Exception {+ Path modelDir = root.resolve("models");+ Path preDir = root.resolve("preinstalled");+ Files.createDirectories(preDir);+ Files.write(preDir.resolve("test-model.onnx"), modelBytes);+ ModelCatalogEntry e = entry(ALLOWED_URL + "/model.onnx", modelSha);++ ApplicationProperties props = new ApplicationProperties();+ props.getFormDetection().setPreinstalledModelDir(preDir.toString());+ FormDetectionModelManager m =+ manager(modelDir, e, Mockito.mock(EndpointConfiguration.class), props);+ m.init();+ assertEquals("test-model", m.status().getActiveModelId(), "seeded on first boot");+ assertEquals("ready", m.status().getStatus());+ assertTrue(m.status().getInstalled().contains("test-model"));+ assertFalse(+ Files.exists(modelDir.resolve("test-model.onnx")),+ "image-baked model is read in place, never duplicated into the writable dir");++ m.deleteModel("test-model");+ assertEquals("not_installed", m.status().getStatus());+ assertTrue(+ Files.exists(preDir.resolve("test-model.onnx")),+ "uninstall must not touch the read-only image copy");+ assertTrue(+ Files.exists(modelDir.resolve("test-model.onnx.removed")),+ "uninstall records a tombstone");++ // Simulate a container restart over the same volume: seeding must not resurrect it.+ ApplicationProperties props2 = new ApplicationProperties();+ props2.getFormDetection().setPreinstalledModelDir(preDir.toString());+ FormDetectionModelManager m2 =+ manager(modelDir, e, Mockito.mock(EndpointConfiguration.class), props2);+ m2.init();+ assertEquals("not_installed", m2.status().getStatus());+ assertFalse(+ m2.status().getInstalled().contains("test-model"),+ "tombstoned model must not be re-seeded");++ // An explicit reinstall clears the tombstone and seeding works again afterwards.+ m2.startInstall("test-model");+ awaitState(m2, "ready", 5000);+ assertFalse(Files.exists(modelDir.resolve("test-model.onnx.removed")));+ }++ @Test+ void gatesTheToolWhileASwitchIsDownloading(@TempDir Path dir) throws Exception {+ CountDownLatch gate = new CountDownLatch(1);+ server.createContext(+ "/switch.onnx",+ ex -> {+ try {+ gate.await(5, TimeUnit.SECONDS);+ } catch (InterruptedException ignored) {+ Thread.currentThread().interrupt();+ }+ ex.sendResponseHeaders(200, modelBytes.length);+ ex.getResponseBody().write(modelBytes);+ ex.close();+ });+ Files.write(dir.resolve("test-model.onnx"), modelBytes);+ ApplicationProperties props = new ApplicationProperties();+ props.getFormDetection().setActiveModelId("test-model");+ EndpointConfiguration ep = Mockito.mock(EndpointConfiguration.class);+ FormDetectionModelManager m =+ manager(dir, entry(ALLOWED_URL + "/switch.onnx", modelSha), ep, props);+ m.init();+ Mockito.verify(ep).enableEndpoint("form-detection");++ m.startInstall("test-model");++ assertFalse(m.isReady(), "a download is not something the tool can serve from");+ Mockito.verify(ep).disableEndpoint("form-detection", DisableReason.DEPENDENCY);++ gate.countDown();+ awaitState(m, "ready", 5000);+ }+}diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/formdetection/service/FormDetectionServiceTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/formdetection/service/FormDetectionServiceTest.javanew file mode 100644index 0000000000..679b8d3ec1--- /dev/null+++ b/app/proprietary/src/test/java/stirling/software/proprietary/formdetection/service/FormDetectionServiceTest.java@@ -0,0 +1,108 @@+package stirling.software.proprietary.formdetection.service;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertTrue;++import java.util.List;+import java.util.Map;+import java.util.Optional;+import java.util.function.Consumer;++import org.junit.jupiter.api.Test;+import org.mockito.Mockito;++import stirling.software.proprietary.formdetection.inference.OnnxFormDetector;+import stirling.software.proprietary.formdetection.inference.Yolo;+import stirling.software.proprietary.formdetection.model.DetectedField;+import stirling.software.proprietary.formdetection.model.ModelCatalogEntry;+import stirling.software.proprietary.formdetection.render.PageRasterizer;++class FormDetectionServiceTest {++ private static final int SIZE = 10;++ private ModelCatalogEntry spec() {+ ModelCatalogEntry e = new ModelCatalogEntry();+ e.setInputSize(SIZE);+ e.setResizeMode("stretch");+ e.setChannelOrder("rgb");+ e.setOutputLayout("nc_first");+ e.setHasObjectness(false);+ e.setClassNames(List.of("text"));+ e.setClassFieldTypes(List.of("text"));+ e.setNms("perClass");+ e.setIou(0.5f);+ e.setScoreThreshold(0.25f);+ return e;+ }++ private FormDetectionModelManager readyManager(ModelCatalogEntry spec) {+ FormDetectionModelManager manager = Mockito.mock(FormDetectionModelManager.class);+ Mockito.when(manager.isReady()).thenReturn(true);+ Mockito.when(manager.getActiveEntry()).thenReturn(Optional.of(spec));+ return manager;+ }++ /** A rasterizer that hands the pipeline one blank 10x10 page. */+ @SuppressWarnings("unchecked")+ private PageRasterizer onePage() throws Exception {+ PageRasterizer rasterizer = Mockito.mock(PageRasterizer.class);+ PageRasterizer.RasterPage page =+ new PageRasterizer.RasterPage(+ 0,+ new byte[SIZE * SIZE * 4],+ SIZE,+ SIZE,+ SIZE,+ SIZE,+ 1f,+ 1f,+ 0,+ SIZE,+ SIZE,+ 0f,+ 0f);+ Mockito.doAnswer(+ inv -> {+ ((Consumer<PageRasterizer.RasterPage>) inv.getArgument(3)).accept(page);+ return null;+ })+ .when(rasterizer)+ .rasterize(Mockito.any(), Mockito.anyInt(), Mockito.anyInt(), Mockito.any());+ return rasterizer;+ }++ /** Two overlapping boxes on one class, at the caller-chosen score. */+ private OnnxFormDetector detectorScoring(float first, float second) {+ float[] data = {5, 5, 5, 5, 4, 4, 4, 4, first, second};+ OnnxFormDetector detector = Mockito.mock(OnnxFormDetector.class);+ Mockito.when(detector.infer(Mockito.any(), Mockito.anyInt()))+ .thenReturn(Map.of("out", new Yolo.RawOutput(data, 5, 2)));+ return detector;+ }++ @Test+ void aZeroThresholdIsFlooredSoSubThresholdAnchorsAreNotAllKept() throws Exception {+ ModelCatalogEntry spec = spec();+ FormDetectionService service =+ new FormDetectionService(+ readyManager(spec), detectorScoring(0.005f, 0.004f), onePage());++ assertTrue(+ service.detect(new byte[] {1}, 0f).isEmpty(),+ "a threshold of 0 must not let every anchor through");+ }++ @Test+ void aThresholdAboveTheFloorStillSelectsNormally() throws Exception {+ ModelCatalogEntry spec = spec();+ FormDetectionService service =+ new FormDetectionService(+ readyManager(spec), detectorScoring(0.9f, 0.8f), onePage());++ List<DetectedField> fields = service.detect(new byte[] {1}, 0.5f);++ assertEquals(1, fields.size(), "the overlapping pair collapses to one field");+ assertEquals(0.9f, fields.getFirst().confidence(), 1e-5);+ }+}diff --git a/app/proprietary/src/test/resources/formdetection/rfdetr-reference.json b/app/proprietary/src/test/resources/formdetection/rfdetr-reference.jsonnew file mode 100644index 0000000000..bbb0b2b5a3--- /dev/null+++ b/app/proprietary/src/test/resources/formdetection/rfdetr-reference.json@@ -0,0 +1,318 @@+{+ "note": "Captured from ffdetr-int8.onnx on a synthetic form page via scripts/export-ffdetr-onnx.py.",+ "inputSize": 1024,+ "scoreThreshold": 0.3,+ "queries": [+ {+ "q": 0,+ "dets": [+ 0.594326,+ 0.253922,+ 0.575291,+ 0.03704+ ],+ "labels": [+ 1.494305,+ -4.254563,+ -2.83488,+ -8.221176+ ]+ },+ {+ "q": 1,+ "dets": [+ 0.593039,+ 0.305142,+ 0.574628,+ 0.036171+ ],+ "labels": [+ 1.501225,+ -4.211613,+ -2.82295,+ -8.282976+ ]+ },+ {+ "q": 2,+ "dets": [+ 0.594104,+ 0.355328,+ 0.573003,+ 0.036946+ ],+ "labels": [+ 1.550975,+ -4.177611,+ -3.121929,+ -8.416718+ ]+ },+ {+ "q": 3,+ "dets": [+ 0.593218,+ 0.204408,+ 0.573657,+ 0.036336+ ],+ "labels": [+ 1.483687,+ -4.080855,+ -2.717842,+ -8.144939+ ]+ },+ {+ "q": 4,+ "dets": [+ 0.593249,+ 0.102776,+ 0.573464,+ 0.03605+ ],+ "labels": [+ 1.52258,+ -4.080616,+ -2.611064,+ -8.24098+ ]+ },+ {+ "q": 5,+ "dets": [+ 0.593204,+ 0.153512,+ 0.572868,+ 0.036364+ ],+ "labels": [+ 1.489175,+ -4.014163,+ -2.746595,+ -8.259592+ ]+ },+ {+ "q": 6,+ "dets": [+ 0.593207,+ 0.406301,+ 0.575204,+ 0.036417+ ],+ "labels": [+ 1.523296,+ -4.076083,+ -2.997732,+ -8.246349+ ]+ },+ {+ "q": 7,+ "dets": [+ 0.336551,+ 0.487273,+ 0.021658,+ 0.016205+ ],+ "labels": [+ -2.577461,+ 1.216892,+ -4.798167,+ -7.703153+ ]+ },+ {+ "q": 8,+ "dets": [+ 0.824501,+ 0.570058,+ 0.114489,+ 0.03537+ ],+ "labels": [+ 1.210955,+ -3.528949,+ -3.637566,+ -8.277011+ ]+ },+ {+ "q": 9,+ "dets": [+ 0.499909,+ 0.487268,+ 0.021303,+ 0.016313+ ],+ "labels": [+ -2.650476,+ 1.275709,+ -4.80449,+ -7.729639+ ]+ },+ {+ "q": 10,+ "dets": [+ 0.480432,+ 0.569626,+ 0.345508,+ 0.03706+ ],+ "labels": [+ -0.667743,+ -4.025378,+ -0.391272,+ -7.142419+ ]+ },+ {+ "q": 99,+ "dets": [+ 0.787065,+ 0.572109,+ 0.041269,+ 0.032919+ ],+ "labels": [+ -4.071043,+ -4.381146,+ -5.294834,+ -8.117142+ ]+ },+ {+ "q": 150,+ "dets": [+ 0.617099,+ 0.154866,+ 0.457747,+ 0.034707+ ],+ "labels": [+ -3.982041,+ -5.252909,+ -4.907092,+ -8.302184+ ]+ },+ {+ "q": 299,+ "dets": [+ 0.595358,+ 0.708946,+ 0.331338,+ 0.039393+ ],+ "labels": [+ -4.61758,+ -5.568352,+ -4.882038,+ -7.22629+ ]+ }+ ],+ "expected": [+ {+ "q": 0,+ "cls": 0,+ "score": 0.81672,+ "x": 314.041,+ "y": 241.051,+ "w": 589.098,+ "h": 37.929+ },+ {+ "q": 1,+ "cls": 0,+ "score": 0.81776,+ "x": 313.062,+ "y": 293.945,+ "w": 588.419,+ "h": 37.039+ },+ {+ "q": 2,+ "cls": 0,+ "score": 0.82505,+ "x": 314.985,+ "y": 344.94,+ "w": 586.755,+ "h": 37.833+ },+ {+ "q": 3,+ "cls": 0,+ "score": 0.81513,+ "x": 313.743,+ "y": 190.709,+ "w": 587.424,+ "h": 37.208+ },+ {+ "q": 4,+ "cls": 0,+ "score": 0.82092,+ "x": 313.873,+ "y": 86.785,+ "w": 587.227,+ "h": 36.915+ },+ {+ "q": 5,+ "cls": 0,+ "score": 0.81595,+ "x": 314.133,+ "y": 138.578,+ "w": 586.617,+ "h": 37.237+ },+ {+ "q": 6,+ "cls": 0,+ "score": 0.82102,+ "x": 312.94,+ "y": 397.407,+ "w": 589.009,+ "h": 37.291+ },+ {+ "q": 7,+ "cls": 1,+ "score": 0.77152,+ "x": 333.539,+ "y": 490.671,+ "w": 22.178,+ "h": 16.594+ },+ {+ "q": 8,+ "cls": 0,+ "score": 0.77047,+ "x": 785.671,+ "y": 565.63,+ "w": 117.237,+ "h": 36.219+ },+ {+ "q": 9,+ "cls": 1,+ "score": 0.78172,+ "x": 500.999,+ "y": 490.61,+ "w": 21.814,+ "h": 16.705+ },+ {+ "q": 10,+ "cls": 2,+ "score": 0.40341,+ "x": 315.062,+ "y": 564.322,+ "w": 353.801,+ "h": 37.95+ }+ ]+}diff --git a/app/saas/src/main/java/stirling/software/saas/security/SupabaseSecurityConfig.java b/app/saas/src/main/java/stirling/software/saas/security/SupabaseSecurityConfig.javaindex 1314bfaa5b..df2ed77a23 100644--- a/app/saas/src/main/java/stirling/software/saas/security/SupabaseSecurityConfig.java+++ b/app/saas/src/main/java/stirling/software/saas/security/SupabaseSecurityConfig.java@@ -397,7 +397,8 @@ public class SupabaseSecurityConfig {List.of("WWW-Authenticate","X-Stirling-Skipped-Field-Edits",- "X-Stirling-Skipped-Field-Edits-Total"));+ "X-Stirling-Skipped-Field-Edits-Total",+ "X-Stirling-Detected-Fields"));cfg.setAllowCredentials(true);cfg.setMaxAge(3600L);UrlBasedCorsConfigurationSource allowListed = new UrlBasedCorsConfigurationSource();diff --git a/docker/embedded/Dockerfile b/docker/embedded/Dockerfileindex 6f525b2732..5d13e9f977 100644--- a/docker/embedded/Dockerfile+++ b/docker/embedded/Dockerfile@@ -19,6 +19,19 @@ RUN apt-get update \&& rm /tmp/task.deb \&& rm -rf /var/lib/apt/lists/*+# Bake the detection model in so the tool works out of the box (~26MB pull, 35MB on disk).+# Only weights we may redistribute belong here; FFDetr is Apache-2.0 end to end.+ARG FORM_DETECTION_MODEL_URL="https://huggingface.co/Frooodle/ffdetr-int8/resolve/ad3223d7c3ae25ce1d1ec8fe972c8ff7630aff45/ffdetr-int8.onnx"+ARG FORM_DETECTION_MODEL_SHA256="de43bb39adb08459fe62fa1a7be6bfb4f2d397bb034c46055f3b8fa3d04fc8f4"+ARG FORM_DETECTION_MODEL_ID="ffdetr"+RUN mkdir -p /preinstalled-models \+ && if [ -n "${FORM_DETECTION_MODEL_URL}" ]; then \+ curl -fSL "${FORM_DETECTION_MODEL_URL}" -o "/preinstalled-models/${FORM_DETECTION_MODEL_ID}.onnx" \+ && echo "${FORM_DETECTION_MODEL_SHA256} /preinstalled-models/${FORM_DETECTION_MODEL_ID}.onnx" | sha256sum -c -; \+ else \+ echo "No form-detection model pre-bundled (FORM_DETECTION_MODEL_URL unset)"; \+ fi+# JDK 25+: --add-exports is no longer accepted via JAVA_TOOL_OPTIONS; use JDK_JAVA_OPTIONS insteadENV JDK_JAVA_OPTIONS="--add-exports=jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED \--add-exports=jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED \@@ -71,6 +84,7 @@ RUN JPDFIUM_PLATFORM="$([ "$TARGETARCH" = arm64 ] && echo linux-arm64 || echo li-PbuildWithPortal=${BUILD_PORTAL} \-PjpdfiumPlatforms="$JPDFIUM_PLATFORM" \-PprototypesMode=${PROTOTYPES_BUILD} \+ -PbundleOnnxRuntime=true \-x spotlessApply -x spotlessCheck -x test -x sonarqube \--no-daemon@@ -80,6 +94,13 @@ WORKDIR /tmpCOPY --from=app-build /app/app/core/build/libs/*.jar app.jarRUN java -Djarmode=tools -jar app.jar extract --layers --destination /layers+# Strip the bundled ONNX Runtime's natives down to the target Linux arch (~42MB jar -> ~8MB).+COPY scripts/slim-onnxruntime.sh /tmp/slim-onnxruntime.sh+RUN apt-get update \+ && apt-get install -y --no-install-recommends zip \+ && rm -rf /var/lib/apt/lists/* \+ && sh /tmp/slim-onnxruntime.sh /layers/dependencies+# Stage 3: Final runtime image on top of pre-built baseFROM ${BASE_IMAGE}@@ -98,6 +119,9 @@ COPY --link --from=app-build --chown=1000:1000 \/app/build/libs/restart-helper.jar /restart-helper.jarCOPY --link --chown=1000:1000 scripts/ /scripts/+# Baked-in detection model; FormDetectionModelManager seeds it into /configs on startup.+COPY --link --from=app-build --chown=1000:1000 /preinstalled-models/ /opt/stirling/preinstalled-models/+# Fonts go to system dir, root ownership is correct (world-readable)COPY app/core/src/main/resources/static/fonts/*.ttf /usr/share/fonts/truetype/@@ -121,6 +145,7 @@ RUN echo "${VERSION_TAG:-dev}" > /etc/stirling_version# Environment variablesENV VERSION_TAG=$VERSION_TAG \+ FORMDETECTION_PREINSTALLEDMODELDIR="/opt/stirling/preinstalled-models" \STIRLING_AOT_ENABLE="false" \STIRLING_JVM_PROFILE="balanced" \_JVM_OPTS_BALANCED="-XX:+ExitOnOutOfMemoryError -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/configs/heap_dumps -XX:+UseG1GC -XX:MaxGCPauseMillis=200 -XX:G1HeapRegionSize=4m -XX:G1PeriodicGCInterval=60000 -XX:+UseStringDeduplication -XX:+UseCompactObjectHeaders -XX:+ExplicitGCInvokesConcurrent -Dspring.threads.virtual.enabled=true -Djava.awt.headless=true" \diff --git a/docker/embedded/Dockerfile.fat b/docker/embedded/Dockerfile.fatindex 38c8bcc8f1..666f44d4cf 100644--- a/docker/embedded/Dockerfile.fat+++ b/docker/embedded/Dockerfile.fat@@ -22,6 +22,19 @@ RUN apt-get update \&& rm /tmp/task.deb \&& rm -rf /var/lib/apt/lists/*+# Air-gapped image, so the detection model must be baked in (~27MB pull). FFDetr is Apache-2.0+# end to end; keep these args in step with model-catalog.json or the sha256sum check below fails.+ARG FORM_DETECTION_MODEL_URL="https://huggingface.co/Frooodle/ffdetr-int8/resolve/ad3223d7c3ae25ce1d1ec8fe972c8ff7630aff45/ffdetr-int8.onnx"+ARG FORM_DETECTION_MODEL_SHA256="de43bb39adb08459fe62fa1a7be6bfb4f2d397bb034c46055f3b8fa3d04fc8f4"+ARG FORM_DETECTION_MODEL_ID="ffdetr"+RUN mkdir -p /preinstalled-models \+ && if [ -n "${FORM_DETECTION_MODEL_URL}" ]; then \+ curl -fSL "${FORM_DETECTION_MODEL_URL}" -o "/preinstalled-models/${FORM_DETECTION_MODEL_ID}.onnx" \+ && echo "${FORM_DETECTION_MODEL_SHA256} /preinstalled-models/${FORM_DETECTION_MODEL_ID}.onnx" | sha256sum -c -; \+ else \+ echo "No form-detection model pre-bundled (FORM_DETECTION_MODEL_URL unset)"; \+ fi+# JDK 25+: --add-exports is no longer accepted via JAVA_TOOL_OPTIONS; use JDK_JAVA_OPTIONS insteadENV JDK_JAVA_OPTIONS="--add-exports=jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED \--add-exports=jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED \@@ -55,6 +68,7 @@ RUN --mount=type=cache,id=stirling-pdf-npm-cache,target=/root/.npm,sharing=lockeDISABLE_ADDITIONAL_FEATURES=false \gradle clean build \-PbuildWithFrontend=true \+ -PbundleOnnxRuntime=true \-PbuildWithPortal=${BUILD_PORTAL} \-PjpdfiumPlatforms="$JPDFIUM_PLATFORM" \-x spotlessApply -x spotlessCheck -x test -x sonarqube \@@ -66,6 +80,13 @@ WORKDIR /tmpCOPY --from=app-build /app/app/core/build/libs/*.jar app.jarRUN java -Djarmode=tools -jar app.jar extract --layers --destination /layers+# Strip the bundled ONNX Runtime's natives down to the target Linux arch (~42MB jar -> ~8MB).+COPY scripts/slim-onnxruntime.sh /tmp/slim-onnxruntime.sh+RUN apt-get update \+ && apt-get install -y --no-install-recommends zip \+ && rm -rf /var/lib/apt/lists/* \+ && sh /tmp/slim-onnxruntime.sh /layers/dependencies+# Stage 2b: AI engine. Built at its final path so the venv resolves after the copy, on uv's# managed CPython because the runtime base ships Python 3.12.@@ -114,6 +135,9 @@ COPY --link --from=engine-build --chown=1000:1000 /opt/stirling-engine/.venv /oCOPY --link --chown=1000:1000 engine/.env /opt/stirling-engine/.envCOPY --link --chown=1000:1000 engine/src/ /opt/stirling-engine/src/+# Baked-in detection model; FormDetectionModelManager seeds it into /configs on startup.+COPY --link --from=app-build --chown=1000:1000 /preinstalled-models/ /opt/stirling/preinstalled-models/+# Fonts go to system dir, root ownership is correct (world-readable)COPY app/core/src/main/resources/static/fonts/*.ttf /usr/share/fonts/truetype/@@ -138,6 +162,7 @@ RUN echo "${VERSION_TAG:-dev}" > /etc/stirling_version# Environment variablesENV VERSION_TAG=$VERSION_TAG \+ FORMDETECTION_PREINSTALLEDMODELDIR="/opt/stirling/preinstalled-models" \STIRLING_AOT_ENABLE="false" \STIRLING_JVM_PROFILE="balanced" \_JVM_OPTS_BALANCED="-XX:+ExitOnOutOfMemoryError -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/configs/heap_dumps -XX:+UseG1GC -XX:MaxGCPauseMillis=200 -XX:G1HeapRegionSize=4m -XX:G1PeriodicGCInterval=60000 -XX:+UseStringDeduplication -XX:+UseCompactObjectHeaders -XX:+ExplicitGCInvokesConcurrent -Dspring.threads.virtual.enabled=true -Djava.awt.headless=true" \diff --git a/frontend/editor/playwright.config.ts b/frontend/editor/playwright.config.tsindex ec63e5d8e9..865f03020f 100644--- a/frontend/editor/playwright.config.ts+++ b/frontend/editor/playwright.config.ts@@ -130,7 +130,7 @@ export default defineConfig({command: process.env.CI? `npx vite preview --port ${DEV_PORT} --strictPort`: `npx vite --port ${DEV_PORT} --strictPort`,- url: `http://localhost:${DEV_PORT}`,+ url: process.env.PLAYWRIGHT_BASE_URL ?? `http://localhost:${DEV_PORT}`,reuseExistingServer: !process.env.CI,timeout: 120_000,},diff --git a/frontend/editor/public/locales/en-US/translation.toml b/frontend/editor/public/locales/en-US/translation.tomlindex 55dcf80c8c..49ceb554a6 100644--- a/frontend/editor/public/locales/en-US/translation.toml+++ b/frontend/editor/public/locales/en-US/translation.toml@@ -557,6 +557,47 @@ close = "Close"error = "Error"expand = "Expand"+[admin.formDetection]+confirmUninstall = "Click to confirm"+description = "Detects text fields, checkboxes and signature areas in a PDF and turns them into fillable form fields. Detection runs on this server with the model you install below."+downloadingNote = "{{percent}}% of {{size}}"+enableFeature = "Enable feature"+engineUnavailable = "This build does not include the detection engine, so the tool stays unavailable even with a model installed."+errorTitle = "Something went wrong"+install = "Install"+installFailed = "Install failed"+licenseLabel = "Licence"+modelsLabel = "Detection model"+notAvailable = "No download URL/checksum configured yet, so this model cannot be installed."+notWritable = "The model directory is not writable; check the configs volume mount."+saveFailed = "Failed to save setting"+sizeUnknown = "size unknown"+switch = "Use this model"+title = "AI Form Detection"+uninstall = "Uninstall"+uninstallFailed = "Uninstall failed"+verifyingNote = "Verifying SHA-256 checksum..."++[admin.formDetection.airgap]+intro = "No internet on the server? Download the model elsewhere, verify it, and copy it into the model directory. It is picked up on restart."+noSha = "(checksum not set)"+show = "Offline / air-gapped install"+step1 = "1. Download on a machine with internet:"+step2 = "2. Check the SHA-256 checksum matches:"+step3 = "3. Copy it into the model directory on this server:"+step4 = "4. Set formDetection.activeModelId to the model's id in settings.yml and restart. <configs> is the configs volume (e.g. /configs in Docker). The air-gapped image ships with a model already installed."++[admin.formDetection.badge]+active = "Active"+installed = "Installed"++[admin.formDetection.state]+downloading = "Downloading..."+failed = "Failed"+notInstalled = "No model installed"+ready = "Ready"+verifying = "Verifying..."+[admin.settings]discard = "Discard"error = "Failed to save settings"@@ -2059,6 +2100,50 @@ bullet2 = "Creates a clean, valid filename from the detected title"bullet3 = "Keeps the original name if no suitable title is found"title = "Smart Renaming"+[autoFormDetection]+loading = "Detecting form fields..."+submit = "Detect form fields"++[autoFormDetection.detects]+checkboxes = "Checkboxes"+label = "Finds and makes fillable"+signatures = "Signatures"+text = "Text fields"++[autoFormDetection.error]+failed = "An error occurred while detecting form fields."++[autoFormDetection.progress]+detecting = "Analyzing your document..."++[autoFormDetection.results]+title = "Review fillable PDF"++[autoFormDetection.sensitivity]+balanced = "Balanced"+balancedHint = "Recommended for most forms."+high = "Thorough"+highHint = "Finds more fields, but may add some where none belong."+label = "Detection sensitivity"+low = "Strict"+lowHint = "Only very confident matches - fewer fields, fewer mistakes."++[autoFormDetection.settings]+title = "Settings"++[autoFormDetection.summary]+checkboxes = "Checkboxes"+noneBody = "The document may not contain form-like areas. Undo, switch sensitivity to \"Thorough\", and run again to look harder."+noneTitle = "No form fields found"+pages_one = "Across {{count}} page."+pages_other = "Across {{count}} pages."+radioButtons = "Radio buttons"+signatures = "Signatures"+stepTitle = "Detection results"+textFields = "Text fields"+title_one = "{{count}} fillable field added"+title_other = "{{count}} fillable fields added"+[automate]copyToSaved = "Copy to Saved"desc = "Build multi-step workflows by chaining together PDF actions. Ideal for recurring tasks."@@ -5051,6 +5136,12 @@ desc = "Highlight, draw, add notes and shapes in the viewer"tags = "annotate,highlight,draw,markup,comment,notes,review,redline,feedback,markup tools,sticky notes,shapes,arrows,text box,freehand"title = "Annotate"+[home.autoFormDetection]+desc = "Automatically detect form fields with AI and make your PDF fillable."+tags = "form,detect,fillable,acroform,auto detect,ai,fields,make fillable,form detection"+title = "Auto Form Detection"+unavailable = "Needs the AI detection model, which isn't installed on this server. An administrator can add it under Settings > Features > AI Form Detection."+[home.automate]desc = "Build multi-step workflows by chaining together PDF actions. Ideal for recurring tasks."tags = "workflow,sequence,automation,automate,batch,batch processing,pipeline,chain,multi-step,recurring,scheduled,automatic,process multiple,bulk operations"diff --git a/frontend/editor/public/og-metadata.json b/frontend/editor/public/og-metadata.jsonindex 7608a1d315..87c05a8d2d 100644--- a/frontend/editor/public/og-metadata.json+++ b/frontend/editor/public/og-metadata.json@@ -275,6 +275,11 @@"title": "Form Editor - Stirling PDF","description": "Fill, create, edit, and delete PDF form fields with a visual editor"},+ "autoFormDetection": {+ "image": "/og_images/home.png",+ "title": "Auto Form Detection - Stirling PDF",+ "description": "Automatically detect form fields with AI and make your PDF fillable."+ },"multiTool": {"image": "/og_images/multi-tool.png","title": "Multi-Tool - Stirling PDF",@@ -596,6 +601,7 @@"/booklet-imposition": "bookletImposition","/pdf-text-editor": "pdfTextEditor","/form-fill": "formFill",+ "/auto-form-detection": "autoFormDetection","/multi-tool": "multiTool","/read": "read","/automate": "automate",diff --git a/frontend/editor/public/og-metadata.saas.json b/frontend/editor/public/og-metadata.saas.jsonindex fff936752f..d73b8bab55 100644--- a/frontend/editor/public/og-metadata.saas.json+++ b/frontend/editor/public/og-metadata.saas.json@@ -276,6 +276,11 @@"title": "Form Editor - Stirling PDF","description": "Fill, create, edit, and delete PDF form fields with a visual editor"},+ "autoFormDetection": {+ "image": "/og_images/home.png",+ "title": "Auto Form Detection - Stirling PDF",+ "description": "Automatically detect form fields with AI and make your PDF fillable."+ },"multiTool": {"image": "/og_images/multi-tool.png","title": "Multi-Tool - Stirling PDF",@@ -609,6 +614,7 @@"/booklet-imposition": "bookletImposition","/pdf-text-editor": "pdfTextEditor","/form-fill": "formFill",+ "/auto-form-detection": "autoFormDetection","/multi-tool": "multiTool","/read": "read","/automate": "automate",diff --git a/frontend/editor/scripts/generate-tool-api-types.mts b/frontend/editor/scripts/generate-tool-api-types.mtsindex ac570748fd..caa85d8bee 100644--- a/frontend/editor/scripts/generate-tool-api-types.mts+++ b/frontend/editor/scripts/generate-tool-api-types.mts@@ -21,6 +21,9 @@ const ALLOWED_PATH_PREFIXES = ["/api/v1/filter/","/api/v1/integration/","/api/v1/ai/tools/classify-and-label",+ // Admitted on its own rather than the whole form namespace: this is the only /form/ endpoint+ // that takes a document and returns one, so it is the only one a pipeline can chain.+ "/api/v1/form/form-detection/detect",];// File plumbing, not user parameters: `fileInput` and `file` are the uploaded primary documentdiff --git a/frontend/editor/src/core/components/tools/autoFormDetection/AutoFormDetectionSettings.tsx b/frontend/editor/src/core/components/tools/autoFormDetection/AutoFormDetectionSettings.tsxnew file mode 100644index 0000000000..5ef90e7f62--- /dev/null+++ b/frontend/editor/src/core/components/tools/autoFormDetection/AutoFormDetectionSettings.tsx@@ -0,0 +1,113 @@+import { Stack, Text, Group } from "@mantine/core";+import { useTranslation } from "react-i18next";+import { SegmentedControl } from "@app/ui/SegmentedControl";+import LocalIcon from "@app/components/shared/LocalIcon";+import {+ AutoFormDetectionParameters,+ DetectionSensitivity,+} from "@app/hooks/tools/autoFormDetection/useAutoFormDetectionParameters";++interface AutoFormDetectionSettingsProps {+ parameters: AutoFormDetectionParameters;+ onParameterChange: <K extends keyof AutoFormDetectionParameters>(+ key: K,+ value: AutoFormDetectionParameters[K],+ ) => void;+ disabled?: boolean;+}++const FIELD_TYPES = [+ { icon: "text-fields-rounded", key: "text", fallback: "Text fields" },+ {+ icon: "check-box-outline-rounded",+ key: "checkboxes",+ fallback: "Checkboxes",+ },+ { icon: "signature-rounded", key: "signatures", fallback: "Signatures" },+] as const;++export default function AutoFormDetectionSettings({+ parameters,+ onParameterChange,+ disabled,+}: AutoFormDetectionSettingsProps) {+ const { t } = useTranslation();++ const sensitivity = parameters.sensitivity ?? "balanced";+ const sensitivityHint: Record<DetectionSensitivity, string> = {+ low: t(+ "autoFormDetection.sensitivity.lowHint",+ "Only very confident matches - fewer fields, fewer mistakes.",+ ),+ balanced: t(+ "autoFormDetection.sensitivity.balancedHint",+ "Recommended for most forms.",+ ),+ high: t(+ "autoFormDetection.sensitivity.highHint",+ "Finds more fields, but may add some where none belong.",+ ),+ };++ return (+ <Stack gap="sm">+ <div>+ <Text size="sm" fw={500} mb={4}>+ {t("autoFormDetection.detects.label", "Finds and makes fillable")}+ </Text>+ <Group gap="xs">+ {FIELD_TYPES.map((f) => (+ <Group+ key={f.key}+ gap={4}+ wrap="nowrap"+ style={{+ border: "1px solid var(--c-border-subtle)",+ borderRadius: "var(--mantine-radius-xl)",+ padding: "0.125rem 0.5rem",+ }}+ >+ <LocalIcon icon={f.icon} width="0.9rem" height="0.9rem" />+ <Text size="xs">+ {t(`autoFormDetection.detects.${f.key}`, f.fallback)}+ </Text>+ </Group>+ ))}+ </Group>+ </div>++ <div>+ <Text size="sm" fw={500} mb={4}>+ {t("autoFormDetection.sensitivity.label", "Detection sensitivity")}+ </Text>+ <SegmentedControl<DetectionSensitivity>+ fullWidth+ value={sensitivity}+ disabled={disabled}+ onChange={(v) => onParameterChange("sensitivity", v)}+ ariaLabel={t(+ "autoFormDetection.sensitivity.label",+ "Detection sensitivity",+ )}+ options={[+ {+ value: "low",+ label: t("autoFormDetection.sensitivity.low", "Strict"),+ },+ {+ value: "balanced",+ label: t("autoFormDetection.sensitivity.balanced", "Balanced"),+ },+ {+ value: "high",+ label: t("autoFormDetection.sensitivity.high", "Thorough"),+ },+ ]}+ />+ <Text size="xs" c="dimmed" mt={4}>+ {sensitivityHint[sensitivity]}+ </Text>+ </div>+ </Stack>+ );+}diff --git a/frontend/editor/src/core/components/tools/autoFormDetection/DetectionProgressPanel.tsx b/frontend/editor/src/core/components/tools/autoFormDetection/DetectionProgressPanel.tsxnew file mode 100644index 0000000000..5d08307959--- /dev/null+++ b/frontend/editor/src/core/components/tools/autoFormDetection/DetectionProgressPanel.tsx@@ -0,0 +1,29 @@+import { Group, Loader, Stack, Text } from "@mantine/core";+import { useTranslation } from "react-i18next";++/**+ * Detection is one request of unknown length, so there is no progress to report beyond+ * "in flight" - hence a spinner driven by the operation's own loading flag.+ */+export default function DetectionProgressPanel({+ active,+}: {+ active: boolean;+}) {+ const { t } = useTranslation();+ if (!active) return null;++ return (+ <Stack gap={6} mx="md" mt="sm">+ <Group gap={8} wrap="nowrap">+ <Loader size="xs" />+ <Text size="xs" c="dimmed">+ {t(+ "autoFormDetection.progress.detecting",+ "Analyzing your document...",+ )}+ </Text>+ </Group>+ </Stack>+ );+}diff --git a/frontend/editor/src/core/components/tools/autoFormDetection/DetectionSummaryPanel.tsx b/frontend/editor/src/core/components/tools/autoFormDetection/DetectionSummaryPanel.tsxnew file mode 100644index 0000000000..d767621b8e--- /dev/null+++ b/frontend/editor/src/core/components/tools/autoFormDetection/DetectionSummaryPanel.tsx@@ -0,0 +1,113 @@+import { Group, Stack, Text } from "@mantine/core";+import { useTranslation } from "react-i18next";+import LocalIcon from "@app/components/shared/LocalIcon";+import { Banner } from "@app/ui/Banner";+import { DetectionSummary } from "@app/services/formDetection/progress";++const TYPE_META: Record<+ string,+ { icon: string; labelKey: string; fallback: string }+> = {+ text: {+ icon: "text-fields-rounded",+ labelKey: "autoFormDetection.summary.textFields",+ fallback: "Text fields",+ },+ checkbox: {+ icon: "check-box-outline-rounded",+ labelKey: "autoFormDetection.summary.checkboxes",+ fallback: "Checkboxes",+ },+ radio: {+ icon: "radio-button-checked-outline",+ labelKey: "autoFormDetection.summary.radioButtons",+ fallback: "Radio buttons",+ },+ signature: {+ icon: "signature-rounded",+ labelKey: "autoFormDetection.summary.signatures",+ fallback: "Signatures",+ },+};++export default function DetectionSummaryPanel({+ summary,+}: {+ summary: DetectionSummary;+}) {+ const { t } = useTranslation();++ if (summary.total === 0) {+ return (+ <Banner+ tone="warning"+ icon={+ <LocalIcon icon="search-rounded" width="1.1rem" height="1.1rem" />+ }+ title={t("autoFormDetection.summary.noneTitle", "No form fields found")}+ description={t(+ "autoFormDetection.summary.noneBody",+ 'The document may not contain form-like areas. Undo, switch sensitivity to "Thorough", and run again to look harder.',+ )}+ />+ );+ }++ const entries = Object.entries(summary.byType).sort((a, b) => b[1] - a[1]);++ return (+ <Stack gap="xs">+ <Group gap={6} wrap="nowrap">+ <LocalIcon+ icon="verified-outline-rounded"+ width="1.15rem"+ height="1.15rem"+ style={{ color: "var(--c-success)" }}+ />+ <Text size="sm" fw={600}>+ {t(+ "autoFormDetection.summary.title",+ "{{count}} fillable fields added",+ { count: summary.total },+ )}+ </Text>+ </Group>++ <Group gap="xs">+ {entries.map(([type, count]) => {+ const meta = TYPE_META[type] ?? {+ icon: "text-fields-rounded",+ labelKey: `autoFormDetection.summary.${type}`,+ fallback: type,+ };+ return (+ <Group+ key={type}+ gap={4}+ wrap="nowrap"+ style={{+ border: "1px solid var(--c-border-subtle)",+ background: "var(--c-surface-sunken)",+ borderRadius: "var(--mantine-radius-xl)",+ padding: "0.125rem 0.5rem",+ }}+ >+ <LocalIcon icon={meta.icon} width="0.9rem" height="0.9rem" />+ <Text size="xs">+ {t(meta.labelKey, meta.fallback)}: {count}+ </Text>+ </Group>+ );+ })}+ </Group>++ {summary.pagesWithFields > 1 ? (+ <Text size="xs" c="dimmed">+ {t("autoFormDetection.summary.pages", "Across {{count}} pages.", {+ count: summary.pagesWithFields,+ })}+ </Text>+ ) : null}+ </Stack>+ );+}diff --git a/frontend/editor/src/core/components/tools/fullscreen/CompactToolItem.tsx b/frontend/editor/src/core/components/tools/fullscreen/CompactToolItem.tsxindex 37300cfeec..84b6143a46 100644--- a/frontend/editor/src/core/components/tools/fullscreen/CompactToolItem.tsx+++ b/frontend/editor/src/core/components/tools/fullscreen/CompactToolItem.tsx@@ -13,7 +13,7 @@ import {getIconStyle,getItemClasses,useToolMeta,- getDisabledLabel,+ resolveDisabledMessage,} from "@app/components/tools/fullscreen/shared";import { Button } from "@app/ui/Button";@@ -101,9 +101,7 @@ const CompactToolItem: React.FC<CompactToolItemProps> = ({</Button>);- const { key: disabledKey, fallback: disabledFallback } =- getDisabledLabel(disabledReason);- const disabledMessage = t(disabledKey, disabledFallback);+ const disabledMessage = resolveDisabledMessage(t, disabledReason, tool);const tooltipContent = disabled ? (<span>diff --git a/frontend/editor/src/core/components/tools/fullscreen/DetailedToolItem.tsx b/frontend/editor/src/core/components/tools/fullscreen/DetailedToolItem.tsxindex 464403e286..9a99c542d1 100644--- a/frontend/editor/src/core/components/tools/fullscreen/DetailedToolItem.tsx+++ b/frontend/editor/src/core/components/tools/fullscreen/DetailedToolItem.tsx@@ -12,7 +12,7 @@ import {getIconStyle,getItemClasses,useToolMeta,- getDisabledLabel,+ resolveDisabledMessage,} from "@app/components/tools/fullscreen/shared";import { Button } from "@app/ui/Button";@@ -52,9 +52,7 @@ const DetailedToolItem: React.FC<DetailedToolItemProps> = ({iconNode = tool.icon;}- const { key: disabledKey, fallback: disabledFallback } =- getDisabledLabel(disabledReason);- const disabledMessage = t(disabledKey, disabledFallback);+ const disabledMessage = resolveDisabledMessage(t, disabledReason, tool);return (<Buttondiff --git a/frontend/editor/src/core/components/tools/fullscreen/shared.ts b/frontend/editor/src/core/components/tools/fullscreen/shared.tsindex b6f451ca1b..3b589da218 100644--- a/frontend/editor/src/core/components/tools/fullscreen/shared.ts+++ b/frontend/editor/src/core/components/tools/fullscreen/shared.ts@@ -70,6 +70,28 @@ export const getToolDisabledReason = (return null;};+const AVAILABILITY_REASONS: ToolDisabledReason[] = [+ "disabledByAdmin",+ "missingDependency",+ "unknownUnavailable",+];++/** Per-tool override for availability-driven disabled labels, else the generic one. */+export const resolveDisabledMessage = (+ t: (key: string, fallback: string) => string,+ disabledReason: ToolDisabledReason,+ tool: ToolRegistryEntry,+): string => {+ if (+ tool.unavailableMessage &&+ AVAILABILITY_REASONS.includes(disabledReason)+ ) {+ return tool.unavailableMessage;+ }+ const { key, fallback } = getDisabledLabel(disabledReason);+ return t(key, fallback);+};+export const getDisabledLabel = (disabledReason: ToolDisabledReason,): { key: string; fallback: string } => {diff --git a/frontend/editor/src/core/components/tools/toolPicker/ToolButton.tsx b/frontend/editor/src/core/components/tools/toolPicker/ToolButton.tsxindex 8daf2cb019..90f31bd58d 100644--- a/frontend/editor/src/core/components/tools/toolPicker/ToolButton.tsx+++ b/frontend/editor/src/core/components/tools/toolPicker/ToolButton.tsx@@ -18,7 +18,7 @@ import {import type { ToolId } from "@app/types/toolId";import {getToolDisabledReason,- getDisabledLabel,+ resolveDisabledMessage,} from "@app/components/tools/fullscreen/shared";import { useAppConfig } from "@app/contexts/AppConfigContext";import { CloudBadge } from "@app/components/shared/CloudBadge";@@ -102,9 +102,7 @@ const ToolButton: React.FC<ToolButtonProps> = ({? getToolNavigation(id, tool): null;- const { key: disabledKey, fallback: disabledFallback } =- getDisabledLabel(disabledReason);- const disabledMessage = t(disabledKey, disabledFallback);+ const disabledMessage = resolveDisabledMessage(t, disabledReason, tool);const tooltipContent = visuallyUnavailable ? (<span>diff --git a/frontend/editor/src/core/data/toolsTaxonomy.ts b/frontend/editor/src/core/data/toolsTaxonomy.tsindex 740b8a13ec..529e80a503 100644--- a/frontend/editor/src/core/data/toolsTaxonomy.ts+++ b/frontend/editor/src/core/data/toolsTaxonomy.ts@@ -80,6 +80,8 @@ export type ToolRegistryEntry = {versionStatus?: "alpha" | "beta";// Whether this tool requires premium accessrequiresPremium?: boolean;+ // Pre-translated override for the generic "unavailable on server" tooltip label+ unavailableMessage?: string;};export type RegularToolRegistry = Record<RegularToolId, ToolRegistryEntry>;diff --git a/frontend/editor/src/core/data/useTranslatedToolRegistry.tsx b/frontend/editor/src/core/data/useTranslatedToolRegistry.tsxindex feec25ec2f..a62e0a7734 100644--- a/frontend/editor/src/core/data/useTranslatedToolRegistry.tsx+++ b/frontend/editor/src/core/data/useTranslatedToolRegistry.tsx@@ -31,6 +31,7 @@ import { addWatermarkOperationConfig } from "@app/hooks/tools/addWatermark/useAdimport { addStampOperationConfig } from "@app/components/tools/addStamp/useAddStampOperation";import { addAttachmentsOperationConfig } from "@app/hooks/tools/addAttachments/useAddAttachmentsOperation";import { unlockPdfFormsOperationConfig } from "@app/hooks/tools/unlockPdfForms/useUnlockPdfFormsOperation";+import { autoFormDetectionOperationConfig } from "@app/hooks/tools/autoFormDetection/useAutoFormDetectionOperation";import { singleLargePageOperationConfig } from "@app/hooks/tools/singleLargePage/useSingleLargePageOperation";import { ocrOperationConfig } from "@app/hooks/tools/ocr/useOCROperation";import { convertOperationConfig } from "@app/hooks/tools/convert/useConvertOperation";@@ -480,6 +481,46 @@ export function useTranslatedToolCatalog(): TranslatedToolCatalog {"builder",],},+ autoFormDetection: {+ icon: (+ <LocalIcon+ icon="document-scanner-outline-rounded"+ width="1.5rem"+ height="1.5rem"+ />+ ),+ name: t("home.autoFormDetection.title", "Auto Form Detection"),+ component: lazy(+ () => import("@app/tools/autoFormDetection/AutoFormDetection"),+ ),+ description: t(+ "home.autoFormDetection.desc",+ "Automatically detect form fields with AI and make your PDF fillable.",+ ),+ categoryId: ToolCategoryId.STANDARD_TOOLS,+ subcategoryId: SubcategoryId.AUTOMATION,+ maxFiles: 1,+ endpoints: ["form-detection"],+ unavailableMessage: t(+ "home.autoFormDetection.unavailable",+ "Needs the AI detection model, which isn't installed on this server. An administrator can add it under Settings > Features > AI Form Detection.",+ ),+ operationConfig: asRegistryConfig(autoFormDetectionOperationConfig),+ synonyms: [+ "form",+ "detect",+ "fillable",+ "acroform",+ "ai",+ "fields",+ "auto",+ ],+ automationSettings: lazySettings(+ () =>+ import("@app/components/tools/autoFormDetection/AutoFormDetectionSettings"),+ ),+ supportsAutomate: true,+ },changePermissions: {icon: <LocalIcon icon="lock-outline" width="1.5rem" height="1.5rem" />,name: t("home.changePermissions.title", "Change Permissions"),diff --git a/frontend/editor/src/core/hooks/tools/autoFormDetection/useAutoFormDetectionOperation.test.ts b/frontend/editor/src/core/hooks/tools/autoFormDetection/useAutoFormDetectionOperation.test.tsnew file mode 100644index 0000000000..8454a4431c--- /dev/null+++ b/frontend/editor/src/core/hooks/tools/autoFormDetection/useAutoFormDetectionOperation.test.ts@@ -0,0 +1,96 @@+import { beforeEach, describe, expect, it, vi, type Mock } from "vitest";++vi.mock("@app/services/apiClient", () => ({+ default: { get: vi.fn(), post: vi.fn() },+}));+// Only the hook is stubbed; defineCustomTool and friends stay real so this does not break+// every time the module grows an export.+vi.mock("@app/hooks/tools/shared/useToolOperation", async (importOriginal) => ({+ ...(await importOriginal<+ typeof import("@app/hooks/tools/shared/useToolOperation")+ >()),+ useToolOperation: vi.fn(),+}));+vi.mock("react-i18next", () => ({+ useTranslation: () => ({+ t: (_key: string, fallback?: string) => fallback ?? _key,+ }),+}));++import { expectConsole } from "@app/tests/failOnConsole";+import apiClient from "@app/services/apiClient";+import { onSummary } from "@app/services/formDetection/progress";+import { autoFormDetectionOperationConfig } from "@app/hooks/tools/autoFormDetection/useAutoFormDetectionOperation";+import { defaultParameters } from "@app/hooks/tools/autoFormDetection/useAutoFormDetectionParameters";++const DETECT_ENDPOINT = "/api/v1/form/form-detection/detect";++function pdfFile(): File {+ return new File(["%PDF-1.4 dummy"], "doc.pdf", { type: "application/pdf" });+}++const SUMMARY =+ '{"total":11,"byType":{"text":8,"checkbox":3},"pagesWithFields":1}';++function respond(+ headers: Record<string, string> = { "x-stirling-detected-fields": SUMMARY },+) {+ (apiClient.post as Mock).mockResolvedValue({+ data: new Blob(["%PDF-1.4 applied"]),+ headers,+ });+}++const process = autoFormDetectionOperationConfig.customProcessor;++describe("processAutoFormDetection", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ respond();+ });++ it("asks the server to apply the fields and returns the PDF it sends back", async () => {+ const { files } = await process(defaultParameters, [pdfFile()]);++ expect(apiClient.post).toHaveBeenCalledTimes(1);+ const [url, body, config] = (apiClient.post as Mock).mock.calls[0];+ expect(url).toBe(DETECT_ENDPOINT);+ expect((body as FormData).get("applyToPdf")).toBe("true");+ expect(config).toMatchObject({ responseType: "blob" });+ expect(files[0].name).toBe("doc_form.pdf");+ expect(files[0].type).toBe("application/pdf");+ });++ it("sends the sensitivity's confidence threshold", async () => {+ await process({ ...defaultParameters, sensitivity: "low" }, [pdfFile()]);++ const body = (apiClient.post as Mock).mock.calls[0][1] as FormData;+ expect(body.get("confThreshold")).toBe("0.45");+ });++ it("publishes the summary the server reported", async () => {+ respond({ "x-stirling-detected-fields": SUMMARY });+ const seen: unknown[] = [];+ const stop = onSummary((s) => seen.push(s));++ await process(defaultParameters, [pdfFile()]);+ stop();++ expect(seen).toEqual([+ { total: 11, byType: { text: 8, checkbox: 3 }, pagesWithFields: 1 },+ ]);+ });++ it("still returns the PDF when the summary header is missing or malformed", async () => {+ expectConsole.warn(/no X-Stirling-Detected-Fields header/);+ respond({ "x-stirling-detected-fields": "not json" });+ const seen: unknown[] = [];+ const stop = onSummary((s) => seen.push(s));++ const { files } = await process(defaultParameters, [pdfFile()]);+ stop();++ expect(seen).toEqual([]);+ expect(files[0].name).toBe("doc_form.pdf");+ });+});diff --git a/frontend/editor/src/core/hooks/tools/autoFormDetection/useAutoFormDetectionOperation.ts b/frontend/editor/src/core/hooks/tools/autoFormDetection/useAutoFormDetectionOperation.tsnew file mode 100644index 0000000000..64b0d325c7--- /dev/null+++ b/frontend/editor/src/core/hooks/tools/autoFormDetection/useAutoFormDetectionOperation.ts@@ -0,0 +1,104 @@+import { useTranslation } from "react-i18next";++import {+ defineCustomTool,+ useToolOperation,+} from "@app/hooks/tools/shared/useToolOperation";+import type { ToolApiParams } from "@app/types/toolApiTypes";+import apiClient from "@app/services/apiClient";+import { createStandardErrorHandler } from "@app/utils/toolErrorHandler";+import {+ emitSummary,+ parseSummary,+} from "@app/services/formDetection/progress";+import {+ AutoFormDetectionParameters,+ defaultParameters,+ resolveConfidence,+ sensitivityFor,+} from "@app/hooks/tools/autoFormDetection/useAutoFormDetectionParameters";++const DETECT_ENDPOINT = "/api/v1/form/form-detection/detect";++export const buildAutoFormDetectionFormData = (+ parameters: AutoFormDetectionParameters,+ file: File,+): FormData => {+ const formData = new FormData();+ formData.append("file", file);+ // The server writes the AcroForm with PDFBox and reports what it added in a header, so one+ // request covers both the fillable PDF and the counts the results panel shows.+ formData.append("applyToPdf", "true");+ const confidence = resolveConfidence(parameters);+ if (typeof confidence === "number") {+ formData.append("confThreshold", String(confidence));+ }+ return formData;+};++function asPdf(data: Blob, source: File): File {+ const base = (source.name || "document").replace(/\.pdf$/i, "");+ return new File([data], `${base}_form.pdf`, { type: "application/pdf" });+}++async function processAutoFormDetection(+ parameters: AutoFormDetectionParameters,+ files: File[],+): Promise<{ files: File[] }> {+ const file = files[0];+ const res = await apiClient.post(+ DETECT_ENDPOINT,+ buildAutoFormDetectionFormData(parameters, file),+ { responseType: "blob" },+ );++ const summary = parseSummary(res.headers?.["x-stirling-detected-fields"]);+ if (summary) {+ emitSummary(summary);+ } else {+ // Not fatal - the PDF is still correct - but the results panel needs the header, so a+ // proxy that drops it would otherwise mean a silently missing summary.+ console.warn(+ "[AutoFormDetection] no X-Stirling-Detected-Fields header; skipping the results summary",+ );+ }+ return { files: [asPdf(res.data as Blob, file)] };+}++type DetectApiParams = ToolApiParams[typeof DETECT_ENDPOINT];++export const autoFormDetectionOperationConfig =+ defineCustomTool<AutoFormDetectionParameters>({+ customProcessor: processAutoFormDetection,+ operationType: "autoFormDetection",+ endpoint: DETECT_ENDPOINT,+ defaultParameters,+ // Automation runs the endpoint directly rather than through customProcessor, so the request+ // it builds comes from here. applyToPdf keeps a chained step producing a document.+ toApiParams: (parameters) => ({+ applyToPdf: true,+ confThreshold: resolveConfidence(parameters),+ }),+ fromApiParams: (api) => {+ // Narrowed to this endpoint's generated model, so a spec rename breaks the build here.+ const { confThreshold } = api as DetectApiParams;+ return {+ sensitivity: sensitivityFor(confThreshold),+ confidence: confThreshold,+ };+ },+ });++export const useAutoFormDetectionOperation = () => {+ const { t } = useTranslation();++ return useToolOperation<AutoFormDetectionParameters>({+ ...autoFormDetectionOperationConfig,+ getErrorMessage: createStandardErrorHandler(+ t(+ "autoFormDetection.error.failed",+ "An error occurred while detecting form fields.",+ ),+ ),+ });+};diff --git a/frontend/editor/src/core/hooks/tools/autoFormDetection/useAutoFormDetectionParameters.ts b/frontend/editor/src/core/hooks/tools/autoFormDetection/useAutoFormDetectionParameters.tsnew file mode 100644index 0000000000..b0cd21407b--- /dev/null+++ b/frontend/editor/src/core/hooks/tools/autoFormDetection/useAutoFormDetectionParameters.ts@@ -0,0 +1,58 @@+import { BaseParameters } from "@app/types/parameters";+import {+ useBaseParameters,+ BaseParametersHook,+} from "@app/hooks/tools/shared/useBaseParameters";++export type DetectionSensitivity = "low" | "balanced" | "high";++export interface AutoFormDetectionParameters extends BaseParameters {+ sensitivity: DetectionSensitivity;+ confidence?: number;+}++export const SENSITIVITY_CONFIDENCE: Record<+ DetectionSensitivity,+ number | undefined+> = {+ low: 0.45,+ balanced: undefined,+ high: 0.18,+};++export function resolveConfidence(+ parameters: AutoFormDetectionParameters,+): number | undefined {+ return typeof parameters.confidence === "number"+ ? parameters.confidence+ : SENSITIVITY_CONFIDENCE[parameters.sensitivity ?? "balanced"];+}++export const defaultParameters: AutoFormDetectionParameters = {+ sensitivity: "balanced",+};++/** Invert resolveConfidence, so a stored automation step reopens on the sensitivity it was saved with. */+export function sensitivityFor(+ confThreshold: number | undefined,+): DetectionSensitivity {+ if (typeof confThreshold !== "number") return "balanced";+ const match = (+ Object.entries(SENSITIVITY_CONFIDENCE) as [+ DetectionSensitivity,+ number | undefined,+ ][]+ ).find(([, value]) => value === confThreshold);+ return match ? match[0] : "balanced";+}++export type AutoFormDetectionParametersHook =+ BaseParametersHook<AutoFormDetectionParameters>;++export const useAutoFormDetectionParameters =+ (): AutoFormDetectionParametersHook => {+ return useBaseParameters({+ defaultParameters,+ endpointName: "form-detection",+ });+ };diff --git a/frontend/editor/src/core/hooks/useFormDetectionModelStatus.test.tsx b/frontend/editor/src/core/hooks/useFormDetectionModelStatus.test.tsxnew file mode 100644index 0000000000..54570d6f30--- /dev/null+++ b/frontend/editor/src/core/hooks/useFormDetectionModelStatus.test.tsx@@ -0,0 +1,78 @@+import { beforeEach, describe, expect, it, vi, type Mock } from "vitest";+import { act, render, waitFor } from "@testing-library/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";++vi.mock("@app/services/apiClient", () => ({+ default: { get: vi.fn(), post: vi.fn(), delete: vi.fn() },+}));++import apiClient from "@app/services/apiClient";+import { qk } from "@app/query/keys";+import {+ useFormDetectionModelStatus,+ type FormDetectionModelStatus,+} from "@app/hooks/useFormDetectionModelStatus";++function statusPayload(enabled: boolean): FormDetectionModelStatus {+ return {+ status: "ready",+ progress: 100,+ activeModelId: "test-model",+ installed: ["test-model"],+ error: null,+ writable: true,+ catalog: [],+ enabled,+ serverEngineAvailable: true,+ };+}++let hook: ReturnType<typeof useFormDetectionModelStatus> | null = null;++function Probe() {+ hook = useFormDetectionModelStatus();+ return (+ <span data-testid="enabled">+ {hook.status ? String(hook.status.enabled) : "loading"}+ </span>+ );+}++describe("useFormDetectionModelStatus", () => {+ beforeEach(() => {+ hook = null;+ (apiClient.get as Mock).mockReset();+ (apiClient.post as Mock).mockReset().mockResolvedValue({ data: {} });+ });++ it("refreshes the tool availability cache when the master switch flips", async () => {+ // The endpoint is re-gated server-side on toggle without the wire status changing,+ // so an effect keyed only on status would leave the tile clickable until a reload.+ (apiClient.get as Mock).mockResolvedValue({ data: statusPayload(true) });+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ const invalidate = vi.spyOn(client, "invalidateQueries");++ const el = render(+ <QueryClientProvider client={client}>+ <Probe />+ </QueryClientProvider>,+ ).getByTestId("enabled");+ await waitFor(() => expect(el.textContent).toBe("true"));++ invalidate.mockClear();+ (apiClient.get as Mock).mockResolvedValue({ data: statusPayload(false) });+ await act(async () => {+ await hook!.setConfig({ enabled: false });+ });++ await waitFor(() => expect(el.textContent).toBe("false"));+ expect(invalidate).toHaveBeenCalledWith({+ queryKey: qk.endpointsAvailability(),+ });+ expect(invalidate).toHaveBeenCalledWith({+ queryKey: qk.endpointEnabled("form-detection"),+ });+ });+});diff --git a/frontend/editor/src/core/hooks/useFormDetectionModelStatus.ts b/frontend/editor/src/core/hooks/useFormDetectionModelStatus.tsnew file mode 100644index 0000000000..8817d6143b--- /dev/null+++ b/frontend/editor/src/core/hooks/useFormDetectionModelStatus.ts@@ -0,0 +1,128 @@+import { useCallback, useEffect, useState } from "react";+import { useQueryClient } from "@tanstack/react-query";+import apiClient from "@app/services/apiClient";+import { qk } from "@app/query/keys";++export interface FormDetectionCatalogEntry {+ id: string;+ displayName: string;+ description: string;+ license: string;+ sizeBytes: number;+ onnxUrl: string;+ sha256: string;+}++export type FormDetectionState =+ | "not_installed"+ | "downloading"+ | "verifying"+ | "ready"+ | "failed";++export interface FormDetectionModelStatus {+ status: FormDetectionState;+ progress: number;+ activeModelId: string;+ installed: string[];+ error: string | null;+ writable: boolean;+ catalog: FormDetectionCatalogEntry[];+ enabled: boolean;+ serverEngineAvailable: boolean;+ downloadingModelId?: string | null;+}++const STATUS_URL = "/api/v1/form/form-detection-model/status";+const INSTALL_URL = "/api/v1/form/form-detection-model/install";+const CONFIG_URL = "/api/v1/form/form-detection-model/config";+const MODEL_URL = "/api/v1/form/form-detection-model";++/**+ * Polls model status while an install is in flight and exposes the admin actions. Readiness flips+ * invalidate the endpoint-availability cache so the tool tile enables/disables.+ */+export function useFormDetectionModelStatus() {+ const queryClient = useQueryClient();+ const [status, setStatus] = useState<FormDetectionModelStatus | null>(null);+ const [loading, setLoading] = useState(true);+ const [error, setError] = useState<string | null>(null);++ const fetchStatus = useCallback(async () => {+ try {+ const res = await apiClient.get<FormDetectionModelStatus>(STATUS_URL);+ setStatus(res.data);+ setError(null);+ } catch (e) {+ setError(e instanceof Error ? e.message : "Failed to load model status");+ } finally {+ setLoading(false);+ }+ }, []);++ useEffect(() => {+ fetchStatus();+ }, [fetchStatus]);++ const active = status?.status;+ const featureEnabled = status?.enabled;++ // Poll only while an install is in flight.+ useEffect(() => {+ if (active === "downloading" || active === "verifying") {+ const id = setInterval(fetchStatus, 1500);+ return () => clearInterval(id);+ }+ return undefined;+ }, [active, fetchStatus]);++ // Readiness and the master switch both gate the endpoint, so either flipping must refresh+ // the tool availability cache.+ useEffect(() => {+ if (active === "ready" || active === "not_installed") {+ void queryClient.invalidateQueries({+ queryKey: qk.endpointsAvailability(),+ });+ void queryClient.invalidateQueries({+ queryKey: qk.endpointEnabled("form-detection"),+ });+ }+ }, [active, featureEnabled, queryClient]);++ const install = useCallback(+ async (modelId: string) => {+ await apiClient.post(INSTALL_URL, { modelId });+ await fetchStatus();+ },+ [fetchStatus],+ );++ const uninstall = useCallback(+ async (modelId?: string) => {+ const url = modelId+ ? `${MODEL_URL}?modelId=${encodeURIComponent(modelId)}`+ : MODEL_URL;+ await apiClient.delete(url);+ await fetchStatus();+ },+ [fetchStatus],+ );++ const setConfig = useCallback(+ async (config: { enabled?: boolean }) => {+ await apiClient.post(CONFIG_URL, config);+ await fetchStatus();+ },+ [fetchStatus],+ );++ return {+ status,+ loading,+ error,+ refetch: fetchStatus,+ install,+ uninstall,+ setConfig,+ };+}diff --git a/frontend/editor/src/core/services/formDetection/progress.ts b/frontend/editor/src/core/services/formDetection/progress.tsnew file mode 100644index 0000000000..9c200c4c8a--- /dev/null+++ b/frontend/editor/src/core/services/formDetection/progress.ts@@ -0,0 +1,34 @@+export interface DetectionSummary {+ total: number;+ byType: Record<string, number>;+ pagesWithFields: number;+}++const SUMMARY_EVENT = "stirling:form-detection:summary";++export function emitSummary(summary: DetectionSummary): void {+ window.dispatchEvent(new CustomEvent(SUMMARY_EVENT, { detail: summary }));+}++export function onSummary(cb: (s: DetectionSummary) => void): () => void {+ const handler = (e: Event) =>+ cb((e as CustomEvent).detail as DetectionSummary);+ window.addEventListener(SUMMARY_EVENT, handler);+ return () => window.removeEventListener(SUMMARY_EVENT, handler);+}++/** Parse the server's X-Stirling-Detected-Fields header; a missing or bad one shows nothing. */+export function parseSummary(header: unknown): DetectionSummary | null {+ if (typeof header !== "string" || header.length === 0) return null;+ try {+ const raw = JSON.parse(header) as Partial<DetectionSummary>;+ if (typeof raw.total !== "number") return null;+ return {+ total: raw.total,+ byType: raw.byType ?? {},+ pagesWithFields: raw.pagesWithFields ?? 0,+ };+ } catch {+ return null;+ }+}diff --git a/frontend/editor/src/core/tests/stubbed/auto-form-detection-walkthrough.spec.ts b/frontend/editor/src/core/tests/stubbed/auto-form-detection-walkthrough.spec.tsnew file mode 100644index 0000000000..c268f8d134--- /dev/null+++ b/frontend/editor/src/core/tests/stubbed/auto-form-detection-walkthrough.spec.ts@@ -0,0 +1,443 @@+import { test, expect } from "@app/tests/helpers/stub-test-base";+import { uploadFiles } from "@app/tests/helpers/ui-helpers";+import type { Page, Route } from "@playwright/test";+import path from "node:path";+import fs from "node:fs";++/** Walkthrough capture for the Auto Form Detection feature. Not for CI. */++test.skip(!!process.env.CI, "capture-only spec; not for CI");++const SHOT_DIR =+ process.env.SHOT_DIR ??+ path.join(import.meta.dirname, "../../../../screenshots/auto-form-detection");++const SAMPLE_PDF = path.join(+ import.meta.dirname,+ "../test-fixtures/sample.pdf",+);++function shot(name: string): string {+ fs.mkdirSync(SHOT_DIR, { recursive: true });+ return path.join(SHOT_DIR, `${name}.png`);+}++const CATALOG = [+ {+ id: "ffdnet-s",+ displayName: "CommonForms FFDNet-S (Small)",+ description:+ "Small, fast detector with lower memory use - a good default for most forms. Finds text inputs, checkboxes, and signature fields.",+ license:+ "CommonForms dataset CC-BY-4.0; Ultralytics-YOLO lineage AGPL-3.0. Downloaded on demand, never bundled.",+ sizeBytes: 38370092,+ onnxUrl:+ "https://huggingface.co/jbarrow/FFDNet-S-cpu/resolve/main/FFDNet-S.onnx",+ sha256: "93bccf47c048f9f947f9b1b52d002edf144a8a583dae39f164d9e5725321acc0",+ },+ {+ id: "ffdnet-l",+ displayName: "CommonForms FFDNet-L (Large)",+ description:+ "Larger, higher-accuracy detector (~25M parameters) with better recall on dense or complex forms - uses more memory. Finds text inputs, checkboxes, and signature fields.",+ license:+ "CommonForms dataset CC-BY-4.0; Ultralytics-YOLO lineage AGPL-3.0. Downloaded on demand, never bundled.",+ sizeBytes: 101944542,+ onnxUrl:+ "https://huggingface.co/jbarrow/FFDNet-L-cpu/resolve/main/FFDNet-L.onnx",+ sha256: "e00c59edd9a5275dab5847d38f042c8ecc827063650c8aac22b0e486c414cd35",+ },+];++function modelStatus(overrides: Record<string, unknown> = {}) {+ return {+ status: "ready",+ progress: 100,+ activeModelId: "ffdnet-s",+ installed: ["ffdnet-s"],+ error: null,+ writable: true,+ catalog: CATALOG,+ enabled: true,+ serverEngineAvailable: true,+ downloadingModelId: null,+ ...overrides,+ };+}++async function stubStatus(page: Page, overrides: Record<string, unknown> = {}) {+ await page.route("**/api/v1/form/form-detection-model/status", (r: Route) =>+ r.fulfill({ json: modelStatus(overrides) }),+ );+}++const DETECTIONS = [+ ...[0, 1, 2, 3, 4].map((i) => ({+ type: "text",+ page: 0,+ rectInPdfPoints: { x: 90, y: 620 - i * 40, w: 220, h: 22 },+ confidence: 0.92 - i * 0.05,+ })),+ ...[0, 1, 2].map((i) => ({+ type: "checkbox",+ page: 0,+ rectInPdfPoints: { x: 90, y: 420 - i * 30, w: 16, h: 16 },+ confidence: 0.88 - i * 0.06,+ })),+ ...[0, 1, 2].map((i) => ({+ type: "text",+ page: 1,+ rectInPdfPoints: { x: 90, y: 600 - i * 40, w: 220, h: 22 },+ confidence: 0.8 - i * 0.05,+ })),+ {+ type: "signature",+ page: 1,+ rectInPdfPoints: { x: 90, y: 160, w: 220, h: 48 },+ confidence: 0.74,+ },+];++async function stubDetect(+ page: Page,+ opts: { delayMs?: number; detections?: unknown[] } = {},+) {+ const pdf = fs.readFileSync(SAMPLE_PDF);+ const detections = opts.detections ?? DETECTIONS;+ await page.route("**/api/v1/form/form-detection/detect", async (r: Route) => {+ if (opts.delayMs) await new Promise((res) => setTimeout(res, opts.delayMs));+ const body = r.request().postData() ?? "";+ if (body.includes("applyToPdf") && body.includes("true")) {+ await r.fulfill({+ status: 200,+ contentType: "application/pdf",+ body: pdf,+ });+ } else {+ await r.fulfill({ json: { detections } });+ }+ });+}++async function settle(page: Page, ms = 700) {+ await page.waitForTimeout(ms);+}++type Theme = "light" | "dark";++async function applyTheme(page: Page, theme: Theme) {+ if (theme !== "dark") return;+ await page.addInitScript(() => {+ localStorage.setItem("mantine-color-scheme", "dark");+ localStorage.setItem("mantine-color-scheme-value", "dark");+ });+ await page.emulateMedia({ colorScheme: "dark" });+}++async function enableRtl(page: Page) {+ await page.addInitScript(() => {+ localStorage.setItem("i18nextLng", "ar-AR");+ localStorage.setItem("i18nextLng-source", "3");+ const applyDir = () => {+ document.documentElement.setAttribute("dir", "rtl");+ document.documentElement.setAttribute("lang", "ar-AR");+ };+ if (document.documentElement) applyDir();+ else document.addEventListener("DOMContentLoaded", applyDir);+ });+}++const panel = (page: Page) => page.locator('[data-tour="tool-panel"]');++async function gotoTool(page: Page) {+ await page.goto("/auto-form-detection", { waitUntil: "domcontentloaded" });+ await expect(page.locator('[data-tour="run-button"]')).toBeVisible({+ timeout: 15_000,+ });+}++async function runToResults(page: Page) {+ await uploadFiles(page, SAMPLE_PDF);+ await page.locator('[data-tour="run-button"]').click();+ await expect(+ page.getByText(/Detection results|Review fillable/i).first(),+ ).toBeVisible({ timeout: 30_000 });+ await settle(page, 1_200);+}++test.use({ autoGoto: false });++const THEMES: Theme[] = ["light", "dark"];++for (const theme of THEMES) {+ test(`01_tool_tile_${theme}`, async ({ page }) => {+ await applyTheme(page, theme);+ await stubStatus(page);+ await page.goto("/", { waitUntil: "domcontentloaded" });+ const tile = page+ .locator('[data-tour="tool-button-autoFormDetection"]')+ .first();+ await expect(tile).toBeVisible({ timeout: 15_000 });+ await tile.scrollIntoViewIfNeeded();+ await settle(page);+ await panel(page).screenshot({ path: shot(`01_tool_tile_${theme}`) });+ });++ test(`02_panel_empty_${theme}`, async ({ page }) => {+ await applyTheme(page, theme);+ await stubStatus(page);+ await gotoTool(page);+ await settle(page);+ await panel(page).screenshot({ path: shot(`02_panel_empty_${theme}`) });+ });++ test(`03_panel_settings_${theme}`, async ({ page }) => {+ await applyTheme(page, theme);+ await stubStatus(page);+ await gotoTool(page);+ await uploadFiles(page, SAMPLE_PDF);+ await settle(page);+ await panel(page).screenshot({ path: shot(`03_panel_settings_${theme}`) });+ });++ test(`04_running_${theme}`, async ({ page }) => {+ await applyTheme(page, theme);+ await stubStatus(page, { activeModelId: "", installed: [] });+ await stubDetect(page, { delayMs: 15_000 });+ await gotoTool(page);+ await uploadFiles(page, SAMPLE_PDF);+ await page.locator('[data-tour="run-button"]').click();+ await page.waitForTimeout(2_500);+ await panel(page).screenshot({ path: shot(`04_running_${theme}`) });+ });++ test(`05_results_${theme}`, async ({ page }) => {+ await applyTheme(page, theme);+ await stubStatus(page, { activeModelId: "", installed: [] });+ await stubDetect(page);+ await gotoTool(page);+ await runToResults(page);+ await panel(page).screenshot({ path: shot(`05_results_${theme}`) });+ });++ test(`06_results_empty_${theme}`, async ({ page }) => {+ await applyTheme(page, theme);+ await stubStatus(page, { activeModelId: "", installed: [] });+ await stubDetect(page, { detections: [] });+ await gotoTool(page);+ await uploadFiles(page, SAMPLE_PDF);+ await page.locator('[data-tour="run-button"]').click();+ await expect(+ page.getByText(/No form fields found|Review fillable/i).first(),+ ).toBeVisible({ timeout: 30_000 });+ await settle(page, 1_200);+ await panel(page).screenshot({ path: shot(`06_results_empty_${theme}`) });+ });++ test(`07_tile_disabled_${theme}`, async ({ page }) => {+ await applyTheme(page, theme);+ await stubStatus(page, {+ status: "not_installed",+ activeModelId: "",+ installed: [],+ });+ const disabledMap = {+ "form-detection": { enabled: false, reason: "DEPENDENCY" },+ };+ await page.route("**/api/v1/config/endpoints-availability", (r: Route) =>+ r.fulfill({ json: disabledMap }),+ );+ await page.route("**/api/v1/config/endpoints-enabled", (r: Route) =>+ r.fulfill({ json: disabledMap }),+ );+ await page.goto("/", { waitUntil: "domcontentloaded" });+ const tile = page+ .locator('[data-tour="tool-button-autoFormDetection"]')+ .first();+ await expect(tile).toBeVisible({ timeout: 15_000 });+ await tile.scrollIntoViewIfNeeded();+ await settle(page);+ await tile.hover();+ await expect(+ page.getByText(/Needs the AI detection model/i).first(),+ ).toBeVisible({ timeout: 5_000 });+ await settle(page, 400);+ const vp = page.viewportSize() ?? { width: 1920, height: 1080 };+ await page.screenshot({+ path: shot(`07_tile_disabled_${theme}`),+ clip: { x: vp.width - 1150, y: 0, width: 1150, height: 700 },+ });+ });+}++const adminUse = {+ stubOptions: {+ enableLogin: true,+ isAdmin: true,+ user: {+ id: 1,+ username: "admin",+ email: "[email protected]",+ roles: ["ROLE_ADMIN"],+ },+ },+ seedJwt: true,+ autoGoto: false as const,+};++async function openFormDetectionSettings(page: Page) {+ await page.route("**/api/v1/proprietary/ui-data/account", (r: Route) =>+ r.fulfill({+ json: { username: "admin", email: "[email protected]", isAdmin: true },+ }),+ );+ await page.goto("/", { waitUntil: "domcontentloaded" });+ const configBtn = page.locator('[data-testid="config-button"]').first();+ await expect(configBtn).toBeVisible({ timeout: 15_000 });+ await configBtn.click();+ const dialog = page.locator(".mantine-Modal-content").first();+ await expect(dialog).toBeVisible({ timeout: 5_000 });+ await dialog+ .getByText(/^(Features|الميزات)$/)+ .first()+ .click();+ await expect(dialog.getByText(/AI Form Detection/i).first()).toBeVisible({+ timeout: 5_000,+ });+ return dialog;+}++async function shootCard(+ page: Page,+ dialog: ReturnType<Page["locator"]>,+ name: string,+) {+ const paper = dialog+ .locator(".mantine-Paper-root")+ .filter({ hasText: "AI Form Detection" })+ .last();+ await paper.scrollIntoViewIfNeeded();+ await settle(page);+ await paper.screenshot({ path: shot(name) });+}++test.describe("admin", () => {+ test.use(adminUse);++ for (const theme of THEMES) {+ test(`08_admin_ready_${theme}`, async ({ page }) => {+ await applyTheme(page, theme);+ await stubStatus(page);+ const dialog = await openFormDetectionSettings(page);+ await shootCard(page, dialog, `08_admin_ready_${theme}`);+ });++ test(`09_admin_not_installed_${theme}`, async ({ page }) => {+ await applyTheme(page, theme);+ await stubStatus(page, {+ status: "not_installed",+ activeModelId: "",+ installed: [],+ progress: 0,+ });+ const dialog = await openFormDetectionSettings(page);+ await shootCard(page, dialog, `09_admin_not_installed_${theme}`);+ });++ test(`10_admin_downloading_${theme}`, async ({ page }) => {+ await applyTheme(page, theme);+ await stubStatus(page, {+ status: "downloading",+ activeModelId: "",+ installed: [],+ progress: 42,+ downloadingModelId: "ffdnet-s",+ });+ const dialog = await openFormDetectionSettings(page);+ await shootCard(page, dialog, `10_admin_downloading_${theme}`);+ });++ test(`11_admin_failed_${theme}`, async ({ page }) => {+ await applyTheme(page, theme);+ await stubStatus(page, {+ status: "failed",+ activeModelId: "",+ installed: [],+ error: "Model checksum mismatch (expected 93bccf..., got a1b2c3...)",+ });+ const dialog = await openFormDetectionSettings(page);+ await shootCard(page, dialog, `11_admin_failed_${theme}`);+ });++ test(`12_admin_two_installed_${theme}`, async ({ page }) => {+ await applyTheme(page, theme);+ await stubStatus(page, { installed: ["ffdnet-s", "ffdnet-l"] });+ const dialog = await openFormDetectionSettings(page);+ await shootCard(page, dialog, `12_admin_two_installed_${theme}`);+ });++ test(`13_admin_airgap_${theme}`, async ({ page }) => {+ await applyTheme(page, theme);+ await stubStatus(page);+ const dialog = await openFormDetectionSettings(page);+ const toggle = dialog.getByText(/Offline \/ air-gapped install/i).first();+ await toggle.scrollIntoViewIfNeeded();+ await toggle.click();+ await settle(page);+ const section = dialog.locator(".sui-collapsible").first();+ await section.scrollIntoViewIfNeeded();+ await settle(page);+ await section.screenshot({ path: shot(`13_admin_airgap_${theme}`) });+ });++ test(`14_admin_server_unavailable_${theme}`, async ({ page }) => {+ await applyTheme(page, theme);+ await stubStatus(page, { serverEngineAvailable: false });+ const dialog = await openFormDetectionSettings(page);+ await shootCard(page, dialog, `14_admin_server_unavailable_${theme}`);+ });+ }+});++test.describe("rtl tool", () => {+ test.use({ stubOptions: { languages: ["en-US", "ar-AR"] } });++ for (const theme of THEMES) {+ test(`15_rtl_panel_settings_${theme}`, async ({ page }) => {+ await applyTheme(page, theme);+ await enableRtl(page);+ await stubStatus(page);+ await page.goto("/auto-form-detection", {+ waitUntil: "domcontentloaded",+ });+ await expect(page.locator('[data-tour="run-button"]')).toBeVisible({+ timeout: 15_000,+ });+ await uploadFiles(page, SAMPLE_PDF);+ await settle(page);+ await panel(page).screenshot({+ path: shot(`15_rtl_panel_settings_${theme}`),+ });+ });+ }+});++test.describe("rtl admin", () => {+ test.use({+ ...adminUse,+ stubOptions: {+ ...adminUse.stubOptions,+ languages: ["en-US", "ar-AR"],+ },+ });++ for (const theme of THEMES) {+ test(`16_rtl_admin_ready_${theme}`, async ({ page }) => {+ await applyTheme(page, theme);+ await enableRtl(page);+ await stubStatus(page);+ const dialog = await openFormDetectionSettings(page);+ await shootCard(page, dialog, `16_rtl_admin_ready_${theme}`);+ });+ }+});diff --git a/frontend/editor/src/core/tests/stubbed/auto-form-detection.spec.ts b/frontend/editor/src/core/tests/stubbed/auto-form-detection.spec.tsnew file mode 100644index 0000000000..74fd7f23b2--- /dev/null+++ b/frontend/editor/src/core/tests/stubbed/auto-form-detection.spec.ts@@ -0,0 +1,120 @@+import { test, expect, type Page } from "@playwright/test";+import {+ bypassOnboarding,+ mockAppApis,+ seedCookieConsent,+} from "@app/tests/helpers/api-stubs";++/**+ * Stubbed coverage for the tool tile (shown even when the endpoint is disabled, so the tool stays+ * discoverable), opening it once enabled, and the admin install panel.+ */++const MODEL_STATUS_NOT_INSTALLED = {+ status: "not_installed",+ progress: 0,+ activeModelId: "",+ installed: [],+ error: null,+ writable: true,+ catalog: [+ {+ id: "ffdnet-s",+ displayName: "CommonForms FFDNet-S",+ description: "Small form-field detector",+ license: "CC-BY-4.0",+ sizeBytes: 0,+ onnxUrl: "",+ sha256: "",+ },+ ],+};++async function stubModelStatus(page: Page) {+ await page.route("**/api/v1/form/form-detection-model/status", (route) =>+ route.fulfill({ json: MODEL_STATUS_NOT_INSTALLED }),+ );+}++test.describe("Auto Form Detection tool", () => {+ test("tile is present even when the model endpoint is disabled", async ({+ page,+ }) => {+ await seedCookieConsent(page);+ await bypassOnboarding(page);+ await stubModelStatus(page);+ await mockAppApis(page, {+ endpointsAvailability: { "form-detection": { enabled: false } },+ });+ await page.goto("/");++ const tile = page.locator('[data-tour="tool-button-autoFormDetection"]');+ await expect(tile.first()).toBeVisible({ timeout: 10_000 });+ });++ test("clicking the tile opens the tool when the endpoint is enabled", async ({+ page,+ }) => {+ await seedCookieConsent(page);+ await bypassOnboarding(page);+ await stubModelStatus(page);+ await mockAppApis(page, {+ endpointsAvailability: { "form-detection": { enabled: true } },+ });+ await page.goto("/");++ await page+ .locator('[data-tour="tool-button-autoFormDetection"]')+ .first()+ .click();+ await expect(page).toHaveURL(/auto-form-detection/i);+ });++ test("admin sees the AI Form Detection box inside the Features section", async ({+ page,+ }) => {+ await seedCookieConsent(page);+ await bypassOnboarding(page);+ // Seed JWT so the auth-gated dashboard chrome renders for the admin user.+ await page.addInitScript(() => {+ localStorage.setItem(+ "stirling_jwt",+ "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJhZG1pbiJ9.signature",+ );+ });+ await stubModelStatus(page);+ await mockAppApis(page, {+ enableLogin: true,+ isAdmin: true,+ user: {+ id: 1,+ username: "admin",+ email: "[email protected]",+ roles: ["ROLE_ADMIN"],+ },+ });+ await page.route("**/api/v1/proprietary/ui-data/account", (route) =>+ route.fulfill({+ json: { username: "admin", email: "[email protected]", isAdmin: true },+ }),+ );+ await page.goto("/");++ const configBtn = page.locator('[data-testid="config-button"]').first();+ if (!(await configBtn.isVisible({ timeout: 5_000 }).catch(() => false))) {+ test.skip(true, "Config button not rendered for admin on this build");+ return;+ }+ await configBtn.click();+ const dialog = page.locator(".mantine-Modal-content").first();+ await expect(dialog).toBeVisible({ timeout: 5_000 });++ // AI Form Detection now lives as a box inside the "Features" section,+ // not as its own nav entry - navigate there first.+ await dialog.getByText("Features", { exact: true }).first().click();++ await expect(dialog.getByText(/AI Form Detection/i).first()).toBeVisible({+ timeout: 5_000,+ });+ });+});diff --git a/frontend/editor/src/core/tests/stubbed/ui-review-capture.spec.ts b/frontend/editor/src/core/tests/stubbed/ui-review-capture.spec.tsnew file mode 100644index 0000000000..d991297daa--- /dev/null+++ b/frontend/editor/src/core/tests/stubbed/ui-review-capture.spec.ts@@ -0,0 +1,423 @@+import { test, expect } from "@app/tests/helpers/stub-test-base";+import { uploadFiles } from "@app/tests/helpers/ui-helpers";+import type { Page, Route } from "@playwright/test";+import path from "node:path";+import fs from "node:fs";++/**+ * TEMPORARY capture spec for the Auto Form Detection UI review.+ * Dumps PNGs of every tool/admin state into SHOT_DIR (env). Not for CI.+ */++test.skip(!!process.env.CI, "capture-only spec; not for CI");++const SHOT_DIR =+ process.env.SHOT_DIR ??+ path.join(import.meta.dirname, "../../../../screenshots/ui-review");++const SAMPLE_PDF = path.join(+ import.meta.dirname,+ "../test-fixtures/sample.pdf",+);++function shot(name: string): string {+ fs.mkdirSync(SHOT_DIR, { recursive: true });+ return path.join(SHOT_DIR, `${name}.png`);+}++const CATALOG = [+ {+ id: "ffdnet-s",+ displayName: "CommonForms FFDNet-S (Small)",+ description:+ "Small, fast detector with lower memory use - a good default for most forms. Finds text inputs, checkboxes, and signature fields.",+ license:+ "CommonForms dataset CC-BY-4.0; Ultralytics-YOLO lineage AGPL-3.0. Downloaded on demand, never bundled.",+ sizeBytes: 38370092,+ onnxUrl:+ "https://huggingface.co/jbarrow/FFDNet-S-cpu/resolve/main/FFDNet-S.onnx",+ sha256: "93bccf47c048f9f947f9b1b52d002edf144a8a583dae39f164d9e5725321acc0",+ },+ {+ id: "ffdnet-l",+ displayName: "CommonForms FFDNet-L (Large)",+ description:+ "Larger, higher-accuracy detector (~25M parameters) with better recall on dense or complex forms - uses more memory. Finds text inputs, checkboxes, and signature fields.",+ license:+ "CommonForms dataset CC-BY-4.0; Ultralytics-YOLO lineage AGPL-3.0. Downloaded on demand, never bundled.",+ sizeBytes: 101944542,+ onnxUrl:+ "https://huggingface.co/jbarrow/FFDNet-L-cpu/resolve/main/FFDNet-L.onnx",+ sha256: "e00c59edd9a5275dab5847d38f042c8ecc827063650c8aac22b0e486c414cd35",+ },+];++type StatusOverrides = Record<string, unknown>;++function modelStatus(overrides: StatusOverrides = {}) {+ return {+ status: "ready",+ progress: 100,+ activeModelId: "ffdnet-s",+ installed: ["ffdnet-s"],+ error: null,+ writable: true,+ catalog: CATALOG,+ enabled: true,+ serverEngineAvailable: true,+ ...overrides,+ };+}++async function stubStatus(page: Page, overrides: StatusOverrides = {}) {+ await page.route("**/api/v1/form/form-detection-model/status", (r: Route) =>+ r.fulfill({ json: modelStatus(overrides) }),+ );+}++/**+ * Stub the detect endpoint: JSON detections for applyToPdf=false so the summary panel and the+ * pdf-lib apply path run for real, a PDF blob otherwise.+ */+async function stubDetect(page: Page, delayMs = 0) {+ const pdf = fs.readFileSync(SAMPLE_PDF);+ const detections = [+ // page 0: text rows + checkboxes + a signature+ ...[0, 1, 2, 3, 4].map((i) => ({+ type: "text",+ page: 0,+ rectInPdfPoints: { x: 90, y: 620 - i * 40, w: 220, h: 22 },+ confidence: 0.92 - i * 0.05,+ })),+ ...[0, 1, 2].map((i) => ({+ type: "checkbox",+ page: 0,+ rectInPdfPoints: { x: 90, y: 420 - i * 30, w: 16, h: 16 },+ confidence: 0.88 - i * 0.06,+ })),+ ...[0, 1, 2].map((i) => ({+ type: "text",+ page: 1,+ rectInPdfPoints: { x: 90, y: 600 - i * 40, w: 220, h: 22 },+ confidence: 0.8 - i * 0.05,+ })),+ {+ type: "signature",+ page: 1,+ rectInPdfPoints: { x: 90, y: 160, w: 220, h: 48 },+ confidence: 0.74,+ },+ ];+ await page.route("**/api/v1/form/form-detection/detect", async (r: Route) => {+ if (delayMs) await new Promise((res) => setTimeout(res, delayMs));+ const body = r.request().postData() ?? "";+ if (body.includes("applyToPdf") && body.includes("true")) {+ await r.fulfill({+ status: 200,+ contentType: "application/pdf",+ body: pdf,+ });+ } else {+ await r.fulfill({ json: { detections } });+ }+ });+}++async function uploadSample(page: Page) {+ await uploadFiles(page, SAMPLE_PDF);+}++async function settle(page: Page, ms = 700) {+ await page.waitForTimeout(ms);+}++async function darkMode(page: Page) {+ await page.addInitScript(() => {+ localStorage.setItem("mantine-color-scheme", "dark");+ localStorage.setItem("mantine-color-scheme-value", "dark");+ });+ await page.emulateMedia({ colorScheme: "dark" });+}++const panel = (page: Page) => page.locator('[data-tour="tool-panel"]');++test.use({ autoGoto: false });++test("tool-01-home-tile", async ({ page }) => {+ await stubStatus(page);+ await page.goto("/", { waitUntil: "domcontentloaded" });+ const tile = page+ .locator('[data-tour="tool-button-autoFormDetection"]')+ .first();+ await expect(tile).toBeVisible({ timeout: 15_000 });+ await tile.scrollIntoViewIfNeeded();+ await settle(page);+ await panel(page).screenshot({ path: shot("tool-01-home-tile") });+ await tile.screenshot({ path: shot("tool-01b-tile-closeup") });+});++test("tool-02-panel-empty", async ({ page }) => {+ await stubStatus(page);+ await page.goto("/auto-form-detection", { waitUntil: "domcontentloaded" });+ await expect(page.locator('[data-tour="run-button"]')).toBeVisible({+ timeout: 15_000,+ });+ await settle(page);+ await panel(page).screenshot({ path: shot("tool-02-panel-empty") });+});++test("tool-03-panel-file", async ({ page }) => {+ await stubStatus(page);+ await page.goto("/auto-form-detection", { waitUntil: "domcontentloaded" });+ await expect(page.locator('[data-tour="run-button"]')).toBeVisible({+ timeout: 15_000,+ });+ await uploadSample(page);+ await settle(page);+ await panel(page).screenshot({ path: shot("tool-03-panel-file") });+ await page.screenshot({ path: shot("tool-03b-full-page") });+});++test("tool-04-running", async ({ page }) => {+ // No active model -> server path; slow response so the loading state is visible.+ await stubStatus(page, { status: "ready", activeModelId: "", installed: [] });+ await stubDetect(page, 15_000);+ await page.goto("/auto-form-detection", { waitUntil: "domcontentloaded" });+ await expect(page.locator('[data-tour="run-button"]')).toBeVisible({+ timeout: 15_000,+ });+ await uploadSample(page);+ await page.locator('[data-tour="run-button"]').click();+ await page.waitForTimeout(2_500);+ await panel(page).screenshot({ path: shot("tool-04-running") });+});++test("tool-05-results", async ({ page }) => {+ await stubStatus(page, { status: "ready", activeModelId: "", installed: [] });+ await stubDetect(page);+ await page.goto("/auto-form-detection", { waitUntil: "domcontentloaded" });+ await expect(page.locator('[data-tour="run-button"]')).toBeVisible({+ timeout: 15_000,+ });+ await uploadSample(page);+ await page.locator('[data-tour="run-button"]').click();+ await expect(+ page+ .getByText(+ /Detection results|Review fillable|Detected Form Fields|Review/i,+ )+ .first(),+ ).toBeVisible({ timeout: 30_000 });+ await settle(page, 1_200);+ await panel(page).screenshot({ path: shot("tool-05-results") });+});++test("tool-06-endpoint-disabled", async ({ page }) => {+ await stubStatus(page, {+ status: "not_installed",+ activeModelId: "",+ installed: [],+ });+ const disabledMap = {+ "form-detection": { enabled: false, reason: "DEPENDENCY" },+ };+ await page.route("**/api/v1/config/endpoints-availability", (r: Route) =>+ r.fulfill({ json: disabledMap }),+ );+ await page.route("**/api/v1/config/endpoints-enabled", (r: Route) =>+ r.fulfill({ json: disabledMap }),+ );+ await page.goto("/", { waitUntil: "domcontentloaded" });+ const tile = page+ .locator('[data-tour="tool-button-autoFormDetection"]')+ .first();+ await expect(tile).toBeVisible({ timeout: 15_000 });+ await tile.scrollIntoViewIfNeeded();+ await settle(page);+ await tile.hover();+ await expect(+ page+ .getByText(/Needs the AI detection model|missing on server|Unavailable/i)+ .first(),+ ).toBeVisible({ timeout: 5_000 });+ await settle(page, 400);+ const vp = page.viewportSize() ?? { width: 1920, height: 1080 };+ await page.screenshot({+ path: shot("tool-06-endpoint-disabled"),+ clip: { x: vp.width - 1150, y: 0, width: 1150, height: 700 },+ });+});++test("tool-07-dark-panel-file", async ({ page }) => {+ await darkMode(page);+ await stubStatus(page);+ await page.goto("/auto-form-detection", { waitUntil: "domcontentloaded" });+ await expect(page.locator('[data-tour="run-button"]')).toBeVisible({+ timeout: 15_000,+ });+ await uploadSample(page);+ await settle(page);+ await panel(page).screenshot({ path: shot("tool-07-dark-panel-file") });+});++test("tool-08-dark-results", async ({ page }) => {+ await darkMode(page);+ await stubStatus(page, { status: "ready", activeModelId: "", installed: [] });+ await stubDetect(page);+ await page.goto("/auto-form-detection", { waitUntil: "domcontentloaded" });+ await expect(page.locator('[data-tour="run-button"]')).toBeVisible({+ timeout: 15_000,+ });+ await uploadSample(page);+ await page.locator('[data-tour="run-button"]').click();+ await expect(+ page+ .getByText(+ /Detection results|Review fillable|Detected Form Fields|Review/i,+ )+ .first(),+ ).toBeVisible({ timeout: 30_000 });+ await settle(page, 1_200);+ await panel(page).screenshot({ path: shot("tool-08-dark-results") });+});++const adminUse = {+ stubOptions: {+ enableLogin: true,+ isAdmin: true,+ user: {+ id: 1,+ username: "admin",+ email: "[email protected]",+ roles: ["ROLE_ADMIN"],+ },+ },+ seedJwt: true,+ autoGoto: false as const,+};++async function openFormDetectionSettings(page: Page) {+ await page.route("**/api/v1/proprietary/ui-data/account", (r: Route) =>+ r.fulfill({+ json: { username: "admin", email: "[email protected]", isAdmin: true },+ }),+ );+ await page.goto("/", { waitUntil: "domcontentloaded" });+ const configBtn = page.locator('[data-testid="config-button"]').first();+ await expect(configBtn).toBeVisible({ timeout: 15_000 });+ await configBtn.click();+ const dialog = page.locator(".mantine-Modal-content").first();+ await expect(dialog).toBeVisible({ timeout: 5_000 });+ await dialog.getByText("Features", { exact: true }).first().click();+ await expect(dialog.getByText(/AI Form Detection/i).first()).toBeVisible({+ timeout: 5_000,+ });+ // The form-detection card is the Paper containing the title text.+ const card = dialog+ .locator("div")+ .filter({ has: page.getByText(/AI Form Detection/i) });+ return { dialog, card };+}++/** Screenshot the settings card (ancestor Paper of the section title). */+async function shootCard(+ page: Page,+ dialog: ReturnType<Page["locator"]>,+ name: string,+) {+ const paper = dialog+ .locator(".mantine-Paper-root")+ .filter({ hasText: "AI Form Detection" })+ .last();+ await paper.scrollIntoViewIfNeeded();+ await settle(page);+ await paper.screenshot({ path: shot(name) });+}++test.describe("admin", () => {+ test.use(adminUse);++ test("admin-01-ready", async ({ page }) => {+ await stubStatus(page);+ const { dialog } = await openFormDetectionSettings(page);+ await shootCard(page, dialog, "admin-01-ready");+ await dialog.screenshot({ path: shot("admin-01b-dialog") });+ });++ test("admin-02-not-installed", async ({ page }) => {+ await stubStatus(page, {+ status: "not_installed",+ activeModelId: "",+ installed: [],+ progress: 0,+ });+ const { dialog } = await openFormDetectionSettings(page);+ await shootCard(page, dialog, "admin-02-not-installed");+ });++ test("admin-03-downloading", async ({ page }) => {+ await stubStatus(page, {+ status: "downloading",+ activeModelId: "",+ installed: [],+ progress: 42,+ downloadingModelId: "ffdnet-s",+ });+ const { dialog } = await openFormDetectionSettings(page);+ await shootCard(page, dialog, "admin-03-downloading");+ });++ test("admin-04-airgap-open", async ({ page }) => {+ // The expanded instructions run ~1400px tall; a taller viewport keeps the+ // modal scrollport from clipping the element screenshot.+ await page.setViewportSize({ width: 1920, height: 1900 });+ await stubStatus(page);+ const { dialog } = await openFormDetectionSettings(page);+ const toggle = dialog.getByText(/Air-gapped|offline install/i).first();+ if (await toggle.isVisible({ timeout: 3_000 }).catch(() => false)) {+ await toggle.click();+ await settle(page);+ }+ // The expanded card is taller than the modal scrollport; shoot the section itself.+ const section = dialog.locator(".sui-collapsible").first();+ if (await section.isVisible({ timeout: 2_000 }).catch(() => false)) {+ await section.scrollIntoViewIfNeeded();+ await settle(page);+ await section.screenshot({ path: shot("admin-04-airgap-open") });+ } else {+ await shootCard(page, dialog, "admin-04-airgap-open");+ }+ });++ test("admin-05-server-unavailable", async ({ page }) => {+ await stubStatus(page, {+ serverEngineAvailable: false,+ });+ const { dialog } = await openFormDetectionSettings(page);+ await shootCard(page, dialog, "admin-05-server-unavailable");+ });++ test("admin-06-failed", async ({ page }) => {+ await stubStatus(page, {+ status: "failed",+ activeModelId: "",+ installed: [],+ error: "Model checksum mismatch (expected 93bccf..., got a1b2c3...)",+ });+ const { dialog } = await openFormDetectionSettings(page);+ await shootCard(page, dialog, "admin-06-failed");+ });++ test("admin-07-dark-ready", async ({ page }) => {+ await darkMode(page);+ await stubStatus(page);+ const { dialog } = await openFormDetectionSettings(page);+ await shootCard(page, dialog, "admin-07-dark-ready");+ });++ test("admin-08-two-installed", async ({ page }) => {+ await stubStatus(page, { installed: ["ffdnet-s", "ffdnet-l"] });+ const { dialog } = await openFormDetectionSettings(page);+ await shootCard(page, dialog, "admin-08-two-installed");+ });+});diff --git a/frontend/editor/src/core/tools/autoFormDetection/AutoFormDetection.tsx b/frontend/editor/src/core/tools/autoFormDetection/AutoFormDetection.tsxnew file mode 100644index 0000000000..589d0d3860--- /dev/null+++ b/frontend/editor/src/core/tools/autoFormDetection/AutoFormDetection.tsx@@ -0,0 +1,80 @@+import { useEffect, useState } from "react";+import { useTranslation } from "react-i18next";+import { createToolFlow } from "@app/components/tools/shared/createToolFlow";+import { useAutoFormDetectionParameters } from "@app/hooks/tools/autoFormDetection/useAutoFormDetectionParameters";+import { useAutoFormDetectionOperation } from "@app/hooks/tools/autoFormDetection/useAutoFormDetectionOperation";+import { useBaseTool } from "@app/hooks/tools/shared/useBaseTool";+import {+ DetectionSummary,+ onSummary,+} from "@app/services/formDetection/progress";+import AutoFormDetectionSettings from "@app/components/tools/autoFormDetection/AutoFormDetectionSettings";+import DetectionProgressPanel from "@app/components/tools/autoFormDetection/DetectionProgressPanel";+import DetectionSummaryPanel from "@app/components/tools/autoFormDetection/DetectionSummaryPanel";+import { BaseToolProps, ToolComponent } from "@app/types/tool";++const AutoFormDetection = (props: BaseToolProps) => {+ const { t } = useTranslation();++ const base = useBaseTool(+ "autoFormDetection",+ useAutoFormDetectionParameters,+ useAutoFormDetectionOperation,+ props,+ );++ const [summary, setSummary] = useState<DetectionSummary | null>(null);+ useEffect(() => onSummary(setSummary), []);+ useEffect(() => {+ if (!base.hasResults) setSummary(null);+ }, [base.hasResults]);++ return createToolFlow({+ files: {+ selectedFiles: base.selectedFiles,+ isCollapsed: base.hasFiles || base.hasResults,+ },+ steps: [+ {+ title: t("autoFormDetection.settings.title", "Settings"),+ isCollapsed: !base.hasFiles || base.hasResults,+ isVisible: !base.hasResults,+ content: (+ <AutoFormDetectionSettings+ parameters={base.params.parameters}+ onParameterChange={base.params.updateParameter}+ disabled={base.operation.isLoading}+ />+ ),+ },+ {+ title: t("autoFormDetection.summary.stepTitle", "Detection results"),+ isVisible: base.hasResults && summary !== null,+ isCollapsed: false,+ content: summary ? <DetectionSummaryPanel summary={summary} /> : null,+ },+ ],+ executeButton: {+ text: t("autoFormDetection.submit", "Detect form fields"),+ isVisible: !base.hasResults,+ loadingText: t("autoFormDetection.loading", "Detecting form fields..."),+ onClick: base.handleExecute,+ endpointEnabled: base.endpointEnabled,+ paramsValid: base.params.validateParameters(),+ },+ belowExecuteButton: (+ <DetectionProgressPanel active={base.operation.isLoading} />+ ),+ review: {+ isVisible: base.hasResults,+ operation: base.operation,+ title: t("autoFormDetection.results.title", "Review fillable PDF"),+ onFileClick: base.handleThumbnailClick,+ onUndo: base.handleUndo,+ },+ });+};++AutoFormDetection.tool = () => useAutoFormDetectionOperation;++export default AutoFormDetection as ToolComponent;diff --git a/frontend/editor/src/core/types/toolApiTypes.ts b/frontend/editor/src/core/types/toolApiTypes.tsindex aba6746e1b..798ca8fd28 100644--- a/frontend/editor/src/core/types/toolApiTypes.ts+++ b/frontend/editor/src/core/types/toolApiTypes.ts@@ -542,6 +542,10 @@ export interface FlattenRequest {*/renderDpi?: number;}+export interface FormFormDetectionDetectRequest {+ applyToPdf?: boolean;+ confThreshold?: number;+}export type GeneralExtractBookmarksRequest = Record<string, never>;export type GeneralFile = Record<string, never>;export type GeneralPdfToSinglePageRequest = Record<string, never>;@@ -1537,6 +1541,7 @@ export type ToolEndpoint =| "/api/v1/filter/filter-page-count"| "/api/v1/filter/filter-page-rotation"| "/api/v1/filter/filter-page-size"+ | "/api/v1/form/form-detection/detect"| "/api/v1/general/booklet-imposition"| "/api/v1/general/crop"| "/api/v1/general/edit-table-of-contents"@@ -1642,6 +1647,7 @@ export interface ToolApiParams {"/api/v1/filter/filter-page-count": PDFComparisonAndCount;"/api/v1/filter/filter-page-rotation": PageRotationRequest;"/api/v1/filter/filter-page-size": PageSizeRequest;+ "/api/v1/form/form-detection/detect": FormFormDetectionDetectRequest;"/api/v1/general/booklet-imposition": BookletImpositionRequest;"/api/v1/general/crop": CropPdfForm;"/api/v1/general/edit-table-of-contents": EditTableOfContentsRequest;@@ -1748,6 +1754,7 @@ export const TOOL_ENDPOINTS = ["/api/v1/filter/filter-page-count","/api/v1/filter/filter-page-rotation","/api/v1/filter/filter-page-size",+ "/api/v1/form/form-detection/detect","/api/v1/general/booklet-imposition","/api/v1/general/crop","/api/v1/general/edit-table-of-contents",diff --git a/frontend/editor/src/core/types/toolIO.ts b/frontend/editor/src/core/types/toolIO.tsindex 9d62cb086b..c3ccf9a5e5 100644--- a/frontend/editor/src/core/types/toolIO.ts+++ b/frontend/editor/src/core/types/toolIO.ts@@ -392,6 +392,18 @@ export const TOOL_IO: ToolIOTable = {produces: "PDF",arity: "SISO",},+ "/api/v1/form/form-detection/detect": {+ accepts: ["PDF"],+ produces: "PDF",+ arity: "SISO",+ cases: [+ {+ when: [{ param: "applyToPdf", matches: ["false"] }],+ produces: "JSON",+ arity: "SISO",+ },+ ],+ },"/api/v1/general/booklet-imposition": {accepts: ["PDF"],produces: "PDF",diff --git a/frontend/editor/src/core/types/toolId.ts b/frontend/editor/src/core/types/toolId.tsindex 0762c2e81d..77aba0bb3c 100644--- a/frontend/editor/src/core/types/toolId.ts+++ b/frontend/editor/src/core/types/toolId.ts@@ -66,6 +66,7 @@ export const CORE_REGULAR_TOOL_IDS = ["bookletImposition","pdfTextEditor","formFill",+ "autoFormDetection",] as const;export const CORE_SUPER_TOOL_IDS = ["multiTool", "read", "automate"] as const;diff --git a/frontend/editor/src/portal/views/Integrations.test.tsx b/frontend/editor/src/portal/views/Integrations.test.tsxindex 8c4e684bfa..205215faa9 100644--- a/frontend/editor/src/portal/views/Integrations.test.tsx+++ b/frontend/editor/src/portal/views/Integrations.test.tsx@@ -5,13 +5,21 @@ import {screen,waitFor,} from "@testing-library/react";+import type React from "react";+import { MantineProvider } from "@mantine/core";import { HttpError } from "@portal/api/http";import { Integrations } from "@portal/views/Integrations";import type { IntegrationConfig } from "@portal/api/integrations";+// env="test" drops Mantine's transitions; otherwise a pending one fires after the environment+// is torn down and vitest reports "window is not defined" against whichever file ran last.+const TestProvider = ({ children }: { children: React.ReactNode }) => (+ <MantineProvider env="test">{children}</MantineProvider>+);+const render = (ui: Parameters<typeof baseRender>[0]) =>- baseRender(ui, { wrapper: MantineProvider });+ baseRender(ui, { wrapper: TestProvider });vi.mock("react-i18next", () => ({useTranslation: () => ({diff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/AdminFeaturesSection.tsx b/frontend/editor/src/proprietary/components/shared/config/configSections/AdminFeaturesSection.tsxindex de6801f330..15c38f0605 100644--- a/frontend/editor/src/proprietary/components/shared/config/configSections/AdminFeaturesSection.tsx+++ b/frontend/editor/src/proprietary/components/shared/config/configSections/AdminFeaturesSection.tsx@@ -22,6 +22,7 @@ import { SettingsStickyFooter } from "@app/components/shared/config/SettingsSticimport apiClient from "@app/services/apiClient";import { useLoginRequired } from "@app/hooks/useLoginRequired";import LoginRequiredBanner from "@app/components/shared/config/LoginRequiredBanner";+import AdminFormDetectionSection from "@app/components/shared/config/configSections/AdminFormDetectionSection";interface FeaturesSettingsData {serverCertificate?: {@@ -350,6 +351,8 @@ export default function AdminFeaturesSection() {</div></Stack></Paper>++ <AdminFormDetectionSection /></Stack><SettingsStickyFooterdiff --git a/frontend/editor/src/proprietary/components/shared/config/configSections/AdminFormDetectionSection.tsx b/frontend/editor/src/proprietary/components/shared/config/configSections/AdminFormDetectionSection.tsxnew file mode 100644index 0000000000..ed14f93b64--- /dev/null+++ b/frontend/editor/src/proprietary/components/shared/config/configSections/AdminFormDetectionSection.tsx@@ -0,0 +1,555 @@+import { useEffect, useRef, useState } from "react";+import { useTranslation } from "react-i18next";+import {+ Stack,+ Text,+ Paper,+ Group,+ Switch,+ Loader,+ Divider,+} from "@mantine/core";+import { Button } from "@app/ui/Button";+import { ActionIcon } from "@app/ui/ActionIcon";+import { StatusBadge, type StatusTone } from "@app/ui/StatusBadge";+import { ProgressBar } from "@app/ui/ProgressBar";+import { Banner } from "@app/ui/Banner";+import { Collapsible } from "@app/ui/Collapsible";+import { Tooltip } from "@app/components/shared/Tooltip";+import LocalIcon from "@app/components/shared/LocalIcon";+import {+ useFormDetectionModelStatus,+ FormDetectionCatalogEntry,+} from "@app/hooks/useFormDetectionModelStatus";++function formatSize(+ t: (k: string, d: string) => string,+ bytes: number,+): string {+ if (!bytes || bytes <= 0)+ return t("admin.formDetection.sizeUnknown", "size unknown");+ const mb = bytes / (1024 * 1024);+ return mb >= 1024 ? `${(mb / 1024).toFixed(1)} GB` : `${Math.round(mb)} MB`;+}++function CommandRow({ code, copyLabel }: { code: string; copyLabel: string }) {+ const [copied, setCopied] = useState(false);+ return (+ <Group+ gap={6}+ wrap="nowrap"+ style={{+ background: "var(--c-surface-sunken)",+ border: "1px solid var(--c-border-subtle)",+ borderRadius: "var(--mantine-radius-sm)",+ padding: "0.2rem 0.3rem 0.2rem 0.6rem",+ }}+ >+ <Text+ size="xs"+ ff="monospace"+ style={{ overflowX: "auto", whiteSpace: "nowrap", flex: 1 }}+ >+ {code}+ </Text>+ <ActionIcon+ variant="tertiary"+ accent="neutral"+ size="sm"+ aria-label={copyLabel}+ title={copyLabel}+ onClick={async () => {+ try {+ await navigator.clipboard.writeText(code);+ setCopied(true);+ setTimeout(() => setCopied(false), 1500);+ } catch {+ setCopied(false);+ }+ }}+ >+ <LocalIcon+ icon={copied ? "check-rounded" : "content-copy-outline-rounded"}+ width="0.9rem"+ height="0.9rem"+ />+ </ActionIcon>+ </Group>+ );+}++export default function AdminFormDetectionSection() {+ const { t } = useTranslation();+ const { status, loading, error, install, uninstall, setConfig } =+ useFormDetectionModelStatus();+ const [busyId, setBusyId] = useState<string | null>(null);+ const [confirmUninstallId, setConfirmUninstallId] = useState<string | null>(+ null,+ );+ const [configBusy, setConfigBusy] = useState(false);+ const [actionError, setActionError] = useState<string | null>(null);+ const [airgapOpen, setAirgapOpen] = useState(false);+ const confirmTimer = useRef<ReturnType<typeof setTimeout> | null>(null);++ useEffect(+ () => () => {+ if (confirmTimer.current) clearTimeout(confirmTimer.current);+ },+ [],+ );++ const enabled = status?.enabled ?? true;+ const serverEngineAvailable = status?.serverEngineAvailable ?? true;+ const catalog = status?.catalog ?? [];+ const st = status?.status;+ const inFlight = st === "downloading" || st === "verifying";+ const activeId = status?.activeModelId || null;+ const installedIds = status?.installed ?? [];+ const downloadingId =+ status?.downloadingModelId || (inFlight ? busyId : null);++ const statusTone: StatusTone =+ st === "ready"+ ? "success"+ : st === "failed"+ ? "danger"+ : inFlight+ ? "info"+ : "neutral";+ const statusLabel =+ st === "ready"+ ? t("admin.formDetection.state.ready", "Ready")+ : st === "downloading"+ ? t("admin.formDetection.state.downloading", "Downloading...")+ : st === "verifying"+ ? t("admin.formDetection.state.verifying", "Verifying...")+ : st === "failed"+ ? t("admin.formDetection.state.failed", "Failed")+ : t("admin.formDetection.state.notInstalled", "No model installed");++ const armUninstall = (id: string) => {+ setConfirmUninstallId(id);+ if (confirmTimer.current) clearTimeout(confirmTimer.current);+ confirmTimer.current = setTimeout(() => setConfirmUninstallId(null), 4000);+ };++ const doInstall = async (id: string) => {+ setBusyId(id);+ setActionError(null);+ setConfirmUninstallId(null);+ try {+ await install(id);+ } catch (e) {+ setActionError(+ e instanceof Error+ ? e.message+ : t("admin.formDetection.installFailed", "Install failed"),+ );+ } finally {+ setBusyId(null);+ }+ };++ const doUninstall = async (id: string) => {+ setBusyId(id);+ setActionError(null);+ setConfirmUninstallId(null);+ try {+ await uninstall(id);+ } catch (e) {+ setActionError(+ e instanceof Error+ ? e.message+ : t("admin.formDetection.uninstallFailed", "Uninstall failed"),+ );+ } finally {+ setBusyId(null);+ }+ };++ const doSetConfig = async (config: { enabled?: boolean }) => {+ setConfigBusy(true);+ setActionError(null);+ try {+ await setConfig(config);+ } catch (e) {+ setActionError(+ e instanceof Error+ ? e.message+ : t("admin.formDetection.saveFailed", "Failed to save setting"),+ );+ } finally {+ setConfigBusy(false);+ }+ };++ const anyError = actionError || error || status?.error;+ const copyLabel = t("common.copy", "Copy");++ const renderModelCard = (entry: FormDetectionCatalogEntry) => {+ const isActive = entry.id === activeId && st === "ready";+ const isInstalled = installedIds.includes(entry.id);+ const isDownloading = inFlight && downloadingId === entry.id;+ const installable = Boolean(entry.onnxUrl && entry.sha256);+ const isBusy = busyId === entry.id;++ return (+ <Paper+ key={entry.id}+ withBorder+ radius="md"+ p="sm"+ style={+ isActive+ ? {+ borderColor: "var(--c-primary)",+ background: "var(--c-primary-subtle)",+ }+ : undefined+ }+ >+ <Group+ justify="space-between"+ align="flex-start"+ wrap="nowrap"+ gap="sm"+ >+ <div style={{ minWidth: 0 }}>+ <Group gap={6} wrap="wrap">+ <Text fw={600} size="sm">+ {entry.displayName}+ </Text>+ <Text size="xs" c="dimmed">+ {formatSize(t, entry.sizeBytes)}+ </Text>+ {isActive ? (+ <StatusBadge tone="success" size="sm">+ {t("admin.formDetection.badge.active", "Active")}+ </StatusBadge>+ ) : isInstalled ? (+ <StatusBadge tone="neutral" size="sm">+ {t("admin.formDetection.badge.installed", "Installed")}+ </StatusBadge>+ ) : null}+ </Group>+ <Text size="xs" c="dimmed" mt={2}>+ {entry.description}+ </Text>+ {entry.license ? (+ // Installing pulls third-party weights whose terms differ per model, so the+ // admin making that call sees them before choosing, not in a doc somewhere.+ <Text size="xs" c="dimmed" mt={4}>+ {t("admin.formDetection.licenseLabel", "Licence")}:{" "}+ {entry.license}+ </Text>+ ) : null}+ </div>++ <div style={{ flexShrink: 0 }}>+ {isActive ? (+ <Button+ variant="secondary"+ accent="danger"+ size="sm"+ loading={isBusy}+ onClick={() =>+ confirmUninstallId === entry.id+ ? doUninstall(entry.id)+ : armUninstall(entry.id)+ }+ >+ {confirmUninstallId === entry.id+ ? t(+ "admin.formDetection.confirmUninstall",+ "Click to confirm",+ )+ : t("admin.formDetection.uninstall", "Uninstall")}+ </Button>+ ) : (+ <Group gap={4} wrap="nowrap">+ <Button+ size="sm"+ variant={isInstalled ? "secondary" : "primary"}+ loading={isBusy || isDownloading}+ disabled={+ !installable ||+ inFlight ||+ !enabled ||+ !serverEngineAvailable+ }+ onClick={() => doInstall(entry.id)}+ >+ {isInstalled+ ? t("admin.formDetection.switch", "Use this model")+ : t("admin.formDetection.install", "Install")}+ </Button>+ {isInstalled && !isBusy ? (+ <ActionIcon+ variant="tertiary"+ accent="danger"+ size="sm"+ aria-label={+ confirmUninstallId === entry.id+ ? t(+ "admin.formDetection.confirmUninstall",+ "Click to confirm",+ )+ : t("admin.formDetection.uninstall", "Uninstall")+ }+ title={+ confirmUninstallId === entry.id+ ? t(+ "admin.formDetection.confirmUninstall",+ "Click to confirm",+ )+ : t("admin.formDetection.uninstall", "Uninstall")+ }+ onClick={() =>+ confirmUninstallId === entry.id+ ? doUninstall(entry.id)+ : armUninstall(entry.id)+ }+ >+ <LocalIcon+ icon="delete-outline-rounded"+ width="1rem"+ height="1rem"+ />+ </ActionIcon>+ ) : null}+ </Group>+ )}+ </div>+ </Group>++ {isDownloading ? (+ <Stack gap={4} mt="xs">+ <ProgressBar+ value={(status?.progress ?? 0) / 100}+ label={statusLabel}+ />+ <Text size="xs" c="dimmed">+ {st === "verifying"+ ? t(+ "admin.formDetection.verifyingNote",+ "Verifying SHA-256 checksum...",+ )+ : t(+ "admin.formDetection.downloadingNote",+ "{{percent}}% of {{size}}",+ {+ percent: status?.progress ?? 0,+ size: formatSize(t, entry.sizeBytes),+ },+ )}+ </Text>+ </Stack>+ ) : null}++ {!installable ? (+ <Text size="xs" c="dimmed" mt={6}>+ {t(+ "admin.formDetection.notAvailable",+ "No download URL/checksum configured yet, so this model cannot be installed.",+ )}+ </Text>+ ) : null}+ </Paper>+ );+ };++ return (+ <Paper withBorder p="md" radius="md">+ <Stack gap="md">+ <div>+ <Group justify="space-between" align="center" wrap="nowrap">+ <Group gap="xs" wrap="nowrap">+ <Text fw={600} size="sm">+ {t("admin.formDetection.title", "AI Form Detection")}+ </Text>+ <Tooltip+ content={t(+ "admin.formDetection.description",+ "Detects text fields, checkboxes and signature areas in a PDF and turns them into fillable form fields. Detection runs on this server with the model you install below.",+ )}+ position="top"+ arrow+ >+ <LocalIcon+ icon="info-outline-rounded"+ width="1rem"+ height="1rem"+ style={{ color: "var(--c-text-subtle)", cursor: "help" }}+ />+ </Tooltip>+ {status ? (+ <StatusBadge tone={statusTone} size="sm">+ {statusLabel}+ </StatusBadge>+ ) : null}+ </Group>+ <Switch+ checked={enabled}+ onChange={(e) =>+ doSetConfig({ enabled: e.currentTarget.checked })+ }+ disabled={configBusy || (loading && !status)}+ size="sm"+ aria-label={t(+ "admin.formDetection.enableFeature",+ "Enable feature",+ )}+ />+ </Group>+ </div>++ {loading && !status ? (+ <Loader />+ ) : (+ <Stack gap="md">+ {anyError ? (+ <Banner+ tone="danger"+ icon={+ <LocalIcon+ icon="error-outline-rounded"+ width="1.1rem"+ height="1.1rem"+ />+ }+ title={t(+ "admin.formDetection.errorTitle",+ "Something went wrong",+ )}+ description={anyError}+ />+ ) : null}++ {status && !status.writable ? (+ <Banner+ tone="warning"+ icon={+ <LocalIcon+ icon="warning-rounded"+ width="1.1rem"+ height="1.1rem"+ />+ }+ description={t(+ "admin.formDetection.notWritable",+ "The model directory is not writable; check the configs volume mount.",+ )}+ />+ ) : null}++ {!serverEngineAvailable ? (+ <Banner+ tone="warning"+ icon={+ <LocalIcon+ icon="warning-rounded"+ width="1.1rem"+ height="1.1rem"+ />+ }+ description={t(+ "admin.formDetection.engineUnavailable",+ "This build does not include the detection engine, so the tool stays unavailable even with a model installed.",+ )}+ />+ ) : null}++ <div>+ <Text fw={500} size="sm" mb={4}>+ {t("admin.formDetection.modelsLabel", "Detection model")}+ </Text>+ <Stack gap="xs">{catalog.map(renderModelCard)}</Stack>+ </div>++ <Divider />++ <Collapsible+ open={airgapOpen}+ onToggle={() => setAirgapOpen((o) => !o)}+ header={+ <Group gap={6} wrap="nowrap">+ <LocalIcon+ icon="download-rounded"+ width="1rem"+ height="1rem"+ />+ <Text size="sm">+ {t(+ "admin.formDetection.airgap.show",+ "Offline / air-gapped install",+ )}+ </Text>+ </Group>+ }+ >+ <Stack gap="sm" p="sm">+ <Text size="xs" c="dimmed">+ {t(+ "admin.formDetection.airgap.intro",+ "No internet on the server? Download the model elsewhere, verify it, and copy it into the model directory. It is picked up on restart.",+ )}+ </Text>+ {catalog+ .filter((c) => c.onnxUrl)+ .map((c) => (+ <Stack gap={6} key={c.id}>+ <Text size="xs" fw={600}>+ {c.displayName}+ </Text>+ <Text size="xs" c="dimmed">+ {t(+ "admin.formDetection.airgap.step1",+ "1. Download on a machine with internet:",+ )}+ </Text>+ <CommandRow+ code={`curl -L -o ${c.id}.onnx "${c.onnxUrl}"`}+ copyLabel={copyLabel}+ />+ <Text size="xs" c="dimmed">+ {t(+ "admin.formDetection.airgap.step2",+ "2. Check the SHA-256 checksum matches:",+ )}+ </Text>+ <CommandRow+ code={+ c.sha256 ||+ t(+ "admin.formDetection.airgap.noSha",+ "(checksum not set)",+ )+ }+ copyLabel={copyLabel}+ />+ <Text size="xs" c="dimmed">+ {t(+ "admin.formDetection.airgap.step3",+ "3. Copy it into the model directory on this server:",+ )}+ </Text>+ <CommandRow+ code={`<configs>/models/form-detection/${c.id}.onnx`}+ copyLabel={copyLabel}+ />+ </Stack>+ ))}+ <Text size="xs" c="dimmed">+ {t(+ "admin.formDetection.airgap.step4",+ "4. Set formDetection.activeModelId to the model's id in settings.yml and restart. <configs> is the configs volume (e.g. /configs in Docker). The air-gapped image ships with a model already installed.",+ )}+ </Text>+ </Stack>+ </Collapsible>+ </Stack>+ )}+ </Stack>+ </Paper>+ );+}diff --git a/scripts/export-ffdetr-onnx.py b/scripts/export-ffdetr-onnx.pynew file mode 100644index 0000000000..19285e73d6--- /dev/null+++ b/scripts/export-ffdetr-onnx.py@@ -0,0 +1,143 @@+#!/usr/bin/env python3+"""Export the Apache-2.0 FFDetr detector to the ONNX we ship: int8 (~37MB) plus its fp32 source,+printing the sha256 for model-catalog.json. torch is needed here and nowhere else.++ pip install torch torchvision --index-url https://download.pytorch.org/whl/cpu+ pip install rfdetr onnx onnxruntime onnxconverter-common+ python scripts/export-ffdetr-onnx.py --out build/ffdetr+"""++from __future__ import annotations++import argparse+import hashlib+import shutil+import sys+import warnings+from pathlib import Path++# Pinned so a re-export uses the same checkpoint. The output is not byte-reproducible (opset_import+# domains shift with the runtime), so check equivalence by running both graphs, not by hash.+REPO = "jbarrow/FFDetr"+REVISION = "56f4e4235e28dcb2953513dc020bb191a2f54cfe"+CHECKPOINT_SHA256 = "f852e1bac18c8f435b82270fc8ff8e2ca4a2cd8869c411fa8f473f16e69585ef"++# Must match model-catalog.json. 1024 is RF-DETR's native resolution and has to stay divisible+# by 32 (patch_size 16 x num_windows 2).+INPUT_SIZE = 1024+NUM_CLASSES = 3+OPSET = 17+++def sha256_of(path: Path) -> str:+ digest = hashlib.sha256()+ with path.open("rb") as handle:+ for chunk in iter(lambda: handle.read(1 << 20), b""):+ digest.update(chunk)+ return digest.hexdigest()+++def fetch_checkpoint(dest: Path) -> Path:+ """Download the pinned .pth and refuse to continue if it is not the one we vetted."""+ import urllib.request++ if not dest.exists():+ url = f"https://huggingface.co/{REPO}/resolve/{REVISION}/FFDetr.pth"+ print(f"downloading {url}")+ with urllib.request.urlopen(url) as response, dest.open("wb") as out:+ shutil.copyfileobj(response, out)++ actual = sha256_of(dest)+ if actual != CHECKPOINT_SHA256:+ raise SystemExit(f"checkpoint sha256 mismatch\n expected {CHECKPOINT_SHA256}\n actual {actual}")+ print(f"checkpoint verified ({dest.stat().st_size / 1e6:.1f} MB)")+ return dest+++def export_fp32(checkpoint: Path, out_dir: Path) -> Path:+ from rfdetr import RFDETRMedium++ # An absolute path matters: a relative one is resolved against ~/.roboflow/models and 404s.+ model = RFDETRMedium(+ pretrain_weights=str(checkpoint.resolve()),+ num_classes=NUM_CLASSES,+ trust_checkpoint=True,+ )+ # fp16=False keeps the graph single-precision; we quantise to int8 below instead, which is+ # both smaller and - unlike the fp16 converter - produces a graph onnxruntime will load.+ produced = model.export(+ output_dir=str(out_dir),+ shape=(INPUT_SIZE, INPUT_SIZE),+ opset_version=OPSET,+ fp16=False,+ verbose=False,+ )+ return Path(produced)+++def quantize(fp32: Path, out: Path) -> Path:+ from onnxruntime.quantization import QuantType, quantize_dynamic+ from onnxruntime.quantization.shape_inference import quant_pre_process++ prepared = fp32.with_name("ffdetr-prep.onnx")+ quant_pre_process(str(fp32), str(prepared), skip_symbolic_shape=False)+ quantize_dynamic(str(prepared), str(out), weight_type=QuantType.QInt8)+ prepared.unlink(missing_ok=True)+ return out+++def verify(model: Path) -> None:+ """Load under the same onnxruntime the product uses and assert the contract the decoder relies on."""+ import numpy as np+ import onnx+ import onnxruntime as ort++ graph = onnx.load(str(model))+ custom = sorted({n.domain for n in graph.graph.node if n.domain not in ("", "ai.onnx")})+ if custom:+ raise SystemExit(f"refusing to ship: graph needs custom op domains {custom}")++ session = ort.InferenceSession(str(model), providers=["CPUExecutionProvider"])+ names = [o.name for o in session.get_outputs()]+ if names != ["dets", "labels"]:+ raise SystemExit(f"unexpected output names {names}; the decoder binds by name")++ outputs = session.run(None, {session.get_inputs()[0].name: np.zeros((1, 3, INPUT_SIZE, INPUT_SIZE), np.float32)})+ for name, value in zip(names, outputs):+ if np.isnan(value).any():+ raise SystemExit(f"output {name} contains NaN")+ # Both outputs are [1,300,4]: 4 box values vs NUM_CLASSES + 1 no-object logit. They are+ # indistinguishable by shape, which is exactly why everything downstream binds by name.+ print(f"verified: ops all standard, outputs {list(zip(names, (o.shape for o in outputs)))}")+++def main() -> int:+ warnings.filterwarnings("ignore")+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--out", default="build/ffdetr", help="output directory")+ args = parser.parse_args()++ out_dir = Path(args.out)+ out_dir.mkdir(parents=True, exist_ok=True)++ checkpoint = fetch_checkpoint(out_dir / "FFDetr.pth")+ fp32 = export_fp32(checkpoint, out_dir)+ print(f"fp32: {fp32.stat().st_size / 1e6:.1f} MB")++ int8 = quantize(fp32, out_dir / "ffdetr-int8.onnx")+ verify(int8)++ size = int8.stat().st_size+ print()+ print(f" file {int8}")+ print(f" sizeBytes {size}")+ print(f" sha256 {sha256_of(int8)}")+ print()+ print("Host this file, then set onnxUrl/sha256/sizeBytes on the ffdetr entry in")+ print("app/proprietary/src/main/resources/formdetection/model-catalog.json, and the matching")+ print("FORM_DETECTION_MODEL_* build args in docker/embedded/Dockerfile.fat.")+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/scripts/slim-onnxruntime.sh b/scripts/slim-onnxruntime.shnew file mode 100644index 0000000000..455a318c89--- /dev/null+++ b/scripts/slim-onnxruntime.sh@@ -0,0 +1,65 @@+#!/usr/bin/env sh+# Shrink the bundled ONNX Runtime natives to one Linux arch: the jar carries four platforms (~42MB)+# and a container loads exactly one, so keeping only the target takes it to ~8MB. Docker build only.+#+# Usage: slim-onnxruntime.sh <target> [amd64|arm64], where <target> is a dir holding+# onnxruntime-*.jar, that jar, or a Spring Boot fat jar. No-op if it or `zip` is missing.+set -eu++target="${1:?usage: slim-onnxruntime.sh <target> [arch]}"+arch="${2:-$(dpkg --print-architecture 2>/dev/null || uname -m)}"+case "$arch" in+ amd64 | x86_64) keep="linux-x64" ;;+ arm64 | aarch64) keep="linux-aarch64" ;;+ *) keep="linux-x64" ;;+esac++if ! command -v zip >/dev/null 2>&1; then+ echo "[slim-onnxruntime] 'zip' not found - skipping (no slimming applied)"+ exit 0+fi++strip_ort_jar() { # $1 = path to an onnxruntime jar+ _jar="$1"+ _before=$(wc -c <"$_jar" 2>/dev/null || echo 0)+ for _p in osx-x64 osx-aarch64 win-x64 linux-x64 linux-aarch64; do+ [ "$_p" = "$keep" ] && continue+ zip -q -d "$_jar" "ai/onnxruntime/native/$_p/*" >/dev/null 2>&1 || true+ done+ _after=$(wc -c <"$_jar" 2>/dev/null || echo 0)+ echo "[slim-onnxruntime] kept '$keep'; $(basename "$_jar"): ${_before} -> ${_after} bytes"+}++if [ -d "$target" ]; then+ # Find the onnxruntime jar anywhere under the target dir so we are agnostic to the+ # Spring Boot layer layout (dependencies/lib vs dependencies/BOOT-INF/lib, etc.).+ found=$(find "$target" -name 'onnxruntime-*.jar' 2>/dev/null || true)+ if [ -n "$found" ]; then+ echo "$found" | while IFS= read -r ort; do+ [ -n "$ort" ] && strip_ort_jar "$ort"+ done+ else+ echo "[slim-onnxruntime] no onnxruntime jar under $target - nothing to do"+ fi+elif printf '%s' "$target" | grep -q 'onnxruntime-[^/]*\.jar$'; then+ strip_ort_jar "$target"+else+ # Spring Boot fat jar: extract the nested onnxruntime jar, slim it, put it back STORED+ # (Spring Boot requires nested jars to be uncompressed).+ if ! command -v unzip >/dev/null 2>&1; then+ echo "[slim-onnxruntime] 'unzip' needed for fat-jar mode - skipping"+ exit 0+ fi+ fat="$(cd "$(dirname "$target")" && pwd)/$(basename "$target")"+ nested=$(unzip -Z1 "$fat" 'BOOT-INF/lib/onnxruntime-*.jar' 2>/dev/null | head -n1 || true)+ if [ -z "$nested" ]; then+ echo "[slim-onnxruntime] no nested onnxruntime jar in $(basename "$fat") - nothing to do"+ exit 0+ fi+ tmp=$(mktemp -d)+ (cd "$tmp" && unzip -qo "$fat" "$nested")+ strip_ort_jar "$tmp/$nested"+ (cd "$tmp" && zip -q -0 -X "$fat" "$nested")+ rm -rf "$tmp"+ echo "[slim-onnxruntime] updated nested $nested inside $(basename "$fat")"+fidiff --git a/testing/cucumber/features/environment.py b/testing/cucumber/features/environment.pyindex 84d30a50bc..59f9c1a356 100644--- a/testing/cucumber/features/environment.py+++ b/testing/cucumber/features/environment.py@@ -7,8 +7,8 @@ import requestssys.path.insert(0, os.path.join(os.path.dirname(__file__), "steps"))import job_support # noqa: E402import parallel_support # noqa: E402+from api_base import BASE_URL as _BASE_URL # noqa: E402-_BASE_URL = "http://localhost:8080"_CONTAINER_NAME = os.environ.get("TEST_CONTAINER_NAME", "")_REPORT_DIR = os.environ.get("TEST_REPORT_DIR", "")diff --git a/testing/cucumber/features/form_detection_nightly.feature b/testing/cucumber/features/form_detection_nightly.featurenew file mode 100644index 0000000000..9edd945e3b--- /dev/null+++ b/testing/cucumber/features/form_detection_nightly.feature@@ -0,0 +1,92 @@+@nightly @proprietary @form-detection+Feature: Auto Form Detection API Validation++ # Needs the ONNX runtime and a baked-in model, which only Dockerfile.fat has.+ # behave.ini excludes @nightly; the nightly job opts back in against that image.++ @model-status @positive+ Scenario: Model status reports a ready model and an available engine+ Given I am logged in as admin+ When I send a GET request to "/api/v1/form/form-detection-model/status" with JWT authentication+ Then the response status code should be 200+ And the response content type should be "application/json"+ And the JSON value of "status" should be "ready"++ @detect @positive+ Scenario: Detect returns field boxes for a printed form+ Given I generate a PDF file as "file"+ And the pdf looks like a printed form+ And the request data includes+ | parameter | value |+ | applyToPdf | false |+ When I send the API request to the endpoint "/api/v1/form/form-detection/detect"+ Then the response status code should be 200+ And the response content type should be "application/json"+ And the response should contain at least 5 detected fields+ And every detected field should be a usable field box++ @detect @positive+ Scenario: Detect finds fields on every page of a multi-page form+ Given I generate a PDF file as "file"+ And the pdf looks like a printed form on 3 pages+ And the request data includes+ | parameter | value |+ | applyToPdf | false |+ When I send the API request to the endpoint "/api/v1/form/form-detection/detect"+ Then the response status code should be 200+ And the response should contain at least 15 detected fields+ And every detected field should be a usable field box++ @detect @positive+ Scenario: A stricter confidence threshold is honoured+ Given I generate a PDF file as "file"+ And the pdf looks like a printed form+ And the request data includes+ | parameter | value |+ | confThreshold | 0.7 |+ | applyToPdf | false |+ When I send the API request to the endpoint "/api/v1/form/form-detection/detect"+ Then the response status code should be 200+ And every detected field should have confidence of at least 0.7++ @detect @positive+ Scenario: A fillable PDF comes back by default+ Given I generate a PDF file as "file"+ And the pdf looks like a printed form+ When I send the API request to the endpoint "/api/v1/form/form-detection/detect"+ Then the response status code should be 200+ And the response content type should be "application/pdf"+ And the response file should have extension ".pdf"+ And the response PDF should contain 1 pages+ And the response PDF should contain at least 5 form fields++ @detect @positive+ Scenario: A page with nothing form-like yields an empty detection list+ Given I generate a PDF file as "file"+ And the pdf contains 1 blank pages+ And the request data includes+ | parameter | value |+ | applyToPdf | false |+ When I send the API request to the endpoint "/api/v1/form/form-detection/detect"+ Then the response status code should be 200+ And the response content type should be "application/json"+ And every detected field should be a usable field box++ @detect @negative+ Scenario: Detect rejects a non-PDF upload+ Given I generate a PNG image file as "file"+ When I send the API request to the endpoint "/api/v1/form/form-detection/detect"+ Then the response status code should be 400+ And the JSON value of "reason" should be "INVALID_PDF"++ @detect @negative+ Scenario: An out-of-range confidence threshold is clamped rather than failing+ Given I generate a PDF file as "file"+ And the pdf looks like a printed form+ And the request data includes+ | parameter | value |+ | confThreshold | 9.5 |+ | applyToPdf | false |+ When I send the API request to the endpoint "/api/v1/form/form-detection/detect"+ Then the response status code should be 200+ And every detected field should be a usable field boxdiff --git a/testing/cucumber/features/steps/api_base.py b/testing/cucumber/features/steps/api_base.pynew file mode 100644index 0000000000..11c4972baa--- /dev/null+++ b/testing/cucumber/features/steps/api_base.py@@ -0,0 +1,5 @@+import os++# Server under test. The cucumber Taskfile documents BASE_URL as the way to point+# the suite at another host/port; this is the single place that default lives.+BASE_URL = os.environ.get("BASE_URL", "http://localhost:8080").rstrip("/")diff --git a/testing/cucumber/features/steps/auth_step_definitions.py b/testing/cucumber/features/steps/auth_step_definitions.pyindex 5206c09b8c..9263d0044f 100644--- a/testing/cucumber/features/steps/auth_step_definitions.py+++ b/testing/cucumber/features/steps/auth_step_definitions.py@@ -16,7 +16,7 @@ import json as json_moduleimport requestsfrom behave import given, then, when-BASE_URL = "http://localhost:8080"+from api_base import BASE_URL# Default test credentials (set in docker-compose-security-with-login.yml)ADMIN_USERNAME = "admin"diff --git a/testing/cucumber/features/steps/enterprise_step_definitions.py b/testing/cucumber/features/steps/enterprise_step_definitions.pyindex ae3c7a57d4..c347d4a4f3 100644--- a/testing/cucumber/features/steps/enterprise_step_definitions.py+++ b/testing/cucumber/features/steps/enterprise_step_definitions.py@@ -14,7 +14,7 @@ Covers:import requestsfrom behave import given, then, when-BASE_URL = "http://localhost:8080"+from api_base import BASE_URLdef _jwt_headers(context):diff --git a/testing/cucumber/features/steps/folders_step_definitions.py b/testing/cucumber/features/steps/folders_step_definitions.pyindex 40eb122f11..b270a0378a 100644--- a/testing/cucumber/features/steps/folders_step_definitions.py+++ b/testing/cucumber/features/steps/folders_step_definitions.py@@ -27,7 +27,7 @@ from behave import given, then, whenfrom reportlab.lib.pagesizes import letterfrom reportlab.pdfgen import canvas-BASE_URL = "http://localhost:8080"+from api_base import BASE_URLFOLDERS_URL = f"{BASE_URL}/api/v1/storage/folders"FILES_URL = f"{BASE_URL}/api/v1/storage/files"HTTP_TIMEOUT = 30diff --git a/testing/cucumber/features/steps/form_detection_step_definitions.py b/testing/cucumber/features/steps/form_detection_step_definitions.pynew file mode 100644index 0000000000..b81dc338bb--- /dev/null+++ b/testing/cucumber/features/steps/form_detection_step_definitions.py@@ -0,0 +1,118 @@+import io++from behave import given, then+from pypdf import PdfReader+from reportlab.lib.pagesizes import letter+from reportlab.pdfgen import canvas++FIELD_TYPES = {"text", "checkbox", "radio", "signature"}+++def _draw_form_page(c, width, height, title):+ """Draw a printed form: ruled entry boxes, checkbox squares and a signature line.+ The detector works off the rendered page, so an AcroForm-only PDF gives it nothing to see.+ """+ c.setFont("Helvetica-Bold", 16)+ c.drawString(60, height - 70, title)++ c.setFont("Helvetica", 11)+ labels = [+ "First name",+ "Last name",+ "Email address",+ "Street address",+ "City",+ "Postcode",+ ]+ y = height - 120+ for label in labels:+ c.drawString(60, y + 5, f"{label}:")+ c.rect(200, y, 320, 22)+ y -= 42++ c.drawString(60, y + 5, "Contact me by:")+ for offset, choice in enumerate(("Email", "Post", "Phone")):+ x = 200 + offset * 110+ c.rect(x, y, 14, 14)+ c.drawString(x + 22, y + 3, choice)+ y -= 60++ c.drawString(60, y + 5, "Signature:")+ c.line(200, y, 520, y)+ c.drawString(60, y - 40, "Date:")+ c.rect(200, y - 45, 150, 22)+++@given("the pdf looks like a printed form")+def step_pdf_looks_like_a_form(context):+ """Replace the current PDF with a single-page form the detector can find fields on."""+ buffer = io.BytesIO()+ c = canvas.Canvas(buffer, pagesize=letter)+ width, height = letter+ _draw_form_page(c, width, height, "Membership application")+ c.showPage()+ c.save()++ with open(context.file_name, "wb") as f:+ f.write(buffer.getvalue())+ context.files[context.param_name].close()+ context.files[context.param_name] = open(context.file_name, "rb")+++@given("the pdf looks like a printed form on {page_count:d} pages")+def step_pdf_looks_like_a_form_multipage(context, page_count):+ buffer = io.BytesIO()+ c = canvas.Canvas(buffer, pagesize=letter)+ width, height = letter+ for i in range(page_count):+ _draw_form_page(c, width, height, f"Membership application - part {i + 1}")+ c.showPage()+ c.save()++ with open(context.file_name, "wb") as f:+ f.write(buffer.getvalue())+ context.files[context.param_name].close()+ context.files[context.param_name] = open(context.file_name, "rb")+++@then("the response should contain at least {count:d} detected fields")+def step_response_has_detections(context, count):+ detections = context.response.json().get("detections")+ assert detections is not None, (+ f"Response has no 'detections' key: {context.response.text[:400]}"+ )+ assert len(detections) >= count, (+ f"Expected at least {count} detections but got {len(detections)}: {detections}"+ )+++@then("every detected field should be a usable field box")+def step_detections_are_usable(context):+ """Guard the wire contract the frontend applies straight into an AcroForm."""+ detections = context.response.json().get("detections") or []+ page_count = len(PdfReader(context.file_name).pages)+ for index, field in enumerate(detections):+ where = f"detection {index}: {field}"+ assert field.get("type") in FIELD_TYPES, f"unknown type in {where}"+ page = field.get("page")+ assert isinstance(page, int) and 0 <= page < page_count, f"bad page in {where}"+ rect = field.get("rectInPdfPoints") or {}+ assert rect.get("w", 0) > 0 and rect.get("h", 0) > 0, f"empty rect in {where}"+ confidence = field.get("confidence")+ assert 0 <= confidence <= 1, f"confidence out of range in {where}"+++@then("every detected field should have confidence of at least {threshold:f}")+def step_detections_respect_threshold(context, threshold):+ detections = context.response.json().get("detections") or []+ below = [f for f in detections if f["confidence"] < threshold]+ assert not below, f"{len(below)} detections below {threshold}: {below[:3]}"+++@then("the response PDF should contain at least {count:d} form fields")+def step_response_pdf_has_form_fields(context, count):+ reader = PdfReader(io.BytesIO(context.response.content))+ fields = reader.get_fields() or {}+ assert len(fields) >= count, (+ f"Expected at least {count} AcroForm fields but got {len(fields)}: {list(fields)}"+ )diff --git a/testing/cucumber/features/steps/job_support.py b/testing/cucumber/features/steps/job_support.pyindex 027bdcb9eb..302705ce7c 100644--- a/testing/cucumber/features/steps/job_support.py+++ b/testing/cucumber/features/steps/job_support.py@@ -6,7 +6,7 @@ the @when/@then decorators or they would register twice."""import requests-BASE_URL = "http://localhost:8080"+from api_base import BASE_URLAPI_HEADERS = {"X-API-KEY": "123456789"}CLEANUP_URL = f"{BASE_URL}/api/v1/general/jobs/cleanup"diff --git a/testing/cucumber/features/steps/step_definitions.py b/testing/cucumber/features/steps/step_definitions.pyindex 5abefa049a..392e7c284d 100644--- a/testing/cucumber/features/steps/step_definitions.py+++ b/testing/cucumber/features/steps/step_definitions.py@@ -16,6 +16,7 @@ import refrom PIL import Image, ImageDrawimport parallel_support+from api_base import BASE_URLAPI_HEADERS = {"X-API-KEY": "123456789"}@@ -583,8 +584,7 @@ def step_request_json_part(context, part_name, json_content):@when('I send a GET request to "{endpoint}"')def step_send_get_request(context, endpoint):- base_url = "http://localhost:8080"- full_url = f"{base_url}{endpoint}"+ full_url = f"{BASE_URL}{endpoint}"response = requests.get(full_url, headers=API_HEADERS, timeout=60)context.response = responsecontext.parallel_get = (full_url, None, API_HEADERS, endpoint)@@ -593,9 +593,8 @@ def step_send_get_request(context, endpoint):@when('I send a GET request to "{endpoint}" with parameters')def step_send_get_request_with_params(context, endpoint):- base_url = "http://localhost:8080"params = {row["parameter"]: row["value"] for row in context.table}- full_url = f"{base_url}{endpoint}"+ full_url = f"{BASE_URL}{endpoint}"response = requests.get(full_url, params=params, headers=API_HEADERS, timeout=60)context.response = responsecontext.parallel_get = (full_url, params, API_HEADERS, endpoint)@@ -649,7 +648,7 @@ def _build_request_spec(context):@when('I send the API request to the endpoint "{endpoint}"')def step_send_api_request(context, endpoint):- url = f"http://localhost:8080{endpoint}"+ url = f"{BASE_URL}{endpoint}"spec = _build_request_spec(context)# Set timeout to 300 seconds (5 minutes) to prevent infinite hangsdiff --git a/testing/cucumber/features/steps/webhook_step_definitions.py b/testing/cucumber/features/steps/webhook_step_definitions.pyindex bcf88bd715..296786099f 100644--- a/testing/cucumber/features/steps/webhook_step_definitions.py+++ b/testing/cucumber/features/steps/webhook_step_definitions.py@@ -4,7 +4,7 @@ import hmacimport requestsfrom behave import given, when, then-BASE_URL = "http://localhost:8080"+from api_base import BASE_URLAPI_HEADERS = {"X-API-KEY": "123456789"}