World's first open-source enterprise world model.
Rust agent-memorybitemporalgraphragknowledge-baseknowledge-graphllmontologypgvectorpostgresqlragrustself-hostedsemantic-searchtemporal-knowledge-graphworld-model
Read PPTX slides in presentation order (#817)
Maya Kid2556a5a6389b
diff --git a/crates/utopia-ingest/src/parsers.rs b/crates/utopia-ingest/src/parsers.rsindex 035803ef..1058a9b8 100644--- a/crates/utopia-ingest/src/parsers.rs+++ b/crates/utopia-ingest/src/parsers.rs@@ -256,28 +256,36 @@ pub(crate) fn docx_xml_to_text(xml: &str) -> anyhow::Result<String> {Ok(out)}-/// pptx: 按页码顺序解析 ppt/slides/slideN.xml,取 a:t 文本。+/// PPTX: extract a:t text in the presentation's logical slide order.pub fn pptx(bytes: &[u8]) -> anyhow::Result<String> {let mut archive =zip::ZipArchive::new(Cursor::new(bytes.to_vec())).context("Failed to unzip pptx")?;- let mut slides: Vec<(u32, String)> = Vec::new();- for i in 0..archive.len() {- let name = archive.by_index(i)?.name().to_string();- if let Some(num) = name- .strip_prefix("ppt/slides/slide")- .and_then(|s| s.strip_suffix(".xml"))- .and_then(|s| s.parse::<u32>().ok())- {- slides.push((num, name));+ let slides = if let Some(names) = pptx_order(&mut archive)? {+ names+ .into_iter()+ .enumerate()+ .map(|(i, name)| (i as u32 + 1, name))+ .collect()+ } else {+ let mut slides: Vec<(u32, String)> = Vec::new();+ for i in 0..archive.len() {+ let name = archive.by_index(i)?.name().to_string();+ if let Some(num) = name+ .strip_prefix("ppt/slides/slide")+ .and_then(|s| s.strip_suffix(".xml"))+ .and_then(|s| s.parse::<u32>().ok())+ {+ slides.push((num, name));+ }}- }- slides.sort();+ slides.sort();++ slides+ };let mut out = String::new();for (num, name) in slides {- let mut entry = archive.by_name(&name)?;- let mut xml = String::new();- entry.read_to_string(&mut xml)?;+ let xml = pptx_part(&mut archive, &name)?;let text = extract_xml_text(&xml, "a:t", "a:p")?;if !text.trim().is_empty() {out.push_str(&format!("\n## Slide {num}\n{text}\n"));@@ -286,6 +294,240 @@ pub fn pptx(bytes: &[u8]) -> anyhow::Result<String> {Ok(out)}+const PPT_NS: &str = "http://schemas.openxmlformats.org/presentationml/2006/main";+const REL_NS: &str = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";+const PACKAGE_REL_NS: &str = "http://schemas.openxmlformats.org/package/2006/relationships";++fn pptx_part(archive: &mut zip::ZipArchive<Cursor<Vec<u8>>>, name: &str) -> anyhow::Result<String> {+ let mut xml = String::new();+ archive+ .by_name(name)+ .with_context(|| format!("Missing PPTX part: {name}"))?+ .read_to_string(&mut xml)?;+ Ok(xml)+}++// Relationship targets are package URIs, never paths to open or URLs to fetch.+fn pptx_target(source: &str, target: &str) -> anyhow::Result<String> {+ anyhow::ensure!(+ !target.contains([':', '\\', '?', '#']) && !target.starts_with("//"),+ "Invalid PPTX part target"+ );+ let target = percent_encoding::percent_decode_str(target).decode_utf8()?;+ anyhow::ensure!(+ !target.contains([':', '\\', '?', '#', '\0']) && !target.starts_with("//"),+ "Invalid PPTX part target"+ );+ let mut parts: Vec<&str> = if target.starts_with('/') {+ Vec::new()+ } else {+ source+ .rsplit_once('/')+ .map(|(dir, _)| dir.split('/').collect())+ .unwrap_or_default()+ };+ for part in target.split('/') {+ match part {+ "" | "." => {}+ ".." => {+ anyhow::ensure!(parts.pop().is_some(), "PPTX target escapes package");+ }+ _ => parts.push(part),+ }+ }+ anyhow::ensure!(!parts.is_empty(), "Empty PPTX part target");+ Ok(parts.join("/"))+}++// Only the requested relationship type is returned. Other types (notes, masters,+// hyperlinks) cannot become slides. Reject ambiguity rather than silently losing pages.+fn pptx_relationships(+ xml: &str,+ kind: &str,+ source: &str,+) -> anyhow::Result<std::collections::HashMap<String, String>> {+ use quick_xml::name::{Namespace, ResolveResult};+ let mut reader = quick_xml::NsReader::from_str(xml);+ let mut depth = 0;+ let mut root = false;+ let mut ids = std::collections::HashSet::new();+ let mut targets = std::collections::HashMap::new();+ loop {+ let event = reader.read_event()?;+ match &event {+ Event::Start(e) | Event::Empty(e) => {+ let (ns, local) = reader.resolver().resolve_element(e.name());+ let package = ns == ResolveResult::Bound(Namespace(PACKAGE_REL_NS));+ if depth == 0 {+ anyhow::ensure!(+ !root && package && local.as_ref() == "Relationships",+ "Invalid PPTX relationships root"+ );+ root = true;+ } else if depth == 1 && package && local.as_ref() == "Relationship" {+ let attrs: std::collections::HashMap<_, _> = e+ .attributes()+ .map(|a| {+ let a = a?;+ Ok((+ a.key.as_ref().to_string(),+ a.normalized_value(quick_xml::XmlVersion::Implicit1_0)?+ .into_owned(),+ ))+ })+ .collect::<anyhow::Result<_>>()?;+ let id = attrs.get("Id").context("PPTX relationship has no Id")?;+ anyhow::ensure!(ids.insert(id.clone()), "Duplicate PPTX relationship Id");+ let ty = attrs.get("Type").context("PPTX relationship has no Type")?;+ if ty == &format!("{REL_NS}/{kind}")+ || ty+ == &format!(+ "http://purl.oclc.org/ooxml/officeDocument/relationships/{kind}"+ )+ {+ anyhow::ensure!(+ attrs.get("TargetMode").is_none_or(|m| m == "Internal"),+ "External PPTX {kind} relationship is unsupported"+ );+ let target = attrs+ .get("Target")+ .context("PPTX relationship has no Target")?;+ targets.insert(id.clone(), pptx_target(source, target)?);+ }+ }+ if matches!(event, Event::Start(_)) {+ depth += 1;+ }+ }+ Event::End(_) => depth -= 1,+ Event::Eof => {+ anyhow::ensure!(root && depth == 0, "Incomplete PPTX relationships");+ break;+ }+ _ => {}+ }+ }+ Ok(targets)+}++fn pptx_slide_ids(xml: &str) -> anyhow::Result<Vec<String>> {+ use quick_xml::name::{Namespace, ResolveResult};+ let mut reader = quick_xml::NsReader::from_str(xml);+ let mut depth = 0;+ let mut root = false;+ let mut in_list = false;+ let mut seen_list = false;+ let mut ids = Vec::new();+ loop {+ let event = reader.read_event()?;+ match &event {+ Event::Start(e) | Event::Empty(e) => {+ let (ns, local) = reader.resolver().resolve_element(e.name());+ let presentation = matches!(+ ns,+ ResolveResult::Bound(Namespace(+ PPT_NS | "http://purl.oclc.org/ooxml/presentationml/main"+ ))+ );+ if depth == 0 {+ anyhow::ensure!(+ !root && presentation && local.as_ref() == "presentation",+ "Invalid PPTX presentation root"+ );+ root = true;+ } else if depth == 1 && presentation && local.as_ref() == "sldIdLst" {+ anyhow::ensure!(!seen_list, "Duplicate PPTX slide list");+ seen_list = true;+ in_list = matches!(event, Event::Start(_));+ } else if depth == 2 && in_list {+ anyhow::ensure!(+ presentation && local.as_ref() == "sldId",+ "Invalid PPTX slide-list entry"+ );+ let mut id = None;+ for a in e.attributes() {+ let a = a?;+ let (ns, local) = reader.resolver().resolve_attribute(a.key);+ if local.as_ref() == "id"+ && matches!(+ ns,+ ResolveResult::Bound(Namespace(+ REL_NS+ | "http://purl.oclc.org/ooxml/officeDocument/relationships"+ ))+ )+ {+ anyhow::ensure!(id.is_none(), "Duplicate PPTX slide relationship");+ id = Some(+ a.normalized_value(quick_xml::XmlVersion::Implicit1_0)?+ .into_owned(),+ );+ }+ }+ ids.push(id.context("PPTX slide has no relationship id")?);+ }+ if matches!(event, Event::Start(_)) {+ depth += 1;+ }+ }+ Event::End(_) => {+ depth -= 1;+ if depth == 1 {+ in_list = false;+ }+ }+ Event::Eof => {+ anyhow::ensure!(root && depth == 0, "Incomplete PPTX presentation");+ break;+ }+ _ => {}+ }+ }+ Ok(ids)+}++fn pptx_order(+ archive: &mut zip::ZipArchive<Cursor<Vec<u8>>>,+) -> anyhow::Result<Option<Vec<String>>> {+ let has_root = archive.file_names().any(|n| n == "_rels/.rels");+ let main = if has_root {+ let xml = pptx_part(archive, "_rels/.rels")?;+ let mut roots = pptx_relationships(&xml, "officeDocument", "")?.into_values();+ let main = roots+ .next()+ .context("PPTX has no presentation relationship")?;+ anyhow::ensure!(roots.next().is_none(), "PPTX has multiple presentations");+ main+ } else if archive.file_names().any(|n| n == "ppt/presentation.xml") {+ "ppt/presentation.xml".to_string()+ } else {+ // Preserve the existing behavior for legacy partial packages. If a+ // manifest exists, errors must never fall back to guessed filename order.+ return Ok(None);+ };+ let ids = pptx_slide_ids(&pptx_part(archive, &main)?)?;+ if ids.is_empty() {+ return Ok(Some(Vec::new()));+ }+ let (dir, file) = main.rsplit_once('/').unwrap_or(("", main.as_str()));+ let rels = if dir.is_empty() {+ format!("_rels/{file}.rels")+ } else {+ format!("{dir}/_rels/{file}.rels")+ };+ let relationships = pptx_relationships(&pptx_part(archive, &rels)?, "slide", &main)?;+ let slides = ids+ .into_iter()+ .map(|id| {+ relationships+ .get(&id)+ .cloned()+ .with_context(|| format!("Missing PPTX slide relationship: {id}"))+ })+ .collect::<anyhow::Result<_>>()?;+ Ok(Some(slides))+}+/// xlsx / xls / ods: calamine 全格式读取,每 sheet 输出制表符表格(限前 2000 行)。pub fn spreadsheet(bytes: &[u8]) -> anyhow::Result<String> {use calamine::{Data, Reader as _};diff --git a/crates/utopia-ingest/tests/pptx_order.rs b/crates/utopia-ingest/tests/pptx_order.rsnew file mode 100644index 00000000..a4b19c1f--- /dev/null+++ b/crates/utopia-ingest/tests/pptx_order.rs@@ -0,0 +1,218 @@+use std::io::{Cursor, Write};++type Parts = Vec<(String, String)>;++fn package(parts: &Parts) -> Vec<u8> {+ let mut zip = zip::ZipWriter::new(Cursor::new(Vec::new()));+ for (name, xml) in parts {+ zip.start_file(name, zip::write::SimpleFileOptions::default())+ .unwrap();+ zip.write_all(xml.as_bytes()).unwrap();+ }+ zip.finish().unwrap().into_inner()+}++fn slide(text: &str) -> String {+ format!(+ r#"<p:sld xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><p:cSld><p:spTree><p:sp><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:r><a:t>{text}</a:t></a:r></a:p></p:txBody></p:sp></p:spTree></p:cSld></p:sld>"#+ )+}++fn deck() -> Parts {+ vec![+ ("[Content_Types].xml".into(),r#"<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Override PartName="/ppt/presentation.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml"/><Override PartName="/ppt/slides/slide2.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.slide+xml"/><Override PartName="/ppt/slides/slide17.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.slide+xml"/></Types>"#.into()),+ ("_rels/.rels".into(),r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="office" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="ppt/presentation.xml"/></Relationships>"#.into()),+ ("ppt/presentation.xml".into(),r#"<p:presentation xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><p:sldIdLst><p:sldId id="257" r:id="rIdB"/><p:sldId id="256" r:id="rIdA"/></p:sldIdLst></p:presentation>"#.into()),+ ("ppt/_rels/presentation.xml.rels".into(),r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rIdA" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slide" Target="slides/slide2.xml"/><Relationship Id="rIdB" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slide" Target="slides/slide17.xml"/><Relationship Id="notes" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/notesSlide" Target="notesSlides/notesSlide1.xml"/></Relationships>"#.into()),+ ("ppt/slides/slide2.xml".into(),slide("FIRST-CREATED")),+ ("ppt/slides/slide17.xml".into(),slide("SECOND-CREATED & 中 <![CDATA[<raw>]]>")),+ ("ppt/slides/slide99.xml".into(),slide("UNLISTED")),+ ("ppt/notesSlides/notesSlide1.xml".into(),slide("NOTES")),+ ("ppt/slideMasters/slideMaster1.xml".into(),slide("MASTER")),+ ]+}++fn part<'a>(parts: &'a mut Parts, name: &str) -> &'a mut String {+ &mut parts.iter_mut().find(|(n, _)| n == name).unwrap().1+}++fn parsed(parts: &Parts) -> String {+ utopia_ingest::parse("slides.pptx", &package(parts))+ .unwrap()+ .text+}++#[test]+fn logical_order_and_page_numbers_do_not_depend_on_zip_or_part_order() {+ let mut parts = deck();+ let expected = parsed(&parts);+ assert!(+ expected.contains("## Slide 1\nSECOND-CREATED & 中 <raw>"),+ "{expected}"+ );+ assert!(expected.contains("## Slide 2\nFIRST-CREATED"), "{expected}");+ assert!(!expected.contains("UNLISTED"));+ assert!(!expected.contains("NOTES"));+ assert!(!expected.contains("MASTER"));+ for _ in 0..parts.len() {+ parts.rotate_left(1);+ assert_eq!(parsed(&parts), expected);+ }+ parts.reverse();+ assert_eq!(parsed(&parts), expected);+ let xml = part(&mut parts, "ppt/presentation.xml");+ *xml = xml+ .replace("rIdB", "temp")+ .replace("rIdA", "rIdB")+ .replace("temp", "rIdA");+ let normal = parsed(&parts);+ assert!(normal.contains("## Slide 1\nFIRST-CREATED"));+ assert!(normal.contains("## Slide 2\nSECOND-CREATED"));+}++#[test]+fn relationships_resolve_internal_paths_and_namespaces() {+ let expected = parsed(&deck());+ let mut parts = deck();+ // The root relationship can locate a differently named main part.+ for (name, xml) in &mut parts {+ *name = name+ .replace("ppt/presentation.xml", "deck/main.xml")+ .replace(+ "ppt/_rels/presentation.xml.rels",+ "deck/_rels/main.xml.rels",+ );+ *xml = xml.replace("ppt/presentation.xml", "deck/main.xml");+ }+ let xml = part(&mut parts, "deck/_rels/main.xml.rels");+ *xml = xml+ .replace("slides/slide2.xml", "../ppt/slides/./slide2.xml")+ .replace("slides/slide17.xml", "/ppt/slides/slide17.xml");+ let xml = part(&mut parts, "deck/main.xml");+ *xml = xml+ .replace("xmlns:p=", "xmlns:q=")+ .replace("<p:", "<q:")+ .replace("</p:", "</q:")+ .replace("xmlns:r=", "xmlns:rel=")+ .replace("r:id", "rel:id");+ assert_eq!(parsed(&parts), expected);+ // Relationship values are XML-unescaped, then percent-decoded as package URIs.+ let mut parts = deck();+ let xml = part(&mut parts, "ppt/_rels/presentation.xml.rels");+ *xml = xml+ .replace("slides/slide17.xml", "slides/B%20&%20C.xml")+ .replace("rIdB", "rId&B");+ let xml = part(&mut parts, "ppt/presentation.xml");+ *xml = xml.replace("rIdB", "rId&B");+ parts+ .iter_mut()+ .find(|(n, _)| n == "ppt/slides/slide17.xml")+ .unwrap()+ .0 = "ppt/slides/B & C.xml".into();+ assert_eq!(parsed(&parts), expected);+ let mut strict = deck();+ for (_, xml) in &mut strict {+ *xml = xml+ .replace(+ "http://schemas.openxmlformats.org/presentationml/2006/main",+ "http://purl.oclc.org/ooxml/presentationml/main",+ )+ .replace(+ "http://schemas.openxmlformats.org/officeDocument/2006/relationships",+ "http://purl.oclc.org/ooxml/officeDocument/relationships",+ );+ }+ assert_eq!(parsed(&strict), expected);+}++#[test]+fn present_but_broken_manifests_fail_instead_of_guessing_or_skipping_pages() {+ for (old, new) in [+ ("slides/slide17.xml", "slides/missing.xml"),+ ("slides/slide17.xml", "../../../outside.xml"),+ ("slides/slide17.xml", "%2e%2e/%2e%2e/outside.xml"),+ ("slides/slide17.xml", "https://example.test/slide.xml"),+ (+ "Target=\"slides/slide17.xml\"",+ "Target=\"https://example.test/slide.xml\" TargetMode=\"External\"",+ ),+ ("Id=\"rIdB\"", "Id=\"rIdA\""),+ ("</Relationships>", "</Broken>"),+ ("</Relationships>", ""),+ ] {+ let mut parts = deck();+ let xml = part(&mut parts, "ppt/_rels/presentation.xml.rels");+ *xml = xml.replace(old, new);+ assert!(+ utopia_ingest::parse("broken.pptx", &package(&parts)).is_err(),+ "{old} -> {new}"+ );+ }+ for (name, old, new) in [+ ("ppt/presentation.xml", "rIdB", "missing"),+ (+ "ppt/_rels/presentation.xml.rels",+ "/relationships/slide\"",+ "/relationships/notesSlide\"",+ ),+ (+ "_rels/.rels",+ "Target=\"ppt/presentation.xml\"",+ "Target=\"https://example.test/deck.xml\" TargetMode=\"External\"",+ ),+ ("_rels/.rels", "</Relationships>", ""),+ ] {+ let mut parts = deck();+ let xml = part(&mut parts, name);+ *xml = xml.replace(old, new);+ assert!(+ utopia_ingest::parse("broken.pptx", &package(&parts)).is_err(),+ "{name}: {old}"+ );+ }+ for name in [+ "ppt/slides/slide17.xml",+ "ppt/_rels/presentation.xml.rels",+ "ppt/presentation.xml",+ ] {+ let mut parts = deck();+ parts.retain(|(n, _)| n != name);+ assert!(+ utopia_ingest::parse("broken.pptx", &package(&parts)).is_err(),+ "missing {name}"+ );+ }+ for xml in [+ "<bad/>",+ "<p:presentation",+ r#"<p:presentation xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main"><p:sldIdLst><p:sldId id="256"/></p:sldIdLst></p:presentation>"#,+ ] {+ let mut parts = deck();+ *part(&mut parts, "ppt/presentation.xml") = xml.into();+ assert!(+ utopia_ingest::parse("broken.pptx", &package(&parts)).is_err(),+ "{xml}"+ );+ }+}++#[test]+fn empty_presentations_and_manifest_free_legacy_packages_keep_their_behavior() {+ let mut parts = deck();+ *part(&mut parts,"ppt/presentation.xml")=r#"<p:presentation xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main"><p:sldIdLst/></p:presentation>"#.into();+ assert!(utopia_ingest::parse("empty.pptx", &package(&parts))+ .unwrap_err()+ .to_string()+ .contains("No text could be extracted"));+ let legacy = vec![+ ("ppt/slides/slide17.xml".into(), slide("Later")),+ ("ppt/slides/slide2.xml".into(), slide("Earlier")),+ ];+ let text = parsed(&legacy);+ assert!(text.contains("## Slide 2\nEarlier"));+ assert!(text.contains("## Slide 17\nLater"));+ assert!(text.find("Earlier") < text.find("Later"));+ let mut no_root = deck();+ no_root.retain(|(n, _)| n != "_rels/.rels");+ assert_eq!(parsed(&no_root), parsed(&deck()));+}