stam-python 0.12.1

STAM is a library for dealing with standoff annotations on text, this is the python binding.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
use pyo3::exceptions::PyValueError;
use pyo3::prelude::*;
use pyo3::pyclass::CompareOp;

use crate::annotation::PyAnnotation;
use crate::annotationdata::{PyAnnotationData, PyDataKey};
use crate::annotationdataset::PyAnnotationDataSet;
use crate::annotationstore::{MapStore, PyAnnotationStore};
use crate::resources::{PyOffset, PyTextResource};
use stam::*;

#[pyclass(dict, module = "stam", name = "SelectorKind")]
#[derive(Clone, PartialEq)]
pub struct PySelectorKind {
    pub(crate) kind: SelectorKind,
}

#[pymethods]
impl PySelectorKind {
    #[classattr]
    const RESOURCESELECTOR: PySelectorKind = PySelectorKind {
        kind: SelectorKind::ResourceSelector,
    };
    #[classattr]
    const ANNOTATIONSELECTOR: PySelectorKind = PySelectorKind {
        kind: SelectorKind::AnnotationSelector,
    };
    #[classattr]
    const TEXTSELECTOR: PySelectorKind = PySelectorKind {
        kind: SelectorKind::TextSelector,
    };
    #[classattr]
    const DATASETSELECTOR: PySelectorKind = PySelectorKind {
        kind: SelectorKind::DataSetSelector,
    };
    #[classattr]
    const MULTISELECTOR: PySelectorKind = PySelectorKind {
        kind: SelectorKind::MultiSelector,
    };
    #[classattr]
    const COMPOSITESELECTOR: PySelectorKind = PySelectorKind {
        kind: SelectorKind::CompositeSelector,
    };
    #[classattr]
    const DIRECTIONALSELECTOR: PySelectorKind = PySelectorKind {
        kind: SelectorKind::DirectionalSelector,
    };

    fn __richcmp__(&self, other: PyRef<Self>, op: CompareOp) -> bool {
        match op {
            CompareOp::Eq => *self == *other,
            CompareOp::Ne => *self != *other,
            _ => false,
        }
    }
}

#[pyclass(dict, module = "stam", name = "Selector")]
#[derive(Clone, PartialEq)]
/// This is the Python variant of SelectorBuilder, we can't just wrap SelectorBuiler itself because it has a lifetime
pub(crate) struct PySelector {
    pub(crate) kind: PySelectorKind,
    pub(crate) resource: Option<TextResourceHandle>,
    pub(crate) annotation: Option<AnnotationHandle>,
    pub(crate) dataset: Option<AnnotationDataSetHandle>,
    pub(crate) key: Option<(AnnotationDataSetHandle, DataKeyHandle)>,
    pub(crate) data: Option<(AnnotationDataSetHandle, AnnotationDataHandle)>,
    pub(crate) offset: Option<PyOffset>,
    pub(crate) subselectors: Vec<PySelector>,
}

impl PySelector {
    pub(crate) fn build(&self) -> SelectorBuilder<'_> {
        match self.kind.kind {
            SelectorKind::ResourceSelector => SelectorBuilder::ResourceSelector(
                self.resource
                    .expect("pyselector of type resourceselector must have resource, was checked on instantiation")
                    .into(),
            ),
            SelectorKind::TextSelector => SelectorBuilder::TextSelector(
                self.resource
                    .expect("pyselector of type textselector must have resource, was checked on instantiation")
                    .into(),
                self.offset.clone()
                    .expect("pyselector of type textselector must have offset, was checked on instantiation").offset
            ),
            SelectorKind::AnnotationSelector => SelectorBuilder::AnnotationSelector(
                self.annotation
                    .expect("pyselector of type annotationselector must have annotation, was checked on instantiation")
                    .into(),
                self.offset.clone().map(|offset| offset.offset)
            ),
            SelectorKind::DataSetSelector => SelectorBuilder::DataSetSelector(
                self.dataset
                    .expect("pyselector of type datasetselector must have dataset, was checked on instantiation")
                    .into(),
            ),
            SelectorKind::DataKeySelector => SelectorBuilder::DataKeySelector(
                self.key
                    .expect("pyselector of type datakeyselector must have key, was checked on instantiation")
                    .0
                    .into(),
                self.key
                    .expect("pyselector of type datakeyselector must have key, was checked on instantiation")
                    .1
                    .into(),
            ),
            SelectorKind::AnnotationDataSelector => SelectorBuilder::AnnotationDataSelector(
                self.data
                    .expect("pyselector of type annotationdataselector must have key, was checked on instantiation")
                    .0
                    .into(),
                self.data
                    .expect("pyselector of type annotationdataselector must have key, was checked on instantiation")
                    .1
                    .into(),
            ),
            SelectorKind::MultiSelector => {
                SelectorBuilder::MultiSelector(self.subselectors.iter().map(|subselector| subselector.build()).collect())
            }
            SelectorKind::CompositeSelector => {
                SelectorBuilder::CompositeSelector(self.subselectors.iter().map(|subselector| subselector.build()).collect())
            }
            SelectorKind::DirectionalSelector => {
                SelectorBuilder::DirectionalSelector(self.subselectors.iter().map(|subselector| subselector.build()).collect())
            }
            SelectorKind::InternalRangedSelector => unreachable!("internalrangedselector should never be passable from python")
        }
    }
}

#[pymethods]
impl PySelector {
    #[new]
    #[pyo3(signature = (kind, resource=None, annotation=None, dataset=None, key=None, data=None, offset=None, subselectors=Vec::new()))]
    fn new(
        kind: &PySelectorKind,
        resource: Option<PyRef<PyTextResource>>,
        annotation: Option<PyRef<PyAnnotation>>,
        dataset: Option<PyRef<PyAnnotationDataSet>>,
        key: Option<PyRef<PyDataKey>>,
        data: Option<PyRef<PyAnnotationData>>,
        offset: Option<PyRef<PyOffset>>,
        subselectors: Vec<PyRef<PySelector>>,
    ) -> PyResult<Self> {
        match kind.kind {
            SelectorKind::ResourceSelector => {
                if let Some(resource) = resource {
                    Ok(PySelector {
                        kind: kind.clone(),
                        resource: Some(resource.handle),
                        annotation: None,
                        dataset: None,
                        key: None,
                        data: None,
                        offset: None,
                        subselectors: Vec::new(),
                    })
                } else {
                    Err(PyValueError::new_err("'resource' keyword argument must be specified for ResourceSelector and point to a TextResource instance"))
                }
            }
            SelectorKind::AnnotationSelector => {
                if let Some(annotation) = annotation {
                    if let Some(offset) = offset {
                        Ok(PySelector {
                            kind: kind.clone(),
                            annotation: Some(annotation.handle),
                            resource: None,
                            dataset: None,
                            key: None,
                            data: None,
                            offset: Some(offset.clone()),
                            subselectors: Vec::new(),
                        })
                    } else {
                        Ok(PySelector {
                            kind: kind.clone(),
                            annotation: Some(annotation.handle),
                            resource: None,
                            dataset: None,
                            key: None,
                            data: None,
                            offset: None,
                            subselectors: Vec::new(),
                        })
                    }
                } else {
                    Err(PyValueError::new_err("'annotation' keyword argument must be specified for AnnotationSelector and point to a annotation instance"))
                }
            }
            SelectorKind::TextSelector => {
                if let Some(resource) = resource {
                    if let Some(offset) = offset {
                        Ok(PySelector {
                            kind: kind.clone(),
                            resource: Some(resource.handle),
                            annotation: None,
                            dataset: None,
                            key: None,
                            data: None,
                            offset: Some(offset.clone()),
                            subselectors: Vec::new(),
                        })
                    } else {
                        Err(PyValueError::new_err("'offset' keyword argument must be specified for TextSelector and point to a Offset instance"))
                    }
                } else {
                    Err(PyValueError::new_err("'resource' keyword argument must be specified for TextSelector and point to a TextResource instance"))
                }
            }
            SelectorKind::DataSetSelector => {
                if let Some(dataset) = dataset {
                    Ok(PySelector {
                        kind: kind.clone(),
                        resource: None,
                        annotation: None,
                        dataset: Some(dataset.handle),
                        key: None,
                        data: None,
                        offset: None,
                        subselectors: Vec::new(),
                    })
                } else {
                    Err(PyValueError::new_err("'dataset' keyword argument must be specified for DataSetSelector and point to an AnnotationDataSet instance"))
                }
            }
            SelectorKind::DataKeySelector => {
                if let Some(key) = key {
                    Ok(PySelector {
                        kind: kind.clone(),
                        resource: None,
                        annotation: None,
                        dataset: None,
                        key: Some((key.set, key.handle)),
                        data: None,
                        offset: None,
                        subselectors: Vec::new(),
                    })
                } else {
                    Err(PyValueError::new_err("'key' keyword argument must be specified for DataKeySelector and point to a DataKey instance"))
                }
            }
            SelectorKind::AnnotationDataSelector => {
                if let Some(data) = data {
                    Ok(PySelector {
                        kind: kind.clone(),
                        resource: None,
                        annotation: None,
                        dataset: None,
                        data: Some((data.set, data.handle)),
                        key: None,
                        offset: None,
                        subselectors: Vec::new(),
                    })
                } else {
                    Err(PyValueError::new_err("'key' keyword argument must be specified for DataKeySelector and point to a DataKey instance"))
                }
            }
            SelectorKind::MultiSelector
            | SelectorKind::CompositeSelector
            | SelectorKind::DirectionalSelector => {
                if subselectors.is_empty() {
                    Err(PyValueError::new_err("'subselectors' keyword argument must be specified for MultiSelector/CompositeSelector/DirectionalSelector and point to a list of Selector instances"))
                } else {
                    Ok(PySelector {
                        kind: kind.clone(),
                        resource: None,
                        annotation: None,
                        dataset: None,
                        key: None,
                        data: None,
                        offset: None,
                        subselectors: subselectors.into_iter().map(|sel| sel.clone()).collect(),
                    })
                }
            }
            SelectorKind::InternalRangedSelector => Err(PyValueError::new_err(
                "Construction of InternalRangedSelector not allowed",
            )),
        }
    }

    #[staticmethod]
    /// Shortcut static method to construct a TextSelector
    fn textselector(resource: PyRef<PyTextResource>, offset: PyRef<PyOffset>) -> PyResult<Self> {
        PySelector::new(
            &PySelectorKind::TEXTSELECTOR,
            Some(resource),
            None,
            None,
            None,
            None,
            Some(offset),
            Vec::new(),
        )
    }

    #[staticmethod]
    /// Shortcut static method to construct a AnnotationSelector
    #[pyo3(signature = (annotation, offset=None))]
    fn annotationselector(
        annotation: PyRef<PyAnnotation>,
        offset: Option<PyRef<PyOffset>>,
    ) -> PyResult<Self> {
        PySelector::new(
            &PySelectorKind::ANNOTATIONSELECTOR,
            None,
            Some(annotation),
            None,
            None,
            None,
            offset,
            Vec::new(),
        )
    }

    #[staticmethod]
    /// Shortcut static method to construct a ResourceSelector
    fn resourceselector(resource: PyRef<PyTextResource>) -> PyResult<Self> {
        PySelector::new(
            &PySelectorKind::RESOURCESELECTOR,
            Some(resource),
            None,
            None,
            None,
            None,
            None,
            Vec::new(),
        )
    }

    #[staticmethod]
    /// Shortcut static method to construct a DataSetSelector
    fn datasetselector(annotationset: PyRef<PyAnnotationDataSet>) -> PyResult<Self> {
        PySelector::new(
            &PySelectorKind::DATASETSELECTOR,
            None,
            None,
            Some(annotationset),
            None,
            None,
            None,
            Vec::new(),
        )
    }

    #[staticmethod]
    /// Shortcut static method to construct a MultiSelector
    #[pyo3(signature = (*subselectors))]
    fn multiselector(subselectors: Vec<PyRef<PySelector>>) -> PyResult<Self> {
        PySelector::new(
            &PySelectorKind::MULTISELECTOR,
            None,
            None,
            None,
            None,
            None,
            None,
            subselectors,
        )
    }

    #[staticmethod]
    /// Shortcut static method to construct a CompositeSelector
    #[pyo3(signature = (*subselectors))]
    fn compositeselector(subselectors: Vec<PyRef<PySelector>>) -> PyResult<Self> {
        PySelector::new(
            &PySelectorKind::COMPOSITESELECTOR,
            None,
            None,
            None,
            None,
            None,
            None,
            subselectors,
        )
    }

    #[staticmethod]
    /// Shortcut static method to construct a DirectionalSelector
    #[pyo3(signature = (*subselectors))]
    fn directionalselector(subselectors: Vec<PyRef<PySelector>>) -> PyResult<Self> {
        PySelector::new(
            &PySelectorKind::DIRECTIONALSELECTOR,
            None,
            None,
            None,
            None,
            None,
            None,
            subselectors,
        )
    }

    /// Returns the selector kind, use is_kind() instead if you want to test
    fn kind(&self) -> PySelectorKind {
        self.kind.clone()
    }

    fn is_kind(&self, kind: &PySelectorKind) -> bool {
        self.kind.kind == kind.kind
    }

    /// Quicker test for specified selector kind
    fn is_resourceselector(&self) -> bool {
        self.kind.kind == SelectorKind::ResourceSelector
    }

    /// Quicker test for specified selector kind
    fn is_textselector(&self) -> bool {
        self.kind.kind == SelectorKind::TextSelector
    }

    /// Quicker test for specified selector kind
    fn is_annotationselector(&self) -> bool {
        self.kind.kind == SelectorKind::AnnotationSelector
    }

    /// Quicker test for specified selector kind
    fn is_datasetselector(&self) -> bool {
        self.kind.kind == SelectorKind::DataSetSelector
    }

    /// Quicker test for specified selector kind
    fn is_multiselector(&self) -> bool {
        self.kind.kind == SelectorKind::MultiSelector
    }

    /// Quicker test for specified selector kind
    fn is_directionalselector(&self) -> bool {
        self.kind.kind == SelectorKind::DirectionalSelector
    }

    /// Quicker test for specified selector kind
    fn is_compositeselector(&self) -> bool {
        self.kind.kind == SelectorKind::CompositeSelector
    }

    /// Return offset information in the selector.
    /// Works for TextSelector and AnnotationSelector, returns None for others.
    fn offset(&self) -> PyResult<Option<PyOffset>> {
        Ok(self.offset.clone())
    }

    /// Returns the resource this selector points at, if any.
    /// Works only for TextSelector and ResourceSelector, returns None otherwise.
    /// Requires to explicitly pass the store so the resource can be found.
    fn resource(&self, store: PyRef<PyAnnotationStore>) -> Option<PyTextResource> {
        self.resource.map(|resource_handle| PyTextResource {
            handle: resource_handle,
            store: store.get_store().clone(),
        })
    }

    /// Returns the key this selector points at, if any.
    /// Works only for DataKeySelector, returns None otherwise.
    /// Requires to explicitly pass the store so the resource can be found.
    fn key(&self, store: PyRef<PyAnnotationStore>) -> Option<PyDataKey> {
        self.key.map(|(set_handle, key_handle)| PyDataKey {
            set: set_handle,
            handle: key_handle,
            store: store.get_store().clone(),
        })
    }

    /// Returns the annotationdata this selector points at, if any.
    /// Works only for AnnotationDataSelector, returns None otherwise.
    /// Requires to explicitly pass the store so the resource can be found.
    fn annotationdata(&self, store: PyRef<PyAnnotationStore>) -> Option<PyAnnotationData> {
        self.data.map(|(set_handle, data_handle)| PyAnnotationData {
            set: set_handle,
            handle: data_handle,
            store: store.get_store().clone(),
        })
    }

    /// Returns the annotation this selector points at, if any.
    /// Works only for AnnotationSelector, returns None otherwise.
    /// Requires to explicitly pass the store so the resource can be found.
    fn annotation(&self, store: PyRef<PyAnnotationStore>) -> Option<PyAnnotation> {
        self.annotation.map(|annotation_handle| PyAnnotation {
            handle: annotation_handle,
            store: store.get_store().clone(),
        })
    }

    /// Returns the annotation dataset this selector points at, ff any.
    /// Works only for DataSetSelector, returns None otherwise.
    /// Requires to explicitly pass the store so the dataset can be found.
    fn dataset(&self, store: PyRef<PyAnnotationStore>) -> Option<PyAnnotationDataSet> {
        self.dataset.map(|dataset_handle| PyAnnotationDataSet {
            handle: dataset_handle,
            store: store.get_store().clone(),
        })
    }

    fn __richcmp__(&self, other: PyRef<Self>, op: CompareOp) -> bool {
        match op {
            CompareOp::Eq => *self == *other,
            CompareOp::Ne => *self != *other,
            _ => false,
        }
    }
}

impl PySelector {
    pub(crate) fn from_selector(selector: &Selector, store: &AnnotationStore) -> Self {
        Self {
            kind: PySelectorKind {
                kind: selector.kind(),
            },
            resource: match selector {
                Selector::TextSelector(res_id, ..)
                | Selector::ResourceSelector(res_id)
                | Selector::AnnotationSelector(_, Some((res_id, _, _))) => Some(*res_id),
                _ => None,
            },
            dataset: match selector {
                Selector::DataSetSelector(set_id) => Some(*set_id),
                _ => None,
            },
            annotation: match selector {
                Selector::AnnotationSelector(a_id, ..) => Some(*a_id),
                _ => None,
            },
            key: match selector {
                Selector::DataKeySelector(set_id, key_id) => Some((*set_id, *key_id)),
                _ => None,
            },
            data: match selector {
                Selector::AnnotationDataSelector(set_id, data_id) => Some((*set_id, *data_id)),
                _ => None,
            },
            offset: selector.offset(store).map(|offset| PyOffset { offset }),
            subselectors: if selector.is_complex() {
                if let Some(subselectors) = selector.subselectors() {
                    subselectors
                        .into_iter()
                        .map(|x| Self::from_selector(x, store))
                        .collect()
                } else {
                    Vec::new()
                }
            } else {
                Vec::new()
            },
        }
    }
}