dwg2image 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- dwg2image/__init__.py +36 -0
- dwg2image/__main__.py +3 -0
- dwg2image/_conversion.py +117 -0
- dwg2image/render.py +32 -0
- dwg2image/run_headless.sh +15 -0
- dwg2image-0.1.0.dist-info/METADATA +106 -0
- dwg2image-0.1.0.dist-info/RECORD +10 -0
- dwg2image-0.1.0.dist-info/WHEEL +5 -0
- dwg2image-0.1.0.dist-info/entry_points.txt +2 -0
- dwg2image-0.1.0.dist-info/top_level.txt +1 -0
dwg2image/__init__.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
"""DWG conversion requires an external ODA installation; DXF rendering is local."""
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
import tempfile
|
|
4
|
+
|
|
5
|
+
from ._conversion import convert, inspect_dwg, inspect_dxf
|
|
6
|
+
from .render import dxf_to_png
|
|
7
|
+
|
|
8
|
+
__all__ = ["dwg_to_dxf", "dxf_to_png", "dwg_to_png", "inspect_dwg", "inspect_dxf"]
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def dwg_to_dxf(source: str | Path, destination: str | Path, *,
|
|
12
|
+
appdir: str | Path, docker_image: str | None = None,
|
|
13
|
+
timeout: float = 300) -> Path:
|
|
14
|
+
"""Write a fresh DXF using ODA. Existing destinations are never overwritten.
|
|
15
|
+
|
|
16
|
+
appdir is an extracted Linux x86-64 ODA AppImage directory. On other
|
|
17
|
+
platforms, supply a prepared Linux x86-64 docker_image as well.
|
|
18
|
+
Raises FileExistsError, OSError, ValueError, RuntimeError or TimeoutExpired.
|
|
19
|
+
"""
|
|
20
|
+
convert(source, destination, appdir, image=docker_image, timeout=timeout)
|
|
21
|
+
return Path(destination)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def dwg_to_png(source: str | Path, destination: str | Path, *,
|
|
25
|
+
appdir: str | Path, docker_image: str | None = None,
|
|
26
|
+
timeout: float = 300, dpi: int = 150,
|
|
27
|
+
background: str = "#FFFFFF") -> Path:
|
|
28
|
+
"""Convert DWG to a modelspace PNG; temporary DXF is removed afterwards."""
|
|
29
|
+
destination = Path(destination)
|
|
30
|
+
if destination.exists():
|
|
31
|
+
raise FileExistsError(destination)
|
|
32
|
+
with tempfile.TemporaryDirectory(prefix="dwg2image-render-") as directory:
|
|
33
|
+
intermediate = Path(directory) / "drawing.dxf"
|
|
34
|
+
dwg_to_dxf(source, intermediate, appdir=appdir,
|
|
35
|
+
docker_image=docker_image, timeout=timeout)
|
|
36
|
+
return dxf_to_png(intermediate, destination, dpi=dpi, background=background)
|
dwg2image/__main__.py
ADDED
dwg2image/_conversion.py
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
"""DWG inspection and an explicit ODA-backed DXF conversion prototype.
|
|
2
|
+
|
|
3
|
+
This is not an independent DWG geometry decoder. No shell interpolation is used.
|
|
4
|
+
"""
|
|
5
|
+
import argparse
|
|
6
|
+
from collections import Counter
|
|
7
|
+
import hashlib
|
|
8
|
+
import json
|
|
9
|
+
import os
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
import platform
|
|
12
|
+
import shutil
|
|
13
|
+
import struct
|
|
14
|
+
import subprocess
|
|
15
|
+
import tempfile
|
|
16
|
+
import uuid
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def inspect_dwg(path):
|
|
20
|
+
path = Path(path)
|
|
21
|
+
data = path.read_bytes()
|
|
22
|
+
signature = data[:6].decode('ascii', errors='replace')
|
|
23
|
+
result = {'path': str(path.resolve()), 'sha256': hashlib.sha256(data).hexdigest(),
|
|
24
|
+
'bytes': len(data), 'signature': signature, 'geometry_decoded': False}
|
|
25
|
+
if signature == 'AC1015':
|
|
26
|
+
if len(data) < 25:
|
|
27
|
+
raise ValueError('truncated AC1015 header')
|
|
28
|
+
count = struct.unpack_from('<I', data, 0x15)[0]
|
|
29
|
+
if count > (len(data)-25)//9:
|
|
30
|
+
raise ValueError('section directory extends beyond file')
|
|
31
|
+
sections = []
|
|
32
|
+
for i in range(count):
|
|
33
|
+
ident, offset, size = struct.unpack_from('<BII', data, 25+9*i)
|
|
34
|
+
if offset+size > len(data):
|
|
35
|
+
raise ValueError(f'section {ident} extends beyond file')
|
|
36
|
+
sections.append({'id': ident, 'offset': offset, 'size': size})
|
|
37
|
+
result['r2000_section_directory'] = sections
|
|
38
|
+
elif signature != 'AC1032':
|
|
39
|
+
raise ValueError(f'unexamined DWG signature: {signature!r}')
|
|
40
|
+
return result
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def convert(source, destination, appdir, image=None, timeout=300):
|
|
44
|
+
"""Convert one file in fresh staging, so stale output cannot pass validation."""
|
|
45
|
+
source, destination, appdir = Path(source), Path(destination), Path(appdir)
|
|
46
|
+
inspect_dwg(source)
|
|
47
|
+
if destination.exists():
|
|
48
|
+
raise FileExistsError(f'refusing to overwrite {destination}')
|
|
49
|
+
binary = appdir / 'usr/bin/ODAFileConverter'
|
|
50
|
+
if not binary.is_file():
|
|
51
|
+
raise FileNotFoundError(binary)
|
|
52
|
+
destination.parent.mkdir(parents=True, exist_ok=True)
|
|
53
|
+
with tempfile.TemporaryDirectory(prefix='dwg2image-') as temp:
|
|
54
|
+
root = Path(temp); (root/'in').mkdir(); (root/'out').mkdir()
|
|
55
|
+
shutil.copy2(source, root/'in'/source.name)
|
|
56
|
+
args = ['ACAD2018', 'DXF', '0', '1', '*.dwg']
|
|
57
|
+
if image:
|
|
58
|
+
container_name = 'dwg2image-' + uuid.uuid4().hex
|
|
59
|
+
cmd = ['docker', 'run', '--rm', '--name', container_name, '--network=none', '--platform', 'linux/amd64',
|
|
60
|
+
'--ulimit', 'core=0', '-e', 'QT_QPA_PLATFORM=xcb',
|
|
61
|
+
'-e', 'LD_LIBRARY_PATH=/oda/usr/bin:/oda/usr/lib',
|
|
62
|
+
'-e', 'QT_PLUGIN_PATH=/oda/usr/plugins',
|
|
63
|
+
'-v', f'{appdir.resolve()}:/oda:ro', '-v', f'{root.resolve()}:/job',
|
|
64
|
+
'-v', f'{Path(__file__).resolve().parent / "run_headless.sh"}:/run_headless.sh:ro',
|
|
65
|
+
image, 'sh', '/run_headless.sh', '/oda/usr/bin/ODAFileConverter', '/job/in', '/job/out', *args]
|
|
66
|
+
env = None
|
|
67
|
+
else:
|
|
68
|
+
if platform.system() != 'Linux' or platform.machine() not in ('x86_64', 'AMD64'):
|
|
69
|
+
raise RuntimeError('ODA requires Linux x86-64; use --docker-image with a prepared image')
|
|
70
|
+
env = dict(os.environ, QT_QPA_PLATFORM='xcb',
|
|
71
|
+
LD_LIBRARY_PATH=f'{appdir.resolve()}/usr/bin:{appdir.resolve()}/usr/lib',
|
|
72
|
+
QT_PLUGIN_PATH=f'{appdir.resolve()}/usr/plugins')
|
|
73
|
+
cmd = ['xvfb-run', '-a', str(binary.resolve()), str(root/'in'), str(root/'out'), *args]
|
|
74
|
+
try:
|
|
75
|
+
completed = subprocess.run(cmd, env=env, capture_output=True, text=True, timeout=timeout)
|
|
76
|
+
finally:
|
|
77
|
+
if image:
|
|
78
|
+
subprocess.run(['docker', 'rm', '-f', container_name], capture_output=True, timeout=30)
|
|
79
|
+
if completed.returncode:
|
|
80
|
+
raise RuntimeError(f'ODA exit {completed.returncode}: {completed.stderr}\n{completed.stdout}')
|
|
81
|
+
candidates = [f for f in (root/'out').iterdir() if f.suffix.lower()=='.dxf']
|
|
82
|
+
if len(candidates)!=1:
|
|
83
|
+
raise RuntimeError(f'expected one fresh DXF, found {len(candidates)}: {completed.stdout}')
|
|
84
|
+
report = inspect_dxf(candidates[0])
|
|
85
|
+
with destination.open('xb') as output:
|
|
86
|
+
with candidates[0].open('rb') as converted:
|
|
87
|
+
shutil.copyfileobj(converted, output)
|
|
88
|
+
report.update(output=str(destination.resolve()), backend='closed-source ODA',
|
|
89
|
+
source_sha256=hashlib.sha256(source.read_bytes()).hexdigest())
|
|
90
|
+
return report
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def inspect_dxf(path):
|
|
94
|
+
import ezdxf
|
|
95
|
+
doc = ezdxf.readfile(path)
|
|
96
|
+
audit = doc.audit()
|
|
97
|
+
return {'dxf_version': doc.dxfversion, 'modelspace_entities': dict(Counter(e.dxftype() for e in doc.modelspace())),
|
|
98
|
+
'blocks': len(doc.blocks), 'layers': len(doc.layers), 'audit_errors': len(audit.errors),
|
|
99
|
+
'audit_fixes': len(audit.fixes), 'sha256': hashlib.sha256(path.read_bytes()).hexdigest(),
|
|
100
|
+
'limitation': 'Readable DXF does not prove geometric fidelity to the DWG.'}
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def main():
|
|
104
|
+
p=argparse.ArgumentParser(description=__doc__)
|
|
105
|
+
sub=p.add_subparsers(dest='command', required=True)
|
|
106
|
+
for name in ('inspect', 'check-dxf'):
|
|
107
|
+
s=sub.add_parser(name);s.add_argument('path', type=Path)
|
|
108
|
+
s=sub.add_parser('convert');s.add_argument('path', type=Path);s.add_argument('output', type=Path)
|
|
109
|
+
s.add_argument('--appdir', type=Path, required=True);s.add_argument('--docker-image');s.add_argument('--timeout', type=int, default=300)
|
|
110
|
+
a=p.parse_args()
|
|
111
|
+
if a.command=='inspect': result=inspect_dwg(a.path)
|
|
112
|
+
elif a.command=='check-dxf': result=inspect_dxf(a.path)
|
|
113
|
+
else: result=convert(a.path,a.output,a.appdir,a.docker_image,a.timeout)
|
|
114
|
+
print(json.dumps(result, ensure_ascii=False, indent=2))
|
|
115
|
+
|
|
116
|
+
if __name__=='__main__':
|
|
117
|
+
main()
|
dwg2image/render.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
"""Render DXF modelspace to a PNG without an external CAD application."""
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
import tempfile
|
|
4
|
+
import shutil
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def dxf_to_png(source: str | Path, destination: str | Path, *,
|
|
8
|
+
dpi: int = 150, background: str = "#FFFFFF") -> Path:
|
|
9
|
+
"""Write a PNG, preserving existing outputs and removing failed staging.
|
|
10
|
+
|
|
11
|
+
Only modelspace is rendered. Font substitution and unsupported CAD entities
|
|
12
|
+
may affect appearance. Returns the destination Path.
|
|
13
|
+
"""
|
|
14
|
+
import ezdxf
|
|
15
|
+
from ezdxf.addons.drawing.matplotlib import qsave
|
|
16
|
+
|
|
17
|
+
source, destination = Path(source), Path(destination)
|
|
18
|
+
if destination.suffix.lower() != ".png":
|
|
19
|
+
raise ValueError("destination must have a .png suffix")
|
|
20
|
+
if not isinstance(dpi, int) or dpi <= 0:
|
|
21
|
+
raise ValueError("dpi must be a positive integer")
|
|
22
|
+
if destination.exists():
|
|
23
|
+
raise FileExistsError(destination)
|
|
24
|
+
document = ezdxf.readfile(source)
|
|
25
|
+
destination.parent.mkdir(parents=True, exist_ok=True)
|
|
26
|
+
with tempfile.TemporaryDirectory(prefix="dwg2image-png-") as directory:
|
|
27
|
+
rendered = Path(directory) / "drawing.png"
|
|
28
|
+
qsave(document.modelspace(), rendered, dpi=dpi, bg=background, backend="agg")
|
|
29
|
+
with destination.open("xb") as output:
|
|
30
|
+
with rendered.open("rb") as image:
|
|
31
|
+
shutil.copyfileobj(image, output)
|
|
32
|
+
return destination
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
#!/bin/sh
|
|
2
|
+
# Avoid xvfb-run's signal handshake under Docker Desktop x86 emulation.
|
|
3
|
+
set -eu
|
|
4
|
+
Xvfb :99 -screen 0 1280x1024x24 -nolisten tcp &
|
|
5
|
+
xvfb_pid=$!
|
|
6
|
+
trap 'kill "$xvfb_pid" 2>/dev/null || true' EXIT
|
|
7
|
+
export DISPLAY=:99
|
|
8
|
+
attempt=0
|
|
9
|
+
while [ ! -S /tmp/.X11-unix/X99 ]; do
|
|
10
|
+
kill -0 "$xvfb_pid"
|
|
11
|
+
attempt=$((attempt + 1))
|
|
12
|
+
[ "$attempt" -lt 100 ] || exit 1
|
|
13
|
+
sleep 0.1
|
|
14
|
+
done
|
|
15
|
+
"$@"
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: dwg2image
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Convert DWG drawings to PNG via an external ODA converter and ezdxf
|
|
5
|
+
Project-URL: Repository, https://github.com/wjiaxin853-ctrl/dwg2image
|
|
6
|
+
Requires-Python: >=3.10
|
|
7
|
+
Description-Content-Type: text/markdown
|
|
8
|
+
Requires-Dist: ezdxf<2,>=1.4.5
|
|
9
|
+
Requires-Dist: matplotlib<4,>=3.8
|
|
10
|
+
Requires-Dist: Pillow>=10
|
|
11
|
+
|
|
12
|
+
# dwg2image
|
|
13
|
+
|
|
14
|
+
将 DWG 图纸转换为 PNG 的 Python 库,也支持 DWG→DXF 和 DXF→PNG。
|
|
15
|
+
|
|
16
|
+
DWG 解码依赖用户自行准备的 **ODA File Converter**,本库不包含或自动下载 ODA。已有 DXF 转 PNG 不需要 ODA 或 Docker。Python 版本要求:3.10+。
|
|
17
|
+
|
|
18
|
+
## 安装
|
|
19
|
+
|
|
20
|
+
目前尚未发布到 PyPI,可通过 GitHub 安装:
|
|
21
|
+
|
|
22
|
+
```sh
|
|
23
|
+
pip install "git+https://github.com/wjiaxin853-ctrl/dwg2image.git"
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
## 使用
|
|
27
|
+
|
|
28
|
+
已有 DXF 转图片:
|
|
29
|
+
|
|
30
|
+
```python
|
|
31
|
+
from dwg2image import dxf_to_png
|
|
32
|
+
|
|
33
|
+
image = dxf_to_png("drawing.dxf", "drawing.png", dpi=150)
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
DWG 转图片:
|
|
37
|
+
|
|
38
|
+
```python
|
|
39
|
+
from dwg2image import dwg_to_png
|
|
40
|
+
|
|
41
|
+
image = dwg_to_png(
|
|
42
|
+
"drawing.dwg",
|
|
43
|
+
"drawing.png",
|
|
44
|
+
appdir="/absolute/path/to/squashfs-root",
|
|
45
|
+
docker_image="dwg2image-runtime:local",
|
|
46
|
+
dpi=150,
|
|
47
|
+
)
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
仅转换为 DXF:
|
|
51
|
+
|
|
52
|
+
```python
|
|
53
|
+
from dwg2image import dwg_to_dxf
|
|
54
|
+
|
|
55
|
+
dxf = dwg_to_dxf(
|
|
56
|
+
"drawing.dwg", "drawing.dxf",
|
|
57
|
+
appdir="/absolute/path/to/squashfs-root",
|
|
58
|
+
docker_image="dwg2image-runtime:local",
|
|
59
|
+
)
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
三个接口接受字符串或 `Path`,返回输出 `Path`;已有目标文件不会覆盖,抛出 `FileExistsError`。`dwg_to_png()` 自动清理中间 DXF。ODA 非零退出抛出 `RuntimeError`,超时抛出 `subprocess.TimeoutExpired`;超时参数为 `timeout=300`(秒)。
|
|
63
|
+
|
|
64
|
+
## 准备 ODA 运行环境
|
|
65
|
+
|
|
66
|
+
当前适配 Linux x86-64 ODA AppImage 的解包目录,要求包含 `usr/bin/ODAFileConverter` 及随包共享库和 Qt 插件。在 Linux 解包:
|
|
67
|
+
|
|
68
|
+
```sh
|
|
69
|
+
chmod +x ODAFileConverter.AppImage
|
|
70
|
+
./ODAFileConverter.AppImage --appimage-extract
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
将得到的 `squashfs-root` 绝对路径传入 `appdir`。源码目录中的 `artifacts/appdir` 只是本地准备的运行依赖,不随 Git 或 pip 安装包分发。
|
|
74
|
+
|
|
75
|
+
原生 Linux x86-64 需要 Xvfb、xauth 及共享库(参考 Dockerfile),可以省略 `docker_image` 参数。
|
|
76
|
+
|
|
77
|
+
macOS 或使用容器的 Linux 主机,先从仓库构建运行镜像:
|
|
78
|
+
|
|
79
|
+
```sh
|
|
80
|
+
git clone https://github.com/wjiaxin853-ctrl/dwg2image.git
|
|
81
|
+
cd dwg2image
|
|
82
|
+
docker build --platform linux/amd64 -t dwg2image-runtime:local .
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
Docker 必须能访问 `appdir` 和系统临时目录;macOS ARM 还需支持 Linux x86-64 模拟。容器转换期间禁用网络,ODA 目录只读挂载。Dockerfile 只安装运行依赖,不包含 ODA。
|
|
86
|
+
|
|
87
|
+
## 范围与限制
|
|
88
|
+
|
|
89
|
+
- PNG 渲染模型空间。字体替换、外部参照及不支持的实体可能影响显示,不保证所有 CAD 内容保真。
|
|
90
|
+
- 当前入口识别 AC1015、AC1032 文件头,其他 DWG 版本尚未支持。
|
|
91
|
+
- Matplotlib 绘图接口不保证多线程并发安全;服务端并发调用建议使用独立进程。
|
|
92
|
+
- 已提供 `inspect_dwg()` 和 `inspect_dxf()` 检查接口;CLI 保留 `inspect`、`check-dxf` 和 `convert` 子命令,运行 `dwg2image --help` 查看参数。
|
|
93
|
+
|
|
94
|
+
## 开发与打包
|
|
95
|
+
|
|
96
|
+
```sh
|
|
97
|
+
python3 -m venv .venv
|
|
98
|
+
.venv/bin/pip install -e . build twine
|
|
99
|
+
.venv/bin/python -m unittest -v
|
|
100
|
+
.venv/bin/python -m build
|
|
101
|
+
.venv/bin/python -m twine check dist/*
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
发布使用 `python -m twine upload dist/*`,需要 PyPI 项目权限和发布凭证。
|
|
105
|
+
|
|
106
|
+
已验证独立虚拟环境安装 wheel 后从源码目录之外导入,使用本地 ODA 与 Docker 完成一次真实 DWG→PNG 转换。测试包含 DXF 渲染与已有文件保护;尚未进行全量图纸或几何保真验证。
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
dwg2image/__init__.py,sha256=hEoALtaPqR0LE2atJNOnNTC_mC6UAm9vbLx4iab4PVk,1663
|
|
2
|
+
dwg2image/__main__.py,sha256=iRNVwWnRrFvDq07QUWmeNPQ9QU2yWARUnXpibh0wEoA,38
|
|
3
|
+
dwg2image/_conversion.py,sha256=4Cx4BkXl9zInYJNdoNb7OQ1wU3t06P9TV95ilPL4Jm4,5771
|
|
4
|
+
dwg2image/render.py,sha256=sIpZV-627gHTjDdAoxqtLP7Nm9HhyeieTaYXFpD_aSs,1377
|
|
5
|
+
dwg2image/run_headless.sh,sha256=26HDPxriNQ1AZC45ggJgPOppnwEImhk7cuTlMlU1hyM,372
|
|
6
|
+
dwg2image-0.1.0.dist-info/METADATA,sha256=5JKxv1o5hxnEgw6aV6jzNXZtQTOVmfCeLn0gyOWPM0Q,3671
|
|
7
|
+
dwg2image-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
8
|
+
dwg2image-0.1.0.dist-info/entry_points.txt,sha256=JULD3r-qRsOh4c26fbe_I3fPUqwekRyOiOPteNbyjwg,57
|
|
9
|
+
dwg2image-0.1.0.dist-info/top_level.txt,sha256=xDotjl21o1GGOKloTW1yfX6TyRaRkOyS_Bu7Etoxdos,10
|
|
10
|
+
dwg2image-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
dwg2image
|