(model, file_path: Path, out_format: str)
| 18 | |
| 19 | |
| 20 | def _process_file(model, file_path: Path, out_format: str) -> None: |
| 21 | if out_format not in ["txt", "json", "xml"]: |
| 22 | raise ValueError(f"Unsupported output format: {out_format}") |
| 23 | |
| 24 | if os.path.splitext(file_path)[1] in IMAGE_FILE_EXTENSIONS: |
| 25 | doc = DocumentFile.from_images([file_path]) |
| 26 | elif os.path.splitext(file_path)[1] in OTHER_EXTENSIONS: |
| 27 | doc = DocumentFile.from_pdf(file_path) |
| 28 | else: |
| 29 | print(f"Skip unsupported file type: {file_path}") |
| 30 | |
| 31 | out = model(doc) |
| 32 | |
| 33 | if out_format == "json": |
| 34 | output = json.dumps(out.export(), indent=2) |
| 35 | elif out_format == "txt": |
| 36 | output = out.render() |
| 37 | elif out_format == "xml": |
| 38 | output = out.export_as_xml() |
| 39 | |
| 40 | path = Path("output").joinpath(file_path.stem + "." + out_format) |
| 41 | if out_format == "xml": |
| 42 | for i, (xml_bytes, xml_tree) in enumerate(output): |
| 43 | path = Path("output").joinpath(file_path.stem + f"_{i}." + out_format) |
| 44 | xml_tree.write(path, encoding="utf-8", xml_declaration=True) |
| 45 | else: |
| 46 | with open(path, "w") as f: |
| 47 | f.write(output) |
| 48 | |
| 49 | |
| 50 | def main(args): |
no test coverage detected