コード例 #1
0
ファイル: __main__.py プロジェクト: mhenr18/ezdxf
def main() -> None:
    print()
    parser = argparse.ArgumentParser()
    parser.add_argument(
        '-r', '--recover',
        dest='recover',
        action='store_true',
        help='use recover mode to load files with DXF structure errors'
    )
    parser.add_argument(
        'files',
        metavar='FILE',
        nargs='+',
        help='audit DXF files',
    )

    args = parser.parse_args(sys.argv[1:])

    ezdxf.options.compress_binary_data = True
    for pattern in args.files:
        names = list(glob.glob(pattern))
        if len(names) == 0:
            print(f"File(s) '{pattern}' not found.")
            continue
        for filename in names:
            if not os.path.exists(filename):
                print(f"File '{filename}' not found.")
                continue
            if not is_dxf_file(filename):
                print(f"File '{filename}' is not a DXF file.")
                continue
            processing_msg(filename)
            audit(filename, safe=args.recover)
コード例 #2
0
ファイル: filemanagement.py プロジェクト: soldocode/ezdxf
def readfile(filename, encoding=None, legacy_mode=False):
    """
    Read DXF drawing specified by *filename* from file system.

    Supported DXF versions:

    - pre AC1009 DXF versions will be upgraded to AC1009
    - AC1009: AutoCAD R12 (DXF R12)
    - AC1012: AutoCAD R13 upgraded to AC1015
    - AC1014: AutoCAD R14 upgraded to AC1015
    - AC1015: AutoCAD 2000
    - AC1018: AutoCAD 2004
    - AC1021: AutoCAD 2007, fixates encoding='utf-8'
    - AC1024: AutoCAD 2010, fixates encoding='utf-8'
    - AC1027: AutoCAD 2013, fixates encoding='utf-8'
    - AC1032: AutoCAD 2018, fixates encoding='utf-8'

    Args:
        filename: DXF filename
        encoding: use None for auto detect, or set a specific encoding like 'utf-8'
        legacy_mode: True - adds an extra trouble shooting import layer; False - requires DXF file from modern CAD apps

    """
    if not is_dxf_file(filename):
        raise IOError("File '{}' is not a DXF file.".format(filename))

    info = dxf_file_info(filename)
    with io.open(filename, mode='rt', encoding=info.encoding,
                 errors='ignore') as fp:
        dwg = read(fp, legacy_mode=legacy_mode, dxfversion=info.version)

    dwg.filename = filename
    if encoding is not None and is_supported_encoding(encoding):
        dwg.encoding = encoding
    return dwg
コード例 #3
0
def readfile(filename: str,
             encoding: str = None,
             legacy_mode: bool = False,
             filter_stack=None) -> 'Drawing':
    """
    Read DXF document specified by `filename` from file-system.

    This is the preferred method to open existing ASCII or Binary DXF files. Read the DXF drawing from the
    file-system with auto-detection of encoding for ASCII DXF files. Decoding errors will be ignored.
    Override encoding detection by setting argument `encoding` to the estimated encoding. (use Python encoding
    names like in the :func:`open` function).

    If argument `legacy_mode` is ``True``, `ezdxf` tries to reorder the coordinates of the LINE entity in files from
    CAD applications which wrote the coordinates in the order: x1, x2, y1, y2. Additional fixes may be added later. The
    legacy mode has a speed penalty of around 5%.

    .. hint::

        Try argument :code:`legacy_mode=True` if error ``'Missing required y coordinate near line: ...'`` occurs.

    Args:
        filename: filename of ASCII or Binary DXF document
        encoding: use ``None`` for auto detect (default), or set a specific encoding like ``'utf-8'``, ignored for
                  Binary DXF files
        legacy_mode: adds an extra trouble shooting import layer if ``True``
        filter_stack: interface to put filters between reading layers

    Raises:
        IOError: File `filename` is not a DXF file or does not exist.
        DXFStructureError: for invalid DXF structure

    """
    # for argument filter_stack see :class:`~ezdxf.drawing.Drawing.read` for more information
    from ezdxf.lldxf.validator import is_dxf_file, is_binary_dxf_file
    from ezdxf.tools.codepage import is_supported_encoding
    from ezdxf.lldxf.tagger import binary_tags_loader

    if is_binary_dxf_file(filename):
        with open(filename, 'rb') as fp:
            data = fp.read()
            loader = binary_tags_loader(data)
            return Drawing.load(loader, legacy_mode, filter_stack)

    if not is_dxf_file(filename):
        raise IOError("File '{}' is not a DXF file.".format(filename))

    info = dxf_file_info(filename)
    if encoding is not None:
        # override default encodings if absolute necessary
        info.encoding = encoding
    with open(filename, mode='rt', encoding=info.encoding,
              errors='ignore') as fp:
        doc = read(fp, legacy_mode=legacy_mode, filter_stack=filter_stack)

    doc.filename = filename
    if encoding is not None and is_supported_encoding(encoding):
        # store overridden encoding if supported by AutoCAD, else default encoding stored in $DWGENCODING is used
        # as document encoding or 'cp1252' if $DWGENCODING is unset.
        doc.encoding = encoding
    return doc
コード例 #4
0
ファイル: __main__.py プロジェクト: tbwhsb88/ezdxf
def main() -> None:
    print()
    parser = argparse.ArgumentParser()
    parser.add_argument(
        'files',
        metavar='FILE',
        nargs='+',
        help='audit DXF files',
    )

    args = parser.parse_args(sys.argv[1:])

    options.compress_binary_data = True
    for pattern in args.files:
        names = list(glob.glob(pattern))
        if len(names) == 0:
            print("File(s) '{}' not found.".format(pattern))
            continue
        for filename in names:
            if not os.path.exists(filename):
                print("File '{}' not found.".format(filename))
                continue
            if not is_dxf_file(filename):
                print("File '{}' is not a DXF file.".format(filename))
                continue
            processing_msg(filename)
            audit(filename)
コード例 #5
0
ファイル: pprint.py プロジェクト: Rahulghuge94/ezdxf
def run(args):
    for filename in args.files:
        if not Path(filename).exists():
            print(f'File "{filename}" not found.')
            continue

        if is_binary_dxf_file(filename):
            binary_dxf = True
        else:
            binary_dxf = False
            if not is_dxf_file(filename):
                print(f'File "{filename}" is not a DXF file.')
                continue

        if args.raw:
            html_path = raw_pretty_print(
                Path(filename),
                compile_tags=not args.nocompile,
                legacy_mode=args.legacy,
                is_binary_dxf=binary_dxf,
            )
        else:
            html_path = pretty_print(
                Path(filename),
                is_binary_dxf=binary_dxf)  # legacy mode is always used

        print(f'Created "{html_path}"')
        if args.open:
            webbrowser.open(str(html_path))
コード例 #6
0
def test_read_gerber_file():
    from ezdxf.lldxf.validator import is_dxf_file
    assert is_dxf_file(GERBER_FILE)

    doc = ezdxf.readfile(GERBER_FILE)
    assert doc.filename == GERBER_FILE
    assert doc.dxfversion == 'AC1009'
コード例 #7
0
ファイル: odafc.py プロジェクト: mbway/ezdxf
def readfile(filename: str,
             version: str = None,
             audit=False) -> Optional[Drawing]:
    """
    Use an installed `ODA File Converter`_ to convert a DWG/DXB/DXF file into a temporary DXF file and load
    this file by `ezdxf`.

    Args:
        filename: file to load by ODA File Converter
        version: load file as specific DXF version, by default the same version as the source file or
                 if not detectable the latest by `ezdxf` supported version.
        audit: audit source file before loading

    """
    infile = Path(filename).absolute()
    if not infile.exists():
        raise FileNotFoundError(f"No such file or directory: '{infile}'")
    in_folder = infile.parent
    name = infile.name
    ext = infile.suffix.lower()

    tmp_folder = Path(temp_path).absolute()
    if not tmp_folder.exists():
        tmp_folder.mkdir()

    dxf_temp_file = (tmp_folder / name).with_suffix('.dxf')
    _version = 'ACAD2018'
    if ext == '.dxf':
        if is_binary_dxf_file(str(infile)):
            pass
        elif is_dxf_file(str(infile)):
            with open(filename, 'rt') as fp:
                info = dxf_info(fp)
                _version = VERSION_MAP[info.version]
    elif ext == '.dwg':
        _version = dwg_version(str(infile))
        if _version is None:
            raise ValueError('Unknown or unsupported DWG version.')
    else:
        raise ValueError(f"Unsupported file format: '{ext}'")

    if version is None:
        version = _version

    version = map_version(version)
    cmd = _odafc_cmd(name,
                     str(in_folder),
                     str(tmp_folder),
                     fmt='DXF',
                     version=version,
                     audit=audit)
    _execute_odafc(cmd)

    if dxf_temp_file.exists():
        doc = ezdxf.readfile(str(dxf_temp_file))
        dxf_temp_file.unlink()
        doc.filename = infile.with_suffix('.dxf')
        return doc
    return None
コード例 #8
0
 def __init__(self, name: str):
     self.name = str(name)
     if not is_dxf_file(name):
         raise DXFStructureError(f'File {name} is not a DXF file')
     info = dxf_file_info(name)
     self.encoding = info.encoding
     self.dxfversion = info.version
     self.file = open(name, mode='rt', encoding=self.encoding)
     self._fp_entities_section = None
     self._fp_objects_section = None
コード例 #9
0
ファイル: buildheadertables.py プロジェクト: jrflack/ezdxf
def get_tagger(filename):
    from ezdxf.lldxf.validator import is_dxf_file
    from ezdxf.filemanagement import dxf_file_info
    if not is_dxf_file(filename):
        raise IOError("File '{}' is not a DXF file.".format(filename))

    info = dxf_file_info(filename)
    with open(filename, mode='rt', encoding=info.encoding, errors='ignore') as fp:
        tagger = read(fp)
    return tagger
コード例 #10
0
def strip(filename: str, backup=False, thumbnail=False, verbose=False):
    def remove_tmp_file():
        if tmp_file.exists():
            if verbose:
                print(f'deleting temp file: "{tmp_file.name}"')
            tmp_file.unlink(missing_ok=True)

    if verbose:
        print(f'\nProcessing file: "{filename}"')
    try:
        if not is_dxf_file(filename):
            print(
                f'CANCELED: "{filename}" is not a DXF file, binary DXF files '
                f"are not supported")
            return
    except IOError as e:
        print(f"IOError: {str(e)}")
        return
    source_file = Path(filename)
    tmp_file = source_file.with_suffix(".ezdxf.tmp")
    error = False
    tagwriter: TagWriter
    if verbose:
        print(f'make a temporary copy: "{tmp_file.name}"')
    with open(tmp_file, "wb") as fp, open(source_file, "rb") as infile:
        if thumbnail:
            tagwriter = ThumbnailRemover(fp)
        else:
            tagwriter = TagWriter(fp)
        try:
            removed_tags = strip_comments(infile, tagwriter, verbose)
        except IOError as e:
            print(f"IOError: {str(e)}")
            error = True
        except DXFStructureError as e:
            print(str(e))
            error = True

    if not error:
        rename = False
        if thumbnail and tagwriter.removed_thumbnail_image:  # type: ignore
            print(f'"{source_file.name}" - removed THUMBNAILIMAGE section')
            rename = True

        if removed_tags > 0:
            tags = "tag" if removed_tags == 1 else "tags"
            print(
                f'"{source_file.name}" - {removed_tags} comment {tags} removed'
            )
            rename = True

        if rename:
            safe_rename(tmp_file, source_file, backup, verbose)

    remove_tmp_file()
コード例 #11
0
ファイル: __main__.py プロジェクト: shangulaike/ezdxf
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument(
        'files',
        metavar='FILE',
        nargs='+',
        help='DXF files pretty print',
    )
    parser.add_argument(
        '-o',
        '--open',
        action='store_true',
        help='open generated HTML file with the default web browser',
    )
    parser.add_argument(
        '-r',
        '--raw',
        action='store_true',
        help='raw mode - just print tags, no DXF structure interpretation',
    )
    parser.add_argument(
        '-x',
        '--nocompile',
        action='store_true',
        help=
        "don't compile points coordinates into single tags (only in raw mode)",
    )
    parser.add_argument(
        '-l',
        '--legacy',
        action='store_true',
        help="legacy mode - reorders DXF point coordinates",
    )
    args = parser.parse_args(sys.argv[1:])

    options.compress_binary_data = True
    options.check_entity_tag_structures = False
    for filename in args.files:
        if not Path(filename).exists():
            print("File '{}' not found.".format(filename))
            continue
        if not is_dxf_file(filename):
            print("File '{}' is not a DXF file.".format(filename))
            continue

        if args.raw:
            html_path = raw_pretty_print(Path(filename), args.nocompile,
                                         args.legacy)
        else:
            html_path = pretty_print(
                Path(filename))  # legacy mode is always used

        print("dxfpp created '{}'".format(html_path))
        if args.open:
            webbrowser.open(html_path)
コード例 #12
0
def get_tag_loader(filename: Union[str, Path],
                   errors: str = "ignore") -> Iterable[DXFTag]:

    filename = str(filename)
    if not is_dxf_file(filename):
        raise IOError(f"File '{filename}' is not an ASCII DXF file.")

    info = dxf_file_info(filename)
    with open(filename, mode="rt", encoding=info.encoding,
              errors=errors) as fp:  # type: ignore
        return list(ascii_tags_loader(fp, skip_comments=True))  # type: ignore
コード例 #13
0
ファイル: __main__.py プロジェクト: suffrajet/ezdxf
def readfile(filename: str, legacy_mode: bool = False, compile_tags=True) -> Iterable[DXFTag]:
    from ezdxf.lldxf.validator import is_dxf_file

    if not is_dxf_file(filename):
        raise IOError("File '{}' is not a DXF file.".format(filename))

    info = dxf_file_info(filename)
    fp = open(filename, mode='rt', encoding=info.encoding, errors='ignore')
    tagger = low_level_tagger(fp)
    if legacy_mode:
        tagger = tag_reorder_layer(tagger)
    if compile_tags:
        tagger = tag_compiler(tagger)
    return tagger
コード例 #14
0
def from_file(filename: str, codes: Set[int] = None) -> Iterable['DXFTag']:
    """
    Yields comment tags from file `filename` as :class:`~ezdxf.lldxf.types.DXFTag` objects.

    Args:
        filename: filename as string
        codes: yields also additional tags with specified group codes e.g. {5, 0} to also yield handle and
               structure tags

    """
    if is_dxf_file(filename):
        info = dxf_file_info(filename)
        with open(filename, mode='rt', encoding=info.encoding) as fp:
            yield from from_stream(fp, codes=codes)
    else:
        raise IOError('File "{}" is not a DXF file.'.format(filename))
コード例 #15
0
ファイル: odafc.py プロジェクト: Rahulghuge94/ezdxf
def _detect_version(path: str) -> str:
    version = "ACAD2018"
    ext = os.path.splitext(path)[1].lower()
    if ext == ".dxf":
        if is_binary_dxf_file(path):
            pass
        elif is_dxf_file(path):
            with open(path, "rt") as fp:
                info = dxf_info(fp)
                version = VERSION_MAP[info.version]
    elif ext == ".dwg":
        version = dwg_version(path)  # type: ignore
        if version is None:
            raise ValueError("Unknown or unsupported DWG version.")
    else:
        raise ValueError(f"Unsupported file format: '{ext}'")

    return map_version(version)
コード例 #16
0
def _detect_version(path: str) -> str:
    version = 'ACAD2018'
    ext = os.path.splitext(path)[1].lower()
    if ext == '.dxf':
        if is_binary_dxf_file(path):
            pass
        elif is_dxf_file(path):
            with open(path, 'rt') as fp:
                info = dxf_info(fp)
                version = VERSION_MAP[info.version]
    elif ext == '.dwg':
        version = dwg_version(path)
        if version is None:
            raise ValueError('Unknown or unsupported DWG version.')
    else:
        raise ValueError(f"Unsupported file format: '{ext}'")

    return map_version(version)
コード例 #17
0
def readfile(filename: str,
             encoding: str = None,
             legacy_mode: bool = False) -> 'Drawing':
    """  Read the DXF document `filename` from the file-system.

    This is the preferred method to load existing ASCII or Binary DXF files,
    the required text encoding will be detected automatically and decoding
    errors will be ignored.

    Override encoding detection by setting argument `encoding` to the
    estimated encoding. (use Python encoding names like in the :func:`open`
    function).

    If this function struggles to load the DXF document and raises a
    :class:`DXFStructureError` exception, try the :func:`ezdxf.recover.readfile`
    function to load this corrupt DXF document.

    Args:
        filename: filename of the ASCII- or Binary DXF document
        encoding: use ``None`` for auto detect (default), or set a specific
            encoding like "utf-8", argument is ignored for Binary DXF files
        legacy_mode: adds an extra trouble shooting import layer if ``True``
            (deprecated)

    Raises:
        IOError: File `filename` is not a DXF file or does not exist.
        DXFStructureError: for invalid DXF structure

    .. deprecated:: v0.14

        argument `legacy_mode`, use module :mod:`ezdxf.recover`
        to load DXF documents with structural flaws.

    """
    from ezdxf.lldxf.validator import is_dxf_file, is_binary_dxf_file
    from ezdxf.tools.codepage import is_supported_encoding
    from ezdxf.lldxf.tagger import binary_tags_loader
    if legacy_mode:
        warnings.warn(
            '"legacy_mode" is deprecated (removed in v0.16), replace call by '
            'ezdxf.recover.read().', DeprecationWarning)

    filename = str(filename)
    if is_binary_dxf_file(filename):
        with open(filename, 'rb') as fp:
            data = fp.read()
            loader = binary_tags_loader(data)
            return Drawing.load(loader, legacy_mode)

    if not is_dxf_file(filename):
        raise IOError("File '{}' is not a DXF file.".format(filename))

    info = dxf_file_info(filename)
    if encoding is not None:
        # override default encodings if absolute necessary
        info.encoding = encoding
    with open(filename, mode='rt', encoding=info.encoding,
              errors='ignore') as fp:
        doc = read(fp, legacy_mode=legacy_mode)

    doc.filename = filename
    if encoding is not None and is_supported_encoding(encoding):
        # store overridden encoding if supported by AutoCAD, else default
        # encoding stored in $DWGENCODING is used as document encoding or
        # 'cp1252' if $DWGENCODING is unset.
        doc.encoding = encoding
    return doc
コード例 #18
0
ファイル: commands.py プロジェクト: Rahulghuge94/ezdxf
    def run(args):
        def build_outname(name: str) -> str:
            p = Path(name)
            return str(p.parent / (p.stem + ".rec.dxf"))

        def log_fixes(auditor):
            for error in auditor.fixes:
                logger.info("fixed:" + error.message)

        def log_errors(auditor):
            for error in auditor.errors:
                logger.error(error.message)

        def _audit(filename: str) -> None:
            msg = f"auditing file: {filename}"
            print(msg)
            logger.info(msg)
            try:
                doc, auditor = recover.readfile(filename)
            except IOError:
                msg = "Not a DXF file or a generic I/O error."
                print(msg)
                logger.error(msg)
                return  # keep on processing additional files
            except const.DXFStructureError:
                msg = "Invalid or corrupted DXF file."
                print(msg)
                logger.error(msg)
                return  # keep on processing additional files

            if auditor.has_errors:
                auditor.print_error_report()
                log_errors(auditor)
            if auditor.has_fixes:
                auditor.print_fixed_errors()
                log_fixes(auditor)

            if auditor.has_errors is False and auditor.has_fixes is False:
                print("No errors found.")
            else:
                print(
                    f"Found {len(auditor.errors)} errors, "
                    f"applied {len(auditor.fixes)} fixes"
                )

            if args.save:
                outname = build_outname(filename)
                doc.saveas(outname)
                print(f"Saved recovered file as: {outname}")

        for pattern in args.files:
            names = list(glob.glob(pattern))
            if len(names) == 0:
                msg = f"File(s) '{pattern}' not found."
                print(msg)
                logger.error(msg)
                continue
            for filename in names:
                if not os.path.exists(filename):
                    msg = f"File '{filename}' not found."
                    print(msg)
                    logger.error(msg)
                    continue
                if not is_dxf_file(filename):
                    msg = f"File '{filename}' is not a DXF file."
                    print(msg)
                    logger.error(msg)
                    continue
                _audit(filename)
コード例 #19
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument(
        'files',
        metavar='FILE',
        nargs='+',
        help='DXF files pretty print',
    )
    parser.add_argument(
        '-o',
        '--open',
        action='store_true',
        help='open generated HTML file with the default web browser',
    )
    parser.add_argument(
        '-r',
        '--raw',
        action='store_true',
        help='raw mode - just print tags, no DXF structure interpretation',
    )
    parser.add_argument(
        '-x',
        '--nocompile',
        action='store_true',
        help="don't compile points coordinates into single tags "
        "(only in raw mode)",
    )
    parser.add_argument(
        '-l',
        '--legacy',
        action='store_true',
        help="legacy mode - reorders DXF point coordinates",
    )
    parser.add_argument(
        '-s',
        '--sections',
        action='store',
        default='hctbeo',
        help="choose sections to include and their order, h=HEADER, c=CLASSES, "
        "t=TABLES, b=BLOCKS, e=ENTITIES, o=OBJECTS",
    )
    args = parser.parse_args(sys.argv[1:])

    options.compress_binary_data = True
    for filename in args.files:
        if not Path(filename).exists():
            print(f"File '{filename}' not found.")
            continue

        if is_binary_dxf_file(filename):
            binary_dxf = True
        else:
            binary_dxf = False
            if not is_dxf_file(filename):
                print(f"File '{filename}' is not a DXF file.")
                continue

        if args.raw:
            html_path = raw_pretty_print(Path(filename),
                                         compile_tags=not args.nocompile,
                                         legacy_mode=args.legacy,
                                         is_binary_dxf=binary_dxf)
        else:
            html_path = pretty_print(
                Path(filename),
                is_binary_dxf=binary_dxf)  # legacy mode is always used

        print(f"dxfpp created '{html_path}'")
        if args.open:
            webbrowser.open(str(html_path))
コード例 #20
0
ファイル: filemanagement.py プロジェクト: yanbin-ha/ezdxf
def readfile(filename: Union[str, 'Path'],
             encoding: str = None,
             errors: str = 'surrogateescape') -> 'Drawing':
    """  Read the DXF document `filename` from the file-system.

    This is the preferred method to load existing ASCII or Binary DXF files,
    the required text encoding will be detected automatically and decoding
    errors will be ignored.

    Override encoding detection by setting argument `encoding` to the
    estimated encoding. (use Python encoding names like in the :func:`open`
    function).

    If this function struggles to load the DXF document and raises a
    :class:`DXFStructureError` exception, try the :func:`ezdxf.recover.readfile`
    function to load this corrupt DXF document.

    Args:
        filename: filename of the ASCII- or Binary DXF document
        encoding: use ``None`` for auto detect (default), or set a specific
            encoding like "utf-8", argument is ignored for Binary DXF files
        errors: specify decoding error handler

            - "surrogateescape" to preserve possible binary data (default)
            - "ignore" to use the replacement char U+FFFD "\ufffd" for invalid data
            - "strict" to raise an :class:`UnicodeDecodeError` exception for invalid data

    Raises:
        IOError: not a DXF file or file does not exist
        DXFStructureError: for invalid or corrupted DXF structures
        UnicodeDecodeError: if `errors` is "strict" and a decoding error occurs

    .. deprecated:: v0.14

        argument `legacy_mode`, use module :mod:`ezdxf.recover`
        to load DXF documents with structural flaws.

    """
    from ezdxf.lldxf.validator import is_dxf_file, is_binary_dxf_file
    from ezdxf.tools.codepage import is_supported_encoding
    from ezdxf.lldxf.tagger import binary_tags_loader

    filename = str(filename)
    if is_binary_dxf_file(filename):
        with open(filename, 'rb') as fp:
            data = fp.read()
            loader = binary_tags_loader(data, errors=errors)
            return Drawing.load(loader)

    if not is_dxf_file(filename):
        raise IOError(f"File '{filename}' is not a DXF file.")

    info = dxf_file_info(filename)
    if encoding is not None:
        # override default encodings if absolute necessary
        info.encoding = encoding
    with open(filename, mode='rt', encoding=info.encoding,
              errors=errors) as fp:
        doc = read(fp)

    doc.filename = filename
    if encoding is not None and is_supported_encoding(encoding):
        # store overridden encoding if supported by AutoCAD, else default
        # encoding stored in $DWGENCODING is used as document encoding or
        # 'cp1252' if $DWGENCODING is unset.
        doc.encoding = encoding
    return doc