CAD DWG/DXF Drawing Analysis Tool
Purpose
Provide professional-grade DWG/DXF drawing file reading and analysis capabilities. This skill enables structured data extraction from CAD drawings, spatial analysis between entities, visual capture of drawing regions, and standards compliance auditing.
⚠️ Security Notice
Before using this skill, please review the following:
This skill does NOT automatically install any packages or run any setup scripts. If dependencies are missing, it will output a clear error message with manual installation instructions. To set up the environment, the user must explicitly run the setup command:
CODEBLOCK0
The full setup process (when explicitly confirmed) will:
- - Install Python packages (
ezdxf, matplotlib) - Install system packages (
xvfb, libGL) via INLINECODE4 - Download and install ODA File Converter from INLINECODE5
- Download and install QCAD dwg2bmp from INLINECODE6
All downloads are from official sources, but the skill requires network access and elevated permissions.
Prerequisites
- - Python 3.8+ (system installed)
- Python packages:
ezdxf and matplotlib must be installed before use - root/sudo permissions (only if you choose to run automatic setup)
- x86_64 Linux system
Setup Options
Option A: Manual Setup (Recommended for security-conscious users)
Install dependencies yourself before using the skill:
CODEBLOCK1
Option B: Assisted Setup (Requires confirmation)
Run the setup script with explicit confirmation:
CODEBLOCK2
What setup does (with your confirmation):
- 1. Installs Python dependencies (
ezdxf, matplotlib) - required - Installs
xvfb virtual display - optional but recommended - Downloads and installs ODA File Converter from
opendesign.com - required for DWG support - Downloads and installs QCAD dwg2bmp from
qcad.org - optional, for high-quality screenshots
ODA Download: https://www.opendesign.com/guestfiles/odafileconverter (free registration required)
QCAD Download: https://qcad.org/en/download (Professional Trial)
Check Environment Status
CODEBLOCK3
Outputs JSON-formatted dependency status, including whether each component is installed, its path, and repair commands if missing.
When to use: Run check-env to diagnose issues when any command fails.
Core Tool
All operations use a single CLI tool located at:
CODEBLOCK4
Usage pattern:
CODEBLOCK5
All commands output structured JSON to stdout, making the results directly parseable.
Available Commands
1. info — Get Drawing Basic Information
Read file version, units, entity count summary, and metadata.
CODEBLOCK6
Output includes: DXF version, drawing units, layer count, block count, entity type breakdown.
When to use: As the first step when analyzing any new DWG file. Always start with info to understand the drawing's scope.
2. layers — List All Layers
List all layer definitions with color, linetype, and state (on/off/locked/frozen).
CODEBLOCK7
Options:
- -
--count-entities: Count entities on each layer (slower but informative) - INLINECODE19 : Sort layers by name or color
When to use: To understand the drawing's organizational structure and identify which layers contain relevant content.
3. entities — List Model Space Entities
List entities with optional type and layer filtering.
CODEBLOCK8
Options:
- -
--type: Filter by entity type (INSERT, LINE, CIRCLE, TEXT, MTEXT, LWPOLYLINE, ARC, etc.) - INLINECODE22 : Filter by layer name (exact match)
- INLINECODE23 : Maximum number of results
When to use: To inspect specific types of entities or explore a particular layer's contents.
4. blocks — List Block Definitions
List all block definitions (templates) with their internal entity composition.
CODEBLOCK9
Options:
- -
--name-filter: Filter blocks by name (case-insensitive substring match)
When to use: To catalog available equipment types and standard components in the drawing.
5. inserts — List Block Reference Instances
List block reference instances (placed equipment/components) in model space.
CODEBLOCK10
Options:
- -
--name-filter: Filter by block name - INLINECODE28 : Show internal layer distribution of each block
- INLINECODE29 : Maximum results
When to use: To find specific equipment instances, their positions, and verify their layer assignments.
6. texts — Extract Text Content
Extract all text content (TEXT, MTEXT, and block attributes).
CODEBLOCK11
Options:
- -
--keyword: Filter by keyword (case-insensitive) - INLINECODE32 : Maximum results
When to use: To find labels, annotations, equipment names, or any textual information in the drawing.
7. layer-content — Extract Layer Entity Details
Get all entities on a specific layer with full details.
CODEBLOCK12
When to use: To deeply inspect the contents of a particular professional layer.
8. spaces — View Space Layout System
List all spaces (model space, paper space, block definitions).
CODEBLOCK13
Options:
- -
--detail: Include viewport information for paper spaces
When to use: To understand the drawing's overall structure and printing layout.
9. distance — Calculate Distance Between Points/Entities
Calculate 2D and 3D distances between two entities or coordinates.
CODEBLOCK14
Output includes: 2D distance, 3D distance, delta X/Y/Z, and unit.
When to use: To verify clearance requirements, check equipment spacing, or measure distances between specific points.
10. screenshot — Entity/Region Screenshot
Capture a visual image of a specific entity, layer, or region.
CODEBLOCK15
Options:
- -
--block-name: Center on a named block instance - INLINECODE39 : Center on entity by handle
- INLINECODE40 : Capture the bounding box of all entities on a layer
- INLINECODE41 : Specify exact capture region
- INLINECODE42 : Expansion radius around entity center (default: 5000)
- INLINECODE43 : Output file path (supports .png, .pdf, .svg)
- INLINECODE44 : Image resolution (default: 3000)
- INLINECODE45 : Background color (default: black)
- INLINECODE46 : Path to QCAD dwg2bmp tool
When to use: To visually inspect equipment, verify spatial arrangements, or generate images for reports and multimodal AI analysis.
11. audit — Drawing Compliance Audit
Run automated compliance checks on the drawing.
CODEBLOCK16
Checks performed:
- - Zero-layer violations: INSERT entities on default layer 0
- Block layer mixing: Blocks with non-standard internal layer assignments
- Empty layers: Layers with no entities (potentially redundant)
- DEFPOINTS entities: Non-printing entities on DEFPOINTS layer
Output: Issue list with severity (error/warning/info), rule name, and details.
When to use: Before submitting drawings for review, or when auditing received drawings for compliance.
12. search — Search Entities by Keyword
Search entities by keyword across block names, text content, and layer names.
CODEBLOCK17
When to use: To quickly locate specific equipment, annotations, or components by name.
13. export-pdf — Export to PDF
Convert the drawing to a vector PDF file.
CODEBLOCK18
When to use: To generate a portable visual representation of the drawing.
Recommended Workflow
When analyzing a new DWG file, follow this order:
- 0. Review past learnings → Check
.learning/ for relevant experience (see Self-Learning Mechanism) info → Understand file basics (version, units, entity count)layers → See the organizational structureinserts or entities → Find specific equipment/componentstexts → Extract textual annotationsdistance → Measure spatial relationshipsscreenshot → Capture visuals for detailed inspectionaudit → Check compliance
CAD Domain Knowledge
For detailed understanding of DWG file structure, entity types, layer conventions, and CAD coordinate systems, refer to:
CODEBLOCK19
This reference covers: DWG file hierarchy, entity type catalog, unit systems, layer naming conventions for data center drawings, and common audit rules.
Output Format
All commands produce JSON output to stdout. Error messages go to stderr. Exit code 0 indicates success, non-zero indicates failure.
Example output structure (for info command):
CODEBLOCK20
Error Handling
- - If a file does not exist, the tool exits with a descriptive error message
- If required Python packages are missing, the tool outputs clear installation instructions and exits
- If ODA/QCAD are not available, the tool provides manual setup instructions
- If QCAD is not available for screenshots, the tool automatically falls back to matplotlib rendering
- All errors are written to stderr in JSON format for programmatic consumption
- No packages are installed automatically — all installation requires explicit user action
Notes
- - The
{SKILL_DIR} placeholder refers to the directory containing this SKILL.md file - First run may take 1-3 minutes as the tool automatically installs all dependencies
- After first setup, a marker file is created at
assets/.setup_done to skip future setup - To re-run setup (e.g. after system update), delete
assets/.setup_done and run any command - DWG files require ODA File Converter for reading; DXF files can be read directly
- Screenshot quality is best with QCAD dwg2bmp; matplotlib is a reasonable fallback
- Large drawings may take several seconds to load — this is normal for complex engineering files
- Coordinate values in CAD drawings can be very large (millions); this is normal for real-world projects
Self-Learning Mechanism
This skill supports a self-learning mechanism that records user preferences, error resolutions, and best practices discovered during usage. These records are stored in a .learning/ directory within the user's project and are automatically referenced in subsequent sessions to provide more accurate and personalized assistance.
⚡ Core Principle
Unless the user explicitly requests to skip past experience (e.g., "don't refer to previous learnings", "start fresh"), the agent MUST review .learning/ files at the beginning of every task and apply relevant knowledge throughout the session.
📏 Capacity Limits & Eviction
To prevent records from growing indefinitely and losing their effectiveness, strict limits are enforced:
| File | Max Entries | Eviction Trigger |
|---|
| INLINECODE65 | 50 | When adding a new entry would exceed 50 |
| INLINECODE66 |
30 | When adding a new entry would exceed 30 |
Counting method: Count the number of ## [ heading lines in the file to determine the current entry count.
Eviction strategy — when the limit is reached, before adding a new entry, remove the lowest-value entry using this priority order:
- 1. Status =
resolved entries are evicted first (already addressed, least future value) - Status =
wont_fix entries are evicted next - Among candidates with the same status, evict the one with the oldest
Logged date - Among candidates with the same status and date, evict the one with the lowest priority (
low < medium < high < critical)
Important rules:
- -
pending and in_progress entries are never evicted automatically — if all entries are pending/in_progress and the limit is reached, the agent should ask the user which entry to remove or resolve - When evicting, remove the entire entry block (from
## [ to the next ---) - User preference entries (
user_preference category) have eviction protection — they are only evicted when no other candidates remain, because preferences are persistently valuable
Quick count check (the agent should do this before adding a new entry):
CODEBLOCK21
First-Use Initialization
Before logging anything, ensure the .learning/ directory and files exist in the user's project root (NOT in the skill directory). If any are missing, create them:
CODEBLOCK22
Never overwrite existing files. This is a no-op if .learning/ is already initialized.
When to Review Learnings (Start of Session)
At the start of every CAD analysis task, before executing any commands:
- 1. Check if
.learning/ directory exists in the project root - If it exists, read
.learning/LEARNINGS.md and INLINECODE84 - Identify entries relevant to the current task (by file type, command, layer names, error patterns, etc.)
- Apply relevant learnings proactively — for example:
- If a user preference for screenshot background color was recorded, use it automatically
- If a known error with certain DWG versions was logged, warn the user or apply the fix preemptively
- If a best practice for specific layer analysis was discovered, follow it
When to Log
| Situation | Action |
|---|
| Command fails or produces unexpected output | Log to INLINECODE85 |
| User corrects the agent's approach |
Log to
.learning/LEARNINGS.md with category
correction |
| User specifies a preference (e.g., output format, default options) | Log to
.learning/LEARNINGS.md with category
user_preference |
| A non-obvious solution is discovered | Log to
.learning/LEARNINGS.md with category
insight |
| Agent's knowledge about CAD was incorrect or outdated | Log to
.learning/LEARNINGS.md with category
knowledge_gap |
| A better workflow or approach is found | Log to
.learning/LEARNINGS.md with category
best_practice |
Learning Entry Format
Append to .learning/LEARNINGS.md:
CODEBLOCK23
Error Entry Format
Append to .learning/ERRORS.md:
CODEBLOCK24
Actual error message or output
CODEBLOCK25
ID Generation
Format: TYPE-YYYYMMDD-XXX
- - TYPE:
LRN (learning), ERR (error) - YYYYMMDD: Current date
- XXX: Sequential number (e.g.,
001, 002)
Examples: LRN-20260408-001, INLINECODE104
Resolving Entries
When an issue is fixed or a learning is confirmed, update the entry:
- 1. Change
**Status**: pending → INLINECODE106 - For errors, fill in the
### Resolution section
Privacy & Safety
- - Do NOT log secrets, tokens, private keys, or sensitive environment variables
- Prefer short summaries over full command output
- Do NOT log full file contents — reference file paths instead
- The
.learning/ directory is local to the project and is NOT committed to version control by default
Gitignore Recommendation
Add to the project's .gitignore:
CODEBLOCK26
Quick Reference for Agent Behavior
CODEBLOCK27
CAD DWG/DXF 图纸分析工具
目的
提供专业级的DWG/DXF图纸文件读取和分析能力。该技能支持从CAD图纸中提取结构化数据、实体间的空间分析、图纸区域的视觉捕获以及标准合规性审计。
⚠️ 安全须知
使用此技能前,请查看以下内容:
此技能不会自动安装任何软件包或运行任何设置脚本。如果缺少依赖项,它将输出清晰的错误信息并提供手动安装说明。要设置环境,用户必须显式运行设置命令:
bash
辅助设置(需要显式 --confirm 标志)
python3 {SKILL
DIR}/scripts/cadtools.py setup --confirm
完整的设置过程(在显式确认后)将:
- - 安装Python包(ezdxf、matplotlib)
- 通过 sudo 安装系统包(xvfb、libGL)
- 从 opendesign.com 下载并安装 ODA File Converter
- 从 qcad.org 下载并安装 QCAD dwg2bmp
所有下载均来自官方源,但该技能需要网络访问和提升的权限。
前置条件
- - Python 3.8+(系统已安装)
- Python包:使用前必须安装 ezdxf 和 matplotlib
- root/sudo 权限(仅当您选择运行自动设置时)
- x86_64 Linux 系统
设置选项
选项A:手动设置(推荐安全意识强的用户使用)
在使用技能前自行安装依赖项:
bash
1. 安装Python包
pip3 install ezdxf matplotlib
2. 安装系统包(Ubuntu/Debian)
sudo apt-get install xvfb libgl1-mesa-glx libglu1-mesa
3. 手动从以下地址下载并安装ODA File Converter:
https://www.opendesign.com/guestfiles/odafileconverter
4. 手动从以下地址下载并解压QCAD dwg2bmp:
https://qcad.org/en/download
然后设置:export QCADDWG2BMPPATH=/path/to/qcad/dwg2bmp
选项B:辅助设置(需要确认)
使用显式确认运行设置脚本:
bash
运行设置并交互式确认
python3 {SKILL
DIR}/scripts/cadtools.py setup --confirm
或手动指定您已下载的包
python3 {SKILL
DIR}/scripts/cadtools.py setup --oda-rpm /path/to/ODAFileConverter
xxx.rpm --qcad-tar /path/to/qcad-xxx-trial-linux-x8664.tar.gz
设置会做什么(在您确认后):
- 1. 安装Python依赖项(ezdxf、matplotlib)— 必需
- 安装 xvfb 虚拟显示器 — 可选但推荐
- 从 opendesign.com 下载并安装 ODA File Converter — DWG支持必需
- 从 qcad.org 下载并安装 QCAD dwg2bmp — 可选,用于高质量截图
ODA下载:https://www.opendesign.com/guestfiles/odafileconverter(需要免费注册)
QCAD下载:https://qcad.org/en/download(专业试用版)
检查环境状态
bash
python3 {SKILLDIR}/scripts/cadtools.py check-env
输出JSON格式的依赖状态,包括每个组件是否已安装、其路径以及缺失时的修复命令。
使用时机:当任何命令失败时,运行 check-env 来诊断问题。
核心工具
所有操作均使用位于以下位置的单一CLI工具:
scripts/cad_tools.py
使用模式:
bash
python3 {SKILLDIR}/scripts/cadtools.py COMMAND DWG_FILE [OPTIONS]
所有命令输出结构化的 JSON 到标准输出,使结果可直接解析。
可用命令
1. info — 获取图纸基本信息
读取文件版本、单位、实体计数摘要和元数据。
bash
python3 {SKILLDIR}/scripts/cadtools.py info /path/to/drawing.dwg
输出包括:DXF版本、图纸单位、图层数量、块数量、实体类型细分。
使用时机:作为分析任何新DWG文件的第一步。始终从 info 开始以了解图纸的范围。
2. layers — 列出所有图层
列出所有图层定义,包括颜色、线型和状态(开/关/锁定/冻结)。
bash
python3 {SKILLDIR}/scripts/cadtools.py layers /path/to/drawing.dwg --count-entities --sort-by name
选项:
- - --count-entities:统计每个图层上的实体数量(较慢但有信息量)
- --sort-by name|color:按名称或颜色排序图层
使用时机:了解图纸的组织结构并识别哪些图层包含相关内容。
3. entities — 列出模型空间实体
列出实体,可选的类型和图层过滤。
bash
python3 {SKILLDIR}/scripts/cadtools.py entities /path/to/drawing.dwg --type INSERT --layer EC.SingleLine --limit 20
选项:
- - --type:按实体类型过滤(INSERT、LINE、CIRCLE、TEXT、MTEXT、LWPOLYLINE、ARC等)
- --layer:按图层名称过滤(精确匹配)
- --limit:最大结果数
使用时机:检查特定类型的实体或探索特定图层的内容。
4. blocks — 列出块定义
列出所有块定义(模板)及其内部实体组成。
bash
python3 {SKILLDIR}/scripts/cadtools.py blocks /path/to/drawing.dwg --name-filter breaker
选项:
- - --name-filter:按名称过滤块(不区分大小写的子字符串匹配)
使用时机:编目图纸中可用的设备类型和标准组件。
5. inserts — 列出块参照实例
列出模型空间中的块参照实例(已放置的设备/组件)。
bash
python3 {SKILLDIR}/scripts/cadtools.py inserts /path/to/drawing.dwg --name-filter 10KV --analyze-layers --limit 50
选项:
- - --name-filter:按块名称过滤
- --analyze-layers:显示每个块的内部图层分布
- --limit:最大结果数
使用时机:查找特定设备实例、其位置,并验证其图层分配。
6. texts — 提取文本内容
提取所有文本内容(TEXT、MTEXT和块属性)。
bash
python3 {SKILLDIR}/scripts/cadtools.py texts /path/to/drawing.dwg --keyword distribution --limit 30
选项:
- - --keyword:按关键字过滤(不区分大小写)
- --limit:最大结果数
使用时机:查找标签、注释、设备名称或图纸中的任何文本信息。
7. layer-content — 提取图层实体详情
获取特定图层上的所有实体及其完整详情。
bash
python3 {SKILLDIR}/scripts/cadtools.py layer-content /path/to/drawing.dwg EC.SingleLine --limit 20
使用时机:深入检查特定专业图层的内容。
8. spaces — 查看空间布局系统
列出所有空间(模型空间、图纸空间、块定义)。
bash
python3 {SKILLDIR}/scripts/cadtools.py spaces /path/to/drawing.dwg --detail
选项:
使用时机:了解图纸的整体结构和打印布局。
9. distance — 计算点/实体间的距离
计算两个实体或坐标之间的2D和3D距离。
bash
按块名称
python3 {SKILL
DIR}/scripts/cadtools.py distance /path/to/drawing.dwg --entity1 10KV.GenSet.01IncomingHV --entity2 10KV.RouteA-01Incoming.BreakerHV
按坐标
python3 {SKILL
DIR}/scripts/cadtools.py distance /path/to/drawing.dwg --coord1 100,200 --coord2 500,600
混合:实体 + 坐标
python3 {SKILL
DIR}/scripts/cadtools.py distance /path/to/drawing.dwg --entity1 10KV.GenSet.01IncomingHV --coord2 500,600
输出包括:2D距离、3D距离、X/Y/Z增量以及单位。
使用时机:验证净空要求、检查设备间距或测量特定点之间的距离。
10. screenshot —