#![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::config::{ExcelConfig, WorkbookPdfConfig, WorkbookPdfStyle};
use kakemono::model::{Block, BlockKind, Loc};
use kakemono::source::{arxiv, web};
use kakemono::{
AnalyzeOptions, ChunkOptions, DocxOptions, EpubOptions, Equations, HtmlOptions, JsonOptions, LatexOptions,
MarkdownOptions, Mode, PageImage, Paper, PngCompression, TokenCounter, TypstLayout, TypstOptions,
};
use std::io::Write;
use std::path::{Path, PathBuf};
use std::time::Instant;
#[cfg(not(target_arch = "wasm32"))]
#[global_allocator]
static GLOBAL: mimalloc::MiMalloc = mimalloc::MiMalloc;
#[cfg(not(target_arch = "wasm32"))]
const MI_OPTION_PURGE_DELAY: libmimalloc_sys::mi_option_t = 15;
fn tune_allocator() {
#[cfg(not(target_arch = "wasm32"))]
unsafe {
libmimalloc_sys::mi_option_set(MI_OPTION_PURGE_DELAY, 0);
}
}
const MIN_SCALE: f32 = 0.2;
const MAX_SCALE: f32 = 8.0;
const MIN_CHUNK_TOKENS: usize = 32;
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), Word documents, Excel workbooks and EPUB books into clean, readable HTML, Word documents, Markdown, LaTeX or EPUB books"
)]
struct Cli {
#[command(subcommand)]
command: Command,
}
#[derive(Subcommand)]
enum Command {
Convert(ConvertArgs),
Fetch {
id: String,
#[arg(short, long)]
output: Option<PathBuf>,
},
Inspect {
input: String,
#[arg(long, value_name = "N")]
header_rows: Option<usize>,
},
#[command(hide = true)]
Lines {
input: PathBuf,
},
Formula {
#[arg(required = true)]
images: Vec<PathBuf>,
#[arg(long, hide = true)]
scores: bool,
},
RenderSvg {
input: PathBuf,
#[arg(short, long)]
output: PathBuf,
#[arg(long, default_value_t = 1.0)]
scale: f32,
},
}
#[derive(Clone, Copy, PartialEq, 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 FormatArg {
Html,
Docx,
#[value(name = "md", alias = "markdown")]
Markdown,
#[value(name = "tex", alias = "latex")]
Latex,
#[value(name = "typst", alias = "typ")]
Typst,
Epub,
Json,
Chunks,
Pdf,
}
#[derive(Clone, Copy, ValueEnum, PartialEq)]
enum ImagesArg {
Inline,
Files,
}
#[derive(Clone, Copy, ValueEnum, PartialEq)]
enum LayoutArg {
Auto,
Article,
Book,
}
#[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(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 PngCompressionArg {
Fast,
Balanced,
High,
}
#[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 PdfStyleArg {
Print,
Document,
}
impl From<PdfStyleArg> for WorkbookPdfStyle {
fn from(arg: PdfStyleArg) -> Self {
match arg {
PdfStyleArg::Print => WorkbookPdfStyle::Print,
PdfStyleArg::Document => WorkbookPdfStyle::Document,
}
}
}
impl From<PngCompressionArg> for PngCompression {
fn from(arg: PngCompressionArg) -> Self {
match arg {
PngCompressionArg::Fast => PngCompression::Fast,
PngCompressionArg::Balanced => PngCompression::Balanced,
PngCompressionArg::High => PngCompression::High,
}
}
}
#[derive(clap::Args)]
struct ConvertArgs {
input: String,
#[arg(long, value_name = "N")]
header_rows: Option<usize>,
#[arg(short, long, value_enum, default_value = "friendly")]
mode: ModeArg,
#[arg(long, conflicts_with = "mode")]
all: bool,
#[arg(short, long, value_enum)]
format: Option<FormatArg>,
#[arg(short, long)]
output: Option<PathBuf>,
#[arg(long, value_enum)]
images: Option<ImagesArg>,
#[arg(long, value_name = "DIR")]
image_dir: Option<String>,
#[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 = "balanced")]
png_compression: PngCompressionArg,
#[arg(long, value_enum, default_value = "print")]
pdf_style: PdfStyleArg,
#[arg(long, value_enum, default_value = "auto")]
tables: TablesArg,
#[arg(long, value_enum, default_value = "auto")]
layout: LayoutArg,
#[arg(long, value_enum, default_value = "embed")]
fonts: FontsArg,
#[arg(long, value_enum, default_value = "mathml")]
equations: EquationsArg,
#[arg(long)]
json: bool,
#[arg(long, value_name = "FILE.json")]
content: Option<PathBuf>,
#[arg(long, default_value_t = 512, value_name = "N")]
chunk_tokens: usize,
#[arg(long, value_name = "FILE.json|NAME")]
tokenizer: Option<String>,
#[arg(short, long, default_value_t = 0, value_name = "N")]
jobs: usize,
#[arg(long, value_name = "URL")]
base_url: Option<String>,
}
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 single_file(&self, stem: &str, ext: &str) -> PathBuf {
match &self.file {
Some(file) => file.clone(),
None => self.dir.join(format!("{stem}.{ext}")),
}
}
}
fn main() {
tune_allocator();
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, header_rows } => inspect(&input, header_rows),
Command::Lines { input } => {
let data = std::fs::read(&input).with_context(|| format!("reading {}", input.display()))?;
let (lines, pages) = kakemono::layout::lines::pdf_lines(data)?;
let mut out = std::io::BufWriter::new(std::io::stdout().lock());
let written = writeln!(out, "pages\t{pages}").and_then(|()| {
for line in lines {
writeln!(
out,
"{}\t{:.2}\t{:.2}\t{:.2}\t{}",
line.page, line.baseline, line.left, line.right, line.text
)?;
}
out.flush()
});
match written {
Err(error) if error.kind() != std::io::ErrorKind::BrokenPipe => Err(error.into()),
_ => Ok(()),
}
}
Command::Formula { images, scores } => formula(&images, scores),
Command::RenderSvg { input, output, scale } => render_svg(&input, &output, scale),
}
}
fn render_svg(input: &Path, output: &Path, scale: f32) -> Result<()> {
let svg = std::fs::read_to_string(input).with_context(|| format!("cannot read {}", input.display()))?;
let png = kakemono::backend::svg_to_png_in(&svg, scale, input.parent())
.map_err(|why| anyhow::anyhow!("cannot read {} as SVG: {why}", input.display()))?;
std::fs::write(output, png).with_context(|| format!("writing {}", output.display()))
}
fn load(input: &str, header_rows: Option<usize>) -> Result<(Paper, String)> {
let excel = ExcelConfig {
header_rows,
..Default::default()
};
let path = Path::new(input);
if path.is_file() {
let stem = path
.file_stem()
.and_then(std::ffi::OsStr::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_path_with(path, &excel)?.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_with(data, &excel)?.with_source(format!("arXiv:{id}")),
stem,
));
}
if web::is_url(input) {
eprintln!("fetching {input} ...");
return Ok((Paper::from_url(input)?, url_stem(input)));
}
bail!("'{input}' is neither an existing file, an arXiv id/URL nor an http(s) address")
}
fn load_saved_page(input: &str, url: &str) -> Result<(Paper, String)> {
if !web::is_url(url) {
bail!("--base-url: '{url}' is not an http(s) address");
}
let path = Path::new(input);
let data = std::fs::read(path).with_context(|| format!("reading {input}"))?;
if !kakemono::html::is_html(&data) {
bail!("--base-url applies to a web page; {input} is not one");
}
let stem = path
.file_stem()
.and_then(std::ffi::OsStr::to_str)
.unwrap_or("page")
.to_string();
Ok((Paper::from_page_at(&data, url)?, stem))
}
fn url_stem(url: &str) -> String {
let parsed = url::Url::parse(url.trim()).ok();
let segment = parsed
.as_ref()
.and_then(|url| {
url.path_segments()?
.rev()
.find(|segment| !segment.is_empty())
.map(str::to_string)
})
.map(|segment| {
let decoded = percent_decode(&segment);
match decoded.rsplit_once('.') {
Some((stem, ext)) if !stem.is_empty() && ext.len() <= 5 => stem.to_string(),
_ => decoded,
}
});
let name = segment
.or_else(|| parsed.as_ref().and_then(|url| url.host_str().map(str::to_string)))
.unwrap_or_default();
let mut stem = String::new();
for ch in name.chars() {
let ch = if ch.is_alphanumeric() || matches!(ch, '-' | '.') {
ch
} else {
'_'
};
if !(ch == '_' && stem.ends_with('_')) {
stem.push(ch);
}
}
let stem = stem.trim_matches(['_', '.']).to_string();
if stem.is_empty() { "page".to_string() } else { stem }
}
fn percent_decode(text: &str) -> String {
let bytes = text.as_bytes();
let mut out = Vec::with_capacity(bytes.len());
let mut i = 0;
while i < bytes.len() {
if bytes[i] == b'%'
&& let Some(byte) = text.get(i + 1..i + 3).and_then(|hex| u8::from_str_radix(hex, 16).ok())
{
out.push(byte);
i += 3;
continue;
}
out.push(bytes[i]);
i += 1;
}
String::from_utf8_lossy(&out).into_owned()
}
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 check_args(args: &ConvertArgs) -> Result<FormatArg> {
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, tex, epub, json or chunks");
}
if args.chunk_tokens < MIN_CHUNK_TOKENS {
bail!("--chunk-tokens must be at least {MIN_CHUNK_TOKENS}");
}
if format != FormatArg::Chunks && args.tokenizer.is_some() {
bail!("--tokenizer counts the tokens of chunks: it needs --format chunks (or a .jsonl output)");
}
if args.content.is_some() && format == FormatArg::Html && !args.all && args.mode == ModeArg::Hard {
bail!("hard mode shows the pages of the PDF: it cannot show edited text from --content (hard-95 can)");
}
if format == FormatArg::Markdown && matches!(args.mode, ModeArg::Hard | ModeArg::Hard95) {
bail!("Markdown has no pages: --mode can be friendly or medium with --format md");
}
if format == FormatArg::Latex && args.images == Some(ImagesArg::Inline) {
bail!("LaTeX cannot embed pictures: --images inline cannot be used with --format tex");
}
if format == FormatArg::Typst && args.images == Some(ImagesArg::Inline) {
bail!("Typst cannot embed pictures in its source: --images inline cannot be used with --format typst");
}
if format != FormatArg::Typst && args.layout != LayoutArg::Auto {
bail!("--layout chooses the layout of the Typst output: it needs --format typst (or a .typ output)");
}
if format == FormatArg::Epub && (args.images == Some(ImagesArg::Files) || args.image_dir.is_some()) {
bail!("an EPUB book holds its pictures: --images files and --image-dir cannot be used with --format epub");
}
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");
}
Ok(format)
}
fn write_pdf(paper: &Paper, args: &ConvertArgs, stem: &str) -> Result<()> {
let started = Instant::now();
let file = OutputPaths::new(args.output.as_ref(), false).single_file(stem, "pdf");
let data = match &args.content {
Some(content) => {
let mut analysis = paper.analyze();
apply_content(paper, &mut analysis, content)?;
let docx = paper.to_docx(&analysis, &kakemono::DocxOptions::default());
Paper::from_bytes(docx)?.to_pdf()?
}
None => paper.to_pdf_with(&WorkbookPdfConfig {
style: args.pdf_style.into(),
..WorkbookPdfConfig::default()
})?,
};
write_file(&file, &data)?;
eprintln!(
"{:<8} -> {} ({:.1} MB, {:.2}s)",
"pdf",
file.display(),
data.len() as f64 / BYTES_PER_MB,
started.elapsed().as_secs_f32()
);
Ok(())
}
fn convert(args: ConvertArgs) -> Result<()> {
let format = check_args(&args)?;
let (paper, stem) = match &args.base_url {
Some(url) => load_saved_page(&args.input, url)?,
None => load(&args.input, args.header_rows)?,
};
let paper = paper.with_png_compression(args.png_compression.into());
if format == FormatArg::Pdf {
return write_pdf(&paper, &args, &stem);
}
let started = Instant::now();
let jobs = kakemono::common::parallel::resolve_jobs(args.jobs);
let mut 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();
if paper.format().has_pages() {
eprintln!(
"analysed {} pages ({jobs} threads), {} blocks, {tables} tables rebuilt in {:.2}s",
paper.page_count(),
analysis.doc.blocks.len(),
started.elapsed().as_secs_f32()
);
} else {
eprintln!(
"read {} document, {} blocks, {tables} tables",
paper.format().name(),
analysis.doc.blocks.len(),
);
}
if let Some(content) = &args.content {
apply_content(&paper, &mut analysis, content)?;
}
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::Typst => write_typst(&paper, &analysis, &args, jobs, &paths.single_file(&stem, "typ"))?,
FormatArg::Epub => write_epub(&paper, &analysis, &args, jobs, &paths.single_file(&stem, "epub"))?,
FormatArg::Json => write_json(&paper, &analysis, &args, jobs, &paths.single_file(&stem, "json"))?,
FormatArg::Chunks => write_chunks(&paper, &analysis, &args, &paths.single_file(&stem, "chunks.jsonl"))?,
FormatArg::Html => write_html(&paper, &analysis, &args, jobs, &paths, &stem)?,
FormatArg::Pdf => unreachable!("written above"),
}
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 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,
"typ" => FormatArg::Typst,
"epub" => FormatArg::Epub,
"json" => FormatArg::Json,
"jsonl" => FormatArg::Chunks,
"pdf" => FormatArg::Pdf,
_ => FormatArg::Html,
}
})
}
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")
}
}
}
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()
))
}
fn write_html(
paper: &Paper,
analysis: &Analysis,
args: &ConvertArgs,
jobs: usize,
paths: &OutputPaths,
stem: &str,
) -> Result<()> {
let modes: Vec<Mode> = if args.all && args.content.is_some() {
eprintln!("hard mode skipped: it cannot show edited text from --content");
vec![Mode::Hard95, Mode::Medium, Mode::Friendly]
} else 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(())
}
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(())
}
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),
mode: args.mode.into(),
};
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(())
}
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(())
}
fn write_typst(paper: &Paper, analysis: &Analysis, args: &ConvertArgs, jobs: usize, file: &Path) -> Result<()> {
let opts = TypstOptions {
asset_dir: image_dir(args, file, None),
scale: args.scale,
jobs,
equations: equations(args.equations),
layout: match args.layout {
LayoutArg::Auto => None,
LayoutArg::Article => Some(TypstLayout::Article),
LayoutArg::Book => Some(TypstLayout::Book),
},
};
let started = Instant::now();
let out = paper.to_typst(analysis, &opts);
write_file(file, out.typst.as_bytes())?;
let report = write_images(file, &out.files)?;
eprintln!(
"{:<8} -> {} ({:.1} MB{report}, {:.2}s)",
"typst",
file.display(),
out.typst.len() as f64 / BYTES_PER_MB,
started.elapsed().as_secs_f32()
);
Ok(())
}
fn write_json(paper: &Paper, analysis: &Analysis, args: &ConvertArgs, jobs: usize, file: &Path) -> Result<()> {
let opts = JsonOptions {
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_json(analysis, &opts);
write_file(file, out.json.as_bytes())?;
let report = write_images(file, &out.files)?;
eprintln!(
"{:<8} -> {} ({:.1} MB{report}, {:.2}s)",
"json",
file.display(),
out.json.len() as f64 / BYTES_PER_MB,
started.elapsed().as_secs_f32()
);
Ok(())
}
fn write_chunks(paper: &Paper, analysis: &Analysis, args: &ConvertArgs, file: &Path) -> Result<()> {
let counter = match &args.tokenizer {
Some(spec) => TokenCounter::load(spec)?,
None => TokenCounter::estimate(),
};
let opts = ChunkOptions {
max_tokens: args.chunk_tokens,
counter,
};
let started = Instant::now();
let chunks = paper.to_chunks(analysis, &opts);
write_file(file, kakemono::chunks_jsonl(&chunks).as_bytes())?;
let tokens: usize = chunks.iter().map(|chunk| chunk.tokens).sum();
eprintln!(
"{:<8} -> {} ({} chunks, {tokens} tokens{}, {:.2}s)",
"chunks",
file.display(),
chunks.len(),
if args.tokenizer.is_some() { "" } else { " estimated" },
started.elapsed().as_secs_f32()
);
Ok(())
}
fn apply_content(paper: &Paper, analysis: &mut Analysis, path: &Path) -> Result<()> {
let json = std::fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
let base = path.parent().unwrap_or(Path::new("."));
let report = paper
.apply_content_in(analysis, &json, base)
.with_context(|| format!("applying {}", path.display()))?;
for warning in &report.warnings {
eprintln!("warning: {warning}");
}
eprintln!(
"content <- {} ({} blocks edited, {} warnings)",
path.display(),
report.edited_blocks,
report.warnings.len()
);
Ok(())
}
fn write_epub(paper: &Paper, analysis: &Analysis, args: &ConvertArgs, jobs: usize, file: &Path) -> Result<()> {
let opts = EpubOptions {
scale: args.scale,
jobs,
equations: equations(args.equations),
modified: Some(utc_timestamp(std::time::SystemTime::now())),
..Default::default()
};
let started = Instant::now();
let data = paper.to_epub(analysis, &opts);
write_file(file, &data)?;
eprintln!(
"{:<8} -> {} ({:.1} MB, {:.2}s)",
"epub",
file.display(),
data.len() as f64 / BYTES_PER_MB,
started.elapsed().as_secs_f32()
);
Ok(())
}
fn utc_timestamp(time: std::time::SystemTime) -> String {
const SECONDS_PER_DAY: u64 = 86_400;
let secs = time
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |since| since.as_secs());
let (days, rest) = (secs / SECONDS_PER_DAY, secs % SECONDS_PER_DAY);
let days = days + 719_468;
let era = days / 146_097;
let day_of_era = days % 146_097;
let year_of_era = (day_of_era - day_of_era / 1460 + day_of_era / 36_524 - day_of_era / 146_096) / 365;
let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
let month_index = (5 * day_of_year + 2) / 153;
let day = day_of_year - (153 * month_index + 2) / 5 + 1;
let month = if month_index < 10 {
month_index + 3
} else {
month_index - 9
};
let year = year_of_era + era * 400 + u64::from(month <= 2);
format!(
"{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}Z",
rest / 3600,
rest / 60 % 60,
rest % 60
)
}
fn equations(arg: EquationsArg) -> Equations {
match arg {
EquationsArg::Image => Equations::Image,
EquationsArg::Mathml => Equations::MathMl,
}
}
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 base = file.parent().map(Path::to_path_buf).unwrap_or_default();
if !base.as_os_str().is_empty() {
std::fs::create_dir_all(&base).with_context(|| format!("creating {}", base.display()))?;
}
let mut partial = file.as_os_str().to_owned();
partial.push(".part");
let partial = PathBuf::from(partial);
let created = std::fs::File::create(&partial).with_context(|| format!("writing {}", partial.display()))?;
let mut out = CountingWriter {
inner: std::io::BufWriter::new(created),
bytes: 0,
};
let mut images: Vec<String> = Vec::new();
let written = paper
.write_html(analysis, &opts, &mut out, &mut |rel, data| {
let path = base.join(rel);
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)?;
}
std::fs::write(&path, data)?;
images.push(rel.to_string());
Ok(())
})
.and_then(|()| out.inner.flush());
if let Err(err) = written {
let _ = std::fs::remove_file(&partial);
return Err(err).with_context(|| format!("writing {}", file.display()));
}
std::fs::rename(&partial, file).with_context(|| format!("writing {}", file.display()))?;
let report = match images.first() {
Some(first) => format!(
" + {} image files in {}",
images.len(),
base.join(Path::new(first).parent().unwrap_or(Path::new(""))).display()
),
None => String::new(),
};
eprintln!(
"{:<8} -> {} ({:.1} MB{report}, {:.2}s)",
mode.name(),
file.display(),
out.bytes as f64 / BYTES_PER_MB,
started.elapsed().as_secs_f32()
);
Ok(())
}
struct CountingWriter<W> {
inner: W,
bytes: usize,
}
impl<W: Write> Write for CountingWriter<W> {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
let written = self.inner.write(buf)?;
self.bytes += written;
Ok(written)
}
fn flush(&mut self) -> std::io::Result<()> {
self.inner.flush()
}
}
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, header_rows: Option<usize>) -> Result<()> {
let (paper, _) = load(input, header_rows)?;
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::ContentsEntry { level, page } => format!("TOC{level} {page}"),
BlockKind::ListItem { marker, level } => format!("LI{level} {}", marker.clone().unwrap_or_default()),
BlockKind::ListContinuation => "LI+".to_string(),
BlockKind::Equation { number, image } => format!(
"EQ {} {}",
number.clone().unwrap_or_default(),
image
.map(|spec| format!("[{:.0}x{:.0}]", spec.rect.width(), spec.rect.height()))
.unwrap_or_else(|| "[math]".into())
),
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()
}
}
#[cfg(test)]
mod tests {
use super::{url_stem, utc_timestamp};
use std::time::{Duration, UNIX_EPOCH};
#[test]
fn addresses_give_file_names() {
assert_eq!(
url_stem("https://en.wikipedia.org/wiki/Rust_(programming_language)"),
"Rust_programming_language"
);
assert_eq!(url_stem("https://vi.wikipedia.org/wiki/H%C3%A0_N%E1%BB%99i"), "Hà_Nội");
assert_eq!(
url_stem("https://doc.rust-lang.org/book/ch04-01-what-is-ownership.html"),
"ch04-01-what-is-ownership"
);
assert_eq!(url_stem("https://example.org/"), "example.org");
assert_eq!(url_stem("https://example.org/a/b/?q=1"), "b");
}
#[test]
fn timestamps_are_utc_dates() {
assert_eq!(utc_timestamp(UNIX_EPOCH), "1970-01-01T00:00:00Z");
assert_eq!(
utc_timestamp(UNIX_EPOCH + Duration::from_secs(951_782_400 + 3_723)),
"2000-02-29T01:02:03Z"
);
assert_eq!(
utc_timestamp(UNIX_EPOCH + Duration::from_secs(1_794_960_000)),
"2026-11-18T00:00:00Z"
);
}
}