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 recibes la misma forma: una lista de secciones, cada una con una secuencia de elementos tipados (títulos, párrafos, tablas, listas, imágenes).

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

Leer la 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())
{
    // ...
}

Esquema

La forma es deliberadamente pequeña y estable.

{
  "sections": [
    {
      "title": "Título de sección opcional",     // 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) Títulos clavetados por w:pStyle
XLSX Una sección por hoja title = nombre de la hoja; un Table por rango usado
PPTX Una sección por diapositiva title = placeholder del título; notas anexadas como último párrafo
DOC / XLS / PPT Misma forma que sus equivalentes OOXML Parseados por el pipeline legado de CFB

Por qué usar la IR

  • Construye una vez, renderiza muchas. Convierte DOCX, XLSX y PPTX a la misma forma y corre un único pipeline de búsqueda/chunking.
  • Contexto LLM que sobrevive cambios de formato. El schema no se desplaza cuando los documentos migran de .doc a .docx.
  • Round-trip con save_as. Edita la IR y escribe un nuevo documento en cualquier formato soportado.
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 con to_ir_json() / ToIRJSON() / ToIrJson().

Véase también