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 6.1 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
  1. extern crate structopt;
  2. extern crate quick_xml;
  3. extern crate flate2;
  4. extern crate indicatif;
  5. extern crate bookdata;
  6. use std::io::prelude::*;
  7. use std::io::{self, BufReader};
  8. use std::fs::File;
  9. use std::path::PathBuf;
  10. use std::str;
  11. use structopt::StructOpt;
  12. use quick_xml::Reader;
  13. use quick_xml::events::Event;
  14. use flate2::bufread::MultiGzDecoder;
  15. use indicatif::{ProgressBar, ProgressStyle};
  16. use bookdata::{Result, err};
  17. use bookdata::cleaning::write_pgencoded;
  18. use bookdata::tsv::split_first;
  19. /// Parse MARC files into records for a PostgreSQL table.
  20. #[derive(StructOpt, Debug)]
  21. #[structopt(name="parse-marc")]
  22. struct Opt {
  23. /// Activate line mode, e.g. for VIAF
  24. #[structopt(short="L", long="line-mode")]
  25. linemode: bool,
  26. /// Input files to parse (GZ-compressed)
  27. #[structopt(name = "FILE", parse(from_os_str))]
  28. files: Vec<PathBuf>
  29. }
  30. struct Field<'a> {
  31. ind1: &'a [u8],
  32. ind2: &'a [u8],
  33. code: &'a [u8]
  34. }
  35. /// Process a tab-delimited line file. VIAF provides their files in this format;
  36. /// each line is a tab-separated pair of the VIAF ID and a single `record` instance.
  37. fn process_delim_file<R: BufRead, W: Write>(r: &mut R, w: &mut W, init: usize) -> Result<usize> {
  38. let mut rec_count = 0;
  39. for line in r.lines() {
  40. let lstr = line?;
  41. let (_id, xml) = split_first(&lstr).ok_or(err("invalid line"))?;
  42. let mut parse = Reader::from_str(xml);
  43. let n = process_records(&mut parse, w, init + rec_count)?;
  44. // we should only have one record per file
  45. assert_eq!(n, 1);
  46. rec_count += n;
  47. }
  48. Ok(rec_count)
  49. }
  50. /// Process a file containing a MARC collection.
  51. fn process_marc_file<R: BufRead, W: Write>(r: &mut R, w: &mut W, init: usize) -> Result<usize> {
  52. let mut parse = Reader::from_reader(r);
  53. let count = process_records(&mut parse, w, init)?;
  54. Ok(count)
  55. }
  56. fn write_codes<W: Write>(w: &mut W, rno: usize, fno: i32, tag: &[u8], fld: Option<&Field>) -> Result<()> {
  57. let ids = format!("{}\t{}\t", rno, fno);
  58. w.write_all(ids.as_str().as_bytes())?;
  59. w.write_all(tag)?;
  60. w.write_all(b"\t")?;
  61. match fld {
  62. Some(f) => {
  63. w.write_all(f.ind1)?;
  64. w.write_all(b"\t")?;
  65. w.write_all(f.ind2)?;
  66. w.write_all(b"\t")?;
  67. w.write_all(f.code)?;
  68. w.write_all(b"\t")?;
  69. },
  70. None => {
  71. w.write_all(b"\\N\t\\N\t\\N\t")?;
  72. }
  73. }
  74. Ok(())
  75. }
  76. fn write_nl<W: Write>(w: &mut W) -> io::Result<()> {
  77. w.write_all(b"\n")
  78. }
  79. fn process_records<B: BufRead, W: Write>(rdr: &mut Reader<B>, out: &mut W, start: usize) -> Result<usize> {
  80. let mut buf = Vec::new();
  81. let mut output = false;
  82. let mut fno = 0;
  83. let mut tag = Vec::with_capacity(5);
  84. let mut ind1 = Vec::with_capacity(10);
  85. let mut ind2 = Vec::with_capacity(10);
  86. let mut recid = start;
  87. loop {
  88. match rdr.read_event(&mut buf)? {
  89. Event::Start(ref e) => {
  90. let name = str::from_utf8(e.local_name())?;
  91. match name {
  92. "record" => {
  93. recid += 1
  94. },
  95. "leader" => {
  96. write_codes(out, recid, fno, b"LDR", None)?;
  97. output = true;
  98. },
  99. "controlfield" => {
  100. fno += 1;
  101. let mut done = false;
  102. for ar in e.attributes() {
  103. let a = ar?;
  104. if a.key == b"tag" {
  105. let tag = a.unescaped_value()?;
  106. write_codes(out, recid, fno, &tag, None)?;
  107. done = true;
  108. }
  109. }
  110. assert!(done, "no tag found for control field");
  111. output = true;
  112. },
  113. "datafield" => {
  114. fno += 1;
  115. for ar in e.attributes() {
  116. let a = ar?;
  117. let v = a.unescaped_value()?;
  118. match a.key {
  119. b"tag" => tag.extend_from_slice(&*v),
  120. b"ind1" => ind1.extend_from_slice(&*v),
  121. b"ind2" => ind2.extend_from_slice(&*v),
  122. _ => ()
  123. }
  124. }
  125. assert!(tag.len() > 0, "no tag found for data field");
  126. assert!(ind1.len() > 0, "no ind1 found for data field");
  127. assert!(ind2.len() > 0, "no ind2 found for data field");
  128. },
  129. "subfield" => {
  130. let mut done = false;
  131. for ar in e.attributes() {
  132. let a = ar?;
  133. if a.key == b"code" {
  134. let code = a.unescaped_value()?;
  135. let field = Field { ind1: &ind1, ind2: &ind2, code: &code };
  136. write_codes(out, recid, fno, &tag, Some(&field))?;
  137. done = true;
  138. }
  139. }
  140. assert!(done, "no code found for subfield");
  141. output = true;
  142. }
  143. _ => ()
  144. }
  145. },
  146. Event::End(ref e) => {
  147. let name = str::from_utf8(e.local_name())?;
  148. match name {
  149. "leader" | "controlfield" | "subfield" => {
  150. write_nl(out)?;
  151. output = false;
  152. },
  153. "datafield" => {
  154. tag.clear();
  155. ind1.clear();
  156. ind2.clear();
  157. },
  158. _ => ()
  159. }
  160. },
  161. Event::Text(e) => {
  162. if output {
  163. let t = e.unescaped()?;
  164. write_pgencoded(out, &t)?
  165. }
  166. },
  167. Event::Eof => break,
  168. _ => ()
  169. }
  170. }
  171. Ok(recid - start)
  172. }
  173. fn main() -> Result<()> {
  174. let opt = Opt::from_args();
  175. let out = io::stdout();
  176. let mut outlock = out.lock();
  177. let mut count = 0;
  178. for inf in opt.files {
  179. let inf = inf.as_path();
  180. eprintln!("reading from compressed file {:?}", inf);
  181. let fs = File::open(inf)?;
  182. let pb = ProgressBar::new(fs.metadata()?.len());
  183. pb.set_style(ProgressStyle::default_bar().template("{elapsed_precise} {bar} {percent}% {bytes}/{total_bytes} (eta: {eta})"));
  184. let pbr = pb.wrap_read(fs);
  185. let pbr = BufReader::new(pbr);
  186. let gzf = MultiGzDecoder::new(pbr);
  187. let mut bfs = BufReader::new(gzf);
  188. let nrecs = if opt.linemode {
  189. process_delim_file(&mut bfs, &mut outlock, count)
  190. } else {
  191. process_marc_file(&mut bfs, &mut outlock, count)
  192. };
  193. match nrecs {
  194. Ok(n) => {
  195. eprintln!("processed {} records from {:?}", n, inf);
  196. count += n;
  197. },
  198. Err(e) => {
  199. eprintln!("error in {:?}: {}", inf, e);
  200. return Err(e)
  201. }
  202. }
  203. }
  204. Ok(())
  205. }
Tip!

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

Comments

Loading...