-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathextract.py
More file actions
145 lines (121 loc) · 4.3 KB
/
Copy pathextract.py
File metadata and controls
145 lines (121 loc) · 4.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
#!/usr/bin/env python3
"""CLI entry point — extract Excel workbooks to JSON (Phase 1)."""
from __future__ import annotations
import argparse
import json
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
if str(ROOT) not in sys.path:
sys.path.insert(0, str(ROOT))
from src.workbook_extract import ( # noqa: E402
EXCEL_EXTENSIONS,
LEGACY_XLS_EXTENSIONS,
XLS_CONVERSION_MESSAGE,
extract_workbook,
)
def _default_output_path(input_path: Path, output: Path | None) -> Path:
if output is not None:
return output
return (
input_path.with_suffix(".json").name
if input_path.is_file()
else Path("extraction_report.json")
)
def _process_file(file_path: Path, output: Path | None) -> dict:
print(f"Extracting {file_path}...")
report = extract_workbook(file_path)
out_path = _default_output_path(file_path, output)
if file_path.is_file() and output is None:
out_path = Path("extractions") / f"{file_path.stem}_extraction.json"
if out_path.exists() and out_path.is_dir():
raise IsADirectoryError(
f"Output path is a directory, not a file: {out_path}. "
"Example: -o extractions/mon_fichier_extraction.json"
)
out_path.parent.mkdir(parents=True, exist_ok=True)
out_path.write_text(
json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8"
)
stats = report["statistics"]
print(f" -> {out_path}")
print(
f" {stats['sheets']} sheet(s), {stats['formulas']} formula(s), "
f"{stats.get('static_cells', 0)} static cell(s), "
f"{stats.get('label_hints', 0)} label hint(s), "
f"{stats['comments']} comment(s), {stats['controls']} control(s), "
f"{stats['vba_modules']} VBA module(s), {stats['vba_procedures']} procedure(s)"
)
for warning in report["warnings"]:
print(f" [!] {warning}")
return report
def _collect_excel_files(path: Path) -> list[Path]:
if path.is_file():
return [path]
return sorted(
p for p in path.iterdir()
if p.is_file() and p.suffix.lower() in EXCEL_EXTENSIONS
)
def main() -> int:
parser = argparse.ArgumentParser(
description="Extract formulas and VBA macros from an Excel file to JSON."
)
parser.add_argument(
"path",
type=Path,
help="Excel file or directory containing Excel files",
)
parser.add_argument(
"-o",
"--output",
type=Path,
default=None,
help="Output JSON file (single input file only)",
)
parser.add_argument(
"--output-dir",
type=Path,
default=Path("extractions"),
help="Output directory in batch mode (default: extractions/)",
)
args = parser.parse_args()
if not args.path.exists():
print(f"Error: path not found — {args.path}", file=sys.stderr)
return 1
files = _collect_excel_files(args.path)
if not files:
if args.path.is_dir():
legacy = sorted(
p for p in args.path.iterdir()
if p.is_file() and p.suffix.lower() in LEGACY_XLS_EXTENSIONS
)
if legacy:
print(
"Error: .xls files found but not supported.", file=sys.stderr
)
print(XLS_CONVERSION_MESSAGE.format(suffix=".xls"), file=sys.stderr)
for f in legacy:
print(f" - {f.name}", file=sys.stderr)
return 1
print(f"Error: no Excel files found in {args.path}", file=sys.stderr)
print(
"Supported formats: .xlsx, .xlsm (convert .xls to .xlsx first).",
file=sys.stderr,
)
return 1
errors = 0
for file_path in files:
try:
if args.path.is_dir():
out = args.output_dir / f"{file_path.stem}_extraction.json"
_process_file(file_path, out)
else:
_process_file(file_path, args.output)
except Exception as exc:
errors += 1
print(f"Error processing {file_path}: {exc}", file=sys.stderr)
if len(files) > 1:
print(f"\n{len(files) - errors}/{len(files)} file(s) extracted.")
return 1 if errors else 0
if __name__ == "__main__":
raise SystemExit(main())