C#ATIA

↑タイトル詐欺 主にFusion360API 偶にCATIA V5 VBA(絶賛ネタ切れ中)※記載されている内容は個人の意見であり、所属する団体等を代表する意見では御座いません・・・・よ!

CATIA V5 VBAマクロ開発向け VSCode拡張6

こちらの続きです。
CATIA V5 VBAマクロ開発向け VSCode拡張5 - C#ATIA

先日の日曜日は朝から晩までクソ忙しいものすごく忙しい予定だったのですが、
複数の予定がキャンセルとなり時間が出来たので、日頃使いにくい部分を思い切って
改修に取り組みました。
(前回の約半年前だったので、そこからのAIの進化が凄まじい事を実感しています。)
GitHub - kantoku-code/Cat5Dev: Cat5Dev is a VSCode extension that syncs VBA modules between VSCode and CATIA V5. · GitHub

長い間放置して申し訳なかったのですが、中国語サポートのPRが入っていたので、そちらを
取り込みました。v0.4.0 -> v0.6.7へ一気に上げてますが、一番不便だと感じていたインテリセンスの強化が
一番大きいと感じてます。VSCodeでの開発を目的にしていたにも関わらず、ここが
貧弱過ぎたので、実質開発出来ない状態でした。不便ないぐらいの性能にはなっているはず。
もう一つ不便に感じていたのが、パンくずリストの表示がソートされていなかった部分ですが、
こちらもソートした状態での表示に出来る設定を追加したので、関数が探しやすくなりました。

Lintやフォーマッタはまだ評価しきれていないものの、Push/Pullは問題無いです。
(Pushは開発当初から不安定で、出来れば変更したくない・・・)
Pushも以前に比べて送り込む量を減らしているので処理も早くなってます。

細かな部分では、ホバーするだけでちょっとした情報も表示するので、VBAエディタより
リッチな機能も付いているので、VSCodeでもある程度開発出来る可能性が見えてきました。

最新版の.vsixファイルのダウンロードはこちらから
Release v0.6.8 · kantoku-code/Cat5Dev · GitHub

CATPartパーサー

Githubを見ていたのですが、これ本当かな・・
GitHub - MadManJohnSmith/catpart-parser: Open-source parser for the CATIA V5 .CATPart/.CATProduct binary format - reads files without a CATIA installation · GitHub
始まったばかりの様ですし、試してもいないのですが、本当にこれが可能なのであれば
ファイル内の情報取得がCATIA無しで可能になる事を意味していますよね?
凄いのではないかな?

こちらもすごいですね。
GitHub - wind1022-cmd/catiarecon: Rebuild a history-less STEP solid in CATIA V5 as a part with history, driven by an LLM (experimental) · GitHub
実験とはなっているので継続的に取り組むか分からないのですが、
実現すれば面白そうです。
Fusionには既になりますが。

ScriptLauncher3

こちらの続きです。
ScriptLauncher2 - C#ATIA

前回からほぼ毎日少しづつ変更を加えて、見た目も含めソコソコ変わりましたのでご紹介です。
GitHub - kantoku-code/Fusion360_ScriptLauncher: This is an experimental and simplified script menu. · GitHub

1. どのワークスペースからでも呼び出せるようになりました(QAT 対応)

これまではワークスペースごとのパネルにボタンを置いていましたが、クイックアクセスツールバー(QAT) に登録する形に変更しました。デザインでも CAM でも図面でも、同じ場所から呼び出せます。

あわせて、ワークスペースを切り替えるとパレットが消えてしまう不具合も直しました。

2. 検索ボックスを追加しました

スクリプトが増えてくると、ツリーから目的のものを探すのが大変になります。そこでツリーの上に検索ボックスを付けました。

  • スクリプト名と説明(description)の両方が検索対象
  • 部分一致・大文字小文字は区別なし
  • ワイルドカード(* ?)が使えます
  • ヒットしたスクリプトは太字になり、該当するグループだけが展開されます
  • Esc キーで検索をクリア

検索ボックスの右には「すべて展開」「すべて折りたたみ」「設定」ボタンも並んでいます。

3. 設定パネルを追加しました

「設定」ボタンを押すと、上からスッと設定パネルが降りてきます。設定できるのは次の3つです。

  • カラーテーマ(ライト/ダーク)
  • フォント(ファミコン風/標準)
  • マウスが離れているときに背景を透明にする(オン/オフ)

設定は setting.json に保存されるので、次に開いたときもそのまま使えます。パレットをフローティングで使っている場合は、閉じたときのサイズも覚えておくようにしました。

何故、ファミコン風フォント?
・・・思い付いたからです。思い付いたら止まらない。
フォントを公開してくださっている Itou Hiroki 様、M+ FONTS PROJECT の皆様に感謝いたします。

4. ツリーの使い勝手を改善しました

  • スクリプトにマウスを乗せると、説明(description)がツールチップで表示されます
  • 右クリックメニューに「フォルダオープン」を追加しました。スクリプトの中身を確認したいときに便利です
  • スクリプトの manifest に iconFilename が指定されていれば、そのアイコンをツリーに表示します
  • パレットの文言は Fusion の表示言語に合わせて切り替わります
  • キーボード操作にも対応しました(↑↓で移動、→←で展開/折りたたみ、Home/End で先頭/末尾へ)
  • スクロールするのはツリー部分だけになり、検索ボックスが隠れなくなりました

5. 中身もけっこう変わっています

見た目以外にも、内部をかなり整理しました。

  • jQuery / jsTree への依存をやめて、ツリー表示を自前で実装しました。ライブラリ一式が無くなり、ファイル数もコードの量もだいぶ減っています
  • HTML / CSS / JavaScript を html フォルダにまとめました
  • セキュリティ対策として、アイコンの読み込みをスクリプトフォルダ内・画像ファイル・1MB 以下に制限し、パレットの HTML に Content-Security-Policy を設定、パレットから受け取るデータのチェックも強化しました

6. Windows 用インストーラーを付けました

installer\install_Win.cmd を実行して Y を入力すると、アドインフォルダへコピーされます。手作業でフォルダを探してコピーする必要はなくなりました(実行前に Fusion は終了しておいてください)。

7. その他

Fusionは様々な言語モードがありますが、全ての言語をサポートしました。
ただし、言語によってはファミコン風フォント対応しているのかな・・・



とりあえず、心当たりの改修はしたので、このアドインの改修は一旦終わりです。

BLACKSMITH 3

多分、こちらの続きです。
BLACKSMITH更新 - C#ATIA

機能的には追加していないのですが、メンテナンスしました。

元々多言語対応させていたのですが、作った当初よりFusionがサポートしている
言語が増えたのでその辺りの対応です。

又、アドインとして登録するための.cmdファイルも用意しています。

寸法の文字を二倍にする

絶対役に立たないのですが、アクティブなシートの寸法のテキストを2倍にします。

こんなデータです。

処理後はこんな感じです。

役に立ちません。実験です。

# Fusion 360 API Python script
# Scale the text height of every dimension on the active drawing sheet.
# The Drawing API does not expose per-dimension text height, so the DIMTXT
# override (ACAD/DSTYLE xdata, group 140) is written via AutoLISP entmod.
# 寸法のフォントを2倍
import os
import re
import tempfile
import time
import traceback

import adsk
import adsk.core as core
import adsk.drawing as drawing

# Text height multiplier. Run again with the reciprocal (e.g. 0.5) to revert.
SCALE = 2.0

TITLE = "寸法文字の倍率変更"

# Temporary file used to pass results from AutoLISP (%TEMP%/FUSIONDIMS).
OUT_PATH = os.path.join(os.environ.get("TEMP", tempfile.gettempdir()), "FUSIONDIMS")
LISP_PATH = '(strcat (getenv "TEMP") "/FUSIONDIMS")'
END_MARK = "END"
ERROR_MARK = "ERROR"

# Lines written per dimension, in LISP_MAIN output order.
FIELDS = ("handle", "old", "status", "new")
FIELD_COUNT = len(FIELDS)

# Close a result file left open by an earlier run that stopped with an error.
LISP_CLOSE = (
    "(progn (if _f (vl-catch-all-apply (quote close) (list _f))) (setq _f nil) (princ))"
)

# Helper definitions. The file is opened first and progress is written after
# each stage (OPEN, DEFUN) so a failure point can be located.
#   _cc: apply f to a, returning the result only if it is a string
#   _xv: value following (1070 . c) in DSTYLE xdata
#   _ht: current DIMTXT (override first, then dimension style)
#   _nx: ACAD xdata items with DIMTXT override set to n (other items kept)
LISP_DEFS = f"""
(progn
  (setq _f (open {LISP_PATH} "w"))
  (defun _w (v) (write-line v _f))
  (_w "OPEN")
  (defun _r (v) (if v (rtos v 2 12) ""))
  (defun _cc (f a / r)
    (setq r (vl-catch-all-apply f a))
    (if (= (type r) (quote STR)) r))
  (defun _xv (x c / r)
    (setq x (cdr (member (assoc 1002 x) x)))
    (while (and x (cdr x) (not r))
      (if (equal (car x) (cons 1070 c)) (setq r (cdadr x)))
      (setq x (cddr x)))
    r)
  (defun _ht (d / v)
    (setq v (_xv (cdr (cadr (assoc -3 d))) 140))
    (if (and (null v) (cdr (assoc 3 d)))
      (setq v (cdr (assoc 140 (tblsearch "DIMSTYLE" (cdr (assoc 3 d)))))))
    v)
  (defun _nx (x n / a r)
    (setq a (member (cons 1000 "DSTYLE") x))
    (if (null a)
      (append x (list (cons 1000 "DSTYLE") (cons 1002 _ob)
                      (cons 1070 140) (cons 1040 n) (cons 1002 _cb)))
      (progn
        (while (not (eq x a)) (setq r (cons (car x) r) x (cdr x)))
        (setq r (cons (cadr x) (cons (car x) r)) x (cddr x))
        (while (and x (cdr x) (not (equal (car x) (cons 1002 _cb))))
          (if (not (equal (car x) (cons 1070 140)))
            (setq r (cons (cadr x) (cons (car x) r))))
          (setq x (cddr x)))
        (append (reverse r) (list (cons 1070 140) (cons 1040 n)) x))))
  (_w "DEFUN")
  (setq _ob nil _cb nil)
  (_w "{END_MARK}")
  (close _f)
  (setq _f nil)
  (princ))
"""


def brace_lisp(setup: str, func: str, arg_open: str, arg_close: str) -> str:
    """Set _ob / _cb ("{" / "}") by calling func; writes OK or NG."""
    return f"""
(progn
  (setq _f (open {LISP_PATH} "w"))
  {setup}
  (setq _ob (_cc (quote {func}) (list {arg_open}))
        _cb (_cc (quote {func}) (list {arg_close})))
  (_w (if (and _ob _cb) "OK" "NG"))
  (_w "{END_MARK}")
  (close _f)
  (setq _f nil)
  (princ))
"""


# _bk: take the "{" or "}" xdata string from an existing dimension.
LISP_BK = """
(defun _bk (k / ss i x r)
  (setq ss (ssget "X" (list (cons 0 "*DIMENSION") (list -3 (list "ACAD")))) i 0)
  (while (and ss (null r) (< i (sslength ss)))
    (setq x (cdr (cadr (assoc -3 (entget (ssname ss i) (list "ACAD"))))) i (1+ i))
    (if (assoc 1002 x)
      (setq r (cdr (assoc 1002 (if (= k 0) x (reverse x)))))))
  r)
"""

# Ways to get "{" / "}", tried in order until one works. Each is sent as a
# separate command so an unsupported function cannot break the others.
BRACE_TRIALS = (
    ("図面の寸法 xdata", LISP_BK, "_bk", "0", "1"),
    ("vl-list->string", "", "vl-list->string", "(list 123)", "(list 125)"),
    ("chr", "", "chr", "123", "125"),
)


# Modify dimensions on the current layout (CTAB) and report each result:
# handle, old height, OK/NG/SKIP, height read back after entmod.
# Errors are caught so the file is always closed; they are written as
# ERROR_MARK followed by the message.
LISP_MAIN = f"""
(progn
  (setq _f (open {LISP_PATH} "w"))
  (_w (getvar "CTAB"))
  (setq _er (vl-catch-all-apply (function (lambda () (progn
  (setq _ss (ssget "X" (list (cons 0 "*DIMENSION") (cons 410 (getvar "CTAB")))))
  (setq _i 0)
  (if _ss
    (repeat (sslength _ss)
      (setq _e (ssname _ss _i) _i (1+ _i))
      (setq _d (entget _e (list "ACAD")))
      (setq _h (_ht _d))
      (_w (cdr (assoc 5 _d)))
      (_w (_r _h))
      (_w
        (cond
          ((not (and _h (> _h 0))) "SKIP")
          ((entmod
             (if (assoc -3 _d)
               (subst
                 (list -3 (cons "ACAD" (_nx (cdr (cadr (assoc -3 _d))) (* _h {SCALE!r}))))
                 (assoc -3 _d) _d)
               (append _d (list (list -3 (cons "ACAD" (_nx nil (* _h {SCALE!r}))))))))
           (entupd _e)
           "OK")
          (t "NG")))
      (_w (_r (_ht (entget _e (list "ACAD")))))))))) nil))
  (if (vl-catch-all-error-p _er)
    (progn (_w "{ERROR_MARK}") (_w (vl-catch-all-error-message _er))))
  (_w "{END_MARK}")
  (close _f)
  (setq _f nil)
  (princ))
"""


class StepError(Exception):
    """A step failed; the message is shown to the user as is."""


def run(context):
    ui: core.UserInterface = None
    try:
        app: core.Application = core.Application.get()
        ui = app.userInterface

        drw: drawing.Drawing = drawing.Drawing.cast(app.activeProduct)
        if not drw:
            ui.messageBox(
                "図面ドキュメントをアクティブにしてから実行してください。", TITLE
            )
            return

        sheet: drawing.Sheet = drw.activeSheet
        print(
            f"Sheet: {sheet.name}; dimension count (API): {sheet.drawingDimensions.count}"
        )

        ans = ui.messageBox(
            f"ドキュメント: {app.activeDocument.name}\n"
            f"シート: {sheet.name}\n\n"
            f"このシートの寸法文字の高さを {SCALE:g} 倍にしますか?",
            TITLE,
            core.MessageBoxButtonTypes.YesNoButtonType,
            core.MessageBoxIconTypes.QuestionIconType,
        )
        if ans != core.DialogResults.DialogYes:
            return

        print(f"Close stale file -> {exec_lisp(to_lisp(LISP_CLOSE))!r}")

        # 1. Helper definitions (wait until finished; commands may run asynchronously).
        lines, resp = run_step(LISP_DEFS, "Define helpers")
        if lines is None:
            partial = read_partial(OUT_PATH)
            if partial == "(no file)":
                detail = (
                    "結果ファイルが作られていません。\n"
                    "LISP の命令そのものが Fusion に受け付けられていない可能性があります。"
                )
            else:
                detail = (
                    f"途中経過: {partial}\n"
                    "(OPEN=ファイル作成、DEFUN=関数定義 まで進んだことを示します)"
                )
            raise StepError(
                f"補助関数の定義が完了しませんでした。\n\n{detail}\n\nFusion の応答: {resp[:300]}"
            )
        # 2. Get "{" / "}" for dimensions that have no override xdata yet.
        brace = ""
        for name, setup, func, arg_open, arg_close in BRACE_TRIALS:
            result, _ = run_step(
                brace_lisp(setup, func, arg_open, arg_close), f"Brace via {func}", 3.0
            )
            if result and result[0] == "OK":
                brace = name
                break

        # 3. Scale the dimensions.
        lines, resp = run_step(LISP_MAIN, "Scale dimensions")
        if lines is None:
            raise StepError(
                "寸法の処理が最後まで終わりませんでした。\n\n"
                f"途中経過(レイアウト名、以降は寸法ごとに ハンドル/変更前/結果/変更後):\n"
                f"{read_partial(OUT_PATH)}\n\nFusion の応答: {resp[:300]}"
            )

        if ERROR_MARK in lines:
            k = lines.index(ERROR_MARK)
            message = lines[k + 1] if k + 1 < len(lines) else ""
            raise StepError(
                f"AutoLISP でエラーが発生しました:\n{message}\n\n"
                "エラーまでの出力(レイアウト名、以降は寸法ごとに ハンドル/変更前/結果/変更後):\n"
                f"{' | '.join(lines[:k])[:500]}"
            )

        ctab, recs = parse_result(lines)
        if not recs:
            raise StepError(
                f"レイアウト「{ctab}」(シート「{sheet.name}」)に寸法が見つかりませんでした。"
            )
        ui.messageBox(summarize(ctab, recs, brace), TITLE)
    except StepError as e:
        if ui:
            ui.messageBox(str(e), TITLE)
    except Exception:
        if ui:
            ui.messageBox(
                "エラーが発生しました:\n{}".format(traceback.format_exc()), TITLE
            )


def run_step(src: str, label: str, timeout: float = 5.0):
    """Send one LISP command and wait for its result file. Returns (lines, response)."""
    if not remove_out(OUT_PATH):
        raise StepError(
            f"結果ファイルが使用中のため削除できません:\n{OUT_PATH}\n\n"
            "Fusion を再起動してから実行してください。"
        )
    resp = exec_lisp(to_lisp(src))
    print(f"{label} -> {resp!r}")
    return wait_result(OUT_PATH, timeout), resp


# ---------------------------------------------------------------- Results


def parse_result(lines: list):
    ctab = lines[0]
    body = lines[1:]
    recs = [
        dict(zip(FIELDS, body[i : i + FIELD_COUNT]))
        for i in range(0, len(body) - FIELD_COUNT + 1, FIELD_COUNT)
    ]
    for r in recs:
        print(f"{r['handle']}: {r['old']} -> {r['new']} [{r['status']}]")
    return ctab, recs


def classify(r: dict) -> str:
    """Return changed / unchanged / failed / skipped for one dimension."""
    if r["status"] == "SKIP":
        return "skipped"
    if r["status"] != "OK":
        return "failed"
    old, new = to_float(r["old"]), to_float(r["new"])
    if (
        old is not None
        and new is not None
        and abs(new - old * SCALE) <= 1e-9 * max(1.0, abs(new))
    ):
        return "changed"
    return "unchanged"


def summarize(ctab: str, recs: list, brace: str) -> str:
    groups = {}
    for r in recs:
        groups.setdefault(classify(r), []).append(r)
    sample = recs[0]
    lines = [
        f"レイアウト: {ctab}",
        f"寸法の数: {len(recs)}",
        f"変更できた({SCALE:g} 倍): {len(groups.get('changed', []))}",
        f"書き込みは成功したが値が変わらない: {len(groups.get('unchanged', []))}",
        f"書き込み失敗: {len(groups.get('failed', []))}",
        f"文字高さが取れずスキップ: {len(groups.get('skipped', []))}",
        "",
        f"例: ハンドル {sample['handle']}  {sample['old']} → {sample['new']}",
        f"{{ }} の取得方法: {brace or '取得できず(上書きのない寸法は変更できません)'}",
        "",
        "画面で文字が大きくなったか確認してください。",
        "そのあと、保存 → 開き直し → 図面の更新 をしても残るか確認してください。",
        "寸法ごとの詳細は Text Commands ウィンドウに出力しています。",
    ]
    return "\n".join(lines)


def to_float(s: str):
    try:
        return float(s)
    except (TypeError, ValueError):
        return None


# ---------------------------------------------------------------- AutoLISP execution


def to_lisp(src: str) -> str:
    # Text commands cannot use quotes or chr; build string literals from symbol names.
    return re.sub(
        r'"([^"]*)"',
        lambda m: lisp_str(m.group(1)),
        " ".join(src.split()),
    )


def lisp_str(text: str) -> str:
    if not text:
        return "(substr (itoa 1) 2)"

    parts = []
    for tok in re.findall(r"[A-Z_]+|[a-z]+|[0-9]|.", text):
        if re.fullmatch(r"[A-Z_]+", tok) or tok in "/*-":
            parts.append(f"(vl-symbol-name (quote {tok}))")
        elif tok.islower():
            parts.append(f"(strcase (vl-symbol-name (quote {tok})) t)")
        elif tok.isdigit():
            parts.append(f"(itoa {tok})")
        else:
            raise ValueError(f"Character cannot be passed to AutoLISP: {tok!r}")

    if len(parts) == 1:
        return parts[0]
    return "(strcat " + " ".join(parts) + ")"


def exec_lisp(src: str) -> str:
    app: core.Application = core.Application.get()
    try:
        return app.executeTextCommand(f"FusionDoc.ExecuteAcadCommand {src}")
    except Exception as e:
        return f"NG {e}"


def wait_result(path: str, timeout: float = 5.0) -> list:
    # The command may run asynchronously; wait for the end marker.
    start = time.time()
    while time.time() - start < timeout:
        adsk.doEvents()
        if os.path.exists(path):
            with open(path, "rb") as f:
                lines = decode(f.read()).splitlines()
            if lines and lines[-1] == END_MARK:
                return lines[:-1]
        time.sleep(0.1)
    return None


def remove_out(path: str, timeout: float = 3.0) -> bool:
    """Delete the result file, retrying while AutoLISP may still hold it open."""
    start = time.time()
    while True:
        try:
            if os.path.exists(path):
                os.remove(path)
            return True
        except PermissionError:
            if time.time() - start >= timeout:
                return False
            adsk.doEvents()
            time.sleep(0.1)


def read_partial(path: str, limit: int = 500) -> str:
    """Return whatever AutoLISP wrote before stopping, for diagnosis."""
    if not os.path.exists(path):
        return "(no file)"
    try:
        with open(path, "rb") as f:
            text = decode(f.read())
    except OSError as e:
        return f"(unreadable: {e})"
    return " | ".join(text.splitlines())[:limit] or "(empty)"


def decode(data: bytes) -> str:
    try:
        return data.decode("utf-8")
    except UnicodeDecodeError:
        return data.decode("cp932", errors="replace")

こんな感じのものは幾らでも作れそう。

図面の寸法をCSV出力する2

こちらの続きです。
図面の寸法をCSV出力する - C#ATIA

前回の宿題を修正しました。

# Fusion360API Python script
# アクティブシートの寸法を CSV(UTF-8 BOM / Excel で開ける)に出力する
#   寸法は Drawing API では取れないため、AutoLISP 経由で取得する。

import csv
import math
import os
import re
import tempfile
import time
import traceback
from decimal import Decimal, InvalidOperation, ROUND_HALF_UP

import adsk
import adsk.core as core
import adsk.drawing as drawing

# 結果の受け渡し用ファイル(LISP側は %TEMP%/FUSIONDIMS)
OUT_PATH = os.path.join(os.environ.get("TEMP", tempfile.gettempdir()), "FUSIONDIMS")
LISP_PATH = '(strcat (getenv "TEMP") "/FUSIONDIMS")'
END_MARK = "END"

# 1寸法あたりの出力行(LISP_SRC の出力順と一致させること)
FIELDS = (
    "handle",
    "ent",
    "type",
    "value",
    "override",
    "layout",
    "text",
    "dimtol",
    "dimlim",
    "dimtp",
    "dimtm",
    "dimdec",
    "dimadec",
    "dimzin",
    "dimazin",
    "p10x",
    "p10y",
    "p11x",
    "p11y",
    "p13x",
    "p13y",
    "p14x",
    "p14y",
    "p15x",
    "p15y",
)
FIELD_COUNT = len(FIELDS)

# 寸法を列挙して OUT_PATH に1行1項目で書き出すLISP(先頭行はCTAB)
#   公差は寸法のスタイル上書き(xdata ACAD/DSTYLE)から取り、無ければ寸法スタイルの値を使う
#   71:DIMTOL 72:DIMLIM 47:DIMTP 48:DIMTM
#   271:DIMDEC 179:DIMADEC 78:DIMZIN 79:DIMAZIN
LISP_SRC = f"""
(progn
  (defun _s (v) (if v v ""))
  (defun _r (v) (if v (rtos v 2 12) ""))
  (defun _w (v) (write-line v _f))
  (defun _p (c / p)
    (setq p (cdr (assoc c _d)))
    (_w (_r (car p)))
    (_w (_r (cadr p))))
  (defun _bt (n / e d r)
    (setq r "")
    (if (and n (setq e (tblobjname "BLOCK" n)))
      (while (setq e (entnext e))
        (setq d (entget e))
        (if (member (cdr (assoc 0 d)) (list "MTEXT" "TEXT"))
          (setq r (strcat r (_s (cdr (assoc 1 d))))))))
    r)
  (defun _xv (x c / r)
    (setq x (cdr (member (assoc 1002 x) x)))
    (while (and x (cdr x) (not r))
      (if (and (= (caar x) 1070) (= (cdar x) c)) (setq r (cdadr x)))
      (setq x (cddr x)))
    r)
  (defun _tv (c / v)
    (setq v (_xv _x c))
    (if (null v) (setq v (cdr (assoc c _st))))
    v)
  (setq _f (open {LISP_PATH} "w"))
  (_w (getvar "CTAB"))
  (setq _ss (ssget "X" (list (cons 0 "*DIMENSION"))))
  (setq _i 0)
  (if _ss
    (repeat (sslength _ss)
      (setq _e (ssname _ss _i) _i (1+ _i))
      (setq _d (entget _e (list "ACAD")))
      (setq _x (cdr (car (cdr (assoc -3 _d)))))
      (setq _st (if (cdr (assoc 3 _d)) (tblsearch "DIMSTYLE" (cdr (assoc 3 _d)))))
      (foreach _v
        (list
          (_s (cdr (assoc 5 _d)))
          (_s (cdr (assoc 0 _d)))
          (itoa (cdr (assoc 70 _d)))
          (_r (cdr (assoc 42 _d)))
          (_s (cdr (assoc 1 _d)))
          (_s (cdr (assoc 410 _d)))
          (_bt (cdr (assoc 2 _d)))
          (_r (_tv 71))
          (_r (_tv 72))
          (_r (_tv 47))
          (_r (_tv 48)))
        (_w _v))
      (foreach _c (list 271 179 78 79) (_w (_r (_tv _c))))
      (foreach _c (list 10 11 13 14 15) (_p _c))))
  (_w "{END_MARK}")
  (close _f)
  (princ))
"""

# DXF code 70 の下位3bit -> 寸法種類
KIND_NAMES = {
    0: "長さ",
    1: "平行",
    2: "角度",
    3: "直径",
    4: "半径",
    5: "角度",
    6: "座標",
}

CSV_HEADER = ("No", "ビュー", "寸法種類", "呼び寸法", "上の許容差", "下の許容差")

# どのビューにも入らない寸法のビュー名
OUTSIDE_NAME = "ビュー外"

# API座標 -> LISP座標 の単位換算候補(定義点が最も多くビュー内に入るものを採用)
UNIT_CANDIDATES = (1.0, 10.0, 0.1, 25.4, 1 / 25.4, 2.54, 1 / 2.54)

# ビュー種類(drawing.ViewTypes の値) -> 名前
VIEW_TYPE_NAMES = {
    0: "基準図",
    1: "投影図",
    2: "断面図",
    3: "詳細図",
    4: "補助投影図",
    5: "展開図",
}

# 基準図の向き(drawing.ViewOrientationTypes の値) -> 名前
ORIENT_NAMES = {
    0: "正面",
    1: "背面",
    2: "上面",
    3: "下面",
    4: "右側面",
    5: "左側面",
    6: "等角",
    7: "等角",
    8: "等角",
    9: "等角",
}


def run(context):
    ui: core.UserInterface = None
    try:
        app: core.Application = core.Application.get()
        ui = app.userInterface

        drw: drawing.Drawing = drawing.Drawing.cast(app.activeProduct)
        if not drw:
            ui.messageBox("図面ドキュメントをアクティブにしてください")
            return

        sheet: drawing.Sheet = drw.activeSheet
        print(f"Sheet: {sheet.name} 寸法数(API): {sheet.drawingDimensions.count}")

        # 実行の確認
        ans = ui.messageBox(
            f"ファイル名: {app.activeDocument.name}\n"
            f"シート名: {sheet.name}\n\n"
            "の寸法を CSV 出力します。良いですか?",
            "寸法出力",
            core.MessageBoxButtonTypes.YesNoButtonType,
            core.MessageBoxIconTypes.QuestionIconType,
        )
        if ans != core.DialogResults.DialogYes:
            return

        # 寸法の取得
        if os.path.exists(OUT_PATH):
            os.remove(OUT_PATH)
        command_result = exec_lisp(to_lisp(LISP_SRC))
        print(f"寸法取得 -> {command_result!r}")

        lines = wait_result(OUT_PATH)
        if lines is None:
            ui.messageBox(
                f"結果ファイルが作成されませんでした:\n{OUT_PATH}\n\n"
                f"コマンド応答: {command_result[:500]}"
            )
            return

        recs = parse_dims(lines)
        if not recs:
            ui.messageBox(f"シート「{sheet.name}」に寸法がありません")
            return
        rows = build_rows(get_views(sheet), recs)

        # 保存先の選択
        dlg = ui.createFileDialog()
        dlg.title = "寸法の出力先"
        dlg.filter = "CSV (*.csv)"
        dlg.initialFilename = safe_name(f"{app.activeDocument.name}_{sheet.name}.csv")
        if dlg.showSave() != core.DialogResults.DialogOK:
            return
        path = dlg.filename

        try:
            with open(path, "w", encoding="utf-8-sig", newline="") as f:
                w = csv.writer(f)
                w.writerow(CSV_HEADER)
                w.writerows(rows)
        except PermissionError:
            ui.messageBox(f"書き込めません(Excel で開いていないか確認してください):\n{path}")
            return

        ui.messageBox(f"{len(rows)} 件の寸法を出力しました\n{path}", "寸法出力")
    except Exception:
        if ui:
            ui.messageBox("Failed:\n{}".format(traceback.format_exc()))


# ---------------------------------------------------------------- 変換


def parse_dims(lines: list) -> list:
    ctab = lines[0]
    body = lines[1:]
    recs = [
        dict(zip(FIELDS, body[i : i + FIELD_COUNT]))
        for i in range(0, len(body) - FIELD_COUNT + 1, FIELD_COUNT)
    ]
    for r in recs:
        r["pts"] = {}
        for code in (10, 11, 13, 14, 15):
            x, y = to_float(r[f"p{code}x"]), to_float(r[f"p{code}y"])
            if x is not None and y is not None:
                r["pts"][code] = (x, y)
    # アクティブシートの寸法に絞る(判別できない場合は全件)
    same = [r for r in recs if r["layout"] == ctab]
    return same or recs


# ---------------------------------------------------------------- ビュー


class ViewBox:
    def __init__(self, index: int, view, pts: list):
        self.index = index
        try:
            self.vtype = view.type
        except Exception:
            self.vtype = None
        try:
            self.orientation = view.orientation  # 基準図のみ対応
        except Exception:
            self.orientation = None
        xs = [p[0] for p in pts]
        ys = [p[1] for p in pts]
        self.box = [min(xs), min(ys), max(xs), max(ys)]
        self.name = f"View{index + 1}"

    def scaled(self, f: float):
        self.box = [v * f for v in self.box]

    @property
    def center(self):
        return ((self.box[0] + self.box[2]) / 2, (self.box[1] + self.box[3]) / 2)

    @property
    def size(self):
        return (self.box[2] - self.box[0], self.box[3] - self.box[1])

    def contains(self, p, margin_ratio: float = 0.02) -> bool:
        w, h = self.size
        m = max(w, h) * margin_ratio + 1e-6
        return (
            self.box[0] - m <= p[0] <= self.box[2] + m
            and self.box[1] - m <= p[1] <= self.box[3] + m
        )


def get_views(sheet) -> list:
    """各ビューの viewCurves からシート上の外接矩形を作る"""
    views = []
    for i, view in enumerate(sheet.views):
        pts = []
        try:
            for crv in view.viewCurves:
                # 中心点は大半径の円弧で形状から大きく離れるため、範囲には始点・終点を使う
                ends = []
                for acc in ("startPoint", "endPoint"):
                    dp = getattr(crv, acc, None)
                    if dp:
                        c = dp.coordinate
                        ends.append((c.x, c.y))
                pts += ends
                # 閉じた曲線(円)だけは 中心±半径 を範囲に加える
                cp = getattr(crv, "centerPoint", None)
                if cp and len(ends) == 2 and math.dist(ends[0], ends[1]) < 1e-6:
                    c = cp.coordinate
                    r = math.dist((c.x, c.y), ends[0])
                    pts += [(c.x - r, c.y - r), (c.x + r, c.y + r)]
        except Exception:
            print(f"View{i + 1}: viewCurves を取得できません")
        if pts:
            views.append(ViewBox(i, view, pts))
    return views


def calibrate(views: list, recs: list) -> float:
    pts = [p for r in recs for p in r["pts"].values()]

    def score(f):
        n = 0
        for p in pts:
            for v in views:
                b = ViewBox.__new__(ViewBox)
                b.box = [x * f for x in v.box]
                if b.contains(p):
                    n += 1
                    break
        return n

    return max(UNIT_CANDIDATES, key=score)


def name_views(views: list):
    """「View番号 種類(向き)」の名前を付ける"""
    bases = [v for v in views if v.vtype == drawing.ViewTypes.BaseViewType]
    for v in views:
        direction = ""
        if v.vtype == drawing.ViewTypes.BaseViewType:
            direction = ORIENT_NAMES.get(v.orientation, "")
        elif v.vtype == drawing.ViewTypes.ProjectedViewType and bases:
            # 投影図は最も近い基準図との位置関係で判定
            b = min(bases, key=lambda b: math.dist(b.center, v.center))
            dx, dy = v.center[0] - b.center[0], v.center[1] - b.center[1]
            bw, bh = b.size
            if abs(dx) < bw * 0.1 and abs(dy) > bh / 2:
                direction = "上" if dy > 0 else "下"
            elif abs(dy) < bh * 0.1 and abs(dx) > bw / 2:
                direction = "右" if dx > 0 else "左"
            else:
                direction = "等角"
        label = VIEW_TYPE_NAMES.get(v.vtype, "ビュー")
        v.name = f"View{v.index + 1} {label}" + (f"({direction})" if direction else "")


def def_points(r: dict) -> list:
    """所属ビューの判定に使う定義点(無ければ文字位置)"""
    flags = int(to_float(r["type"]) or 0)
    codes = {
        0: (13, 14),
        1: (13, 14),
        2: (13, 14, 15, 10),
        3: (10, 15),
        4: (10, 15),
        5: (13, 14, 15),
        6: (13,),
    }.get(flags & 7, (13, 14))
    pts = [r["pts"][c] for c in codes if c in r["pts"]]
    if not pts and 11 in r["pts"]:
        pts = [r["pts"][11]]
    return pts


def find_view(views: list, r: dict):
    pts = def_points(r)
    if not pts:
        return None
    # 範囲が重なる場合に備え、含むビューのうち最小のものを選ぶ
    hits = [v for v in views if all(v.contains(p) for p in pts)]
    if not hits:
        hits = [v for v in views if v.contains(pts[0])]
    return min(hits, key=lambda v: v.size[0] * v.size[1]) if hits else None


def build_rows(views: list, recs: list) -> list:
    """ビュー順(ビュー外は最後)に並べた CSV の行"""
    if views:
        factor = calibrate(views, recs)
        for v in views:
            v.scaled(factor)
        name_views(views)
        print(f"単位換算(API→LISP): x{factor:g}")

    groups = {}
    for r in recs:
        groups.setdefault(find_view(views, r), []).append(r)

    order = [v for v in views if v in groups]
    if None in groups:
        order.append(None)
    rows = []
    for v in order:
        name = v.name if v else OUTSIDE_NAME
        for r in groups[v]:
            rows.append(to_row(len(rows) + 1, name, r))
    return rows


# ---------------------------------------------------------------- 寸法の項目


def to_row(no: int, view_name: str, r: dict) -> list:
    upper, lower = tolerance(r)
    return [no, view_name, kind_name(r), nominal_value(r), upper, lower]


def kind_name(r: dict) -> str:
    ent = r["ent"].upper()
    if ent == "ARC_DIMENSION":
        return "弧長"
    if ent == "LARGE_RADIAL_DIMENSION":
        return "半径(折れ線)"
    flags = int(to_float(r["type"]) or 0)
    kind = flags & 7
    if kind == 6:
        return "座標(X)" if flags & 64 else "座標(Y)"
    return KIND_NAMES.get(kind, ent)


def nominal_value(r: dict) -> str:
    """測定値を寸法スタイルの表示桁に丸め、寸法種類の記号を付ける。"""
    try:
        value = Decimal(r["value"])
    except (TypeError, ValueError, ArithmeticError):
        return ""
    if not value.is_finite():
        return ""

    ent = r["ent"].upper()
    kind = int(to_float(r["type"]) or 0) & 7
    angular = kind in (2, 5) and ent not in ("ARC_DIMENSION", "LARGE_RADIAL_DIMENSION")
    places = to_float(r["dimadec" if angular else "dimdec"])
    if angular and places == -1:
        places = to_float(r["dimdec"])
    places = int(places) if places is not None and places.is_integer() and 0 <= places <= 8 else (3 if angular else 6)
    if angular:
        places = min(places, 3)
    zero_code = to_float(r["dimazin" if angular else "dimzin"])
    zero_code = int(zero_code) if zero_code is not None else (0 if angular else 8)

    try:
        if angular:
            value = Decimal(str(math.degrees(float(value))))
        rounded = value.quantize(Decimal(1).scaleb(-places), rounding=ROUND_HALF_UP)
    except (InvalidOperation, OverflowError, ValueError):
        return ""
    if rounded == 0:
        rounded = abs(rounded)
    number = f"{rounded:.{places}f}"
    suppress_trailing = angular or bool(zero_code & 8)
    suppress_leading = zero_code & (1 if angular else 4)
    if suppress_trailing and "." in number:
        number = number.rstrip("0").rstrip(".")
    if suppress_leading and number.startswith(("0.", "-0.")):
        number = number.replace("0.", ".", 1)

    if ent == "ARC_DIMENSION":
        return number
    if ent == "LARGE_RADIAL_DIMENSION" or kind == 4:
        return "R" + number
    if kind == 3:
        return "φ" + number
    if angular:
        return number + "°"
    return number


def tolerance(r: dict):
    """(上の許容差, 下の許容差)。公差なしは ("", "")"""
    value = to_float(r["value"])
    tp, tm = to_float(r["dimtp"]), to_float(r["dimtm"])
    if to_float(r["dimtol"]) == 1 and tp is not None and tm is not None:
        return signed(tp), signed(-tm)
    if to_float(r["dimlim"]) == 1 and tp is not None and tm is not None and value is not None:
        # 限界寸法: 上限・下限
        return fmt(value + tp), fmt(value - tm)

    # スタイルで判別できない場合は表示文字列から拾う
    raw = r["text"] or r["override"]
    m = re.search(r"\\S([^;]*?)[\^/#]([^;]*);", raw)
    if m:
        a, b = to_float(m.group(1).strip()), to_float(m.group(2).strip())
        if a is not None and b is not None:
            return signed(a), signed(b)
    m = re.search(r"(?:%%[pP]|±)\s*([0-9.]+)", raw)
    if m:
        t = to_float(m.group(1))
        if t is not None:
            return signed(t), signed(-t)
    return "", ""


def to_float(s: str):
    try:
        return float(s)
    except (TypeError, ValueError):
        return None


def fmt(v) -> str:
    return "" if v is None else f"{round(v, 6):g}"


def signed(v: float) -> str:
    v = round(v, 6)
    return "0" if v == 0 else f"{v:+g}"


def safe_name(name: str) -> str:
    return re.sub(r'[\\/:*?"<>|]', "_", name)


# ---------------------------------------------------------------- LISP実行


def to_lisp(src: str) -> str:
    # テキストコマンドでは " と chr が使えないため、文字列リテラルをシンボル名から組み立てる
    return re.sub(
        r'"([^"]*)"',
        lambda m: lisp_str(m.group(1)),
        " ".join(src.split()),
    )


def lisp_str(text: str) -> str:
    if not text:
        return "(substr (itoa 1) 2)"

    parts = []
    for tok in re.findall(r"[A-Z_]+|[a-z]+|[0-9]|.", text):
        if re.fullmatch(r"[A-Z_]+", tok) or tok in "/*-":
            parts.append(f"(vl-symbol-name (quote {tok}))")
        elif tok.islower():
            parts.append(f"(strcase (vl-symbol-name (quote {tok})) t)")
        elif tok.isdigit():
            parts.append(f"(itoa {tok})")
        else:
            raise ValueError(f"LISPに渡せない文字です: {tok!r}")

    if len(parts) == 1:
        return parts[0]
    return "(strcat " + " ".join(parts) + ")"


def exec_lisp(src: str) -> str:
    app: core.Application = core.Application.get()
    try:
        return app.executeTextCommand(f"FusionDoc.ExecuteAcadCommand {src}")
    except Exception as e:
        return f"NG {e}"


def wait_result(path: str, timeout: float = 5.0) -> list:
    # 非同期で実行される場合に備え、終了マークが書かれるまで待つ
    start = time.time()
    while time.time() - start < timeout:
        adsk.doEvents()
        if os.path.exists(path):
            with open(path, "rb") as f:
                lines = decode(f.read()).splitlines()
            if lines and lines[-1] == END_MARK:
                return lines[:-1]
        time.sleep(0.1)
    return None


def decode(data: bytes) -> str:
    try:
        return data.decode("utf-8")
    except UnicodeDecodeError:
        return data.decode("cp932", errors="replace")

図面の寸法をCSV出力する

タイトルはAutodesk Fusionのお話です。

Updateで図面寸法にもアクセス出来るのですが、肝心の寸法値なんかも取得が出来ません。
・・・その内出来るようになるだろうと期待したい。

そこで、色々とClaudeで相談しつつ試しているうちに発見しました。
AutoCADコマンドを実行するテキストコマンドが存在している事は以前から知っていたのですが、
AutoCADLispが実行出来る事が分かりました。全てでは無いはずです。

これを利用する事で寸法値を含む情報の取得をして、CSVファイルに出力するサンプルを
作成しました。またまた、正気ではないボリュームです。

# Fusion360API Python script
# アクティブシートの寸法を CSV(UTF-8 BOM / Excel で開ける)に出力する
#   寸法は Drawing API では取れないため、AutoLISP 経由で取得する。

import csv
import math
import os
import re
import tempfile
import time
import traceback

import adsk
import adsk.core as core
import adsk.drawing as drawing

# 結果の受け渡し用ファイル(LISP側は %TEMP%/FUSIONDIMS)
OUT_PATH = os.path.join(os.environ.get("TEMP", tempfile.gettempdir()), "FUSIONDIMS")
LISP_PATH = '(strcat (getenv "TEMP") "/FUSIONDIMS")'
END_MARK = "END"

# 1寸法あたりの出力行(LISP_SRC の出力順と一致させること)
FIELDS = (
    "handle",
    "ent",
    "type",
    "value",
    "override",
    "layout",
    "text",
    "dimtol",
    "dimlim",
    "dimtp",
    "dimtm",
    "p10x",
    "p10y",
    "p11x",
    "p11y",
    "p13x",
    "p13y",
    "p14x",
    "p14y",
    "p15x",
    "p15y",
)
FIELD_COUNT = len(FIELDS)

# 寸法を列挙して OUT_PATH に1行1項目で書き出すLISP(先頭行はCTAB)
#   公差は寸法のスタイル上書き(xdata ACAD/DSTYLE)から取り、無ければ寸法スタイルの値を使う
#   71:DIMTOL 72:DIMLIM 47:DIMTP 48:DIMTM
LISP_SRC = f"""
(progn
  (defun _s (v) (if v v ""))
  (defun _r (v) (if v (rtos v 2 6) ""))
  (defun _n (v) (cond ((null v) "") ((eq (type v) (quote INT)) (itoa v)) (t (rtos v 2 6))))
  (defun _w (v) (write-line v _f))
  (defun _p (c / p)
    (setq p (cdr (assoc c _d)))
    (_w (_r (car p)))
    (_w (_r (cadr p))))
  (defun _bt (n / e d r)
    (setq r "")
    (if (and n (setq e (tblobjname "BLOCK" n)))
      (while (setq e (entnext e))
        (setq d (entget e))
        (if (member (cdr (assoc 0 d)) (list "MTEXT" "TEXT"))
          (setq r (strcat r (_s (cdr (assoc 1 d))))))))
    r)
  (defun _xv (x c / r)
    (setq x (cdr (member (assoc 1002 x) x)))
    (while (and x (cdr x) (not r))
      (if (and (= (caar x) 1070) (= (cdar x) c)) (setq r (cdadr x)))
      (setq x (cddr x)))
    r)
  (defun _tv (c / v)
    (setq v (_xv _x c))
    (if (null v) (setq v (cdr (assoc c _st))))
    v)
  (setq _f (open {LISP_PATH} "w"))
  (_w (getvar "CTAB"))
  (setq _ss (ssget "X" (list (cons 0 "*DIMENSION"))))
  (setq _i 0)
  (if _ss
    (repeat (sslength _ss)
      (setq _e (ssname _ss _i) _i (1+ _i))
      (setq _d (entget _e (list "ACAD")))
      (setq _x (cdr (car (cdr (assoc -3 _d)))))
      (setq _st (if (cdr (assoc 3 _d)) (tblsearch "DIMSTYLE" (cdr (assoc 3 _d)))))
      (foreach _v
        (list
          (_s (cdr (assoc 5 _d)))
          (_s (cdr (assoc 0 _d)))
          (itoa (cdr (assoc 70 _d)))
          (_r (cdr (assoc 42 _d)))
          (_s (cdr (assoc 1 _d)))
          (_s (cdr (assoc 410 _d)))
          (_bt (cdr (assoc 2 _d)))
          (_n (_tv 71))
          (_n (_tv 72))
          (_n (_tv 47))
          (_n (_tv 48)))
        (_w _v))
      (foreach _c (list 10 11 13 14 15) (_p _c))))
  (_w "{END_MARK}")
  (close _f)
  (princ))
"""

# DXF code 70 の下位3bit -> 寸法種類
KIND_NAMES = {
    0: "長さ",
    1: "平行",
    2: "角度",
    3: "直径",
    4: "半径",
    5: "角度",
    6: "座標",
}

CSV_HEADER = ("No", "ビュー","寸法種類", "表示文字列", "上の許容差", "下の許容差")

# どのビューにも入らない寸法のビュー名
OUTSIDE_NAME = "ビュー外"

# API座標 -> LISP座標 の単位換算候補(定義点が最も多くビュー内に入るものを採用)
UNIT_CANDIDATES = (1.0, 10.0, 0.1, 25.4, 1 / 25.4, 2.54, 1 / 2.54)

# ビュー種類(drawing.ViewTypes の値) -> 名前
VIEW_TYPE_NAMES = {
    0: "基準図",
    1: "投影図",
    2: "断面図",
    3: "詳細図",
    4: "補助投影図",
    5: "展開図",
}

# 基準図の向き(drawing.ViewOrientationTypes の値) -> 名前
ORIENT_NAMES = {
    0: "正面",
    1: "背面",
    2: "上面",
    3: "下面",
    4: "右側面",
    5: "左側面",
    6: "等角",
    7: "等角",
    8: "等角",
    9: "等角",
}


def run(context):
    ui: core.UserInterface = None
    try:
        app: core.Application = core.Application.get()
        ui = app.userInterface

        drw: drawing.Drawing = drawing.Drawing.cast(app.activeProduct)
        if not drw:
            ui.messageBox("図面ドキュメントをアクティブにしてください")
            return

        sheet: drawing.Sheet = drw.activeSheet
        print(f"Sheet: {sheet.name} 寸法数(API): {sheet.drawingDimensions.count}")

        # 実行の確認
        ans = ui.messageBox(
            f"ファイル名: {app.activeDocument.name}\n"
            f"シート名: {sheet.name}\n\n"
            "の寸法を CSV 出力します。良いですか?",
            "寸法出力",
            core.MessageBoxButtonTypes.YesNoButtonType,
            core.MessageBoxIconTypes.QuestionIconType,
        )
        if ans != core.DialogResults.DialogYes:
            return

        # 寸法の取得
        if os.path.exists(OUT_PATH):
            os.remove(OUT_PATH)
        print(f"寸法取得 -> {exec_lisp(to_lisp(LISP_SRC))!r}")

        lines = wait_result(OUT_PATH)
        if lines is None:
            ui.messageBox(f"結果ファイルが作成されませんでした:\n{OUT_PATH}")
            return

        recs = parse_dims(lines)
        if not recs:
            ui.messageBox(f"シート「{sheet.name}」に寸法がありません")
            return
        rows = build_rows(get_views(sheet), recs)

        # 保存先の選択
        dlg = ui.createFileDialog()
        dlg.title = "寸法の出力先"
        dlg.filter = "CSV (*.csv)"
        dlg.initialFilename = safe_name(f"{app.activeDocument.name}_{sheet.name}.csv")
        if dlg.showSave() != core.DialogResults.DialogOK:
            return
        path = dlg.filename

        try:
            with open(path, "w", encoding="utf-8-sig", newline="") as f:
                w = csv.writer(f)
                w.writerow(CSV_HEADER)
                w.writerows(rows)
        except PermissionError:
            ui.messageBox(f"書き込めません(Excel で開いていないか確認してください):\n{path}")
            return

        ui.messageBox(f"{len(rows)} 件の寸法を出力しました\n{path}", "寸法出力")
    except Exception:
        if ui:
            ui.messageBox("Failed:\n{}".format(traceback.format_exc()))


# ---------------------------------------------------------------- 変換


def parse_dims(lines: list) -> list:
    ctab = lines[0]
    body = lines[1:]
    recs = [
        dict(zip(FIELDS, body[i : i + FIELD_COUNT]))
        for i in range(0, len(body) - FIELD_COUNT + 1, FIELD_COUNT)
    ]
    for r in recs:
        r["pts"] = {}
        for code in (10, 11, 13, 14, 15):
            x, y = to_float(r[f"p{code}x"]), to_float(r[f"p{code}y"])
            if x is not None and y is not None:
                r["pts"][code] = (x, y)
    # アクティブシートの寸法に絞る(判別できない場合は全件)
    same = [r for r in recs if r["layout"] == ctab]
    return same or recs


# ---------------------------------------------------------------- ビュー


class ViewBox:
    def __init__(self, index: int, view, pts: list):
        self.index = index
        try:
            self.vtype = view.type
        except Exception:
            self.vtype = None
        try:
            self.orientation = view.orientation  # 基準図のみ対応
        except Exception:
            self.orientation = None
        xs = [p[0] for p in pts]
        ys = [p[1] for p in pts]
        self.box = [min(xs), min(ys), max(xs), max(ys)]
        self.name = f"View{index + 1}"

    def scaled(self, f: float):
        self.box = [v * f for v in self.box]

    @property
    def center(self):
        return ((self.box[0] + self.box[2]) / 2, (self.box[1] + self.box[3]) / 2)

    @property
    def size(self):
        return (self.box[2] - self.box[0], self.box[3] - self.box[1])

    def contains(self, p, margin_ratio: float = 0.02) -> bool:
        w, h = self.size
        m = max(w, h) * margin_ratio + 1e-6
        return (
            self.box[0] - m <= p[0] <= self.box[2] + m
            and self.box[1] - m <= p[1] <= self.box[3] + m
        )


def get_views(sheet) -> list:
    """各ビューの viewCurves からシート上の外接矩形を作る"""
    views = []
    for i, view in enumerate(sheet.views):
        pts = []
        try:
            for crv in view.viewCurves:
                # 中心点は大半径の円弧で形状から大きく離れるため、範囲には始点・終点を使う
                ends = []
                for acc in ("startPoint", "endPoint"):
                    dp = getattr(crv, acc, None)
                    if dp:
                        c = dp.coordinate
                        ends.append((c.x, c.y))
                pts += ends
                # 閉じた曲線(円)だけは 中心±半径 を範囲に加える
                cp = getattr(crv, "centerPoint", None)
                if cp and len(ends) == 2 and math.dist(ends[0], ends[1]) < 1e-6:
                    c = cp.coordinate
                    r = math.dist((c.x, c.y), ends[0])
                    pts += [(c.x - r, c.y - r), (c.x + r, c.y + r)]
        except Exception:
            print(f"View{i + 1}: viewCurves を取得できません")
        if pts:
            views.append(ViewBox(i, view, pts))
    return views


def calibrate(views: list, recs: list) -> float:
    pts = [p for r in recs for p in r["pts"].values()]

    def score(f):
        n = 0
        for p in pts:
            for v in views:
                b = ViewBox.__new__(ViewBox)
                b.box = [x * f for x in v.box]
                if b.contains(p):
                    n += 1
                    break
        return n

    return max(UNIT_CANDIDATES, key=score)


def name_views(views: list):
    """「View番号 種類(向き)」の名前を付ける"""
    bases = [v for v in views if v.vtype == drawing.ViewTypes.BaseViewType]
    for v in views:
        direction = ""
        if v.vtype == drawing.ViewTypes.BaseViewType:
            direction = ORIENT_NAMES.get(v.orientation, "")
        elif v.vtype == drawing.ViewTypes.ProjectedViewType and bases:
            # 投影図は最も近い基準図との位置関係で判定
            b = min(bases, key=lambda b: math.dist(b.center, v.center))
            dx, dy = v.center[0] - b.center[0], v.center[1] - b.center[1]
            bw, bh = b.size
            if abs(dx) < bw * 0.1 and abs(dy) > bh / 2:
                direction = "上" if dy > 0 else "下"
            elif abs(dy) < bh * 0.1 and abs(dx) > bw / 2:
                direction = "右" if dx > 0 else "左"
            else:
                direction = "等角"
        label = VIEW_TYPE_NAMES.get(v.vtype, "ビュー")
        v.name = f"View{v.index + 1} {label}" + (f"({direction})" if direction else "")


def def_points(r: dict) -> list:
    """所属ビューの判定に使う定義点(無ければ文字位置)"""
    flags = int(to_float(r["type"]) or 0)
    codes = {
        0: (13, 14),
        1: (13, 14),
        2: (13, 14, 15, 10),
        3: (10, 15),
        4: (10, 15),
        5: (13, 14, 15),
        6: (13,),
    }.get(flags & 7, (13, 14))
    pts = [r["pts"][c] for c in codes if c in r["pts"]]
    if not pts and 11 in r["pts"]:
        pts = [r["pts"][11]]
    return pts


def find_view(views: list, r: dict):
    pts = def_points(r)
    if not pts:
        return None
    # 範囲が重なる場合に備え、含むビューのうち最小のものを選ぶ
    hits = [v for v in views if all(v.contains(p) for p in pts)]
    if not hits:
        hits = [v for v in views if v.contains(pts[0])]
    return min(hits, key=lambda v: v.size[0] * v.size[1]) if hits else None


def build_rows(views: list, recs: list) -> list:
    """ビュー順(ビュー外は最後)に並べた CSV の行"""
    if views:
        factor = calibrate(views, recs)
        for v in views:
            v.scaled(factor)
        name_views(views)
        print(f"単位換算(API→LISP): x{factor:g}")

    groups = {}
    for r in recs:
        groups.setdefault(find_view(views, r), []).append(r)

    order = [v for v in views if v in groups]
    if None in groups:
        order.append(None)
    rows = []
    for v in order:
        name = v.name if v else OUTSIDE_NAME
        for r in groups[v]:
            rows.append(to_row(len(rows) + 1, name, r))
    return rows


# ---------------------------------------------------------------- 寸法の項目


def to_row(no: int, view_name: str, r: dict) -> list:
    upper, lower = tolerance(r)
    return [no, view_name, kind_name(r), display_text(r), upper, lower]


def kind_name(r: dict) -> str:
    ent = r["ent"].upper()
    if ent == "ARC_DIMENSION":
        return "弧長"
    if ent == "LARGE_RADIAL_DIMENSION":
        return "半径(折れ線)"
    flags = int(to_float(r["type"]) or 0)
    kind = flags & 7
    if kind == 6:
        return "座標(X)" if flags & 64 else "座標(Y)"
    return KIND_NAMES.get(kind, ent)


def display_text(r: dict) -> str:
    """図面に表示されている文字列(匿名ブロック内の文字 -> 上書き文字 -> 測定値 の順)"""
    text = clean_mtext(r["text"])
    if text:
        return text
    value = fmt(to_float(r["value"]))
    override = clean_mtext(r["override"])
    if override:
        return override.replace("<>", value)
    return value


def clean_mtext(s: str) -> str:
    """MTEXT の書式コードを除去して表示文字に近づける"""
    if not s:
        return ""
    # エスケープ文字を退避
    s = s.replace("\\\\", "\x00").replace("\\{", "\x01").replace("\\}", "\x02")
    s = re.sub(r"%%[cC]", "Ø", s)
    s = re.sub(r"%%[dD]", "°", s)
    s = re.sub(r"%%[pP]", "±", s)
    s = s.replace("%%%", "%")
    s = re.sub(r"\\[uU]\+([0-9A-Fa-f]{4})", lambda m: chr(int(m.group(1), 16)), s)
    # 積み重ね(公差など) \S上^下; -> " 上/下"
    s = re.sub(r"\\S([^;]*?)[\^/#]([^;]*);", lambda m: f" {m.group(1).strip()}/{m.group(2).strip()}", s)
    s = re.sub(r"\\[PX~]", " ", s)
    s = re.sub(r"\\[ACcFfHhQqTWwp][^;]*;", "", s)
    s = re.sub(r"\\[LlOoKkNn]", "", s)
    s = s.replace("{", "").replace("}", "")
    s = s.replace("\x00", "\\").replace("\x01", "{").replace("\x02", "}")
    return " ".join(s.split())


def tolerance(r: dict):
    """(上の許容差, 下の許容差)。公差なしは ("", "")"""
    value = to_float(r["value"])
    tp, tm = to_float(r["dimtp"]), to_float(r["dimtm"])
    if to_float(r["dimtol"]) == 1 and tp is not None and tm is not None:
        return signed(tp), signed(-tm)
    if to_float(r["dimlim"]) == 1 and tp is not None and tm is not None and value is not None:
        # 限界寸法: 上限・下限
        return fmt(value + tp), fmt(value - tm)

    # スタイルで判別できない場合は表示文字列から拾う
    raw = r["text"] or r["override"]
    m = re.search(r"\\S([^;]*?)[\^/#]([^;]*);", raw)
    if m:
        a, b = to_float(m.group(1).strip()), to_float(m.group(2).strip())
        if a is not None and b is not None:
            return signed(a), signed(b)
    m = re.search(r"(?:%%[pP]|±)\s*([0-9.]+)", raw)
    if m:
        t = to_float(m.group(1))
        if t is not None:
            return signed(t), signed(-t)
    return "", ""


def to_float(s: str):
    try:
        return float(s)
    except (TypeError, ValueError):
        return None


def fmt(v) -> str:
    return "" if v is None else f"{round(v, 6):g}"


def signed(v: float) -> str:
    v = round(v, 6)
    return "0" if v == 0 else f"{v:+g}"


def safe_name(name: str) -> str:
    return re.sub(r'[\\/:*?"<>|]', "_", name)


# ---------------------------------------------------------------- LISP実行


def to_lisp(src: str) -> str:
    # テキストコマンドでは " と chr が使えないため、文字列リテラルをシンボル名から組み立てる
    return re.sub(
        r'"([^"]*)"',
        lambda m: lisp_str(m.group(1)),
        " ".join(src.split()),
    )


def lisp_str(text: str) -> str:
    if not text:
        return "(substr (itoa 1) 2)"

    parts = []
    for tok in re.findall(r"[A-Z_]+|[a-z]+|[0-9]|.", text):
        if re.fullmatch(r"[A-Z_]+", tok) or tok in "/*-":
            parts.append(f"(vl-symbol-name (quote {tok}))")
        elif tok.islower():
            parts.append(f"(strcase (vl-symbol-name (quote {tok})) t)")
        elif tok.isdigit():
            parts.append(f"(itoa {tok})")
        else:
            raise ValueError(f"LISPに渡せない文字です: {tok!r}")

    if len(parts) == 1:
        return parts[0]
    return "(strcat " + " ".join(parts) + ")"


def exec_lisp(src: str) -> str:
    app: core.Application = core.Application.get()
    try:
        return app.executeTextCommand(f"FusionDoc.ExecuteAcadCommand {src}")
    except Exception as e:
        return f"NG {e}"


def wait_result(path: str, timeout: float = 5.0) -> list:
    # 非同期で実行される場合に備え、終了マークが書かれるまで待つ
    start = time.time()
    while time.time() - start < timeout:
        adsk.doEvents()
        if os.path.exists(path):
            with open(path, "rb") as f:
                lines = decode(f.read()).splitlines()
            if lines and lines[-1] == END_MARK:
                return lines[:-1]
        time.sleep(0.1)
    return None


def decode(data: bytes) -> str:
    try:
        return data.decode("utf-8")
    except UnicodeDecodeError:
        return data.decode("cp932", errors="replace")

この様な図面を用意しました。
※他のテストを行っていたデータの為、不要な寸法があります。

出力したCSVファイルをExcelで開くとこんな感じです。

・公差付きの呼び寸法に辺の文字が入っている。(公差の為の文字だと思います)<-恐らく直せるはず
・穴サイズ部分の出力が無い(あの部分は寸法ではなく、引き出し線付きのテキスト)

寸法をExcelで管理したい会社あるんじゃないかな?検査とかで。
現状、APIだけでは取得出来ないので貴重じゃないかな?