Office documents
Create, read, save and delete an editor document with the Indox SDK. Import and export spend credits, so they run only with RUN_PAID_CALLS = True. The office editor needs a paid plan: on a free account the first cell shows the server’s 403 and the rest print skipped.
Config
Add your settings to the repo .env (local) or Colab Secrets — this cell reads them with get(...):
INDOX_API_KEY (your ak_… key) and INDOX_BASE_URL (https://indox.org; the SDK adds /api/v1/… itself). A missing key stops here with its name.
import json, logging, re, sys, tempfile
from pathlib import Path
REPO = Path.cwd().parents[1]
sys.path[:0] = [str(REPO), str(REPO / "languages" / "python")]
try:
from google.colab import userdata
get = userdata.get
except ImportError:
from tools.env import require_env as get
from indox_client import Indox
logging.basicConfig(format="→ %(message)s", force=True)
logging.getLogger("urllib3.connectionpool").setLevel(logging.DEBUG)
def _mask(record):
record.msg = re.sub(r"/(public|sign)/[^/ ]+", r"/\1/***", record.getMessage())
record.args = ()
return True
logging.getLogger("urllib3.connectionpool").addFilter(_mask)
def show(data, limit=2500):
print(json.dumps(data, indent=2, default=str)[:limit])
client = Indox(api_key=get("INDOX_API_KEY"), base_url=get("INDOX_BASE_URL"))
start_credits = client.billing.credits_balance()["credit_amount"]
SAMPLES = REPO / "colab"
out = Path(tempfile.mkdtemp())
RUN_PAID_CALLS = Falsefrom indox_client import PermissionDeniedError
try:
documents = client.office.list_documents(page_size=5)
show(documents)
except PermissionDeniedError as exc:
documents = None
print("403: the office editor needs a paid plan on this account")
show(exc.response)
assert documents is None or documents["count"] >= len(documents["results"])doc = None
if documents is not None:
doc = client.office.create_document(kind="doc", title="SDK notebook doc")
show(doc)
assert doc["kind"] == "doc" and doc["id"]
else:
print("skipped: no office editor access")if doc:
fetched = client.office.get_document(doc["id"])
show(fetched)
assert fetched["id"] == doc["id"] and fetched["rev"] == doc["rev"]
else:
print("skipped: no document")if doc:
saved = client.office.save_document(
doc["id"], rev=doc["rev"], snapshot=doc["snapshot"], title="SDK notebook doc (saved)"
)
show(saved)
assert saved["rev"] == doc["rev"] + 1 and saved["title"].endswith("(saved)")
else:
print("skipped: no document")import time
FINISHED = {"completed", "done", "ready", "failed"}
def poll(fetch, done=lambda r: r["status"] in FINISHED, every=3, limit=900):
for _ in range(limit // every):
resp = fetch()
if done(resp):
return resp
time.sleep(every)
raise TimeoutError(f"still running after {limit}s")
if RUN_PAID_CALLS and doc:
job = client.office.export(doc["id"], target_format="docx")
show(poll(lambda: client.office.job(job["job_id"])))
docx = client.office.download(job["job_id"], out / "doc.docx")
job = client.office.import_file(docx, kind="doc")
imported = poll(lambda: client.office.job(job["job_id"]))
show(imported)
assert imported["status"] == "completed" and imported["document_id"]
client.office.delete_document(imported["document_id"])
else:
print("skipped: office.export / office.import_file spend credits (RUN_PAID_CALLS = False)")if doc:
show(client.office.delete_document(doc["id"]))
remaining = client.office.list_documents(page_size=100)["results"]
assert doc["id"] not in [d["id"] for d in remaining]
else:
print("skipped: no document")Usage
now = client.billing.credits_balance()["credit_amount"]
print(f"credits used by this notebook: {start_credits - now} (balance {now})")
show(client.billing.usage_by_feature())