- Python: tree of python objects instead of tree of dicts

- Rust: more derives
This commit is contained in:
w.pomp
2026-06-22 18:08:58 +02:00
parent 034b879e3f
commit 5ecc5c6cb4
38 changed files with 7582 additions and 3435 deletions
-171
View File
@@ -1,171 +0,0 @@
name: Publish
on: [push, pull_request, workflow_call]
permissions:
contents: read
jobs:
linux:
runs-on: ${{ matrix.platform.runner }}
strategy:
matrix:
platform:
- runner: ubuntu-latest
target: x86_64
- runner: ubuntu-latest
target: x86
- runner: ubuntu-latest
target: aarch64
- runner: ubuntu-latest
target: armv7
- runner: ubuntu-latest
target: s390x
- runner: ubuntu-latest
target: ppc64le
steps:
- uses: actions/checkout@v6
- uses: actions/setup-python@v6
with:
python-version: '3.12'
- name: Build wheels
uses: PyO3/maturin-action@v1
with:
target: ${{ matrix.platform.target }}
args: --release --out dist
sccache: 'true'
manylinux: auto
- name: Upload wheels
uses: actions/upload-artifact@v6
with:
name: wheels-linux-${{ matrix.platform.target }}
path: dist
windows:
runs-on: ${{ matrix.platform.runner }}
strategy:
matrix:
platform:
- runner: windows-latest
target: x64
# - runner: windows-11-arm
# target: aarch64
steps:
- uses: actions/checkout@v6
- uses: actions/setup-python@v6
with:
python-version: '3.12'
architecture: ${{ matrix.platform.target }}
- name: Build wheels
uses: PyO3/maturin-action@v1
with:
target: ${{ matrix.platform.target }}
args: --release --out dist
sccache: 'true'
- name: Upload wheels
uses: actions/upload-artifact@v6
with:
name: wheels-windows-${{ matrix.platform.target }}
path: dist
macos:
runs-on: ${{ matrix.platform.runner }}
strategy:
matrix:
platform:
- runner: macos-latest
target: x86_64
- runner: macos-14
target: aarch64
steps:
- uses: actions/checkout@v6
- uses: actions/setup-python@v6
with:
python-version: '3.12'
- name: Build wheels
uses: PyO3/maturin-action@v1
with:
target: ${{ matrix.platform.target }}
args: --release --out dist
sccache: 'true'
- name: Upload wheels
uses: actions/upload-artifact@v6
with:
name: wheels-macos-${{ matrix.platform.target }}
path: dist
sdist:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
- name: Build sdist
uses: PyO3/maturin-action@v1
with:
command: sdist
args: --out dist
- name: Upload sdist
uses: actions/upload-artifact@v6
with:
name: wheels-sdist
path: dist
release:
name: Release
runs-on: ubuntu-latest
needs: [linux, windows, macos, sdist]
steps:
- uses: actions/download-artifact@v7
- name: Publish to PyPI
uses: PyO3/maturin-action@v1
env:
MATURIN_PYPI_TOKEN: ${{ secrets.PYPI_API_TOKEN }}
with:
command: upload
args: --non-interactive --skip-existing wheels-*/*
crates_io_publish:
name: Publish (crates.io)
runs-on: ubuntu-latest
timeout-minutes: 25
steps:
- uses: actions/checkout@v6
- uses: dtolnay/rust-toolchain@stable
- name: cargo-release Cache
id: cargo_release_cache
uses: actions/cache@v5
with:
path: ~/.cargo/bin/cargo-release
key: ${{ runner.os }}-cargo-release
- run: cargo install cargo-release
if: steps.cargo_release_cache.outputs.cache-hit != 'true'
- name: cargo login
run: cargo login ${{ secrets.CRATES_IO_API_TOKEN }}
# allow-branch HEAD is because GitHub actions switches
# to the tag while building, which is a detached head
# Publishing is currently messy, because:
#
# * `peace_rt_model_core` exports `NativeError` or `WebError` depending on the target.
# * `peace_rt_model_web` fails to build when publishing the workspace for a native target.
# * `peace_rt_model_web` still needs its dependencies to be published before it can be
# published.
# * `peace_rt_model_hack` needs `peace_rt_model_web` to be published before it can be
# published.
#
# We *could* pass through `--no-verify` so `cargo` doesn't build the crate before publishing,
# which is reasonable, since this job only runs after the Linux, Windows, and WASM builds
# have passed.
- name: "cargo release publish"
run: |-
cargo release \
publish \
--workspace \
--all-features \
--allow-branch "main" \
--no-confirm \
--no-verify \
--execute
+66
View File
@@ -0,0 +1,66 @@
name: Publish
on: [workflow_dispatch]
permissions:
contents: read
jobs:
crates_io_publish:
name: Publish (crates.io)
runs-on: ubuntu-latest
timeout-minutes: 25
steps:
- uses: actions/checkout@v6
- name: Restore cache
uses: actions/cache/restore@v4
with:
path: |
~/.cargo
key: cache-ubuntu-cargo-publish
- name: Install Rust
run: |-
export PATH="$HOME/.cargo/bin:$PATH"
if ! command -v rustc >/dev/null 2>&1; then
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y
else
rustup update
fi
cargo install cargo-release
shell: bash
# allow-branch HEAD is because GitHub actions switches
# to the tag while building, which is a detached head
# Publishing is currently messy, because:
#
# * `peace_rt_model_core` exports `NativeError` or `WebError` depending on the target.
# * `peace_rt_model_web` fails to build when publishing the workspace for a native target.
# * `peace_rt_model_web` still needs its dependencies to be published before it can be
# published.
# * `peace_rt_model_hack` needs `peace_rt_model_web` to be published before it can be
# published.
#
# We *could* pass through `--no-verify` so `cargo` doesn't build the crate before publishing,
# which is reasonable, since this job only runs after the Linux, Windows, and WASM builds
# have passed.
- name: "cargo release publish"
run: |-
export PATH="$HOME/.osxcross/bin:$PATH"
cargo login ${{ secrets.CRATES_IO_API_TOKEN }}
cargo release \
publish \
--workspace \
--all-features \
--allow-branch "main" \
--no-confirm \
--no-verify \
--execute
- name: Store cache
uses: actions/cache/save@v4
with:
path: |
~/.cargo
key: cache-ubuntu-cargo-publish
+115
View File
@@ -0,0 +1,115 @@
name: CI
on: [workflow_dispatch]
permissions:
contents: read
jobs:
pypi_publish:
name: Publish (pypi.org)
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
- uses: actions/setup-python@v5
with:
python-version: 3.x
- name: Restore cache
uses: actions/cache/restore@v4
with:
path: |
~/.cache/pip
~/.cache/pip-wheel
~/.cache/sccache
~/.cache/cargo-xwin
~/.cargo
~/.osxcross
key: cache-ubuntu-maturin-cross-compile
- name: Install llvm
run: |
if ! command -v llvm-dlltool >/dev/null 2>&1; then
sudo apt update
sudo apt install -y llvm
fi
shell: bash
- name: Install Rust
run: |
export PATH="$HOME/.cargo/bin:$PATH"
if ! command -v rustc >/dev/null 2>&1; then
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y
else
rustup update
fi
shell: bash
- name: Install sccache and maturin
run: |
export PATH="$HOME/.cargo/bin:$PATH"
python -m pip install --upgrade pip
pip install maturin ziglang
if ! command -v sccache >/dev/null 2>&1; then
cargo install sccache || pip install sccache
fi
shell: bash
- name: Install xwin
run: |
export PATH="$HOME/.cargo/bin:$PATH"
if ! command -v cargo-xwin >/dev/null 2>&1; then
cargo install cargo-xwin || pip install cargo-xwin
cargo xwin cache xwin
fi
shell: bash
- name: Install osxcross
run: |
export PATH="$HOME/.osxcross/bin:$PATH"
if ! command -v osxcross >/dev/null 2>&1; then
wget ${{ secrets.OSXCROSS_LINK }} -O osxcross.tar.gz
tar -xzf osxcross.tar.gz -C ~/
mv ~/osxcross ~/.osxcross
fi
- name: Build wheels
run: |
export PATH="$HOME/.cargo/bin:$HOME/.osxcross/bin:$PATH"
rm -rf dist
maturin sdist --out dist -m ome-metadata/Cargo.toml
rustup default nightly
rustup target add x86_64-unknown-linux-gnu --toolchain nightly
maturin build --release --out ../dist --target x86_64-unknown-linux-gnu -m ome-metadata/Cargo.toml
rustup target add aarch64-unknown-linux-gnu --toolchain nightly
maturin build --release --out ../dist --target aarch64-unknown-linux-gnu --zig -m ome-metadata/Cargo.toml
rustup target add x86_64-pc-windows-msvc --toolchain nightly
maturin build --release --out dist --target x86_64-pc-windows-msvc -m ome-metadata/Cargo.toml
rustup target add aarch64-pc-windows-msvc --toolchain nightly
maturin build --release --out dist --target aarch64-pc-windows-msvc -m ome-metadata/Cargo.toml
rustup target add x86_64-apple-darwin --toolchain nightly
maturin build --release --out dist --target x86_64-apple-darwin --zig -m ome-metadata/Cargo.toml
rustup target add aarch64-apple-darwin --toolchain nightly
maturin build --release --out dist --target aarch64-apple-darwin --zig -m ome-metadata/Cargo.toml
- name: Store cache
uses: actions/cache/save@v4
with:
path: |
~/.cache/pip
~/.cache/pip-wheel
~/.cache/sccache
~/.cache/cargo-xwin
~/.cargo
~/.osxcross
key: cache-ubuntu-maturin-cross-compile
- name: Publish to PyPI
uses: pypa/gh-action-pypi-publish@release/v1
with:
password: ${{ secrets.PYPI_API_TOKEN }}
env:
GITHUB_WORKFLOW_REF: 1.10.1
+4 -2
View File
@@ -70,5 +70,7 @@ docs/_build/
# Pyenv
.python-version
/Cargo.lock
/tests/om/
Cargo.lock
target/
.agentbridge
+10 -28
View File
@@ -1,34 +1,16 @@
[package]
name = "ome-metadata"
version = "0.4.0"
[workspace]
resolver = "3"
members = ["ome-metadata", "ome-metadata-derive"]
[workspace.package]
version = "0.5.0"
edition = "2024"
rust-version = "1.85.1"
rust-version = "1.88.0"
authors = ["Wim Pomp <w.pomp@nki.nl>"]
license = "MIT"
license = "MIT OR Apache-2.0"
description = "Ome metadata as a rust/python structure."
homepage = "https://github.com/wimpomp/ome-metadata"
repository = "https://github.com/wimpomp/ome-metadata"
documentation = "https://docs.rs/ome-metadata"
homepage = "https://git.pomppervova.nl/wim/ome-metadata"
repository = "https://git.pomppervova.nl/wim/ome-metadata"
readme = "README.md"
keywords = ["bioformats", "imread", "ome", "metadata"]
categories = ["multimedia::images", "science"]
exclude = ["/tests"]
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[lib]
name = "ome_metadata"
crate-type = ["cdylib", "rlib"]
[dependencies]
enum-utils = "0.1"
serde = { version = "1", features = ["derive"] }
thiserror = "2"
quick-xml = { version = "0.38", features = ["serialize"] }
[dependencies.pyo3]
version = "0.27"
features = ["extension-module", "abi3-py310", "generate-import-lib", "anyhow"]
optional = true
[features]
python = ["dep:pyo3"]
-19
View File
@@ -1,19 +0,0 @@
Copyright (c) 2025 Wim Pomp
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+2 -2
View File
@@ -9,7 +9,7 @@ use ome_metadata::Ome;
let xml = read_to_string($file)?;
let ome: Ome = xml.parse()?;
let image = &ome.image.unwrap()[0];
let image = &ome.image[0];
println!("acquisition date: {:#?}", image.acquisition_date);
```
@@ -22,4 +22,4 @@ with open($file) as f:
ome = Ome.from_xml(xml)
image = ome.image[0]
print(f"acquisition date: {image.acquisition_date}")
```
```
+11
View File
@@ -0,0 +1,11 @@
[package]
name = "ome-metadata-derive"
version = "0.5.0"
edition = "2024"
[dependencies]
quote = "1"
syn = "2"
[lib]
proc-macro = true
+201
View File
@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+27
View File
@@ -0,0 +1,27 @@
Copyright (c) 2015 - 2021 Ulrik Sverdrup "bluss",
Jim Turner,
and ndarray developers
Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the
Software without restriction, including without
limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice
shall be included in all copies or substantial portions
of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
+1
View File
@@ -0,0 +1 @@
# Derive macros for ome-metadata
+297
View File
@@ -0,0 +1,297 @@
use proc_macro::TokenStream;
use quote::quote;
use syn::{Data, DeriveInput, Fields, Visibility, parse_macro_input};
#[proc_macro_derive(OmeXML)]
pub fn ome_metadata_derive_xml(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
let ident = input.ident;
let expanded = quote! {
impl #ident {
pub fn from_xml<T: AsRef<str>>(s: T) -> Result<Self, Error> {
Ok(from_str(s.as_ref())?)
}
pub fn to_xml(&self) -> Result<String, Error> {
Ok(to_string(self)?)
}
}
};
TokenStream::from(expanded)
}
#[proc_macro_derive(PyOmeComplexEnum)]
pub fn ome_metadata_derive_complex_enum(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
let ident = input.ident;
let mut variants = Vec::new();
match input.data {
Data::Enum(s) => {
for variant in &s.variants {
let variant_ident = &variant.ident;
variants.push(quote! {
Self::#variant_ident(v) => v.clone().into_bound_py_any(py)?,
});
}
}
_ => {
return syn::Error::new_spanned(ident, "PyOmeComplexEnum only supports structs")
.to_compile_error()
.into();
}
};
let expanded = quote! {
impl PyDisplay for #ident {
fn py_str(&self) -> String {
format!("{:?}", self)
}
}
#[pyo3::prelude::pymethods]
impl #ident {
/// all possible variants of this enum that can be constructed or converted into
#[staticmethod]
fn variants() -> Vec<String> {
Self::VARIANTS.iter().map(|v| v.trim_matches('"').to_string()).collect()
}
fn __repr__(&self) -> String {
self.py_str()
}
fn __str__(&self) -> String {
self.py_str()
}
fn __getnewargs__<'py>(&self, py: Python<'py>) -> PyResult<(Bound<'py, PyAny>,)> {
Ok((match self { #(#variants)* },))
}
#[staticmethod]
#[pyo3(name = "from_xml")]
fn py_from_xml(xml: &str) -> PyResult<Self> {
Ok(Self::from_xml(xml)?)
}
#[pyo3(name = "to_xml")]
fn py_to_xml(&self) -> PyResult<String> {
Ok(self.to_xml()?)
}
}
};
TokenStream::from(expanded)
}
#[proc_macro_derive(PyOmeEnum)]
pub fn ome_metadata_derive_enum(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
let name = input.ident;
let expanded = quote! {
impl PyDisplay for #name {
fn py_str(&self) -> String {
format!("{}", self)
}
}
#[pyo3::prelude::pymethods]
impl #name {
#[new]
fn new(unit: &str) -> PyResult<Self> {
unit.parse().map_err(|_| PyErr::new::<pyo3::exceptions::PyValueError, _>(format!("could not parse {}", unit)))
}
/// all possible variants of this enum that can be constructed or converted into
#[staticmethod]
fn variants() -> Vec<String> {
Self::VARIANTS.iter().map(|v| v.trim_matches('"').to_string()).collect()
}
fn __repr__(&self) -> String {
self.py_str()
}
fn __str__(&self) -> String {
self.py_str()
}
fn __getnewargs__(&self) -> (String,) {
(format!("{}", self),)
}
#[staticmethod]
#[pyo3(name = "from_xml")]
fn py_from_xml(xml: &str) -> PyResult<Self> {
Ok(Self::from_xml(xml)?)
}
#[pyo3(name = "to_xml")]
fn py_to_xml(&self) -> PyResult<String> {
Ok(self.to_xml()?)
}
}
};
TokenStream::from(expanded)
}
#[proc_macro_derive(PyOmeUnit)]
pub fn ome_metadata_derive_unit(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
let name = input.ident;
let expanded = quote! {
impl PyDisplay for #name {
fn py_str(&self) -> String {
format!("{}", self)
}
}
#[pyo3::prelude::pymethods]
impl #name {
#[new]
fn new(unit: &str) -> PyResult<Self> {
unit.parse().map_err(|_| PyErr::new::<pyo3::exceptions::PyValueError, _>(format!("could not parse {}", unit)))
}
/// convert a value between units
#[pyo3(name = "convert")]
fn py_convert(&self, unit: &Self, value: f64) -> PyResult<f64> {
Ok(self.convert(unit, value)?)
}
/// all possible variants of this enum that can be constructed or converted into
#[staticmethod]
fn variants() -> Vec<String> {
Self::VARIANTS.iter().map(|v| v.trim_matches('"').to_string()).collect()
}
fn __repr__(&self) -> String {
self.py_str()
}
fn __str__(&self) -> String {
self.py_str()
}
fn __getnewargs__(&self) -> (String,) {
(format!("{}", self),)
}
#[staticmethod]
#[pyo3(name = "from_xml")]
fn py_from_xml(xml: &str) -> PyResult<Self> {
Ok(Self::from_xml(xml)?)
}
#[pyo3(name = "to_xml")]
fn py_to_xml(&self) -> PyResult<String> {
Ok(self.to_xml()?)
}
}
};
TokenStream::from(expanded)
}
#[proc_macro_derive(PyOme)]
pub fn ome_metadata_derive(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
let name = input.ident;
// Only support named structs
let fields = match input.data {
Data::Struct(s) => match s.fields {
Fields::Named(named) => named.named,
_ => {
return syn::Error::new_spanned(name, "PyOme only supports named structs")
.to_compile_error()
.into();
}
},
_ => {
return syn::Error::new_spanned(name, "PyOme only supports structs")
.to_compile_error()
.into();
}
};
let mut idents = Vec::new();
let mut types = Vec::new();
let mut f = Vec::new();
let mut ps = Vec::new();
let mut new_kwargs = Vec::new();
let mut s = Vec::new();
for field in fields.iter() {
let ty = &field.ty;
if let Some(ident) = &field.ident
&& let Visibility::Public(_) = field.vis
{
let tmp = ident.to_string();
let field_name = tmp.trim_start_matches("r#");
idents.push(quote! {
self.#ident
});
types.push(quote! { #ty });
f.push(quote! {
pub #ident: #ty
});
ps.push(quote! {
self.#ident.py_str()
});
new_kwargs.push(quote! {
(#field_name, self.#ident.clone().into_bound_py_any(py)?)
});
s.push(format!("{}: {{}}", field_name));
} else {
return syn::Error::new_spanned(field, "PyOme type only supports public named fields")
.to_compile_error()
.into();
}
}
let fmt = format!("{}({})", name, s.join(", "));
// Generate the token stream
let expanded = quote! {
impl PyDisplay for #name {
fn py_str(&self) -> String {
format!(#fmt, #(#ps,)*)
}
}
#[pyo3::prelude::pymethods]
impl #name {
fn __getnewargs_ex__<'py>(&self, py: Python<'py>) -> PyResult<((), std::collections::HashMap<&str, Bound<'py, PyAny>>)> {
Ok(((), std::collections::HashMap::from_iter([#(#new_kwargs,)*])))
}
fn __repr__(&self) -> String {
self.py_str()
}
fn __str__(&self) -> String {
self.py_str()
}
#[staticmethod]
#[pyo3(name = "from_xml")]
fn py_from_xml(xml: &str) -> PyResult<Self> {
Ok(Self::from_xml(xml)?)
}
#[pyo3(name = "to_xml")]
fn py_to_xml(&self) -> PyResult<String> {
Ok(self.to_xml()?)
}
}
};
TokenStream::from(expanded)
}
+32
View File
@@ -0,0 +1,32 @@
[package]
name = "ome-metadata"
version = "0.5.0"
edition = "2024"
rust-version = "1.88.0"
authors = ["Wim Pomp <w.pomp@nki.nl>"]
license = "MIT OR Apache-2.0"
description = "Ome metadata as a rust/python structure."
homepage = "https://git.pomppervova.nl/wim/ome-metadata"
repository = "https://git.pomppervova.nl/wim/ome-metadata"
documentation = "https://docs.rs/ome-metadata"
readme = "README.md"
keywords = ["bioformats", "imread", "ome", "metadata"]
categories = ["multimedia::images", "science"]
exclude = ["/tests"]
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[lib]
name = "ome_metadata"
crate-type = ["cdylib", "rlib"]
[dependencies]
color-eyre = { version = "0.6", optional = true }
ome-metadata-derive = { path = "../ome-metadata-derive" }
pyo3 = { version = "0.29", features = ["abi3-py310", "anyhow", "eyre", "generate-import-lib"], optional = true}
quick-xml = { version = "0.40", features = ["serialize"] }
serde = { version = "1", features = ["derive"] }
strum = { version = "0.28", features = ["derive"] }
thiserror = "2"
[features]
python = ["dep:pyo3", "dep:color-eyre"]
+201
View File
@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+27
View File
@@ -0,0 +1,27 @@
Copyright (c) 2015 - 2021 Ulrik Sverdrup "bluss",
Jim Turner,
and ndarray developers
Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the
Software without restriction, including without
limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice
shall be included in all copies or substantial portions
of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
+25
View File
@@ -0,0 +1,25 @@
# ome-metadata
Open Microscopy XML metadata (https://www.openmicroscopy.org/Schemas/) as a collection of Rust structs and enums, with translation to Python.
## Rust
```
use std::fs::read_to_string;
use ome_metadata::Ome;
let xml = read_to_string($file)?;
let ome: Ome = xml.parse()?;
let image = &ome.image[0];
println!("acquisition date: {:#?}", image.acquisition_date);
```
## Python
```
from ome_metadata import Ome
with open($file) as f:
xml = f.read()
ome = Ome.from_xml(xml)
image = ome.image[0]
print(f"acquisition date: {image.acquisition_date}")
```
View File
+33
View File
@@ -0,0 +1,33 @@
[build-system]
requires = ["maturin>=1.9.4,<2.0"]
build-backend = "maturin"
[project]
name = "ome-metadata"
requires-python = ">=3.10"
classifiers = [
"License :: OSI Approved :: MIT License",
"License :: OSI Approved :: Apache Software License",
"Programming Language :: Rust",
"Programming Language :: Python",
"Programming Language :: Python :: 3",
]
dynamic = [
"version",
"description",
"readme",
"license",
"license-files",
"authors",
"maintainers",
"keywords",
"urls",
]
[tool.maturin]
features = ["python"]
module-name = "ome_metadata"
strip = true
[tool.isort]
line_length = 119
+3 -1
View File
@@ -5,7 +5,9 @@ pub enum Error {
#[error(transparent)]
IO(#[from] std::io::Error),
#[error(transparent)]
SerdeXml(#[from] quick_xml::DeError),
XmlDe(#[from] quick_xml::DeError),
#[error(transparent)]
XmlSe(#[from] quick_xml::SeError),
#[error("size of {0} is unknown")]
SizeOfUnknown(String),
#[error("no conversion to K by multiplication only")]
+5 -14
View File
@@ -3,24 +3,14 @@ pub mod ome;
pub mod error;
#[cfg(feature = "python")]
mod py;
pub mod py;
use crate::error::Error;
pub use ome::Ome;
use quick_xml::de::from_str;
use std::str::FromStr;
impl FromStr for Ome {
type Err = Error;
fn from_str(s: &str) -> Result<Self, Error> {
Ok(from_str(s)?)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::Ome;
use crate::error::Error;
use std::fs::read_to_string;
macro_rules! test_read {
@@ -29,7 +19,8 @@ mod tests {
#[test]
fn $name() -> Result<(), Error> {
let file = read_to_string(format!("tests/{}.xml", $file))?;
let _ome: Ome = file.parse()?;
let ome = Ome::from_xml(file)?;
let _xml = ome.to_xml()?;
Ok(())
}
)*
File diff suppressed because it is too large Load Diff
+487
View File
@@ -0,0 +1,487 @@
use crate::error::Error;
use crate::ome::{ExperimentType, MetadataOnly, MicrobeamManipulationType, XmlAnnotationValue};
use pyo3::prelude::*;
use pyo3::types::PyTuple;
impl From<crate::error::Error> for PyErr {
fn from(err: crate::error::Error) -> PyErr {
color_eyre::eyre::Report::from(err).into()
}
}
pub(crate) trait PyDisplay {
fn py_str(&self) -> String;
}
impl PyDisplay for String {
fn py_str(&self) -> String {
self.clone()
}
}
impl PyDisplay for bool {
fn py_str(&self) -> String {
self.to_string()
}
}
impl PyDisplay for i32 {
fn py_str(&self) -> String {
self.to_string()
}
}
impl PyDisplay for i64 {
fn py_str(&self) -> String {
self.to_string()
}
}
impl PyDisplay for f32 {
fn py_str(&self) -> String {
self.to_string()
}
}
impl PyDisplay for f64 {
fn py_str(&self) -> String {
self.to_string()
}
}
impl<T> PyDisplay for Option<T>
where
T: PyDisplay,
{
fn py_str(&self) -> String {
if let Some(val) = self {
val.py_str()
} else {
"None".to_string()
}
}
}
impl<T> PyDisplay for Vec<T>
where
T: PyDisplay,
{
fn py_str(&self) -> String {
format!(
"[{}]",
self.iter()
.map(|x| x.py_str())
.collect::<Vec<_>>()
.join(", ")
)
}
}
impl PyDisplay for MetadataOnly {
fn py_str(&self) -> String {
"MetadataOnly".into()
}
}
impl<'a, 'py> FromPyObject<'a, 'py> for MetadataOnly {
type Error = Error;
fn extract(_obj: Borrowed<'a, 'py, PyAny>) -> Result<Self, Self::Error> {
Ok(Self {})
}
}
impl PyDisplay for MicrobeamManipulationType {
fn py_str(&self) -> String {
format!(
"[{}]",
self.0
.iter()
.map(|i| i.py_str())
.collect::<Vec<_>>()
.join(", ")
)
}
}
impl<'a, 'py> FromPyObject<'a, 'py> for XmlAnnotationValue {
type Error = Error;
fn extract(_obj: Borrowed<'a, 'py, PyAny>) -> Result<Self, Self::Error> {
Ok(Self {})
}
}
impl PyDisplay for XmlAnnotationValue {
fn py_str(&self) -> String {
"XmlAnnotationValue".to_string()
}
}
impl PyDisplay for ExperimentType {
fn py_str(&self) -> String {
format!(
"[{}]",
self.0
.iter()
.map(|i| i.py_str())
.collect::<Vec<_>>()
.join(", ")
)
}
}
#[pymethods]
impl MetadataOnly {
fn __getnewargs__<'py>(&self, py: Python<'py>) -> Bound<'py, PyTuple> {
PyTuple::empty(py)
}
fn __repr__(&self) -> String {
"MetadataOnly".into()
}
fn __str__(&self) -> String {
"MetadataOnly".into()
}
}
#[pyfunction]
fn parse_ome(text: &str) -> PyResult<crate::Ome> {
Ok(crate::ome::Ome::from_xml(text)?)
}
#[pyfunction]
fn to_xml(ome: crate::ome::Ome) -> PyResult<String> {
Ok(ome.to_xml()?)
}
#[pymodule]
#[pyo3(name = "ome_metadata")]
pub mod ome_metadata {
use pyo3::prelude::*;
#[pymodule_export]
use super::parse_ome;
#[pymodule_export]
use super::to_xml;
#[pymodule_export]
use crate::ome::AffineTransform;
#[pymodule_export]
use crate::ome::Annotation;
#[pymodule_export]
use crate::ome::AnnotationRef;
#[pymodule_export]
use crate::ome::Arc;
#[pymodule_export]
use crate::ome::BinData;
#[pymodule_export]
use crate::ome::BinaryFile;
#[pymodule_export]
use crate::ome::BooleanAnnotation;
#[pymodule_export]
use crate::ome::Channel;
#[pymodule_export]
use crate::ome::CommentAnnotation;
#[pymodule_export]
use crate::ome::Dataset;
#[pymodule_export]
use crate::ome::Detector;
#[pymodule_export]
use crate::ome::DetectorSettings;
#[pymodule_export]
use crate::ome::Dichroic;
#[pymodule_export]
use crate::ome::DoubleAnnotation;
#[pymodule_export]
use crate::ome::Ellipse;
#[pymodule_export]
use crate::ome::Experiment;
#[pymodule_export]
use crate::ome::ExperimentType;
#[pymodule_export]
use crate::ome::Experimenter;
#[pymodule_export]
use crate::ome::ExperimenterGroup;
#[pymodule_export]
use crate::ome::External;
#[pymodule_export]
use crate::ome::Filament;
#[pymodule_export]
use crate::ome::FileAnnotation;
#[pymodule_export]
use crate::ome::Filter;
#[pymodule_export]
use crate::ome::FilterSet;
#[pymodule_export]
use crate::ome::Folder;
#[pymodule_export]
use crate::ome::GenericExcitationSource;
#[pymodule_export]
use crate::ome::Image;
#[pymodule_export]
use crate::ome::ImagingEnvironment;
#[pymodule_export]
use crate::ome::Instrument;
#[pymodule_export]
use crate::ome::Label;
#[pymodule_export]
use crate::ome::Laser;
#[pymodule_export]
use crate::ome::LightEmittingDiode;
#[pymodule_export]
use crate::ome::LightPath;
#[pymodule_export]
use crate::ome::LightSourceType;
#[pymodule_export]
use crate::ome::LightSourceSettings;
#[pymodule_export]
use crate::ome::Line;
#[pymodule_export]
use crate::ome::LongAnnotation;
#[pymodule_export]
use crate::ome::MapType;
#[pymodule_export]
use crate::ome::MapAnnotation;
#[pymodule_export]
use crate::ome::MapM;
#[pymodule_export]
use crate::ome::Mask;
#[pymodule_export]
use crate::ome::MetadataOnly;
#[pymodule_export]
use crate::ome::MicrobeamManipulation;
#[pymodule_export]
use crate::ome::MicrobeamManipulationType;
#[pymodule_export]
use crate::ome::Microscope;
#[pymodule_export]
use crate::ome::Ome;
#[pymodule_export]
use crate::ome::Objective;
#[pymodule_export]
use crate::ome::ObjectiveSettings;
#[pymodule_export]
use crate::ome::OmeBinaryOnly;
#[pymodule_export]
use crate::ome::Pixels;
#[pymodule_export]
use crate::ome::Plane;
#[pymodule_export]
use crate::ome::Plate;
#[pymodule_export]
use crate::ome::PlateAcquisition;
#[pymodule_export]
use crate::ome::Polygon;
#[pymodule_export]
use crate::ome::Polyline;
#[pymodule_export]
use crate::ome::Project;
#[pymodule_export]
use crate::ome::Roi;
#[pymodule_export]
use crate::ome::Reagent;
#[pymodule_export]
use crate::ome::Rectangle;
#[pymodule_export]
use crate::ome::Rights;
#[pymodule_export]
use crate::ome::RoiUnion;
#[pymodule_export]
use crate::ome::Screen;
#[pymodule_export]
use crate::ome::ShapeType;
#[pymodule_export]
use crate::ome::StageLabel;
#[pymodule_export]
use crate::ome::StructuredAnnotations;
#[pymodule_export]
use crate::ome::TiffData;
#[pymodule_export]
use crate::ome::TiffDataUuid;
#[pymodule_export]
use crate::ome::TransmittanceRange;
#[pymodule_export]
use crate::ome::Well;
#[pymodule_export]
use crate::ome::WellSample;
#[pymodule_export]
use crate::ome::XmlAnnotation;
#[pymodule_export]
use crate::ome::XmlAnnotationValue;
#[pymodule_export]
use crate::ome::ArcType;
#[pymodule_export]
use crate::ome::BinDataCompressionType;
#[pymodule_export]
use crate::ome::BinaryFileContent;
#[pymodule_export]
use crate::ome::BinningType;
#[pymodule_export]
use crate::ome::ChannelAcquisitionModeType;
#[pymodule_export]
use crate::ome::ChannelContrastMethodType;
#[pymodule_export]
use crate::ome::ChannelIlluminationType;
#[pymodule_export]
use crate::ome::DetectorType;
#[pymodule_export]
use crate::ome::ExperimentItemType;
#[pymodule_export]
use crate::ome::FilamentType;
#[pymodule_export]
use crate::ome::FilterType;
#[pymodule_export]
use crate::ome::FontFamilyType;
#[pymodule_export]
use crate::ome::LaserLaserMediumType;
#[pymodule_export]
use crate::ome::LaserPulseType;
#[pymodule_export]
use crate::ome::LaserType;
#[pymodule_export]
use crate::ome::LightSourceGroup;
#[pymodule_export]
use crate::ome::MarkerType;
#[pymodule_export]
use crate::ome::MicrobeamManipulationItemType;
#[pymodule_export]
use crate::ome::MicroscopeType;
#[pymodule_export]
use crate::ome::NamingConventionType;
#[pymodule_export]
use crate::ome::ObjectiveCorrectionType;
#[pymodule_export]
use crate::ome::ObjectiveImmersionType;
#[pymodule_export]
use crate::ome::ObjectiveSettingsMediumType;
#[pymodule_export]
use crate::ome::PixelType;
#[pymodule_export]
use crate::ome::PixelsDimensionOrderType;
#[pymodule_export]
use crate::ome::ShapeFillRuleType;
#[pymodule_export]
use crate::ome::ShapeFontStyleType;
#[pymodule_export]
use crate::ome::ShapeGroup;
#[pymodule_export]
use crate::ome::StructuredAnnotationsContent;
#[pymodule_export]
use crate::ome::UnitsElectricPotential;
#[pymodule_export]
use crate::ome::UnitsFrequency;
#[pymodule_export]
use crate::ome::UnitsLength;
#[pymodule_export]
use crate::ome::UnitsPower;
#[pymodule_export]
use crate::ome::UnitsPressure;
#[pymodule_export]
use crate::ome::UnitsTemperature;
#[pymodule_export]
use crate::ome::UnitsTime;
#[pymodule_init]
fn init(_: &Bound<'_, PyModule>) -> PyResult<()> {
let _ = color_eyre::install();
Ok(())
}
}
-45
View File
@@ -1,45 +0,0 @@
from __future__ import annotations
from collections import UserDict, UserList
from . import ome_metadata_rs as rs # noqa
class Ome(UserDict):
@staticmethod
def from_xml(xml: str) -> Ome:
"""Create the OME structure from an XML string"""
new = Ome()
new.update(rs.ome(str(xml)))
return new
def __dir__(self) -> list[str]:
return list(self.keys()) + list(super().__dir__())
def __getattr__(self, key: str) -> Ome | OmeList | int | float | str:
try:
new = self.__getitem__(key)
except KeyError:
raise AttributeError(f"'Ome' object has no attribute '{key}'")
if isinstance(new, dict):
return Ome(**new)
elif isinstance(new, list):
return OmeList(new)
else:
return new
def __getstate__(self) -> dict[str, Any]:
return self.data
def __setstate__(self, state: dict[str, Any]) -> None:
self.data = state
class OmeList(UserList):
def __getitem__(self, item: int) -> Ome | OmeList | int | float | str:
new = super().__getitem__(item)
if isinstance(new, dict):
return Ome(**new)
elif isinstance(new, list):
return OmeList(new)
else:
return new
-32
View File
@@ -1,32 +0,0 @@
[build-system]
requires = ["maturin>=1.8,<2.0"]
build-backend = "maturin"
[project]
name = "ome-metadata"
keywords = ["bioformats", "imread", "ome", "metadata"]
requires-python = ">=3.10"
classifiers = [
"License :: OSI Approved :: MIT License",
"Programming Language :: Rust",
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3 :: Only",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
"Programming Language :: Python :: 3.13",
"Programming Language :: Python :: 3.14",
]
dynamic = ["version", "description", "authors", "license", "readme"]
[project.urls]
Repository = "https://github.com/wimpomp/ome-metadata"
[tool.maturin]
python-source = "py"
features = ["pyo3/extension-module", "python"]
module-name = "ome_metadata.ome_metadata_rs"
[tool.isort]
line_length = 119
-3022
View File
File diff suppressed because it is too large Load Diff
-99
View File
@@ -1,99 +0,0 @@
use crate::Ome;
use crate::ome::{
Convert, UnitsElectricPotential, UnitsFrequency, UnitsLength, UnitsPower, UnitsPressure,
UnitsTemperature, UnitsTime,
};
use pyo3::exceptions::PyValueError;
use pyo3::prelude::*;
impl From<crate::error::Error> for PyErr {
fn from(err: crate::error::Error) -> PyErr {
PyErr::new::<PyValueError, _>(err.to_string())
}
}
macro_rules! impl_enum_into_py_object {
($($s:ident: $t:ty $(,)?)*) => {
$(
#[pyclass(module = "ome_metadata.ome_metadata_rs")]
pub struct $s {
inner: $t,
}
#[pymethods]
impl $s {
#[new]
fn new(unit: &str) -> PyResult<Self> {
match unit.parse() {
Ok(unit) => Ok(Self { inner: unit }),
Err(_) => Err(PyErr::new::<PyValueError, _>(format!("Invalid unit: {}", unit)))
}
}
/// convert a value between units
fn convert(&self, unit: &str, value: f64) -> PyResult<f64> {
match unit.parse() {
Ok(unit) => Ok(self.inner.convert(&unit, value)?),
Err(_) => Err(PyErr::new::<PyValueError, _>(format!("Invalid unit: {}", unit)))
}
}
/// all possible variants of this enum that can be constructed or converted into
#[staticmethod]
fn variants() -> Vec<String> {
<$t>::variants().iter().map(|v| format!("{:?}", v)).collect()
}
fn __repr__(&self) -> String {
format!("{:?}", self.inner)
}
fn __str__(&self) -> String {
format!("{:?}", self.inner)
}
fn __getnewargs__(&self) -> (String,) {
(format!("{:?}", self.inner),)
}
}
impl<'py> IntoPyObject<'py> for $t {
type Target = $s;
type Output = Bound<'py, Self::Target>;
type Error = PyErr;
fn into_pyobject(self, py: Python<'py>) -> PyResult<Self::Output> {
Bound::new(py, $s { inner: self })
}
}
)*
};
}
impl_enum_into_py_object! {
ElectricPotential: UnitsElectricPotential
Frequency: UnitsFrequency
Length: UnitsLength
Power: UnitsPower
Pressure: UnitsPressure
Temperature: UnitsTemperature
Time: UnitsTime
}
#[pyfunction]
fn ome(text: &str) -> PyResult<Ome> {
Ok(text.parse()?)
}
#[pymodule]
#[pyo3(name = "ome_metadata_rs")]
fn ome_metadata_rs(m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_class::<ElectricPotential>()?;
m.add_class::<Frequency>()?;
m.add_class::<Length>()?;
m.add_class::<Power>()?;
m.add_class::<Pressure>()?;
m.add_class::<Temperature>()?;
m.add_class::<Time>()?;
m.add_function(wrap_pyfunction!(ome, m)?)?;
Ok(())
}