| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
from collections.abc import Callable, Iterator |
| 4 |
from datetime import datetime |
| 5 |
from pathlib import Path |
| 6 |
from re import split |
| 7 |
from typing import Any |
| 8 |
|
| 9 |
|
| 10 |
date_formats = ( |
| 11 |
|
| 12 |
"%d/%m/%Y", |
| 13 |
"%m/%d/%Y", |
| 14 |
"%Y/%m/%d", |
| 15 |
"%d.%m.%Y", |
| 16 |
"%d-%m-%Y", |
| 17 |
"%m-%d-%Y", |
| 18 |
"%Y-%m-%d", |
| 19 |
"%d/%m/%y", |
| 20 |
"%m/%d/%y", |
| 21 |
"%y/%m/%d", |
| 22 |
"%d,%m,%Y", |
| 23 |
"%m,%d,%Y", |
| 24 |
"%Y,%m,%d", |
| 25 |
"%d %m %Y", |
| 26 |
"%m %d %Y", |
| 27 |
"%Y %d %m", |
| 28 |
|
| 29 |
"%d %b %Y", |
| 30 |
"%b %d, %Y", |
| 31 |
"%d %B %Y", |
| 32 |
"%B %d, %Y", |
| 33 |
|
| 34 |
"%Y-%m-%dT%H:%M:%S", |
| 35 |
"%Y-%m-%d", |
| 36 |
|
| 37 |
e date |
| 38 |
"%Y%m%d", |
| 39 |
"%y%m%d", |
| 40 |
"%d%m%Y", |
| 41 |
|
| 42 |
"%d/%m/%y %H:%M", |
| 43 |
"%m/%d/%y %H:%M", |
| 44 |
"%Y-%m-%d %H:%M:%S", |
| 45 |
) |
| 46 |
|
| 47 |
|
| 48 |
def _string_fallback(item: str) -> tuple[int, ...]: |
| 49 |
""" |
| 50 |
In order to have reasonable file path sorting: |
| 51 |
- Split by path separators |
| 52 |
- Determine depth, more separators more depth |
| 53 |
- Deal with every dir by splitting by digits |
| 54 |
- Deal with file name by splitting by digits |
| 55 |
""" |
| 56 |
components = split(r"[/\\]", item) |
| 57 |
if components[-1]: |
| 58 |
return ( |
| 59 |
5, |
| 60 |
len(components), |
| 61 |
tuple(int(e) if e.isdigit() else e.lower() for comp in components[:-1] for e in split(r"(\d+)", comp) if e), |
| 62 |
tuple(int(e) if e.isdigit() else e.lower() for e in split(r"(\d+)", components[-1])), |
| 63 |
) |
| 64 |
else: |
| 65 |
return ( |
| 66 |
5, |
| 67 |
len(components), |
| 68 |
tuple(int(e) if e.isdigit() else e.lower() for comp in components[:-1] for e in split(r"(\d+)", comp) if e), |
| 69 |
(), |
| 70 |
) |
| 71 |
|
| 72 |
|
| 73 |
def version_sort_key(item: Any) -> tuple[int, ...]: |
| 74 |
""" |
| 75 |
A key for natural sorting of various Python types. |
| 76 |
|
| 77 |
- Won't convert strings to floats |
| 78 |
- Will sort string version numbers |
| 79 |
|
| 80 |
0. None |
| 81 |
1. Empty strings |
| 82 |
2. bool |
| 83 |
3. int, float |
| 84 |
4. datetime (inc. strings that are dates) |
| 85 |
5. strings (including string file paths and paths as POSIX strings) & unknown objects with __str__ |
| 86 |
6. unknown objects |
| 87 |
""" |
| 88 |
if isinstance(item, str): |
| 89 |
if item: |
| 90 |
for date_format in date_formats: |
| 91 |
try: |
| 92 |
return (4, datetime.strptime(item, date_format).timestamp()) |
| 93 |
except ValueError: |
| 94 |
continue |
| 95 |
|
| 96 |
components = split(r"[/\\]", item) |
| 97 |
if components[-1]: |
| 98 |
return ( |
| 99 |
5, |
| 100 |
len(components), |
| 101 |
tuple( |
| 102 |
int(e) if e.isdigit() else e.lower() |
| 103 |
for comp in components[:-1] |
| 104 |
for e in split(r"(\d+)", comp) |
| 105 |
if e |
| 106 |
), |
| 107 |
tuple(int(e) if e.isdigit() else e.lower() for e in split(r"(\d+)", components[-1])), |
| 108 |
) |
| 109 |
else: |
| 110 |
return ( |
| 111 |
5, |
| 112 |
len(components), |
| 113 |
tuple( |
| 114 |
int(e) if e.isdigit() else e.lower() |
| 115 |
for comp in components[:-1] |
| 116 |
for e in split(r"(\d+)", comp) |
| 117 |
if e |
| 118 |
), |
| 119 |
(), |
| 120 |
) |
| 121 |
else: |
| 122 |
return (1, item) |
| 123 |
|
| 124 |
elif item is None: |
| 125 |
return (0,) |
| 126 |
|
| 127 |
elif isinstance(item, bool): |
| 128 |
return (2, item) |
| 129 |
|
| 130 |
elif isinstance(item, (int, float)): |
| 131 |
return (3, item) |
| 132 |
|
| 133 |
elif isinstance(item, datetime): |
| 134 |
return (4, item.timestamp()) |
| 135 |
|
| 136 |
elif isinstance(item, Path): |
| 137 |
return _string_fallback(item.as_posix()) |
| 138 |
|
| 139 |
else: |
| 140 |
try: |
| 141 |
return _string_fallback(f"{item}") |
| 142 |
except Exception: |
| 143 |
return (6, item) |
| 144 |
|
| 145 |
|
| 146 |
def natural_sort_key(item: Any) -> tuple[int, ...]: |
| 147 |
""" |
| 148 |
A key for natural sorting of various Python types. |
| 149 |
|
| 150 |
- Won't sort string version numbers |
| 151 |
- Will convert strings to floats |
| 152 |
- Will sort strings that are file paths |
| 153 |
|
| 154 |
0. None |
| 155 |
1. Empty strings |
| 156 |
2. bool |
| 157 |
3. int, float (inc. strings that are numbers) |
| 158 |
4. datetime (inc. strings that are dates) |
| 159 |
5. strings (including string file paths and paths as POSIX strings) & unknown objects with __str__ |
| 160 |
6. unknown objects |
| 161 |
""" |
| 162 |
if isinstance(item, str): |
| 163 |
if item: |
| 164 |
for date_format in date_formats: |
| 165 |
try: |
| 166 |
return (4, datetime.strptime(item, date_format).timestamp()) |
| 167 |
except ValueError: |
| 168 |
continue |
| 169 |
|
| 170 |
try: |
| 171 |
return (3, float(item)) |
| 172 |
except ValueError: |
| 173 |
|
| 174 |
components = split(r"[/\\]", item) |
| 175 |
if components[-1]: |
| 176 |
return ( |
| 177 |
5, |
| 178 |
len(components), |
| 179 |
tuple( |
| 180 |
int(e) if e.isdigit() else e.lower() |
| 181 |
for comp in components[:-1] |
| 182 |
for e in split(r"(\d+)", comp) |
| 183 |
if e |
| 184 |
), |
| 185 |
tuple(int(e) if e.isdigit() else e.lower() for e in split(r"(\d+)", components[-1])), |
| 186 |
) |
| 187 |
else: |
| 188 |
return ( |
| 189 |
5, |
| 190 |
len(components), |
| 191 |
tuple( |
| 192 |
int(e) if e.isdigit() else e.lower() |
| 193 |
for comp in components[:-1] |
| 194 |
for e in split(r"(\d+)", comp) |
| 195 |
if e |
| 196 |
), |
| 197 |
(), |
| 198 |
) |
| 199 |
else: |
| 200 |
return (1, item) |
| 201 |
|
| 202 |
elif item is None: |
| 203 |
return (0,) |
| 204 |
|
| 205 |
elif isinstance(item, bool): |
| 206 |
return (2, item) |
| 207 |
|
| 208 |
elif isinstance(item, (int, float)): |
| 209 |
return (3, item) |
| 210 |
|
| 211 |
elif isinstance(item, datetime): |
| 212 |
return (4, item.timestamp()) |
| 213 |
|
| 214 |
elif isinstance(item, Path): |
| 215 |
return _string_fallback(item.as_posix()) |
| 216 |
|
| 217 |
else: |
| 218 |
try: |
| 219 |
return _string_fallback(f"{item}") |
| 220 |
except Exception: |
| 221 |
return (6, item) |
| 222 |
|
| 223 |
|
| 224 |
def fast_sort_key(item: Any) -> tuple[int, ...]: |
| 225 |
""" |
| 226 |
A faster key for natural sorting of various Python types. |
| 227 |
|
| 228 |
- Won't sort strings that are dates very well |
| 229 |
- Won't convert strings to floats |
| 230 |
- Won't sort string file paths very well |
| 231 |
- Will do ok with string version numbers |
| 232 |
|
| 233 |
0. None |
| 234 |
1. Empty strings |
| 235 |
2. bool |
| 236 |
3. int, float |
| 237 |
4. datetime |
| 238 |
5. strings (including paths as POSIX strings) & unknown objects with __str__ |
| 239 |
6. unknown objects |
| 240 |
""" |
| 241 |
if isinstance(item, str): |
| 242 |
if item: |
| 243 |
return (5, tuple(int(e) if e.isdigit() else e.lower() for e in split(r"(\d+)", item))) |
| 244 |
else: |
| 245 |
return (1, item) |
| 246 |
|
| 247 |
elif item is None: |
| 248 |
return (0,) |
| 249 |
|
| 250 |
elif isinstance(item, bool): |
| 251 |
return (2, item) |
| 252 |
|
| 253 |
elif isinstance(item, (int, float)): |
| 254 |
return (3, item) |
| 255 |
|
| 256 |
elif isinstance(item, datetime): |
| 257 |
return (4, item.timestamp()) |
| 258 |
|
| 259 |
elif isinstance(item, Path): |
| 260 |
return _string_fallback(item.as_posix()) |
| 261 |
|
| 262 |
else: |
| 263 |
try: |
| 264 |
return _string_fallback(f"{item}") |
| 265 |
except Exception: |
| 266 |
return (6, item) |
| 267 |
|
| 268 |
|
| 269 |
def sort_selection( |
| 270 |
data: list[list[Any]], |
| 271 |
reverse: bool = False, |
| 272 |
key: Callable | None = None, |
| 273 |
row_wise: bool = False, |
| 274 |
) -> list[list[Any]]: |
| 275 |
if not data or not isinstance(data[0], list): |
| 276 |
raise ValueError("Data must be a list of lists.") |
| 277 |
|
| 278 |
if key is None: |
| 279 |
key = natural_sort_key |
| 280 |
|
| 281 |
if row_wise: |
| 282 |
return [sorted(row, key=key, reverse=reverse) for row in data] |
| 283 |
else: |
| 284 |
return list( |
| 285 |
zip( |
| 286 |
*( |
| 287 |
sorted( |
| 288 |
(row[col] for row in data), |
| 289 |
key=key, |
| 290 |
reverse=reverse, |
| 291 |
) |
| 292 |
for col in range(len(data[0])) |
| 293 |
) |
| 294 |
) |
| 295 |
) |
| 296 |
|
| 297 |
|
| 298 |
def sort_column( |
| 299 |
data: list[list[Any]] | list[Any] | Iterator[Any], |
| 300 |
column: int = 0, |
| 301 |
reverse: bool = False, |
| 302 |
key: Callable | None = None, |
| 303 |
) -> list[list[Any]] | list[Any]: |
| 304 |
if not data: |
| 305 |
return data |
| 306 |
|
| 307 |
if key is None: |
| 308 |
key = natural_sort_key |
| 309 |
|
| 310 |
if isinstance(data, list) and isinstance(data[0], list): |
| 311 |
return sorted(data, key=lambda row: key(row[column]) if len(row) > column else key(None), reverse=reverse) |
| 312 |
else: |
| 313 |
return sorted(data, reverse=reverse, key=key) |
| 314 |
|
| 315 |
|
| 316 |
def sort_row( |
| 317 |
data: list[list[Any]] | list[Any] | Iterator[Any], |
| 318 |
row: int = 0, |
| 319 |
reverse: bool = False, |
| 320 |
key: Callable | None = None, |
| 321 |
) -> list[list[Any]]: |
| 322 |
if not data: |
| 323 |
return data |
| 324 |
|
| 325 |
if key is None: |
| 326 |
key = natural_sort_key |
| 327 |
|
| 328 |
if isinstance(data, list) and isinstance(data[0], list): |
| 329 |
if 0 <= row < len(data): |
| 330 |
data[row] = sorted(data[row], key=key, reverse=reverse) |
| 331 |
return data |
| 332 |
else: |
| 333 |
raise IndexError(f"Row index {row} out of range for data with {len(data)} rows.") |
| 334 |
else: |
| 335 |
return sorted(data, reverse=reverse, key=key) |
| 336 |
|
| 337 |
|
| 338 |
def sort_rows_by_column( |
| 339 |
data: list[list[Any]], |
| 340 |
column: int = 0, |
| 341 |
reverse: bool = False, |
| 342 |
key: Callable | None = None, |
| 343 |
) -> tuple[list[tuple[int, list[Any]]], dict[int, int]]: |
| 344 |
if not data: |
| 345 |
return data, {} |
| 346 |
|
| 347 |
|
| 348 |
if not isinstance(data[0], list): |
| 349 |
raise ValueError("Data must be a list of lists for row sorting.") |
| 350 |
|
| 351 |
if key is None: |
| 352 |
key = natural_sort_key |
| 353 |
|
| 354 |
|
| 355 |
sorted_indexed_data = sorted( |
| 356 |
((i, row) for i, row in enumerate(data)), |
| 357 |
key=lambda item: key(item[1][column]) if len(item[1]) > column else key(None), |
| 358 |
reverse=reverse, |
| 359 |
) |
| 360 |
|
| 361 |
|
| 362 |
return sorted_indexed_data, {old: new for new, (old, _) in enumerate(sorted_indexed_data)} |
| 363 |
|
| 364 |
|
| 365 |
def sort_columns_by_row( |
| 366 |
data: list[list[Any]], |
| 367 |
row: int = 0, |
| 368 |
reverse: bool = False, |
| 369 |
key: Callable | None = None, |
| 370 |
) -> tuple[list[int], dict[int, int]]: |
| 371 |
if not data: |
| 372 |
return data, {} |
| 373 |
|
| 374 |
|
| 375 |
if not isinstance(data[0], list): |
| 376 |
raise ValueError("Data must be a list of lists for column sorting.") |
| 377 |
|
| 378 |
if row >= len(data) or row < 0: |
| 379 |
raise IndexError(f"Row index {row} out of range for data with {len(data)} rows.") |
| 380 |
|
| 381 |
if key is None: |
| 382 |
key = natural_sort_key |
| 383 |
|
| 384 |
|
| 385 |
sort_indices = sorted(range(len(data[row])), key=lambda i: key(data[row][i]), reverse=reverse) |
| 386 |
sort_indices_set = set(sort_indices) |
| 387 |
|
| 388 |
new_data = [] |
| 389 |
for row_data in data: |
| 390 |
|
| 391 |
sorted_part = [row_data[i] for i in sort_indices if i < len(row_data)] |
| 392 |
unsorted_part = [elem for idx, elem in enumerate(row_data) if idx not in sort_indices_set] |
| 393 |
new_data.append(sorted_part + unsorted_part) |
| 394 |
|
| 395 |
return sort_indices, dict(zip(range(len(data[row])), sort_indices)) |
| 396 |
|
| 397 |
|
| 398 |
def sort_tree_rows_by_column( |
| 399 |
data: list[list[Any]], |
| 400 |
column: int, |
| 401 |
index: list[Any], |
| 402 |
rns: dict[str, int], |
| 403 |
reverse: bool = False, |
| 404 |
key: Callable | None = None, |
| 405 |
) -> tuple[list[Any], dict[int, int]]: |
| 406 |
""" |
| 407 |
Sorts tree rows by a specified column in depth-first order, returning sorted nodes and a row mapping. |
| 408 |
|
| 409 |
Args: |
| 410 |
data: List of rows, where each row is a list of column values. |
| 411 |
column: Index of the column to sort by. |
| 412 |
index: List of nodes, where each node has 'iid', 'parent', and 'children' attributes. |
| 413 |
rns: Dictionary mapping item IDs (iid) to original row numbers in data. |
| 414 |
reverse: If True, sort in descending order; otherwise, ascending. |
| 415 |
key: Optional function to compute sort keys; defaults to natural_sort_key if None. |
| 416 |
|
| 417 |
Returns: |
| 418 |
Tuple containing: |
| 419 |
- List of nodes in sorted order. |
| 420 |
- Dictionary mapping original row numbers to new row numbers. |
| 421 |
""" |
| 422 |
if not index or not rns: |
| 423 |
return [], {} |
| 424 |
|
| 425 |
if key is None: |
| 426 |
key = natural_sort_key |
| 427 |
|
| 428 |
|
| 429 |
sort_reverse = not reverse |
| 430 |
|
| 431 |
|
| 432 |
def get_key(node): |
| 433 |
row = data[rns[node.iid]] |
| 434 |
return key(row[column] if len(row) > column else None) |
| 435 |
|
| 436 |
|
| 437 |
stack = sorted( |
| 438 |
(node for node in index if node.parent == ""), |
| 439 |
key=get_key, |
| 440 |
reverse=sort_reverse, |
| 441 |
) |
| 442 |
|
| 443 |
|
| 444 |
sorted_nodes = [] |
| 445 |
mapping = {} |
| 446 |
new_rn = 0 |
| 447 |
|
| 448 |
|
| 449 |
while stack: |
| 450 |
current = stack.pop() |
| 451 |
sorted_nodes.append(current) |
| 452 |
mapping[rns[current.iid]] = new_rn |
| 453 |
new_rn += 1 |
| 454 |
if current.children: |
| 455 |
|
| 456 |
sorted_children = sorted( |
| 457 |
(index[rns[ciid]] for ciid in current.children if ciid in rns), |
| 458 |
key=get_key, |
| 459 |
reverse=sort_reverse, |
| 460 |
) |
| 461 |
|
| 462 |
stack.extend(sorted_children) |
| 463 |
|
| 464 |
return sorted_nodes, mapping |
| 465 |
|
| 466 |
|
| 467 |
|
| 468 |
|
| 469 |
|
| 470 |
|
| 471 |
|
| 472 |
|
| 473 |
|
| 474 |
|
| 475 |
|
| 476 |
|
| 477 |
|
| 478 |
|
| 479 |
|
| 480 |
|
| 481 |
|
| 482 |
|
| 483 |
|
| 484 |
|
| 485 |
|
| 486 |
|
| 487 |
|
| 488 |
|
| 489 |
|
| 490 |
|
| 491 |
|
| 492 |
|
| 493 |
|
| 494 |
|
| 495 |
|
| 496 |
|
| 497 |
|
| 498 |
|
| 499 |
|
| 500 |
|
| 501 |
|
| 502 |
|
| 503 |
|
| 504 |
|
| 505 |
|
| 506 |
|
| 507 |
|
| 508 |
|
| 509 |
|
| 510 |
|
| 511 |
|
| 512 |
|
| 513 |
|
| 514 |
|
| 515 |
|
| 516 |
|
| 517 |
|
| 518 |
|
| 519 |
|
| 520 |
|
| 521 |
|
| 522 |
|
| 523 |
|
| 524 |
|
| 525 |
|
| 526 |
|
| 527 |
|
| 528 |
|
| 529 |
|
| 530 |
|
| 531 |
|
| 532 |
|
| 533 |
|
| 534 |
|
| 535 |
|
| 536 |
|
| 537 |
|
| 538 |
|
| 539 |
|
| 540 |
|
| 541 |
|
| 542 |
|
| 543 |
|