annatto 0.50.1

Converts linguistic data formats based on the graphANNIS data model as intermediate representation and can apply consistency tests.
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
use std::{
    collections::{BTreeMap, btree_map::Entry},
    fs::File,
    io::{BufWriter, Write},
    path::Path,
    sync::Arc,
};

use anyhow::anyhow;
use facet::Facet;
use graphannis::{
    AnnotationGraph,
    graph::{AnnoKey, GraphStorage, NodeID},
    model::{AnnotationComponent, AnnotationComponentType},
};
use graphannis_core::{
    dfs::{self, CycleSafeDFS},
    graph::{ANNIS_NS, DEFAULT_NS, NODE_NAME_KEY},
};
use itertools::Itertools;
use serde::{Deserialize, Serialize};

use super::Exporter;

use crate::{
    progress::ProgressReporter,
    util::token_helper::{TOKEN_KEY, TokenHelper},
};

#[derive(Facet, Clone, Debug, Deserialize, PartialEq, Serialize, Default)]
#[repr(u8)]
#[serde(tag = "strategy", content = "name", rename_all = "snake_case")]
enum SpanName {
    #[default]
    FirstAnnoName,
    FirstAnnoNamespace,
    Fixed(String),
}

/// Exporter for the file format used by the TreeTagger.
#[derive(Facet, Deserialize, Serialize, Clone, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct ExportTreeTagger {
    /// Provide the token annotation names that should be exported as columns.
    /// If you do not provide a namespace, "default_ns" will be used
    /// automatically.
    #[serde(
        default = "default_column_names",
        with = "crate::estarde::anno_key::in_sequence"
    )]
    column_names: Vec<AnnoKey>,
    /// If given, use this segmentation instead of the token as token column.
    #[serde(default)]
    segmentation: Option<String>,
    /// Use a strategy to determine the SGML tag names for spans.
    ///
    /// Use the *name* of the first annotation (default):
    /// ```toml
    /// [export.config]
    /// span_names = { strategy = "first_anno_name"}
    /// ```
    ///
    /// Use the *namespace* of the first annotation:
    /// ```toml
    /// [export.config]
    /// span_names = { strategy = "first_anno_namespace"}
    /// ```
    ///
    /// Use a *fixed name* for all spans:
    /// ```toml
    /// [export.config]
    /// span_names = { strategy = "fixed", name = "mytagname"}
    /// ```
    #[serde(default)]
    span_names: SpanName,
    /// The provided annotation key defines which nodes within the part-of component define a document. All nodes holding said annotation
    /// will be exported to a file with the name according to the annotation value. Therefore annotation values must not contain path
    /// delimiters.
    ///
    /// Example:
    /// ```toml
    /// [export.config]
    /// doc_anno = "my_namespace::document"
    /// ```
    ///
    /// The default is `annis::doc`.
    #[serde(default = "default_doc_anno", with = "crate::estarde::anno_key")]
    doc_anno: AnnoKey,
    /// Don't output meta data header when set to `true`
    #[serde(default)]
    skip_meta: bool,
    /// Don't output SGML tags for span annotations when set to `true`
    #[serde(default)]
    skip_spans: bool,
}

fn default_doc_anno() -> AnnoKey {
    AnnoKey {
        name: "doc".into(),
        ns: ANNIS_NS.into(),
    }
}

fn default_column_names() -> Vec<AnnoKey> {
    vec![
        AnnoKey {
            name: "pos".into(),
            ns: DEFAULT_NS.into(),
        },
        AnnoKey {
            name: "lemma".into(),
            ns: DEFAULT_NS.into(),
        },
    ]
}

impl Default for ExportTreeTagger {
    fn default() -> Self {
        Self {
            column_names: default_column_names(),
            segmentation: None,
            doc_anno: default_doc_anno(),
            skip_meta: false,
            skip_spans: false,
            span_names: SpanName::FirstAnnoName,
        }
    }
}

const FILE_EXTENSION: &str = "tt";

impl Exporter for ExportTreeTagger {
    fn export_corpus(
        &self,
        graph: &graphannis::AnnotationGraph,
        output_path: &std::path::Path,
        step_id: crate::StepID,
        tx: Option<crate::workflow::StatusSender>,
    ) -> Result<(), Box<dyn std::error::Error>> {
        let _progress = ProgressReporter::new_unknown_total_work(tx.clone(), step_id.clone())?;

        std::fs::create_dir_all(output_path)?;

        let base_ordering = AnnotationComponent::new(
            AnnotationComponentType::Ordering,
            ANNIS_NS.into(),
            "".into(),
        );

        let mut selected_ordering = base_ordering;
        if let Some(seg) = &self.segmentation {
            let matching_components =
                graph.get_all_components(Some(AnnotationComponentType::Ordering), Some(seg));
            if matching_components.len() == 1 {
                selected_ordering = matching_components[0].clone();
            } else {
                for layer in self.possible_namespace_for_segmentation() {
                    if let Some(matching) = matching_components
                        .iter()
                        .find(|c| c.layer.as_str() == layer)
                    {
                        selected_ordering = matching.clone();
                        break;
                    }
                }
            }
        }

        let gs_ordering = graph
            .get_graphstorage(&selected_ordering)
            .ok_or(anyhow!("Storage of ordering component unavailable"))?;
        let part_of_storage = graph
            .get_graphstorage(&AnnotationComponent::new(
                AnnotationComponentType::PartOf,
                ANNIS_NS.into(),
                "".into(),
            ))
            .ok_or(anyhow!("Part-of storage unavailable."))?;

        let mut doc_node_to_start = BTreeMap::new();
        for node in gs_ordering.root_nodes() {
            let node = node?;
            let dfs = CycleSafeDFS::new(
                part_of_storage.as_edgecontainer(),
                node,
                0,
                NodeID::MAX as usize,
            );
            for n in dfs {
                let n = n?.node;
                if graph
                    .get_node_annos()
                    .has_value_for_item(&n, &self.doc_anno)
                    .unwrap_or_default()
                {
                    if let Entry::Vacant(e) = doc_node_to_start.entry(n) {
                        e.insert(node);
                        break;
                    } else {
                        let doc_node_name = graph
                            .get_node_annos()
                            .get_value_for_item(&n, &NODE_NAME_KEY)?
                            .unwrap_or_default();
                        return Err(anyhow!(
                            "Document {doc_node_name} has more than one start node for base ordering."
                        )
                        .into());
                    }
                }
            }
        }
        let progress = ProgressReporter::new(tx, step_id, doc_node_to_start.len())?;
        progress.info(format!("Exporting {} documents", doc_node_to_start.len()))?;
        doc_node_to_start
            .into_iter()
            .try_for_each(move |(doc, start)| -> anyhow::Result<()> {
                self.export_document(graph, output_path, doc, start, gs_ordering.clone())?;
                progress.worked(1)?;
                Ok(())
            })?;
        Ok(())
    }

    fn file_extension(&self) -> &str {
        FILE_EXTENSION
    }
}

impl ExportTreeTagger {
    fn export_document(
        &self,
        graph: &AnnotationGraph,
        corpus_path: &Path,
        doc_node: NodeID,
        start_node: NodeID,
        gs_ordering: Arc<dyn GraphStorage>,
    ) -> anyhow::Result<()> {
        let token_helper = TokenHelper::new(graph)?;

        let node_annos = graph.get_node_annos();
        let doc_node_name = node_annos
            .get_value_for_item(&doc_node, &self.doc_anno)?
            .ok_or(anyhow!("Could not determine document node name."))?;
        let file_path =
            Path::new(corpus_path).join(format!("{doc_node_name}.{}", self.file_extension()));
        let mut w = BufWriter::new(File::create(file_path)?);

        let footer = if self.skip_meta {
            None
        } else {
            Some(self.write_metadata_header(graph, doc_node, &mut w)?)
        };

        let it = dfs::CycleSafeDFS::new(gs_ordering.as_edgecontainer(), start_node, 0, usize::MAX);
        for token in it {
            let token = token?.node;

            let mut matching_token_key = TOKEN_KEY.as_ref().clone();
            if !node_annos.has_value_for_item(&token, &matching_token_key)?
                && let Some(seg) = &self.segmentation
            {
                matching_token_key.name = seg.clone();
                for ns in self.possible_namespace_for_segmentation() {
                    matching_token_key.ns = ns;
                    if node_annos.has_value_for_item(&token, &matching_token_key)? {
                        break;
                    }
                }
            }

            if !self.skip_spans {
                self.write_starting_spans(graph, token, &token_helper, &mut w)?;
            }

            let token_val = node_annos
                .get_value_for_item(&token, &matching_token_key)?
                .unwrap_or_default();

            write!(w, "{token_val}")?;
            for column in &self.column_names {
                let anno_value = node_annos
                    .get_value_for_item(&token, column)?
                    .unwrap_or_default();
                write!(w, "\t{anno_value}")?;
            }
            writeln!(w)?;

            if !self.skip_spans {
                self.write_ending_spans(graph, token, &token_helper, &mut w)?;
            }
        }

        if let Some(footer) = footer {
            writeln!(w, "{footer}")?;
        }
        Ok(())
    }

    /// Writes the metadata of this document as line with a span, returns the
    /// end-tag that needs to be added at the end.
    fn write_metadata_header<W: Write>(
        &self,
        graph: &AnnotationGraph,
        doc_node: NodeID,
        mut w: W,
    ) -> anyhow::Result<String> {
        write!(w, "<doc")?;

        for anno in graph.get_node_annos().get_annotations_for_item(&doc_node)? {
            if anno.key.ns != ANNIS_NS {
                let name = quick_xml::escape::escape(&anno.key.name);
                let value = quick_xml::escape::escape(&anno.val);
                write!(w, " {name}=\"{value}\"")?;
            }
        }
        writeln!(w, ">")?;

        Ok("</doc>".to_string())
    }

    /// Finds all spans that start at the given token and write their annotation values out.
    fn write_starting_spans<W: Write>(
        &self,
        graph: &AnnotationGraph,
        token: NodeID,
        token_helper: &TokenHelper,
        mut w: W,
    ) -> anyhow::Result<()> {
        if let Some(left_token) = token_helper.left_token_for(token)? {
            for starting_span in token_helper
                .get_gs_left_token()
                .get_ingoing_edges(left_token)
            {
                let starting_span = starting_span?;

                if !self.is_segmentation_span(starting_span, graph, token_helper)? {
                    let tag = self.tag_name_for_span(graph, starting_span)?;
                    write!(w, "<{tag}")?;
                    for anno in graph
                        .get_node_annos()
                        .get_annotations_for_item(&starting_span)?
                    {
                        if anno.key.ns != ANNIS_NS {
                            let name = quick_xml::escape::escape(&anno.key.name);
                            let value = quick_xml::escape::escape(&anno.val);
                            write!(w, " {name}=\"{value}\"")?;
                        }
                    }
                    writeln!(w, ">")?;
                }
            }
        }

        Ok(())
    }

    /// Finds all spans that end at the given token and write their annotation values out.
    fn write_ending_spans<W: Write>(
        &self,
        graph: &AnnotationGraph,
        token: NodeID,
        token_helper: &TokenHelper,
        mut w: W,
    ) -> anyhow::Result<()> {
        if let Some(right_token) = token_helper.right_token_for(token)? {
            for ending_span in token_helper
                .get_gs_right_token()
                .get_ingoing_edges(right_token)
            {
                let ending_span = ending_span?;
                if !self.is_segmentation_span(ending_span, graph, token_helper)? {
                    let tag = self.tag_name_for_span(graph, ending_span)?;
                    writeln!(w, "</{tag}>")?;
                }
            }
        }

        Ok(())
    }

    fn is_segmentation_span(
        &self,
        span: NodeID,
        graph: &AnnotationGraph,
        token_helper: &TokenHelper,
    ) -> anyhow::Result<bool> {
        if graph
            .get_node_annos()
            .has_value_for_item(&span, &TOKEN_KEY)?
        {
            Ok(true)
        } else {
            // Check if it is connected to any ordering component
            for gs in token_helper.get_gs_ordering().values() {
                if gs.has_outgoing_edges(span)? || gs.has_ingoing_edges(span)? {
                    return Ok(true);
                }
            }
            Ok(false)
        }
    }

    fn tag_name_for_span(&self, graph: &AnnotationGraph, span: NodeID) -> anyhow::Result<String> {
        match &self.span_names {
            SpanName::FirstAnnoName => {
                let keys: Vec<_> = graph
                    .get_node_annos()
                    .get_all_keys_for_item(&span, None, None)?
                    .into_iter()
                    .filter(|key| key.ns != ANNIS_NS)
                    .sorted()
                    .collect();
                let first_name = keys
                    .first()
                    .map(|key| quick_xml::escape::escape(&key.name).to_string())
                    .unwrap_or_else(|| "span".to_string());
                Ok(first_name)
            }
            SpanName::FirstAnnoNamespace => {
                let keys: Vec<_> = graph
                    .get_node_annos()
                    .get_all_keys_for_item(&span, None, None)?
                    .into_iter()
                    .filter(|key| key.ns != ANNIS_NS)
                    .sorted()
                    .collect();
                let first_name = keys
                    .first()
                    .map(|key| quick_xml::escape::escape(&key.ns).to_string())
                    .unwrap_or_else(|| "span".to_string());
                Ok(first_name)
            }
            SpanName::Fixed(name) => Ok(name.clone()),
        }
    }

    /// A segmentation annotation and ordering component could have different
    /// possible namespaces. Return a vector of the ones that need to be checked
    /// (in order).
    fn possible_namespace_for_segmentation(&self) -> Vec<String> {
        let mut result = Vec::new();
        if let Some(segmentation) = &self.segmentation {
            result.push(segmentation.clone());
            result.push(ANNIS_NS.to_string());
            result.push(DEFAULT_NS.to_string());
            result.push("".to_string());
        }
        result
    }
}

#[cfg(test)]
mod tests;