├── .github ├── build.sh ├── get_jars_sizes.py ├── setup.sh └── workflows │ ├── build.yml │ ├── download_all_engines.yml │ ├── example_run_all_bmz_models.yml │ ├── example_run_pytorch1_2_model.yml │ ├── example_run_tf1_and_tf2_model.yml │ └── jar_sizes.yml ├── .gitignore ├── LICENSE.txt ├── README.md ├── download-engines.py ├── lib └── ShmCreate.c ├── pom.xml ├── python ├── op_environments │ ├── stardist_environment.yaml │ └── stardist_postprocessing.yaml └── ops │ ├── stardist_fine_tune │ └── stardist_fine_tune.py │ ├── stardist_inference │ └── stardist_inference.py │ └── stardist_postprocessing │ └── stardist_postprocessing.py ├── scripts ├── example-download-bmz-model.py ├── example-download-engine.py ├── example-run-pytorch-model-in-fiji.py └── example-run-tf2-model-in-fiji.py ├── src └── main │ ├── java │ └── io │ │ └── bioimage │ │ └── modelrunner │ │ ├── apposed │ │ └── appose │ │ │ ├── Appose.java │ │ │ ├── Builder.java │ │ │ ├── CondaException.java │ │ │ ├── Environment.java │ │ │ ├── FilePaths.java │ │ │ ├── Mamba.java │ │ │ ├── MambaInstallException.java │ │ │ ├── MambaInstallerUtils.java │ │ │ ├── Service.java │ │ │ ├── SharedMemory.java │ │ │ ├── TaskEvent.java │ │ │ └── Types.java │ │ ├── bioimageio │ │ ├── BioimageioDirectConnection.java │ │ ├── BioimageioRepo.java │ │ ├── description │ │ │ ├── Author.java │ │ │ ├── Axes.java │ │ │ ├── AxesV04.java │ │ │ ├── AxesV05.java │ │ │ ├── Axis.java │ │ │ ├── AxisSize.java │ │ │ ├── AxisV04.java │ │ │ ├── AxisV05.java │ │ │ ├── Badge.java │ │ │ ├── Cite.java │ │ │ ├── ExecutionConfig.java │ │ │ ├── ModelDescriptor.java │ │ │ ├── ModelDescriptorFactory.java │ │ │ ├── ModelDescriptorV04.java │ │ │ ├── ModelDescriptorV05.java │ │ │ ├── SampleImage.java │ │ │ ├── SpecialModels.java │ │ │ ├── TensorSpec.java │ │ │ ├── TensorSpecV04.java │ │ │ ├── TensorSpecV05.java │ │ │ ├── TestArtifact.java │ │ │ ├── TransformSpec.java │ │ │ ├── cellpose │ │ │ │ ├── ModelDescriptorCellposeV04.java │ │ │ │ └── ModelDescriptorCellposeV05.java │ │ │ ├── deepimagej │ │ │ │ ├── DeepImageJExecutionConfig.java │ │ │ │ └── DeepImageJProcessing.java │ │ │ ├── exceptions │ │ │ │ └── ModelSpecsException.java │ │ │ ├── stardist │ │ │ │ ├── ModelDescriptorStardistV04.java │ │ │ │ └── ModelDescriptorStardistV05.java │ │ │ └── weights │ │ │ │ ├── KerasWeights.java │ │ │ │ ├── ModelArchitecture.java │ │ │ │ ├── ModelDependencies.java │ │ │ │ ├── ModelWeight.java │ │ │ │ ├── OnnxWeights.java │ │ │ │ ├── PytorchWeights.java │ │ │ │ ├── TfJsWeights.java │ │ │ │ ├── TfWeights.java │ │ │ │ ├── TorchscriptWeights.java │ │ │ │ └── WeightFormat.java │ │ ├── download │ │ │ └── DownloadModel.java │ │ └── tiling │ │ │ ├── ImageInfo.java │ │ │ ├── ImgLib2Utils.java │ │ │ ├── PatchSpec.java │ │ │ ├── TileCalculator.java │ │ │ ├── TileGrid.java │ │ │ ├── TileInfo.java │ │ │ └── TileMaker.java │ │ ├── download │ │ ├── FileDownloader.java │ │ └── MultiFileDownloader.java │ │ ├── engine │ │ ├── AbstractEngine.java │ │ ├── DeepLearningEngineInterface.java │ │ ├── EngineInfo.java │ │ ├── EngineLoader.java │ │ ├── ParentLastURLClassLoader.java │ │ ├── PythonEngine.java │ │ ├── engines │ │ │ ├── JaxEngine.java │ │ │ ├── KerasEngine.java │ │ │ ├── OnnxEngine.java │ │ │ ├── PytorchEngine.java │ │ │ └── TensorflowEngine.java │ │ └── installation │ │ │ └── EngineInstall.java │ │ ├── example │ │ ├── ExampleDownloadEngine.java │ │ ├── ExampleDownloadModel.java │ │ ├── ExampleLoadAndRunAllBmzModels.java │ │ ├── ExampleLoadAndRunModel.java │ │ ├── ExampleLoadPytorch1Pytorch2.java │ │ └── ExampleLoadTensorflow1Tensorflow2.java │ │ ├── exceptions │ │ ├── LoadEngineException.java │ │ ├── LoadModelException.java │ │ └── RunModelException.java │ │ ├── gui │ │ ├── ContentPanel.java │ │ ├── DefaultIcon.java │ │ ├── EnvironmentInstaller.java │ │ ├── Gui.java │ │ ├── GuiUtils.java │ │ ├── Header.java │ │ ├── HeaderGui.java │ │ ├── LogoPanel.java │ │ ├── ModelCard.java │ │ ├── ModelSelectionPanel.java │ │ ├── ModelSelectionPanelGui.java │ │ ├── SearchBar.java │ │ ├── YesNoDialog.java │ │ ├── adapter │ │ │ ├── GuiAdapter.java │ │ │ └── RunnerAdapter.java │ │ ├── custom │ │ │ ├── ButtonsPanel.java │ │ │ ├── CellposeGUI.java │ │ │ ├── CellposePluginUI.java │ │ │ ├── ConsumerInterface.java │ │ │ ├── FooterPanel.java │ │ │ ├── PlaceholderTextField.java │ │ │ └── StardistGUI.java │ │ └── workers │ │ │ ├── ImageLoaderWorker.java │ │ │ ├── InstallEnvWorker.java │ │ │ └── ModelInfoWorker.java │ │ ├── model │ │ ├── BaseModel.java │ │ ├── java │ │ │ ├── BioimageIoModelJava.java │ │ │ └── DLModelJava.java │ │ ├── processing │ │ │ ├── Processing.java │ │ │ └── TransformationInstance.java │ │ ├── python │ │ │ ├── BioimageIoModelPytorch.java │ │ │ ├── BioimageIoModelPytorchProtected.java │ │ │ ├── DLModelPytorch.java │ │ │ └── DLModelPytorchProtected.java │ │ └── special │ │ │ ├── cellpose │ │ │ └── Cellpose.java │ │ │ └── stardist │ │ │ ├── Stardist2D.java │ │ │ ├── Stardist3D.java │ │ │ └── StardistAbstract.java │ │ ├── numpy │ │ ├── ByteArrayUtils.java │ │ ├── DecodeImgLib2.java │ │ └── DecodeNumpy.java │ │ ├── runmode │ │ ├── RunMode.java │ │ ├── RunModeScripts.java │ │ └── ops │ │ │ ├── CellposeFineTuneJdllOp.java │ │ │ ├── CellposeInferJdllOp.java │ │ │ ├── CellposeTrainJdllOp.java │ │ │ ├── GenericOp.java │ │ │ ├── OpInterface.java │ │ │ ├── StardistFineTuneJdllOp.java │ │ │ └── StardistInferJdllOp.java │ │ ├── system │ │ ├── PlatformDetection.java │ │ └── Version.java │ │ ├── tensor │ │ ├── ImgLib2ToArray.java │ │ ├── ListToImgLib2.java │ │ ├── Tensor.java │ │ ├── Utils.java │ │ └── shm │ │ │ ├── CLibrary.java │ │ │ ├── LibRt.java │ │ │ ├── MacosHelpers.java │ │ │ ├── SharedMemoryArray.java │ │ │ ├── SharedMemoryArrayLinux.java │ │ │ ├── SharedMemoryArrayMacOS.java │ │ │ ├── SharedMemoryArrayWin.java │ │ │ └── SharedMemoryFile.java │ │ ├── transformations │ │ ├── AbstractTensorPixelTransformation.java │ │ ├── AbstractTensorTransformation.java │ │ ├── BinarizeTransformation.java │ │ ├── ClipTransformation.java │ │ ├── EnsureDtypeTransformation.java │ │ ├── FixedZeroMeanUnitVarianceTransformation.java │ │ ├── PythonTransformation.java │ │ ├── ScaleLinearTransformation.java │ │ ├── ScaleRangeTransformation.java │ │ ├── SigmoidTransformation.java │ │ ├── TensorTransformation.java │ │ └── ZeroMeanUnitVarianceTransformation.java │ │ ├── utils │ │ ├── CommonUtils.java │ │ ├── Constants.java │ │ ├── FileUtils.java │ │ ├── IndexingUtils.java │ │ ├── JSONUtils.java │ │ ├── Log.java │ │ ├── YAMLUtils.java │ │ └── ZipUtils.java │ │ └── versionmanagement │ │ ├── AvailableEngines.java │ │ ├── DeepLearningVersion.java │ │ ├── InstalledEngines.java │ │ ├── JarInfo.java │ │ ├── SupportedVersions.java │ │ └── VersionStringUtils.java │ └── resources │ ├── .jdll_properties │ ├── ShmCreate.dylib │ ├── appose-python.zip │ ├── availableDLVersions.json │ ├── jar_sizes.json │ ├── jdll_icons │ ├── search_logo.png │ └── search_logo_full_res.png │ ├── op_environments │ └── stardist.yaml │ ├── ops │ └── stardist_postprocessing │ │ ├── stardist_postprocessing.py │ │ └── stardist_postprocessing_3D.py │ ├── special_models │ └── cellpose │ │ └── rdf.yaml │ └── supportedVersions.json └── wiki ├── engines_folders.png └── vs_redist_snapshot.png /.github/build.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | curl -fsLO https://raw.githubusercontent.com/scijava/scijava-scripts/main/ci-build.sh 3 | sh ci-build.sh 4 | -------------------------------------------------------------------------------- /.github/get_jars_sizes.py: -------------------------------------------------------------------------------- 1 | import json 2 | import requests 3 | import argparse 4 | 5 | def get_file_size(url): 6 | response = requests.head(url, allow_redirects=True) 7 | if 'Content-Length' not in response.headers: 8 | raise Exception(f"Unable to find size of {url}") 9 | return int(response.headers['Content-Length']) 10 | 11 | # Parse command-line arguments 12 | parser = argparse.ArgumentParser(description="Get file sizes and save them to a target file.") 13 | parser.add_argument('target_file', type=str, help="Path to the target file where results will be saved.") 14 | args = parser.parse_args() 15 | 16 | # Assign the target file from the command-line argument 17 | target_file = args.target_file 18 | 19 | fname="src/main/resources/availableDLVersions.json" 20 | 21 | with open(fname, 'r') as ff: 22 | engines = json.load(ff) 23 | 24 | jar_dict = {} 25 | 26 | for engine in engines["versions"]: 27 | for jar in engine["jars"]: 28 | if jar in jar_dict.keys(): 29 | continue 30 | jar_dict[jar] = get_file_size(jar) 31 | 32 | 33 | with open(target_file, "w") as ff: 34 | json.dump(jar_dict, ff) 35 | -------------------------------------------------------------------------------- /.github/setup.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | curl -fsLO https://raw.githubusercontent.com/scijava/scijava-scripts/main/ci-setup-github-actions.sh 3 | sh ci-setup-github-actions.sh 4 | -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: build 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | tags: 8 | - "*-[0-9]+.*" 9 | paths-ignore: 10 | - .github/workflows/bioimageio_ci.yml 11 | pull_request: 12 | branches: 13 | - main 14 | 15 | jobs: 16 | build: 17 | runs-on: ubuntu-latest 18 | 19 | steps: 20 | - uses: actions/checkout@v2 21 | - name: Set up Java 22 | uses: actions/setup-java@v3 23 | with: 24 | java-version: '8' 25 | distribution: 'zulu' 26 | cache: 'maven' 27 | - name: Set up CI environment 28 | run: .github/setup.sh 29 | - name: Execute the build 30 | run: .github/build.sh 31 | env: 32 | GPG_KEY_NAME: ${{ secrets.GPG_KEY_NAME }} 33 | GPG_PASSPHRASE: ${{ secrets.GPG_PASSPHRASE }} 34 | MAVEN_USER: ${{ secrets.MAVEN_USER }} 35 | MAVEN_PASS: ${{ secrets.MAVEN_PASS }} 36 | OSSRH_PASS: ${{ secrets.OSSRH_PASS }} 37 | SIGNING_ASC: ${{ secrets.SIGNING_ASC }} 38 | -------------------------------------------------------------------------------- /.github/workflows/download_all_engines.yml: -------------------------------------------------------------------------------- 1 | name: Download all engines 2 | on: 3 | push: 4 | branches: 5 | - main 6 | paths: 7 | - src/main/resources/availableDLVersions.json 8 | - download-engines.py 9 | - .github/workflows/download_all_engines.yml 10 | pull_request: 11 | branches: [ main ] 12 | jobs: 13 | build-and-run: 14 | runs-on: ${{ matrix.os }} 15 | strategy: 16 | matrix: 17 | os: [macos-latest, ubuntu-latest, windows-latest] # macos-10.15, 18 | steps: 19 | - name: Checkout repository 20 | uses: actions/checkout@v2 21 | - name: Set up Python 3.9 22 | uses: actions/setup-python@v4 23 | with: 24 | python-version: 3.9 25 | - name: Download all engines 26 | run: | 27 | python download-engines.py 28 | -------------------------------------------------------------------------------- /.github/workflows/example_run_all_bmz_models.yml: -------------------------------------------------------------------------------- 1 | name: Run all Bioimage.io models 2 | on: 3 | push: 4 | branches: 5 | - main 6 | paths: 7 | - src/main/java/io/bioimage/modelrunner/example/ExampleLoadAndRunAllBmzModels.java 8 | - .github/workflows/example_run_all_bmz_models.yml 9 | schedule: 10 | - cron: '30 2 * * *' 11 | workflow_dispatch: 12 | release: 13 | types: 14 | - published 15 | jobs: 16 | build-and-run: 17 | runs-on: ${{ matrix.os }} 18 | strategy: 19 | matrix: 20 | os: [macos-latest, ubuntu-latest, windows-latest, macos-13] 21 | fail-fast: false 22 | steps: 23 | - name: Checkout repository 24 | uses: actions/checkout@v2 25 | - name: Set up JDK 11 26 | uses: actions/setup-java@v3 27 | with: 28 | distribution: 'zulu' # See 'Supported distributions' for available options 29 | java-version: '11' 30 | - name: Build with Maven 31 | run: mvn clean install 32 | 33 | - name: Generate Classpath (Unix) 34 | if: runner.os != 'Windows' 35 | run: echo "CLASSPATH=$(mvn -q exec:exec -Dexec.executable=echo -Dexec.args='%classpath')" >> $GITHUB_ENV 36 | 37 | - name: Generate Classpath (Windows) 38 | if: runner.os == 'Windows' 39 | shell: powershell 40 | run: | 41 | $classpath = mvn -q exec:exec "-Dexec.executable=echo" "-Dexec.args='%classpath'" 42 | echo "CLASSPATH=$classpath" | Out-File -FilePath $env:GITHUB_ENV -Append 43 | 44 | - name: Run ExampleLoadAndRunAllBmzModels.java (Unix) 45 | if: runner.os != 'Windows' 46 | run: java -cp $CLASSPATH:target/classes io.bioimage.modelrunner.example.ExampleLoadAndRunAllBmzModels 47 | 48 | - name: Run ExampleLoadAndRunAllBmzModels.java (Windows) 49 | if: runner.os == 'Windows' 50 | shell: powershell 51 | run: java -cp "$env:CLASSPATH;target/classes" io.bioimage.modelrunner.example.ExampleLoadAndRunAllBmzModels 52 | -------------------------------------------------------------------------------- /.github/workflows/example_run_pytorch1_2_model.yml: -------------------------------------------------------------------------------- 1 | name: Run Pytorch 1 and 2 2 | on: 3 | push: 4 | branches: 5 | - main 6 | paths-ignore: 7 | - .github/workflows/bioimageio_ci.yml 8 | - .github/workflows/jar_sizes.yml 9 | - .github/get_jars_sizes.py 10 | pull_request: 11 | branches: [ main ] 12 | jobs: 13 | build-and-run: 14 | runs-on: ${{ matrix.os }} 15 | strategy: 16 | matrix: 17 | os: [macos-latest, ubuntu-latest, windows-latest, macos-13] 18 | fail-fast: false 19 | steps: 20 | - name: Checkout repository 21 | uses: actions/checkout@v2 22 | - name: Set up JDK 11 23 | uses: actions/setup-java@v3 24 | with: 25 | distribution: 'zulu' # See 'Supported distributions' for available options 26 | java-version: '11' 27 | - name: Build with Maven 28 | run: mvn clean install 29 | - name: Generate Classpath (Unix) 30 | if: runner.os != 'Windows' 31 | run: | 32 | mvn clean install org.apache.maven.plugins:maven-shade-plugin:3.2.4:shade -Dshade.mainClass=io.bioimage.modelrunner.example.ExampleLoadPytorch1Pytorch2 33 | 34 | - name: Generate Classpath (Windows) 35 | if: runner.os == 'Windows' 36 | shell: powershell 37 | run: | 38 | $classpath = mvn -q exec:exec "-Dexec.executable=echo" "-Dexec.args='%classpath'" 39 | echo "CLASSPATH=$classpath" | Out-File -FilePath $env:GITHUB_ENV -Append 40 | 41 | - name: Write Version to File 42 | if: runner.os != 'Windows' 43 | run: | 44 | echo "$(mvn help:evaluate -Dexpression=project.version -q -DforceStdout)" > version.txt 45 | echo "JAR_PATH=target/dl-modelrunner-$(cat version.txt).jar" >> $GITHUB_ENV 46 | shell: bash 47 | - name: Run Specific Class (Unix) 48 | if: runner.os != 'Windows' 49 | shell: bash 50 | run: | 51 | java -cp $JAR_PATH io.bioimage.modelrunner.example.ExampleLoadPytorch1Pytorch2 52 | 53 | - name: Run Specific Class (Windows) 54 | if: runner.os == 'Windows' 55 | shell: powershell 56 | run: java -cp "$env:CLASSPATH;target/classes" io.bioimage.modelrunner.example.ExampleLoadPytorch1Pytorch2 57 | -------------------------------------------------------------------------------- /.github/workflows/example_run_tf1_and_tf2_model.yml: -------------------------------------------------------------------------------- 1 | name: Run Tensorflow 1 and Tensorflow 2 models 2 | on: 3 | push: 4 | branches: 5 | - main 6 | pull_request: 7 | branches: [ main ] 8 | paths-ignore: 9 | - .github/workflows/bioimageio_ci.yml 10 | - .github/workflows/jar_sizes.yml 11 | - .github/get_jars_sizes.py 12 | jobs: 13 | build-and-run: 14 | runs-on: ${{ matrix.os }} 15 | strategy: 16 | matrix: 17 | os: [macos-latest, ubuntu-latest, windows-latest, macos-13] 18 | fail-fast: false 19 | steps: 20 | - name: Checkout repository 21 | uses: actions/checkout@v2 22 | - name: Set up JDK 11 23 | uses: actions/setup-java@v3 24 | with: 25 | distribution: 'zulu' # See 'Supported distributions' for available options 26 | java-version: '11' 27 | - name: Build with Maven 28 | run: mvn clean install 29 | - name: Generate Classpath (Unix) 30 | if: runner.os != 'Windows' 31 | run: echo "CLASSPATH=$(mvn -q exec:exec -Dexec.executable=echo -Dexec.args='%classpath')" >> $GITHUB_ENV 32 | 33 | - name: Generate Classpath (Windows) 34 | if: runner.os == 'Windows' 35 | shell: powershell 36 | run: | 37 | $classpath = mvn -q exec:exec "-Dexec.executable=echo" "-Dexec.args='%classpath'" 38 | echo "CLASSPATH=$classpath" | Out-File -FilePath $env:GITHUB_ENV -Append 39 | 40 | - name: Run Specific Class (Unix) 41 | if: runner.os != 'Windows' 42 | run: java -cp $CLASSPATH:target/classes io.bioimage.modelrunner.example.ExampleLoadTensorflow1Tensorflow2 43 | 44 | - name: Run Specific Class (Windows) 45 | if: runner.os == 'Windows' 46 | shell: powershell 47 | run: java -cp "$env:CLASSPATH;target/classes" io.bioimage.modelrunner.example.ExampleLoadTensorflow1Tensorflow2 48 | -------------------------------------------------------------------------------- /.github/workflows/jar_sizes.yml: -------------------------------------------------------------------------------- 1 | name: Get jar sizes 2 | on: 3 | push: 4 | branches: 5 | - main 6 | paths: 7 | - src/main/resources/availableDLVersions.json 8 | - .github/workflows/jar_sizes.yml 9 | - .github/get_jars_sizes.py 10 | workflow_dispatch: 11 | 12 | 13 | env: 14 | FPATH: "src/main/resources/jar_sizes.json" 15 | jobs: 16 | build-and-run: 17 | runs-on: ubuntu-latest 18 | 19 | steps: 20 | - name: Check out repository 21 | uses: actions/checkout@v4 22 | 23 | - name: Set up Python 24 | uses: actions/setup-python@v4 25 | with: 26 | python-version: '3.11' 27 | 28 | - name: Install dep 29 | run: python -m pip install requests 30 | 31 | - name: Get file sizes and generate JSON 32 | run: python .github/get_jars_sizes.py ${{ env.FPATH }} 33 | 34 | - name: Commit and push changes 35 | run: | 36 | # Configure Git 37 | git config user.name "github-actions" 38 | git config user.email "github-actions@github.com" 39 | 40 | # Only commit/push if there are changes 41 | if [ -n "$(git status --porcelain)" ]; then 42 | git add ${{ env.FPATH }} 43 | git commit -m "Update file sizes" 44 | git push 45 | else 46 | echo "No changes to commit." 47 | fi 48 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /engines/ 2 | /models/ 3 | 4 | # maven specific files 5 | /target/ 6 | 7 | # eclipse specific files 8 | /.settings/ 9 | .classpath 10 | .project 11 | 12 | # intellij specific files 13 | .idea 14 | 15 | # miscellaneous 16 | *.swp 17 | 18 | prep.sh 19 | -------------------------------------------------------------------------------- /download-engines.py: -------------------------------------------------------------------------------- 1 | import json 2 | from pathlib import Path 3 | import platform 4 | import sys 5 | import traceback 6 | import urllib.request 7 | 8 | # HACK: Disable SSL certification validation for urllib. 9 | # Because otherwise we see for all attempts ;-) : 10 | # urllib.error.URLError: 11 | import ssl 12 | ssl._create_default_https_context = ssl._create_unverified_context 13 | 14 | engine_filter = sys.argv[1] if len(sys.argv) > 1 else '' 15 | version_filter = sys.argv[2] if len(sys.argv) > 2 else '' 16 | 17 | with open("src/main/resources/availableDLVersions.json") as f: 18 | data = json.load(f) 19 | 20 | my_os = platform.system().lower() 21 | if my_os == "darwin": 22 | my_os = "macosx" 23 | machine = platform.machine() 24 | if my_os == "windows" and machine.endswith('64'): 25 | machine = "x86_64" 26 | my_os = f"{my_os}-{machine}" 27 | 28 | for entry in data["versions"]: 29 | engine = entry["framework"] 30 | version = entry["version"] 31 | pythonVersion = entry["pythonVersion"] 32 | 33 | if ( 34 | engine_filter.lower() not in engine.lower() or 35 | version_filter.lower() not in version.lower() 36 | ): 37 | continue 38 | 39 | os = entry["os"] 40 | if os != my_os: 41 | continue 42 | 43 | gpu = "-gpu" if entry["gpu"] else "" 44 | cpu = "-cpu" if entry["cpu"] else "" 45 | rosetta = entry["rosetta"] 46 | jars = entry["jars"] 47 | 48 | # From the README: 49 | # ....... 50 | # But it's actually dashes, not dots. 51 | folder_name = f"{engine}-{pythonVersion}-{version}-{os}{cpu}{gpu}" 52 | 53 | print(folder_name) 54 | 55 | # download each JAR into the folder 56 | engine_dir = Path(".") / "engines" / folder_name 57 | engine_dir.mkdir(parents=True, exist_ok=True) 58 | for jar_url in jars: 59 | jar_name = Path(jar_url).name 60 | jar_path = engine_dir / jar_name 61 | if jar_path.exists(): 62 | continue 63 | print(f"{engine_dir}: downloading {jar_url}") 64 | try: 65 | urllib.request.urlretrieve(jar_url, jar_path) 66 | except: 67 | print(f"[ERROR] Failed to download {jar_url}") 68 | traceback.print_exc() 69 | sys.exit(1) 70 | -------------------------------------------------------------------------------- /lib/ShmCreate.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | // Function to get the size of a shared memory segment given its file descriptor 9 | long get_shared_memory_size(int fd) { 10 | struct stat shm_stat; 11 | if (fstat(fd, &shm_stat) == -1) { 12 | perror("fstat"); 13 | return -1; 14 | } 15 | return (long)shm_stat.st_size; 16 | } 17 | 18 | // Function to create a shared memory segment, modified to accept a long for size 19 | int create_shared_memory(const char *name, long size) { 20 | int fd = shm_open(name, O_CREAT | O_RDWR, 0666); 21 | if (fd < 0) { 22 | perror("shm_open"); 23 | return -1; 24 | } 25 | long already_size = get_shared_memory_size(fd); 26 | if (already_size > 0) { 27 | return fd; 28 | } 29 | 30 | if (ftruncate(fd, size) == -1) { 31 | perror("ftruncate"); 32 | close(fd); 33 | return -1; 34 | } 35 | 36 | return fd; 37 | } 38 | 39 | // Function to unlink a shared memory segment 40 | void unlink_shared_memory(const char *name) { 41 | if (shm_unlink(name) == -1) { 42 | perror("shm_unlink"); 43 | } 44 | } 45 | 46 | int main() { 47 | const char *shm_name = "/myshm"; 48 | size_t shm_size = 1024; 49 | 50 | // Create shared memory 51 | int shm_fd = create_shared_memory(shm_name, shm_size); 52 | if (shm_fd < 0) { 53 | exit(EXIT_FAILURE); 54 | } 55 | 56 | // Perform operations with shared memory here 57 | // ... 58 | 59 | // Close the shared memory file descriptor 60 | close(shm_fd); 61 | 62 | // Unlink shared memory 63 | unlink_shared_memory(shm_name); 64 | 65 | return 0; 66 | } 67 | 68 | -------------------------------------------------------------------------------- /python/op_environments/stardist_environment.yaml: -------------------------------------------------------------------------------- 1 | name: stardist_op 2 | channels: 3 | - conda-forge 4 | - defaults 5 | dependencies: 6 | - bioimageio.core 7 | - black 8 | - conda-build 9 | - dask 10 | - mypy 11 | - pip 12 | - python==3.9.* 13 | - stardist 14 | - tensorflow==2.* 15 | - xarray -------------------------------------------------------------------------------- /python/op_environments/stardist_postprocessing.yaml: -------------------------------------------------------------------------------- 1 | name: stardist 2 | channels: 3 | - conda-forge 4 | - defaults 5 | dependencies: 6 | - python=3.10 7 | - appose 8 | - numpy 9 | - xarray 10 | - stardist 11 | -------------------------------------------------------------------------------- /python/ops/stardist_fine_tune/stardist_fine_tune.py: -------------------------------------------------------------------------------- 1 | import xarray as xr 2 | from stardist.models import StarDist2D 3 | 4 | import os 5 | import shutil 6 | import os 7 | from pathlib import Path 8 | 9 | 10 | def assertions(model_path, images, ground_truth, ): 11 | 12 | assert isinstance(model_path, str), "The input argument 'model_path' must be a string, either the name" \ 13 | + " of one of the default pre-trained Stardist models or the directory to a pre-trained Stardist model" 14 | 15 | assert isinstance(images, xr.DataArray), "the training samples should be a xr.DataArray" 16 | assert isinstance(ground_truth, xr.DataArray), "the ground thruth should be a xr.DataArray" 17 | 18 | assert images.ndim == 4, "the training samples array must have 4 dimensions" 19 | assert ground_truth.ndim == 3, "the training samples array must have 3 dimensions" 20 | 21 | assert "".join(images.dims) == "byxc", "the training samples axes order should be 'byxc', not '" + "".join(images.dims) + "' as provided." 22 | assert "".join(ground_truth.dims) == "byx", "the ground truth samples axes order should be 'byx', not '" + "".join(ground_truth.dims) + "' as provided." 23 | 24 | axes_dict = {"batch size": 0, "width": 1, "height": 2} 25 | 26 | for ks, vs in axes_dict.items(): 27 | assert images.shape[vs] == ground_truth.shape[vs], "The training samples " \ 28 | + "and the ground truth need to have the same " + ks + " : " \ 29 | + str(images.shape[vs]) + " vs " + str(ground_truth.shape[vs]) 30 | 31 | 32 | def finetune_stardist(model_path, images, ground_truth, weights_file=None): 33 | """ 34 | model_path: String, path to pretrained model or pretrained model from the stardsit available 35 | images: list of tensors or single tensor? If a list of tensors, it would need to be ensured taht they all have same dims, 36 | or reconstruct to have same dims. Check the number of channels and check if the channels of the images coincide 37 | Also for a path, check that it has the needed files fo a stardist model 38 | ground_truth: list of tensors or single tensor? It needs to have the same type and size than images 39 | 40 | epochs and batch_size might have a warning for CPu if selected too large 41 | """ 42 | assertions(model_path, images, ground_truth) 43 | 44 | model = StarDist2D(None, model_path) 45 | if weights_file is not None: 46 | model.load_weights("weights_last.h5") 47 | 48 | # finetune on new data 49 | history = model.train(images, ground_truth, validation_data=(images, ground_truth)) 50 | 51 | Path(model_path).mkdir(parents=True, exist_ok=True) 52 | #model.keras_model.save(os.path.join(model_path, "stardist_weights.h5")) 53 | model.export_TF(os.path.join(os.path.dirname(model_path), "TF_SavedModel.zip")) 54 | 55 | return history.history -------------------------------------------------------------------------------- /scripts/example-download-bmz-model.py: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2023 Institut Pasteur. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | # ============================================================================ 15 | 16 | """Jython script that downloads the wanted model from the Bioimage.io repository 17 | into the wanted folder. 18 | The example model downloaded is: 19 | - B. Sutilist bacteria segmentation - Widefield microscopy - 2D UNet 20 | and can be found at: https://bioimage.io/#/?tags=B.%20Sutilist%20bacteria%20segmentation%20-%20Widefield%20microscopy%20-%202D%20UNet&id=10.5281%2Fzenodo.7261974 21 | 22 | To run this script with the default parameters: 23 | python example-download-bmz-model.py 24 | 25 | In order to download the wanted model in the wanted directory, 26 | please provide *two* parameters: 27 | python example-download-bmz-model.py name_of_the_wanted_model /path/to/the/wanted/model 28 | 29 | """ 30 | 31 | from io.bioimage.modelrunner.bioimageio import BioimageioRepo 32 | import sys 33 | import os 34 | 35 | 36 | full_path = os.path.join(os. getcwd(), "models") 37 | bmzModelName = "B. Sutilist bacteria segmentation - Widefield microscopy - 2D UNet" 38 | 39 | if len(sys.argv) != 1 and len(sys.argv) == 3: 40 | raise TypeError("Script only works either when no arguments are provided or "\ 41 | + "when 2 String arguments are provided.") 42 | if len(sys.argv) == 3: 43 | bmzModelName = sys.argv[1] 44 | full_path = sys.argv[2] 45 | 46 | if not os.path.exists(full_path) or not os.path.isdir(full_path): 47 | os.makedirs(full_path) 48 | 49 | print("Connecting to the Bioimage.io repository") 50 | br = BioimageioRepo.connect() 51 | print("Downloading the Bioimage.io model: " + bmzModelName) 52 | modelDir = br.downloadByName(bmzModelName, full_path) 53 | 54 | print("Model downloaded at: " + modelDir) 55 | -------------------------------------------------------------------------------- /scripts/example-download-engine.py: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2023 Institut Pasteur. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | # ============================================================================ 15 | 16 | """Jython script that downloads the wanted DL engine into the wanted folder. 17 | The default example engine downloaded is: 18 | - Tensorflow 2.7.0 for CPU and GPU 19 | 20 | 21 | To download and install the default example engine, run the script with no parameters: 22 | 23 | python example-download-engine.py 24 | 25 | In order to download the wanted engine in the wanted directory, 26 | please provide *five* parameters:. The first one should be the framework 27 | name, the second one the frmaework version, the third one True or False whether 28 | CPU is supported or not, the fourth one True or False whether GPU is supported 29 | or not, and the fifth should be the directory where the engine is installed: 30 | 31 | python example-download-engine.py framework_name version true_or_false true_or_false 32 | 33 | 34 | A list of the supported DL frameworks and versions can be found at: 35 | https://github.com/bioimage-io/JDLL/wiki/List-of-supported-engines 36 | 37 | Executing the script without parameters is equal to executing it with the 38 | following parameters: 39 | 40 | python example-download-engine.py tensorflow 2.7.0 True True models 41 | """ 42 | 43 | from io.bioimage.modelrunner.engine.installation import EngineInstall 44 | from io.bioimage.modelrunner.versionmanagement import AvailableEngines 45 | import sys 46 | import os 47 | 48 | framework_list = ["tensorflow", "tensorflow_saved_model_bundle", 49 | "torchscript", "pytorch", "onnx"] 50 | full_path = os.path.join(os. getcwd(), "engines") 51 | framework = "tensorflow" 52 | version = "2.7.0" 53 | cpu = True 54 | gpu = True 55 | 56 | if len(sys.argv) != 1 and len(sys.argv) == 6: 57 | raise TypeError("Script only works either when no arguments are provided or "\ 58 | + "when 6 arguments are provided.") 59 | 60 | if len(sys.argv) == 6 and type(sys.argv[3]) == bool: 61 | expected_types = [str, str, bool, bool, str] 62 | for i, arg in enumerate(sys.argv, start=1): 63 | if not isinstance(arg, expected_types[i]): 64 | err_str = "Argument " + str(i) + " is not of the correct data type " \ 65 | + str(expected_types[i]) 66 | raise TypeError(err_str) 67 | elif len(sys.argv) == 6 and sys.argv[1] not in framework_list: 68 | raise TypeError("First argument for the script should be among the supported" \ 69 | + " DL frameworks: " + str(framework_list)) 70 | elif len(sys.argv) == 6: 71 | framework = sys.argv[1] 72 | version = sys.argv[2] 73 | cpu = sys.argv[3] 74 | gpu = sys.argv[4] 75 | full_path = sys.argv[5] 76 | 77 | ## Get the engines compatible with the params introduced 78 | supp_engines = AvailableEngines.getEnginesForOsByParams(framework, version, cpu, gpu) 79 | if len(supp_engines) == 0: 80 | raise Error("JDLL does not support a engine with the introduced arguments") 81 | 82 | if not os.path.exists(full_path) or not os.path.isdir(full_path): 83 | os.makedirs(full_path) 84 | 85 | print("Installing JDLL engine") 86 | success = EngineInstall.installEngineWithArgsInDir(framework, 87 | version, cpu, gpu, full_path) 88 | if (success): 89 | print("Engine correctly installed at: " + full_path) 90 | else: 91 | print("Error with the engine installation.") 92 | -------------------------------------------------------------------------------- /scripts/example-run-pytorch-model-in-fiji.py: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2023 Institut Pasteur. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | # ============================================================================ 15 | 16 | """Jython script that downloads the wanted Pytorch model from the Bioimage.io repository, 17 | downloads the engine and executes it on the sample image. 18 | The example model downloaded is: 19 | - Mitochondria resolution enhancement Wasserstein GAN 20 | and can be found at: https://bioimage.io/#/?type=all&tags=Mitochondria%20resolution%20enhancement%20Wasserstein%20GAN&id=10.5281%2Fzenodo.7786492 21 | 22 | To run this script with the default parameters: 23 | python example-run-pytorch-model-in-fiji.py 24 | 25 | 26 | """ 27 | from io.bioimage.modelrunner.engine.installation import EngineInstall 28 | from io.bioimage.modelrunner.bioimageio import BioimageioRepo 29 | from io.bioimage.modelrunner.model import Model 30 | from io.bioimage.modelrunner.tensor import Tensor 31 | from io.bioimage.modelrunner.versionmanagement import AvailableEngines 32 | 33 | import sys 34 | import os 35 | 36 | from ij import IJ 37 | 38 | from net.imglib2.img.display.imagej import ImageJFunctions 39 | from net.imglib2.view import Views 40 | 41 | 42 | models_path = os.path.join(os. getcwd(), "models") 43 | engine_path = os.path.join(os. getcwd(), "engines") 44 | bmzModelName = "Mitochondria resolution enhancement Wasserstein GAN" 45 | 46 | if not os.path.exists(models_path) or not os.path.isdir(models_path): 47 | os.makedirs(models_path) 48 | 49 | print("Connecting to the Bioimage.io repository") 50 | br = BioimageioRepo.connect() 51 | print("Downloading the Bioimage.io model: " + bmzModelName) 52 | model_fn = br.downloadByName(bmzModelName, models_path) 53 | 54 | print("Model downloaded at: " + model_fn) 55 | 56 | print("Download the engine required for the model") 57 | if not os.path.exists(engine_path) or not os.path.isdir(engine_path): 58 | os.makedirs(engine_path) 59 | 60 | print("Installing JDLL engine") 61 | supportedList = AvailableEngines.getEnginesForOsByParams("pytorch", "1.13.1", True, None) 62 | gpu = supportedList[0].getGPU() 63 | success = EngineInstall.installEngineWithArgsInDir("pytorch", 64 | "1.13.1", True, gpu, engine_path) 65 | if (success): 66 | print("Engine correctly installed at: " + engine_path) 67 | else: 68 | raise Error("Error with the engine installation.") 69 | 70 | imp = IJ.openImage(os.path.join(model_fn, "sample_input_0.tif")) 71 | imp.show() 72 | 73 | wrapImg = ImageJFunctions.convertFloat(imp) 74 | wrapImg = Views.addDimension(wrapImg, 0, 0) 75 | wrapImg = Views.addDimension(wrapImg, 0, 0) 76 | wrapImg = Views.permute(wrapImg, 0, 2) 77 | wrapImg = Views.permute(wrapImg, 1, 3) 78 | 79 | inputTensor = Tensor.build("input", "bcxy", wrapImg) 80 | outputTensor = Tensor.buildEmptyTensor("output", "bcxy") 81 | 82 | 83 | model = Model.createBioimageioModel(model_fn, engine_path) 84 | print("Loading model") 85 | model.loadModel() 86 | print("Running model") 87 | 88 | model.runModel([inputTensor], [outputTensor]) 89 | ImageJFunctions.show( Views.dropSingletonDimensions(outputTensor.getData()) ) 90 | print("Display output") 91 | model.closeModel() 92 | 93 | inputTensor.close() 94 | outputTensor.close() 95 | -------------------------------------------------------------------------------- /scripts/example-run-tf2-model-in-fiji.py: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2023 Institut Pasteur. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | # ============================================================================ 15 | 16 | """Jython script that downloads the wanted Tensorflow 2 model from the Bioimage.io repository, 17 | downloads the engine and executes it on the sample image. 18 | The example model downloaded is: 19 | - B. Sutilist bacteria segmentation - Widefield microscopy - 2D UNet 20 | and can be found at: https://bioimage.io/#/?tags=B.%20Sutilist%20bacteria%20segmentation%20-%20Widefield%20microscopy%20-%202D%20UNet&id=10.5281%2Fzenodo.7261974 21 | 22 | To run this script with the default parameters: 23 | python example-run-tf2-model-in-fiji.py 24 | 25 | Note that this example will not work on Apple Silicon machines or any computer with ARM64 chips. 26 | 27 | """ 28 | from io.bioimage.modelrunner.engine.installation import EngineInstall 29 | from io.bioimage.modelrunner.bioimageio import BioimageioRepo 30 | from io.bioimage.modelrunner.model import Model 31 | from io.bioimage.modelrunner.tensor import Tensor 32 | from io.bioimage.modelrunner.transformations import ScaleRangeTransformation 33 | from io.bioimage.modelrunner.system import PlatformDetection 34 | 35 | import sys 36 | import os 37 | 38 | from ij import IJ 39 | 40 | from net.imglib2.img.display.imagej import ImageJFunctions 41 | from net.imglib2.view import Views 42 | 43 | if PlatformDetection.isUsingRosseta(): 44 | IJ.error("This script does not work on computers using ARM64 chips.") 45 | sys.exit() 46 | 47 | 48 | models_path = os.path.join(os. getcwd(), "models") 49 | engine_path = os.path.join(os. getcwd(), "engines") 50 | bmzModelName = "B. Sutilist bacteria segmentation - Widefield microscopy - 2D UNet" 51 | 52 | if not os.path.exists(models_path) or not os.path.isdir(models_path): 53 | os.makedirs(models_path) 54 | 55 | print("Connecting to the Bioimage.io repository") 56 | br = BioimageioRepo.connect() 57 | print("Downloading the Bioimage.io model: " + bmzModelName) 58 | model_fn = br.downloadByName(bmzModelName, models_path) 59 | 60 | print("Model downloaded at: " + model_fn) 61 | 62 | print("Download the engine required for the model") 63 | if not os.path.exists(engine_path) or not os.path.isdir(engine_path): 64 | os.makedirs(engine_path) 65 | 66 | print("Installing JDLL engine") 67 | success = EngineInstall.installEngineWithArgsInDir("tensorflow", 68 | "2.7.0", True, False, engine_path) 69 | if (success): 70 | print("Engine correctly installed at: " + engine_path) 71 | else: 72 | raise Error("Error with the engine installation.") 73 | 74 | imp = IJ.openImage(os.path.join(model_fn, "sample_input_0.tif")) 75 | imp.show() 76 | 77 | wrapImg = ImageJFunctions.convertFloat(imp) 78 | wrapImg = Views.permute(wrapImg, 0, 1) 79 | wrapImg = Views.addDimension(wrapImg, 0, 0) 80 | wrapImg = Views.permute(wrapImg, 0, 2) 81 | wrapImg = Views.addDimension(wrapImg, 0, 0) 82 | 83 | inputTensor = Tensor.build("input_1", "bxyc", wrapImg) 84 | print("Pre-process input tensor") 85 | transform = ScaleRangeTransformation() 86 | transform.setMinPercentile(1) 87 | transform.setMaxPercentile(99.8) 88 | transform.setMode("per_sample") 89 | transform.setAxes("xyc") 90 | transform.applyInPlace(inputTensor) 91 | outputTensor = Tensor.buildEmptyTensor("conv2d_19", "bxyc") 92 | 93 | 94 | model = Model.createBioimageioModel(model_fn, engine_path) 95 | print("Loading model") 96 | model.loadModel() 97 | print("Running model") 98 | 99 | model.runModel([inputTensor], [outputTensor]) 100 | ImageJFunctions.show( Views.dropSingletonDimensions(outputTensor.getData()) ) 101 | print("Display output") 102 | model.closeModel() 103 | 104 | inputTensor.close() 105 | outputTensor.close() 106 | 107 | 108 | -------------------------------------------------------------------------------- /src/main/java/io/bioimage/modelrunner/apposed/appose/Builder.java: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * Appose: multi-language interprocess cooperation with shared memory. 4 | * %% 5 | * Copyright (C) 2023 Appose developers. 6 | * %% 7 | * Redistribution and use in source and binary forms, with or without 8 | * modification, are permitted provided that the following conditions are met: 9 | * 10 | * 1. Redistributions of source code must retain the above copyright notice, 11 | * this list of conditions and the following disclaimer. 12 | * 2. Redistributions in binary form must reproduce the above copyright notice, 13 | * this list of conditions and the following disclaimer in the documentation 14 | * and/or other materials provided with the distribution. 15 | * 16 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 17 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 18 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 19 | * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE 20 | * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 21 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 22 | * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 23 | * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 24 | * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 25 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 26 | * POSSIBILITY OF SUCH DAMAGE. 27 | * #L% 28 | */ 29 | 30 | package io.bioimage.modelrunner.apposed.appose; 31 | 32 | import java.io.File; 33 | import java.io.IOException; 34 | import java.net.URISyntaxException; 35 | 36 | import org.apache.commons.compress.archivers.ArchiveException; 37 | 38 | //TODO remove once appose project is released with the needed changes 39 | //TODO remove once appose project is released with the needed changes 40 | //TODO remove once appose project is released with the needed changes 41 | //TODO remove once appose project is released with the needed changes 42 | //TODO remove once appose project is released with the needed changes 43 | public class Builder { 44 | 45 | 46 | public Environment build() { 47 | String base = baseDir.getPath(); 48 | boolean useSystemPath = systemPath; 49 | 50 | // TODO Build the thing!~ 51 | // Hash the state to make a base directory name. 52 | // - Construct conda environment from condaEnvironmentYaml. 53 | // - Download and unpack JVM of the given vendor+version. 54 | // - Populate ${baseDirectory}/jars with Maven artifacts? 55 | 56 | try { 57 | Mamba conda = new Mamba(Mamba.BASE_PATH); 58 | conda.installMicromamba(); 59 | String envName = "appose"; 60 | if (conda.getEnvironmentNames().contains( envName )) { 61 | // TODO: Should we update it? For now, we just use it. 62 | } 63 | else { 64 | conda.createWithYaml(envName, condaEnvironmentYaml.getAbsolutePath()); 65 | } 66 | } catch (IOException e) { 67 | throw new RuntimeException(e); 68 | } catch (InterruptedException e) { 69 | throw new RuntimeException(e); 70 | } catch (ArchiveException e) { 71 | throw new RuntimeException(e); 72 | } catch (URISyntaxException e) { 73 | throw new RuntimeException(e); 74 | } catch (MambaInstallException e) { 75 | throw new RuntimeException(e); 76 | } 77 | 78 | return new Environment() { 79 | @Override public String base() { return base; } 80 | @Override public boolean useSystemPath() { return useSystemPath; } 81 | }; 82 | } 83 | 84 | // -- Configuration -- 85 | 86 | private boolean systemPath; 87 | 88 | public Builder useSystemPath() { 89 | systemPath = true; 90 | return this; 91 | } 92 | 93 | private File baseDir; 94 | 95 | public Builder base(File directory) { 96 | baseDir = directory; 97 | return this; 98 | } 99 | 100 | // -- Conda -- 101 | 102 | private File condaEnvironmentYaml; 103 | 104 | public Builder conda(File environmentYaml) { 105 | this.condaEnvironmentYaml = environmentYaml; 106 | return this; 107 | } 108 | 109 | // -- Java -- 110 | 111 | private String javaVendor; 112 | private String javaVersion; 113 | 114 | public Builder java(String vendor, String version) { 115 | this.javaVendor = vendor; 116 | this.javaVersion = version; 117 | return this; 118 | } 119 | } 120 | -------------------------------------------------------------------------------- /src/main/java/io/bioimage/modelrunner/apposed/appose/CondaException.java: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * Use deep learning frameworks from Java in an agnostic and isolated way. 4 | * %% 5 | * Copyright (C) 2022 - 2024 Institut Pasteur and BioImage.IO developers. 6 | * %% 7 | * Licensed under the Apache License, Version 2.0 (the "License"); 8 | * you may not use this file except in compliance with the License. 9 | * You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, software 14 | * distributed under the License is distributed on an "AS IS" BASIS, 15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | * See the License for the specific language governing permissions and 17 | * limitations under the License. 18 | * #L% 19 | */ 20 | package io.bioimage.modelrunner.apposed.appose; 21 | 22 | //TODO remove once appose project is released with the needed changes 23 | //TODO remove once appose project is released with the needed changes 24 | //TODO remove once appose project is released with the needed changes 25 | //TODO remove once appose project is released with the needed changes 26 | //TODO remove once appose project is released with the needed changes 27 | public class CondaException 28 | { 29 | 30 | public static class EnvironmentExistsException extends RuntimeException 31 | { 32 | private static final long serialVersionUID = -1625119813967214783L; 33 | 34 | /** 35 | * Constructs a new exception with {@code null} as its detail message. The cause 36 | * is not initialized, and may subsequently be initialized by a call to 37 | * {@link #initCause}. 38 | */ 39 | public EnvironmentExistsException() 40 | { 41 | super(); 42 | } 43 | 44 | /** 45 | * Constructs a new exception with the specified detail message. The cause is 46 | * not initialized, and may subsequently be initialized by a call to 47 | * {@link #initCause}. 48 | * 49 | * @param msg 50 | * the detail message. The detail message is saved for later 51 | * retrieval by the {@link #getMessage()} method. 52 | */ 53 | public EnvironmentExistsException( String msg ) 54 | { 55 | super( msg ); 56 | } 57 | 58 | /** 59 | * Constructs a new exception with the specified detail message and cause. 60 | *

61 | * Note that the detail message associated with {@code cause} is not 62 | * automatically incorporated in this exception's detail message. 63 | * 64 | * @param message 65 | * the detail message (which is saved for later retrieval by the 66 | * {@link #getMessage()} method). 67 | * @param cause 68 | * the cause (which is saved for later retrieval by the 69 | * {@link #getCause()} method). (A null value is permitted, 70 | * and indicates that the cause is nonexistent or unknown.) 71 | * @since 1.4 72 | */ 73 | public EnvironmentExistsException( String message, Throwable cause ) 74 | { 75 | super( message, cause ); 76 | } 77 | 78 | /** 79 | * Constructs a new exception with the specified cause and a detail message of 80 | * (cause==null ? null : cause.toString()) (which typically contains 81 | * the class and detail message of cause). This constructor is useful 82 | * for exceptions that are little more than wrappers for other throwables (for 83 | * example, {@link java.security.PrivilegedActionException}). 84 | * 85 | * @param cause 86 | * the cause (which is saved for later retrieval by the 87 | * {@link #getCause()} method). (A null value is permitted, 88 | * and indicates that the cause is nonexistent or unknown.) 89 | * @since 1.4 90 | */ 91 | public EnvironmentExistsException( Throwable cause ) 92 | { 93 | super( cause ); 94 | } 95 | 96 | /** 97 | * Constructs a new exception with the specified detail message, cause, 98 | * suppression enabled or disabled, and writable stack trace enabled or 99 | * disabled. 100 | * 101 | * @param message 102 | * the detail message. 103 | * @param cause 104 | * the cause. (A {@code null} value is permitted, and indicates that 105 | * the cause is nonexistent or unknown.) 106 | * @param enableSuppression 107 | * whether or not suppression is enabled or disabled 108 | * @param writableStackTrace 109 | * whether or not the stack trace should be writable 110 | * @since 1.7 111 | */ 112 | protected EnvironmentExistsException( String message, Throwable cause, 113 | boolean enableSuppression, 114 | boolean writableStackTrace ) 115 | { 116 | super( message, cause, enableSuppression, writableStackTrace ); 117 | } 118 | } 119 | 120 | } 121 | -------------------------------------------------------------------------------- /src/main/java/io/bioimage/modelrunner/apposed/appose/FilePaths.java: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * Use deep learning frameworks from Java in an agnostic and isolated way. 4 | * %% 5 | * Copyright (C) 2022 - 2024 Institut Pasteur and BioImage.IO developers. 6 | * %% 7 | * Licensed under the Apache License, Version 2.0 (the "License"); 8 | * you may not use this file except in compliance with the License. 9 | * You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, software 14 | * distributed under the License is distributed on an "AS IS" BASIS, 15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | * See the License for the specific language governing permissions and 17 | * limitations under the License. 18 | * #L% 19 | */ 20 | 21 | package io.bioimage.modelrunner.apposed.appose; 22 | 23 | import java.io.File; 24 | import java.net.URISyntaxException; 25 | import java.nio.file.Paths; 26 | import java.util.List; 27 | 28 | //TODO remove once appose project is released with the needed changes 29 | //TODO remove once appose project is released with the needed changes 30 | //TODO remove once appose project is released with the needed changes 31 | //TODO remove once appose project is released with the needed changes 32 | //TODO remove once appose project is released with the needed changes 33 | /** 34 | * Utility methods for working with file paths. 35 | */ 36 | public final class FilePaths { 37 | 38 | private FilePaths() { 39 | // Prevent instantiation of utility class. 40 | } 41 | 42 | /** 43 | * Gets the path to the JAR file containing the given class. Technically 44 | * speaking, it might not actually be a JAR file, it might be a raw class 45 | * file, or even something weirder... But for our purposes, we'll just 46 | * assume it's going to be something you can put onto a classpath. 47 | * 48 | * @param c The class whose file path should be discerned. 49 | * @return File path of the JAR file containing the given class. 50 | */ 51 | public static File location(Class c) { 52 | try { 53 | return new File(c.getProtectionDomain().getCodeSource().getLocation().toURI()); 54 | } 55 | catch (URISyntaxException exc) { 56 | return null; 57 | } 58 | } 59 | 60 | public static File findExe(List dirs, List exes) { 61 | for (String exe : exes) { 62 | File exeFile = new File(exe); 63 | if (exeFile.isAbsolute()) { 64 | // Candidate is an absolute path; check it directly. 65 | if (exeFile.canExecute()) return exeFile; 66 | } 67 | else { 68 | // Candidate is a relative path; check beneath each given directory. 69 | for (String dir : dirs) { 70 | File f = Paths.get(dir, exe).toFile(); 71 | if (f.canExecute()) return f; 72 | } 73 | } 74 | } 75 | return null; 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /src/main/java/io/bioimage/modelrunner/apposed/appose/MambaInstallException.java: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * Use deep learning frameworks from Java in an agnostic and isolated way. 4 | * %% 5 | * Copyright (C) 2022 - 2024 Institut Pasteur and BioImage.IO developers. 6 | * %% 7 | * Licensed under the Apache License, Version 2.0 (the "License"); 8 | * you may not use this file except in compliance with the License. 9 | * You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, software 14 | * distributed under the License is distributed on an "AS IS" BASIS, 15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | * See the License for the specific language governing permissions and 17 | * limitations under the License. 18 | * #L% 19 | */ 20 | package io.bioimage.modelrunner.apposed.appose; 21 | 22 | /** 23 | * Exception to be thrown when Micromamba is not found in the wanted directory 24 | * 25 | * @author Carlos Javier Garcia Lopez de Haro 26 | */ 27 | public class MambaInstallException extends Exception { 28 | 29 | private static final long serialVersionUID = 1L; 30 | 31 | /** 32 | * Constructs a new exception with the default detail message 33 | */ 34 | public MambaInstallException() { 35 | super("Micromamba installation not found in the provided directory."); 36 | } 37 | 38 | /** 39 | * Constructs a new exception with the specified detail message 40 | * @param message 41 | * the detail message. 42 | */ 43 | public MambaInstallException(String message) { 44 | super(message); 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/io/bioimage/modelrunner/apposed/appose/TaskEvent.java: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * Appose: multi-language interprocess cooperation with shared memory. 4 | * %% 5 | * Copyright (C) 2023 Appose developers. 6 | * %% 7 | * Redistribution and use in source and binary forms, with or without 8 | * modification, are permitted provided that the following conditions are met: 9 | * 10 | * 1. Redistributions of source code must retain the above copyright notice, 11 | * this list of conditions and the following disclaimer. 12 | * 2. Redistributions in binary form must reproduce the above copyright notice, 13 | * this list of conditions and the following disclaimer in the documentation 14 | * and/or other materials provided with the distribution. 15 | * 16 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 17 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 18 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 19 | * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE 20 | * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 21 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 22 | * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 23 | * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 24 | * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 25 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 26 | * POSSIBILITY OF SUCH DAMAGE. 27 | * #L% 28 | */ 29 | 30 | package io.bioimage.modelrunner.apposed.appose; 31 | 32 | import io.bioimage.modelrunner.apposed.appose.Service.ResponseType; 33 | 34 | //TODO remove once appose project is released with the needed changes 35 | //TODO remove once appose project is released with the needed changes 36 | //TODO remove once appose project is released with the needed changes 37 | //TODO remove once appose project is released with the needed changes 38 | //TODO remove once appose project is released with the needed changes 39 | public class TaskEvent { 40 | 41 | public final Service.Task task; 42 | public final ResponseType responseType; 43 | 44 | public TaskEvent(Service.Task task, ResponseType responseType) { 45 | this.task = task; 46 | this.responseType = responseType; 47 | } 48 | 49 | @Override 50 | public String toString() { 51 | return String.format("[%s] %s", responseType, task); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/main/java/io/bioimage/modelrunner/apposed/appose/Types.java: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * Appose: multi-language interprocess cooperation with shared memory. 4 | * %% 5 | * Copyright (C) 2023 Appose developers. 6 | * %% 7 | * Redistribution and use in source and binary forms, with or without 8 | * modification, are permitted provided that the following conditions are met: 9 | * 10 | * 1. Redistributions of source code must retain the above copyright notice, 11 | * this list of conditions and the following disclaimer. 12 | * 2. Redistributions in binary form must reproduce the above copyright notice, 13 | * this list of conditions and the following disclaimer in the documentation 14 | * and/or other materials provided with the distribution. 15 | * 16 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 17 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 18 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 19 | * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE 20 | * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 21 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 22 | * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 23 | * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 24 | * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 25 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 26 | * POSSIBILITY OF SUCH DAMAGE. 27 | * #L% 28 | */ 29 | package io.bioimage.modelrunner.apposed.appose; 30 | 31 | import java.io.PrintWriter; 32 | import java.io.StringWriter; 33 | import java.lang.reflect.Type; 34 | import java.util.HashMap; 35 | import java.util.Map; 36 | 37 | import com.google.gson.Gson; 38 | import com.google.gson.reflect.TypeToken; 39 | 40 | //TODO remove once appose project is released with the needed changes 41 | //TODO remove once appose project is released with the needed changes 42 | //TODO remove once appose project is released with the needed changes 43 | //TODO remove once appose project is released with the needed changes 44 | //TODO remove once appose project is released with the needed changes 45 | public final class Types { 46 | 47 | private Types() { 48 | // NB: Prevent instantiation of utility class. 49 | } 50 | 51 | /** 52 | * Encode a Map into a String 53 | * @param data 54 | * data that wants to be encoded 55 | * @return string containing the info of the data map 56 | */ 57 | public static String encode(Map data) { 58 | Gson gson = new Gson(); 59 | return gson.toJson(data); 60 | } 61 | 62 | @SuppressWarnings("unchecked") 63 | /** 64 | * Convert a json string into a map 65 | * @param json 66 | * json string 67 | * @return a map of with the information of the json 68 | */ 69 | public static Map decode(String json) { 70 | Gson gson = new Gson(); 71 | Type mapType = new TypeToken>() {}.getType(); 72 | return gson.fromJson(json, mapType); 73 | } 74 | 75 | /** Dumps the given exception, including stack trace, to a string. 76 | * 77 | * @param t 78 | * the given exception {@link Throwable} 79 | * @return the String containing the whole exception trace 80 | */ 81 | public static String stackTrace(Throwable t) { 82 | StringWriter sw = new StringWriter(); 83 | t.printStackTrace(new PrintWriter(sw)); 84 | return sw.toString(); 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /src/main/java/io/bioimage/modelrunner/bioimageio/description/Author.java: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * Use deep learning frameworks from Java in an agnostic and isolated way. 4 | * %% 5 | * Copyright (C) 2022 - 2024 Institut Pasteur and BioImage.IO developers. 6 | * %% 7 | * Licensed under the Apache License, Version 2.0 (the "License"); 8 | * you may not use this file except in compliance with the License. 9 | * You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, software 14 | * distributed under the License is distributed on an "AS IS" BASIS, 15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | * See the License for the specific language governing permissions and 17 | * limitations under the License. 18 | * #L% 19 | */ 20 | package io.bioimage.modelrunner.bioimageio.description; 21 | 22 | 23 | /** 24 | * The author field related to this specific model.` 25 | * It is composed the textual citation and the DOI reference (resolved as a URL). 26 | * 27 | * @author Carlos Garcia Lopez de Haro and Daniel Felipe Gonzalez Obando 28 | */ 29 | public class Author 30 | { 31 | /** 32 | * Creates a {@link Author} instance with the text and DOI. 33 | * All the fields are optional 34 | * 35 | * @param affiliation 36 | * affiliation of the author 37 | * @param email 38 | * email of the author 39 | * @param githubUser 40 | * github user of the author 41 | * @param name 42 | * name of the author 43 | * @param orcid 44 | * orcid of the author 45 | * @return The creates instance. 46 | */ 47 | public static Author build(String affiliation, String email, 48 | String githubUser, String name, String orcid) 49 | { 50 | Author author = new Author(); 51 | author.affiliation = affiliation; 52 | author.email = email; 53 | author.setGithubUser(githubUser); 54 | author.setName(name); 55 | author.setOrcid(orcid); 56 | return author; 57 | } 58 | 59 | private String affiliation; 60 | private String email; 61 | private String githubUser; 62 | private String name; 63 | private String orcid; 64 | 65 | /** 66 | * @return Affiliation 67 | */ 68 | public String getAffiliation() 69 | { 70 | return affiliation; 71 | } 72 | 73 | /** 74 | * Sets the affiliation 75 | * 76 | * @param affiliation 77 | * affiliation of the author. 78 | */ 79 | public void setText(String affiliation) 80 | { 81 | this.affiliation = affiliation; 82 | } 83 | 84 | /** 85 | * @return The email of the author 86 | */ 87 | public String getEmail() 88 | { 89 | return email; 90 | } 91 | 92 | /** 93 | * Sets the email of the author 94 | * 95 | * @param email 96 | * email of the author. 97 | */ 98 | public void setDoi(String email) 99 | { 100 | this.email = email; 101 | } 102 | 103 | /** 104 | * @return the githubUser 105 | */ 106 | public String getGithubUser() { 107 | return githubUser; 108 | } 109 | 110 | /** 111 | * @param githubUser 112 | * the githubUser of the author 113 | */ 114 | public void setGithubUser(String githubUser) { 115 | this.githubUser = githubUser; 116 | } 117 | 118 | /** 119 | * @return the name of the author 120 | */ 121 | public String getName() { 122 | return name; 123 | } 124 | 125 | /** 126 | * @param name the name tof the author 127 | */ 128 | public void setName(String name) { 129 | this.name = name; 130 | } 131 | 132 | /** 133 | * @return the orcid of the author 134 | */ 135 | public String getOrcid() { 136 | return orcid; 137 | } 138 | 139 | /** 140 | * @param orcid the orcid of the author 141 | */ 142 | public void setOrcid(String orcid) { 143 | this.orcid = orcid; 144 | } 145 | 146 | @Override 147 | public String toString() 148 | { 149 | String str = "Author {"; 150 | if (name != null) 151 | str += " name=" + name; 152 | if (affiliation != null) 153 | str += " affiliation=" + affiliation; 154 | if (orcid != null) 155 | str += " orcid=" + orcid; 156 | if (email != null) 157 | str += " email=" + email; 158 | if (githubUser != null) 159 | str += " github_user=" + githubUser; 160 | str += " }"; 161 | return str; 162 | } 163 | } 164 | -------------------------------------------------------------------------------- /src/main/java/io/bioimage/modelrunner/bioimageio/description/Axes.java: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * Use deep learning frameworks from Java in an agnostic and isolated way. 4 | * %% 5 | * Copyright (C) 2022 - 2024 Institut Pasteur and BioImage.IO developers. 6 | * %% 7 | * Licensed under the Apache License, Version 2.0 (the "License"); 8 | * you may not use this file except in compliance with the License. 9 | * You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, software 14 | * distributed under the License is distributed on an "AS IS" BASIS, 15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | * See the License for the specific language governing permissions and 17 | * limitations under the License. 18 | * #L% 19 | */ 20 | package io.bioimage.modelrunner.bioimageio.description; 21 | 22 | import java.util.List; 23 | 24 | 25 | public interface Axes { 26 | 27 | public String getAxesOrder(); 28 | 29 | /** 30 | * @return the axesList 31 | */ 32 | public List getAxesList(); 33 | 34 | public int[] getMinTileSizeArr(); 35 | 36 | public int[] getTileStepArr(); 37 | 38 | public double[] getTileScaleArr(); 39 | 40 | public int[] getHaloArr(); 41 | 42 | public Axis getAxis(String abreviation); 43 | 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/io/bioimage/modelrunner/bioimageio/description/AxesV05.java: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * Use deep learning frameworks from Java in an agnostic and isolated way. 4 | * %% 5 | * Copyright (C) 2022 - 2024 Institut Pasteur and BioImage.IO developers. 6 | * %% 7 | * Licensed under the Apache License, Version 2.0 (the "License"); 8 | * you may not use this file except in compliance with the License. 9 | * You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, software 14 | * distributed under the License is distributed on an "AS IS" BASIS, 15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | * See the License for the specific language governing permissions and 17 | * limitations under the License. 18 | * #L% 19 | */ 20 | package io.bioimage.modelrunner.bioimageio.description; 21 | 22 | import java.util.ArrayList; 23 | import java.util.List; 24 | import java.util.Map; 25 | 26 | 27 | public class AxesV05 implements Axes { 28 | 29 | private final List axesList; 30 | 31 | private final String axesOrder; 32 | 33 | private final double[] scaleArr; 34 | 35 | private final int[] minArr; 36 | 37 | private final int[] stepArr; 38 | 39 | private int[] haloArr; 40 | 41 | protected AxesV05(List axesList) { 42 | List axesListInit = new ArrayList(); 43 | String order = ""; 44 | int[] minArr = new int[axesList.size()]; 45 | int[] stepArr = new int[axesList.size()]; 46 | double[] scaleArr = new double[axesList.size()]; 47 | int c = 0; 48 | for (Object axisObject : axesList) { 49 | if (!(axisObject instanceof Map)) 50 | throw new IllegalArgumentException("The input argument should be a list of maps. " 51 | + "Go to the Bioimage.io specs documentation for more info."); 52 | Axis axis = new AxisV05((Map) axisObject); 53 | axesListInit.add(axis); 54 | order += axis.getAxis(); 55 | minArr[c] = axis.getMin(); 56 | stepArr[c] = axis.getStep(); 57 | scaleArr[c ++] = axis.getScale(); 58 | } 59 | this.axesList = axesListInit; 60 | this.axesOrder = order; 61 | this.scaleArr = scaleArr; 62 | this.minArr = minArr; 63 | this.stepArr = stepArr; 64 | } 65 | 66 | public String getAxesOrder() { 67 | return this.axesOrder; 68 | } 69 | 70 | /** 71 | * @return the axesList 72 | */ 73 | public List getAxesList() { 74 | return axesList; 75 | } 76 | 77 | public int[] getMinTileSizeArr() { 78 | return this.minArr; 79 | } 80 | 81 | public int[] getTileStepArr() { 82 | return this.stepArr; 83 | } 84 | 85 | public int[] getHaloArr() { 86 | haloArr = new int[this.axesList.size()]; 87 | for (int i = 0; i < this.axesList.size(); i ++) 88 | haloArr[i] = this.axesList.get(i).getHalo(); 89 | return this.haloArr; 90 | } 91 | 92 | public double[] getTileScaleArr() { 93 | return this.scaleArr; 94 | } 95 | 96 | public Axis getAxis(String abreviation) { 97 | return axesList.stream().filter(ax -> ax.getAxis().equals(abreviation)).findFirst().orElse(null); 98 | } 99 | 100 | } 101 | -------------------------------------------------------------------------------- /src/main/java/io/bioimage/modelrunner/bioimageio/description/Axis.java: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * Use deep learning frameworks from Java in an agnostic and isolated way. 4 | * %% 5 | * Copyright (C) 2022 - 2024 Institut Pasteur and BioImage.IO developers. 6 | * %% 7 | * Licensed under the Apache License, Version 2.0 (the "License"); 8 | * you may not use this file except in compliance with the License. 9 | * You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, software 14 | * distributed under the License is distributed on an "AS IS" BASIS, 15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | * See the License for the specific language governing permissions and 17 | * limitations under the License. 18 | * #L% 19 | */ 20 | package io.bioimage.modelrunner.bioimageio.description; 21 | 22 | import java.util.List; 23 | 24 | public interface Axis { 25 | 26 | public String getAxis(); 27 | 28 | public int getMin(); 29 | 30 | public int getStep(); 31 | 32 | public double getScale(); 33 | 34 | /** 35 | * @return the channelNames 36 | */ 37 | public List getChannelNames(); 38 | 39 | /** 40 | * @return the description 41 | */ 42 | public String getDescription(); 43 | 44 | /** 45 | * @return the concat 46 | */ 47 | public boolean isConcat(); 48 | 49 | public int getHalo(); 50 | 51 | public double getOffset(); 52 | 53 | public String getReferenceTensor(); 54 | 55 | public String getReferenceAxis(); 56 | 57 | } 58 | -------------------------------------------------------------------------------- /src/main/java/io/bioimage/modelrunner/bioimageio/description/AxisSize.java: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * Use deep learning frameworks from Java in an agnostic and isolated way. 4 | * %% 5 | * Copyright (C) 2022 - 2024 Institut Pasteur and BioImage.IO developers. 6 | * %% 7 | * Licensed under the Apache License, Version 2.0 (the "License"); 8 | * you may not use this file except in compliance with the License. 9 | * You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, software 14 | * distributed under the License is distributed on an "AS IS" BASIS, 15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | * See the License for the specific language governing permissions and 17 | * limitations under the License. 18 | * #L% 19 | */ 20 | package io.bioimage.modelrunner.bioimageio.description; 21 | 22 | import java.util.Map; 23 | 24 | public class AxisSize { 25 | 26 | protected int min = 1; 27 | private int step = 0; 28 | private double offset = 0; 29 | private String axisID; 30 | private String ref; 31 | 32 | 33 | 34 | protected AxisSize(Object object) { 35 | if (object instanceof Number) { 36 | min = (int) object; 37 | step = 0; 38 | } 39 | 40 | if (!(object instanceof Map)) 41 | return; 42 | Map map = (Map) object; 43 | 44 | 45 | if (map.get("min") != null && (map.get("min") instanceof Number)) 46 | min = ((Number) map.get("min")).intValue(); 47 | if (map.get("step") != null && (map.get("step") instanceof Number)) 48 | step = ((Number) map.get("step")).intValue(); 49 | if (map.get("offset") != null && (map.get("offset") instanceof Number)) 50 | offset = ((Number) map.get("offset")).doubleValue(); 51 | if (map.get("axis_id") != null && (map.get("axis_id") instanceof String)) 52 | axisID = (String) map.get("axis_id"); 53 | if (map.get("tensor_id") != null && (map.get("tensor_id") instanceof String)) 54 | ref = (String) map.get("tensor_id"); 55 | } 56 | 57 | public int getMin() { 58 | return this.min; 59 | } 60 | 61 | public int getStep() { 62 | return this.step; 63 | } 64 | 65 | public double getOffset() { 66 | return this.offset; 67 | } 68 | 69 | public String getReferenceAxis() { 70 | return this.axisID; 71 | } 72 | 73 | public String getReferenceTensor() { 74 | return this.ref; 75 | } 76 | 77 | } 78 | -------------------------------------------------------------------------------- /src/main/java/io/bioimage/modelrunner/bioimageio/description/AxisV04.java: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * Use deep learning frameworks from Java in an agnostic and isolated way. 4 | * %% 5 | * Copyright (C) 2022 - 2024 Institut Pasteur and BioImage.IO developers. 6 | * %% 7 | * Licensed under the Apache License, Version 2.0 (the "License"); 8 | * you may not use this file except in compliance with the License. 9 | * You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, software 14 | * distributed under the License is distributed on an "AS IS" BASIS, 15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | * See the License for the specific language governing permissions and 17 | * limitations under the License. 18 | * #L% 19 | */ 20 | package io.bioimage.modelrunner.bioimageio.description; 21 | 22 | import java.util.List; 23 | 24 | public class AxisV04 implements Axis { 25 | 26 | private String description = ""; 27 | private final String abreviation; 28 | private boolean concat = false; 29 | private double scale = 1.0; 30 | private int min = 1; 31 | private int step = 1; 32 | protected int halo = 0; 33 | private double offset = 0; 34 | String referenceTensor; 35 | String referenceAxis; 36 | 37 | 38 | protected AxisV04(String abreviation, int min, int step, int halo, double offset, double scale, String ref) { 39 | this.abreviation = abreviation; 40 | this.halo = halo; 41 | this.min = min; 42 | this.offset = offset; 43 | this.scale = scale; 44 | this.step = step; 45 | this.referenceAxis = abreviation; 46 | this.referenceTensor = ref; 47 | } 48 | 49 | public String getAxis() { 50 | return this.abreviation; 51 | } 52 | 53 | public int getMin() { 54 | return this.min; 55 | } 56 | 57 | public int getStep() { 58 | return this.step; 59 | } 60 | 61 | public double getScale() { 62 | return this.scale; 63 | } 64 | 65 | /** 66 | * @return the channelNames 67 | */ 68 | public List getChannelNames() { 69 | return null; 70 | } 71 | 72 | /** 73 | * @return the description 74 | */ 75 | public String getDescription() { 76 | return description; 77 | } 78 | 79 | /** 80 | * @return the concat 81 | */ 82 | public boolean isConcat() { 83 | return concat; 84 | } 85 | 86 | public int getHalo() { 87 | return this.halo; 88 | } 89 | 90 | public double getOffset() { 91 | return this.offset; 92 | } 93 | 94 | public String getReferenceTensor() { 95 | return this.referenceTensor; 96 | } 97 | 98 | public String getReferenceAxis() { 99 | return this.referenceAxis; 100 | } 101 | 102 | } 103 | -------------------------------------------------------------------------------- /src/main/java/io/bioimage/modelrunner/bioimageio/description/AxisV05.java: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * Use deep learning frameworks from Java in an agnostic and isolated way. 4 | * %% 5 | * Copyright (C) 2022 - 2024 Institut Pasteur and BioImage.IO developers. 6 | * %% 7 | * Licensed under the Apache License, Version 2.0 (the "License"); 8 | * you may not use this file except in compliance with the License. 9 | * You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, software 14 | * distributed under the License is distributed on an "AS IS" BASIS, 15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | * See the License for the specific language governing permissions and 17 | * limitations under the License. 18 | * #L% 19 | */ 20 | package io.bioimage.modelrunner.bioimageio.description; 21 | 22 | import java.util.List; 23 | import java.util.Map; 24 | 25 | public class AxisV05 implements Axis{ 26 | 27 | private String id; 28 | private String type; 29 | private String description = ""; 30 | private List channelNames; 31 | private final String abreviation; 32 | private boolean concat = false; 33 | private double scale = 1.0; 34 | private AxisSize size; 35 | protected int halo = 0; 36 | 37 | private Map originalDescription; 38 | 39 | 40 | protected AxisV05(Map map) { 41 | originalDescription = map; 42 | this.id = (String) map.get("id"); 43 | this.type = (String) map.get("type"); 44 | this.channelNames = (List) map.get("channel_names"); 45 | 46 | if (map.get("description") != null) 47 | this.description = (String) map.get("description"); 48 | if (map.get("concatenable") != null) 49 | this.concat = (boolean) map.get("concatenable"); 50 | if (map.get("scale") != null) 51 | this.scale = ((Number) map.get("scale")).doubleValue(); 52 | if (map.get("halo") != null) 53 | this.halo = ((Number) map.get("halo")).intValue(); 54 | 55 | this.size = new AxisSize(map.get("size")); 56 | 57 | if (this.id == null && this.type == null) 58 | throw new IllegalArgumentException("Invalid axis configuration: " 59 | + "Either 'type' or 'id' must be defined for each axis. " 60 | + "Current axis definition is missing both."); 61 | else if (this.id == null && this.type.equals("space")) 62 | throw new IllegalArgumentException(String.format( 63 | "Invalid axis configuration: When axis type is 'spaces', an 'id' must be defined. " + 64 | "Current configuration: type='%s', id=%s", 65 | type, "null" 66 | )); 67 | else if ((this.id == null || this.id != "b") && this.type.equals("batch")) 68 | this.abreviation = "b"; 69 | else if (this.id != null && id.equals("channel")) { 70 | this.abreviation = "c"; 71 | this.size.min = channelNames.size(); 72 | } else if (this.type != null && this.type.equals("channel")) { 73 | this.abreviation = "c"; 74 | this.size.min = channelNames.size(); 75 | } else 76 | this.abreviation = this.id; 77 | } 78 | 79 | public String getAxis() { 80 | return this.abreviation; 81 | } 82 | 83 | public int getMin() { 84 | if (this.abreviation .equals("c")) 85 | return this.channelNames != null ? this.channelNames.size() : 1; 86 | return this.size.getMin(); 87 | } 88 | 89 | public int getStep() { 90 | return this.size.getStep(); 91 | } 92 | 93 | public double getScale() { 94 | return this.scale; 95 | } 96 | 97 | /** 98 | * @return the channelNames 99 | */ 100 | public List getChannelNames() { 101 | return channelNames; 102 | } 103 | 104 | /** 105 | * @return the description 106 | */ 107 | public String getDescription() { 108 | return description; 109 | } 110 | 111 | /** 112 | * @return the concat 113 | */ 114 | public boolean isConcat() { 115 | return concat; 116 | } 117 | 118 | public int getHalo() { 119 | return this.halo; 120 | } 121 | 122 | public double getOffset() { 123 | return this.size.getOffset(); 124 | } 125 | 126 | public String getReferenceTensor() { 127 | return this.size.getReferenceTensor(); 128 | } 129 | 130 | public String getReferenceAxis() { 131 | return this.size.getReferenceAxis(); 132 | } 133 | 134 | /** 135 | * 136 | * @return a map containing the original description used in the Bioimage.io rdf.yaml file 137 | */ 138 | public Map getOriginalDescription(){ 139 | return this.originalDescription; 140 | } 141 | 142 | } 143 | -------------------------------------------------------------------------------- /src/main/java/io/bioimage/modelrunner/bioimageio/description/Badge.java: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * Use deep learning frameworks from Java in an agnostic and isolated way. 4 | * %% 5 | * Copyright (C) 2022 - 2024 Institut Pasteur and BioImage.IO developers. 6 | * %% 7 | * Licensed under the Apache License, Version 2.0 (the "License"); 8 | * you may not use this file except in compliance with the License. 9 | * You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, software 14 | * distributed under the License is distributed on an "AS IS" BASIS, 15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | * See the License for the specific language governing permissions and 17 | * limitations under the License. 18 | * #L% 19 | */ 20 | package io.bioimage.modelrunner.bioimageio.description; 21 | 22 | 23 | /** 24 | * Custom badges specified in some Bioimage.io models' rdf.yaml. 25 | * For more info go to: 26 | * https://github.com/bioimage-io/spec-bioimage-io/blob/gh-pages/model_spec_latest.md 27 | * 28 | * @author Carlos Garcia Lopez de Haro 29 | */ 30 | public class Badge 31 | { 32 | /** 33 | * Creates a {@link Badge} instance. 34 | * 35 | * @param label 36 | * label of the badge, e.g. 'Open in Colab' 37 | * @param icon 38 | * optional String e.g. 'https://colab.research.google.com/assets/colab-badge.svg' 39 | * @param url 40 | * e.g. 'https://colab.research.google.com/github/HenriquesLab/ZeroCostDL4Mic/blob/master/Colab_notebooks/U-net_2D_ZeroCostDL4Mic.ipynb' 41 | * @return The creates instance. 42 | */ 43 | public static Badge build(String label, String icon, String url) 44 | { 45 | Badge badge = new Badge(); 46 | badge.label = label; 47 | badge.icon = icon; 48 | badge.url = url; 49 | return badge; 50 | } 51 | 52 | private String label; 53 | private String icon; 54 | private String url; 55 | 56 | /** 57 | * @return label of the badge 58 | */ 59 | public String getLabel() 60 | { 61 | return label; 62 | } 63 | 64 | /** 65 | * Sets the label of the badge 66 | * 67 | * @param label 68 | * label of the badge. 69 | */ 70 | public void setText(String label) 71 | { 72 | this.label = label; 73 | } 74 | 75 | /** 76 | * @return The icon url as a String 77 | */ 78 | public String getIcon() 79 | { 80 | return icon; 81 | } 82 | 83 | /** 84 | * Sets the icon url as a String 85 | * 86 | * @param icon 87 | * icon url as a String 88 | */ 89 | public void setIcon(String icon) 90 | { 91 | this.icon = icon; 92 | } 93 | 94 | /** 95 | * @return the url 96 | */ 97 | public String getUrl() { 98 | return url; 99 | } 100 | 101 | /** 102 | * @param url the url to set 103 | */ 104 | public void setUrl(String url) { 105 | this.url = url; 106 | } 107 | 108 | @Override 109 | public String toString() 110 | { 111 | String str = "Cite {"; 112 | label += " label=" + label; 113 | if (icon != null) 114 | str += " icon=" + icon; 115 | if (url != null) 116 | str += " url=" + url; 117 | str += " }"; 118 | return str; 119 | } 120 | } 121 | -------------------------------------------------------------------------------- /src/main/java/io/bioimage/modelrunner/bioimageio/description/Cite.java: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * Use deep learning frameworks from Java in an agnostic and isolated way. 4 | * %% 5 | * Copyright (C) 2022 - 2024 Institut Pasteur and BioImage.IO developers. 6 | * %% 7 | * Licensed under the Apache License, Version 2.0 (the "License"); 8 | * you may not use this file except in compliance with the License. 9 | * You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, software 14 | * distributed under the License is distributed on an "AS IS" BASIS, 15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | * See the License for the specific language governing permissions and 17 | * limitations under the License. 18 | * #L% 19 | */ 20 | package io.bioimage.modelrunner.bioimageio.description; 21 | 22 | import java.net.MalformedURLException; 23 | import java.net.URL; 24 | 25 | /** 26 | * The citation related to this specific model.` 27 | * It is composed the textual citation and the DOI reference (resolved as a URL). 28 | * 29 | * @author Daniel Felipe Gonzalez Obando 30 | */ 31 | public class Cite 32 | { 33 | /** 34 | * Creates a {@link Cite} instance with the text and DOI. 35 | * 36 | * @param text 37 | * The citation text. 38 | * @param doi 39 | * The DOI url. It can be null. 40 | * @param url 41 | * url useful for the citation. It can be null. 42 | * @return The creates instance. 43 | */ 44 | public static Cite build(String text, String doi, String url) 45 | { 46 | Cite cite = new Cite(); 47 | cite.text = text; 48 | try { 49 | cite.doi = new URL(doi); 50 | } catch (MalformedURLException e) { 51 | cite.doi = null; 52 | } 53 | try { 54 | cite.setUrl(new URL(url)); 55 | } catch (MalformedURLException e) { 56 | cite.setUrl(null); 57 | } 58 | return cite; 59 | } 60 | 61 | private String text; 62 | private URL doi; 63 | private URL url; 64 | 65 | /** 66 | * @return Citation text 67 | */ 68 | public String getText() 69 | { 70 | return text; 71 | } 72 | 73 | /** 74 | * Sets the citation text. 75 | * 76 | * @param text 77 | * Citation text. 78 | */ 79 | public void setText(String text) 80 | { 81 | this.text = text; 82 | } 83 | 84 | /** 85 | * @return The DOI url. 86 | */ 87 | public URL getDoi() 88 | { 89 | return doi; 90 | } 91 | 92 | /** 93 | * Sets the citation DOI url. 94 | * 95 | * @param doi 96 | * DOI url. 97 | */ 98 | public void setDoi(URL doi) 99 | { 100 | this.doi = doi; 101 | } 102 | 103 | /** 104 | * @return the url 105 | */ 106 | public URL getUrl() { 107 | return url; 108 | } 109 | 110 | /** 111 | * @param url the url to set 112 | */ 113 | public void setUrl(URL url) { 114 | this.url = url; 115 | } 116 | 117 | @Override 118 | public String toString() 119 | { 120 | String str = "Cite {"; 121 | if (text != null) 122 | str += " text=" + text; 123 | if (doi != null) 124 | str += " doi=" + doi.toString(); 125 | if (url != null) 126 | str += " url=" + url.toString(); 127 | str += " }"; 128 | return str; 129 | } 130 | } 131 | -------------------------------------------------------------------------------- /src/main/java/io/bioimage/modelrunner/bioimageio/description/ExecutionConfig.java: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * Use deep learning frameworks from Java in an agnostic and isolated way. 4 | * %% 5 | * Copyright (C) 2022 - 2024 Institut Pasteur and BioImage.IO developers. 6 | * %% 7 | * Licensed under the Apache License, Version 2.0 (the "License"); 8 | * you may not use this file except in compliance with the License. 9 | * You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, software 14 | * distributed under the License is distributed on an "AS IS" BASIS, 15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | * See the License for the specific language governing permissions and 17 | * limitations under the License. 18 | * #L% 19 | */ 20 | package io.bioimage.modelrunner.bioimageio.description; 21 | 22 | import java.util.HashMap; 23 | import java.util.Map; 24 | 25 | import io.bioimage.modelrunner.bioimageio.description.deepimagej.DeepImageJExecutionConfig; 26 | 27 | /** 28 | * Execution configuration element. Comes from the config section in the yaml file. 29 | * 30 | * @author Daniel Felipe Gonzalez Obando and Carlos GArcia Lopez de Haro 31 | */ 32 | public class ExecutionConfig 33 | { 34 | 35 | protected static int FRIEND_COUNT = 0; 36 | 37 | /** 38 | * Creates an execution configuration instance with the config element map from the yaml file. 39 | * 40 | * @param yamlFieldElements 41 | * The config map. 42 | * @return The execution configuration instance. 43 | */ 44 | public static ExecutionConfig build(Map yamlFieldElements) 45 | { 46 | if (yamlFieldElements == null) { 47 | yamlFieldElements = new HashMap(); 48 | Map bmzConfig = new HashMap(); 49 | bmzConfig.put("nickname", "friend-" + (FRIEND_COUNT ++)); 50 | yamlFieldElements.put("bioimageio", bmzConfig); 51 | } 52 | 53 | ExecutionConfig config = new ExecutionConfig(); 54 | config.specMap = yamlFieldElements; 55 | return config; 56 | } 57 | 58 | private Map specMap; 59 | 60 | /** 61 | * Retrieves the yaml config element map. 62 | * 63 | * @return The config element map. 64 | */ 65 | public Map getSpecMap() 66 | { 67 | return specMap; 68 | } 69 | 70 | private DeepImageJExecutionConfig deepImageJExecutionConfig; 71 | 72 | /** 73 | * Retrieves the configuration instance for DeepImageI. 74 | * 75 | * @return The DeepImageJ execution configuration instance. 76 | */ 77 | public DeepImageJExecutionConfig getDeepImageJ() 78 | { 79 | if (deepImageJExecutionConfig == null) 80 | { 81 | @SuppressWarnings("unchecked") 82 | Map deepImageJEntry = (Map) specMap.get("deepimagej"); 83 | if (deepImageJEntry != null) 84 | { 85 | deepImageJExecutionConfig = DeepImageJExecutionConfig.build(deepImageJEntry); 86 | } 87 | } 88 | return deepImageJExecutionConfig; 89 | } 90 | 91 | /** 92 | * Key for the model id in the ocnfig field 93 | */ 94 | private static String idKey = "_id"; 95 | 96 | /** 97 | * Get the model ID specified inside the config field. This is the same as the ID that appears 98 | * in the rd.yaml in the collections repo 99 | * @return the model ID 100 | */ 101 | public String getID() { 102 | return (String) specMap.get(idKey); 103 | } 104 | 105 | 106 | 107 | @Override 108 | public String toString() 109 | { 110 | return "ExecutionConfig {specMap=" + specMap + "}"; 111 | } 112 | 113 | } 114 | -------------------------------------------------------------------------------- /src/main/java/io/bioimage/modelrunner/bioimageio/description/TensorSpec.java: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * Use deep learning frameworks from Java in an agnostic and isolated way. 4 | * %% 5 | * Copyright (C) 2022 - 2024 Institut Pasteur and BioImage.IO developers. 6 | * %% 7 | * Licensed under the Apache License, Version 2.0 (the "License"); 8 | * you may not use this file except in compliance with the License. 9 | * You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, software 14 | * distributed under the License is distributed on an "AS IS" BASIS, 15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | * See the License for the specific language governing permissions and 17 | * limitations under the License. 18 | * #L% 19 | */ 20 | package io.bioimage.modelrunner.bioimageio.description; 21 | 22 | import java.util.List; 23 | 24 | 25 | /** 26 | * A tensor specification descriptor. It holds the information of an input or output tensor (name, shape, axis order, data type, halo, etc.). 27 | * It is built from a input or output tensor map element in the yaml file. 28 | * 29 | * @author Carlos Garcia Lopez de Haro and Daniel Felipe Gonzalez Obando 30 | */ 31 | public interface TensorSpec { 32 | 33 | 34 | 35 | public String getName(); 36 | 37 | public String getDescription(); 38 | 39 | public List getPreprocessing(); 40 | 41 | public List getPostprocessing(); 42 | 43 | public String getAxesOrder(); 44 | 45 | public String getSampleTensorName(); 46 | 47 | public String getTestTensorName(); 48 | 49 | public int[] getMinTileSizeArr(); 50 | 51 | public int[] getTileStepArr(); 52 | 53 | public int[] getHaloArr(); 54 | 55 | public double[] getTileScaleArr(); 56 | 57 | public Axes getAxesInfo(); 58 | 59 | public String getDataType(); 60 | 61 | public boolean isImage(); 62 | 63 | public String getPixelSizeUnit(); 64 | } 65 | -------------------------------------------------------------------------------- /src/main/java/io/bioimage/modelrunner/bioimageio/description/TransformSpec.java: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * Use deep learning frameworks from Java in an agnostic and isolated way. 4 | * %% 5 | * Copyright (C) 2022 - 2024 Institut Pasteur and BioImage.IO developers. 6 | * %% 7 | * Licensed under the Apache License, Version 2.0 (the "License"); 8 | * you may not use this file except in compliance with the License. 9 | * You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, software 14 | * distributed under the License is distributed on an "AS IS" BASIS, 15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | * See the License for the specific language governing permissions and 17 | * limitations under the License. 18 | * #L% 19 | */ 20 | package io.bioimage.modelrunner.bioimageio.description; 21 | 22 | import java.util.Collections; 23 | import java.util.HashMap; 24 | import java.util.Map; 25 | 26 | import io.bioimage.modelrunner.bioimageio.description.deepimagej.DeepImageJProcessing; 27 | 28 | /** 29 | * A pre or post processing transformation descriptor applied on a tensor. 30 | * 31 | * @author Daniel Felipe Gonzalez Obando and Carlos Garcia Lopez de Haro 32 | */ 33 | public class TransformSpec 34 | { 35 | /** 36 | * Whether the transformation represents a DIJ transformation or not 37 | */ 38 | private boolean isDIJ = false; 39 | private static String KWARGS_KEY = "kwargs"; 40 | private static String TRANSFORMATION_NAME_KEY = "name"; 41 | 42 | /** 43 | * Builds a transformation specification from the provided element map. 44 | * 45 | * @param transformSpecMap 46 | * Element map. 47 | * @return The transformation specification instance. 48 | */ 49 | public static TransformSpec build(Map transformSpecMap) 50 | { 51 | TransformSpec transform = new TransformSpec(); 52 | transform.specMap = transformSpecMap; 53 | return transform; 54 | } 55 | 56 | private Map specMap; 57 | 58 | /** 59 | * @return The specification map describing the transformation and the parameters used. 60 | */ 61 | public Map getSpecMap() 62 | { 63 | return specMap == null ? null : specMap; 64 | } 65 | 66 | /** 67 | * @return The transformation name. Null if the specification map is not specified or if the transformation has no name. 68 | */ 69 | public String getName() 70 | { 71 | if (specMap == null) 72 | return null; 73 | if (specMap.get("name") != null) 74 | return (String) specMap.get("name"); 75 | return (String) specMap.get("id"); 76 | } 77 | 78 | /** 79 | * @return The keyword arguments for this transformation. Null if the specification map is not specified or if the transformation has no kwargs element. 80 | */ 81 | @SuppressWarnings("unchecked") 82 | public Map getKwargs() 83 | { 84 | return specMap == null ? null : (Map) specMap.get("kwargs"); 85 | } 86 | 87 | /** 88 | * 89 | * @return whether the transformation represents a DIJ transformation 90 | */ 91 | public boolean isDIJ() { 92 | return isDIJ; 93 | } 94 | 95 | /** 96 | * Create a {@link TransformSpec} object from a DIJ transformation 97 | * @param dij 98 | * the DIj transformation 99 | * @return the DIJ trnasformation as {@link TransformSpec} 100 | */ 101 | public static TransformSpec createTransformForDIJ(DeepImageJProcessing dij) { 102 | Map transformSpecs = new HashMap(); 103 | transformSpecs.put("name", dij.getMacros().toString()); 104 | TransformSpec transform = new TransformSpec(); 105 | transform.specMap = transformSpecs; 106 | transform.isDIJ = true; 107 | return transform; 108 | } 109 | 110 | public static String getKwargsKey() { 111 | return KWARGS_KEY; 112 | } 113 | 114 | public static String getTransformationNameKey() { 115 | return TRANSFORMATION_NAME_KEY; 116 | } 117 | 118 | @Override 119 | public String toString() 120 | { 121 | return "TransformSpec {specMap=" + specMap + "}"; 122 | } 123 | } 124 | -------------------------------------------------------------------------------- /src/main/java/io/bioimage/modelrunner/bioimageio/description/cellpose/ModelDescriptorCellposeV04.java: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * Use deep learning frameworks from Java in an agnostic and isolated way. 4 | * %% 5 | * Copyright (C) 2022 - 2024 Institut Pasteur and BioImage.IO developers. 6 | * %% 7 | * Licensed under the Apache License, Version 2.0 (the "License"); 8 | * you may not use this file except in compliance with the License. 9 | * You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, software 14 | * distributed under the License is distributed on an "AS IS" BASIS, 15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | * See the License for the specific language governing permissions and 17 | * limitations under the License. 18 | * #L% 19 | */ 20 | package io.bioimage.modelrunner.bioimageio.description.cellpose; 21 | 22 | import java.io.File; 23 | import java.io.IOException; 24 | import java.net.MalformedURLException; 25 | import java.nio.file.Path; 26 | import java.util.ArrayList; 27 | import java.util.Arrays; 28 | import java.util.List; 29 | import java.util.Map; 30 | import java.util.Set; 31 | import java.util.stream.Collectors; 32 | 33 | import io.bioimage.modelrunner.bioimageio.BioimageioRepo; 34 | import io.bioimage.modelrunner.bioimageio.description.Author; 35 | import io.bioimage.modelrunner.bioimageio.description.Badge; 36 | import io.bioimage.modelrunner.bioimageio.description.Cite; 37 | import io.bioimage.modelrunner.bioimageio.description.ModelDescriptor; 38 | import io.bioimage.modelrunner.bioimageio.description.ModelDescriptorV04; 39 | import io.bioimage.modelrunner.bioimageio.description.TensorSpec; 40 | import io.bioimage.modelrunner.bioimageio.description.exceptions.ModelSpecsException; 41 | import io.bioimage.modelrunner.bioimageio.description.weights.ModelWeight; 42 | import io.bioimage.modelrunner.utils.Constants; 43 | 44 | 45 | /** 46 | * A data structure holding a single Bioimage.io pretrained model description. This instances are created by opening a {@code model.yaml} file. 47 | * More info about the parameters can be found at: 48 | * https://github.com/bioimage-io/spec-bioimage-io/blob/gh-pages/model_spec_latest.md 49 | * 50 | * @author Carlos Garcia Lopez de Haro 51 | */ 52 | public class ModelDescriptorCellposeV04 extends ModelDescriptorV04 53 | { 54 | 55 | public ModelDescriptorCellposeV04(Map yamlElements) { 56 | super(yamlElements); 57 | // TODO Auto-generated constructor stub 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/main/java/io/bioimage/modelrunner/bioimageio/description/cellpose/ModelDescriptorCellposeV05.java: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * Use deep learning frameworks from Java in an agnostic and isolated way. 4 | * %% 5 | * Copyright (C) 2022 - 2024 Institut Pasteur and BioImage.IO developers. 6 | * %% 7 | * Licensed under the Apache License, Version 2.0 (the "License"); 8 | * you may not use this file except in compliance with the License. 9 | * You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, software 14 | * distributed under the License is distributed on an "AS IS" BASIS, 15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | * See the License for the specific language governing permissions and 17 | * limitations under the License. 18 | * #L% 19 | */ 20 | package io.bioimage.modelrunner.bioimageio.description.cellpose; 21 | 22 | import java.io.File; 23 | import java.io.IOException; 24 | import java.net.MalformedURLException; 25 | import java.nio.file.Path; 26 | import java.util.ArrayList; 27 | import java.util.Arrays; 28 | import java.util.List; 29 | import java.util.Map; 30 | import java.util.Set; 31 | 32 | import io.bioimage.modelrunner.bioimageio.BioimageioRepo; 33 | import io.bioimage.modelrunner.bioimageio.description.ModelDescriptor; 34 | import io.bioimage.modelrunner.bioimageio.description.ModelDescriptorV05; 35 | import io.bioimage.modelrunner.bioimageio.description.TensorSpec; 36 | import io.bioimage.modelrunner.bioimageio.description.exceptions.ModelSpecsException; 37 | import io.bioimage.modelrunner.bioimageio.description.weights.ModelWeight; 38 | import io.bioimage.modelrunner.utils.Constants; 39 | 40 | 41 | /** 42 | * A data structure holding a single Bioimage.io pretrained model description. This instances are created by opening a {@code model.yaml} file. 43 | * More info about the parameters can be found at: 44 | * https://github.com/bioimage-io/spec-bioimage-io/blob/gh-pages/model_spec_latest.md 45 | * 46 | * @author Carlos Garcia Lopez de Haro 47 | */ 48 | public class ModelDescriptorCellposeV05 extends ModelDescriptorV05 49 | { 50 | 51 | public ModelDescriptorCellposeV05(Map yamlElements) { 52 | super(yamlElements); 53 | // TODO Auto-generated constructor stub 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/main/java/io/bioimage/modelrunner/bioimageio/description/exceptions/ModelSpecsException.java: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * Use deep learning frameworks from Java in an agnostic and isolated way. 4 | * %% 5 | * Copyright (C) 2022 - 2024 Institut Pasteur and BioImage.IO developers. 6 | * %% 7 | * Licensed under the Apache License, Version 2.0 (the "License"); 8 | * you may not use this file except in compliance with the License. 9 | * You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, software 14 | * distributed under the License is distributed on an "AS IS" BASIS, 15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | * See the License for the specific language governing permissions and 17 | * limitations under the License. 18 | * #L% 19 | */ 20 | package io.bioimage.modelrunner.bioimageio.description.exceptions; 21 | 22 | /** 23 | * A exception to be launched when there is any error reading the Bioimage.io rdf.yaml file 24 | * 25 | * @author Carlos Garcia Lopez de Haro 26 | */ 27 | public class ModelSpecsException extends Exception 28 | { 29 | private static final long serialVersionUID = 1L; 30 | 31 | /** 32 | * Constructor for every exception related to reading the Bioimage.io rdf.yaml specs file 33 | * @param message 34 | * the message that wants to be passed as the exception info. 35 | */ 36 | public ModelSpecsException(String message) { 37 | super(message); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/io/bioimage/modelrunner/bioimageio/description/weights/ModelArchitecture.java: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * Use deep learning frameworks from Java in an agnostic and isolated way. 4 | * %% 5 | * Copyright (C) 2022 - 2024 Institut Pasteur and BioImage.IO developers. 6 | * %% 7 | * Licensed under the Apache License, Version 2.0 (the "License"); 8 | * you may not use this file except in compliance with the License. 9 | * You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, software 14 | * distributed under the License is distributed on an "AS IS" BASIS, 15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | * See the License for the specific language governing permissions and 17 | * limitations under the License. 18 | * #L% 19 | */ 20 | 21 | package io.bioimage.modelrunner.bioimageio.description.weights; 22 | 23 | import java.util.LinkedHashMap; 24 | import java.util.Map; 25 | 26 | public class ModelArchitecture { 27 | 28 | private String callable; 29 | 30 | private String importModule; 31 | 32 | private String source; 33 | 34 | private LinkedHashMap kwargs; 35 | 36 | protected ModelArchitecture(Map map) { 37 | kwargs = new LinkedHashMap(); 38 | if (map.get("callable") != null && map.get("callable") instanceof String) 39 | callable = (String) map.get("callable"); 40 | if (map.get("import_from") != null && map.get("import_from") instanceof String) 41 | importModule = (String) map.get("import_from"); 42 | if (map.get("source") != null && map.get("source") instanceof String) 43 | source = (String) map.get("source"); 44 | if (map.get("kwargs") != null && map.get("kwargs") instanceof Map) { 45 | for (String kk : ((Map) map.get("kwargs")).keySet()) 46 | kwargs.put(kk, ((Map) map.get("kwargs")).get(kk)); 47 | } 48 | } 49 | 50 | public String getCallable() { 51 | return callable; 52 | } 53 | 54 | public String getImportModule() { 55 | return importModule; 56 | } 57 | 58 | public String getSource() { 59 | return source; 60 | } 61 | 62 | public Map getKwargs() { 63 | return kwargs; 64 | } 65 | 66 | } 67 | -------------------------------------------------------------------------------- /src/main/java/io/bioimage/modelrunner/bioimageio/description/weights/ModelDependencies.java: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * Use deep learning frameworks from Java in an agnostic and isolated way. 4 | * %% 5 | * Copyright (C) 2022 - 2024 Institut Pasteur and BioImage.IO developers. 6 | * %% 7 | * Licensed under the Apache License, Version 2.0 (the "License"); 8 | * you may not use this file except in compliance with the License. 9 | * You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, software 14 | * distributed under the License is distributed on an "AS IS" BASIS, 15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | * See the License for the specific language governing permissions and 17 | * limitations under the License. 18 | * #L% 19 | */ 20 | 21 | package io.bioimage.modelrunner.bioimageio.description.weights; 22 | 23 | import java.io.File; 24 | import java.io.IOException; 25 | import java.util.ArrayList; 26 | import java.util.LinkedHashMap; 27 | import java.util.List; 28 | import java.util.Map; 29 | 30 | import io.bioimage.modelrunner.bioimageio.BioimageioRepo; 31 | import io.bioimage.modelrunner.bioimageio.description.ModelDescriptor; 32 | import io.bioimage.modelrunner.utils.YAMLUtils; 33 | 34 | public class ModelDependencies { 35 | 36 | private String envFile; 37 | 38 | private LinkedHashMap kwargs; 39 | 40 | protected ModelDependencies(Map map) { 41 | this.envFile = (String) map.get("source"); 42 | } 43 | 44 | public String getSource() { 45 | return envFile; 46 | } 47 | 48 | public static List getDependencies(ModelDescriptor descriptor, WeightFormat weights) { 49 | List deps = new ArrayList(); 50 | if (weights.getEnvDependencies() == null || weights.getEnvDependencies().getSource() == null) 51 | return deps; 52 | try { 53 | if (descriptor.getModelPath() != null) { 54 | String path = descriptor.getModelPath() + File.separator + weights.getEnvDependencies().getSource(); 55 | Map map = YAMLUtils.load(path); 56 | if (map.get("dependencies") != null && map.get("dependencies") instanceof List) 57 | return dependenciesMapToList((List) map.get("dependencies")); 58 | } 59 | String url = descriptor.getModelURL() + weights.getEnvDependencies().getSource(); 60 | String stringRDF = BioimageioRepo.getJSONFromUrl(url); 61 | Map map = YAMLUtils.loadFromString(stringRDF); 62 | if (map.get("dependencies") != null && map.get("dependencies") instanceof List) 63 | return dependenciesMapToList((List) map.get("dependencies")); 64 | } catch (IOException e) { 65 | return deps; 66 | } 67 | return deps; 68 | } 69 | 70 | private static List dependenciesMapToList(List list) { 71 | List deps = new ArrayList(); 72 | for (Object elem : list) { 73 | if (elem instanceof String) { 74 | deps.add((String) elem); 75 | } else if (elem instanceof Map && ((Map) elem).containsKey("pip")) { 76 | Object pipList = ((Map) elem).get("pip"); 77 | if (pipList instanceof List) 78 | deps.addAll(dependenciesMapToList((List) pipList)); 79 | } 80 | } 81 | return deps; 82 | } 83 | 84 | } 85 | -------------------------------------------------------------------------------- /src/main/java/io/bioimage/modelrunner/bioimageio/tiling/ImageInfo.java: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * Use deep learning frameworks from Java in an agnostic and isolated way. 4 | * %% 5 | * Copyright (C) 2022 - 2024 Institut Pasteur and BioImage.IO developers. 6 | * %% 7 | * Licensed under the Apache License, Version 2.0 (the "License"); 8 | * you may not use this file except in compliance with the License. 9 | * You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, software 14 | * distributed under the License is distributed on an "AS IS" BASIS, 15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | * See the License for the specific language governing permissions and 17 | * limitations under the License. 18 | * #L% 19 | */ 20 | package io.bioimage.modelrunner.bioimageio.tiling; 21 | 22 | public class ImageInfo { 23 | 24 | private final String name; 25 | 26 | private final String axesOrder; 27 | 28 | private final long[] dims; 29 | 30 | public ImageInfo(String tensorName, String axesOrder, long[] dims) { 31 | this.dims = dims; 32 | this.name = tensorName; 33 | this.axesOrder = axesOrder; 34 | } 35 | 36 | public String getAxesOrder() { 37 | return this.axesOrder; 38 | } 39 | 40 | public String getTensorName() { 41 | return this.name; 42 | } 43 | 44 | public long[] getDimensions() { 45 | return this.dims; 46 | } 47 | 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/io/bioimage/modelrunner/engine/DeepLearningEngineInterface.java: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * Use deep learning frameworks from Java in an agnostic and isolated way. 4 | * %% 5 | * Copyright (C) 2022 - 2024 Institut Pasteur and BioImage.IO developers. 6 | * %% 7 | * Licensed under the Apache License, Version 2.0 (the "License"); 8 | * you may not use this file except in compliance with the License. 9 | * You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, software 14 | * distributed under the License is distributed on an "AS IS" BASIS, 15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | * See the License for the specific language governing permissions and 17 | * limitations under the License. 18 | * #L% 19 | */ 20 | package io.bioimage.modelrunner.engine; 21 | 22 | import java.util.List; 23 | 24 | import io.bioimage.modelrunner.tensor.Tensor; 25 | import net.imglib2.RandomAccessibleInterval; 26 | import net.imglib2.type.NativeType; 27 | import net.imglib2.type.numeric.RealType; 28 | import io.bioimage.modelrunner.exceptions.LoadModelException; 29 | import io.bioimage.modelrunner.exceptions.RunModelException; 30 | 31 | public interface DeepLearningEngineInterface 32 | { 33 | /** 34 | * Simply run inference on the images provided. If the dimensions, number, data type or other 35 | * characteristic of the tensor is not correct, an exception will be thrown. 36 | * @param 37 | * input data type 38 | * @param 39 | * ouptut data type 40 | * @param inputs 41 | * the list of {@link RandomAccessibleInterval} that will be used as inputs 42 | * @return a list of {@link RandomAccessibleInterval} that has been outputed by the model 43 | * @throws RunModelException 44 | * if there is an error in the execution of the model 45 | */ 46 | public & NativeType, R extends RealType & NativeType> 47 | List> inference(List> inputs) throws RunModelException; 48 | 49 | /** 50 | * Method that the interface implements to make inference. In the class that 51 | * implements the interface, the code to run the model on the tensors should 52 | * go here. 53 | * 54 | * @param 55 | * ImgLib2 data type of the inputs 56 | * @param 57 | * ImgLib2 data type of the outputs, both can be the same 58 | * @param inputTensors 59 | * list containing the input tensors 60 | * @param outputTensors 61 | * list containing only the information about output tensors 62 | * @throws RunModelException 63 | * if there is an error in the execution of the model 64 | */ 65 | public & NativeType, R extends RealType & NativeType> 66 | void run( List< Tensor < T > > inputTensors, List< Tensor < R > > outputTensors ) throws RunModelException; 67 | 68 | /** 69 | * Load the model with the corresponding engine on the particular 70 | * independent ClassLoader. This is done to be able to load the model only 71 | * one time and use it several times. 72 | * 73 | * @param modelFolder 74 | * String path to the folder where all the components of the 75 | * model are stored 76 | * @param modelSource 77 | * String path to the actual model file. In Pytorch is the path 78 | * to a .pt file and for Tf it is the same as the modelFolder 79 | * @throws LoadModelException 80 | * if there is any problem loading the model, and the model 81 | * cannot be loaded 82 | */ 83 | public void loadModel( String modelFolder, String modelSource ) throws LoadModelException; 84 | 85 | /** 86 | * Closes the model loaded on the class on a particular ClassLoader 87 | */ 88 | public void closeModel(); 89 | } 90 | -------------------------------------------------------------------------------- /src/main/java/io/bioimage/modelrunner/example/ExampleDownloadModel.java: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * Use deep learning frameworks from Java in an agnostic and isolated way. 4 | * %% 5 | * Copyright (C) 2022 - 2024 Institut Pasteur and BioImage.IO developers. 6 | * %% 7 | * Licensed under the Apache License, Version 2.0 (the "License"); 8 | * you may not use this file except in compliance with the License. 9 | * You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, software 14 | * distributed under the License is distributed on an "AS IS" BASIS, 15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | * See the License for the specific language governing permissions and 17 | * limitations under the License. 18 | * #L% 19 | */ 20 | package io.bioimage.modelrunner.example; 21 | 22 | import java.io.File; 23 | import java.io.IOException; 24 | import java.util.function.Consumer; 25 | 26 | import io.bioimage.modelrunner.bioimageio.BioimageioRepo; 27 | 28 | /** 29 | * Class that provides an example on how to download a model using JDLL. 30 | * @author Carlos Javier Garcia Lopez de Haro 31 | * 32 | */ 33 | public class ExampleDownloadModel { 34 | /** 35 | * Field 'id' in the rdf.yaml file. 36 | * Used in this example to identify the model we want to download. 37 | * However, regard that the model can also be downloaded using the 38 | * {@link ModelDescriptor} created from its rdf.yaml file, using the 39 | * field 'name' in the rdf.yaml as identifier or using the field 40 | * 'rdf_source' as identifeir. 41 | * For more details, explore the methods: {@link BioimageioRepo#downloadByName(String, String)}, 42 | * {@link BioimageioRepo#downloadByRdfSource(String, String)} 43 | * or {@link BioimageioRepo#downloadModel(io.bioimage.modelrunner.bioimageio.description.ModelDescriptor, String)} 44 | */ 45 | private static final String MODEL_ID = "10.5281/zenodo.5874741"; 46 | /** 47 | * Current directory 48 | */ 49 | private static final String CWD = System.getProperty("user.dir"); 50 | /** 51 | * Directory where the model will be downloaded, if you want to download it 52 | * into another folder, please change it. 53 | */ 54 | private static final String MODELS_DIR = new File(CWD, "models").getAbsolutePath(); 55 | 56 | 57 | /** 58 | * Test method to check the download of models 59 | * @param args 60 | * there are no args in this method 61 | * @throws IOException if there is any error related to finding the model or its files 62 | * on the internet 63 | * @throws InterruptedException if the thread is stopped while the model is being downloaded 64 | */ 65 | public static void main(String[] args) throws IOException, InterruptedException { 66 | // Create an instance of the BioimageRepo object 67 | BioimageioRepo br = BioimageioRepo.connect(); 68 | // Retrieve a list of all the models that exist in the Bioimage.io repo. 69 | // Use verbose = false as we don' watn to print any info about the models in the terminal 70 | boolean verbose = false; 71 | br.listAllModels(verbose); 72 | // Create a consumer that gets live information about the download. 73 | // This consumer contains a LinkedHashMap that where the keys 74 | // correspond to the file being downloaded and the value corresponds 75 | // to the fraction of file that has already been downloaded. 76 | Consumer consumer = (c) -> {System.out.println("TOTAL PROGRESS OF THE DOWNLOAD: " + c);}; 77 | // Download the model using the ID, regard that we can also download the model 78 | // using its gieven name, the model descriptor or the url to its rdf.yaml file. 79 | // The download of the model prints some information about the download in the terminal. 80 | // The download of the model stops the thread until the download is finished. 81 | br.downloadModelByID(MODEL_ID, MODELS_DIR, consumer); 82 | // Another option is to launch the download in a separate thread 83 | // and wait for it to end while tracking the progress using the consumer 84 | Thread downloadThread = new Thread(() -> { 85 | try { 86 | br.downloadModelByID(MODEL_ID, MODELS_DIR, consumer); 87 | } catch (IOException | InterruptedException e) { 88 | // If one of the files to be downloaded is corrupted or the download thread 89 | // is stopped abruptly 90 | e.printStackTrace(); 91 | } 92 | }); 93 | downloadThread.start(); 94 | 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /src/main/java/io/bioimage/modelrunner/exceptions/LoadEngineException.java: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * Use deep learning frameworks from Java in an agnostic and isolated way. 4 | * %% 5 | * Copyright (C) 2022 - 2024 Institut Pasteur and BioImage.IO developers. 6 | * %% 7 | * Licensed under the Apache License, Version 2.0 (the "License"); 8 | * you may not use this file except in compliance with the License. 9 | * You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, software 14 | * distributed under the License is distributed on an "AS IS" BASIS, 15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | * See the License for the specific language governing permissions and 17 | * limitations under the License. 18 | * #L% 19 | */ 20 | package io.bioimage.modelrunner.exceptions; 21 | 22 | import java.io.File; 23 | 24 | /** 25 | * Exception thrown when there have been problems loading a Deep Learning model 26 | * 27 | * @author Carlos Garcia Lopez de Haro 28 | */ 29 | public class LoadEngineException extends Exception 30 | { 31 | 32 | private static final long serialVersionUID = 1L; 33 | 34 | /** 35 | * Message given by the Deep Learning engine interface 36 | */ 37 | private static String msg = "Error loading a Deep Learning engine"; 38 | 39 | private String nonStaticMsg; 40 | 41 | public LoadEngineException( String info ) 42 | { 43 | super( msg + ".\n" + info ); 44 | this.nonStaticMsg = msg + "\n" + info; 45 | } 46 | 47 | public LoadEngineException( File dir, String info ) 48 | { 49 | super( msg + " located at " + dir.getName() + ".\n" + info ); 50 | this.nonStaticMsg = msg + " located at " + dir.getName() + ".\n" + info; 51 | } 52 | 53 | public LoadEngineException( File dir ) 54 | { 55 | super( msg + " located at " + dir.getName() ); 56 | this.nonStaticMsg = msg + " located at " + dir.getName(); 57 | } 58 | 59 | public LoadEngineException() 60 | { 61 | super( msg ); 62 | this.nonStaticMsg = msg; 63 | } 64 | 65 | public String toString() 66 | { 67 | return this.nonStaticMsg; 68 | } 69 | 70 | } 71 | -------------------------------------------------------------------------------- /src/main/java/io/bioimage/modelrunner/exceptions/LoadModelException.java: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * Use deep learning frameworks from Java in an agnostic and isolated way. 4 | * %% 5 | * Copyright (C) 2022 - 2024 Institut Pasteur and BioImage.IO developers. 6 | * %% 7 | * Licensed under the Apache License, Version 2.0 (the "License"); 8 | * you may not use this file except in compliance with the License. 9 | * You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, software 14 | * distributed under the License is distributed on an "AS IS" BASIS, 15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | * See the License for the specific language governing permissions and 17 | * limitations under the License. 18 | * #L% 19 | */ 20 | package io.bioimage.modelrunner.exceptions; 21 | 22 | /** 23 | * Exception thrown when there have been problems loading a Deep Learning model 24 | * 25 | * @author Carlos Garcia Lopez de Haro 26 | */ 27 | public class LoadModelException extends Exception 28 | { 29 | 30 | private static final long serialVersionUID = 1L; 31 | 32 | /** 33 | * The original exception that caused the error 34 | */ 35 | private String ex; 36 | 37 | /** 38 | * Message given by the Deep Learning engine interface 39 | */ 40 | private static String defaultMsg = "Error loading a Deep Learning model."; 41 | 42 | public LoadModelException( String ex ) 43 | { 44 | super( defaultMsg + System.lineSeparator() + ex ); 45 | this.ex = defaultMsg + System.lineSeparator() + ex; 46 | } 47 | 48 | public LoadModelException( String msg, String ex ) 49 | { 50 | super( msg + System.lineSeparator() + ex ); 51 | this.ex = msg + System.lineSeparator() + ex; 52 | } 53 | 54 | public LoadModelException() 55 | { 56 | super( defaultMsg ); 57 | this.ex = defaultMsg; 58 | } 59 | 60 | public String toString() 61 | { 62 | return this.ex; 63 | } 64 | 65 | } 66 | -------------------------------------------------------------------------------- /src/main/java/io/bioimage/modelrunner/exceptions/RunModelException.java: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * Use deep learning frameworks from Java in an agnostic and isolated way. 4 | * %% 5 | * Copyright (C) 2022 - 2024 Institut Pasteur and BioImage.IO developers. 6 | * %% 7 | * Licensed under the Apache License, Version 2.0 (the "License"); 8 | * you may not use this file except in compliance with the License. 9 | * You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, software 14 | * distributed under the License is distributed on an "AS IS" BASIS, 15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | * See the License for the specific language governing permissions and 17 | * limitations under the License. 18 | * #L% 19 | */ 20 | package io.bioimage.modelrunner.exceptions; 21 | 22 | /** 23 | * Exception thrown when there have been problems running a Deep Learning model 24 | * 25 | * @author Carlos Garcia Lopez de Haro 26 | * 27 | */ 28 | public class RunModelException extends Exception 29 | { 30 | 31 | private static final long serialVersionUID = 1L; 32 | 33 | /** 34 | * Constructor that transports exceptions that happened in the Deep Learning 35 | * engine interface into the Deep LEarning manager inside which is being run 36 | * inside the main program 37 | * 38 | * @param msg 39 | * the message of the original exception 40 | */ 41 | public RunModelException( String msg ) 42 | { 43 | super( msg ); 44 | } 45 | 46 | /** 47 | * Exception when the number of tensors expected is not the same as the 48 | * number of tensors outputted by the model 49 | * 50 | * @param nOutputTensors 51 | * number of tensors outputted by the model 52 | * @param nExpectedTensors 53 | * number of tensors expected 54 | */ 55 | public RunModelException( int nOutputTensors, int nExpectedTensors ) 56 | { 57 | super( "The Deep Learning model outputted " + nOutputTensors 58 | + " tensors but the specifications of the model indicated that" + "there were only " + nExpectedTensors 59 | + " output tensors." ); 60 | } 61 | 62 | } 63 | -------------------------------------------------------------------------------- /src/main/java/io/bioimage/modelrunner/gui/GuiUtils.java: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * Use deep learning frameworks from Java in an agnostic and isolated way. 4 | * %% 5 | * Copyright (C) 2022 - 2024 Institut Pasteur and BioImage.IO developers. 6 | * %% 7 | * Licensed under the Apache License, Version 2.0 (the "License"); 8 | * you may not use this file except in compliance with the License. 9 | * You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, software 14 | * distributed under the License is distributed on an "AS IS" BASIS, 15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | * See the License for the specific language governing permissions and 17 | * limitations under the License. 18 | * #L% 19 | */ 20 | package io.bioimage.modelrunner.gui; 21 | 22 | public class GuiUtils { 23 | 24 | public static boolean isEDTAlive() { 25 | Thread[] threads = new Thread[Thread.activeCount()]; 26 | Thread.enumerate(threads); 27 | 28 | for (Thread thread : threads) { 29 | if (thread.getName().startsWith("AWT-EventQueue")) { 30 | if (thread.isAlive()) { 31 | return true; 32 | } 33 | } 34 | } 35 | return false; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/io/bioimage/modelrunner/gui/Header.java: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * Use deep learning frameworks from Java in an agnostic and isolated way. 4 | * %% 5 | * Copyright (C) 2022 - 2024 Institut Pasteur and BioImage.IO developers. 6 | * %% 7 | * Licensed under the Apache License, Version 2.0 (the "License"); 8 | * you may not use this file except in compliance with the License. 9 | * You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, software 14 | * distributed under the License is distributed on an "AS IS" BASIS, 15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | * See the License for the specific language governing permissions and 17 | * limitations under the License. 18 | * #L% 19 | */ 20 | package io.bioimage.modelrunner.gui; 21 | 22 | import java.awt.BorderLayout; 23 | import java.awt.Color; 24 | import java.io.File; 25 | import java.net.URL; 26 | import java.util.function.Consumer; 27 | 28 | import javax.swing.JLabel; 29 | import javax.swing.JPanel; 30 | import javax.swing.JProgressBar; 31 | import javax.swing.SwingConstants; 32 | import javax.swing.SwingUtilities; 33 | import javax.swing.border.LineBorder; 34 | 35 | import io.bioimage.modelrunner.gui.adapter.GuiAdapter; 36 | 37 | public class Header extends JPanel { 38 | private static final long serialVersionUID = -7691139174208436363L; 39 | 40 | 41 | // pulled out so we can resize them on‐the‐fly: 42 | private final JLabel titleLabel; 43 | private final JLabel subtitleLabel; 44 | 45 | private JProgressBar progressBar; 46 | private JLabel progressLabel; 47 | 48 | public Header(GuiAdapter adapter) { 49 | super(new BorderLayout()); 50 | setForeground(adapter.getHeaderColor()); 51 | setBorder(new LineBorder(Color.BLACK, 2, true)); 52 | 53 | // — create + style the two text labels 54 | titleLabel = new JLabel(adapter.getSoftwareName(), SwingConstants.CENTER); 55 | titleLabel.setForeground(adapter.getTitleColor()); 56 | 57 | subtitleLabel = new JLabel(adapter.getSoftwareDescription(), SwingConstants.CENTER); 58 | subtitleLabel.setForeground(adapter.getSubtitleColor()); 59 | 60 | createProgressBar(); 61 | URL defaultIconUrl = Header.class.getClassLoader().getResource(adapter.getIconPath()); 62 | this.add(new HeaderGui(titleLabel, subtitleLabel, progressBar, progressLabel, defaultIconUrl), BorderLayout.CENTER); 63 | } 64 | 65 | private void createProgressBar() { 66 | progressBar = new JProgressBar(0, 100); 67 | progressBar.setStringPainted(false); 68 | progressBar.setBackground(Color.LIGHT_GRAY); 69 | progressBar.setForeground(new Color(46, 204, 113)); 70 | 71 | progressLabel = new JLabel("Processing...", SwingConstants.CENTER); 72 | progressLabel.setBackground(Color.GRAY); 73 | progressLabel.setOpaque(true); 74 | } 75 | 76 | protected void setGUIStartInstallation() { 77 | SwingUtilities.invokeLater(() -> { 78 | progressBar.setIndeterminate(true); 79 | progressBar.setStringPainted(true); 80 | progressBar.setVisible(true); 81 | progressBar.setString("0%"); 82 | progressLabel.setText("Preparing installation..."); 83 | progressLabel.setVisible(true); 84 | 85 | }); 86 | } 87 | 88 | public Consumer createStringConsumer(){ 89 | Consumer consumer = (ss) -> { 90 | SwingUtilities.invokeLater(() -> { 91 | this.progressLabel.setText("Installing " + new File(ss).getName()); 92 | }); 93 | }; 94 | return consumer; 95 | } 96 | 97 | public Consumer createProgressConsumer(){ 98 | Consumer consumer = (dd) -> { 99 | SwingUtilities.invokeLater(() -> { 100 | if (progressBar.isIndeterminate()) 101 | progressBar.setIndeterminate(false); 102 | double perc = Math.floor(dd * 1000) / 10; 103 | progressBar.setString(perc + "%"); 104 | progressBar.setValue((int) perc); 105 | if (perc == 100){ 106 | progressLabel.setVisible(false); 107 | progressBar.setVisible(false); 108 | } 109 | }); 110 | }; 111 | return consumer; 112 | } 113 | } 114 | -------------------------------------------------------------------------------- /src/main/java/io/bioimage/modelrunner/gui/LogoPanel.java: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * Use deep learning frameworks from Java in an agnostic and isolated way. 4 | * %% 5 | * Copyright (C) 2022 - 2024 Institut Pasteur and BioImage.IO developers. 6 | * %% 7 | * Licensed under the Apache License, Version 2.0 (the "License"); 8 | * you may not use this file except in compliance with the License. 9 | * You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, software 14 | * distributed under the License is distributed on an "AS IS" BASIS, 15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | * See the License for the specific language governing permissions and 17 | * limitations under the License. 18 | * #L% 19 | */ 20 | package io.bioimage.modelrunner.gui; 21 | 22 | import java.awt.Graphics; 23 | import java.awt.image.BufferedImage; 24 | import java.beans.PropertyChangeListener; 25 | import java.beans.PropertyChangeSupport; 26 | import java.util.concurrent.atomic.AtomicBoolean; 27 | 28 | import javax.swing.JPanel; 29 | 30 | public class LogoPanel extends JPanel{ 31 | 32 | private static final long serialVersionUID = -8109832428317782274L; 33 | private BufferedImage image; 34 | private AtomicBoolean isDefault = new AtomicBoolean(true); 35 | private final PropertyChangeSupport pcs = new PropertyChangeSupport(this); 36 | 37 | 38 | LogoPanel(BufferedImage img) { 39 | this.image = img; 40 | setOpaque(false); 41 | } 42 | 43 | LogoPanel() { 44 | setOpaque(false); 45 | } 46 | 47 | @Override 48 | protected void paintComponent(Graphics g) { 49 | super.paintComponent(g); 50 | int side = Math.min(getWidth(), getHeight()); 51 | if (image != null) { 52 | g.drawImage(image, 0, 0, getWidth(), getHeight(), this); 53 | } else { 54 | g.fillRect(0, 0, side, side); 55 | } 56 | } 57 | 58 | public void setImage(BufferedImage image, boolean defaultIm) { 59 | if (!this.isDefault.get() && defaultIm) 60 | return; 61 | isDefault.set(false); 62 | BufferedImage oldIm = this.image; 63 | this.image = image; 64 | pcs.firePropertyChange("image", oldIm, image); 65 | repaint(); 66 | } 67 | 68 | public BufferedImage getImage() { 69 | return this.image; 70 | } 71 | 72 | // listener registration 73 | public void addPropertyChangeListener(PropertyChangeListener l) { 74 | if (pcs != null) { 75 | pcs.addPropertyChangeListener(l); 76 | } else { 77 | super.addPropertyChangeListener(l); 78 | } 79 | } 80 | 81 | public void removePropertyChangeListener(PropertyChangeListener l) { 82 | pcs.removePropertyChangeListener(l); 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /src/main/java/io/bioimage/modelrunner/gui/YesNoDialog.java: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * Use deep learning frameworks from Java in an agnostic and isolated way. 4 | * %% 5 | * Copyright (C) 2022 - 2024 Institut Pasteur and BioImage.IO developers. 6 | * %% 7 | * Licensed under the Apache License, Version 2.0 (the "License"); 8 | * you may not use this file except in compliance with the License. 9 | * You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, software 14 | * distributed under the License is distributed on an "AS IS" BASIS, 15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | * See the License for the specific language governing permissions and 17 | * limitations under the License. 18 | * #L% 19 | */ 20 | package io.bioimage.modelrunner.gui; 21 | 22 | import java.lang.reflect.InvocationTargetException; 23 | 24 | import javax.swing.JOptionPane; 25 | import javax.swing.SwingUtilities; 26 | 27 | public class YesNoDialog { 28 | 29 | public static boolean askQuestion(String title, String message) { 30 | // Show the Yes/No dialog 31 | if (SwingUtilities.isEventDispatchThread()) { 32 | return askFromEDT(title, message); 33 | } else { 34 | return askFromNonEDT(title, message); 35 | } 36 | } 37 | 38 | private static boolean askFromEDT(String title, String message) { 39 | int response = JOptionPane.showConfirmDialog(null, message, title, JOptionPane.YES_NO_OPTION); 40 | 41 | 42 | return response == JOptionPane.YES_OPTION ? true : false; 43 | } 44 | 45 | private static boolean askFromNonEDT(String title, String message) { 46 | int[] response = new int[1]; 47 | try { 48 | SwingUtilities.invokeAndWait(() ->{ 49 | int res = JOptionPane.showConfirmDialog(null, message, title, JOptionPane.YES_NO_OPTION); 50 | response[0] = res; 51 | }); 52 | } catch (InvocationTargetException | InterruptedException e) { 53 | e.printStackTrace(); 54 | } 55 | return response[0] == JOptionPane.YES_OPTION ? true : false; 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/main/java/io/bioimage/modelrunner/gui/adapter/GuiAdapter.java: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * Use deep learning frameworks from Java in an agnostic and isolated way. 4 | * %% 5 | * Copyright (C) 2022 - 2024 Institut Pasteur and BioImage.IO developers. 6 | * %% 7 | * Licensed under the Apache License, Version 2.0 (the "License"); 8 | * you may not use this file except in compliance with the License. 9 | * You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, software 14 | * distributed under the License is distributed on an "AS IS" BASIS, 15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | * See the License for the specific language governing permissions and 17 | * limitations under the License. 18 | * #L% 19 | */ 20 | package io.bioimage.modelrunner.gui.adapter; 21 | 22 | 23 | import java.awt.Color; 24 | import java.io.IOException; 25 | import java.util.List; 26 | import java.util.Map; 27 | 28 | import io.bioimage.modelrunner.bioimageio.description.ModelDescriptor; 29 | import io.bioimage.modelrunner.exceptions.LoadEngineException; 30 | import io.bioimage.modelrunner.tensor.Tensor; 31 | import net.imglib2.RandomAccessibleInterval; 32 | import net.imglib2.type.NativeType; 33 | import net.imglib2.type.numeric.RealType; 34 | 35 | public interface GuiAdapter { 36 | 37 | public String getSoftwareName(); 38 | 39 | public String getSoftwareDescription(); 40 | 41 | public Color getTitleColor(); 42 | 43 | public Color getSubtitleColor(); 44 | 45 | public Color getHeaderColor(); 46 | 47 | public String getIconPath(); 48 | 49 | public String getModelsDir(); 50 | 51 | public String getEnginesDir(); 52 | 53 | public RunnerAdapter createRunner(ModelDescriptor descriptor) throws IOException, LoadEngineException; 54 | 55 | public RunnerAdapter createRunner(ModelDescriptor descriptor, String enginesPath) throws IOException, LoadEngineException; 56 | 57 | public & NativeType> void displayRai(RandomAccessibleInterval rai, String axesOrder, String imTitle); 58 | 59 | public & NativeType> List> getInputTensors(ModelDescriptor descriptor); 60 | 61 | public List getInputImageNames(); 62 | 63 | public & NativeType> List> convertToInputTensors(Map inputs, ModelDescriptor descriptor); 64 | } 65 | -------------------------------------------------------------------------------- /src/main/java/io/bioimage/modelrunner/gui/custom/ButtonsPanel.java: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * Use deep learning frameworks from Java in an agnostic and isolated way. 4 | * %% 5 | * Copyright (C) 2022 - 2024 Institut Pasteur and BioImage.IO developers. 6 | * %% 7 | * Licensed under the Apache License, Version 2.0 (the "License"); 8 | * you may not use this file except in compliance with the License. 9 | * You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, software 14 | * distributed under the License is distributed on an "AS IS" BASIS, 15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | * See the License for the specific language governing permissions and 17 | * limitations under the License. 18 | * #L% 19 | */ 20 | package io.bioimage.modelrunner.gui.custom; 21 | 22 | import javax.swing.JButton; 23 | import javax.swing.JFrame; 24 | import javax.swing.JPanel; 25 | import javax.swing.SwingUtilities; 26 | 27 | import java.awt.event.ComponentAdapter; 28 | import java.awt.event.ComponentEvent; 29 | 30 | public class ButtonsPanel extends JPanel { 31 | 32 | private static final long serialVersionUID = 5381352117710530216L; 33 | 34 | protected JButton cancelButton, installButton, runButton; 35 | 36 | private static final double BUTTON_WRATIO = 1d / 3d; 37 | 38 | protected ButtonsPanel() { 39 | setLayout(null); 40 | 41 | // --- Buttons Panel --- 42 | cancelButton = new JButton("Cancel"); 43 | installButton = new JButton("Install"); 44 | runButton = new JButton("Run"); 45 | add(cancelButton); 46 | add(installButton); 47 | add(runButton); 48 | 49 | organiseComponents(); 50 | 51 | } 52 | 53 | private void organiseComponents() { 54 | addComponentListener(new ComponentAdapter() { 55 | @Override 56 | public void componentResized(ComponentEvent e) { 57 | int rawW = getWidth(); 58 | int rawH = getHeight(); 59 | int inset = 2; 60 | int w = (int) ((rawW - 2 * inset) * BUTTON_WRATIO); 61 | cancelButton.setBounds(0, 0, w, rawH); 62 | installButton.setBounds(w + inset, 0, w, rawH); 63 | runButton.setBounds((w + inset) * 2, 0, w, rawH); 64 | } 65 | }); 66 | } 67 | 68 | // For demonstration purposes: a main method to show the UI in a JFrame. 69 | public static void main(String[] args) { 70 | SwingUtilities.invokeLater(new Runnable() { 71 | public void run() { 72 | JFrame frame = new JFrame("Buttons pannel"); 73 | frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 74 | frame.getContentPane().add(new ButtonsPanel()); 75 | frame.pack(); 76 | frame.setLocationRelativeTo(null); 77 | frame.setVisible(true); 78 | frame.setSize(200, 200); 79 | } 80 | }); 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /src/main/java/io/bioimage/modelrunner/gui/custom/ConsumerInterface.java: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * Use deep learning frameworks from Java in an agnostic and isolated way. 4 | * %% 5 | * Copyright (C) 2022 - 2024 Institut Pasteur and BioImage.IO developers. 6 | * %% 7 | * Licensed under the Apache License, Version 2.0 (the "License"); 8 | * you may not use this file except in compliance with the License. 9 | * You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, software 14 | * distributed under the License is distributed on an "AS IS" BASIS, 15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | * See the License for the specific language governing permissions and 17 | * limitations under the License. 18 | * #L% 19 | */ 20 | package io.bioimage.modelrunner.gui.custom; 21 | 22 | import java.util.List; 23 | 24 | import javax.swing.JComponent; 25 | 26 | import net.imglib2.RandomAccessibleInterval; 27 | import net.imglib2.type.NativeType; 28 | import net.imglib2.type.numeric.RealType; 29 | 30 | /** 31 | * @author Carlos Garcia 32 | */ 33 | public abstract class ConsumerInterface { 34 | 35 | protected List varNames; 36 | 37 | protected List componentsGui; 38 | 39 | public abstract String getModelsDir(); 40 | 41 | public abstract void setComponents(List components); 42 | 43 | public abstract void setVarNames(List componentNames); 44 | 45 | public abstract Object getFocusedImage(); 46 | 47 | public abstract String getFocusedImageName(); 48 | 49 | public abstract Integer getFocusedImageChannels(); 50 | 51 | public abstract Integer getFocusedImageSlices(); 52 | 53 | public abstract Integer getFocusedImageFrames(); 54 | 55 | public abstract Integer getFocusedImageWidth(); 56 | 57 | public abstract Integer getFocusedImageHeight(); 58 | 59 | public abstract < T extends RealType< T > & NativeType< T > > RandomAccessibleInterval getFocusedImageAsRai(); 60 | 61 | public abstract < T extends RealType< T > & NativeType< T > > 62 | void display(RandomAccessibleInterval rai, String axes, String name); 63 | 64 | public void setVariableNames(List varNames) { 65 | this.varNames = varNames; 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/main/java/io/bioimage/modelrunner/gui/custom/FooterPanel.java: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * Use deep learning frameworks from Java in an agnostic and isolated way. 4 | * %% 5 | * Copyright (C) 2022 - 2024 Institut Pasteur and BioImage.IO developers. 6 | * %% 7 | * Licensed under the Apache License, Version 2.0 (the "License"); 8 | * you may not use this file except in compliance with the License. 9 | * You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, software 14 | * distributed under the License is distributed on an "AS IS" BASIS, 15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | * See the License for the specific language governing permissions and 17 | * limitations under the License. 18 | * #L% 19 | */ 20 | package io.bioimage.modelrunner.gui.custom; 21 | 22 | import javax.swing.BorderFactory; 23 | import javax.swing.JFrame; 24 | import javax.swing.JPanel; 25 | import javax.swing.JProgressBar; 26 | import javax.swing.SwingUtilities; 27 | 28 | import java.awt.Color; 29 | import java.awt.Dimension; 30 | import java.awt.event.ComponentAdapter; 31 | import java.awt.event.ComponentEvent; 32 | 33 | public class FooterPanel extends JPanel { 34 | 35 | private static final long serialVersionUID = 5381352117710530216L; 36 | 37 | protected ButtonsPanel buttons; 38 | 39 | protected JProgressBar bar; 40 | 41 | private static final double BUTTON_WRATIO = 1d / 2d; 42 | 43 | private static final Dimension MIN_D = new Dimension(20, 10); 44 | 45 | protected FooterPanel() { 46 | setLayout(null); 47 | 48 | 49 | buttons = new ButtonsPanel(); 50 | bar = new JProgressBar(); 51 | bar.setStringPainted(true); 52 | bar.setString(""); 53 | add(buttons); 54 | add(bar); 55 | 56 | this.setMinimumSize(MIN_D); 57 | 58 | organiseComponents(); 59 | 60 | } 61 | 62 | private void organiseComponents() { 63 | addComponentListener(new ComponentAdapter() { 64 | @Override 65 | public void componentResized(ComponentEvent e) { 66 | int rawW = getWidth(); 67 | int rawH = getHeight(); 68 | int inset = 2; 69 | int w = (int) ((rawW - inset) * BUTTON_WRATIO); 70 | bar.setBounds(0, inset, w, rawH - 2 * inset); 71 | buttons.setBounds(w + inset, 0, w, rawH); 72 | } 73 | }); 74 | } 75 | 76 | // For demonstration purposes: a main method to show the UI in a JFrame. 77 | public static void main(String[] args) { 78 | SwingUtilities.invokeLater(new Runnable() { 79 | public void run() { 80 | JFrame frame = new JFrame("Buttons pannel"); 81 | frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 82 | frame.getContentPane().add(new FooterPanel()); 83 | frame.pack(); 84 | frame.setLocationRelativeTo(null); 85 | frame.setVisible(true); 86 | frame.setSize(200, 200); 87 | } 88 | }); 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /src/main/java/io/bioimage/modelrunner/gui/custom/PlaceholderTextField.java: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * Use deep learning frameworks from Java in an agnostic and isolated way. 4 | * %% 5 | * Copyright (C) 2022 - 2024 Institut Pasteur and BioImage.IO developers. 6 | * %% 7 | * Licensed under the Apache License, Version 2.0 (the "License"); 8 | * you may not use this file except in compliance with the License. 9 | * You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, software 14 | * distributed under the License is distributed on an "AS IS" BASIS, 15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | * See the License for the specific language governing permissions and 17 | * limitations under the License. 18 | * #L% 19 | */ 20 | package io.bioimage.modelrunner.gui.custom; 21 | 22 | import java.awt.Color; 23 | import java.awt.FontMetrics; 24 | import java.awt.Graphics; 25 | import java.awt.Graphics2D; 26 | import java.awt.Insets; 27 | 28 | import javax.swing.JTextField; 29 | 30 | public class PlaceholderTextField extends JTextField { 31 | private static final long serialVersionUID = 5112778641734509160L; 32 | private final String placeholder; 33 | private final Color placeholderColor; 34 | 35 | protected PlaceholderTextField(String placeholder) { 36 | this.placeholder = placeholder; 37 | this.placeholderColor = Color.LIGHT_GRAY; 38 | } 39 | 40 | @Override 41 | protected void paintComponent(Graphics g) { 42 | super.paintComponent(g); 43 | 44 | if (getText().isEmpty()) { 45 | Graphics2D g2 = (Graphics2D) g.create(); 46 | g2.setColor(placeholderColor); 47 | Insets ins = getInsets(); 48 | FontMetrics fm = g2.getFontMetrics(); 49 | int x = ins.left; 50 | // Vertically center the text: 51 | int y = (getHeight() + fm.getAscent() - fm.getDescent()) / 2; 52 | g2.drawString(placeholder, x, y); 53 | g2.dispose(); 54 | } 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/main/java/io/bioimage/modelrunner/gui/workers/InstallEnvWorker.java: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * Use deep learning frameworks from Java in an agnostic and isolated way. 4 | * %% 5 | * Copyright (C) 2022 - 2024 Institut Pasteur and BioImage.IO developers. 6 | * %% 7 | * Licensed under the Apache License, Version 2.0 (the "License"); 8 | * you may not use this file except in compliance with the License. 9 | * You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, software 14 | * distributed under the License is distributed on an "AS IS" BASIS, 15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | * See the License for the specific language governing permissions and 17 | * limitations under the License. 18 | * #L% 19 | */ 20 | package io.bioimage.modelrunner.gui.workers; 21 | 22 | import java.io.IOException; 23 | import java.net.URISyntaxException; 24 | import java.util.concurrent.CountDownLatch; 25 | import java.util.concurrent.ExecutionException; 26 | import java.util.function.Consumer; 27 | 28 | import javax.swing.SwingWorker; 29 | 30 | import org.apache.commons.compress.archivers.ArchiveException; 31 | 32 | import io.bioimage.modelrunner.apposed.appose.MambaInstallException; 33 | import io.bioimage.modelrunner.bioimageio.description.ModelDescriptor; 34 | import io.bioimage.modelrunner.model.python.DLModelPytorch; 35 | import io.bioimage.modelrunner.model.special.cellpose.Cellpose; 36 | import io.bioimage.modelrunner.model.special.stardist.StardistAbstract; 37 | 38 | public class InstallEnvWorker extends SwingWorker { 39 | 40 | private final String modelFamily; 41 | private Consumer consumer; 42 | private final CountDownLatch latch; 43 | private final Consumer callback; 44 | 45 | private Thread workerThread; 46 | 47 | public InstallEnvWorker(ModelDescriptor descriptor, CountDownLatch latch, Consumer callback) { 48 | this.modelFamily = descriptor.getModelFamily(); 49 | this.latch = latch; 50 | this.callback = callback; 51 | } 52 | 53 | public InstallEnvWorker(String modelFamily, CountDownLatch latch, Consumer callback) { 54 | this.modelFamily = modelFamily; 55 | this.latch = latch; 56 | this.callback = callback; 57 | } 58 | 59 | public void setConsumer(Consumer consumer) { 60 | this.consumer = consumer; 61 | } 62 | 63 | public String getModelFamily() { 64 | return this.modelFamily; 65 | } 66 | 67 | public CountDownLatch getCountDownLatch() { 68 | return this.latch; 69 | } 70 | 71 | @Override 72 | protected Boolean doInBackground() { 73 | workerThread = Thread.currentThread(); 74 | try { 75 | if (modelFamily.toLowerCase().equals(ModelDescriptor.STARDIST)) { 76 | StardistAbstract.installRequirements(consumer); 77 | } else if (modelFamily.toLowerCase().equals(ModelDescriptor.CELLPOSE)) { 78 | Cellpose.installRequirements(consumer); 79 | } else if (modelFamily.toLowerCase().equals(ModelDescriptor.BIOIMAGEIO)) 80 | DLModelPytorch.installRequirements(consumer); 81 | } catch (IOException | RuntimeException | MambaInstallException | ArchiveException 82 | | URISyntaxException e) { 83 | e.printStackTrace(); 84 | return false; 85 | } catch (InterruptedException e) { 86 | return false; 87 | } 88 | return true; 89 | } 90 | 91 | @Override 92 | protected void done() { 93 | Boolean success = false; 94 | try { 95 | success = this.get(); 96 | } catch (InterruptedException | ExecutionException e) { 97 | e.printStackTrace(); 98 | } 99 | latch.countDown(); 100 | if (callback != null) { 101 | callback.accept(success); 102 | } 103 | } 104 | 105 | public void stopBackground() { 106 | if (workerThread != null && workerThread.isAlive()) 107 | workerThread.interrupt(); 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /src/main/java/io/bioimage/modelrunner/gui/workers/ModelInfoWorker.java: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * Use deep learning frameworks from Java in an agnostic and isolated way. 4 | * %% 5 | * Copyright (C) 2022 - 2024 Institut Pasteur and BioImage.IO developers. 6 | * %% 7 | * Licensed under the Apache License, Version 2.0 (the "License"); 8 | * you may not use this file except in compliance with the License. 9 | * You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, software 14 | * distributed under the License is distributed on an "AS IS" BASIS, 15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | * See the License for the specific language governing permissions and 17 | * limitations under the License. 18 | * #L% 19 | */ 20 | package io.bioimage.modelrunner.gui.workers; 21 | 22 | import javax.swing.SwingUtilities; 23 | import javax.swing.SwingWorker; 24 | 25 | import io.bioimage.modelrunner.gui.Gui; 26 | import io.bioimage.modelrunner.bioimageio.description.ModelDescriptor; 27 | 28 | public class ModelInfoWorker extends SwingWorker { 29 | 30 | private ModelDescriptor model; 31 | private TextLoadCallback callback; 32 | 33 | public ModelInfoWorker(ModelDescriptor model, TextLoadCallback callback) { 34 | this.model = model; 35 | this.callback = callback; 36 | } 37 | 38 | @Override 39 | protected String doInBackground() throws Exception { 40 | // Perform the time-consuming task of generating the info text 41 | if (model == null) { 42 | // Return default text if model is null 43 | return Gui.INSTALL_INSTRUCTIONS; 44 | } else { 45 | // Generate the info from the model 46 | return model.buildInfo(); 47 | } 48 | } 49 | 50 | @Override 51 | protected void done() { 52 | try { 53 | String infoText = get(); 54 | SwingUtilities.invokeLater(() -> callback.onTextLoaded(infoText)); 55 | } catch (Exception e) { 56 | SwingUtilities.invokeLater(() -> callback.onTextLoadFailed(e)); 57 | } 58 | } 59 | 60 | @FunctionalInterface 61 | public interface TextLoadCallback { 62 | void onTextLoaded(String text); 63 | 64 | default void onTextLoadFailed(Exception e) { 65 | System.err.println("Failed to load text: " + e.getMessage()); 66 | } 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /src/main/java/io/bioimage/modelrunner/model/BaseModel.java: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * Use deep learning frameworks from Java in an agnostic and isolated way. 4 | * %% 5 | * Copyright (C) 2022 - 2024 Institut Pasteur and BioImage.IO developers. 6 | * %% 7 | * Licensed under the Apache License, Version 2.0 (the "License"); 8 | * you may not use this file except in compliance with the License. 9 | * You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, software 14 | * distributed under the License is distributed on an "AS IS" BASIS, 15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | * See the License for the specific language governing permissions and 17 | * limitations under the License. 18 | * #L% 19 | */ 20 | /** 21 | * 22 | */ 23 | package io.bioimage.modelrunner.model; 24 | 25 | import java.io.Closeable; 26 | import java.io.FileNotFoundException; 27 | import java.io.IOException; 28 | import java.util.List; 29 | 30 | import io.bioimage.modelrunner.bioimageio.description.exceptions.ModelSpecsException; 31 | import io.bioimage.modelrunner.exceptions.LoadModelException; 32 | import io.bioimage.modelrunner.exceptions.RunModelException; 33 | import io.bioimage.modelrunner.tensor.Tensor; 34 | import net.imglib2.type.NativeType; 35 | import net.imglib2.type.numeric.RealType; 36 | 37 | /** 38 | * Class that manages a Deep Learning model to load it and run it. 39 | * 40 | * @author Carlos Garcia Lopez de Haro 41 | */ 42 | public abstract class BaseModel implements Closeable 43 | { 44 | /** 45 | * Whether the model is loaded or not 46 | */ 47 | protected boolean loaded = false; 48 | /** 49 | * Whether the model is closed or not 50 | */ 51 | protected boolean closed = false; 52 | 53 | /** 54 | * Path to the folder containing the Bioimage.io model 55 | */ 56 | protected String modelFolder; 57 | 58 | /** 59 | * Load the model wanted to make inference into the particular ClassLoader 60 | * created to run a specific Deep Learning framework (engine) 61 | * 62 | * @throws LoadModelException 63 | * if the model was not loaded 64 | */ 65 | public abstract void loadModel() throws LoadModelException; 66 | 67 | /** 68 | * Close the Deep LEarning model in the ClassLoader where the Deep Learning 69 | * framework has been called and instantiated 70 | */ 71 | @Override 72 | public abstract void close(); 73 | 74 | /** 75 | * Method that calls the ClassLoader with the corresponding JARs of the Deep 76 | * Learning framework (engine) loaded to run inference on the tensors. The 77 | * method returns the corresponding output tensors 78 | * 79 | * @param 80 | * ImgLib2 data type of the input tensors 81 | * @param 82 | * ImgLib2 data type of the output tensors, it can be the same as in the input 83 | * @param inTensors 84 | * input tensors containing all the tensor data 85 | * @param outTensors 86 | * expected output tensors. Their backend data will be rewritten with the result of the inference 87 | * @throws RunModelException 88 | * if the is any problem running the model 89 | */ 90 | public abstract & NativeType, R extends RealType & NativeType> 91 | void run( List< Tensor < T > > inTensors, List< Tensor < R > > outTensors ) throws RunModelException; 92 | 93 | /** 94 | * Run a Bioimage.io model and execute the tiling strategy in one go. 95 | * The model needs to have been previously loaded with {@link #loadModel()}. 96 | * This method does not execute pre- or post-processing, they 97 | * need to be executed independently before or after 98 | * 99 | * @param 100 | * ImgLib2 data type of the output images 101 | * @param 102 | * ImgLib2 data type of the input images 103 | * @param inputTensors 104 | * list of the input tensors that are going to be inputed to the model 105 | * @return the resulting tensors 106 | * @throws RunModelException if the model has not been previously loaded 107 | * rdf.yaml specs file in the model folder. 108 | */ 109 | public abstract & NativeType, R extends RealType & NativeType> 110 | List> run(List> inputTensors) 111 | throws RunModelException; 112 | 113 | /** 114 | * Get the folder where this model is located 115 | * 116 | * @return the folder where this model is located 117 | */ 118 | public String getModelFolder() 119 | { 120 | return this.modelFolder; 121 | } 122 | 123 | /** 124 | * Whether the model is loaded or not 125 | * @return whether the model is loaded or not 126 | */ 127 | public boolean isLoaded() { 128 | return loaded; 129 | } 130 | 131 | /** 132 | * Whether the model is closed or not 133 | * @return whether the model is closed or not 134 | */ 135 | public boolean isClosed() { 136 | return closed; 137 | } 138 | } 139 | -------------------------------------------------------------------------------- /src/main/java/io/bioimage/modelrunner/model/python/DLModelPytorch.java: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * Use deep learning frameworks from Java in an agnostic and isolated way. 4 | * %% 5 | * Copyright (C) 2022 - 2024 Institut Pasteur and BioImage.IO developers. 6 | * %% 7 | * Licensed under the Apache License, Version 2.0 (the "License"); 8 | * you may not use this file except in compliance with the License. 9 | * You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, software 14 | * distributed under the License is distributed on an "AS IS" BASIS, 15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | * See the License for the specific language governing permissions and 17 | * limitations under the License. 18 | * #L% 19 | */ 20 | /** 21 | * 22 | */ 23 | package io.bioimage.modelrunner.model.python; 24 | 25 | import java.io.IOException; 26 | import java.util.HashMap; 27 | import java.util.Map; 28 | 29 | /** 30 | * Class that contains the methods to use a Pytorch model from JDLL. 31 | * The model should be compatible with the default environment (Biapy environment) or the environmemt 32 | * preferred. 33 | * 34 | * The callable to instantiate the model should be defined as well as the module from where it has to be imported 35 | * or the Python file that contains its declaration. 36 | * 37 | */ 38 | public class DLModelPytorch extends DLModelPytorchProtected { 39 | 40 | protected DLModelPytorch(String modelFile, String callable, String importModule, String weightsPath, Map kwargs) 41 | throws IOException { 42 | super(modelFile, callable, importModule, weightsPath, kwargs); 43 | } 44 | 45 | /** 46 | * Create a Pytorch model that can run from Java 47 | * @param modelClass 48 | * file where the class of the model is defined. It the class can be imported this param can be null as long as the 49 | * module from which the class can be imported is defined at 'importModule' 50 | * @param callable 51 | * class of the model 52 | * @param importModule 53 | * module from where the model class is imported. It can be null it we provide a file that contains the class 54 | * @param modelPath 55 | * path to the Pytorch weights 56 | * @return a Java class that can do inference using a Python Pytorch model 57 | * @throws IOException if there is any error trying to run Python from Java 58 | */ 59 | public static DLModelPytorch create(String modelClass, String callable, String importModule, 60 | String modelPath) throws IOException { 61 | return create(modelClass, callable, importModule, modelPath, new HashMap()); 62 | } 63 | 64 | /** 65 | * Create a Pytorch model that can run from Java 66 | * @param modelClass 67 | * file where the class of the model is defined. It the class can be imported this param can be null as long as the 68 | * module from which the class can be imported is defined at 'importModule' 69 | * @param callable 70 | * class of the model 71 | * @param importModule 72 | * module from where the model class is imported. It can be null it we provide a file that contains the class 73 | * @param modelPath 74 | * path to the Pytorch weights 75 | * @param kwargs 76 | * other kwargs that might be needed to instantiate the model 77 | * @return a Java class that can do inference using a Python Pytorch model 78 | * @throws IOException if there is any error trying to run Python from Java 79 | */ 80 | public static DLModelPytorch create(String modelClass, String callable, String importModule, 81 | String modelPath, Map kwargs) throws IOException { 82 | return new DLModelPytorch(modelClass, callable, importModule, modelPath, kwargs); 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /src/main/java/io/bioimage/modelrunner/runmode/ops/CellposeFineTuneJdllOp.java: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * Use deep learning frameworks from Java in an agnostic and isolated way. 4 | * %% 5 | * Copyright (C) 2022 - 2024 Institut Pasteur and BioImage.IO developers. 6 | * %% 7 | * Licensed under the Apache License, Version 2.0 (the "License"); 8 | * you may not use this file except in compliance with the License. 9 | * You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, software 14 | * distributed under the License is distributed on an "AS IS" BASIS, 15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | * See the License for the specific language governing permissions and 17 | * limitations under the License. 18 | * #L% 19 | */ 20 | package io.bioimage.modelrunner.runmode.ops; 21 | 22 | /** 23 | * TODO fill 24 | * Class to fine tune Cellpose 25 | * 26 | * @author Carlos Garcia Lopez de Haro 27 | */ 28 | public class CellposeFineTuneJdllOp { 29 | 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/io/bioimage/modelrunner/runmode/ops/CellposeInferJdllOp.java: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * Use deep learning frameworks from Java in an agnostic and isolated way. 4 | * %% 5 | * Copyright (C) 2022 - 2024 Institut Pasteur and BioImage.IO developers. 6 | * %% 7 | * Licensed under the Apache License, Version 2.0 (the "License"); 8 | * you may not use this file except in compliance with the License. 9 | * You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, software 14 | * distributed under the License is distributed on an "AS IS" BASIS, 15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | * See the License for the specific language governing permissions and 17 | * limitations under the License. 18 | * #L% 19 | */ 20 | package io.bioimage.modelrunner.runmode.ops; 21 | 22 | /** 23 | * TODO fill 24 | * Class to make inference with cell-pose 25 | * 26 | * @author Carlos Garcia Lopez de Haro 27 | */ 28 | public class CellposeInferJdllOp { 29 | 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/io/bioimage/modelrunner/runmode/ops/CellposeTrainJdllOp.java: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * Use deep learning frameworks from Java in an agnostic and isolated way. 4 | * %% 5 | * Copyright (C) 2022 - 2024 Institut Pasteur and BioImage.IO developers. 6 | * %% 7 | * Licensed under the Apache License, Version 2.0 (the "License"); 8 | * you may not use this file except in compliance with the License. 9 | * You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, software 14 | * distributed under the License is distributed on an "AS IS" BASIS, 15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | * See the License for the specific language governing permissions and 17 | * limitations under the License. 18 | * #L% 19 | */ 20 | package io.bioimage.modelrunner.runmode.ops; 21 | 22 | /** 23 | * TODO fill 24 | * Class to train cell-pose from scratch Cellpose 25 | * 26 | * @author Carlos Garcia Lopez de Haro 27 | */ 28 | public class CellposeTrainJdllOp { 29 | 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/io/bioimage/modelrunner/runmode/ops/GenericOp.java: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * Use deep learning frameworks from Java in an agnostic and isolated way. 4 | * %% 5 | * Copyright (C) 2022 - 2024 Institut Pasteur and BioImage.IO developers. 6 | * %% 7 | * Licensed under the Apache License, Version 2.0 (the "License"); 8 | * you may not use this file except in compliance with the License. 9 | * You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, software 14 | * distributed under the License is distributed on an "AS IS" BASIS, 15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | * See the License for the specific language governing permissions and 17 | * limitations under the License. 18 | * #L% 19 | */ 20 | package io.bioimage.modelrunner.runmode.ops; 21 | 22 | import java.io.File; 23 | import java.util.LinkedHashMap; 24 | 25 | import io.bioimage.modelrunner.runmode.RunMode; 26 | 27 | /** 28 | * A generic OP that allows running Python code from JDLL if it is formatted correctly. 29 | * 30 | * A good example of a GEneric OP can be seen with the stardist model. 31 | * TODO add meaningfill examples with details 32 | * @author Carlos Javier Garcia Lopez de Haro 33 | * 34 | */ 35 | public class GenericOp implements OpInterface { 36 | 37 | private String opFilePath; 38 | 39 | private String envPath; 40 | 41 | private String methodName; 42 | 43 | private int nOutputs; 44 | 45 | private LinkedHashMap inputsMap; 46 | 47 | /** 48 | * Create the corresponding Python OP to be able to execute Python pre-designed scripts that 49 | * enable more complex tasks. One example is StarDist post-processing or cell-pose model 50 | * @param envYaml 51 | * path to the Python Conda/Mamba environment yaml file that the 52 | * OP needs to run properly 53 | * @param script 54 | * the path to the script that contains the wanted OP 55 | * @param method 56 | * the method of the script that needs to be called to run the OP 57 | * @param nOutputs 58 | * the final number of outputs that the method that runs the OP defined by the argument 'method' has 59 | * @return the OP that can be used by the class {@link RunMode} to run 60 | */ 61 | public static GenericOp create(String envYaml, String script, String method, int nOutputs) { 62 | GenericOp op = new GenericOp(); 63 | op.envPath = envYaml; 64 | op.opFilePath = script; 65 | op.methodName = method; 66 | op.nOutputs = nOutputs; 67 | return op; 68 | } 69 | 70 | /** 71 | * Set the inputs to the OP. These are the inputs to the method that is used to run the OP in the OP script. 72 | * The Map keys will be the names of the corresponding variables in Python and the values will be the variables values. 73 | * @param kwargs 74 | * Map containing the variables that will be the inputs to the OP main method in the Python script 75 | */ 76 | public void setInputs(LinkedHashMap kwargs) { 77 | this.inputsMap = kwargs; 78 | } 79 | 80 | @Override 81 | /** 82 | * {@inheritDoc} 83 | */ 84 | public String getOpPythonFilename() { 85 | return new File(this.opFilePath).getName(); 86 | } 87 | 88 | @Override 89 | /** 90 | * {@inheritDoc} 91 | */ 92 | public int getNumberOfOutputs() { 93 | return nOutputs; 94 | } 95 | 96 | @Override 97 | /** 98 | * {@inheritDoc} 99 | */ 100 | public void installOp() { 101 | // TODO 102 | } 103 | 104 | @Override 105 | /** 106 | * {@inheritDoc} 107 | */ 108 | public LinkedHashMap getOpInputs() { 109 | return this.inputsMap; 110 | } 111 | 112 | @Override 113 | /** 114 | * {@inheritDoc} 115 | */ 116 | public String getCondaEnv() { 117 | return envPath; 118 | } 119 | 120 | @Override 121 | /** 122 | * {@inheritDoc} 123 | */ 124 | public String getMethodName() { 125 | return this.methodName; 126 | } 127 | 128 | @Override 129 | /** 130 | * {@inheritDoc} 131 | */ 132 | public String getOpDir() { 133 | return new File(opFilePath).getParent(); 134 | } 135 | 136 | @Override 137 | /** 138 | * {@inheritDoc} 139 | */ 140 | public boolean isOpInstalled() { 141 | // TODO maybe remove this method? Make the check at installOp? 142 | return false; 143 | } 144 | } 145 | -------------------------------------------------------------------------------- /src/main/java/io/bioimage/modelrunner/runmode/ops/OpInterface.java: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * Use deep learning frameworks from Java in an agnostic and isolated way. 4 | * %% 5 | * Copyright (C) 2022 - 2024 Institut Pasteur and BioImage.IO developers. 6 | * %% 7 | * Licensed under the Apache License, Version 2.0 (the "License"); 8 | * you may not use this file except in compliance with the License. 9 | * You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, software 14 | * distributed under the License is distributed on an "AS IS" BASIS, 15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | * See the License for the specific language governing permissions and 17 | * limitations under the License. 18 | * #L% 19 | */ 20 | package io.bioimage.modelrunner.runmode.ops; 21 | 22 | import java.util.LinkedHashMap; 23 | 24 | /** 25 | * Interface that every OP needs to implement to be able to be run as a RunMode 26 | * @author Carlos Javier Garcia Lopez de Haro 27 | * 28 | */ 29 | public interface OpInterface { 30 | /** 31 | * The imports that need to be added to the Python code to run the OP 32 | * @return a String containing a Python snippet with the imports needed to use the 33 | * OP 34 | */ 35 | public String getOpPythonFilename(); 36 | /** 37 | * Number of outputs that the OP method will produce 38 | * @return number of ouptuts that the OP method will produce 39 | */ 40 | public int getNumberOfOutputs(); 41 | /** 42 | * Check whether the OP is installed or not 43 | * @return true if the OP is installed ot false otherwise 44 | */ 45 | public boolean isOpInstalled(); 46 | /** 47 | * Method that installs the OP to be ready to be used 48 | */ 49 | public void installOp(); 50 | /** 51 | * Get a Map contianing the inputs defined for the OP 52 | * @return an ordered map with the inputs to the OP, where the key 53 | * is the variable name and the object is the variable 54 | */ 55 | public LinkedHashMap getOpInputs() ; 56 | /** 57 | * Get the Conda env needed to run the OP 58 | * 59 | * @return the Conda env required to run the OP 60 | */ 61 | public String getCondaEnv(); 62 | /** 63 | * The name of the method that is used to call the OP 64 | * @return a String with the name of the method used to call the OP 65 | */ 66 | public String getMethodName(); 67 | /** 68 | * Directory where the OP is stored 69 | * @return tirectory where the OP is stored 70 | */ 71 | public String getOpDir(); 72 | } 73 | -------------------------------------------------------------------------------- /src/main/java/io/bioimage/modelrunner/system/Version.java: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * Use deep learning frameworks from Java in an agnostic and isolated way. 4 | * %% 5 | * Copyright (C) 2022 - 2024 Institut Pasteur and BioImage.IO developers. 6 | * %% 7 | * Licensed under the Apache License, Version 2.0 (the "License"); 8 | * you may not use this file except in compliance with the License. 9 | * You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, software 14 | * distributed under the License is distributed on an "AS IS" BASIS, 15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | * See the License for the specific language governing permissions and 17 | * limitations under the License. 18 | * #L% 19 | */ 20 | package io.bioimage.modelrunner.system; 21 | 22 | import java.io.BufferedReader; 23 | import java.io.IOException; 24 | import java.io.InputStreamReader; 25 | import java.util.Collections; 26 | import java.util.HashMap; 27 | import java.util.Map; 28 | import java.util.regex.Matcher; 29 | import java.util.regex.Pattern; 30 | 31 | /** 32 | * Represents the detected platform in a given system. When a new instance is created it is assigned the local detected platform but it can be changed using the 33 | * available setters. 34 | * 35 | * @author Carlos Garcia Lopez de Haro and Daniel Felipe Gonzalez Obando 36 | */ 37 | public class Version 38 | { 39 | private final int major; 40 | private final int minor; 41 | private final int patch; 42 | private final String preRelease; // e.g. "beta", "RC1", "SNAPSHOT" 43 | private final String buildMetadata; // e.g. "001", "exp.sha.5114f85" 44 | 45 | private static final Pattern VERSION_PATTERN = Pattern.compile( 46 | "^" + 47 | "(?0|[1-9]\\d*)" + // major 48 | "(?:\\.(?0|[1-9]\\d*))?" + // .minor (optional) 49 | "(?:\\.(?0|[1-9]\\d*))?" + // .patch (optional) 50 | "(?:-(?
[0-9A-Za-z-\\.]+))?" +      // -preRelease (optional)
 51 | 	        "(?:\\+(?[0-9A-Za-z-\\.]+))?" +  // +buildMetadata (optional)
 52 | 	        "$"
 53 | 	    );
 54 | 
 55 | 
 56 |     private Version(int major, int minor, int patch, String preRelease, String buildMetadata) {
 57 |         this.major = major;
 58 |         this.minor = minor;
 59 |         this.patch = patch;
 60 |         this.preRelease = preRelease;
 61 |         this.buildMetadata = buildMetadata;
 62 |     }
 63 | 
 64 |     public static Version parse(String version) {
 65 |         Matcher m = VERSION_PATTERN.matcher(version);
 66 |         if (!m.matches()) {
 67 |             throw new IllegalArgumentException("Invalid version string: " + version);
 68 |         }
 69 |         int maj = Integer.parseInt(m.group("major"));
 70 |         int min = m.group("minor") != null ? Integer.parseInt(m.group("minor")) : 0;
 71 |         int pat = m.group("patch") != null ? Integer.parseInt(m.group("patch")) : 0;
 72 |         String pre = m.group("pre");
 73 |         String build = m.group("build");
 74 |         return new Version(maj, min, pat, pre, build);
 75 |     }
 76 | 
 77 |     // Getters
 78 |     public int getMajor()       { return major; }
 79 |     public int getMinor()       { return minor; }
 80 |     public int getPatch()       { return patch; }
 81 |     public String getPreRelease()    { return preRelease; }
 82 |     public String getBuildMetadata() { return buildMetadata; }
 83 | 
 84 |     @Override
 85 |     public String toString() {
 86 |         StringBuilder sb = new StringBuilder();
 87 |         sb.append(major).append('.').append(minor).append('.').append(patch);
 88 |         if (preRelease != null)    sb.append('-').append(preRelease);
 89 |         if (buildMetadata != null) sb.append('+').append(buildMetadata);
 90 |         return sb.toString();
 91 |     }
 92 | 
 93 |     // Example use
 94 |     public static void main(String[] args) {
 95 |         String[] examples = {
 96 |             "1.2.3",
 97 |             "2.0",
 98 |             "3",
 99 |             "4.5.6-RC1",
100 |             "7.8-SNAPSHOT+exp.sha.5114f85",
101 |             "10.0.1+001"
102 |         };
103 | 
104 |         for (String ver : examples) {
105 |             Version v = Version.parse(ver);
106 |             System.out.println("Parsed “" + ver + "” → " +
107 |                 "major=" + v.getMajor() +
108 |                 ", minor=" + v.getMinor() +
109 |                 ", patch=" + v.getPatch() +
110 |                 ", preRelease=" + v.getPreRelease() +
111 |                 ", buildMetadata=" + v.getBuildMetadata()
112 |             );
113 |         }
114 |     }
115 | }
116 | 


--------------------------------------------------------------------------------
/src/main/java/io/bioimage/modelrunner/tensor/Utils.java:
--------------------------------------------------------------------------------
 1 | /*-
 2 |  * #%L
 3 |  * Use deep learning frameworks from Java in an agnostic and isolated way.
 4 |  * %%
 5 |  * Copyright (C) 2022 - 2024 Institut Pasteur and BioImage.IO developers.
 6 |  * %%
 7 |  * Licensed under the Apache License, Version 2.0 (the "License");
 8 |  * you may not use this file except in compliance with the License.
 9 |  * You may obtain a copy of the License at
10 |  * 
11 |  *      http://www.apache.org/licenses/LICENSE-2.0
12 |  * 
13 |  * Unless required by applicable law or agreed to in writing, software
14 |  * distributed under the License is distributed on an "AS IS" BASIS,
15 |  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 |  * See the License for the specific language governing permissions and
17 |  * limitations under the License.
18 |  * #L%
19 |  */
20 | package io.bioimage.modelrunner.tensor;
21 | 
22 | 
23 | import net.imglib2.RandomAccessibleInterval;
24 | import net.imglib2.transform.integer.MixedTransform;
25 | import net.imglib2.type.numeric.NumericType;
26 | import net.imglib2.type.numeric.RealType;
27 | import net.imglib2.util.Intervals;
28 | import net.imglib2.view.MixedTransformView;
29 | import net.imglib2.view.Views;
30 | 
31 | /**
32 |  * Provide static methods that can be used to make transformations on tensors
33 |  *
34 |  * @author Carlos Garcia Lopez de Haro
35 |  */
36 | public final class Utils
37 | {
38 | 	/**
39 | 	 * Method that transposes every dimension of a {@link RandomAccessibleInterval}.
40 | 	 * If a {@link RandomAccessibleInterval} with {3, 256, 512} dimensions is provided,
41 | 	 * it will be converted into one of {512, 256, 3}
42 | 	 * @param 
43 | 	 * 	possible data types of the {@link RandomAccessibleInterval}
44 | 	 * @param rai
45 | 	 * 	{@link RandomAccessibleInterval} to be transposed
46 | 	 * @return the transposed {@link RandomAccessibleInterval}
47 | 	 */
48 | 	public static  & RealType> 
49 | 	RandomAccessibleInterval transpose(RandomAccessibleInterval rai){
50 | 		long[] max = rai.maxAsPoint().positionAsLongArray();
51 | 		long[] min = rai.minAsPoint().positionAsLongArray();
52 | 		long[] tensorShape = rai.dimensionsAsLongArray();
53 | 		MixedTransform t = new MixedTransform( tensorShape.length, tensorShape.length );
54 | 		int[] transposeAxesOrderChange = new int[tensorShape.length];
55 | 		for (int i = 0; i < tensorShape.length; i ++) transposeAxesOrderChange[i] = tensorShape.length - 1 - i;
56 | 		t.setComponentMapping(transposeAxesOrderChange);
57 | 		long[] minMax = new long[tensorShape.length * 2];
58 | 		for (int i = 0; i < tensorShape.length; i ++) {
59 | 			minMax[i] = min[tensorShape.length - i - 1];
60 | 			minMax[i + tensorShape.length] = max[tensorShape.length - i - 1];
61 | 		}
62 | 		return Views.interval(new MixedTransformView( rai, t ), 
63 | 				Intervals.createMinMax(minMax));
64 | 	}
65 | 	/**
66 | 	 * Method that rearanges the dimensions on the {@link RandomAccessibleInterval}
67 | 	 * to the order provided in the 'orderChange' parameter.
68 | 	 * For example, for an array of {512, 256, 3, 1}, and orderChange = [3, 0, 2, 1] the 
69 | 	 * resulting array would be have the following dimensions [1, 512, 3, 256]
70 | 	 * @param 
71 | 	 * 	possible data types of the {@link RandomAccessibleInterval}
72 | 	 * @param rai
73 | 	 * 	{@link RandomAccessibleInterval} to be re-aranged
74 | 	 * @param orderChange
75 | 	 * 	the way to re-arange the new array
76 | 	 * @return the transposed {@link RandomAccessibleInterval}
77 | 	 */
78 | 	public static  & RealType> 
79 | 	RandomAccessibleInterval rearangeAxes(RandomAccessibleInterval rai, int[] orderChange){
80 |         final int n = rai.numDimensions();
81 |         final long[] min = new long[n];
82 |         final long[] max = new long[n];
83 |         final int[] invOrderChange = new int[n];
84 |         for (int i = 0; i < n; i++) {
85 |             min[i] = rai.min(orderChange[i]);
86 |             max[i] = rai.max(orderChange[i]);
87 |             invOrderChange[orderChange[i]] = i;
88 |         }
89 |         MixedTransform t = new MixedTransform(n, n);
90 |         t.setComponentMapping(invOrderChange);
91 |         return Views.interval(new MixedTransformView<>(rai, t), min, max);
92 | 	}
93 | }
94 | 


--------------------------------------------------------------------------------
/src/main/java/io/bioimage/modelrunner/tensor/shm/CLibrary.java:
--------------------------------------------------------------------------------
 1 | /*-
 2 |  * #%L
 3 |  * Use deep learning frameworks from Java in an agnostic and isolated way.
 4 |  * %%
 5 |  * Copyright (C) 2022 - 2024 Institut Pasteur and BioImage.IO developers.
 6 |  * %%
 7 |  * Licensed under the Apache License, Version 2.0 (the "License");
 8 |  * you may not use this file except in compliance with the License.
 9 |  * You may obtain a copy of the License at
10 |  * 
11 |  *      http://www.apache.org/licenses/LICENSE-2.0
12 |  * 
13 |  * Unless required by applicable law or agreed to in writing, software
14 |  * distributed under the License is distributed on an "AS IS" BASIS,
15 |  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 |  * See the License for the specific language governing permissions and
17 |  * limitations under the License.
18 |  * #L%
19 |  */
20 | package io.bioimage.modelrunner.tensor.shm;
21 | 
22 | import com.sun.jna.Library;
23 | import com.sun.jna.Native;
24 | import com.sun.jna.Pointer;
25 | 
26 | 
27 | public interface CLibrary extends Library {
28 |     CLibrary INSTANCE = Native.load("c", CLibrary.class);
29 | 
30 |     int shm_open(String name, int oflag, int mode);
31 |     int ftruncate(int fd, int length);
32 |     Pointer mmap(Pointer addr, int length, int prot, int flags, int fd, int offset);
33 |     int munmap(Pointer addr, int length);
34 |     int close(int fd);
35 |     int shm_unlink(String name);
36 |     
37 |     int SEEK_SET = 0;
38 |     int SEEK_CUR = 1;
39 |     int SEEK_END = 2;
40 |     long lseek(int fd, long offset, int whence);
41 | }
42 | 


--------------------------------------------------------------------------------
/src/main/java/io/bioimage/modelrunner/tensor/shm/LibRt.java:
--------------------------------------------------------------------------------
 1 | /*-
 2 |  * #%L
 3 |  * Use deep learning frameworks from Java in an agnostic and isolated way.
 4 |  * %%
 5 |  * Copyright (C) 2022 - 2024 Institut Pasteur and BioImage.IO developers.
 6 |  * %%
 7 |  * Licensed under the Apache License, Version 2.0 (the "License");
 8 |  * you may not use this file except in compliance with the License.
 9 |  * You may obtain a copy of the License at
10 |  * 
11 |  *      http://www.apache.org/licenses/LICENSE-2.0
12 |  * 
13 |  * Unless required by applicable law or agreed to in writing, software
14 |  * distributed under the License is distributed on an "AS IS" BASIS,
15 |  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 |  * See the License for the specific language governing permissions and
17 |  * limitations under the License.
18 |  * #L%
19 |  */
20 | package io.bioimage.modelrunner.tensor.shm;
21 | 
22 | import com.sun.jna.Library;
23 | import com.sun.jna.Native;
24 | import com.sun.jna.Pointer;
25 | 
26 | 
27 | public interface LibRt extends Library {
28 |     LibRt INSTANCE = Native.load("rt", LibRt.class);
29 | 
30 |     int shm_open(String name, int oflag, int mode);
31 |     int ftruncate(int fd, int length);
32 |     Pointer mmap(Pointer addr, int length, int prot, int flags, int fd, int offset);
33 |     int munmap(Pointer addr, int length);
34 |     int close(int fd);
35 |     int shm_unlink(String name);
36 |     
37 |     int SEEK_SET = 0;
38 |     int SEEK_CUR = 1;
39 |     int SEEK_END = 2;
40 |     long lseek(int fd, long offset, int whence);
41 | }
42 | 


--------------------------------------------------------------------------------
/src/main/java/io/bioimage/modelrunner/tensor/shm/MacosHelpers.java:
--------------------------------------------------------------------------------
 1 | /*-
 2 |  * #%L
 3 |  * Use deep learning frameworks from Java in an agnostic and isolated way.
 4 |  * %%
 5 |  * Copyright (C) 2022 - 2024 Institut Pasteur and BioImage.IO developers.
 6 |  * %%
 7 |  * Licensed under the Apache License, Version 2.0 (the "License");
 8 |  * you may not use this file except in compliance with the License.
 9 |  * You may obtain a copy of the License at
10 |  * 
11 |  *      http://www.apache.org/licenses/LICENSE-2.0
12 |  * 
13 |  * Unless required by applicable law or agreed to in writing, software
14 |  * distributed under the License is distributed on an "AS IS" BASIS,
15 |  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 |  * See the License for the specific language governing permissions and
17 |  * limitations under the License.
18 |  * #L%
19 |  */
20 | package io.bioimage.modelrunner.tensor.shm;
21 | 
22 | import java.io.File;
23 | import java.io.FileNotFoundException;
24 | import java.io.FileOutputStream;
25 | import java.io.IOException;
26 | import java.io.InputStream;
27 | import java.io.OutputStream;
28 | 
29 | import com.sun.jna.Library;
30 | import com.sun.jna.Native;
31 | import com.sun.jna.Platform;
32 | 
33 | public interface MacosHelpers extends Library {
34 | 	
35 | 	static final String LIBRARY_NAME = "ShmCreate";
36 | 	
37 | 	static final String LIBRARY_NAME_SUF = ".dylib";
38 | 
39 |     // Load the native library
40 | 	MacosHelpers INSTANCE = loadLibrary();
41 | 
42 |     static MacosHelpers loadLibrary() {
43 |     	InputStream in = MacosHelpers.class.getClassLoader().getResourceAsStream(LIBRARY_NAME + LIBRARY_NAME_SUF);
44 |         /*if (in == null) {
45 |             throw new FileNotFoundException("Library file " + LIBRARY_NAME + " not found in JAR.");
46 |         }*/
47 | 
48 |         File tempFile = null;
49 | 		try {
50 | 			tempFile = File.createTempFile(LIBRARY_NAME, LIBRARY_NAME_SUF);
51 | 		} catch (IOException e1) {
52 | 			e1.printStackTrace();
53 | 		}
54 |         tempFile.deleteOnExit();
55 | 
56 |         try (OutputStream out = new FileOutputStream(tempFile)) {
57 |             byte[] buffer = new byte[1024];
58 |             int readBytes;
59 |             while ((readBytes = in.read(buffer)) != -1) {
60 |                 out.write(buffer, 0, readBytes);
61 |             }
62 |         } catch (IOException e) {
63 | 			e.printStackTrace();
64 | 		}
65 | 
66 |         return (MacosHelpers) Native.load(tempFile.getAbsolutePath(), MacosHelpers.class);
67 |     }
68 | 
69 |     // Declare methods corresponding to the native functions
70 |     int create_shared_memory(String name, int size);
71 |     
72 |     void unlink_shared_memory(String name);
73 |     
74 |     long get_shared_memory_size(int fd);
75 | }
76 | 
77 | 
78 | 


--------------------------------------------------------------------------------
/src/main/java/io/bioimage/modelrunner/tensor/shm/SharedMemoryFile.java:
--------------------------------------------------------------------------------
 1 | /*-
 2 |  * #%L
 3 |  * Use deep learning frameworks from Java in an agnostic and isolated way.
 4 |  * %%
 5 |  * Copyright (C) 2022 - 2024 Institut Pasteur and BioImage.IO developers.
 6 |  * %%
 7 |  * Licensed under the Apache License, Version 2.0 (the "License");
 8 |  * you may not use this file except in compliance with the License.
 9 |  * You may obtain a copy of the License at
10 |  * 
11 |  *      http://www.apache.org/licenses/LICENSE-2.0
12 |  * 
13 |  * Unless required by applicable law or agreed to in writing, software
14 |  * distributed under the License is distributed on an "AS IS" BASIS,
15 |  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 |  * See the License for the specific language governing permissions and
17 |  * limitations under the License.
18 |  * #L%
19 |  */
20 | package io.bioimage.modelrunner.tensor.shm;
21 | 
22 | import java.io.FileNotFoundException;
23 | import java.io.IOException;
24 | 
25 | import io.bioimage.modelrunner.tensor.Tensor;
26 | import io.bioimage.modelrunner.numpy.DecodeNumpy;
27 | 
28 | import net.imglib2.RandomAccessibleInterval;
29 | import net.imglib2.type.NativeType;
30 | import net.imglib2.type.numeric.RealType;
31 | 
32 | /**
33 |  * TODO get rid of this class in favour of shared memory IPC
34 |  * Class that maps {@link Tensor} objects to a temporal file for inter-processing communication
35 |  * 
36 |  * @author Carlos Garcia Lopez de Haro
37 |  */
38 | public final class SharedMemoryFile
39 | {
40 | 	/**
41 | 	 * Create a .npy Numpy file from a {@link RandomAccessibleInterval}
42 | 	 * @param 
43 | 	 * 	the ImgLib2 data type of the {@link RandomAccessibleInterval}
44 | 	 * @param fileDir
45 | 	 * 	file path to the .npy file that is going to be created
46 | 	 * @param rai
47 | 	 * 	the {@link RandomAccessibleInterval} of interest
48 | 	 * @throws FileNotFoundException if the parent directory where the file wants to be created does not exist
49 | 	 * @throws IOException if there is any error creating the file
50 | 	 */
51 | 	public static  & NativeType> 
52 | 	void buildFileFromRai(String fileDir, RandomAccessibleInterval rai) throws FileNotFoundException, IOException {
53 | 		DecodeNumpy.saveNpy(fileDir, rai);
54 | 	}
55 | 	
56 | 	/**
57 | 	 * Read a {@link RandomAccessibleInterval} from a .npy Numpy file created to share between processes
58 | 	 * @param 
59 | 	 * 	the ImgLib2 data type of the {@link RandomAccessibleInterval}
60 | 	 * @param fileName
61 | 	 * 	name of the .npy file that contains a {@link RandomAccessibleInterval}
62 | 	 * @return a {@link RandomAccessibleInterval}
63 | 	 * @throws FileNotFoundException if the file is not found
64 | 	 * @throws IOException if there is any error reading the file
65 | 	 */
66 | 	public static  & NativeType> 
67 | 	RandomAccessibleInterval buildRaiFromFile(String fileName) throws FileNotFoundException, IOException {
68 | 		return DecodeNumpy.loadNpy(fileName);
69 | 	}
70 | }
71 | 


--------------------------------------------------------------------------------
/src/main/java/io/bioimage/modelrunner/transformations/AbstractTensorPixelTransformation.java:
--------------------------------------------------------------------------------
 1 | /*-
 2 |  * #%L
 3 |  * Use deep learning frameworks from Java in an agnostic and isolated way.
 4 |  * %%
 5 |  * Copyright (C) 2022 - 2024 Institut Pasteur and BioImage.IO developers.
 6 |  * %%
 7 |  * Licensed under the Apache License, Version 2.0 (the "License");
 8 |  * you may not use this file except in compliance with the License.
 9 |  * You may obtain a copy of the License at
10 |  * 
11 |  *      http://www.apache.org/licenses/LICENSE-2.0
12 |  * 
13 |  * Unless required by applicable law or agreed to in writing, software
14 |  * distributed under the License is distributed on an "AS IS" BASIS,
15 |  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 |  * See the License for the specific language governing permissions and
17 |  * limitations under the License.
18 |  * #L%
19 |  */
20 | package io.bioimage.modelrunner.transformations;
21 | 
22 | import io.bioimage.modelrunner.tensor.Tensor;
23 | import net.imglib2.loops.LoopBuilder;
24 | import net.imglib2.type.NativeType;
25 | import net.imglib2.type.numeric.IntegerType;
26 | import net.imglib2.type.numeric.RealType;
27 | import net.imglib2.type.numeric.real.FloatType;
28 | import net.imglib2.util.Util;
29 | 
30 | /**
31 |  * Abstract classes for tensor transformations where a new pixel value can be
32 |  * calculated solely from the corresponding pixel value in the input. This
33 |  * mapping is specified by a
34 |  *
35 |  * @author Jean-Yves Tinevez
36 |  *
37 |  */
38 | public class AbstractTensorPixelTransformation extends AbstractTensorTransformation
39 | {
40 | 
41 | 	private DoubleUnitaryOperator dun;
42 | 
43 | 	protected AbstractTensorPixelTransformation( final String name)
44 | 	{
45 | 		super( name );
46 | 	}
47 | 	
48 | 	protected void setDoubleUnitaryOperator(final DoubleUnitaryOperator fun) {
49 | 		this.dun = fun;
50 | 	}
51 | 
52 | 	@Override
53 | 	public < R extends RealType< R > & NativeType< R > > Tensor< FloatType > apply( final Tensor< R > input )
54 | 	{
55 | 		final Tensor< FloatType > output = makeOutput( input );
56 | 		applyInPlace(output);
57 | 		return output;
58 | 	}
59 | 
60 | 	@Override
61 | 	public < R extends RealType< R > & NativeType< R > >
62 | 	void applyInPlace( final Tensor< R > input )
63 | 	{
64 | 		if (Util.getTypeFromInterval(input.getData()) instanceof IntegerType && dun != null) {
65 | 			LoopBuilder
66 | 			.setImages( input.getData() )
67 | 			.multiThreaded()
68 | 			.forEachPixel( i -> i.setReal( Math.floor(dun.applyAs( i.getRealDouble() )) ) );
69 | 		} else if (dun != null) {
70 | 			LoopBuilder
71 | 			.setImages( input.getData() )
72 | 			.multiThreaded()
73 | 			.forEachPixel( i -> i.setReal( dun.applyAs( i.getRealDouble() ) ) );
74 | 		}
75 | 	}
76 | 
77 | 	@FunctionalInterface
78 | 	public interface DoubleUnitaryOperator
79 | 	{
80 | 		double applyAs( double in );
81 | 	}
82 | }
83 | 


--------------------------------------------------------------------------------
/src/main/java/io/bioimage/modelrunner/transformations/AbstractTensorTransformation.java:
--------------------------------------------------------------------------------
 1 | /*-
 2 |  * #%L
 3 |  * Use deep learning frameworks from Java in an agnostic and isolated way.
 4 |  * %%
 5 |  * Copyright (C) 2022 - 2024 Institut Pasteur and BioImage.IO developers.
 6 |  * %%
 7 |  * Licensed under the Apache License, Version 2.0 (the "License");
 8 |  * you may not use this file except in compliance with the License.
 9 |  * You may obtain a copy of the License at
10 |  * 
11 |  *      http://www.apache.org/licenses/LICENSE-2.0
12 |  * 
13 |  * Unless required by applicable law or agreed to in writing, software
14 |  * distributed under the License is distributed on an "AS IS" BASIS,
15 |  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 |  * See the License for the specific language governing permissions and
17 |  * limitations under the License.
18 |  * #L%
19 |  */
20 | package io.bioimage.modelrunner.transformations;
21 | 
22 | import io.bioimage.modelrunner.tensor.Tensor;
23 | 
24 | import net.imglib2.converter.RealTypeConverters;
25 | import net.imglib2.img.Img;
26 | import net.imglib2.img.ImgFactory;
27 | import net.imglib2.type.NativeType;
28 | import net.imglib2.type.numeric.RealType;
29 | import net.imglib2.type.numeric.real.FloatType;
30 | import net.imglib2.util.Util;
31 | 
32 | public abstract class AbstractTensorTransformation extends TensorTransformation
33 | {
34 | 
35 | 	private final String name;
36 | 	
37 | 	protected static String DEFAULT_MISSING_ARG_ERR = "Cannot execute %s BioImage.io transformation because '%s' "
38 | 			+ "parameter was not set.";
39 | 
40 | 	protected AbstractTensorTransformation( final String name )
41 | 	{
42 | 		this.name = name;
43 | 	}
44 | 
45 | 	@Override
46 | 	public String getName()
47 | 	{
48 | 		return name;
49 | 	}
50 | 
51 | 	@Override
52 | 	public Mode getMode()
53 | 	{
54 | 		return mode;
55 | 	}
56 | 
57 | 	protected < R extends RealType< R > & NativeType< R > > Tensor< FloatType > makeOutput( final Tensor< R > input )
58 | 	{
59 | 		final ImgFactory< FloatType > factory = Util.getArrayOrCellImgFactory( input.getData(), new FloatType() );
60 | 		final Img< FloatType > outputImg = factory.create( input.getData() );
61 | 		RealTypeConverters.copyFromTo(input.getData(), outputImg);
62 | 		// TODO what name final Tensor< FloatType > output = Tensor.build( getName() + '_' + input.getName(), input.getAxesOrderString(), outputImg );
63 | 		final Tensor< FloatType > output = Tensor.build( input.getName(), input.getAxesOrderString(), outputImg );
64 | 		return output;
65 | 	}
66 | }
67 | 


--------------------------------------------------------------------------------
/src/main/java/io/bioimage/modelrunner/transformations/BinarizeTransformation.java:
--------------------------------------------------------------------------------
 1 | /*-
 2 |  * #%L
 3 |  * Use deep learning frameworks from Java in an agnostic and isolated way.
 4 |  * %%
 5 |  * Copyright (C) 2022 - 2024 Institut Pasteur and BioImage.IO developers.
 6 |  * %%
 7 |  * Licensed under the Apache License, Version 2.0 (the "License");
 8 |  * you may not use this file except in compliance with the License.
 9 |  * You may obtain a copy of the License at
10 |  * 
11 |  *      http://www.apache.org/licenses/LICENSE-2.0
12 |  * 
13 |  * Unless required by applicable law or agreed to in writing, software
14 |  * distributed under the License is distributed on an "AS IS" BASIS,
15 |  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 |  * See the License for the specific language governing permissions and
17 |  * limitations under the License.
18 |  * #L%
19 |  */
20 | package io.bioimage.modelrunner.transformations;
21 | 
22 | import io.bioimage.modelrunner.tensor.Tensor;
23 | 
24 | import net.imglib2.type.NativeType;
25 | import net.imglib2.type.numeric.RealType;
26 | import net.imglib2.type.numeric.real.FloatType;
27 | 
28 | public class BinarizeTransformation extends AbstractTensorPixelTransformation
29 | {
30 | 	
31 | 	private static String name = "binarize";
32 | 	private Double threshold;
33 | 	private Double eps = Math.pow(10, -6);
34 | 	
35 | 
36 | 	public BinarizeTransformation()
37 | 	{
38 | 		super( name );
39 | 		super.setDoubleUnitaryOperator(v -> ( v >= threshold ) ? 1d : 0d);
40 | 	}
41 | 	
42 | 	public void setEps(Object eps) {
43 | 		if (eps instanceof Integer) {
44 | 			this.eps = Double.valueOf((int) eps);
45 | 		} else if (eps instanceof Double) {
46 | 			this.eps = (double) eps;
47 | 		} else if (eps instanceof String) {
48 | 			this.eps = Double.valueOf((String) eps);
49 | 		} else {
50 | 			throw new IllegalArgumentException("'eps' parameter has to be either and instance of "
51 | 					+ Float.class + " or " + Double.class
52 | 					+ ". The provided argument is an instance of: " + eps.getClass());
53 | 		}
54 | 	}
55 | 	
56 | 	public void setThreshold(Object threshold) {
57 | 		if (threshold instanceof Integer) {
58 | 			this.threshold = Double.valueOf((int) threshold);
59 | 		} else if (threshold instanceof Double) {
60 | 			this.threshold = (double) threshold;
61 | 		} else if (threshold instanceof String) {
62 | 			this.threshold = Double.valueOf((String) threshold);
63 | 		} else {
64 | 			throw new IllegalArgumentException("'threshold' parameter has to be either and instance of "
65 | 					+ Integer.class + " or " + Double.class
66 | 					+ ". The provided argument is an instance of: " + threshold.getClass());
67 | 		}
68 | 	}
69 | 	
70 | 	public void checkRequiredArgs() {
71 | 		if (threshold == null) {
72 | 			throw new IllegalArgumentException(String.format(DEFAULT_MISSING_ARG_ERR, name, "threshold"));
73 | 		}
74 | 	}
75 | 
76 | 	public < R extends RealType< R > & NativeType< R > > Tensor< FloatType > apply( final Tensor< R > input )
77 | 	{
78 | 		checkRequiredArgs();
79 | 		return super.apply(input);
80 | 	}
81 | 
82 | 	public < R extends RealType< R > & NativeType< R > >  void applyInPlace( final Tensor< R > input )
83 | 	{
84 | 		checkRequiredArgs();
85 | 		super.applyInPlace(input);
86 | 	}
87 | }
88 | 


--------------------------------------------------------------------------------
/src/main/java/io/bioimage/modelrunner/transformations/ClipTransformation.java:
--------------------------------------------------------------------------------
  1 | /*-
  2 |  * #%L
  3 |  * Use deep learning frameworks from Java in an agnostic and isolated way.
  4 |  * %%
  5 |  * Copyright (C) 2022 - 2024 Institut Pasteur and BioImage.IO developers.
  6 |  * %%
  7 |  * Licensed under the Apache License, Version 2.0 (the "License");
  8 |  * you may not use this file except in compliance with the License.
  9 |  * You may obtain a copy of the License at
 10 |  * 
 11 |  *      http://www.apache.org/licenses/LICENSE-2.0
 12 |  * 
 13 |  * Unless required by applicable law or agreed to in writing, software
 14 |  * distributed under the License is distributed on an "AS IS" BASIS,
 15 |  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 16 |  * See the License for the specific language governing permissions and
 17 |  * limitations under the License.
 18 |  * #L%
 19 |  */
 20 | package io.bioimage.modelrunner.transformations;
 21 | 
 22 | import io.bioimage.modelrunner.tensor.Tensor;
 23 | 
 24 | import net.imglib2.type.NativeType;
 25 | import net.imglib2.type.numeric.RealType;
 26 | import net.imglib2.type.numeric.real.FloatType;
 27 | 
 28 | public class ClipTransformation extends AbstractTensorPixelTransformation
 29 | {
 30 | 	
 31 | 	private static String name = "clip";
 32 | 	private Double min;
 33 | 	private Double max;
 34 | 	private double eps = Math.pow(10, -6);
 35 | 
 36 | 	public ClipTransformation()
 37 | 	{
 38 | 		super(name);
 39 | 		super.setDoubleUnitaryOperator(v -> v >= max ? max.doubleValue() : (v < min ? min.doubleValue() : v));
 40 | 	}
 41 | 	
 42 | 	public void setEps(Object eps) {
 43 | 		if (eps instanceof Integer) {
 44 | 			this.eps = Double.valueOf((int) eps);
 45 | 		} else if (eps instanceof Double) {
 46 | 			this.eps = (double) eps;
 47 | 		} else if (eps instanceof String) {
 48 | 			this.eps = Double.valueOf((String) eps);
 49 | 		} else {
 50 | 			throw new IllegalArgumentException("'eps' parameter has to be either and instance of "
 51 | 					+ Float.class + " or " + Double.class
 52 | 					+ ". The provided argument is an instance of: " + eps.getClass());
 53 | 		}
 54 | 	}
 55 | 	
 56 | 	public void setMin(Object min) {
 57 | 		if (min instanceof Integer) {
 58 | 			this.min = Double.valueOf((int) min);
 59 | 		} else if (min instanceof Double) {
 60 | 			this.min = (double) min;
 61 | 		} else if (min instanceof String) {
 62 | 			this.min = Double.valueOf((String) min);
 63 | 		} else {
 64 | 			throw new IllegalArgumentException("'min' parameter has to be either and instance of "
 65 | 					+ Integer.class + " or " + Double.class
 66 | 					+ ". The provided argument is an instance of: " + min.getClass());
 67 | 		}
 68 | 	}
 69 | 	
 70 | 	public void setMax(Object max) {
 71 | 		if (max instanceof Integer) {
 72 | 			this.max = Double.valueOf((int) max);
 73 | 		} else if (max instanceof Double) {
 74 | 			this.max = (double) max;
 75 | 		} else if (max instanceof String) {
 76 | 			this.max = Double.valueOf((String) max);
 77 | 		} else {
 78 | 			throw new IllegalArgumentException("'max' parameter has to be either and instance of "
 79 | 					+ Integer.class + " or " + Double.class
 80 | 					+ ". The provided argument is an instance of: " + max.getClass());
 81 | 		}
 82 | 	}
 83 | 	
 84 | 	public void checkRequiredArgs() {
 85 | 		if (min == null) {
 86 | 			throw new IllegalArgumentException(String.format(DEFAULT_MISSING_ARG_ERR, name, "min"));
 87 | 		} else if (max == null) {
 88 | 			throw new IllegalArgumentException(String.format(DEFAULT_MISSING_ARG_ERR, name, "max"));
 89 | 		}
 90 | 	}
 91 | 
 92 | 	public < R extends RealType< R > & NativeType< R > > Tensor< FloatType > apply( final Tensor< R > input )
 93 | 	{
 94 | 		checkRequiredArgs();
 95 | 		return super.apply(input);
 96 | 	}
 97 | 
 98 | 	public < R extends RealType< R > & NativeType< R > >
 99 | 	void applyInPlace( final Tensor< R > input )
100 | 	{
101 | 		checkRequiredArgs();
102 | 		super.applyInPlace(input);
103 | 	}
104 | }
105 | 


--------------------------------------------------------------------------------
/src/main/java/io/bioimage/modelrunner/transformations/EnsureDtypeTransformation.java:
--------------------------------------------------------------------------------
 1 | /*-
 2 |  * #%L
 3 |  * Use deep learning frameworks from Java in an agnostic and isolated way.
 4 |  * %%
 5 |  * Copyright (C) 2022 - 2024 Institut Pasteur and BioImage.IO developers.
 6 |  * %%
 7 |  * Licensed under the Apache License, Version 2.0 (the "License");
 8 |  * you may not use this file except in compliance with the License.
 9 |  * You may obtain a copy of the License at
10 |  * 
11 |  *      http://www.apache.org/licenses/LICENSE-2.0
12 |  * 
13 |  * Unless required by applicable law or agreed to in writing, software
14 |  * distributed under the License is distributed on an "AS IS" BASIS,
15 |  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 |  * See the License for the specific language governing permissions and
17 |  * limitations under the License.
18 |  * #L%
19 |  */
20 | package io.bioimage.modelrunner.transformations;
21 | 
22 | 
23 | /**
24 |  * TODO do it
25 |  */
26 | public class EnsureDtypeTransformation extends AbstractTensorPixelTransformation
27 | {
28 | 	
29 | 	private static String name = "ensure_dtype";
30 | 
31 | 	public EnsureDtypeTransformation()
32 | 	{
33 | 		super(name);
34 | 	}
35 | }
36 | 


--------------------------------------------------------------------------------
/src/main/java/io/bioimage/modelrunner/transformations/SigmoidTransformation.java:
--------------------------------------------------------------------------------
 1 | /*-
 2 |  * #%L
 3 |  * Use deep learning frameworks from Java in an agnostic and isolated way.
 4 |  * %%
 5 |  * Copyright (C) 2022 - 2024 Institut Pasteur and BioImage.IO developers.
 6 |  * %%
 7 |  * Licensed under the Apache License, Version 2.0 (the "License");
 8 |  * you may not use this file except in compliance with the License.
 9 |  * You may obtain a copy of the License at
10 |  * 
11 |  *      http://www.apache.org/licenses/LICENSE-2.0
12 |  * 
13 |  * Unless required by applicable law or agreed to in writing, software
14 |  * distributed under the License is distributed on an "AS IS" BASIS,
15 |  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 |  * See the License for the specific language governing permissions and
17 |  * limitations under the License.
18 |  * #L%
19 |  */
20 | package io.bioimage.modelrunner.transformations;
21 | 
22 | import io.bioimage.modelrunner.tensor.Tensor;
23 | 
24 | import net.imglib2.type.NativeType;
25 | import net.imglib2.type.numeric.RealType;
26 | import net.imglib2.type.numeric.real.FloatType;
27 | 
28 | public class SigmoidTransformation extends AbstractTensorPixelTransformation
29 | {
30 | 	private static String name = "sigmoid";
31 | 
32 | 	public SigmoidTransformation()
33 | 	{
34 | 		super(name);
35 | 		super.setDoubleUnitaryOperator(v -> ( double ) ( 1. / ( 1. + Math.exp( -v ) ) ));
36 | 	}
37 | 
38 | 	public < R extends RealType< R > & NativeType< R > > Tensor< FloatType > apply( final Tensor< R > input )
39 | 	{
40 | 		return super.apply(input);
41 | 	}
42 | 
43 | 	public < R extends RealType< R > & NativeType< R > > void applyInPlace( final Tensor< R > input )
44 | 	{
45 | 		super.applyInPlace(input);
46 | 	}
47 | }
48 | 


--------------------------------------------------------------------------------
/src/main/java/io/bioimage/modelrunner/transformations/TensorTransformation.java:
--------------------------------------------------------------------------------
  1 | /*-
  2 |  * #%L
  3 |  * Use deep learning frameworks from Java in an agnostic and isolated way.
  4 |  * %%
  5 |  * Copyright (C) 2022 - 2024 Institut Pasteur and BioImage.IO developers.
  6 |  * %%
  7 |  * Licensed under the Apache License, Version 2.0 (the "License");
  8 |  * you may not use this file except in compliance with the License.
  9 |  * You may obtain a copy of the License at
 10 |  * 
 11 |  *      http://www.apache.org/licenses/LICENSE-2.0
 12 |  * 
 13 |  * Unless required by applicable law or agreed to in writing, software
 14 |  * distributed under the License is distributed on an "AS IS" BASIS,
 15 |  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 16 |  * See the License for the specific language governing permissions and
 17 |  * limitations under the License.
 18 |  * #L%
 19 |  */
 20 | package io.bioimage.modelrunner.transformations;
 21 | 
 22 | import io.bioimage.modelrunner.tensor.Tensor;
 23 | import io.bioimage.modelrunner.transformations.TensorTransformation.Mode;
 24 | import net.imglib2.type.NativeType;
 25 | import net.imglib2.type.numeric.RealType;
 26 | import net.imglib2.type.numeric.real.FloatType;
 27 | 
 28 | /**
 29 |  * Interface for transformation that change the data in a tensor.
 30 |  *
 31 |  * @author Jean-Yves Tinevez
 32 |  *
 33 |  */
 34 | public abstract class TensorTransformation
 35 | {
 36 | 	
 37 | 	protected Mode mode = Mode.FIXED;
 38 | 
 39 | 	/**
 40 | 	 * Applies this transformation to the specified input tensor.
 41 | 	 * 

42 | * This method will instantiate a new tensor of floats, with the same name, 43 | * and axis ordering that of the input, and write the transformation results 44 | * in it. 45 | * 46 | * @param 47 | * the pixel type of the input tensor. 48 | * @param input 49 | * the input tensor. 50 | * @return a new tensor with float pixels. 51 | */ 52 | public abstract < R extends RealType< R > & NativeType< R > > Tensor< FloatType > apply( Tensor< R > input ); 53 | 54 | /** 55 | * Applies this transformation to the specified input tensor, and overwrites 56 | * it with the results. The input tensor must of type float. 57 | * 58 | * @param 59 | * ImgLib2 data type of the input tensor 60 | * @param input 61 | * the input tensor. 62 | */ 63 | public abstract < R extends RealType< R > & NativeType< R > > void applyInPlace( Tensor< R > input ); 64 | 65 | /** 66 | * Returns the name of this transformation. 67 | * 68 | * @return the name of this transformation. 69 | */ 70 | public abstract String getName(); 71 | 72 | public void setMode(Object mode) { 73 | if (mode instanceof String ) 74 | this.mode = Mode.valueOf(((String) mode).toUpperCase()); 75 | else if (mode instanceof Mode) 76 | this.mode = (Mode) mode; 77 | else 78 | throw new IllegalArgumentException("'mode' parameter has to be either and instance of " + String.class 79 | + " or " + Mode.class + ". The provided argument is an instance of: " + mode.getClass()); 80 | } 81 | 82 | public abstract Mode getMode(); 83 | 84 | /** 85 | * Tensor transformation modes. 86 | */ 87 | public enum Mode 88 | { 89 | 90 | FIXED( "fixed" ), 91 | PER_DATASET( "per_dataset" ), 92 | PER_SAMPLE( "per_sample" ); 93 | 94 | private final String name; 95 | 96 | private Mode( final String name ) 97 | { 98 | this.name = name; 99 | } 100 | 101 | @Override 102 | public String toString() 103 | { 104 | return name; 105 | } 106 | } 107 | } 108 | -------------------------------------------------------------------------------- /src/main/java/io/bioimage/modelrunner/utils/Constants.java: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * Use deep learning frameworks from Java in an agnostic and isolated way. 4 | * %% 5 | * Copyright (C) 2022 - 2024 Institut Pasteur and BioImage.IO developers. 6 | * %% 7 | * Licensed under the Apache License, Version 2.0 (the "License"); 8 | * you may not use this file except in compliance with the License. 9 | * You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, software 14 | * distributed under the License is distributed on an "AS IS" BASIS, 15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | * See the License for the specific language governing permissions and 17 | * limitations under the License. 18 | * #L% 19 | */ 20 | package io.bioimage.modelrunner.utils; 21 | 22 | import java.io.InputStream; 23 | import java.util.Properties; 24 | 25 | import io.bioimage.modelrunner.transformations.PythonTransformation; 26 | 27 | /** 28 | * Class that contains important constants for the software 29 | * @author Carlos Garcia Lopez de Haro 30 | * 31 | */ 32 | public class Constants { 33 | 34 | final public static String ISSUES_LINK = "https://github.com/bioimage-io/JDLL/issues"; 35 | // TODO update wiki link 36 | final public static String WIKI_LINK = "https://github.com/bioimage-io/JDLL/wiki"; 37 | final public static String ENGINES_LINK = "https://raw.githubusercontent.com/bioimage-io/JDLL/main/src/main/resources/availableDLVersions.yml"; 38 | 39 | /** 40 | * File name of the resource description file inside the model folder 41 | */ 42 | public static final String RDF_FNAME = "rdf.yaml"; 43 | /** 44 | * Last part of files stored in zenodo 45 | */ 46 | public static final String ZENODO_ANNOYING_SUFFIX = "/content"; 47 | /** 48 | * Zenodo domain 49 | */ 50 | public static final String ZENODO_DOMAIN = "https://zenodo.org/"; 51 | /** 52 | * Name of the pre- or post-processing that requires using Python 53 | */ 54 | public static final String PYTHON_PROCESSING_NAME = PythonTransformation.NAME; 55 | 56 | public static final String JDLL_VERSION = getVersion(); 57 | 58 | public static final String JAR_NAME = getNAME(); 59 | 60 | private static String getVersion() { 61 | try (InputStream input = Constants.class.getResourceAsStream("/.jdll_properties")) { 62 | Properties prop = new Properties(); 63 | prop.load(input); 64 | return prop.getProperty("version"); 65 | } catch (Exception | Error ex) { 66 | return "unknown"; 67 | } 68 | } 69 | 70 | private static String getNAME() { 71 | try (InputStream input = Constants.class.getResourceAsStream("/.jdll_properties")) { 72 | Properties prop = new Properties(); 73 | prop.load(input); 74 | return prop.getProperty("name"); 75 | } catch (Exception | Error ex) { 76 | return "unknown"; 77 | } 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /src/main/java/io/bioimage/modelrunner/utils/FileUtils.java: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * Use deep learning frameworks from Java in an agnostic and isolated way. 4 | * %% 5 | * Copyright (C) 2022 - 2024 Institut Pasteur and BioImage.IO developers. 6 | * %% 7 | * Licensed under the Apache License, Version 2.0 (the "License"); 8 | * you may not use this file except in compliance with the License. 9 | * You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, software 14 | * distributed under the License is distributed on an "AS IS" BASIS, 15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | * See the License for the specific language governing permissions and 17 | * limitations under the License. 18 | * #L% 19 | */ 20 | package io.bioimage.modelrunner.utils; 21 | 22 | import java.io.IOException; 23 | import java.nio.file.DirectoryStream; 24 | import java.nio.file.Files; 25 | import java.nio.file.Path; 26 | import java.nio.file.StandardCopyOption; 27 | 28 | 29 | /** 30 | * Class to unzip files and directories 31 | * 32 | * @author Carlos Javier Garcia Lopez de Haro 33 | */ 34 | 35 | public class FileUtils { 36 | 37 | /** 38 | * Copy one folder into another folder creating the necessary subfolders 39 | * 40 | * @param src 41 | * folder to be copied 42 | * @param dest 43 | * destination folder 44 | * @throws IOException if there is any error copying the contents of the folder 45 | */ 46 | public static void copyFolder(Path src, Path dest) throws IOException { 47 | // If the directory does not exist, create it 48 | if (!Files.exists(dest)) { 49 | Files.createDirectories(dest); 50 | } 51 | try (DirectoryStream stream = Files.newDirectoryStream(src)) { 52 | for (Path entry : stream) { 53 | Path newDest = dest.resolve(entry.getFileName()); 54 | 55 | if (Files.isDirectory(entry)) { 56 | copyFolder(entry, newDest); 57 | } else { 58 | Files.copy(entry, newDest, StandardCopyOption.REPLACE_EXISTING); 59 | } 60 | } 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/main/java/io/bioimage/modelrunner/utils/Log.java: -------------------------------------------------------------------------------- 1 | /*- 2 | * #%L 3 | * Use deep learning frameworks from Java in an agnostic and isolated way. 4 | * %% 5 | * Copyright (C) 2022 - 2024 Institut Pasteur and BioImage.IO developers. 6 | * %% 7 | * Licensed under the Apache License, Version 2.0 (the "License"); 8 | * you may not use this file except in compliance with the License. 9 | * You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, software 14 | * distributed under the License is distributed on an "AS IS" BASIS, 15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | * See the License for the specific language governing permissions and 17 | * limitations under the License. 18 | * #L% 19 | */ 20 | package io.bioimage.modelrunner.utils; 21 | 22 | import java.text.SimpleDateFormat; 23 | import java.util.Date; 24 | import java.util.function.Consumer; 25 | 26 | public class Log { 27 | /** 28 | * Format of the time 29 | */ 30 | public static SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss"); 31 | 32 | /** 33 | * Get current time. 34 | * REturns the time of the day in "HH:mm:ss" format with military time. 35 | * Example 16:20:59 36 | * @return the time 37 | */ 38 | public static String gct() { 39 | return format.format(new Date()); 40 | } 41 | 42 | /** 43 | * Write the wanted string to a Consumer to communicate with the main interface. 44 | * It also prints the message on the terminal 45 | * @param consumer 46 | * consumer to communicate with the main code. This parameter can be null and 47 | * then the log will only be displayed on the terminal. 48 | * @param str 49 | * String to communicate 50 | */ 51 | public static void addProgressAndShowInTerminal(Consumer consumer, String str) { 52 | addProgressAndShowInTerminal(consumer, str, false); 53 | } 54 | 55 | /** 56 | * Write the wanted string to a Consumer to communicate with the main interface. 57 | * It also prints the message on the terminal 58 | * @param consumer 59 | * consumer to communicate with the main code. This parameter can be null and 60 | * then the log will only be displayed on the terminal. 61 | * @param str 62 | * String to communicate 63 | * @param addTime 64 | * whether to specify the time along with the message or not 65 | */ 66 | public static void addProgressAndShowInTerminal(Consumer consumer, String str, boolean addTime) { 67 | if (addTime) 68 | str = Log.gct() + " -- " + str + System.lineSeparator(); 69 | else 70 | str += System.lineSeparator(); 71 | if (consumer != null) 72 | consumer.accept(str); 73 | System.out.println(str); 74 | } 75 | 76 | /** 77 | * Write the wanted string to a Consumer to communicate with the main interface. 78 | * @param consumer 79 | * consumer to communicate with the main code 80 | * @param str 81 | * String to communicate 82 | */ 83 | public static void addProgress(Consumer consumer, String str) { 84 | addProgress(consumer, str, false); 85 | } 86 | 87 | /** 88 | * Write the wanted string to a Consumer to communicate with the main interface. 89 | * @param consumer 90 | * consumer to communicate with the main code 91 | * @param str 92 | * String to communicate 93 | * @param addTime 94 | * whether to specify the time along with the message or not 95 | */ 96 | public static void addProgress(Consumer consumer, String str, boolean addTime) { 97 | if (consumer == null) 98 | return; 99 | if (addTime) 100 | str = Log.gct() + " -- " + str + System.lineSeparator(); 101 | else 102 | str += System.lineSeparator(); 103 | consumer.accept(str); 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /src/main/java/io/bioimage/modelrunner/versionmanagement/JarInfo.java: -------------------------------------------------------------------------------- 1 | package io.bioimage.modelrunner.versionmanagement; 2 | 3 | import com.fasterxml.jackson.databind.ObjectMapper; 4 | 5 | import java.io.IOException; 6 | import java.net.URL; 7 | import java.util.Map; 8 | 9 | public class JarInfo { 10 | 11 | // Static instance for the Singleton 12 | private static JarInfo instance; 13 | 14 | // Map to store the parsed JSON data 15 | private Map urlData; 16 | 17 | private static URL FILE_PATH = JarInfo.class.getClassLoader().getResource("jar_sizes.json"); 18 | 19 | // Private constructor to restrict instantiation 20 | private JarInfo() throws IOException { 21 | loadJsonData(); 22 | } 23 | 24 | /** 25 | * Public method to initialize or get the singleton instance. 26 | * 27 | * @return The single instance of {@link JarInfo} 28 | * @throws IOException If the file cannot be loaded 29 | */ 30 | public static JarInfo getInstance() throws IOException { 31 | if (instance == null) { 32 | instance = new JarInfo(); 33 | } 34 | return instance; 35 | } 36 | 37 | /** 38 | * Public method to access the URL data 39 | * 40 | * @return Map containing the URL and their respective sizes 41 | */ 42 | public Map getAllData() { 43 | return urlData; 44 | } 45 | 46 | /** 47 | * Method to retrieve the size for a specific URL 48 | * 49 | * @param url The URL to look up 50 | * @return The size associated with the URL, or null if not found 51 | */ 52 | public Integer get(String url) { 53 | return urlData.get(url); 54 | } 55 | 56 | // Private method to load and parse the JSON data 57 | @SuppressWarnings("unchecked") 58 | private void loadJsonData() throws IOException { 59 | ObjectMapper objectMapper = new ObjectMapper(); 60 | urlData = objectMapper.readValue(FILE_PATH, Map.class); 61 | } 62 | } 63 | 64 | -------------------------------------------------------------------------------- /src/main/resources/.jdll_properties: -------------------------------------------------------------------------------- 1 | version=${project.version} 2 | name=${project.artifactId} 3 | -------------------------------------------------------------------------------- /src/main/resources/ShmCreate.dylib: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bioimage-io/JDLL/a0c32d8e502759214c7188b9ef0167397521f220/src/main/resources/ShmCreate.dylib -------------------------------------------------------------------------------- /src/main/resources/appose-python.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bioimage-io/JDLL/a0c32d8e502759214c7188b9ef0167397521f220/src/main/resources/appose-python.zip -------------------------------------------------------------------------------- /src/main/resources/jdll_icons/search_logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bioimage-io/JDLL/a0c32d8e502759214c7188b9ef0167397521f220/src/main/resources/jdll_icons/search_logo.png -------------------------------------------------------------------------------- /src/main/resources/jdll_icons/search_logo_full_res.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bioimage-io/JDLL/a0c32d8e502759214c7188b9ef0167397521f220/src/main/resources/jdll_icons/search_logo_full_res.png -------------------------------------------------------------------------------- /src/main/resources/op_environments/stardist.yaml: -------------------------------------------------------------------------------- 1 | name: stardist 2 | channels: 3 | - conda-forge 4 | - defaults 5 | dependencies: 6 | - python=3.10 7 | - appose 8 | - numpy 9 | - xarray 10 | - stardist 11 | -------------------------------------------------------------------------------- /src/main/resources/special_models/cellpose/rdf.yaml: -------------------------------------------------------------------------------- 1 | authors: null 2 | cite: 3 | - {doi: 10.1038/s41592-020-01018-x, text: 'Stringer, C., Wang, T., Michaelos, M., 4 | & Pachitariu, M. (2021). Cellpose: a generalist algorithm for cellular segmentation. 5 | Nature methods, 18(1), 100-106.', url: null} 6 | - {doi: 10.1038/s41592-022-01663-4, text: 'Pachitariu, M. & Stringer, C. (2022). Cellpose 7 | 2.0: how to train your own model. Nature methods, 1-8.', url: null} 8 | config: 9 | bioimageio: 10 | thumbnails: {cover.png: cover.thumbnail.png} 11 | covers: [cover.png] 12 | description: cellpose, a eneralist algorithm for cellular segmentation. 13 | documentation: doc.md 14 | format_version: 0.5.3 15 | id: jdll-cellpose 16 | inputs: 17 | - axes: 18 | - {id: x, size: -1, type: space} 19 | - {id: y, size: -1, type: space} 20 | - channel_names: [%s] 21 | type: channel 22 | id: input 23 | test_tensor: null 24 | license: CC-BY-NC-4.0 25 | maintainers: [] 26 | name: jdll cellpose 27 | outputs: 28 | - axes: 29 | - id: x 30 | scale: 1.0 31 | size: {axis_id: x, offset: 0, tensor_id: input} 32 | type: space 33 | - id: y 34 | scale: 1.0 35 | size: {axis_id: y, offset: 0, tensor_id: input} 36 | type: space 37 | id: labels 38 | test_tensor: null 39 | data: 40 | type: uint16 41 | unit: arbitrary unit 42 | - axes: 43 | - id: x 44 | scale: 1.0 45 | size: {axis_id: x, offset: 0, tensor_id: input} 46 | type: space 47 | - id: y 48 | scale: 1.0 49 | size: {axis_id: y, offset: 0, tensor_id: input} 50 | type: space 51 | - channel_names: [ch_0, ch_1, ch_2] 52 | type: channel 53 | id: flows_0 54 | test_tensor: null 55 | data: 56 | type: uint8 57 | unit: arbitrary unit 58 | - axes: 59 | - channel_names: [ch_0, ch_1] 60 | type: channel 61 | - id: x 62 | scale: 1.0 63 | size: {axis_id: x, offset: 0, tensor_id: input} 64 | type: space 65 | - id: y 66 | scale: 1.0 67 | size: {axis_id: y, offset: 0, tensor_id: input} 68 | type: space 69 | id: flows_1 70 | test_tensor: null 71 | data: 72 | type: float32 73 | unit: arbitrary unit 74 | - axes: 75 | - id: x 76 | scale: 1.0 77 | size: {axis_id: x, offset: 0, tensor_id: input} 78 | type: space 79 | - id: y 80 | scale: 1.0 81 | size: {axis_id: y, offset: 0, tensor_id: input} 82 | type: space 83 | id: flows_2 84 | data: 85 | type: float32 86 | unit: arbitrary unit 87 | test_tensor: null 88 | - axes: 89 | - {id: i, size: 256, type: space} 90 | id: styles 91 | test_tensor: null 92 | data: 93 | type: float32 94 | unit: arbitrary unit 95 | - axes: 96 | - id: x 97 | scale: 1.0 98 | size: {axis_id: x, offset: 0, tensor_id: input} 99 | type: space 100 | - id: y 101 | scale: 1.0 102 | size: {axis_id: y, offset: 0, tensor_id: input} 103 | type: space 104 | - channel_names: [%s] 105 | type: channel 106 | id: image_dn 107 | test_tensor: null 108 | data: 109 | type: float32 110 | unit: arbitrary unit 111 | tags: [nuclei segmentation, epithelial cells, fluorescence microscopy, cell-segmentation, cellpose, 2D] 112 | type: model 113 | version: 0.1.0 114 | weights: 115 | pytorch_state_dict: 116 | architecture: 117 | callable: CellposeJDLLWrapper 118 | kwargs: 119 | channels: [0, 0] 120 | flow_threshold: 0.4 121 | source: cellpose_jdll.py 122 | pytorch_version: 2.4.0 123 | sha256: 02b82974f25f670215bbfba32409e02941e90bf4852e3fcea6a0a8e75edc3936 124 | source: %s 125 | -------------------------------------------------------------------------------- /wiki/engines_folders.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bioimage-io/JDLL/a0c32d8e502759214c7188b9ef0167397521f220/wiki/engines_folders.png -------------------------------------------------------------------------------- /wiki/vs_redist_snapshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bioimage-io/JDLL/a0c32d8e502759214c7188b9ef0167397521f220/wiki/vs_redist_snapshot.png --------------------------------------------------------------------------------