Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

parse_marc.rs 7.8 KB

You have to be logged in to leave a comment. Sign In
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
  1. use std::io::prelude::*;
  2. use std::io::{self, BufReader, BufWriter};
  3. use std::fs::File;
  4. use std::path::PathBuf;
  5. use std::str;
  6. use log::*;
  7. use sha1::Sha1;
  8. use glob::glob;
  9. use structopt::StructOpt;
  10. use quick_xml::Reader;
  11. use quick_xml::events::Event;
  12. use flate2::bufread::MultiGzDecoder;
  13. use indicatif::{ProgressBar, ProgressStyle};
  14. use anyhow::{Result, anyhow};
  15. use happylog::set_progress;
  16. use crate::cleaning::write_pgencoded;
  17. use crate::tsv::split_first;
  18. use crate::tracking::StageOpts;
  19. use crate::io::{HashWrite};
  20. use crate::db::{DbOpts, CopyRequest};
  21. use super::Command;
  22. /// Parse MARC files into records for a PostgreSQL table.
  23. #[derive(StructOpt, Debug)]
  24. #[structopt(name="parse-marc")]
  25. pub struct ParseMarc {
  26. #[structopt(flatten)]
  27. db: DbOpts,
  28. #[structopt(flatten)]
  29. stage: StageOpts,
  30. #[structopt(short="-t", long="table")]
  31. table: String,
  32. #[structopt(long="truncate")]
  33. truncate: bool,
  34. /// Activate line mode, e.g. for VIAF
  35. #[structopt(short="L", long="line-mode")]
  36. linemode: bool,
  37. #[structopt(long="src-dir")]
  38. src_dir: Option<PathBuf>,
  39. #[structopt(long="src-prefix")]
  40. src_prefix: Option<String>,
  41. /// Input files to parse (GZ-compressed)
  42. #[structopt(name = "FILE", parse(from_os_str))]
  43. files: Vec<PathBuf>
  44. }
  45. struct Field<'a> {
  46. ind1: &'a [u8],
  47. ind2: &'a [u8],
  48. code: &'a [u8]
  49. }
  50. /// Process a tab-delimited line file. VIAF provides their files in this format;
  51. /// each line is a tab-separated pair of the VIAF ID and a single `record` instance.
  52. fn process_delim_file<R: BufRead, W: Write>(r: &mut R, w: &mut W, init: usize) -> Result<usize> {
  53. let mut rec_count = 0;
  54. for line in r.lines() {
  55. let lstr = line?;
  56. let (_id, xml) = split_first(&lstr).ok_or(anyhow!("invalid line"))?;
  57. let mut parse = Reader::from_str(xml);
  58. let n = process_records(&mut parse, w, init + rec_count)?;
  59. // we should only have one record per file
  60. assert_eq!(n, 1);
  61. rec_count += n;
  62. }
  63. Ok(rec_count)
  64. }
  65. /// Process a file containing a MARC collection.
  66. fn process_marc_file<R: BufRead, W: Write>(r: &mut R, w: &mut W, init: usize) -> Result<usize> {
  67. let mut parse = Reader::from_reader(r);
  68. let count = process_records(&mut parse, w, init)?;
  69. Ok(count)
  70. }
  71. fn write_codes<W: Write>(w: &mut W, rno: usize, fno: i32, tag: &[u8], fld: Option<&Field>) -> Result<()> {
  72. let ids = format!("{}\t{}\t", rno, fno);
  73. w.write_all(ids.as_str().as_bytes())?;
  74. w.write_all(tag)?;
  75. w.write_all(b"\t")?;
  76. match fld {
  77. Some(f) => {
  78. w.write_all(f.ind1)?;
  79. w.write_all(b"\t")?;
  80. w.write_all(f.ind2)?;
  81. w.write_all(b"\t")?;
  82. w.write_all(f.code)?;
  83. w.write_all(b"\t")?;
  84. },
  85. None => {
  86. w.write_all(b"\\N\t\\N\t\\N\t")?;
  87. }
  88. }
  89. Ok(())
  90. }
  91. fn write_nl<W: Write>(w: &mut W) -> io::Result<()> {
  92. w.write_all(b"\n")
  93. }
  94. fn process_records<B: BufRead, W: Write>(rdr: &mut Reader<B>, out: &mut W, start: usize) -> Result<usize> {
  95. let mut buf = Vec::new();
  96. let mut output = false;
  97. let mut fno = 0;
  98. let mut tag = Vec::with_capacity(5);
  99. let mut ind1 = Vec::with_capacity(10);
  100. let mut ind2 = Vec::with_capacity(10);
  101. let mut recid = start;
  102. loop {
  103. match rdr.read_event(&mut buf)? {
  104. Event::Start(ref e) => {
  105. let name = str::from_utf8(e.local_name())?;
  106. match name {
  107. "record" => {
  108. recid += 1
  109. },
  110. "leader" => {
  111. write_codes(out, recid, fno, b"LDR", None)?;
  112. output = true;
  113. },
  114. "controlfield" => {
  115. fno += 1;
  116. let mut done = false;
  117. for ar in e.attributes() {
  118. let a = ar?;
  119. if a.key == b"tag" {
  120. let tag = a.unescaped_value()?;
  121. write_codes(out, recid, fno, &tag, None)?;
  122. done = true;
  123. }
  124. }
  125. assert!(done, "no tag found for control field");
  126. output = true;
  127. },
  128. "datafield" => {
  129. fno += 1;
  130. for ar in e.attributes() {
  131. let a = ar?;
  132. let v = a.unescaped_value()?;
  133. match a.key {
  134. b"tag" => tag.extend_from_slice(&*v),
  135. b"ind1" => ind1.extend_from_slice(&*v),
  136. b"ind2" => ind2.extend_from_slice(&*v),
  137. _ => ()
  138. }
  139. }
  140. assert!(tag.len() > 0, "no tag found for data field");
  141. assert!(ind1.len() > 0, "no ind1 found for data field");
  142. assert!(ind2.len() > 0, "no ind2 found for data field");
  143. },
  144. "subfield" => {
  145. let mut done = false;
  146. for ar in e.attributes() {
  147. let a = ar?;
  148. if a.key == b"code" {
  149. let code = a.unescaped_value()?;
  150. let field = Field { ind1: &ind1, ind2: &ind2, code: &code };
  151. write_codes(out, recid, fno, &tag, Some(&field))?;
  152. done = true;
  153. }
  154. }
  155. assert!(done, "no code found for subfield");
  156. output = true;
  157. }
  158. _ => ()
  159. }
  160. },
  161. Event::End(ref e) => {
  162. let name = str::from_utf8(e.local_name())?;
  163. match name {
  164. "leader" | "controlfield" | "subfield" => {
  165. write_nl(out)?;
  166. output = false;
  167. },
  168. "datafield" => {
  169. tag.clear();
  170. ind1.clear();
  171. ind2.clear();
  172. },
  173. _ => ()
  174. }
  175. },
  176. Event::Text(e) => {
  177. if output {
  178. let t = e.unescaped()?;
  179. write_pgencoded(out, &t)?
  180. }
  181. },
  182. Event::Eof => break,
  183. _ => ()
  184. }
  185. }
  186. Ok(recid - start)
  187. }
  188. impl Command for ParseMarc {
  189. fn exec(self) -> Result<()> {
  190. let db = self.db.open()?;
  191. let req = CopyRequest::new(&self.db, &self.table)?;
  192. let req = req.with_schema(self.db.schema());
  193. let req = req.truncate(self.truncate);
  194. let out = req.open()?;
  195. let mut out_h = Sha1::new();
  196. let out = HashWrite::create(out, &mut out_h);
  197. let mut out = BufWriter::new(out);
  198. let mut stage = self.stage.begin_stage(&db)?;
  199. let mut count = 0;
  200. for inf in self.find_files()? {
  201. let inf = inf.as_path();
  202. info!("reading from compressed file {:?}", inf);
  203. let fs = File::open(inf)?;
  204. let pb = ProgressBar::new(fs.metadata()?.len());
  205. pb.set_style(ProgressStyle::default_bar().template("{elapsed_precise} {bar} {percent}% {bytes}/{total_bytes} (eta: {eta})"));
  206. let _pbs = set_progress(&pb);
  207. let mut in_sf = stage.source_file(inf);
  208. let pbr = pb.wrap_read(fs);
  209. let pbr = BufReader::new(pbr);
  210. let gzf = MultiGzDecoder::new(pbr);
  211. let gzf = in_sf.wrap_read(gzf);
  212. let mut bfs = BufReader::new(gzf);
  213. let nrecs = if self.linemode {
  214. process_delim_file(&mut bfs, &mut out, count)
  215. } else {
  216. process_marc_file(&mut bfs, &mut out, count)
  217. };
  218. drop(bfs);
  219. match nrecs {
  220. Ok(n) => {
  221. info!("processed {} records from {:?}", n, inf);
  222. let hash = in_sf.record()?;
  223. writeln!(&mut stage, "READ {:?} {} {}", inf, n, hash)?;
  224. count += n;
  225. },
  226. Err(e) => {
  227. error!("error in {:?}: {}", inf, e);
  228. return Err(e)
  229. }
  230. }
  231. }
  232. drop(out);
  233. let out_h = out_h.hexdigest();
  234. writeln!(&mut stage, "COPY {}", out_h)?;
  235. stage.end(&Some(out_h))?;
  236. Ok(())
  237. }
  238. }
  239. impl ParseMarc {
  240. fn find_files(&self) -> Result<Vec<PathBuf>> {
  241. if let Some(ref dir) = self.src_dir {
  242. let mut ds = dir.to_str().unwrap().to_string();
  243. if let Some(ref pfx) = self.src_prefix {
  244. ds.push_str("/");
  245. ds.push_str(pfx);
  246. ds.push_str("*.xml.gz");
  247. } else {
  248. ds.push_str("/*.xml.gz");
  249. }
  250. info!("scanning for files {}", ds);
  251. let mut v = Vec::new();
  252. for entry in glob(&ds)? {
  253. let entry = entry?;
  254. v.push(entry);
  255. }
  256. Ok(v)
  257. } else {
  258. Ok(self.files.clone())
  259. }
  260. }
  261. }
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...