Skip to content

Формат-независимый IR

DocumentIR — структурный мост Office Oxide между форматами. Откройте .docx, .xlsx или legacy-.ppt — и получите одну и ту же форму: список секций, в каждой из которых последовательность типизированных элементов (заголовки, абзацы, таблицы, списки, изображения).

IR лежит в основе to_html, save_as и конвертации legacy → OOXML. Это и правильная точка входа для downstream-пайплайнов — поисковых индексов, RAG-чанкеров, собственных рендереров, — потому что вы работаете с одной схемой вместо шести форматных.

Читаем 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 — это 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();
}

Схема

Форма намеренно компактная и стабильная.

{
  "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>" }
      ]
    }
  ]
}

Маппинг по форматам:

Формат Граница секции Примечания
DOCX Одна секция на <w:sectPr> (или весь body, если нет) Заголовки — по w:pStyle
XLSX Одна секция на лист title = имя листа; по одному Table на используемый диапазон
PPTX Одна секция на слайд title = плейсхолдер заголовка слайда; заметки прицепляются последним абзацем
DOC / XLS / PPT Та же форма, что у OOXML-аналогов Парсится через legacy-CFB-пайплайн

Зачем использовать IR

  • Сделай раз — рендери по-разному. Конвертируйте DOCX, XLSX и PPTX в единую форму и гоняйте один пайплайн поиска/чанкинга.
  • LLM-контекст, переживающий смену формата. Схема не дрейфует, когда источники переходят с .doc на .docx.
  • Round-trip с save_as. Отредактируйте IR — запишите новый документ в любом поддерживаемом формате.

Rust

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

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

Сериализация

Rust-DocumentIR имеет Serialize / Deserialize (через serde). Python-to_ir() возвращает обычный dict (уже JSON-сериализуемый). Node-, Go-, C#- и C-привязки выставляют JSON-строки через to_ir_json() / ToIRJSON() / ToIrJson().

Смотрите также