From dfdf3240b8506aa268dc049c27a2b88e8cf07bba Mon Sep 17 00:00:00 2001 From: Jack Hogan Date: Thu, 26 Nov 2026 18:17:19 +0000 Subject: [PATCH] Export dialogs as structured cells and typed parts --- DEV.md | 2 +- README.md | 2 +- py/src/lib.rs | 6 ++ python/aihist/hist.py | 17 +++- src/export.rs | 228 +++++++++++++++++++++++++++++++++++------- src/lib.rs | 8 +- src/output.rs | 70 +++++++++++-- src/reply.rs | 22 ++++ tests/aihist.rs | 51 +++++++++- tests/test_hist.py | 19 +++- 10 files changed, 370 insertions(+), 55 deletions(-) diff --git a/DEV.md b/DEV.md index b6d6112..96ce8fb 100644 --- a/DEV.md +++ b/DEV.md @@ -14,7 +14,7 @@ ship-rs-build The root package is a pure Rust crate, published to crates.io. Rust users who depend on it never build PyO3. `default = ["full"]` enables all modules; `default-features = false` exposes `output` (core `render`/`strip_ansi`/`keep_ends`/MIME helpers) and `paths` (`realpath`) with only `serde_json`. Its modules are: - `cells`: one notebook cell as a dialog message, and as a model reads it -- `export`: Markdown documents (`msg2md`, `dlg2md`), plain-text message parts (`msg2text`), and Python scripts (`msgs2py`) +- `export`: structured typed cell projection (`export_nb`, `export_cell`), Markdown documents (`msg2md`, `dlg2md`), plain-text message parts (`msg2text`), and Python scripts (`msgs2py`) - `input`: a prompt's model input, with the examples, CRAFTs, `$` values and warnings that a host supplies - `output`: code outputs and tool results as a model reads them - `media`: linked-media loading, MIME detection, resizing images, and media tags diff --git a/README.md b/README.md index e734352..b572e79 100644 --- a/README.md +++ b/README.md @@ -47,7 +47,7 @@ A saved reply is Markdown, with each tool call and its result in a fenced `json `dlg2chat` turns a dialog into chat messages, with each reply's tool calls as real parts, and `chat2dlg` turns chat messages back into a dialog. `reply2dlg` turns one reply into a dialog of notes and code that calls the tools, which `dlg2reply` turns back into the reply. `hist_xml`, `to_media` and `to_parts` give one message as a model reads it. -`dlg2md` writes a dialog as one Markdown document: notes as they are, code in language fences with its outputs in `::: output` divs, and each prompt and its reply in `::: prompt` and `::: reply` divs. `msg2md` writes one message. Both accept `language='python'` and inline stored attachments referenced by notes, prompts and replies; ordinary file links remain links. +`export_dlg` projects a dialog or notebook dict into `{frontmatter, language, cells}` structured typed parts (preserving cell IDs, metadata, types, typed source/output parts including Markdown, raw code, plain-text/HTML/image outputs with plain-text fallbacks, separated prompt-reply tool and usage blocks, and stored attachment maps) with `exportfilter`, `weave`, `frontmatter`, `att_data`, and kernelspec `language` inference. `dlg2md` joins those parts into one Markdown document (with stored attachments inlined, tools folded, code outputs in `::: output` divs, and prompts/replies in `::: prompt`/`::: reply` divs), and `msg2md` writes one message; ordinary file links remain links. `msg2text(m, part='input')` gives the source, or `part='output'` gives text output with prompt tools removed. `msgs2py(msgs)` writes nbdev-marked code; `full=True` includes all code, commenting notes, prompts, replies and outputs. These conversions read saved messages without fetching linked files or changing the dialog. diff --git a/py/src/lib.rs b/py/src/lib.rs index 40b9ca6..2997da9 100644 --- a/py/src/lib.rs +++ b/py/src/lib.rs @@ -211,6 +211,11 @@ fn msg2md(nb: &str, language: &str, weave: bool) -> PyResult> { Ok(export::msg2md_in(Some(&nb), cell, language, weave)) } +/// Project a notebook JSON into `{frontmatter, language, cells}` structured typed parts +#[pyfunction] +#[pyo3(signature = (nb, opts="{}"))] +fn export_nb(nb: &str, opts: &str) -> PyResult { Ok(ser(export::export_nb(&de(nb)?, &de(opts)?))) } + /// A notebook JSON as one Markdown document #[pyfunction] #[pyo3(signature = (nb, language="python", exportfilter=false, weave=false))] @@ -292,6 +297,7 @@ fn _core(m: &Bound<'_, PyModule>) -> PyResult<()> { m.add_function(wrap_pyfunction!(usage_md, m)?)?; m.add_function(wrap_pyfunction!(fmt_tools, m)?)?; m.add_function(wrap_pyfunction!(msg2md, m)?)?; + m.add_function(wrap_pyfunction!(export_nb, m)?)?; m.add_function(wrap_pyfunction!(dlg2md, m)?)?; m.add_function(wrap_pyfunction!(msg2text, m)?)?; m.add_function(wrap_pyfunction!(msgs2py, m)?)?; diff --git a/python/aihist/hist.py b/python/aihist/hist.py index 07d2351..1555100 100644 --- a/python/aihist/hist.py +++ b/python/aihist/hist.py @@ -11,7 +11,7 @@ __all__ = ['UNSUPPORTED_MSG', 'im_max', 'IMG_TOKS', 'jwrap', 'media_item', 'resize_img', 'prep_img', 'pdf_pages', 'count_tokens', 'output_parts', 'merge_media', 'tool_result', 'get_refs', 'get_exprs', 'is_nameerr', 'vars_tag', 'vars_hist', 'task_tags', 'warning_tag', 'cell_turn', 'cell_media', 'cell_reply', 'is_shown', 'references', 'hist_xml', 'to_media', 'to_parts', 'tool_call', 'build', 'dlg2hist', 'reply2chat', 'dlg2chat', 'chat2dlg', 'reply2dlg', - 'dlg2reply', 'msg2md', 'dlg2md', 'msg2text', 'msgs2py'] + 'dlg2reply', 'export_dlg', 'msg2md', 'dlg2md', 'msg2text', 'msgs2py'] UNSUPPORTED_MSG,im_max,IMG_TOKS = _core.UNSUPPORTED,_core.IM_MAX,_core.IMG_TOKENS @@ -286,7 +286,18 @@ def dlg2reply(sub): msgs += [Msg('assistant', [ToolUse(id=tr.id, name=tr.name, arguments=tr.arguments)]), Msg('tool', [tr])] return write_reply(msgs) -def _nb(d): return get_ipynb(d) if isinstance(d, Dialog) else msgs2ipynb(list(d)) +def _nb(d): return d if isinstance(d, dict) else get_ipynb(d) if isinstance(d, Dialog) else msgs2ipynb(list(d)) + +def export_dlg(d, + *, exportfilter:bool=False, # Keep only the messages `export_filter` selects? + weave:bool=False, # Code messages contribute only `render_text` over their outputs, as document prose? + language:str=None, # Kernel language for code parts (inferred from notebook metadata when None, else 'python') + frontmatter:bool=True, # Extract a leading raw/note YAML frontmatter cell? + att_data:bool=True, # Include base64 payloads in `cell['attachments']` (False keeps only MIME types)? +): + "Project a dialog or notebook dict into `{frontmatter, language, cells}` structured typed parts" + opts = json.dumps(dict(language=language, exportfilter=exportfilter, weave=weave, frontmatter=frontmatter, att_data=att_data)) + return json.loads(_core.export_nb(json.dumps(_nb(d)), opts)) def msg2md(m, weave:bool=False, # Code messages contribute only `render_text` over their outputs, as document prose? @@ -301,7 +312,7 @@ def dlg2md(d, *, language:str='python', # Kernel language for code fences ): "The dialog as one Markdown document" - return _core.dlg2md(json.dumps(_nb(d)), language, exportfilter, weave) + return _core.dlg2md(json.dumps(_nb(d)), language or '', exportfilter, weave) def msg2text(m, part='input'): "Input source or plain-text output for copying one message part" diff --git a/src/export.rs b/src/export.rs index fc214aa..2789458 100644 --- a/src/export.rs +++ b/src/export.rs @@ -1,13 +1,15 @@ -//! Export dialog cells as Markdown documents, plain-text parts, or Python scripts. +//! Export dialog cells as structured typed parts, Markdown documents, plain-text parts, or Python scripts. use percent_encoding::{AsciiSet, CONTROLS, utf8_percent_encode}; use regex::Regex; -use serde_json::Value; +use serde::{Deserialize, Serialize}; +use serde_json::{Map, Value}; +use std::collections::BTreeMap; use std::sync::LazyLock; use crate::cells::{self, ai_fmt, kind, msg, text_str, truthy}; -use crate::output::{render_md, render_outputs_ai, render_text}; -use crate::reply::{TOOL_INFO, USAGE_INFO, fenced_ch, fmt_tools, strip_blocks}; +use crate::output::{OutputPart, output_parts, render_outputs_ai, render_text}; +use crate::reply::{ReplyPart, TOOL_INFO, USAGE_INFO, fenced_ch, reply_parts, strip_blocks, tool_md, usage_md}; /// Characters encoded by Python's `urllib.parse.quote(s)` (default `safe='/'`) const QUOTE_SET: &AsciiSet = &CONTROLS.add(b' ').add(b'!').add(b'"').add(b'#').add(b'$').add(b'%').add(b'&').add(b'\'').add(b'(').add(b')').add(b'*').add(b'+') @@ -16,23 +18,101 @@ const QUOTE_SET: &AsciiSet = &CONTROLS.add(b' ').add(b'!').add(b'"').add(b'#').a static DIRECTIVE_RE: LazyLock = LazyLock::new(|| Regex::new(r"(?m)^\s*#\|\s*exports?\b").expect("valid regex")); +/// Options controlling structured notebook export (`export_nb`). +#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] +#[serde(default)] +pub struct ExportOpts { pub language: Option, pub exportfilter: bool, pub weave: bool, pub frontmatter: bool, pub att_data: bool } + +impl Default for ExportOpts { + fn default() -> Self { Self { language: None, exportfilter: false, weave: false, frontmatter: true, att_data: true } } +} + +/// One stored cell attachment: MIME type and optional whitespace-free base64 payload. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct ExportAttachment { pub mime: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub data: Option } + +/// One typed piece of an exported cell's source or output. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(tag = "type", rename_all = "lowercase")] +pub enum ExportPart { + Md { text: String }, Code { lang: String, text: String }, Text { text: String }, + Html { html: String, #[serde(default, skip_serializing_if = "Option::is_none")] text: Option }, + Image { mime: String, data: String, #[serde(default, skip_serializing_if = "Option::is_none")] text: Option }, Tool { data: Value }, + Usage { data: Value } +} + +/// One dialog cell projected into typed source/output parts, stored attachments, and cell metadata. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct ExportCell { + pub id: String, pub kind: String, pub src: Vec, pub out: Vec, pub attachments: BTreeMap, + pub meta: Map +} + +/// A notebook projected into optional leading YAML frontmatter and structured typed cells. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct ExportDoc { pub frontmatter: String, pub language: String, pub cells: Vec } + fn quote_att(id: &str) -> String { utf8_percent_encode(id, QUOTE_SET).to_string() } -/// Rewrite `attachment:` references in `text` as data URIs from `cell`'s stored attachments -fn inline_atts(nb: Option<&Value>, cell: &Value, mut text: String) -> String { +fn cell_attachments(nb: Option<&Value>, cell: &Value, att_data: bool) -> BTreeMap { let atts = nb.and_then(|n| cells::stored_atts(n, cell)).or_else(|| cell["attachments"].as_object()); - let Some(atts) = atts else { return text; }; - for (id, by_mime) in atts { + let mut out = BTreeMap::new(); + for (id, by_mime) in atts.into_iter().flatten() { let Some((mime, data_v)) = by_mime.as_object().and_then(|m| m.iter().next()) else { continue; }; - let b64 = text_str(data_v); - let uri = format!("data:{mime};base64,{b64}"); - let raw_ref = format!("attachment:{id}"); - let enc_ref = format!("attachment:{}", quote_att(id)); - text = text.replace(&raw_ref, &uri).replace(&enc_ref, &uri); + let data = att_data.then(|| text_str(data_v).split_whitespace().collect()); + out.insert(id.clone(), ExportAttachment { mime: mime.clone(), data }); + } + out +} + +/// Rewrite stored `attachment:` references as data URIs for flat Markdown export, longest name first. +fn inline_atts(atts: &BTreeMap, mut text: String) -> String { + if atts.is_empty() || !text.contains("attachment:") { return text; } + let mut refs: Vec<(String, String)> = Vec::with_capacity(atts.len() * 2); + for (id, att) in atts { + let Some(data) = &att.data else { continue; }; + let uri = format!("data:{};base64,{data}", att.mime); + let enc = quote_att(id); + refs.push((id.clone(), uri.clone())); + if enc != *id { refs.push((enc, uri)); } } + refs.sort_by_key(|a| std::cmp::Reverse(a.0.len())); + for (k, uri) in &refs { text = text.replace(&format!("attachment:{k}"), uri); } text } +fn has_mapping_pair(line: &str) -> bool { + line.char_indices().any(|(i, c)| c == ':' && !line[..i].trim().is_empty() && line[i + 1..].chars().next().is_none_or(char::is_whitespace)) +} + +fn split_frontmatter(src: &str) -> Option<(String, &str)> { + let mut lines = src.split_inclusive('\n'); + let first = lines.next()?; + if first.trim_end() != "---" { return None; } + let (mut pos, mut mapping) = (first.len(), false); + for line in lines { + pos += line.len(); + let t = line.trim_end(); + if t == "---" || t == "..." { return mapping.then(|| (format!("{}\n", src[..pos].trim_end()), &src[pos..])); } + let t = t.trim(); + if t.is_empty() || t.starts_with('#') { continue; } + if !mapping { + if !has_mapping_pair(t) { return None; } + mapping = true; + } + } + None +} + +fn resolve_language(nb: Option<&Value>, language: Option<&str>) -> String { + if let Some(l) = language.filter(|s| !s.is_empty()) { return l.to_owned(); } + if let Some(nb) = nb { + if let Some(l) = nb["metadata"]["kernelspec"]["language"].as_str().filter(|s| !s.is_empty()) { return l.to_owned(); } + if let Some(l) = nb["metadata"]["language_info"]["name"].as_str().filter(|s| !s.is_empty()) { return l.to_owned(); } + } + "python".into() +} + /// Whether `cell` carries an nbdev `export` or `exports` directive in metadata or source comments pub fn is_exported(cell: &Value) -> bool { let nbdev = &cell["metadata"]["nbdev"]; @@ -40,43 +120,123 @@ pub fn is_exported(cell: &Value) -> bool { DIRECTIVE_RE.is_match(&cells::content(cell)) } -/// One cell as Markdown, resolving prompt/code attachments from `nb` when present; `None` for empty code -pub fn msg2md_in(nb: Option<&Value>, cell: &Value, language: &str, weave: bool) -> Option { +fn export_cell_with(nb: Option<&Value>, cell: &Value, language: &str, weave: bool, att_data: bool) -> Option { + let id = cell["id"].as_str().unwrap_or_default().to_owned(); + let attachments = cell_attachments(nb, cell, att_data); + let meta = cell["metadata"].as_object().cloned().unwrap_or_default(); let m = msg(cell); + let md = |text: String| if text.is_empty() { Vec::new() } else { vec![ExportPart::Md { text }] }; match m.typ { - "note" => Some(inline_atts(nb, cell, m.content)), - "raw" => Some(fenced_ch(&m.content, "", '`')), + "note" => Some(ExportCell { id, kind: "note".into(), src: md(m.content), out: Vec::new(), attachments, meta }), + "raw" => { + let src = if m.content.is_empty() { Vec::new() } else { vec![ExportPart::Code { lang: String::new(), text: m.content }] }; + Some(ExportCell { id, kind: "raw".into(), src, out: Vec::new(), attachments, meta }) + } "prompt" => { - let mut parts = vec![fenced_ch(&inline_atts(nb, cell, m.content), " prompt", ':')]; - if !m.out.trim().is_empty() { parts.push(fenced_ch(&inline_atts(nb, cell, fmt_tools(&m.out)), " reply", ':')); } - Some(parts.join("\n\n")) + let out = reply_parts(&m.out).into_iter().map(|p| match p { + ReplyPart::Md(text) => ExportPart::Md { text }, ReplyPart::Tool(data) => ExportPart::Tool { data }, + ReplyPart::Usage(data) => ExportPart::Usage { data } + }).collect(); + Some(ExportCell { id, kind: "prompt".into(), src: md(m.content), out, attachments, meta }) } _ => { let outs = cell["outputs"].as_array().map(Vec::as_slice).unwrap_or_default(); - if weave { let text = render_text(outs, false, false); return (!text.is_empty()).then_some(text); } + if weave { + let text = render_text(outs, false, false); + return (!text.is_empty()).then(|| ExportCell { id, kind: "code".into(), src: vec![ExportPart::Md { text }], out: Vec::new(), attachments, meta + }); + } + let src = if m.content.trim().is_empty() { Vec::new() } else { vec![ExportPart::Code { lang: language.to_owned(), text: m.content }] }; + let out: Vec = output_parts(outs, true).into_iter().map(|p| match p { + OutputPart::Text(text) => ExportPart::Text { text }, OutputPart::Md(text) => ExportPart::Md { text }, + OutputPart::Html { html, text } => ExportPart::Html { html, text }, + OutputPart::Image { mime, data, text } => ExportPart::Image { mime, data, text } + }).collect(); + if src.is_empty() && out.is_empty() { None } else { Some(ExportCell { id, kind: "code".into(), src, out, attachments, meta }) } + } + } +} + +/// Project one cell into typed source/output parts; `None` for empty code cells. +pub fn export_cell(nb: Option<&Value>, cell: &Value, language: &str, weave: bool) -> Option { export_cell_with(nb, cell, language, weave, true) } + +fn parts_to_md(parts: &[ExportPart], atts: &BTreeMap) -> String { + parts.iter().map(|p| match p { + ExportPart::Md { text } => inline_atts(atts, text.clone()), ExportPart::Code { lang, text } => fenced_ch(text, lang, '`'), + ExportPart::Text { text } => fenced_ch(text, "output", '`'), ExportPart::Html { html, .. } => fenced_ch(html, "{=html}", '`'), + ExportPart::Image { mime, data, .. } => format!("![](data:{mime};base64,{data})"), ExportPart::Tool { data } => tool_md(data), + ExportPart::Usage { data } => usage_md(data) + }).filter(|s| !s.is_empty()).collect::>().join("\n\n") +} + +fn cell_to_md(c: &ExportCell, weave: bool) -> String { + let (src, out) = (parts_to_md(&c.src, &c.attachments), parts_to_md(&c.out, &c.attachments)); + match c.kind.as_str() { + "note" => src, + "raw" => { if src.is_empty() { fenced_ch("", "", '`') } else { src } } + "prompt" => { + let mut parts = vec![fenced_ch(&src, " prompt", ':')]; + if !out.is_empty() { parts.push(fenced_ch(&out, " reply", ':')); } + parts.join("\n\n") + } + _ if weave => src, + _ => { let mut parts = Vec::new(); - if !m.content.trim().is_empty() { parts.push(fenced_ch(&m.content, language, '`')); } - let rendered = render_md(outs, true); - if !rendered.is_empty() { parts.push(fenced_ch(&rendered, " output", ':')); } - (!parts.is_empty()).then(|| parts.join("\n\n")) + if !src.is_empty() { parts.push(src); } + if !out.is_empty() { parts.push(fenced_ch(&out, " output", ':')); } + parts.join("\n\n") } } } -/// One cell as Markdown with `language` code fences and stored attachments inlined; `None` for empty code -pub fn msg2md(cell: &Value, language: &str) -> Option { msg2md_in(None, cell, language, false) } +fn filter_exported<'a>(cells: &[&'a Value]) -> Vec<&'a Value> { + let exp: Vec<_> = cells.iter().copied().filter(|c| is_exported(c)).collect(); + if !exp.is_empty() { exp } else { cells.iter().copied().filter(|c| !truthy(&c["metadata"]["pinned"])).collect() } +} + +/// Project a notebook into optional leading YAML frontmatter and structured typed cells. +pub fn export_nb(nb: &Value, opts: &ExportOpts) -> ExportDoc { + let language = resolve_language(Some(nb), opts.language.as_deref()); + let all = nb["cells"].as_array().map(Vec::as_slice).unwrap_or_default(); + let (mut frontmatter, mut owned_first, mut start) = (String::new(), None, 0usize); + if opts.frontmatter && let Some(first) = all.first() { + let k = kind(first); + if (k == "raw" || k == "note") && let Some((fm, rest)) = split_frontmatter(&cells::content(first)) { + if rest.trim().is_empty() { + frontmatter = fm; + start = 1; + } else if k == "note" { + frontmatter = fm; + let mut c = first.clone(); + c["source"] = Value::String(rest.trim_start_matches(['\r', '\n']).to_owned()); + owned_first = Some(c); + start = 1; + } + } + } + let body: Vec<&Value> = owned_first.iter().chain(&all[start..]).collect(); + let selected = if opts.exportfilter { filter_exported(&body) } else { body }; + let cells = selected.into_iter().filter_map(|c| export_cell_with(Some(nb), c, &language, opts.weave, opts.att_data)).collect(); + ExportDoc { frontmatter, language, cells } +} -fn filter_exported(cells: &[Value]) -> Vec<&Value> { - let exp: Vec<&Value> = cells.iter().filter(|c| is_exported(c)).collect(); - if !exp.is_empty() { exp } else { cells.iter().filter(|c| !truthy(&c["metadata"]["pinned"])).collect() } +/// One cell as Markdown, resolving prompt/code attachments from `nb` when present; `None` for empty code +pub fn msg2md_in(nb: Option<&Value>, cell: &Value, language: &str, weave: bool) -> Option { + let lang = resolve_language(nb, (!language.is_empty()).then_some(language)); + export_cell(nb, cell, &lang, weave).map(|c| cell_to_md(&c, weave)) } +/// One cell as Markdown with `language` code fences and stored attachments inlined; `None` for empty code +pub fn msg2md(cell: &Value, language: &str) -> Option { msg2md_in(None, cell, language, false) } + /// A notebook as one Markdown document, with optional export filtering and `weave` output-only code cells pub fn dlg2md_nb(nb: &Value, language: &str, exportfilter: bool, weave: bool) -> String { - let cells = nb["cells"].as_array().map(Vec::as_slice).unwrap_or_default(); - let selected: Vec<&Value> = if exportfilter { filter_exported(cells) } else { cells.iter().collect() }; - let joined = selected.into_iter().filter_map(|c| msg2md_in(Some(nb), c, language, weave)).filter(|s| !s.is_empty()).collect::>().join("\n\n"); - format!("{joined}\n") + let opts = ExportOpts { language: (!language.is_empty()).then(|| language.to_owned()), exportfilter, weave, ..Default::default() }; + let doc = export_nb(nb, &opts); + let mut parts = Vec::new(); + if !doc.frontmatter.is_empty() { parts.push(doc.frontmatter.trim_end().to_owned()); } + for c in &doc.cells { let s = cell_to_md(c, weave); if !s.is_empty() { parts.push(s); } } + format!("{}\n", parts.join("\n\n")) } /// Cells as one Markdown document with `language` code fences and stored attachments inlined diff --git a/src/lib.rs b/src/lib.rs index af54385..f95d171 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -17,8 +17,12 @@ pub mod paths; #[cfg(feature = "full")] pub mod reply; #[cfg(feature = "full")] pub mod tokens; -#[cfg(feature = "full")] pub use export::{dlg2md, dlg2md_nb, msg2md, msg2md_in, msg2text, msgs2py}; -#[cfg(feature = "full")] pub use reply::{fmt_tools, tool_md, usage_md}; +#[cfg(feature = "full")] +pub use export::{ + ExportAttachment, ExportCell, ExportDoc, ExportOpts, ExportPart, dlg2md, dlg2md_nb, export_cell, export_nb, msg2md, msg2md_in, msg2text, msgs2py, +}; +#[cfg(feature = "full")] pub use output::{OutputPart, output_parts}; +#[cfg(feature = "full")] pub use reply::{ReplyPart, fmt_tools, reply_parts, tool_md, usage_md}; /// What a model can read, as a model catalog entry or fastllm's `get_model_info` gives it #[cfg(feature = "full")] diff --git a/src/output.rs b/src/output.rs index 5041b98..c7e437e 100644 --- a/src/output.rs +++ b/src/output.rs @@ -299,16 +299,54 @@ pub fn render_outputs_ai(outputs: &[Value], dollars: bool) -> String { }).collect::>().join("\n") } -/// Render notebook outputs as Markdown: text in `output` fences, HTML in `{=html}`, Markdown inlined, images as data URIs +/// One structured display part of a code cell's outputs. #[cfg(feature = "full")] -pub fn render_md(outputs: &[Value], html1st: bool) -> String { +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum OutputPart { Text(String), Md(String), Html { html: String, text: Option }, Image { mime: String, data: String, text: Option } } + +#[cfg(feature = "full")] +fn plain_fallback(out: &Value) -> Option { + let s = strip_ansi(&text_str(out["data"].as_object()?.get("text/plain")?)); + let trimmed = s.trim_end(); + (!trimmed.is_empty()).then(|| trimmed.to_owned()) +} + +#[cfg(feature = "full")] +fn merge_streams(outputs: &[Value]) -> Vec { + let (mut res, mut cur): (Vec, Option<(&str, String)>) = (Vec::new(), None); + let flush = |cur: &mut Option<(&str, String)>, res: &mut Vec| { + let Some((name, text)) = cur.take() else { return; }; + if name == "markdown" { res.push(json!({"output_type": "display_data", "data": {"text/markdown": text}, "metadata": {}})); } + else { res.push(json!({"output_type": "stream", "name": name, "text": clean_cli(&text)})); } + }; + for out in outputs { + let stream = + (out["output_type"].as_str() == Some("stream")).then(|| out["name"].as_str().filter(|&n| matches!(n, "stdout" | "stderr" | "markdown"))).flatten(); + if let Some(name) = stream { + let text = text_str(&out["text"]); + if let Some((prev, buf)) = &mut cur && *prev == name { buf.push_str(&text); } else { + flush(&mut cur, &mut res); + cur = Some((name, text)); + } + } else { + flush(&mut cur, &mut res); + res.push(out.clone()); + } + } + flush(&mut cur, &mut res); + res +} + +/// Project notebook outputs into typed display parts, preserving output order and merging adjacent plain-text streams. +#[cfg(feature = "full")] +pub fn output_parts(outputs: &[Value], html1st: bool) -> Vec { let (mut parts, mut buf) = (Vec::new(), String::new()); - let flush = |buf: &mut String, parts: &mut Vec| { + let flush = |buf: &mut String, parts: &mut Vec| { let trimmed = buf.trim_end(); - if !trimmed.is_empty() { parts.push(crate::reply::fenced_ch(trimmed, "output", '`')); } + if !trimmed.is_empty() { parts.push(OutputPart::Text(trimmed.to_owned())); } buf.clear(); }; - for o in concat_streams(outputs) { + for o in merge_streams(outputs) { let (mime, d) = preferred_msg_out(&o, html1st, true); if d.is_empty() { continue; } match mime { @@ -319,26 +357,36 @@ pub fn render_md(outputs: &[Value], html1st: bool) -> String { } "text/html" | "image/svg+xml" => { flush(&mut buf, &mut parts); - parts.push(crate::reply::fenced_ch(d.trim(), "{=html}", '`')); + parts.push(OutputPart::Html { html: d.trim().to_owned(), text: plain_fallback(&o) }); } "application/javascript" => { flush(&mut buf, &mut parts); - parts.push(crate::reply::fenced_ch(&format!(""), "{=html}", '`')); + parts.push(OutputPart::Html { html: format!(""), text: plain_fallback(&o) }); } "text/markdown" | "text/latex" => { flush(&mut buf, &mut parts); - parts.push(d.trim().to_owned()); + parts.push(OutputPart::Md(d.trim().to_owned())); } "image/jpeg" | "image/png" | "image/webp" => { flush(&mut buf, &mut parts); - let b64: String = d.split_whitespace().collect(); - parts.push(format!("![](data:{mime};base64,{b64})")); + let data: String = d.split_whitespace().collect(); + parts.push(OutputPart::Image { mime: mime.to_owned(), data, text: plain_fallback(&o) }); } _ => {} } } flush(&mut buf, &mut parts); - parts.join("\n\n") + parts +} + +/// Render notebook outputs as Markdown: text in `output` fences, HTML in `{=html}`, Markdown inlined, images as data URIs +#[cfg(feature = "full")] +pub fn render_md(outputs: &[Value], html1st: bool) -> String { + output_parts(outputs, html1st).into_iter().map(|p| match p { + OutputPart::Text(t) => crate::reply::fenced_ch(&t, "output", '`'), OutputPart::Md(t) => t, + OutputPart::Html { html, .. } => crate::reply::fenced_ch(&html, "{=html}", '`'), + OutputPart::Image { mime, data, .. } => format!("![](data:{mime};base64,{data})") + }).collect::>().join("\n\n") } /// Concise ANSI-stripped text for outputs, wrapped in XML-ish tags when multiple outputs appear diff --git a/src/reply.rs b/src/reply.rs index e31be3d..a2e7845 100644 --- a/src/reply.rs +++ b/src/reply.rs @@ -457,6 +457,28 @@ pub fn usage_md(d: &Value) -> String { fenced_ch(&format!("## {summ}\n\n{}", code_span(&det)), " {.details .token-usage-details}", ':') } +/// One piece of a saved reply: Markdown prose, a parsed `{.tool}` block, or a parsed `{.usage}` block. +#[derive(Debug, Clone, PartialEq)] +pub enum ReplyPart { Md(String), Tool(Value), Usage(Value) } + +/// Split a saved reply into alternating `Md`, `Tool`, and `Usage` parts; invalid JSON fences remain inside prose. +pub fn reply_parts(s: &str) -> Vec { + let (mut parts, mut pos) = (Vec::new(), 0); + let push_md = |parts: &mut Vec, chunk: &str| { + let t = chunk.trim_matches(['\r', '\n']); + if !t.trim().is_empty() { parts.push(ReplyPart::Md(t.to_owned())); } + }; + for (info, body, start, end) in fenced_blocks(s) { + if info != TOOL_INFO && info != USAGE_INFO { continue; } + let Ok(data) = serde_json::from_str::(body) else { continue; }; + push_md(&mut parts, &s[pos..start]); + parts.push(if info == TOOL_INFO { ReplyPart::Tool(data) } else { ReplyPart::Usage(data) }); + pos = end; + } + push_md(&mut parts, &s[pos..]); + parts +} + /// Rewrite fenced JSON tool and usage blocks in `s` into folded `::: details` display Markdown pub fn fmt_tools(s: &str) -> String { let (mut out, mut pos) = (String::with_capacity(s.len()), 0); diff --git a/tests/aihist.rs b/tests/aihist.rs index 6f60cc0..f119ea5 100644 --- a/tests/aihist.rs +++ b/tests/aihist.rs @@ -4,7 +4,7 @@ use aihist::output::keep_ends; #[cfg(feature = "full")] use aihist::tokens::{IMG_TOKENS, PDF_PAGE_TOKENS, bundle, cell, count, pdf_pages}; -#[cfg(feature = "full")] use aihist::{dlg2md_nb, msg2md_in, msg2text, msgs2py}; +#[cfg(feature = "full")] use aihist::{ExportAttachment, ExportOpts, ExportPart, dlg2md_nb, export_nb, msg2md_in, msg2text, msgs2py}; #[test] fn keep_ends_cuts_the_middle_at_char_boundaries() { @@ -84,4 +84,53 @@ fn markdown_text_and_python_exports() { assert_eq!(msgs2py(cells, false), "x = 1"); let full = msgs2py(cells, true); assert!(full.contains("# --- Cell: p1 (prompt) ---") && full.contains("#> ok") && full.contains("# --- Assistant Response ---")); + + // Structured cell export returns typed parts, attachment maps, cell metadata, and multi-MIME fallbacks. + let mut with_fm = nb.clone(); + with_fm["metadata"]["kernelspec"] = json!({"language": "julia"}); + with_fm["cells"].as_array_mut().unwrap().insert(0, json!({"id": "fm", "cell_type": "raw", "metadata": {}, "source": "---\ntitle: Demo\n---"})); + with_fm["cells"].as_array_mut().unwrap().push(json!({ + "id": "c2", "cell_type": "code", "metadata": {}, "source": "show()", + "outputs": [ + {"output_type": "display_data", "metadata": {}, "data": {"text/html": "hi", "text/plain": "\x1b[1mhi\x1b[0m"}}, + {"output_type": "display_data", "metadata": {}, "data": {"image/png": "CC\nCC", "text/plain": ""}} + ] + })); + with_fm["cells"].as_array_mut().unwrap().push(json!({"id": "sk", "cell_type": "markdown", "metadata": {"skipped": true}, "source": "hidden"})); + + let exp = export_nb(&with_fm, &ExportOpts::default()); + assert_eq!((exp.frontmatter.as_str(), exp.language.as_str()), ("---\ntitle: Demo\n---\n", "julia")); + assert_eq!(exp.cells.iter().map(|c| c.id.as_str()).collect::>(), vec!["n1", "c1", "p1", "c2", "sk"]); + assert_eq!(exp.cells[0].attachments.get("a.png"), Some(&ExportAttachment { mime: "image/png".into(), data: Some("AAAA".into()) })); + assert_eq!(exp.cells[1].src, vec![ExportPart::Code { lang: "julia".into(), text: "x = 1".into() }]); + assert_eq!(exp.cells[1].out, vec![ExportPart::Text { text: "ok".into() }]); + assert_eq!(exp.cells[1].meta.get("nbdev"), Some(&json!({"export": "true"}))); + assert!(matches!(exp.cells[2].out.as_slice(), [ExportPart::Md { .. }, ExportPart::Tool { .. }, ExportPart::Md { .. }])); + assert_eq!( + exp.cells[3].out, vec![ + ExportPart::Html { html: "hi".into(), text: Some("hi".into()) }, + ExportPart::Image { mime: "image/png".into(), data: "CCCC".into(), text: Some("".into()) }, + ] + ); + assert_eq!(exp.cells[4].meta.get("skipped"), Some(&json!(true))); + + let filt = export_nb(&with_fm, &ExportOpts { exportfilter: true, ..Default::default() }); + assert_eq!((filt.frontmatter.as_str(), filt.cells.len(), filt.cells[0].id.as_str()), ("---\ntitle: Demo\n---\n", 1, "c1")); + let no_fm = export_nb(&with_fm, &ExportOpts { frontmatter: false, ..Default::default() }); + assert!(no_fm.frontmatter.is_empty() && no_fm.cells[0].src == vec![ExportPart::Code { lang: String::new(), text: "---\ntitle: Demo\n---".into() }]); + // Interleaved streams and rich displays keep their exact notebook order, merging only consecutive stream runs. + let inter = json!({"cells": [{"id": "i", "cell_type": "code", "metadata": {}, "source": "run()", "outputs": [ + {"output_type": "stream", "name": "stdout", "text": "## Results\n"}, {"output_type": "stream", "name": "stdout", "text": "Two rows.\n"}, + {"output_type": "display_data", "metadata": {}, "data": {"text/markdown": "| a | b |\n|---|---|\n| 1 | 2 |"}}, + {"output_type": "stream", "name": "stdout", "text": "*Table 1*\n"} + ]}]}); + assert_eq!( + export_nb(&inter, &ExportOpts::default()).cells[0].out, vec![ + ExportPart::Text { text: "## Results\nTwo rows.".into() }, ExportPart::Md { text: "| a | b |\n|---|---|\n| 1 | 2 |".into() }, + ExportPart::Text { text: "*Table 1*".into() }, + ] + ); + // Longest-first attachment inlining avoids prefix collisions (`a.png` vs `a.png2`). + let pfx_nb = json!({"cells": [{"id": "p", "cell_type": "markdown", "metadata": {}, "source": "![1](attachment:a.png) ![2](attachment:a.png2)", "attachments": {"a.png": {"image/png": "AAA"}, "a.png2": {"image/png": "BBB"}}}]}); + assert_eq!(dlg2md_nb(&pfx_nb, "", false, false), "![1](data:image/png;base64,AAA) ![2](data:image/png;base64,BBB)\n"); } diff --git a/tests/test_hist.py b/tests/test_hist.py index bbf3bff..b2c3149 100644 --- a/tests/test_hist.py +++ b/tests/test_hist.py @@ -5,8 +5,8 @@ from aidialog.dialog import Dialog, Message, Attachment, prompt_output, code_output, displayobj from aidialog.msg_parts import Msg, Text, ToolUse, ToolResult, hist2fmt from aihist import (build, dlg2hist, dlg2chat, chat2dlg, reply2dlg, dlg2reply, tool_call, hist_xml, to_parts, to_media, media_item, resize_img, - pdf_pages, output_parts, merge_media, vars_hist, is_nameerr, get_exprs, get_refs, references, cell_turn, _core, task_tags, warning_tag, msg2md, dlg2md, - msg2text, msgs2py) + pdf_pages, output_parts, merge_media, vars_hist, is_nameerr, get_exprs, get_refs, references, cell_turn, _core, task_tags, warning_tag, + export_dlg, msg2md, dlg2md, msg2text, msgs2py) png = base64.b64decode('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAAAAAA6fptVAAAACklEQVR4nGP4DwABAQEAsTj2FAAAAABJRU5ErkJggg==') images = dict(input_modalities=['text', 'image']) @@ -155,3 +155,18 @@ def test_markdown_documents(): assert dlg2md(d, weave=True).split('\n\n')[1] == '64' d.messages[2].pinned = True assert '::: prompt' not in dlg2md(d, exportfilter=True) + # `export_dlg` preserves cell identity, metadata, typed parts, and attachment maps. + fm = Message('---\ntitle: Demo\n---', msg_type='raw') + rich = Message('table()', output=[dict(output_type='display_data', metadata={}, data={'text/html': '1
', 'text/plain': '1'})]) + d2 = Dialog([fm, *d.messages, rich, Message('hidden', msg_type='note', skipped=True)], meta=dict(kernelspec=dict(language='julia'))) + exp = export_dlg(d2) + assert exp['frontmatter'] == '---\ntitle: Demo\n---\n' and exp['language'] == 'julia' + assert [c['kind'] for c in exp['cells']] == ['note', 'code', 'prompt', 'code', 'code', 'note'] + assert exp['cells'][0]['src'] == [dict(type='md', text='# Results ![plot](attachment:img1.png)')] and exp['cells'][0]['attachments']['img1.png']['mime'] == 'image/png' + assert export_dlg(d2, att_data=False)['cells'][0]['attachments'] == {'img1.png': {'mime': 'image/png'}} + assert exp['cells'][1]['src'] == [dict(type='code', lang='julia', text='8*8')] and exp['cells'][1]['out'] == [dict(type='text', text='64')] + assert [p['type'] for p in exp['cells'][2]['out']] == ['tool', 'md'] and exp['cells'][4]['out'] == [dict(type='html', html='1
', text='1')] + assert exp['cells'][5]['meta'].get('skipped') is True and export_dlg(d2, exportfilter=True)['frontmatter'] == '---\ntitle: Demo\n---\n' + assert dlg2md(d2).startswith('---\ntitle: Demo\n---\n\n# Results ![plot](data:image/png;base64,') and '```python\n8*8' in dlg2md(d2) + assert export_dlg(dict(cells=[dict(id='a', cell_type='markdown', source='hi')]))['cells'][0] == dict( + id='a', kind='note', src=[dict(type='md', text='hi')], out=[], attachments={}, meta={})