bookdata/cli/
collect_isbns.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
//! Collect ISBNs from across the data sources.
use std::fmt::Debug;

use fallible_iterator::IteratorExt;
use polars::prelude::*;

use crate::prelude::Result;
use crate::prelude::*;

/// Collect ISBNs from across the data sources.
#[derive(Args, Debug)]
#[command(name = "collect-isbns")]
pub struct CollectISBNs {
    /// Path to the output file (in Parquet format)
    #[arg(short = 'o', long = "output")]
    out_file: PathBuf,
}

/// Get the active ISBN layouts.
///
/// Modify this function to add more sources.
fn all_sources(cfg: &Config) -> Vec<ISBNSource> {
    vec![
        ISBNSource::new("LOC")
            .path("../loc-mds/book-isbns.parquet")
            .finish(),
        ISBNSource::new("OL")
            .path("../openlibrary/edition-isbns.parquet")
            .finish(),
        ISBNSource::new("GR")
            .enabled(cfg.goodreads.enabled)
            .path("../goodreads/gr-book-ids.parquet")
            .columns(&["isbn10", "isbn13", "asin"])
            .finish(),
        ISBNSource::new("BX")
            .enabled(cfg.bx.enabled)
            .path("../bx/cleaned-ratings.csv")
            .finish(),
        ISBNSource::new("AZ14")
            .enabled(cfg.az2014.enabled)
            .path("../az2014/ratings.parquet")
            .column("asin")
            .finish(),
        ISBNSource::new("AZ18")
            .enabled(cfg.az2018.enabled)
            .path("../az2018/ratings.parquet")
            .column("asin")
            .finish(),
    ]
}

#[derive(Debug, Clone)]
struct ISBNSource {
    name: &'static str,
    enabled: bool,
    path: &'static str,
    columns: Vec<&'static str>,
}

impl ISBNSource {
    fn new(name: &'static str) -> ISBNSource {
        ISBNSource {
            name: name,
            enabled: true,
            path: "",
            columns: vec![],
        }
    }

    fn enabled(self, e: bool) -> ISBNSource {
        ISBNSource { enabled: e, ..self }
    }

    fn path(self, path: &'static str) -> ISBNSource {
        ISBNSource { path, ..self }
    }

    fn column(self, col: &'static str) -> ISBNSource {
        ISBNSource {
            columns: vec![col],
            ..self
        }
    }

    fn columns(self, cols: &[&'static str]) -> ISBNSource {
        ISBNSource {
            columns: cols.iter().map(|s| *s).collect(),
            ..self
        }
    }

    fn finish(self) -> ISBNSource {
        ISBNSource {
            columns: if self.columns.len() > 0 {
                self.columns
            } else {
                vec!["isbn".into()]
            },
            ..self
        }
    }
}

/// Read a single ISBN source into the accumulator.
fn scan_source(src: &ISBNSource) -> Result<LazyFrame> {
    info!("scanning ISBNs from {}", src.path);

    let read = if src.path.ends_with(".csv") {
        LazyCsvReader::new(src.path.to_string())
            .has_header(true)
            .finish()?
    } else {
        scan_df_parquet(src.path)?
    };

    let mut counted: Option<LazyFrame> = None;
    for id_col in &src.columns {
        info!("counting column {}", id_col);
        let df = read.clone().select(&[col(id_col).alias("isbn")]);
        let df = df.drop_nulls(None);
        let df = df.group_by(["isbn"]).agg([len().alias("nrecs")]);
        if let Some(prev) = counted {
            let joined = prev.join(
                df,
                [col("isbn")],
                [col("isbn")],
                JoinArgs::new(JoinType::Outer { coalesce: true }),
            );
            counted = Some(joined.select([
                col("isbn"),
                (col(src.name).fill_null(0) + col("nrecs").fill_null(0)).alias(src.name),
            ]));
        } else {
            counted = Some(df.select([col("isbn"), col("nrecs").alias(src.name)]));
        }
    }

    Ok(counted.expect("data frame with no columns"))
}

impl Command for CollectISBNs {
    fn exec(&self) -> Result<()> {
        let cfg = load_config()?;
        let sources = all_sources(&cfg);
        let active: Vec<_> = sources.iter().filter(|s| s.enabled).collect();
        info!(
            "preparing to collect ISBNs from {} active sources (of {} known)",
            active.len(),
            sources.len()
        );

        let df = active
            .iter()
            .map(|s| scan_source(*s))
            .transpose_into_fallible()
            .fold(None, |cur: Option<LazyFrame>, df2| {
                let out = if let Some(df1) = cur {
                    df1.join(
                        df2.clone(),
                        [col("isbn")],
                        [col("isbn")],
                        JoinArgs::new(JoinType::Outer { coalesce: true }),
                    )
                } else {
                    df2
                };
                debug!("join result schema:\n{:?}", out.schema()?);
                debug!("join result plan:\n{:?}", out.logical_plan);
                Ok(Some(out))
            })?;

        let df = df.ok_or_else(|| anyhow!("no sources loaded"))?;
        let df = df.with_row_index("isbn_id", Some(1));
        let mut cast = vec![col("isbn_id").cast(DataType::Int32), col("isbn")];
        for src in &active {
            cast.push(col(src.name).fill_null(0));
        }
        let df = df.select(&cast);
        info!("collecting ISBNs");
        let df = df.collect()?;

        info!(
            "saving {} ISBNs to {}",
            df.height(),
            self.out_file.display()
        );
        save_df_parquet(df, &self.out_file)?;
        info!("wrote ISBN collection file");

        Ok(())
    }
}