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
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
mod corpus_structure;
mod document;
#[cfg(test)]
mod tests;

use std::{
    borrow::Cow,
    collections::{BTreeMap, BTreeSet, HashMap, HashSet},
    path::PathBuf,
};

use crate::{importer::saltxml::SaltObject, progress::ProgressReporter};

use super::Exporter;
use anyhow::{Context, Result, bail};
use bimap::BiBTreeMap;
use corpus_structure::SaltCorpusStructureMapper;
use document::SaltDocumentGraphMapper;
use facet::Facet;
use graphannis::{
    AnnotationGraph,
    graph::{AnnoKey, Edge, NodeID},
    model::{AnnotationComponent, AnnotationComponentType},
};
use graphannis_core::graph::{ANNIS_NS, NODE_NAME_KEY};

use lazy_static::lazy_static;
use quick_xml::{
    Writer,
    events::{BytesStart, Event},
};
use serde::{Deserialize, Serialize};

/// Exports to the SaltXML format used by Pepper
/// (<https://corpus-tools.org/pepper/>). SaltXML is an XMI serialization of the
/// [Salt
/// model](https://raw.githubusercontent.com/korpling/salt/master/gh-site/doc/salt_modelGuide.pdf).
#[derive(Facet, Deserialize, Default, Serialize, Clone, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct ExportSaltXml {}

impl Exporter for ExportSaltXml {
    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())?;
        let corpus_mapper = SaltCorpusStructureMapper::new();

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

        progress.info("Writing SaltXML corpus structure")?;
        let document_node_ids =
            corpus_mapper.map_corpus_structure(graph, output_path, &progress)?;
        let progress = ProgressReporter::new(tx, step_id, document_node_ids.len())?;
        for id in document_node_ids {
            let mut doc_mapper = SaltDocumentGraphMapper::new();
            doc_mapper.map_document_graph(graph, id, output_path, &progress)?;
            progress.worked(1)?;
        }

        Ok(())
    }

    fn file_extension(&self) -> &str {
        ".salt"
    }
}

#[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Debug)]
enum NodeType {
    Id(NodeID),
    Custom(String),
}

struct SaltWriter<'a, W> {
    graph: &'a AnnotationGraph,
    xml: &'a mut Writer<W>,
    output_path: PathBuf,
    progress: &'a ProgressReporter,
    layer_positions: BiBTreeMap<String, usize>,
    node_positions: BTreeMap<NodeType, usize>,
    number_of_edges: usize,
    nodes_in_layer: HashMap<String, Vec<usize>>,
    edges_in_layer: HashMap<String, Vec<usize>>,
    excluded_nodes: HashSet<NodeID>,
}

lazy_static! {
    static ref LAYER_KEY: AnnoKey = {
        AnnoKey {
            ns: ANNIS_NS.into(),
            name: "layer".into(),
        }
    };
    static ref DOC_KEY: AnnoKey = {
        AnnoKey {
            ns: ANNIS_NS.into(),
            name: "doc".into(),
        }
    };
    static ref TOK_WHITESPACE_BEFORE_KEY: AnnoKey = {
        AnnoKey {
            ns: ANNIS_NS.into(),
            name: "tok-whitespace-before".into(),
        }
    };
    static ref TOK_WHITESPACE_AFTER_KEY: AnnoKey = {
        AnnoKey {
            ns: ANNIS_NS.into(),
            name: "tok-whitespace-after".into(),
        }
    };
}

impl<'a, W> SaltWriter<'a, W>
where
    W: std::io::Write,
{
    fn new(
        graph: &'a AnnotationGraph,
        writer: &'a mut Writer<W>,
        output_path: &std::path::Path,
        progress: &'a ProgressReporter,
    ) -> Result<Self> {
        // Collect node and edge layer names
        let mut layer_names = BTreeSet::new();
        layer_names.extend(
            graph
                .get_node_annos()
                .get_all_values(&LAYER_KEY, false)?
                .into_iter()
                .filter(|l| !l.is_empty())
                .map(|l| l.to_string()),
        );
        layer_names.extend(
            graph
                .get_all_components(None, None)
                .into_iter()
                .filter(|c| !c.layer.is_empty())
                .map(|c| c.layer.to_string()),
        );
        // Create a map of all layer names to their position in the XML file.
        let layer_positions = layer_names
            .into_iter()
            .enumerate()
            .map(|(pos, layer)| (layer, pos))
            .collect();

        Ok(SaltWriter {
            graph,
            xml: writer,
            output_path: output_path.to_path_buf(),
            progress,
            layer_positions,
            number_of_edges: 0,
            node_positions: BTreeMap::new(),
            nodes_in_layer: HashMap::new(),
            edges_in_layer: HashMap::new(),
            excluded_nodes: HashSet::new(),
        })
    }

    fn write_label(&mut self, key: &AnnoKey, value: &SaltObject, salt_type: &str) -> Result<()> {
        let anno_ns: &str = &key.ns;
        let anno_name: &str = &key.name;

        let mut label = self
            .xml
            .create_element("labels")
            .with_attribute(("xsi:type", salt_type));

        if !anno_ns.is_empty() {
            if anno_name == "SDATA" {
                label = label.with_attribute(("namespace", "saltCommon"));
            } else {
                label = label.with_attribute(("namespace", anno_ns));
            }
        }
        if anno_name.is_empty() {
            // Ignore labels that have no name
            self.progress.warn(format!(
                "Label ({:?}={}) with empty name is ignored for file {}",
                key,
                value,
                self.output_path.to_string_lossy()
            ))?;
        } else {
            label = label.with_attribute(("name", anno_name));
            label = label.with_attribute(("value", value.marshall().as_str()));
            label.write_empty()?;
        }

        Ok(())
    }

    fn write_graphannis_node(&mut self, n: NodeID, salt_type: &str) -> Result<()> {
        // Get the layer from the attribute
        let layer = self
            .graph
            .get_node_annos()
            .get_value_for_item(&n, &LAYER_KEY)?
            .map(|l| l.to_string());

        // Collect all annotations for this nodes labels
        let annotations: Vec<_> = self
            .graph
            .get_node_annos()
            .get_annotations_for_item(&n)?
            .into_iter()
            .filter(|a| a.key.ns != "annis" || a.key.name != "tok")
            .collect();

        // Use the "annis:doc" label as SNAME or the fragment of the URI as fallback
        let sname = if salt_type == "sCorpusStructure:SDocument" {
            self.graph
                .get_node_annos()
                .get_value_for_item(&n, &DOC_KEY)?
                .context("Missing annis:doc annotation for document node")?
        } else {
            let node_name = self
                .graph
                .get_node_annos()
                .get_value_for_item(&n, &NODE_NAME_KEY)?
                .context("Missing node name")?;
            Cow::Owned(
                node_name
                    .split('#')
                    .next_back()
                    .unwrap_or_default()
                    .to_string(),
            )
        };

        // Use the more general method to actual write the XML
        let annotations: Vec<_> = annotations
            .into_iter()
            .map(|a| (a.key, SaltObject::Text(a.val.to_string())))
            .collect();
        self.write_node(NodeType::Id(n), &sname, salt_type, &annotations, &[], layer)?;
        Ok(())
    }

    fn write_node(
        &mut self,
        n: NodeType,
        sname: &str,
        salt_type: &str,
        output_annotations: &[(AnnoKey, SaltObject)],
        output_features: &[(AnnoKey, SaltObject)],
        layer: Option<String>,
    ) -> Result<()> {
        // Remember the position of this node in the XML file
        let node_position = self.node_positions.len();
        self.node_positions.insert(n.clone(), node_position);

        let mut attributes: Vec<(String, String)> = Vec::new();
        attributes.push(("xsi:type".to_string(), salt_type.to_string()));

        // Add the layer reference to the attributes
        if let Some(layer) = layer {
            let pos = self
                .layer_positions
                .get_by_left(&layer)
                .context("Unknown position for layer")?;
            let layer_att_value = format!("//@layers.{pos}");
            attributes.push(("layers".to_string(), layer_att_value));
            self.nodes_in_layer
                .entry(layer.to_string())
                .or_default()
                .push(node_position);
        }
        let node_name = match &n {
            NodeType::Id(n) => self
                .graph
                .get_node_annos()
                .get_value_for_item(n, &NODE_NAME_KEY)?
                .context("Missing node name")?
                .to_string(),
            NodeType::Custom(node_name) => node_name.clone(),
        };
        let nodes_tag = BytesStart::new("nodes")
            .with_attributes(attributes.iter().map(|(n, v)| (n.as_str(), v.as_str())));
        self.xml.write_event(Event::Start(nodes_tag.borrow()))?;

        // Write Salt ID and SNAME
        let salt_id = format!("T::salt:/{node_name}");
        self.xml
            .create_element("labels")
            .with_attribute(("xsi:type", "saltCore:SElementId"))
            .with_attribute(("namespace", "salt"))
            .with_attribute(("name", "id"))
            .with_attribute(("value", salt_id.as_str()))
            .write_empty()?;

        // Get the last part of the URI path
        self.xml
            .create_element("labels")
            .with_attribute(("xsi:type", "saltCore:SFeature"))
            .with_attribute(("namespace", "salt"))
            .with_attribute(("name", "SNAME"))
            .with_attribute(("value", format!("T::{sname}").as_str()))
            .write_empty()?;

        // Write all other annotations as labels
        for (key, value) in output_annotations {
            if key.ns != "annis" {
                let label_type = if salt_type == "sCorpusStructure:SCorpus"
                    || salt_type == "sCorpusStructure:SDocument"
                {
                    "saltCore:SMetaAnnotation"
                } else {
                    "saltCore:SAnnotation"
                };
                self.write_label(key, value, label_type)?;
            }
        }
        for (key, value) in output_features {
            self.write_label(key, value, "saltCore:SFeature")?;
        }
        self.xml.write_event(Event::End(nodes_tag.to_end()))?;

        Ok(())
    }

    fn write_graphannis_edge(&mut self, edge: Edge, component: &AnnotationComponent) -> Result<()> {
        if self.excluded_nodes.contains(&edge.source) || self.excluded_nodes.contains(&edge.target)
        {
            return Ok(());
        }
        // Invert edge for PartOf components
        let output_edge = if component.get_type() == AnnotationComponentType::PartOf {
            edge.inverse()
        } else {
            edge.clone()
        };

        let source = NodeType::Id(output_edge.source);
        let target = NodeType::Id(output_edge.target);

        let gs = self
            .graph
            .get_graphstorage_as_ref(component)
            .context("Missing graph storage for edge component")?;
        let salt_type = match component.get_type() {
            AnnotationComponentType::Coverage => "sDocumentStructure:SSpanningRelation",
            AnnotationComponentType::Dominance => "sDocumentStructure:SDominanceRelation",
            AnnotationComponentType::Pointing => "sDocumentStructure:SPointingRelation",
            AnnotationComponentType::Ordering => "sDocumentStructure:SOrderRelation",
            AnnotationComponentType::PartOf => {
                // Check if this is a document or a (sub)-corpus by testing if there are any incoming PartOfEdges
                if gs.has_ingoing_edges(edge.source)? {
                    "sCorpusStructure:SCorpusDocumentRelation"
                } else {
                    "sCorpusStructure:SCorpusRelation"
                }
            }
            _ => {
                bail!(
                    "Invalid component type {} for SaltXML",
                    component.get_type()
                )
            }
        };

        let output_annotations = gs.get_anno_storage().get_annotations_for_item(&edge)?;
        let output_annotations: Vec<_> = output_annotations
            .into_iter()
            .map(|a| (a.key, SaltObject::Text(a.val.to_string())))
            .collect();

        let layer = if component.layer.is_empty() {
            None
        } else {
            Some(component.layer.to_string())
        };

        self.write_edge(source, target, salt_type, &output_annotations, &[], layer)?;

        Ok(())
    }

    fn write_edge(
        &mut self,
        source: NodeType,
        target: NodeType,
        salt_type: &str,
        output_annotations: &[(AnnoKey, SaltObject)],
        output_features: &[(AnnoKey, SaltObject)],
        layer: Option<String>,
    ) -> Result<()> {
        let mut attributes = Vec::new();
        attributes.push(("xsi:type".to_string(), salt_type.to_string()));

        let source_position = self
            .node_positions
            .get(&source)
            .with_context(|| format!("Missing position for source node {source:?}"))?;

        let target_position = self
            .node_positions
            .get(&target)
            .with_context(|| format!("Missing position for target node {target:?}"))?;

        attributes.push(("source".to_string(), format!("//@nodes.{source_position}")));
        attributes.push(("target".to_string(), format!("//@nodes.{target_position}")));

        // Add the layer reference to the attributes
        if let Some(layer) = layer {
            let pos = self
                .layer_positions
                .get_by_left(&layer)
                .context("Unknown position for layer")?;
            let layer_att_value = format!("//@layers.{pos}");
            attributes.push(("layers".to_string(), layer_att_value));
            self.edges_in_layer
                .entry(layer)
                .or_default()
                .push(self.number_of_edges);
        }

        let edges_tag = BytesStart::new("edges")
            .with_attributes(attributes.iter().map(|(n, v)| (n.as_str(), v.as_str())));

        if output_annotations.is_empty() && output_features.is_empty() {
            self.xml.write_event(Event::Empty(edges_tag))?;
        } else {
            self.xml.write_event(Event::Start(edges_tag.borrow()))?;

            // add all edge labels
            for (key, value) in output_annotations {
                if key.ns != "annis" {
                    self.write_label(key, value, "saltCore:SAnnotation")?;
                }
            }
            for (key, value) in output_features {
                if key.ns != "annis" {
                    self.write_label(key, value, "saltCore:SFeature")?;
                }
            }
            self.xml.write_event(Event::End(edges_tag.to_end()))?;
        }

        self.number_of_edges += 1;

        Ok(())
    }

    fn write_all_layers(&mut self) -> Result<()> {
        // Iterate over the layers in order of their position
        for (layer, pos) in self.layer_positions.right_range(..) {
            let mut attributes = Vec::new();
            attributes.push(("xsi:type".to_string(), "saltCore:SLayer".to_string()));

            // Write nodes as attribute
            if let Some(included_positions) = self.nodes_in_layer.get(layer) {
                let att_value = position_references_to_string(included_positions, "nodes");
                attributes.push(("nodes".to_string(), att_value));
            }

            // Write edges as attributes
            if let Some(included_positions) = self.edges_in_layer.get(layer) {
                let att_value = position_references_to_string(included_positions, "edges");
                attributes.push(("edges".to_string(), att_value));
            }

            let layers_tag = BytesStart::new("layers")
                .with_attributes(attributes.iter().map(|(n, v)| (n.as_str(), v.as_str())));
            self.xml.write_event(Event::Start(layers_tag.borrow()))?;

            let marshalled_id = format!("T::l{pos}");
            self.xml
                .create_element("labels")
                .with_attribute(("xsi:type", "saltCore:SElementId"))
                .with_attribute(("namespace", "salt"))
                .with_attribute(("name", "id"))
                .with_attribute(("value", marshalled_id.as_str()))
                .write_empty()?;

            let marshalled_name = format!("T::{layer}");
            self.xml
                .create_element("labels")
                .with_attribute(("xsi:type", "saltCore:SFeature"))
                .with_attribute(("namespace", "salt"))
                .with_attribute(("name", "SNAME"))
                .with_attribute(("value", marshalled_name.as_str()))
                .write_empty()?;
            self.xml.write_event(Event::End(layers_tag.to_end()))?;
        }
        Ok(())
    }
}

fn position_references_to_string(included_positions: &[usize], att_name: &str) -> String {
    let mut att_value = String::new();
    for (i, pos) in included_positions.iter().enumerate() {
        if i > 0 {
            att_value.push(' ');
        }
        att_value.push_str("//@");
        att_value.push_str(att_name);
        att_value.push('.');
        att_value.push_str(&pos.to_string());
    }
    att_value
}