kakemono 0.8.0

Convert scientific-paper PDFs (arXiv) into clean, readable HTML in four fidelity modes, or Word documents
Documentation
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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
//! The `kakemono` command line: parses the arguments and calls the
//! library. `convert` turns a PDF into HTML, Word, Markdown or LaTeX (and JSON), `fetch` downloads an
//! arXiv PDF and `inspect` prints the detected structure for debugging.
#![warn(
    missing_docs,
    clippy::missing_docs_in_private_items,
    clippy::too_many_lines,
    clippy::min_ident_chars
)]

use anyhow::{Context, Result, anyhow, bail};
use clap::{Parser, Subcommand, ValueEnum};
use kakemono::analysis::pipeline::Analysis;
use kakemono::model::{Block, BlockKind, Loc};
use kakemono::source::arxiv;
use kakemono::{
    AnalyzeOptions, DocxOptions, Equations, HtmlOptions, LatexOptions, MarkdownOptions, Mode, PageImage, Paper,
};
use std::io::Write;
use std::path::{Path, PathBuf};
use std::time::Instant;

/// `--scale` must be larger than this (pixels per PDF point): smaller images
/// are unreadable.
const MIN_SCALE: f32 = 0.2;
/// Largest accepted `--scale` (pixels per PDF point): larger images only
/// waste space.
const MAX_SCALE: f32 = 8.0;
/// `inspect` shortens block texts longer than this many characters.
const INSPECT_MAX_CHARS: usize = 150;
/// Characters kept from the start of a shortened block text.
const INSPECT_HEAD_CHARS: usize = 95;
/// Characters kept from the end of a shortened block text.
const INSPECT_TAIL_CHARS: usize = 45;
/// Bytes per megabyte, for the size report.
const BYTES_PER_MB: f64 = 1e6;

/// Command-line arguments.
#[derive(Parser)]
#[command(
    name = "kakemono",
    version,
    about = "Convert scientific-paper PDFs (arXiv) into clean, readable HTML, Word documents, Markdown or LaTeX"
)]
struct Cli {
    /// The subcommand to run.
    #[command(subcommand)]
    command: Command,
}

/// The subcommands. The doc comments of the variants and their fields are
/// the help texts.
#[derive(Subcommand)]
enum Command {
    /// Convert a PDF (local file, arXiv id or arXiv URL) to HTML, Word, Markdown or LaTeX.
    Convert(ConvertArgs),
    /// Download the PDF of an arXiv paper.
    Fetch {
        /// arXiv id or URL, e.g. 1706.03762
        id: String,
        /// Output file (default: <id>.pdf)
        #[arg(short, long)]
        output: Option<PathBuf>,
    },
    /// Print the detected structure of a paper (for debugging).
    Inspect {
        /// Local PDF file, arXiv id or arXiv URL
        input: String,
    },
    /// Read pictures of formulas (black on white, as LaTeX renders them) and
    /// print them as MathML. With several pictures, each line is the file
    /// name, a tab and its MathML (empty when it cannot be read).
    Formula {
        /// Picture files (PNG or JPEG)
        #[arg(required = true)]
        images: Vec<PathBuf>,
        /// Print how sure each reading is (weakest glyph, closest rival)
        /// before its MathML, and give every reading whatever its confidence
        #[arg(long, hide = true)]
        scores: bool,
    },
}

/// Values of `--mode`; the doc comments are the help texts.
#[derive(Clone, Copy, ValueEnum)]
enum ModeArg {
    /// Facsimile of every page with a selectable text layer
    Hard,
    /// Like hard, but all text is real HTML text placed as in the PDF
    #[value(name = "hard-95")]
    Hard95,
    /// Page and column layout kept, text reflowed
    Medium,
    /// Single-column responsive article
    Friendly,
}

impl From<ModeArg> for Mode {
    fn from(arg: ModeArg) -> Self {
        match arg {
            ModeArg::Hard => Mode::Hard,
            ModeArg::Hard95 => Mode::Hard95,
            ModeArg::Medium => Mode::Medium,
            ModeArg::Friendly => Mode::Friendly,
        }
    }
}

/// Values of `--format`; the doc comments are the help texts.
#[derive(Clone, Copy, ValueEnum, PartialEq)]
enum FormatArg {
    /// HTML page(s) in the chosen mode(s)
    Html,
    /// A Word document (.docx): styles, Word tables and Office Math equations
    Docx,
    /// Markdown (.md): pipe tables, LaTeX formulas ($$), pictures in an image folder
    #[value(name = "md", alias = "markdown")]
    Markdown,
    /// LaTeX (.tex) for pdfLaTeX, XeLaTeX or LuaLaTeX: tables, LaTeX formulas, pictures in an image folder
    #[value(name = "tex", alias = "latex")]
    Latex,
}

/// Values of `--images`; the doc comments are the help texts.
#[derive(Clone, Copy, ValueEnum, PartialEq)]
enum ImagesArg {
    /// Embed images in the output file (one self-contained file)
    Inline,
    /// Write images to a folder next to the output file (Word documents keep them embedded too; always for LaTeX)
    Files,
}

/// Values of `--fonts`; the doc comments are the help texts.
#[derive(Clone, Copy, ValueEnum, PartialEq)]
enum FontsArg {
    /// Embed the reading fonts in friendly pages (works offline, about 250 KB) and the math font in pages with MathML (about 280 KB)
    Embed,
    /// Use the fonts installed on the reader's system (smaller files)
    System,
}

/// Values of `--tables`; the doc comments are the help texts.
#[derive(Clone, Copy, ValueEnum, PartialEq)]
enum TablesArg {
    /// Rebuild tables as real HTML tables where their structure is clear
    Auto,
    /// Never rebuild tables (pictures in medium/friendly, placed text in hard-95)
    Image,
}

/// Values of `--equations`; the doc comments are the help texts.
#[derive(Clone, Copy, ValueEnum, PartialEq)]
enum EquationsArg {
    /// Pictures of the formulas
    Image,
    /// MathML rebuilt from the glyphs where the structure is clear, pictures elsewhere
    Mathml,
}

/// Values of `--page-image`.
#[derive(Clone, Copy, ValueEnum)]
#[allow(
    clippy::missing_docs_in_private_items,
    reason = "a doc comment on a variant becomes its help text and would change --help"
)]
enum PageImageArg {
    // Pages as SVG (vector graphics, sharp at any zoom); a very large page as PNG.
    Svg,
    // Every page as SVG, however large.
    SvgOnly,
    // Pages as PNG bitmaps.
    Png,
}

/// Arguments of `convert`; the doc comments of the fields are the help
/// texts.
#[derive(clap::Args)]
struct ConvertArgs {
    /// Local PDF file, arXiv id (1706.03762) or arXiv URL
    input: String,
    /// Fidelity mode
    #[arg(short, long, value_enum, default_value = "friendly")]
    mode: ModeArg,
    /// Produce all four modes
    #[arg(long, conflicts_with = "mode")]
    all: bool,
    /// Output format (default: from the extension of --output, .docx, .md or .tex; html otherwise); --mode applies to html only
    #[arg(short, long, value_enum)]
    format: Option<FormatArg>,
    /// Output HTML, .docx, .md or .tex file, or a directory (required to be a directory with --all)
    #[arg(short, long)]
    output: Option<PathBuf>,
    /// How images are stored [default: inline for HTML and Word, files for Markdown and LaTeX]
    #[arg(long, value_enum)]
    images: Option<ImagesArg>,
    /// Folder of the image files, relative to the output file [default: <name>_assets]; with --all, one subfolder per mode
    #[arg(long, value_name = "DIR")]
    image_dir: Option<String>,
    /// Resolution of figure/equation images in pixels per PDF point (HTML and Word)
    #[arg(long, default_value_t = 3.0)]
    scale: f32,
    /// Page background used by hard and hard-95 modes
    #[arg(long, value_enum, default_value = "svg")]
    page_image: PageImageArg,
    /// How tables are handled
    #[arg(long, value_enum, default_value = "auto")]
    tables: TablesArg,
    /// Fonts of friendly mode, and of the formulas of medium and friendly modes
    #[arg(long, value_enum, default_value = "embed")]
    fonts: FontsArg,
    /// How medium and friendly modes (and Word, Markdown and LaTeX documents) show displayed formulas
    #[arg(long, value_enum, default_value = "mathml")]
    equations: EquationsArg,
    /// Also write the structured document as JSON (for translation tools)
    #[arg(long)]
    json: bool,
    /// Number of worker threads: 0 = one per CPU core, 1 = no parallelism
    #[arg(short, long, default_value_t = 0, value_name = "N")]
    jobs: usize,
}

/// Where the files of one `convert` run go.
struct OutputPaths {
    /// The HTML file named by `--output`, when it names a single file.
    file: Option<PathBuf>,
    /// Directory for the generated file names (`<stem>.<mode>.html`, the
    /// JSON); empty for the current directory.
    dir: PathBuf,
}

impl OutputPaths {
    /// Interprets `--output`: a directory when `--all` is given, when it is
    /// an existing directory or when it has no extension; a file otherwise
    /// (then its parent directory takes the JSON). Without `--output`
    /// everything goes to the current directory.
    fn new(output: Option<&PathBuf>, all: bool) -> Self {
        let out_is_dir = all || output.is_some_and(|path| path.is_dir() || path.extension().is_none());
        let dir: PathBuf = match (output, out_is_dir) {
            (Some(path), true) => path.clone(),
            (Some(path), false) => path.parent().map(Path::to_path_buf).unwrap_or_default(),
            (None, _) => PathBuf::new(),
        };
        let file = if out_is_dir { None } else { output.cloned() };
        Self { file, dir }
    }

    /// The HTML file for `mode`: the file named by `--output`, or
    /// `<stem>.<mode>.html` in the output directory.
    fn html_file(&self, stem: &str, mode: Mode) -> PathBuf {
        match &self.file {
            Some(file) => file.clone(),
            None => self.dir.join(format!("{stem}.{}.html", mode.name())),
        }
    }

    /// The Word, Markdown or LaTeX file: the file named by `--output`, or
    /// `<stem>.<ext>` in the output directory.
    fn single_file(&self, stem: &str, ext: &str) -> PathBuf {
        match &self.file {
            Some(file) => file.clone(),
            None => self.dir.join(format!("{stem}.{ext}")),
        }
    }
}

/// Runs the command line and exits with status 1 on error.
fn main() {
    if let Err(err) = run() {
        eprintln!("error: {err:#}");
        std::process::exit(1);
    }
}

/// Parses the arguments and runs the subcommand.
fn run() -> Result<()> {
    let cli = Cli::parse();
    match cli.command {
        Command::Convert(args) => convert(args),
        Command::Fetch { id, output } => {
            let id = arxiv::parse_id(&id).ok_or_else(|| anyhow!("'{id}' is not an arXiv id or URL"))?;
            let dest = output.unwrap_or_else(|| PathBuf::from(format!("{}.pdf", id.replace('/', "_"))));
            arxiv::save_pdf(&id, &dest)?;
            eprintln!("saved {}", dest.display());
            Ok(())
        }
        Command::Inspect { input } => inspect(&input),
        Command::Formula { images, scores } => formula(&images, scores),
    }
}

/// Loads the PDF named by `input` (an existing file, else an arXiv id or
/// URL) and returns it with the stem for output file names.
///
/// # Errors
/// When the file cannot be read, the download fails, the data is not a PDF,
/// or `input` is neither a file nor an arXiv id.
fn load(input: &str) -> Result<(Paper, String)> {
    let path = Path::new(input);
    if path.is_file() {
        let data = std::fs::read(path).with_context(|| format!("reading {input}"))?;
        let stem = path
            .file_stem()
            .and_then(|stem| stem.to_str())
            .unwrap_or("paper")
            .to_string();
        let name = path
            .file_name()
            .and_then(|name| name.to_str())
            .unwrap_or(input)
            .to_string();
        return Ok((Paper::from_bytes(data)?.with_source(name), stem));
    }
    if let Some(id) = arxiv::parse_id(input) {
        eprintln!("fetching arXiv:{id} ...");
        let data = arxiv::fetch_pdf(&id)?;
        let stem = id.replace('/', "_");
        return Ok((Paper::from_bytes(data)?.with_source(format!("arXiv:{id}")), stem));
    }
    bail!("'{input}' is neither an existing file nor an arXiv id/URL")
}

/// Writes `data` to `path`, creating the parent directories first.
///
/// # Errors
/// When a directory or the file cannot be written.
fn write_file(path: &Path, data: &[u8]) -> Result<()> {
    if let Some(parent) = path.parent()
        && !parent.as_os_str().is_empty()
    {
        std::fs::create_dir_all(parent).with_context(|| format!("creating {}", parent.display()))?;
    }
    std::fs::write(path, data).with_context(|| format!("writing {}", path.display()))
}

/// The `convert` subcommand: analyses the paper once, then writes the HTML
/// of each requested mode or the Word document and, with `--json`, the
/// document as JSON.
///
/// # Errors
/// When `--scale` is out of range, `--all` is given for a Word, Markdown or LaTeX document, `--images inline` for
/// LaTeX, the input cannot be loaded or an output file cannot be written.
fn convert(args: ConvertArgs) -> Result<()> {
    if !(args.scale > MIN_SCALE && args.scale <= MAX_SCALE) {
        bail!("--scale must be between 0.2 and 8");
    }
    let format = output_format(&args);
    if format != FormatArg::Html && args.all {
        bail!("--all produces the HTML modes; it cannot be used with --format docx, md or tex");
    }
    if format == FormatArg::Latex && args.images == Some(ImagesArg::Inline) {
        bail!("LaTeX cannot embed pictures: --images inline cannot be used with --format tex");
    }
    if let Some(dir) = &args.image_dir
        && (dir.trim().is_empty() || Path::new(dir).is_absolute() || dir.split(['/', '\\']).any(|part| part == ".."))
    {
        bail!("--image-dir must be a relative folder inside the output directory");
    }
    let (paper, stem) = load(&args.input)?;
    let started = Instant::now();
    let jobs = kakemono::common::parallel::resolve_jobs(args.jobs);
    let analysis = paper.analyze_with(AnalyzeOptions {
        tables: args.tables == TablesArg::Auto,
        jobs,
        ..Default::default()
    });
    let tables = analysis.doc.blocks.iter().filter(|block| block.table.is_some()).count();
    eprintln!(
        "analysed {} pages ({jobs} threads), {} blocks, {tables} tables rebuilt in {:.2}s",
        paper.page_count(),
        analysis.doc.blocks.len(),
        started.elapsed().as_secs_f32()
    );

    let paths = OutputPaths::new(args.output.as_ref(), args.all);
    match format {
        FormatArg::Docx => write_docx(&paper, &analysis, &args, jobs, &paths.single_file(&stem, "docx"))?,
        FormatArg::Markdown => write_markdown(&paper, &analysis, &args, jobs, &paths.single_file(&stem, "md"))?,
        FormatArg::Latex => write_latex(&paper, &analysis, &args, jobs, &paths.single_file(&stem, "tex"))?,
        FormatArg::Html => write_html(&paper, &analysis, &args, jobs, &paths, &stem)?,
    }

    if args.json {
        let file = paths.dir.join(format!("{stem}.json"));
        let json = serde_json::to_vec_pretty(&analysis.doc)?;
        write_file(&file, &json)?;
        eprintln!("json     -> {}", file.display());
    }
    Ok(())
}

/// The output format: `--format`, or Word when `--output` names a `.docx`
/// file, Markdown when it names a `.md` file, LaTeX when it names a `.tex`
/// file, HTML otherwise.
fn output_format(args: &ConvertArgs) -> FormatArg {
    args.format.unwrap_or_else(|| {
        let ext = args
            .output
            .as_ref()
            .and_then(|path| path.extension())
            .and_then(std::ffi::OsStr::to_str)
            .unwrap_or_default()
            .to_ascii_lowercase();
        match ext.as_str() {
            "docx" => FormatArg::Docx,
            "md" | "markdown" => FormatArg::Markdown,
            "tex" | "latex" => FormatArg::Latex,
            _ => FormatArg::Html,
        }
    })
}

/// The folder of the image files of `file` (relative to its directory):
/// `--image-dir`, with a subfolder per mode when several modes are written
/// (`mode`), or `<name>_assets`.
fn image_dir(args: &ConvertArgs, file: &Path, mode: Option<Mode>) -> String {
    match (&args.image_dir, mode) {
        (Some(dir), Some(mode)) if args.all => format!("{}/{}", dir.trim_end_matches(['/', '\\']), mode.name()),
        (Some(dir), _) => dir.trim_end_matches(['/', '\\']).to_string(),
        (None, _) => {
            let stem = file.file_stem().and_then(std::ffi::OsStr::to_str).unwrap_or("paper");
            format!("{stem}_assets")
        }
    }
}

/// Writes the image `files` (paths relative to the directory of `file`) and
/// returns the size report: ` + N image files in DIR`, or nothing.
///
/// # Errors
/// When a file cannot be written.
fn write_images(file: &Path, files: &[(String, Vec<u8>)]) -> Result<String> {
    let base = file.parent().map(Path::to_path_buf).unwrap_or_default();
    for (rel, data) in files {
        write_file(&base.join(rel), data)?;
    }
    let Some((first, _)) = files.first() else {
        return Ok(String::new());
    };
    let dir = Path::new(first).parent().unwrap_or(Path::new(""));
    Ok(format!(
        " + {} image files in {}",
        files.len(),
        base.join(dir).display()
    ))
}

/// Writes the HTML of each requested mode (`--mode`, or all four with
/// `--all`).
///
/// # Errors
/// When a file cannot be written.
fn write_html(
    paper: &Paper,
    analysis: &Analysis,
    args: &ConvertArgs,
    jobs: usize,
    paths: &OutputPaths,
    stem: &str,
) -> Result<()> {
    let modes: Vec<Mode> = if args.all {
        vec![Mode::Hard, Mode::Hard95, Mode::Medium, Mode::Friendly]
    } else {
        vec![args.mode.into()]
    };

    for mode in modes {
        let file = paths.html_file(stem, mode);
        write_mode(paper, analysis, args, jobs, mode, &file)?;
    }
    Ok(())
}

/// Writes `analysis` as a Word document to `file` and reports the result
/// on stderr.
///
/// # Errors
/// When the file cannot be written.
fn write_docx(paper: &Paper, analysis: &Analysis, args: &ConvertArgs, jobs: usize, file: &Path) -> Result<()> {
    let opts = DocxOptions {
        scale: args.scale,
        jobs,
        equations: equations(args.equations),
    };
    let started = Instant::now();
    let (data, images) = if args.images == Some(ImagesArg::Files) {
        let out = paper.to_docx_with_images(analysis, &opts, &image_dir(args, file, None));
        (out.docx, out.files)
    } else {
        (paper.to_docx(analysis, &opts), Vec::new())
    };
    write_file(file, &data)?;
    let report = write_images(file, &images)?;
    eprintln!(
        "{:<8} -> {} ({:.1} MB{report}, {:.2}s)",
        "docx",
        file.display(),
        data.len() as f64 / BYTES_PER_MB,
        started.elapsed().as_secs_f32()
    );
    Ok(())
}

/// Writes `analysis` as Markdown to `file`, with the image files next to it
/// unless `--images inline`, and reports the result on stderr.
///
/// # Errors
/// When a file cannot be written.
fn write_markdown(paper: &Paper, analysis: &Analysis, args: &ConvertArgs, jobs: usize, file: &Path) -> Result<()> {
    let opts = MarkdownOptions {
        inline_images: args.images == Some(ImagesArg::Inline),
        asset_dir: image_dir(args, file, None),
        scale: args.scale,
        jobs,
        equations: equations(args.equations),
    };
    let started = Instant::now();
    let out = paper.to_markdown(analysis, &opts);
    write_file(file, out.markdown.as_bytes())?;
    let report = write_images(file, &out.files)?;
    eprintln!(
        "{:<8} -> {} ({:.1} MB{report}, {:.2}s)",
        "markdown",
        file.display(),
        out.markdown.len() as f64 / BYTES_PER_MB,
        started.elapsed().as_secs_f32()
    );
    Ok(())
}

/// Writes `analysis` as LaTeX to `file`, with the image files next to it,
/// and reports the result on stderr.
///
/// # Errors
/// When a file cannot be written.
fn write_latex(paper: &Paper, analysis: &Analysis, args: &ConvertArgs, jobs: usize, file: &Path) -> Result<()> {
    let opts = LatexOptions {
        asset_dir: image_dir(args, file, None),
        scale: args.scale,
        jobs,
        equations: equations(args.equations),
    };
    let started = Instant::now();
    let out = paper.to_latex(analysis, &opts);
    write_file(file, out.latex.as_bytes())?;
    let report = write_images(file, &out.files)?;
    eprintln!(
        "{:<8} -> {} ({:.1} MB{report}, {:.2}s)",
        "latex",
        file.display(),
        out.latex.len() as f64 / BYTES_PER_MB,
        started.elapsed().as_secs_f32()
    );
    Ok(())
}

/// The library value of `--equations`.
fn equations(arg: EquationsArg) -> Equations {
    match arg {
        EquationsArg::Image => Equations::Image,
        EquationsArg::Mathml => Equations::MathMl,
    }
}

/// Renders `analysis` in `mode` and writes the HTML to `file`, with the
/// image files next to it when images are not inlined, then reports the
/// result on stderr.
///
/// # Errors
/// When a file cannot be written.
fn write_mode(
    paper: &Paper,
    analysis: &Analysis,
    args: &ConvertArgs,
    jobs: usize,
    mode: Mode,
    file: &Path,
) -> Result<()> {
    let opts = HtmlOptions {
        mode,
        inline_images: args.images != Some(ImagesArg::Files),
        asset_dir: image_dir(args, file, Some(mode)),
        scale: args.scale,
        page_image: match args.page_image {
            PageImageArg::Svg => PageImage::Svg,
            PageImageArg::SvgOnly => PageImage::SvgOnly,
            PageImageArg::Png => PageImage::Png,
        },
        jobs,
        embed_fonts: args.fonts == FontsArg::Embed,
        equations: equations(args.equations),
    };
    let started = Instant::now();
    let out = paper.to_html(analysis, &opts);
    write_file(file, out.html.as_bytes())?;
    let report = write_images(file, &out.files)?;
    eprintln!(
        "{:<8} -> {} ({:.1} MB{report}, {:.2}s)",
        mode.name(),
        file.display(),
        out.html.len() as f64 / BYTES_PER_MB,
        started.elapsed().as_secs_f32()
    );
    Ok(())
}

/// The `formula` subcommand: prints the MathML of the formulas pictured in `images`.
///
/// # Errors
/// When a picture cannot be opened, or a single picture cannot be read.
fn formula(images: &[PathBuf], scores: bool) -> Result<()> {
    let cfg = kakemono::raster::RasterConfig::default();
    let mut out = std::io::stdout().lock();
    for path in images {
        let image = image::open(path).with_context(|| format!("cannot open {}", path.display()))?;
        if scores {
            let read = kakemono::raster::formula_with_confidence(&image, &cfg);
            let (weakest, closest, math) = read.map_or((f32::NAN, f32::NAN, String::new()), |(node, confidence)| {
                (
                    confidence.weakest,
                    confidence.closest,
                    kakemono::render::math_html(&node, ""),
                )
            });
            writeln!(out, "{}\t{weakest:.3}\t{closest:.3}\t{math}", path.display())?;
            continue;
        }
        let math = kakemono::raster::formula(&image, &cfg).map(|node| kakemono::render::math_html(&node, ""));
        if images.len() == 1 {
            let math = math.ok_or_else(|| anyhow!("cannot read the formula in {}", path.display()))?;
            writeln!(out, "{math}")?;
        } else {
            writeln!(out, "{}\t{}", path.display(), math.unwrap_or_default())?;
        }
    }
    Ok(())
}

/// The `inspect` subcommand: prints the document's metadata and one line
/// per block (page, column, kind, shortened text) to stdout. Stops quietly
/// when stdout is closed (e.g. piped into `head`).
///
/// # Errors
/// When the input cannot be loaded.
fn inspect(input: &str) -> Result<()> {
    let (paper, _) = load(input)?;
    let analysis = paper.analyze();
    let doc = &analysis.doc;
    let mut out = std::io::stdout().lock();
    let _ = writeln!(
        out,
        "title: {:?}\narxiv: {:?}\npages: {}  body font: {}pt  leading: {:.1}pt\n",
        doc.meta.title,
        doc.meta.arxiv_id,
        doc.pages.len(),
        doc.body_size,
        doc.leading
    );
    for block in &doc.blocks {
        let short = shorten(block.text());
        let kind = block_label(block);
        let zone = zone_label(&block.loc);
        if writeln!(out, "p{:<3} {:<4} {:<22} {}", block.page + 1, zone, kind, short).is_err() {
            break;
        }
    }
    Ok(())
}

/// `text` itself, or for texts longer than [`INSPECT_MAX_CHARS`] its start
/// and end joined by an ellipsis.
fn shorten(text: String) -> String {
    let n = text.chars().count();
    if n > INSPECT_MAX_CHARS {
        let head: String = text.chars().take(INSPECT_HEAD_CHARS).collect();
        let tail: String = text.chars().skip(n - INSPECT_TAIL_CHARS).collect();
        format!("{head} … {tail}")
    } else {
        text
    }
}

/// Short description of a block's kind for `inspect` ("H2", "EQ (3)
/// [200x30]", ...), followed by the table's size for rebuilt tables and by
/// `<math>` for equations whose structure was rebuilt (MathML).
fn block_label(block: &Block) -> String {
    let kind = kind_label(&block.kind);
    match &block.table {
        Some(table) => format!(
            "{kind} <table {}x{} hdr={}>",
            table.rows.len(),
            table.n_cols,
            table.header_rows
        ),
        None if block.math.is_some() => format!("{kind} <math>"),
        None => kind,
    }
}

/// Short description of a block kind with its main attributes.
fn kind_label(kind: &BlockKind) -> String {
    match kind {
        BlockKind::Title => "TITLE".to_string(),
        BlockKind::Authors => "AUTHOR".to_string(),
        BlockKind::Note => "NOTE".to_string(),
        BlockKind::Heading { level } => format!("H{level}"),
        BlockKind::Paragraph { in_abstract: true } => "ABSTRACT".into(),
        BlockKind::Paragraph { .. } => "P".into(),
        BlockKind::Code => "CODE".into(),
        BlockKind::ContentsEntry { level, page } => format!("TOC{level} {page}"),
        BlockKind::ListItem { marker } => format!("LI {}", marker.clone().unwrap_or_default()),
        BlockKind::ListContinuation => "LI+".to_string(),
        BlockKind::Equation { number, image } => format!(
            "EQ {} [{:.0}x{:.0}]",
            number.clone().unwrap_or_default(),
            image.rect.width(),
            image.rect.height()
        ),
        BlockKind::Figure { kind, image, label } => format!(
            "{:?} {} {}",
            kind,
            label.clone().unwrap_or_default(),
            image
                .map(|spec| format!(
                    "[{:.0},{:.0} {:.0}x{:.0}]",
                    spec.rect.x0,
                    spec.rect.y0,
                    spec.rect.width(),
                    spec.rect.height()
                ))
                .unwrap_or_else(|| "[no image]".into())
        ),
        BlockKind::Footnote { marker } => format!("FN {marker}"),
        BlockKind::Reference { label } => format!("REF {}", label.clone().unwrap_or_default()),
    }
}

/// Column of a block in a multi-column zone as "column/columns", or "-"
/// for single-column zones.
fn zone_label(loc: &Loc) -> String {
    if loc.zone_cols > 1 {
        format!("{}/{}", loc.col + 1, loc.zone_cols)
    } else {
        "-".into()
    }
}