-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplot_strokes.py
More file actions
287 lines (239 loc) · 8.75 KB
/
Copy pathplot_strokes.py
File metadata and controls
287 lines (239 loc) · 8.75 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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
#!/usr/bin/env python3
"""
Generate SVG visualization of extracted strokes from Samsung Notes .sdocx files.
Usage:
python3 plot_strokes.py [options] [sdocx_file...]
Options:
--all Process all .sdocx files in sdocxFiles/ directory
--output-dir Output directory for generated files (default: current dir)
--no-bbox Don't draw bounding boxes
--stroke-width Stroke width in pixels (default: 2)
Examples:
python3 plot_strokes.py # Process default test file
python3 plot_strokes.py --all # Process all files in sdocxFiles/
python3 plot_strokes.py file1.sdocx file2.sdocx # Process specific files
python3 plot_strokes.py --output-dir=output/ --all # Output to specific directory
"""
import json
import subprocess
import sys
import os
import argparse
from pathlib import Path
from typing import Optional
def extract_strokes(sdocx_path: str) -> Optional[dict]:
"""Run sdocx_extractor.py and return parsed JSON."""
script_dir = os.path.dirname(os.path.abspath(__file__)) or "."
result = subprocess.run(
["python3", os.path.join(script_dir, "sdocx_extractor.py"), sdocx_path],
capture_output=True,
text=True,
)
if result.returncode != 0:
print(f"Error extracting {sdocx_path}: {result.stderr}", file=sys.stderr)
return None
return json.loads(result.stdout)
def iter_objects(objects: list):
"""Recursively iterate through objects including container children."""
for obj in objects:
yield obj
if obj.get("children"):
yield from iter_objects(obj["children"])
def generate_svg(
data: Optional[dict],
output_path: str,
show_bbox: bool = True,
stroke_width: float = 2.0,
stroke_color: Optional[str] = None,
) -> bool:
"""Generate SVG from extracted stroke data. Returns True on success."""
if not data or not data.get("pages"):
print("Error: No pages found in SDOCX file", file=sys.stderr)
return False
page = data["pages"][0]
width = page["width"]
height = page["height"]
title = data.get("metadata", {}).get("title", "Untitled")
svg_lines = [
'<?xml version="1.0" encoding="UTF-8"?>',
f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {width} {height}" '
f'width="{width}" height="{height}">',
f" <!-- Title: {title} -->",
f" <!-- Generated from Samsung Notes .sdocx file -->",
' <rect fill="white" width="100%" height="100%"/>',
]
# Use single color if specified, otherwise cycle through palette
colors = (
["#222222"]
if stroke_color
else [
"#0066cc",
"#cc0066",
"#00cc66",
"#cc6600",
"#6600cc",
"#00cccc",
"#336699",
"#993366",
"#669933",
"#996633",
"#663399",
"#339999",
]
)
stroke_idx = 0
for layer in page["layers"]:
for obj in iter_objects(layer["objects"]):
if obj["object_type"] in [1, 15] and obj.get("stroke_points"):
points = obj["stroke_points"]
color = stroke_color or colors[stroke_idx % len(colors)]
# Create path from points
if len(points) >= 2:
path_data = f"M {points[0][0]:.2f},{points[0][1]:.2f}"
for p in points[1:]:
path_data += f" L {p[0]:.2f},{p[1]:.2f}"
svg_lines.append(
f' <path d="{path_data}" fill="none" stroke="{color}" '
f'stroke-width="{stroke_width}" stroke-linecap="round" '
f'stroke-linejoin="round"/>'
)
# Add bounding box overlay (dashed)
if show_bbox:
bbox = obj["bounding_rect"]
bw = bbox["right"] - bbox["left"]
bh = bbox["bottom"] - bbox["top"]
svg_lines.append(
f' <rect x="{bbox["left"]:.2f}" y="{bbox["top"]:.2f}" '
f'width="{bw:.2f}" height="{bh:.2f}" '
f'fill="none" stroke="{color}" stroke-width="0.5" '
f'stroke-dasharray="4" opacity="0.3"/>'
)
stroke_idx += 1
svg_lines.append("</svg>")
# Ensure output directory exists
output_dir = os.path.dirname(output_path)
if output_dir:
os.makedirs(output_dir, exist_ok=True)
with open(output_path, "w") as f:
f.write("\n".join(svg_lines))
return True
def get_output_path(input_path: str, output_dir: str, extension: str) -> str:
"""Generate output path based on input filename."""
base_name = Path(input_path).stem
# Sanitize filename
safe_name = "".join(c if c.isalnum() or c in "._- " else "_" for c in base_name)
return os.path.join(output_dir, f"{safe_name}{extension}")
def process_file(
sdocx_path: str,
output_dir: str,
show_bbox: bool = True,
stroke_width: float = 2.0,
) -> bool:
"""Process a single SDOCX file and generate SVG."""
print(f"\nProcessing: {sdocx_path}")
data = extract_strokes(sdocx_path)
if not data:
return False
title = data.get("metadata", {}).get("title", "Untitled")
stroke_count = data.get("summary", {}).get("stroke_count", 0)
page = data["pages"][0] if data.get("pages") else None
if not page:
print(f" Error: No pages found", file=sys.stderr)
return False
print(f" Title: {title}")
print(f" Size: {page['width']} x {page['height']}")
print(f" Strokes: {stroke_count}")
# Generate SVG
svg_path = get_output_path(sdocx_path, output_dir, ".svg")
if generate_svg(data, svg_path, show_bbox=show_bbox, stroke_width=stroke_width):
print(f" SVG: {svg_path}")
return True
return False
def find_sdocx_files(directory: str) -> list:
"""Find all .sdocx files in directory."""
files = []
for f in os.listdir(directory):
if f.endswith(".sdocx"):
files.append(os.path.join(directory, f))
return sorted(files)
def main():
parser = argparse.ArgumentParser(
description="Generate SVG visualizations from Samsung Notes .sdocx files"
)
parser.add_argument(
"files",
nargs="*",
help="SDOCX files to process",
)
parser.add_argument(
"--all",
action="store_true",
help="Process all .sdocx files in sdocxFiles/ directory",
)
parser.add_argument(
"--output-dir",
default=".",
help="Output directory for generated files (default: current directory)",
)
parser.add_argument(
"--no-bbox",
action="store_true",
help="Don't draw bounding boxes",
)
parser.add_argument(
"--stroke-width",
type=float,
default=2.0,
help="Stroke width in pixels (default: 2)",
)
args = parser.parse_args()
# Determine which files to process
files_to_process = []
if args.all:
sdocx_dir = os.path.join(os.path.dirname(__file__) or ".", "sdocxFiles")
if os.path.isdir(sdocx_dir):
files_to_process = find_sdocx_files(sdocx_dir)
else:
print(f"Error: Directory not found: {sdocx_dir}", file=sys.stderr)
sys.exit(1)
elif args.files:
files_to_process = args.files
else:
# Default: process the test file
default_file = os.path.join(
os.path.dirname(__file__) or ".",
"sdocxFiles",
"ThisIsTheTitle_251009_042302.sdocx",
)
if os.path.exists(default_file):
files_to_process = [default_file]
else:
print(
"Error: No files specified and default file not found", file=sys.stderr
)
print("Usage: python3 plot_strokes.py [--all] [file1.sdocx ...]")
sys.exit(1)
if not files_to_process:
print("No .sdocx files found to process", file=sys.stderr)
sys.exit(1)
print(f"Processing {len(files_to_process)} file(s)...")
# Process each file
success_count = 0
for sdocx_path in files_to_process:
if not os.path.exists(sdocx_path):
print(f"Error: File not found: {sdocx_path}", file=sys.stderr)
continue
if process_file(
sdocx_path,
args.output_dir,
show_bbox=not args.no_bbox,
stroke_width=args.stroke_width,
):
success_count += 1
print(
f"\nCompleted: {success_count}/{len(files_to_process)} files processed successfully"
)
if success_count == 0:
sys.exit(1)
if __name__ == "__main__":
main()