lindera-python 4.0.0

A Python binding for Lindera.
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
//! Dictionary schema definitions.
//!
//! This module provides schema structures that define the format and fields
//! of dictionary entries. The field-management logic is delegated to
//! [`lindera_binding_core::CoreSchema`]; this module only adds the PyO3 wrappers.
//!
//! # Examples
//!
//! ```python
//! # Create a custom schema
//! schema = lindera.Schema([
//!     "surface",
//!     "left_context_id",
//!     "right_context_id",
//!     "cost",
//!     "part_of_speech"
//! ])
//!
//! # Use default schema
//! schema = lindera.Schema.create_default()
//!
//! # Access field information
//! index = schema.get_field_index("surface")
//! field = schema.get_field_by_name("part_of_speech")
//! ```

use pyo3::prelude::*;

use lindera::dictionary::{FieldDefinition, FieldType, Schema};
use lindera_binding_core::{CoreFieldDefinition, CoreFieldType, CoreSchema};

use crate::error::to_py_error;

/// Field type in dictionary schema.
///
/// Defines the type of a field in the dictionary entry.
#[pyclass(name = "FieldType", from_py_object)]
#[derive(Debug, Clone)]
pub enum PyFieldType {
    /// Surface form (word text)
    Surface,
    /// Left context ID for morphological analysis
    LeftContextId,
    /// Right context ID for morphological analysis
    RightContextId,
    /// Word cost (used in path selection)
    Cost,
    /// Custom field (morphological features)
    Custom,
}

#[pymethods]
impl PyFieldType {
    fn __str__(&self) -> &str {
        match self {
            PyFieldType::Surface => "surface",
            PyFieldType::LeftContextId => "left_context_id",
            PyFieldType::RightContextId => "right_context_id",
            PyFieldType::Cost => "cost",
            PyFieldType::Custom => "custom",
        }
    }

    fn __repr__(&self) -> String {
        format!("FieldType.{self:?}")
    }
}

impl From<CoreFieldType> for PyFieldType {
    fn from(field_type: CoreFieldType) -> Self {
        match field_type {
            CoreFieldType::Surface => PyFieldType::Surface,
            CoreFieldType::LeftContextId => PyFieldType::LeftContextId,
            CoreFieldType::RightContextId => PyFieldType::RightContextId,
            CoreFieldType::Cost => PyFieldType::Cost,
            CoreFieldType::Custom => PyFieldType::Custom,
        }
    }
}

impl From<PyFieldType> for CoreFieldType {
    fn from(field_type: PyFieldType) -> Self {
        match field_type {
            PyFieldType::Surface => CoreFieldType::Surface,
            PyFieldType::LeftContextId => CoreFieldType::LeftContextId,
            PyFieldType::RightContextId => CoreFieldType::RightContextId,
            PyFieldType::Cost => CoreFieldType::Cost,
            PyFieldType::Custom => CoreFieldType::Custom,
        }
    }
}

impl From<FieldType> for PyFieldType {
    fn from(field_type: FieldType) -> Self {
        PyFieldType::from(CoreFieldType::from(field_type))
    }
}

impl From<PyFieldType> for FieldType {
    fn from(field_type: PyFieldType) -> Self {
        FieldType::from(CoreFieldType::from(field_type))
    }
}

/// Field definition in dictionary schema.
///
/// Describes a single field in the dictionary entry format.
#[pyclass(name = "FieldDefinition", from_py_object)]
#[derive(Debug, Clone)]
pub struct PyFieldDefinition {
    #[pyo3(get)]
    pub index: usize,
    #[pyo3(get)]
    pub name: String,
    #[pyo3(get)]
    pub field_type: PyFieldType,
    #[pyo3(get)]
    pub description: Option<String>,
}

#[pymethods]
impl PyFieldDefinition {
    #[new]
    pub fn new(
        index: usize,
        name: String,
        field_type: PyFieldType,
        description: Option<String>,
    ) -> Self {
        Self {
            index,
            name,
            field_type,
            description,
        }
    }

    fn __str__(&self) -> String {
        format!("FieldDefinition(index={}, name={})", self.index, self.name)
    }

    fn __repr__(&self) -> String {
        format!(
            "FieldDefinition(index={}, name='{}', field_type={:?}, description={:?})",
            self.index, self.name, self.field_type, self.description
        )
    }
}

impl From<CoreFieldDefinition> for PyFieldDefinition {
    fn from(field_def: CoreFieldDefinition) -> Self {
        PyFieldDefinition {
            index: field_def.index,
            name: field_def.name,
            field_type: field_def.field_type.into(),
            description: field_def.description,
        }
    }
}

impl From<PyFieldDefinition> for CoreFieldDefinition {
    fn from(field_def: PyFieldDefinition) -> Self {
        CoreFieldDefinition {
            index: field_def.index,
            name: field_def.name,
            field_type: field_def.field_type.into(),
            description: field_def.description,
        }
    }
}

impl From<FieldDefinition> for PyFieldDefinition {
    fn from(field_def: FieldDefinition) -> Self {
        PyFieldDefinition::from(CoreFieldDefinition::from(field_def))
    }
}

impl From<PyFieldDefinition> for FieldDefinition {
    fn from(field_def: PyFieldDefinition) -> Self {
        FieldDefinition::from(CoreFieldDefinition::from(field_def))
    }
}

/// Dictionary schema definition.
///
/// A thin PyO3 wrapper over [`lindera_binding_core::CoreSchema`], which owns the
/// field storage, the name-to-index map, and the field lookups.
///
/// # Examples
///
/// ```python
/// # Create schema
/// schema = lindera.Schema(["surface", "pos", "reading"])
///
/// # Query field information
/// index = schema.get_field_index("pos")
/// field = schema.get_field_by_name("reading")
/// ```
#[pyclass(name = "Schema", from_py_object)]
#[derive(Debug, Clone)]
pub struct PySchema {
    /// The backing binding-core schema.
    pub inner: CoreSchema,
}

#[pymethods]
impl PySchema {
    #[new]
    pub fn new(fields: Vec<String>) -> Self {
        Self {
            inner: CoreSchema::new(fields),
        }
    }

    #[staticmethod]
    pub fn create_default() -> Self {
        Self {
            inner: CoreSchema::create_default(),
        }
    }

    #[getter]
    pub fn fields(&self) -> Vec<String> {
        self.inner.fields().to_vec()
    }

    pub fn get_field_index(&self, field_name: &str) -> Option<usize> {
        self.inner.get_field_index(field_name)
    }

    pub fn field_count(&self) -> usize {
        self.inner.field_count()
    }

    pub fn get_field_name(&self, index: usize) -> Option<&str> {
        self.inner.get_field_name(index)
    }

    pub fn get_custom_fields(&self) -> Vec<String> {
        self.inner.get_custom_fields().to_vec()
    }

    pub fn get_all_fields(&self) -> Vec<String> {
        self.inner.fields().to_vec()
    }

    pub fn get_field_by_name(&self, name: &str) -> Option<PyFieldDefinition> {
        self.inner
            .get_field_by_name(name)
            .map(PyFieldDefinition::from)
    }

    pub fn validate_record(&self, record: Vec<String>) -> PyResult<()> {
        self.inner.validate_record(&record).map_err(to_py_error)
    }

    fn __str__(&self) -> String {
        format!("Schema(fields={})", self.inner.field_count())
    }

    fn __repr__(&self) -> String {
        format!("Schema(fields={:?})", self.inner.fields())
    }

    fn __len__(&self) -> usize {
        self.inner.field_count()
    }
}

impl From<CoreSchema> for PySchema {
    fn from(schema: CoreSchema) -> Self {
        PySchema { inner: schema }
    }
}

impl From<PySchema> for CoreSchema {
    fn from(schema: PySchema) -> Self {
        schema.inner
    }
}

impl From<PySchema> for Schema {
    fn from(schema: PySchema) -> Self {
        schema.inner.into()
    }
}

impl From<Schema> for PySchema {
    fn from(schema: Schema) -> Self {
        PySchema {
            inner: CoreSchema::from(schema),
        }
    }
}

pub fn register(parent_module: &Bound<'_, PyModule>) -> PyResult<()> {
    let py = parent_module.py();
    let m = PyModule::new(py, "schema")?;
    m.add_class::<PySchema>()?;
    m.add_class::<PyFieldDefinition>()?;
    m.add_class::<PyFieldType>()?;
    parent_module.add_submodule(&m)?;
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use lindera::dictionary::{FieldDefinition, FieldType, Schema};

    #[test]
    fn test_pyfieldtype_to_fieldtype_all_variants() {
        for (py, ft) in [
            (PyFieldType::Surface, FieldType::Surface),
            (PyFieldType::LeftContextId, FieldType::LeftContextId),
            (PyFieldType::RightContextId, FieldType::RightContextId),
            (PyFieldType::Cost, FieldType::Cost),
            (PyFieldType::Custom, FieldType::Custom),
        ] {
            let converted: FieldType = py.into();
            assert_eq!(converted, ft);
        }
    }

    #[test]
    fn test_fieldtype_to_pyfieldtype_all_variants() {
        assert!(matches!(
            PyFieldType::from(FieldType::Surface),
            PyFieldType::Surface
        ));
        assert!(matches!(
            PyFieldType::from(FieldType::Custom),
            PyFieldType::Custom
        ));
    }

    #[test]
    fn test_pyfielddefinition_to_fielddefinition() {
        let py_fd = PyFieldDefinition {
            index: 0,
            name: "surface".to_string(),
            field_type: PyFieldType::Surface,
            description: Some("Surface form".to_string()),
        };
        let fd: FieldDefinition = py_fd.into();
        assert_eq!(fd.index, 0);
        assert_eq!(fd.name, "surface");
        assert!(matches!(fd.field_type, FieldType::Surface));
        assert_eq!(fd.description, Some("Surface form".to_string()));
    }

    #[test]
    fn test_fielddefinition_to_pyfielddefinition() {
        let fd = FieldDefinition {
            index: 4,
            name: "pos".to_string(),
            field_type: FieldType::Custom,
            description: None,
        };
        let py_fd: PyFieldDefinition = fd.into();
        assert_eq!(py_fd.index, 4);
        assert_eq!(py_fd.name, "pos");
        assert!(matches!(py_fd.field_type, PyFieldType::Custom));
        assert!(py_fd.description.is_none());
    }

    #[test]
    fn test_pyschema_to_schema() {
        let py_schema = PySchema::new(vec![
            "surface".to_string(),
            "left_context_id".to_string(),
            "right_context_id".to_string(),
            "cost".to_string(),
            "pos".to_string(),
        ]);
        let schema: Schema = py_schema.into();
        let fields = schema.get_all_fields();
        assert_eq!(fields.len(), 5);
        assert_eq!(fields[0], "surface");
        assert_eq!(fields[4], "pos");
    }

    #[test]
    fn test_schema_to_pyschema() {
        let schema = Schema::new(vec![
            "surface".to_string(),
            "left_context_id".to_string(),
            "right_context_id".to_string(),
            "cost".to_string(),
        ]);
        let py_schema: PySchema = schema.into();
        assert_eq!(py_schema.fields().len(), 4);
        assert_eq!(py_schema.fields()[0], "surface");
    }

    #[test]
    fn test_pyschema_index_and_name_lookups() {
        let schema = PySchema::new(vec![
            "surface".to_string(),
            "pos".to_string(),
            "reading".to_string(),
        ]);
        assert_eq!(schema.get_field_index("surface"), Some(0));
        assert_eq!(schema.get_field_index("reading"), Some(2));
        assert_eq!(schema.get_field_index("nonexistent"), None);
        assert_eq!(schema.get_field_name(1), Some("pos"));
        assert_eq!(schema.get_field_name(9), None);
        assert_eq!(schema.field_count(), 3);
    }

    #[test]
    fn test_pyschema_custom_fields() {
        let schema = PySchema::new(vec![
            "surface".to_string(),
            "left_context_id".to_string(),
            "right_context_id".to_string(),
            "cost".to_string(),
            "major_pos".to_string(),
            "reading".to_string(),
        ]);
        let custom = schema.get_custom_fields();
        assert_eq!(custom, ["major_pos", "reading"]);
    }

    #[test]
    fn test_pyschema_create_default() {
        let schema = PySchema::create_default();
        assert_eq!(schema.field_count(), 13);
        assert_eq!(schema.fields()[0], "surface");
        assert_eq!(schema.fields()[5], "pos_detail_1");
        assert_eq!(schema.fields()[12], "pronunciation");
        assert_eq!(schema.get_field_index("cost"), Some(3));
    }

    #[test]
    fn test_pyschema_get_field_by_name() {
        let schema = PySchema::create_default();
        let surface = schema.get_field_by_name("surface").unwrap();
        assert_eq!(surface.index, 0);
        assert!(matches!(surface.field_type, PyFieldType::Surface));

        let custom = schema.get_field_by_name("major_pos").unwrap();
        assert_eq!(custom.index, 4);
        assert!(matches!(custom.field_type, PyFieldType::Custom));

        assert!(schema.get_field_by_name("nonexistent").is_none());
    }

    // Note: `validate_record` is intentionally not unit-tested here. It maps
    // `CoreError` to a Python exception via `to_py_error`, which references the
    // Python C-API exception types; exercising it would pull those symbols into
    // the standalone `cargo test --lib` binary, which (with pyo3
    // `extension-module`) does not link libpython. The logic is covered by
    // `lindera-binding-core`'s `core_schema_validate_record` test and by the
    // Python pytest suite.

    #[test]
    fn test_pyschema_roundtrip() {
        let fields = vec![
            "surface".to_string(),
            "left_context_id".to_string(),
            "right_context_id".to_string(),
            "cost".to_string(),
            "pos".to_string(),
        ];
        let py_schema = PySchema::new(fields.clone());
        let schema: Schema = py_schema.into();
        let roundtripped: PySchema = schema.into();
        assert_eq!(roundtripped.fields(), fields);
    }
}