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
use std::cell::{Cell, RefCell};
use std::vec::IntoIter;
use walkdir::IntoIter as WalkDirIterator;
use walkdir::WalkDir;
use crate::dnm::{DNMParameters, DNMRange, DNM};
use crate::tokenizer::Tokenizer;
use libxml::parser::{Parser, XmlParseError};
use libxml::readonly::RoNode;
use libxml::tree::Document as XmlDoc;
use libxml::xpath::Context;
use senna::pos::POS;
use senna::senna::{Senna, SennaParseOptions};
use senna::sennapath::SENNA_PATH;
use senna::sentence::Sentence as SennaSentence;
pub struct Corpus {
pub path: String,
pub xml_parser: Parser,
pub html_parser: Parser,
pub tokenizer: Tokenizer,
pub senna: RefCell<Senna>,
pub senna_options: Cell<SennaParseOptions>,
pub dnm_parameters: DNMParameters,
pub extension: Option<String>,
}
pub struct DocumentIterator<'iter> {
walker: Box<WalkDirIterator>,
pub corpus: &'iter Corpus,
}
pub struct Document<'d> {
pub dom: XmlDoc,
pub path: String,
pub corpus: &'d Corpus,
pub dnm: Option<DNM>,
}
pub struct ParagraphIterator<'iter> {
walker: IntoIter<RoNode>,
pub document: &'iter Document<'iter>,
}
pub struct Paragraph<'p> {
pub dnm: DNM,
pub document: &'p Document<'p>,
}
pub struct SentenceIterator<'iter> {
walker: IntoIter<DNMRange<'iter>>,
pub document: &'iter Document<'iter>,
}
pub struct Sentence<'s> {
pub range: DNMRange<'s>,
pub document: &'s Document<'s>,
pub senna_sentence: Option<SennaSentence<'s>>,
}
pub struct SimpleWordIterator<'iter> {
walker: IntoIter<DNMRange<'iter>>,
pub sentence: &'iter Sentence<'iter>,
}
pub struct SennaWordIterator<'iter> {
pos: usize,
pub sentence: &'iter Sentence<'iter>,
}
pub struct Word<'w> {
pub range: DNMRange<'w>, pub sentence: &'w Sentence<'w>,
pub pos: POS,
}
impl<'iter> Iterator for DocumentIterator<'iter> {
type Item = Document<'iter>;
fn next(&mut self) -> Option<Document<'iter>> {
let walker = &mut self.walker;
loop {
let next_entry = walker.next();
if next_entry.is_none() {
break;
} else if let Some(Ok(ref entry)) = next_entry {
let file_name = entry.file_name().to_str().unwrap_or("").to_owned();
let selected = if let Some(ref extension) = self.corpus.extension {
file_name.ends_with(extension)
} else {
file_name.ends_with(".html") || file_name.ends_with(".xhtml")
};
if selected {
let path = entry.path().to_str().unwrap_or("").to_owned();
let doc_result = Document::new(path, self.corpus);
return match doc_result {
Ok(doc) => Some(doc),
_ => None,
};
}
} else {
println!("-- Error while walking for entry: {next_entry:?}")
}
}
None
}
}
impl Default for Corpus {
fn default() -> Corpus {
Corpus {
extension: None,
path: ".".to_string(),
tokenizer: Tokenizer::default(),
xml_parser: Parser::default(),
html_parser: Parser::default_html(),
senna: RefCell::new(Senna::new(SENNA_PATH.to_owned())),
senna_options: Cell::new(SennaParseOptions::default()),
dnm_parameters: DNMParameters::llamapun_normalization(),
}
}
}
impl Corpus {
pub fn new(dirpath: String) -> Self {
Corpus {
path: dirpath,
..Corpus::default()
}
}
pub fn iter(&mut self) -> DocumentIterator {
DocumentIterator {
walker: Box::new(WalkDir::new(self.path.clone()).into_iter()),
corpus: self,
}
}
pub fn load_doc(&self, path: String) -> Result<Document, XmlParseError> {
Document::new(path, self)
}
}
impl<'d> Document<'d> {
pub fn new(filepath: String, corpus: &'d Corpus) -> Result<Self, XmlParseError> {
let dom = if filepath.ends_with(".xhtml") {
corpus.xml_parser.parse_file(&filepath)?
} else {
corpus.html_parser.parse_file(&filepath)?
};
Ok(Document {
path: filepath,
dom,
corpus,
dnm: None,
})
}
pub fn paragraph_nodes(doc: &XmlDoc) -> Vec<RoNode> {
let xpath_context = Context::new(doc).unwrap();
match xpath_context.evaluate(
"//*[local-name()='div' and contains(@class,'ltx_para') and not(descendant::*[contains(@class,'ltx_ERROR')]) and not(preceding-sibling::*[contains(@class,'ltx_ERROR')])]",
) {
Ok(found_payload) => found_payload.get_readonly_nodes_as_vec(),
_ => Vec::new(),
}
}
pub fn paragraph_iter(&mut self) -> ParagraphIterator {
let paras = Document::paragraph_nodes(&self.dom);
ParagraphIterator {
walker: paras.into_iter(),
document: self,
}
}
pub fn get_math_nodes(&self) -> Vec<RoNode> { Document::math_nodes(&self.dom) }
fn math_nodes(doc: &XmlDoc) -> Vec<RoNode> {
let xpath_context = Context::new(doc).unwrap();
match xpath_context.evaluate("//*[local-name()='math']") {
Ok(found_payload) => found_payload.get_readonly_nodes_as_vec(),
_ => Vec::new(),
}
}
pub fn get_ref_nodes(&self) -> Vec<RoNode> { Document::ref_nodes(&self.dom) }
fn ref_nodes(doc: &XmlDoc) -> Vec<RoNode> {
let xpath_context = Context::new(doc).unwrap();
match xpath_context.evaluate("//*[(local-name()='span' or local-name()='a') and (contains(@class,'ltx_ref ') or @class='ltx_ref')]") {
Ok(found_payload) => found_payload.get_readonly_nodes_as_vec(),
_ => Vec::new(),
}
}
pub fn sentence_iter(&mut self) -> SentenceIterator {
if self.dnm.is_none() {
if let Some(root) = self.dom.get_root_readonly() {
self.dnm = Some(DNM::new(root, self.corpus.dnm_parameters.clone()));
}
}
let tokenizer = &self.corpus.tokenizer;
let sentences = tokenizer.sentences(self.dnm.as_ref().unwrap());
SentenceIterator {
walker: sentences.into_iter(),
document: self,
}
}
}
impl<'iter> Iterator for ParagraphIterator<'iter> {
type Item = Paragraph<'iter>;
fn next(&mut self) -> Option<Paragraph<'iter>> {
match self.walker.next() {
None => None,
Some(node) => {
let dnm = DNM::new(node, DNMParameters::llamapun_normalization());
Some(Paragraph {
dnm,
document: self.document,
})
},
}
}
}
impl<'p> Paragraph<'p> {
pub fn iter(&'p mut self) -> SentenceIterator<'p> {
let tokenizer = &self.document.corpus.tokenizer;
let sentences = tokenizer.sentences(&self.dnm);
SentenceIterator {
walker: sentences.into_iter(),
document: self.document,
}
}
}
impl<'iter> Iterator for SentenceIterator<'iter> {
type Item = Sentence<'iter>;
fn next(&mut self) -> Option<Sentence<'iter>> {
match self.walker.next() {
None => None,
Some(range) => {
if range.is_empty() {
self.next()
} else {
let sentence = Sentence {
range,
document: self.document,
senna_sentence: None,
};
Some(sentence)
}
},
}
}
}
impl<'s> Sentence<'s> {
pub fn simple_iter(&'s mut self) -> SimpleWordIterator<'s> {
let tokenizer = &self.document.corpus.tokenizer;
let words = tokenizer.words(&self.range);
SimpleWordIterator {
walker: words.into_iter(),
sentence: self,
}
}
pub fn senna_iter(&'s mut self) -> SennaWordIterator<'s> {
SennaWordIterator {
pos: 0usize,
sentence: if self.senna_sentence.is_none() {
self.senna_parse()
} else {
self
},
}
}
pub fn senna_parse(&'s mut self) -> &Self {
self.senna_sentence = Some(self.document.corpus.senna.borrow_mut().parse(
self.range.get_plaintext(),
self.document.corpus.senna_options.get(),
));
self
}
}
impl<'iter> Iterator for SimpleWordIterator<'iter> {
type Item = Word<'iter>;
fn next(&mut self) -> Option<Word<'iter>> {
match self.walker.next() {
None => None,
Some(range) => Some(Word {
range,
sentence: self.sentence,
pos: POS::NOT_SET,
}),
}
}
}
impl<'iter> Iterator for SennaWordIterator<'iter> {
type Item = Word<'iter>;
fn next(&mut self) -> Option<Word<'iter>> {
let pos = self.pos;
self.pos += 1;
let sent = &self.sentence;
let sen_sent_wrapped = &sent.senna_sentence;
let sen_sent = sen_sent_wrapped.as_ref().unwrap();
if pos < sen_sent.get_words().len() {
let senna_word = &sen_sent.get_words()[pos];
let range = self
.sentence
.range
.get_subrange_from_byte_offsets(senna_word.get_offset_start(), senna_word.get_offset_end());
Some(Word {
range,
sentence: self.sentence,
pos: senna_word.get_pos(),
})
} else {
None
}
}
}