Skip to content

IR independiente del formato

DocumentIR es el puente estructural de Office Oxide entre formatos. Abre un .docx, un .xlsx o un .ppt heredado — siempre recibirás la misma forma: una lista de secciones, cada una con una secuencia de elementos tipados (títulos, párrafos, tablas, listas, imágenes).

El IR sostiene to_html, save_as y la conversión heredado→OOXML. También es la superficie adecuada para pipelines downstream — índices de búsqueda, chunkers de RAG, renderizadores propios —, porque procesas un único schema en lugar de seis específicos por formato.

Leer el IR

Rust

use office_oxide::Document;

let doc = Document::open("report.docx")?;
let ir = doc.to_ir();

for section in &ir.sections {
    println!("{:?}", section.title);
    for el in &section.elements {
        // el es un enum Element — Heading, Paragraph, Table, List, Image, ...
    }
}

Python

from office_oxide import Document

with Document.open("report.docx") as doc:
    ir = doc.to_ir()

for section in ir["sections"]:
    print(section.get("title"))
    for el in section["elements"]:
        kind = el["kind"]   # "Heading" | "Paragraph" | "Table" | "List" | "Image"

JavaScript

using doc = Document.open('report.docx');
const ir = doc.toIr();

for (const section of ir.sections) {
  for (const el of section.elements) {
    // el.kind: "Heading" | "Paragraph" | "Table" | "List" | "Image"
  }
}

Go

import "encoding/json"

irJSON, _ := doc.ToIRJSON()

var ir struct {
    Sections []struct {
        Title    *string           `json:"title"`
        Elements []json.RawMessage `json:"elements"`
    } `json:"sections"`
}
_ = json.Unmarshal([]byte(irJSON), &ir)

C#

using System.Text.Json;

using var doc = Document.Open("report.docx");
using var ir = JsonDocument.Parse(doc.ToIrJson());

foreach (var section in ir.RootElement.GetProperty("sections").EnumerateArray())
{
    // ...
}

C

int err = 0;
OfficeDocumentHandle *doc = office_document_open("report.docx", &err);
char *ir_json = office_document_to_ir_json(doc, &err);   /* DocumentIR as JSON */
if (ir_json) {
    /* parse with your JSON lib — sections[].elements[].kind: "Heading" | ... */
    office_oxide_free_string(ir_json);
}
office_document_free(doc);

WASM

import { WasmDocument } from 'office-oxide-wasm';

const data = new Uint8Array(await (await fetch('/report.docx')).arrayBuffer());
const doc = new WasmDocument(data, 'docx');
try {
  const ir = doc.toIr();                 // JS object, schema == Rust DocumentIR
  for (const section of ir.sections) {
    for (const el of section.elements) {
      // el.kind: "Heading" | "Paragraph" | "Table" | "List" | "Image"
    }
  }
} finally {
  doc.free();
}

Esquema

La forma es deliberadamente pequeña y estable.

{
  "sections": [
    {
      "title": "Optional section title",     // string | null
      "elements": [
        { "kind": "Heading", "level": 1, "text": "..." },
        { "kind": "Paragraph", "runs": [
            { "text": "Hello ", "bold": false, "italic": false },
            { "text": "world", "bold": true,  "italic": false }
        ] },
        { "kind": "List", "ordered": true, "items": ["one", "two"] },
        { "kind": "Table", "rows": [
            ["A1", "B1"],
            ["A2", "B2"]
        ] },
        { "kind": "Image", "filename": "image1.png", "data": "<base64>" }
      ]
    }
  ]
}

Mapeo por formato:

Formato Frontera de sección Notas
DOCX Una sección por <w:sectPr> (o todo el body si no hay ninguno) Títulos identificados por w:pStyle
XLSX Una sección por hoja de cálculo title = nombre de la hoja; un Table por rango utilizado
PPTX Una sección por diapositiva title = marcador de posición del título; notas adjuntas como último párrafo
DOC / XLS / PPT Misma forma que sus equivalentes OOXML Procesados por el pipeline legado de CFB

Por qué usar el IR

  • Construye una vez, renderiza muchas. Convierte DOCX, XLSX y PPTX a la misma forma y ejecuta un único pipeline de búsqueda/chunking.
  • Contexto para LLM que sobrevive a cambios de formato. El schema no se desplaza cuando los documentos migran de .doc a .docx.
  • Round-trip con save_as. Edita el IR y escribe un nuevo documento en cualquier formato soportado.

Rust

use office_oxide::create::create_from_ir;
use office_oxide::DocumentFormat;

create_from_ir(&ir, DocumentFormat::Docx, "out.docx")?;

Serialización

El DocumentIR en Rust deriva Serialize / Deserialize (vía serde). El to_ir() en Python devuelve un dict plano (ya serializable a JSON). Los bindings Node, Go, C# y C exponen cadenas JSON mediante to_ir_json() / ToIRJSON() / ToIrJson().

Véase también