bookdata/cli/
filter_marc.rs

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
//! Command to filter MARC output.
use std::fs::File;
use std::path::{Path, PathBuf};
use std::sync::Arc;

use arrow::array::StringBuilder;
use arrow::array::UInt32Builder;
use arrow::datatypes::{DataType, Field, Schema};
use arrow::record_batch::RecordBatch;
use friendly::scalar;
use parquet::arrow::ArrowWriter;

use crate::arrow::scan_parquet_file;
use crate::arrow::writer::parquet_writer_defaults;
use crate::io::object::{ThreadObjectWriter, UnchunkWriter};
use crate::marc::flat_fields::FieldRecord;
use crate::prelude::*;

const BATCH_SIZE: usize = 1024 * 1024;

/// Filter a MARC field file to only contain certain results.
#[derive(Args, Debug)]
#[command(name = "filter-marc")]
pub struct FilterMARC {
    #[command(flatten)]
    filter: FilterSpec,

    #[command(flatten)]
    output: OutputSpec,

    /// Input file of MARC field data.
    #[arg(name = "FIELD_FILE")]
    field_file: PathBuf,
}

/// Options for filtering MARC records.
#[derive(Args, Debug, Clone)]
struct FilterSpec {
    /// Specify the tag to filter to.
    #[arg(short = 't', long = "tag", name = "TAG")]
    tag: Option<i16>,

    /// Specify the subfield to filter to.
    #[arg(short = 'f', long = "subfield", name = "CODE")]
    subfield: Option<char>,

    /// Trim the contents before emitting.
    #[arg(short = 'T', long = "trim")]
    trim: bool,

    /// Lowercase the contents before emitting.
    #[arg(short = 'L', long = "lower")]
    lower: bool,
}

/// Options for output.
#[derive(Args, Debug, Clone)]
struct OutputSpec {
    /// Rename the content field.
    #[arg(short = 'n', long = "name", name = "FIELD")]
    content_name: Option<String>,

    /// Output file for filtered MARC fields.
    #[arg(short = 'o', long = "output", name = "FILE")]
    file: PathBuf,
}

impl FilterSpec {
    fn matches(&self, rec: &FieldRecord) -> bool {
        if let Some(t) = &self.tag {
            if rec.tag != *t {
                return false;
            }
        }

        if let Some(sf) = &self.subfield {
            if rec.sf_code != (*sf as u8) {
                return false;
            }
        }

        true
    }

    fn transform<'a>(&self, value: &'a str) -> Cow<'a, str> {
        let content: Cow<'a, str> = if self.trim {
            value.trim().into()
        } else {
            value.into()
        };

        let content: Cow<'a, str> = if self.lower {
            content.to_lowercase().into()
        } else {
            content
        };

        content
    }
}

struct FilterOutput<W: ObjectWriter<RecordBatch>> {
    schema: Arc<Schema>,
    writer: W,
}

impl<W: ObjectWriter<RecordBatch>> ObjectWriter<Vec<FieldRecord>> for FilterOutput<W> {
    fn write_object(&mut self, object: Vec<FieldRecord>) -> Result<()> {
        let size = object.len();

        let mut id_col = UInt32Builder::with_capacity(size);
        let mut val_col = StringBuilder::with_capacity(size, size * 10);

        for rec in object {
            id_col.append_value(rec.rec_id);
            val_col.append_value(rec.contents);
        }

        let id_col = id_col.finish();
        let val_col = val_col.finish();
        let batch = RecordBatch::try_new(
            self.schema.clone(),
            vec![Arc::new(id_col), Arc::new(val_col)],
        )?;

        self.writer.write_object(batch)?;
        Ok(())
    }

    fn finish(self) -> Result<usize> {
        self.writer.finish()
    }
}

/// Scan MARC records from a file.
///
/// Failes quickly if there is an error opening the file; errors reading the file are
/// from the thread and are availabl when it is joined.
fn scan_records(
    path: &Path,
    filter: &FilterSpec,
    out: impl ObjectWriter<FieldRecord> + Send,
) -> Result<(usize, usize)> {
    info!("reading names from authority fields in {:?}", path);
    let scanner = scan_parquet_file(path)?;
    let mut out = out;

    let scanner = scanner;
    let mut nr = 0;
    let mut nw = 0;
    for rec in scanner {
        nr += 1;
        let mut rec: FieldRecord = rec?;
        if filter.matches(&rec) {
            nw += 1;
            rec.contents = filter.transform(rec.contents.as_str()).into();
            out.write_object(rec)?;
        }
    }
    debug!("finished scanning parquet");
    out.finish()?;
    Ok((nr, nw))
}

/// Create an output for the records.
fn open_output(out: &OutputSpec) -> Result<impl ObjectWriter<FieldRecord> + Send> {
    info!("writing output to {:?}", out.file);
    let out_name = out
        .content_name
        .as_ref()
        .map(|s| s.clone())
        .unwrap_or("content".into());
    let schema = Schema::new(vec![
        Field::new("rec_id", DataType::UInt32, false),
        Field::new(&out_name, DataType::Utf8, false),
    ]);
    let schema = Arc::new(schema);

    // we'll open the file early, so bg open failures are only in Parquet.
    let file = File::options()
        .create(true)
        .truncate(true)
        .write(true)
        .open(&out.file)?;

    let writer = ThreadObjectWriter::bg_open(move || {
        let props = parquet_writer_defaults().set_column_dictionary_enabled(out_name.into(), true);
        let writer = ArrowWriter::try_new(file, schema.clone(), Some(props.build()))?;
        Ok(FilterOutput { schema, writer })
    })
    .spawn();
    let writer = UnchunkWriter::with_size(writer, BATCH_SIZE);

    Ok(writer)
}

impl Command for FilterMARC {
    fn exec(&self) -> Result<()> {
        let out = open_output(&self.output)?;
        let (nr, nw) = scan_records(self.field_file.as_path(), &self.filter, out)?;

        info!("wrote {} out of {} records", scalar(nw), scalar(nr));

        Ok(())
    }
}