#![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, Equations, HtmlOptions, Mode, PageImage, Paper};
use std::io::Write;
use std::path::{Path, PathBuf};
use std::time::Instant;
const MIN_SCALE: f32 = 0.2;
const MAX_SCALE: f32 = 8.0;
const INSPECT_MAX_CHARS: usize = 150;
const INSPECT_HEAD_CHARS: usize = 95;
const INSPECT_TAIL_CHARS: usize = 45;
const BYTES_PER_MB: f64 = 1e6;
#[derive(Parser)]
#[command(
name = "kakemono",
version,
about = "Convert scientific-paper PDFs (arXiv) into clean, readable HTML"
)]
struct Cli {
#[command(subcommand)]
command: Command,
}
#[derive(Subcommand)]
enum Command {
Convert(ConvertArgs),
Fetch {
id: String,
#[arg(short, long)]
output: Option<PathBuf>,
},
Inspect {
input: String,
},
Formula {
#[arg(required = true)]
images: Vec<PathBuf>,
#[arg(long, hide = true)]
scores: bool,
},
}
#[derive(Clone, Copy, ValueEnum)]
enum ModeArg {
Hard,
#[value(name = "hard-95")]
Hard95,
Medium,
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,
}
}
}
#[derive(Clone, Copy, ValueEnum, PartialEq)]
enum ImagesArg {
Inline,
Files,
}
#[derive(Clone, Copy, ValueEnum, PartialEq)]
enum FontsArg {
Embed,
System,
}
#[derive(Clone, Copy, ValueEnum, PartialEq)]
enum TablesArg {
Auto,
Image,
}
#[derive(Clone, Copy, ValueEnum, PartialEq)]
enum EquationsArg {
Image,
Mathml,
}
#[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 {
Svg,
SvgOnly,
Png,
}
#[derive(clap::Args)]
struct ConvertArgs {
input: String,
#[arg(short, long, value_enum, default_value = "friendly")]
mode: ModeArg,
#[arg(long, conflicts_with = "mode")]
all: bool,
#[arg(short, long)]
output: Option<PathBuf>,
#[arg(long, value_enum, default_value = "inline")]
images: ImagesArg,
#[arg(long, default_value_t = 3.0)]
scale: f32,
#[arg(long, value_enum, default_value = "svg")]
page_image: PageImageArg,
#[arg(long, value_enum, default_value = "auto")]
tables: TablesArg,
#[arg(long, value_enum, default_value = "embed")]
fonts: FontsArg,
#[arg(long, value_enum, default_value = "mathml")]
equations: EquationsArg,
#[arg(long)]
json: bool,
#[arg(short, long, default_value_t = 0, value_name = "N")]
jobs: usize,
}
struct OutputPaths {
file: Option<PathBuf>,
dir: PathBuf,
}
impl OutputPaths {
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 }
}
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())),
}
}
}
fn main() {
if let Err(err) = run() {
eprintln!("error: {err:#}");
std::process::exit(1);
}
}
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),
}
}
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")
}
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()))
}
fn convert(args: ConvertArgs) -> Result<()> {
if !(args.scale > MIN_SCALE && args.scale <= MAX_SCALE) {
bail!("--scale must be between 0.2 and 8");
}
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 modes: Vec<Mode> = if args.all {
vec![Mode::Hard, Mode::Hard95, Mode::Medium, Mode::Friendly]
} else {
vec![args.mode.into()]
};
let paths = OutputPaths::new(args.output.as_ref(), args.all);
for mode in modes {
let file = paths.html_file(&stem, mode);
write_mode(&paper, &analysis, &args, jobs, mode, &file)?;
}
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(())
}
fn write_mode(
paper: &Paper,
analysis: &Analysis,
args: &ConvertArgs,
jobs: usize,
mode: Mode,
file: &Path,
) -> Result<()> {
let file_stem = file
.file_stem()
.and_then(|stem| stem.to_str())
.unwrap_or("paper")
.to_string();
let opts = HtmlOptions {
mode,
inline_images: args.images == ImagesArg::Inline,
asset_dir: format!("{file_stem}_assets"),
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: match args.equations {
EquationsArg::Image => Equations::Image,
EquationsArg::Mathml => Equations::MathMl,
},
};
let started = Instant::now();
let out = paper.to_html(analysis, &opts);
write_file(file, out.html.as_bytes())?;
let base = file.parent().map(Path::to_path_buf).unwrap_or_default();
for (rel, data) in &out.files {
write_file(&base.join(rel), data)?;
}
eprintln!(
"{:<8} -> {} ({:.1} MB{}, {:.2}s)",
mode.name(),
file.display(),
out.html.len() as f64 / BYTES_PER_MB,
if out.files.is_empty() {
String::new()
} else {
format!(" + {} image files", out.files.len())
},
started.elapsed().as_secs_f32()
);
Ok(())
}
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(())
}
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(())
}
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
}
}
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,
}
}
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::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()),
}
}
fn zone_label(loc: &Loc) -> String {
if loc.zone_cols > 1 {
format!("{}/{}", loc.col + 1, loc.zone_cols)
} else {
"-".into()
}
}