datavzrd 2.75.2

A tool to create visual HTML reports from collections of CSV/TSV tables
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
398
399
400
401
402
403
404
use crate::llm::{self, ColumnContext, Draft, LlmConfig};
use anyhow::{Context, Result};
use datavzrd::spec::{
    default_page_size, Color, ColorRange, DatasetSpecs, ItemSpecs, ItemsSpec, PlotSpec,
    RenderColumnSpec, RenderTableSpecs, ScaleType,
};
use datavzrd::utils::column_type::{ColumnType, IsNa};
use log::warn;
use std::collections::HashMap;
use std::path::PathBuf;

const MAX_EXAMPLES: usize = 2;
const EXAMPLE_MAX_CHARS: usize = 25;

pub(crate) fn suggest(
    files: Vec<PathBuf>,
    separator: Vec<char>,
    name: String,
    llm: Option<LlmConfig>,
) -> Result<String> {
    let mut items_spec = ItemsSpec::new(name);
    let mut dataset_names = Vec::new();
    for (file, sep) in files.iter().zip(separator.iter()) {
        let dataset = DatasetSpecs {
            path: file.to_owned(),
            separator: sep.to_owned(),
            header_rows: 1,
            links: None,
            offer_excel: false,
        };
        let dataset_name = file
            .file_stem()
            .and_then(|stem| stem.to_str())
            .with_context(|| format!("Could not derive a dataset name from {}", file.display()))?
            .to_string();
        items_spec
            .datasets
            .insert(dataset_name.clone(), dataset.clone());
        dataset.reader()?.validate()?;
        let column_types = datavzrd::utils::column_type::classify_table(&dataset, true)?;
        let mut columns: HashMap<String, RenderColumnSpec> = column_types
            .iter()
            .map(|(name, column_type)| (name.to_string(), baseline_column(column_type)))
            .collect();
        if let Some(llm) = &llm {
            let contexts = build_contexts(&dataset, &column_types)?;
            // Retry once
            let draft = llm::request_draft(llm, &contexts)
                .or_else(|_| llm::request_draft(llm, &contexts))?;
            apply_draft(
                draft,
                &mut items_spec.report_name,
                &dataset_name,
                &dataset,
                &column_types,
                &mut columns,
            );
        }
        items_spec
            .views
            .insert(dataset_name.clone(), make_view(&dataset_name, columns));
        dataset_names.push(dataset_name);
    }
    let mut config = serde_yaml::to_value(&items_spec)?;
    for name in &dataset_names {
        let headers = items_spec.datasets[name].reader()?.headers()?;
        sort_keys(
            &mut config["views"][name.as_str()]["render-table"]["columns"],
            &headers,
        );
    }
    sort_keys(&mut config["datasets"], &dataset_names);
    sort_keys(&mut config["views"], &dataset_names);
    Ok(serde_yaml::to_string(&config)?)
}

fn sort_keys(value: &mut serde_yaml::Value, order: &[String]) {
    if let Some(mapping) = value.as_mapping_mut() {
        let mut entries = std::mem::take(mapping).into_iter().collect::<Vec<_>>();
        entries.sort_by_key(|(key, _)| {
            order
                .iter()
                .position(|name| key.as_str() == Some(name.as_str()))
        });
        *mapping = entries.into_iter().collect();
    }
}

fn apply_draft(
    draft: Draft,
    report_name: &mut String,
    dataset_name: &str,
    dataset: &DatasetSpecs,
    column_types: &HashMap<String, ColumnType>,
    columns: &mut HashMap<String, RenderColumnSpec>,
) {
    if let Some(name) = draft.report_name.filter(|name| !name.trim().is_empty()) {
        *report_name = name;
    }
    let suggested: Vec<(String, RenderColumnSpec)> = draft
        .columns
        .into_iter()
        .filter_map(|(name, value)| {
            if !columns.contains_key(&name) {
                warn!("ignoring suggestion for unknown column {name:?}");
                return None;
            }
            match serde_json::from_value(value) {
                Ok(mut spec) => {
                    fill_default_colors(&mut spec, &column_types[&name]);
                    Some((name, spec))
                }
                Err(error) => {
                    warn!("column {name:?} fell back to the default because its suggested configuration could not be parsed: {error}");
                    None
                }
            }
        })
        .collect();

    // Keep each suggestion only if it still validates alongside the rest, else revert to the baseline column.
    for (name, spec) in suggested {
        let baseline = columns.insert(name.clone(), spec);
        if validate_columns(report_name, dataset_name, dataset, columns).is_err() {
            let rejected = serde_yaml::to_string(&columns[&name]).unwrap_or_default();
            warn!("column {name:?} fell back to the default because its suggested configuration was invalid. The rejected configuration was:\n{rejected}");
            if let Some(baseline) = baseline {
                columns.insert(name, baseline);
            }
        }
    }
}

fn validate_columns(
    report_name: &str,
    dataset_name: &str,
    dataset: &DatasetSpecs,
    columns: &HashMap<String, RenderColumnSpec>,
) -> Result<()> {
    let mut items_spec = ItemsSpec::new(report_name.to_string());
    items_spec
        .datasets
        .insert(dataset_name.to_string(), dataset.clone());
    items_spec.views.insert(
        dataset_name.to_string(),
        make_view(dataset_name, columns.clone()),
    );
    items_spec.preprocess()?;
    items_spec.validate()
}

fn make_view(dataset_name: &str, columns: HashMap<String, RenderColumnSpec>) -> ItemSpecs {
    ItemSpecs {
        hidden: false,
        narrow: false,
        dataset: Some(dataset_name.to_string()),
        datasets: None,
        page_size: default_page_size(),
        single_page_page_size: default_page_size(),
        description: None,
        render_table: Some(RenderTableSpecs {
            columns,
            additional_columns: None,
            headers: None,
        }),
        render_plot: None,
        render_html: None,
        render_img: None,
        max_in_memory_rows: None,
        spell: None,
    }
}

fn build_contexts(
    dataset: &DatasetSpecs,
    column_types: &HashMap<String, ColumnType>,
) -> Result<Vec<ColumnContext>> {
    let mut reader = dataset.reader()?;
    let headers = reader.headers()?.clone();
    let mut examples: HashMap<String, Vec<String>> = headers
        .iter()
        .map(|h| (h.to_string(), Vec::new()))
        .collect();
    let mut ranges: HashMap<String, (f64, f64)> = HashMap::new();
    for record in dataset.records()? {
        for (header, value) in headers.iter().zip(record.iter()) {
            if value.is_na() {
                continue;
            }
            let seen = examples.get_mut(header).unwrap();
            if seen.len() < MAX_EXAMPLES && !seen.iter().any(|example| example == value) {
                seen.push(value.to_string());
            }
            if let Ok(number) = value.parse::<f64>() {
                let range = ranges.entry(header.to_string()).or_insert((number, number));
                range.0 = range.0.min(number);
                range.1 = range.1.max(number);
            }
        }
    }
    Ok(headers
        .iter()
        .map(|header| {
            let mut description = column_types[header].to_string();
            if let Some((min, max)) = ranges.get(header) {
                description += &format!(", range {min}..{max}");
            }
            let seen = &examples[header];
            if !seen.is_empty() {
                let previews = seen
                    .iter()
                    .map(|value| {
                        let preview: String = value.chars().take(EXAMPLE_MAX_CHARS).collect();
                        if value.chars().count() > EXAMPLE_MAX_CHARS {
                            format!("{preview}…")
                        } else {
                            preview
                        }
                    })
                    .collect::<Vec<_>>()
                    .join(", ");
                description += &format!(", e.g. {previews}");
            }
            ColumnContext {
                name: header.to_string(),
                description,
            }
        })
        .collect())
}

fn baseline_column(column_type: &ColumnType) -> RenderColumnSpec {
    let plot = match column_type {
        ColumnType::None => None,
        ColumnType::String => Some(PlotSpec::heatmap(
            ScaleType::Ordinal,
            "category20".to_string(),
            ColorRange::default(),
        )),
        ColumnType::Integer | ColumnType::Float => Some(PlotSpec::heatmap(
            ScaleType::Linear,
            String::new(),
            ColorRange(vec![Color("white".to_string()), Color("blue".to_string())]),
        )),
    };
    RenderColumnSpec {
        plot,
        ..RenderColumnSpec::default()
    }
}

/// Completes a suggested pills or heatmap plot that the model left uncolored with a
/// sensible default scheme (`category20` for categorical values, `blues` for numeric
/// ones), so the model's feature choice survives validation instead of falling back.
fn fill_default_colors(spec: &mut RenderColumnSpec, column_type: &ColumnType) {
    let Some(plot) = spec.plot.as_mut() else {
        return;
    };
    if let Some(pills) = plot.pills.as_mut() {
        if pills.color_scheme.is_empty() && pills.color_range.0.is_empty() {
            pills.color_scheme = "category20".to_string();
        }
    }
    if let Some(heatmap) = plot.heatmap.as_mut() {
        if heatmap.vega_type.is_none()
            && heatmap.color_scheme.is_empty()
            && heatmap.color_range.0.is_empty()
        {
            heatmap.color_scheme = match column_type {
                ColumnType::Integer | ColumnType::Float => "blues",
                _ => "category20",
            }
            .to_string();
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use anyhow::Result;
    use std::io::Write;
    use std::path::PathBuf;

    #[test]
    fn test_suggest() -> Result<()> {
        let files = vec![
            PathBuf::from(".examples/data/movies.csv"),
            PathBuf::from(".examples/data/oscars.csv"),
        ];
        let separators = vec![',', ','];
        let name = "Test Report".to_string();
        let result = suggest(files, separators, name, None);
        assert!(result.is_ok());
        let tmp = tempfile::NamedTempFile::new()?;
        tmp.as_file().write_all(result.unwrap().as_bytes())?;
        let config = ItemsSpec::from_file(tmp.path())?;
        assert!(config.validate().is_ok());
        Ok(())
    }

    fn movies() -> (
        DatasetSpecs,
        HashMap<String, ColumnType>,
        HashMap<String, RenderColumnSpec>,
    ) {
        let dataset = DatasetSpecs {
            path: PathBuf::from(".examples/data/movies.csv"),
            separator: ',',
            header_rows: 1,
            links: None,
            offer_excel: false,
        };
        let column_types = datavzrd::utils::column_type::classify_table(&dataset, true).unwrap();
        let columns = column_types
            .iter()
            .map(|(name, column_type)| (name.to_string(), baseline_column(column_type)))
            .collect();
        (dataset, column_types, columns)
    }

    #[test]
    fn apply_draft_updates_name_and_ignores_unknown_columns() {
        let (dataset, column_types, mut columns) = movies();
        let baseline = columns.clone();
        let draft = Draft {
            report_name: Some("New Name".to_string()),
            columns: HashMap::from([(
                "totally_unknown".to_string(),
                serde_json::json!({ "display-mode": "hidden" }),
            )]),
        };
        let mut name = "Old".to_string();
        apply_draft(
            draft,
            &mut name,
            "movies",
            &dataset,
            &column_types,
            &mut columns,
        );
        assert_eq!(name, "New Name");
        assert_eq!(columns, baseline);
    }

    #[test]
    fn apply_draft_reverts_invalid_suggestion_to_baseline() {
        let (dataset, column_types, mut columns) = movies();
        let target = columns.keys().next().unwrap().clone();
        let baseline = columns[&target].clone();
        // A link-to-url with only custom-content and no url is invalid and cannot be
        // auto-completed, so the column must fall back to its baseline.
        let draft = Draft {
            report_name: None,
            columns: HashMap::from([(
                target.clone(),
                serde_json::json!({
                    "link-to-url": { "custom-content": "function(value, row) { return value; }" }
                }),
            )]),
        };
        let mut name = "keep".to_string();
        apply_draft(
            draft,
            &mut name,
            "movies",
            &dataset,
            &column_types,
            &mut columns,
        );
        assert_eq!(name, "keep");
        assert_eq!(columns[&target], baseline);
    }

    #[test]
    fn apply_draft_auto_fills_missing_pills_color() {
        let (dataset, column_types, mut columns) = movies();
        let target = columns.keys().next().unwrap().clone();
        // Pills without a color would be rejected; the auto-fill completes them so the
        // model's pills choice is kept instead of falling back.
        let draft = Draft {
            report_name: None,
            columns: HashMap::from([(
                target.clone(),
                serde_json::json!({ "plot": { "pills": { "separator": ";" } } }),
            )]),
        };
        let mut name = "keep".to_string();
        apply_draft(
            draft,
            &mut name,
            "movies",
            &dataset,
            &column_types,
            &mut columns,
        );
        let pills = columns[&target]
            .plot
            .as_ref()
            .and_then(|plot| plot.pills.as_ref())
            .expect("pills should be kept, not dropped");
        assert!(!pills.color_scheme.is_empty());
    }
}