use numpy::{PyArray2, ToPyArray};
use pyo3::prelude::*;
use pyo3_stub_gen::derive::*;
use crate::batch::{Batch, BatchBuilder, PaddingStrategy};
use crate::seq::SequenceRecord;
#[gen_stub_pyclass]
#[pyclass(name = "Batch", module = "deepbiop.core")]
pub struct PyBatch {
batch: Batch,
}
#[pymethods]
impl PyBatch {
#[getter]
fn ids(&self) -> Vec<String> {
self.batch.ids.clone()
}
#[getter]
fn sequences<'py>(&self, py: Python<'py>) -> Bound<'py, PyArray2<u8>> {
self.batch.sequences.to_pyarray(py)
}
#[getter]
fn quality_scores<'py>(&self, py: Python<'py>) -> Option<Bound<'py, PyArray2<u8>>> {
self.batch.quality_scores.as_ref().map(|q| q.to_pyarray(py))
}
#[getter]
fn attention_mask<'py>(&self, py: Python<'py>) -> Bound<'py, PyArray2<u8>> {
self.batch.attention_mask.to_pyarray(py)
}
#[getter]
fn lengths(&self) -> Vec<usize> {
self.batch.lengths.clone()
}
#[pyo3(name = "__len__")]
fn len(&self) -> usize {
self.batch.size()
}
fn max_length(&self) -> usize {
self.batch.max_length()
}
#[pyo3(name = "__repr__")]
fn repr(&self) -> String {
format!(
"Batch(size={}, max_length={}, has_quality={})",
self.batch.size(),
self.batch.max_length(),
self.batch.quality_scores.is_some()
)
}
}
#[gen_stub_pyfunction(module = "deepbiop.core")]
#[pyfunction]
#[pyo3(signature = (records, padding="longest", max_length=None, pad_value=0, truncate=false))]
fn collate_batch(
records: Vec<SequenceRecord>,
padding: &str,
max_length: Option<usize>,
pad_value: u8,
truncate: bool,
) -> PyResult<PyBatch> {
let strategy = match padding {
"longest" => PaddingStrategy::Longest,
"fixed" => {
let len = max_length.ok_or_else(|| {
pyo3::exceptions::PyValueError::new_err(
"max_length must be specified for fixed padding",
)
})?;
PaddingStrategy::Fixed { length: len }
}
"bucketed" => {
PaddingStrategy::Bucketed {
boundaries: vec![100, 200, 500, 1000],
}
}
_ => {
return Err(pyo3::exceptions::PyValueError::new_err(format!(
"Unknown padding strategy: {}. Use 'longest', 'fixed', or 'bucketed'",
padding
)))
}
};
let batch = BatchBuilder::new()
.padding_strategy(strategy)
.pad_value(pad_value)
.truncate(truncate)
.build(&records)
.map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))?;
Ok(PyBatch { batch })
}
pub(crate) fn register_dataset_functions(module: &Bound<'_, PyModule>) -> PyResult<()> {
module.add_class::<PyBatch>()?;
module.add_function(wrap_pyfunction!(collate_batch, module)?)?;
Ok(())
}