Repository navigation
Expand file tree
/
Copy pathxtras.py
More file actions
1294 lines (1134 loc) · 55.6 KB
/
Copy pathxtras.py
File metadata and controls
1294 lines (1134 loc) · 55.6 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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
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
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Utility functions used in the fastai library
IO utilities include:
- `maybe_open`: accept a path or an open file, closing only files it opens.
- `run`: run a command and return stdout; raise `IOError` on failure.
- `atomic_save`: write a temporary file, then rename it over the destination.
- `untar_dir`: extract an archive, creating a containing directory when needed.
- `globtastic`: recursively find files with include and exclude filters.
`Config` reads and writes an ini file with one `DEFAULT` section. Access keys as attributes, items, or with `.get(key, default)`. Use `create=` to supply initial contents for a missing file.
`types=` converts values on read. `Path` values resolve relative to the config file's directory. `Config.find(name)` searches a directory and its parents for the file.
`dict2obj` converts nested dicts to `AttrDict` and lists to `L`, allowing attribute access such as `d.b.c`. `obj2dict` reverses the conversion:
```python
d = dict2obj({'a':1, 'b':{'c':2, 'd':[3,4]}})
test_eq(d.b.c, 2)
test_eq(d.b.d[1], 4)
```
These methods extend [Pathlib.Path](https://docs.python.org/3/library/pathlib.html#basic-use):
- `ls()` lists directory contents as an `L`, optionally filtered by MIME prefix or extension.
- `read_json`, `write_json`, and `read_jsonl` handle JSON files.
- `readlines` reads lines; `mk_write` creates parent directories before writing.
- `delete`, `relpath`, and `normpath` provide file deletion and path conversions.
Set `Path.BASE_PATH` to display paths relative to that directory.
Other utilities include:
- `exec_eval`: run a code string and return its last expression, like a notebook cell.
- `fenced`: wrap text in a Markdown fence longer than any fence character run in the body.
- `str_diff`: return a unified diff, or `''` for identical text.
- `unqid` and `friendly_name`: generate random Python identifiers or memorable word-based names.
- `flexicache`: cache results with configurable expiration policies.
Docs: https://fastcore.fast.ai/xtras.html.md"""
# AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/03_xtras.ipynb.
# %% auto #0
__all__ = ['UNSET', 'spark_chars', 'walk_join', 'walk', 'exttypes', 'globtastic', 'pglob', 'maybe_open', 'mkdir', 'image_size',
'img_bytes', 'detect_mime', 'bunzip', 'loads', 'loads_multi', 'dumps', 'untar_dir', 'repo_details', 'shell',
'ssh', 'rsync_multi', 'run', 'open_file', 'save_pickle', 'load_pickle', 'parse_env', 'expand_wildcards',
'atomic_save', 'load_mod', 'import_no_init', 'save_config_file', 'read_config_file', 'find_file_parents',
'Config', 'Unset', 'dict2obj', 'obj2dict', 'repr_dict', 'is_listy', 'mapped', 'take_lines', 'IterLen',
'ReindexCollection', 'SaveReturn', 'trim_wraps', 'save_iter', 'asave_iter', 'strloader', 'frontmatter',
'clean_cli_output', 'unqid', 'rtoken_hex', 'friendly_name', 'n_friendly_names', 'exec_eval',
'get_source_link', 'sparkline', 'modify_exception', 'round_multiple', 'set_num_threads', 'join_path_file',
'autostart', 'EventTimer', 'stringfmt_names', 'PartialFormatter', 'partial_format', 'truncstr', 'trunc_ctr',
'TruncatedString', 'fenced', 'fenced_blocks', 'str_diff', 'utc2local', 'local2utc', 'trace', 'modified_env',
'ContextManagers', 'shufflish', 'console_help', 'hl_md', 'type2str', 'dataclass_src', 'nullable_dc',
'make_nullable', 'flexiclass', 'asdict', 'vars_pub', 'is_typeddict', 'is_namedtuple', 'CachedIter',
'flexicache', 'time_policy', 'mtime_policy', 'timed_cache']
# %% ../nbs/03_xtras.ipynb #3401d507
from .imports import *
from .foundation import *
from .basics import *
from .ansi import strip_ansi
from importlib import import_module
from functools import wraps
import string,time,dataclasses,difflib,json
from enum import Enum
from contextlib import contextmanager,ExitStack
from configparser import ConfigParser
from datetime import datetime, timezone
from time import sleep,time,perf_counter
from os.path import getmtime
from dataclasses import dataclass, field, fields, is_dataclass, MISSING, make_dataclass
# %% ../nbs/03_xtras.ipynb #f4b76f47
__pyskill_sigs__ = False
# %% ../nbs/03_xtras.ipynb #f64c2b09
def walk_join(root, name):
return (p:=os.path.join(root, name)) + ('/' if os.path.isdir(p) else '')
# %% ../nbs/03_xtras.ipynb #33decc5e
def walk(
path:Path|str, # path to start searching
symlinks:bool=True, # follow symlinks?
keep_file:callable=ret_true, # function that returns True for wanted files
keep_folder:callable=ret_true, # function that returns True for folders to enter
skip_folder:callable=ret_false, # function that returns True for folders to skip
func:callable=walk_join, # function applied to each entry; default adds `/` to folders
ret_folders:bool=False, # include folder entries inline with files?
sort:bool=True, # sort entries alphabetically within each folder?
maxdepth:int=None, # max depth to descend (1=just immediate contents; None=unlimited)
):
"Generator: yields files and (optionally) folders as unified, inline-sorted entries"
path = Path(path)
def _walk(root, depth):
try: entries = list(os.scandir(root))
except OSError: return
if sort: entries.sort(key=lambda e: e.name)
at_max = maxdepth is not None and depth >= maxdepth-1
for e in entries:
if e.is_dir(follow_symlinks=symlinks):
if skip_folder(root, e.name): continue
keep = keep_folder(root, e.name)
if ret_folders and keep: yield func(root, e.name)
if keep and not at_max: yield from _walk(e.path, depth+1)
elif keep_file(root, e.name): yield func(root, e.name)
yield from _walk(str(path), 0)
# %% ../nbs/03_xtras.ipynb #12a01ff4
_exttypes = dict(
py=['ipynb', 'py'],
js=['js', 'jsx', 'mjs', 'cjs'],
java=['java', 'kt', 'scala', 'gradle'],
c=['c', 'h'],
cpp=['cpp', 'hpp', 'cc', 'cxx'],
rb=['rb', 'rake'],
r=['r', 'R'],
ex=['ex', 'exs', 'erl', 'hrl'],
sh=['sh', 'bash'],
web=['html', 'css'],
doc=['md', 'rst'],
cfg=['json', 'yaml', 'yml', 'toml', 'xml'],
)
def exttypes(types):
"""Get exts for comma-separated or list `typ`; if not found in list, return list with just `types`.
Supported: py, js, java, c, cpp, rb, r, ex, sh, web, doc, cfg"""
typs = L(types).flatmap(~Self.split(','))
return typs.flatmap(lambda x: _exttypes.get(x, [x]))
# %% ../nbs/03_xtras.ipynb #4fef7fef
def globtastic(
path:Path|str='.', # path to start searching
recursive:bool=True, # search subfolders
maxdepth:int=None, # max depth to descend (1=just immediate contents; None=unlimited)
symlinks:bool=True, # follow symlinks?
file_glob:str=None, # Only include files matching glob
file_re:str=None, # Only include files matching regex
path_glob:str=None, # Only include files whose full paths match glob (wildcards match separators)
path_re:str=None, # Only include files whose full paths match regex
folder_re:str=None, # Only enter folders matching regex
skip_file_glob:str=None, # Skip files matching glob
skip_file_re:str=None, # Skip files matching regex
skip_folder_re:str=None, # Skip folders matching regex,
func:callable=walk_join, # function to apply to each matched file
ret_folders:bool=False, # return folders, not just files
sort:bool=True, # sort files by name within each folder
types:str|list=None, # list or comma-separated str of ext types from: py, js, java, c, cpp, rb, r, ex, sh, web, doc, cfg
exts:str|list=None, # list or comma-separated str of exts to include
)->L: # Paths to matched files
"A more powerful `glob`, including regex matches, symlink handling, and skip parameters"
from fnmatch import fnmatch
path = Path(path)
if path.is_file(): return L([path])
if not recursive: skip_folder_re='.'
exts = L(exts).flatmap(~Self.split(','))
exts += exttypes(types)
if exts:
exts = [e if e.startswith('.') else f'.{e}' for e in listify(exts)]
file_re = f"({'|'.join(re.escape(e) for e in exts)})$"
file_re,folder_re,path_re = compile_re(file_re),compile_re(folder_re),compile_re(path_re)
skip_file_re,skip_folder_re = compile_re(skip_file_re),compile_re(skip_folder_re)
def _keep_file(root, name):
fname = os.path.join(root,name)
return (not path_glob or fnmatch(fname, path_glob)) and (
not path_re or path_re.search(fname)) and (
not file_glob or fnmatch(name, file_glob)) and (
not file_re or file_re.search(name)) and (
not skip_file_glob or not fnmatch(name, skip_file_glob)) and (
not skip_file_re or not skip_file_re.search(name))
def _keep_folder(root, name): return not folder_re or folder_re.search(os.path.join(root,name))
def _skip_folder(root, name): return skip_folder_re and skip_folder_re.search(name)
return L(walk(path, symlinks=symlinks, maxdepth=maxdepth, keep_file=_keep_file, keep_folder=_keep_folder,
skip_folder=_skip_folder, func=func, ret_folders=ret_folders, sort=sort))
# %% ../nbs/03_xtras.ipynb #827b4914
@fdelegates(globtastic)
def pglob(
path:Path|str='.', # path to start searching
func:callable=Path, # function to apply to each matched file
**kwargs
)->L: # Paths to matched files
"Shortcut for `globtastic(..., call=Path)`"
return globtastic(path, func=func, **kwargs)
# %% ../nbs/03_xtras.ipynb #d514da68
@contextmanager
def maybe_open(f, mode='r', **kwargs):
"Context manager: open `f` if it is a path (and close on exit)"
if isinstance(f, (str,os.PathLike)):
with open(f, mode, **kwargs) as f: yield f
else: yield f
# %% ../nbs/03_xtras.ipynb #63d86576
def mkdir(path, exist_ok=False, parents=False, overwrite=False, **kwargs):
"Creates and returns a directory defined by `path`, optionally removing previous existing directory if `overwrite` is `True`"
import shutil
path = Path(path)
if path.exists() and overwrite: shutil.rmtree(path)
path.mkdir(exist_ok=exist_ok, parents=parents, **kwargs)
return path
# %% ../nbs/03_xtras.ipynb #b33313ff
def image_size(fn):
"Tuple of (w,h) for png, gif, or jpg; `None` otherwise"
from fastcore import imghdr
import struct
def _jpg_size(f):
size,ftype = 2,0
while not 0xc0 <= ftype <= 0xcf:
f.seek(size, 1)
byte = f.read(1)
while ord(byte) == 0xff: byte = f.read(1)
ftype = ord(byte)
size = struct.unpack('>H', f.read(2))[0] - 2
f.seek(1, 1) # `precision'
h,w = struct.unpack('>HH', f.read(4))
return w,h
def _gif_size(f): return struct.unpack('<HH', head[6:10])
def _png_size(f):
assert struct.unpack('>i', head[4:8])[0]==0x0d0a1a0a
return struct.unpack('>ii', head[16:24])
d = dict(png=_png_size, gif=_gif_size, jpeg=_jpg_size)
with maybe_open(fn, 'rb') as f: return d[imghdr.what(f)](f)
# %% ../nbs/03_xtras.ipynb #d3aa6edf
def img_bytes(img, fmt='PNG'):
# Convert PIL `img` to bytes in format `fmt`
from io import BytesIO
buf=BytesIO()
img.save(buf, format=fmt)
return buf.getvalue()
# %% ../nbs/03_xtras.ipynb #e5801198
_sigs = {
(b'%PDF', 0): 'application/pdf',
(b'RIFF', 0): lambda d: 'audio/wav' if d[8:12]==b'WAVE' else 'video/avi' if d[8:12]==b'AVI ' else None,
(b'ID3', 0): 'audio/mp3',
(b'\xff\xfb', 0): 'audio/mp3',
(b'\xff\xf3', 0): 'audio/mp3',
(b'FORM', 0): lambda d: 'audio/aiff' if d[8:12]==b'AIFF' else None,
(b'OggS', 0): 'audio/ogg',
(b'fLaC', 0): 'audio/flac',
(b'ftyp', 4): lambda d: 'video/3gpp' if d[8:11]==b'3gp' else 'video/mp4',
(b'\x1a\x45\xdf', 0): 'video/webm',
(b'FLV', 0): 'video/x-flv',
(b'\x30\x26\xb2\x75', 0): 'video/wmv',
(b'\x00\x00\x01\xb3', 0): 'video/mpeg',
}
def detect_mime(data):
"Get the MIME type for bytes `data`, covering common PDF, audio, video, and image types"
if not isinstance(data,bytes): return None
import mimetypes
from fastcore import imghdr
for (sig,pos),mime in _sigs.items():
if data[pos:pos+len(sig)]==sig and (res := mime(data) if callable(mime) else mime): return res
return mimetypes.guess_type(f'x.{imghdr.what(None, h=data)}', strict=False)[0]
# %% ../nbs/03_xtras.ipynb #f856746a
def bunzip(fn):
"bunzip `fn`, raising exception if output already exists"
fn = Path(fn)
assert fn.exists(), f"{fn} doesn't exist"
out_fn = fn.with_suffix('')
assert not out_fn.exists(), f"{out_fn} already exists"
import bz2
with bz2.BZ2File(fn, 'rb') as src, out_fn.open('wb') as dst:
for d in iter(lambda: src.read(1024*1024), b''): dst.write(d)
# %% ../nbs/03_xtras.ipynb #0a78c637
def loads(s, **kw):
"Same as `json.loads`, but handles `None`"
if not s: return {}
return json.loads(s, **kw)
# %% ../nbs/03_xtras.ipynb #131170f7
def loads_multi(s:str):
"Generator of >=0 decoded json dicts, possibly with non-json ignored text at start and end"
import json
_dec = json.JSONDecoder()
while s.find('{')>=0:
s = s[s.find('{'):]
obj,pos = _dec.raw_decode(s)
if not pos: raise ValueError(f'no JSON object found at {pos}')
yield obj
s = s[pos:]
# %% ../nbs/03_xtras.ipynb #ed688ac4
def dumps(obj, **kw):
"Same as `json.dumps`"
return json.dumps(obj, **kw)
# %% ../nbs/03_xtras.ipynb #ac84300c
def _unpack(fname, out):
import shutil
shutil.unpack_archive(str(fname), str(out))
ls = out.ls()
return ls[0] if len(ls) == 1 else out
# %% ../nbs/03_xtras.ipynb #6f1e90e9
def untar_dir(fname, dest, rename=False, overwrite=False, uid=-1, gid=-1):
"untar `file` into `dest`, creating a directory if the root contains more than one item; recursively chown if `uid`/`gid` set"
import tempfile,shutil
dest = Path(dest)
with tempfile.TemporaryDirectory() as d:
out = Path(d)/remove_suffix(Path(fname).stem, '.tar')
out.mkdir()
if rename: dest = dest/out.name
else:
src = _unpack(fname, out)
dest = dest/src.name
if dest.exists():
if overwrite: shutil.rmtree(dest) if dest.is_dir() else dest.unlink()
else: return dest
if rename: src = _unpack(fname, out)
shutil.move(str(src), dest)
if uid>-1 or gid>-1:
os.chown(dest, uid, gid)
if dest.is_dir():
for p in dest.rglob('*'): os.chown(p, uid, gid, follow_symlinks=False)
return dest
# %% ../nbs/03_xtras.ipynb #ab91ee87
def repo_details(url):
"Tuple of `owner,name` from ssh or https git repo `url`"
res = remove_suffix(url.strip(), '.git')
res = res.split(':')[-1]
return res.split('/')[-2:]
# %% ../nbs/03_xtras.ipynb #ba70e535
def shell(*args, **kwargs):
"Shortcut for `subprocess.run(shell=True)`"
import subprocess
return subprocess.run(*args, shell=True, **kwargs)
# %% ../nbs/03_xtras.ipynb #f62134a5
def ssh(host, args='', user='ubuntu', sock=None):
"Run SSH command with given arguments"
sock_opts = f'-S {sock}' if sock else ''
return shell(f'ssh {sock_opts} {args} {user}@{host}')
# %% ../nbs/03_xtras.ipynb #cb24780e
def rsync_multi(ip, files, user='ubuntu', persist='5m'):
"Transfer multiple files with rename using persistent SSH connection"
sock = f'/tmp/ssh-{ip}-{user}'
ssh(ip, f'-o ControlMaster=auto -o ControlPersist={persist} -N -f', user, sock)
for src,dst in files: shell(f'rsync -az -e "ssh -S {sock}" {src} {user}@{ip}:{dst}')
# %% ../nbs/03_xtras.ipynb #dda52646
def run(cmd, *rest, same_in_win=False, ignore_ex=False, as_bytes=False, stderr=True, inp=None):
"Pass `cmd` (splitting with `shlex` if string) to `subprocess.run`; return `stdout`; raise `IOError` if fails"
import subprocess
if rest: cmd = ('cmd', '/c', cmd, *rest) if sys.platform == 'win32' and same_in_win else (cmd,)+rest
elif isinstance(cmd, str):
import shlex
if sys.platform == 'win32' and same_in_win: cmd = 'cmd /c ' + cmd
cmd = shlex.split(cmd)
elif isinstance(cmd, list) and sys.platform == 'win32' and same_in_win: cmd = ['cmd', '/c'] + cmd
if isinstance(inp, str): inp = inp.encode()
res = subprocess.run(cmd, input=inp, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout = res.stdout
if stderr and res.stderr: stdout += b' ;; ' + res.stderr
if not as_bytes: stdout = stdout.decode().strip()
if ignore_ex: return (res.returncode, stdout)
if res.returncode: raise IOError((res.stdout + b' ;; ' + res.stderr).decode().strip())
return stdout
# %% ../nbs/03_xtras.ipynb #5097b830
def open_file(fn, mode='r', **kwargs):
"Open a file, with optional compression if gz or bz2 suffix"
if isinstance(fn, io.IOBase): return fn
import bz2,gzip,zipfile
fn = Path(fn)
if fn.suffix=='.bz2': return bz2.BZ2File(fn, mode, **kwargs)
elif fn.suffix=='.gz' : return gzip.GzipFile(fn, mode, **kwargs)
elif fn.suffix=='.zip': return zipfile.ZipFile(fn, mode, **kwargs)
else: return open(fn,mode, **kwargs)
# %% ../nbs/03_xtras.ipynb #a9fc7a40
def save_pickle(fn, o):
"Save a pickle file, to a file name or opened file"
import pickle
with open_file(fn, 'wb') as f: pickle.dump(o, f)
# %% ../nbs/03_xtras.ipynb #5e9bc30e
def load_pickle(fn):
"Load a pickle file from a file name or opened file"
import pickle
with open_file(fn, 'rb') as f: return pickle.load(f)
# %% ../nbs/03_xtras.ipynb #02029d02
def parse_env(s:str=None, fn:Union[str,Path]=None) -> dict:
"Parse a shell-style environment string or file"
assert bool(s)^bool(fn), "Must pass exactly one of `s` or `fn`"
if fn: s = Path(fn).read_text()
def _f(line):
m = re.match(r'^\s*(?:export\s+)?(\w+)\s*=\s*(["\']?)(.*?)(\2)\s*(?:#.*)?$', line).groups()
return m[0], m[2]
return dict(_f(o.strip()) for o in s.splitlines() if o.strip() and not re.match(r'\s*#', o))
# %% ../nbs/03_xtras.ipynb #d030f939
def expand_wildcards(code):
"Expand all wildcard imports in the given code string."
import ast,importlib
tree = ast.parse(code)
def _replace_node(code, old_node, new_node):
"Replace `old_node` in the source `code` with `new_node`."
lines = code.splitlines()
lnum = old_node.lineno
indent = ' ' * (len(lines[lnum-1]) - len(lines[lnum-1].lstrip()))
new_lines = [indent+line for line in ast.unparse(new_node).splitlines()]
lines[lnum-1 : old_node.end_lineno] = new_lines
return '\n'.join(lines)
def _expand_import(node, mod, existing):
"Create expanded import `node` in `tree` from wildcard import of `mod`."
mod_all = getattr(mod, '__all__', None)
available_names = set(mod_all) if mod_all is not None else set(dir(mod))
used_names = {n.id for n in ast.walk(tree) if isinstance(n, ast.Name) and n.id in available_names} - existing
if not used_names: return node
names = [ast.alias(name=name, asname=None) for name in sorted(used_names)]
return ast.ImportFrom(module=node.module, names=names, level=node.level)
existing = set()
for node in ast.walk(tree):
if isinstance(node, ast.ImportFrom) and node.names[0].name != '*': existing.update(n.name for n in node.names)
elif isinstance(node, ast.Import): existing.update(n.name.split('.')[0] for n in node.names)
for node in ast.walk(tree):
if isinstance(node, ast.ImportFrom) and any(n.name == '*' for n in node.names):
new_import = _expand_import(node, importlib.import_module(node.module), existing)
code = _replace_node(code, node, new_import)
return code
# %% ../nbs/03_xtras.ipynb #15c2b62c
@patch
def mkdir_perms(self:Path, mode=0o777, parents=False, exist_ok=False, uid=-1, gid=-1):
"Create directory like Path.mkdir but optionally set uid/gid on newly created dirs"
if self.exists() and not exist_ok: raise FileExistsError(self)
to_create = []
p = self
while not p.exists():
to_create.append(p)
if parents: p = p.parent
else: break
for d in reversed(to_create):
try: d.mkdir(mode=mode)
except FileExistsError:
if d==self and not exist_ok: raise
continue
if uid>-1 or gid>-1: os.chown(d, uid, gid)
# %% ../nbs/03_xtras.ipynb #832397a3
@contextmanager
def atomic_save(fn, mode='wb', uid=-1, gid=-1, **kwargs):
"Context manager for writing a file atomically via a temp file that is renamed on close"
from tempfile import NamedTemporaryFile as ntf
fn = Path(fn)
fn.parent.mkdir_perms(parents=True, exist_ok=True, uid=uid, gid=gid)
with ntf(mode=mode, dir=fn.parent, delete=False, suffix='tmp', **kwargs) as f:
try: yield f
except:
Path(f.name).unlink(missing_ok=True)
raise
if uid>-1 or gid>-1: os.chown(f.name, uid, gid)
Path(f.name).rename(fn)
# %% ../nbs/03_xtras.ipynb #52746e0e
def load_mod(name, path):
"Load module `name` from file `path`"
import importlib.util as iu
spec = iu.spec_from_file_location(name, Path(path))
mod = iu.module_from_spec(spec)
spec.loader.exec_module(mod)
return mod
# %% ../nbs/03_xtras.ipynb #68d60335
def import_no_init(name):
"Import dotted `name` without running any `__init__.py`"
import importlib.util as iu
parts = name.split('.')
path = Path(iu.find_spec(parts[0]).origin)
if len(parts)>1: path = path.parent.joinpath(*parts[1:]).with_suffix('.py')
return load_mod(name, path)
# %% ../nbs/03_xtras.ipynb #427dbfbf
def save_config_file(file, d, **kwargs):
"Write settings dict to a new config file, or overwrite the existing one."
config = ConfigParser(**kwargs)
config['DEFAULT'] = d
config.write(open(file, 'w'))
# %% ../nbs/03_xtras.ipynb #c1e53363
def read_config_file(file, **kwargs):
config = ConfigParser(**kwargs)
config.read(file, encoding='utf8')
return config['DEFAULT']
# %% ../nbs/03_xtras.ipynb #3ab1e73c
def find_file_parents(fname, frompath=None):
"Search `cfg_path` and its parents to find `cfg_name`"
p = Path(frompath or Path.cwd()).expanduser().absolute()
return first(o for o in [p, *p.parents] if (o/fname).exists())
# %% ../nbs/03_xtras.ipynb #11212a22
class Config:
"Reading and writing `ConfigParser` ini files"
def __init__(self, cfg_path, cfg_name, create=None, save=True, extra_files=None, types=None, **cfg_kwargs):
self.types = types or {}
cfg_path = Path(cfg_path).expanduser().absolute()
self.config_path,self.config_file = cfg_path,cfg_path/cfg_name
self._cfg = ConfigParser(**cfg_kwargs)
self.d = self._cfg['DEFAULT']
found = [Path(o) for o in self._cfg.read(L(extra_files)+[self.config_file], encoding='utf8')]
if self.config_file not in found and create is not None:
self._cfg.read_dict({'DEFAULT':create})
if save:
cfg_path.mkdir(exist_ok=True, parents=True)
save_config_file(self.config_file, create)
def __repr__(self): return repr(dict(self._cfg.items('DEFAULT', raw=True)))
def __setitem__(self,k,v): self.d[k] = str(v)
def __contains__(self,k): return k in self.d
def save(self): save_config_file(self.config_file,self.d)
def __getattr__(self,k): return stop(AttributeError(k)) if k=='d' or k not in self.d else self.get(k)
def __getitem__(self,k): return stop(IndexError(k)) if k not in self.d else self.get(k)
def get(self,k,default=None):
v = self.d.get(k, default)
if v is None: return None
typ = self.types.get(k, None)
if typ==bool: return str2bool(v)
if not typ: return str(v)
if typ==Path: return self.config_path/v
return typ(v)
def path(self,k,default=None):
v = self.get(k, default)
return v if v is None else self.config_path/v
@classmethod
def find(cls, cfg_name, cfg_path=None, **kwargs):
"Search `cfg_path` and its parents to find `cfg_name`"
p = find_file_parents(cfg_name, cfg_path)
return cls(p, cfg_name, **kwargs) if p else None
# %% ../nbs/03_xtras.ipynb #6368c600
class Unset(Enum):
_Unset=''
def __repr__(self): return 'UNSET'
def __str__ (self): return 'UNSET'
def __bool__(self): return False
UNSET = Unset._Unset
# %% ../nbs/03_xtras.ipynb #9579358d
def dict2obj(d=UNSET, list_func=L, dict_func=AttrDict, **kwargs):
"Convert (possibly nested) dicts (or lists of dicts) to `AttrDict`"
if d is UNSET: d={}
if isinstance(d, (L,list)): return list_func([dict2obj(v, list_func=list_func, dict_func=dict_func) for v in d])
if not isinstance(d, dict): return d
return dict_func(**{k:dict2obj(v, list_func=list_func, dict_func=dict_func) for k,v in (d|kwargs).items()})
# %% ../nbs/03_xtras.ipynb #055a1e07
def obj2dict(d):
"Convert (possibly nested) AttrDicts (or lists of AttrDicts) to `dict`"
if isinstance(d, (L,list)): return list(L(d).map(obj2dict))
if not isinstance(d, dict): return d
return dict(**{k:obj2dict(v) for k,v in d.items()})
# %% ../nbs/03_xtras.ipynb #36b00c72
def _repr_dict(d, lvl):
if isinstance(d,dict):
its = [f"{k}: {_repr_dict(v,lvl+1)}" for k,v in d.items()]
elif isinstance(d,(list,L)): its = [_repr_dict(o,lvl+1) for o in d]
else: return str(d)
return '\n' + '\n'.join([" "*(lvl*2) + "- " + o for o in its])
# %% ../nbs/03_xtras.ipynb #13bb8fba
def repr_dict(d):
"Print nested dicts and lists, such as returned by `dict2obj`"
return _repr_dict(d,0).strip()
# %% ../nbs/03_xtras.ipynb #20842e1f
def is_listy(x):
"`isinstance(x, (tuple,list,L,slice,Generator,set,frozenset))`"
return isinstance(x, (tuple,list,L,slice,Generator,set,frozenset))
# %% ../nbs/03_xtras.ipynb #40c2c641
def mapped(f, it):
"map `f` over `it`, unless it's not listy, in which case return `f(it)`"
return L(it).map(f) if is_listy(it) else f(it)
# %% ../nbs/03_xtras.ipynb #062ca713
def take_lines(s, pat, atstart=True, atend=False, drop=False):
"Take contiguous lines matching `pat` from either end of `s`"
ls,pred = s.splitlines(keepends=True),re.compile(pat).search
i,j = 0,len(ls)
if atstart:
while i<j and pred(ls[i]): i += 1
if atend:
while i<j and pred(ls[j-1]): j -= 1
return ''.join(ls[i:j] if drop else ls[:i]+ls[j:])
# %% ../nbs/03_xtras.ipynb #ab0758e6
@patch
def readlines(self:Path, hint=-1, encoding='utf8'):
"Read the content of `self`"
with self.open(encoding=encoding) as f: return f.readlines(hint)
# %% ../nbs/03_xtras.ipynb #5ad0571d
@patch
def read_json(self:Path, encoding=None, errors=None):
"Same as `read_text` followed by `loads`"
return loads(self.read_text(encoding=encoding, errors=errors))
# %% ../nbs/03_xtras.ipynb #69a6fa3a
@patch
def read_jsonl(self:Path, encoding=None, errors=None):
"Parse newline-delimited JSON, returning one object per line"
def _load(i,l):
try: return loads(l)
except ValueError as e: raise ValueError(f'{self}:{i}: {e}') from e
with self.open(encoding=encoding, errors=errors) as f: return [_load(i,l) for i,l in enumerate(f,1)]
# %% ../nbs/03_xtras.ipynb #d6d8d893
@patch
def mk_write(self:Path, data, encoding=None, errors=None, mode=511, uid=-1, gid=-1):
"Make all parent dirs of `self`, and write `data`"
self.parent.mkdir(exist_ok=True, parents=True, mode=mode)
self.write_text(data, encoding=encoding, errors=errors)
if uid!=-1 or gid!=-1: os.chown(self, uid, gid)
# %% ../nbs/03_xtras.ipynb #233a8732
@patch
def write_json(self:Path, data, encoding=None, errors=None, mode=511, uid=-1, gid=-1, **kw):
"Same as `dumps`followed by `mk_write`"
self.mk_write(dumps(data,**kw),encoding,errors,mode,uid,gid)
# %% ../nbs/03_xtras.ipynb #9fc9965f
@patch
def relpath(self:Path, start=None):
"Same as `os.path.relpath`, but returns a `Path`, and resolves symlinks"
return Path(os.path.relpath(self.resolve(), Path(start).resolve()))
# %% ../nbs/03_xtras.ipynb #12264861
@patch
def ls(self:Path, n_max=None, file_type=None, file_exts=None):
"Contents of path as a list"
import mimetypes
extns=L(file_exts)
if file_type: extns += L(k for k,v in mimetypes.types_map.items() if v.startswith(file_type+'/'))
has_extns = len(extns)==0
res = (o for o in self.iterdir() if has_extns or o.suffix in extns)
if n_max is not None: res = itertools.islice(res, n_max)
return L(res)
# %% ../nbs/03_xtras.ipynb #abe052c6
@patch
def normpath(self:Path):
"Normalize path, eliminating double slashes, etc."
return Path(os.path.normpath(self))
# %% ../nbs/03_xtras.ipynb #695f90e0
@patch
def __repr__(self:Path):
b = getattr(Path, 'BASE_PATH', None)
if b:
try: self = self.relative_to(b)
except: pass
return f"Path({self.as_posix()!r})"
# %% ../nbs/03_xtras.ipynb #6bd8b653
@patch
def delete(self:Path):
"Delete a file, symlink, or directory tree"
if not self.exists(): return
if self.is_dir():
import shutil
shutil.rmtree(self)
else: self.unlink()
# %% ../nbs/03_xtras.ipynb #f2bb033e
class IterLen:
"Base class to add iteration to anything supporting `__len__` and `__getitem__`"
def __iter__(self): return (self[i] for i in range_of(self))
# %% ../nbs/03_xtras.ipynb #0356640b
@docs
class ReindexCollection(GetAttr, IterLen):
"Reindexes collection `coll` with indices `idxs` and optional LRU cache of size `cache`"
_default='coll'
def __init__(self, coll, idxs=None, cache=None, tfm=noop):
if idxs is None: idxs = L.range(coll)
store_attr()
if cache is not None: self._get = functools.lru_cache(maxsize=cache)(self._get)
def _get(self, i): return self.tfm(self.coll[i])
def __getitem__(self, i): return self._get(self.idxs[i])
def __len__(self): return len(self.coll)
def reindex(self, idxs): self.idxs = idxs
def shuffle(self):
import random
random.shuffle(self.idxs)
def cache_clear(self): self._get.cache_clear()
def __getstate__(self): return {'coll': self.coll, 'idxs': self.idxs, 'cache': self.cache, 'tfm': self.tfm}
def __setstate__(self, s): self.coll,self.idxs,self.cache,self.tfm = s['coll'],s['idxs'],s['cache'],s['tfm']
_docs = dict(reindex="Replace `self.idxs` with idxs",
shuffle="Randomly shuffle indices",
cache_clear="Clear LRU cache")
# %% ../nbs/03_xtras.ipynb #59a2f54d
class SaveReturn:
"Wrap an iterator such that the generator function's return value is stored in `.value`"
def __init__(self, its): self.its = its
def __iter__(self):
self.value = yield from self.its
return self.value
# %% ../nbs/03_xtras.ipynb #e89ff9b0
def trim_wraps(f, n=1):
"Like wraps, but removes the first n parameters from the signature"
import inspect
def _(g):
g = wraps(f)(g)
sig = inspect.signature(f)
params = list(sig.parameters.values())[n:]
g.__signature__ = sig.replace(parameters=params)
return g
return _
# %% ../nbs/03_xtras.ipynb #b867efdd
class _save_iter:
def __init__(self, g, *args, **kw): self.g,self.args,self.kw = g,args,kw
def __iter__(self): yield from self.g(self, *self.args, **self.kw)
def __aiter__(self): return self.g(self, *self.args, **self.kw)
def save_iter(g):
"Decorator that allows a generator function to store values in the returned iterator object"
@trim_wraps(g)
def _(*args, **kwargs): return _save_iter(g, *args, **kwargs)
return _
# %% ../nbs/03_xtras.ipynb #d4017861
def asave_iter(g):
"Like `save_iter`, but for async iterators"
@trim_wraps(g)
def _(*args, **kwargs): return _save_iter(g, *args, **kwargs)
return _
# %% ../nbs/03_xtras.ipynb #d2757e2a
def strloader():
"`yaml.BaseLoader` extended to resolve `true`/`True`/`false`/`False`, and nothing else, to `bool`"
import yaml
if not hasattr(strloader, 'ldr'):
class StrLoader(yaml.BaseLoader): pass
StrLoader.add_constructor('tag:yaml.org,2002:bool', lambda l,n: n.value.lower()=='true')
StrLoader.add_implicit_resolver('tag:yaml.org,2002:bool', re.compile(r'^(?:[Tt]rue|[Ff]alse)$'), list('tTfF'))
strloader.ldr = StrLoader
return strloader.ldr
def frontmatter(txt:str, strvals:bool=False)->tuple:
"Tuple of (dict, body) from frontmatter in `txt`; missing frontmatter returns ({}, txt), malformed YAML raises"
import yaml
if not txt.startswith('---\n'): return {},txt
end = min((i for i in (txt.find(f'\n{c}\n', 3) for c in ('---','...')) if i >= 0), default=-1)
if end < 0:
if not txt.endswith(('\n---','\n...')): return {},txt
end = len(txt) - 4
res = yaml.load(txt[4:end], Loader=strloader() if strvals else yaml.SafeLoader)
return (res,txt[end+5:]) if isinstance(res,dict) else ({},txt)
# %% ../nbs/03_xtras.ipynb #45eb5141
def clean_cli_output(txt:str, strip:bool=True):
r"Render CLI output as it appears on screen: alternate screen, `\r` overwrites, `\b` backspaces, and ANSI escapes"
if '\x1b[?1049h' in txt:
if '\x1b[?1049l' not in txt: return ''
txt = txt.rsplit('\x1b[?1049l', 1)[-1]
txt = txt.replace('\r\n', '\n')
def _line(l):
l = l.rstrip('\r').rsplit('\r', 1)[-1] # trailing \r overwrites nothing; else keep last overwrite
while (i := l.find('\b')) != -1: l = l[:i] if i==len(l)-1 else l[:max(0,i-1)] + l[i+1:]
return l
res = '\n'.join(_line(l) for l in txt.split('\n'))
return strip_ansi(res, term_queries=True) if strip else res
# %% ../nbs/03_xtras.ipynb #35368de5
def unqid(seeded=False):
"Generate a unique id suitable for use as a Python identifier"
from base64 import b64encode
from uuid import uuid4,UUID
id4 = UUID(int=random.getrandbits(128), version=4) if seeded else uuid4()
res = b64encode(id4.bytes)
return '_' + res.decode().rstrip('=').translate(str.maketrans('+/', '_-'))
# %% ../nbs/03_xtras.ipynb #e0e7b294
def rtoken_hex(
nbytes:int=16 # Number of bytes to generate
)->str: # hex string of length nbytes*2
"Generate a random hex string using Python's random module."
import random
return ''.join(f'{random.randint(0, 255):02x}' for _ in range(nbytes))
# %% ../nbs/03_xtras.ipynb #4e02b1f0
def friendly_name(levels=3, suffix=4):
"Generate a random human-readable name with customizable word levels and suffix length"
import random,string
adjectives = ['admiring', 'adoring', 'amazing', 'awesome', 'beautiful', 'blissful', 'bold', 'brave', 'busy', 'charming', 'clever', 'compassionate', 'confident', 'cool', 'dazzling', 'determined', 'dreamy', 'eager', 'ecstatic', 'elastic', 'elated', 'elegant', 'epic', 'exciting', 'fervent', 'festive', 'flamboyant', 'focused', 'friendly', 'frosty', 'funny', 'gallant', 'gifted', 'goofy', 'gracious', 'great', 'happy', 'hopeful', 'hungry', 'inspiring', 'intelligent', 'interesting', 'jolly', 'jovial', 'keen', 'kind', 'laughing', 'loving', 'lucid', 'magical', 'modest', 'nice', 'nifty', 'nostalgic', 'objective', 'optimistic', 'peaceful', 'pensive', 'practical', 'priceless', 'quirky', 'quizzical', 'relaxed', 'reverent', 'romantic', 'serene', 'sharp', 'silly', 'sleepy', 'stoic', 'sweet', 'tender', 'trusting', 'upbeat', 'vibrant', 'vigilant', 'vigorous', 'wizardly', 'wonderful', 'youthful', 'zealous', 'zen', 'golden', 'silver', 'crimson', 'azure', 'emerald', 'violet', 'amber', 'coral', 'turquoise', 'lavender', 'minty', 'citrus', 'vanilla', 'woody', 'floral', 'fresh', 'gentle', 'sparkling', 'precise', 'curious']
nouns = ['tiger', 'eagle', 'river', 'mountain', 'forest', 'ocean', 'star', 'moon', 'wind', 'dragon', 'phoenix', 'wolf', 'bear', 'lion', 'shark', 'falcon', 'raven', 'crystal', 'diamond', 'ruby', 'sapphire', 'pearl', 'wave', 'tide', 'cloud', 'rainbow', 'sunset', 'sunrise', 'galaxy', 'comet', 'meteor', 'planet', 'nebula', 'cosmos', 'universe', 'atom', 'photon', 'quantum', 'matrix', 'cipher', 'code', 'signal', 'pulse', 'beam', 'ray', 'spark', 'frost', 'ice', 'snow', 'mist', 'fog', 'dew', 'rain', 'hail', 'helix', 'prism', 'lens', 'mirror', 'echo', 'heart', 'mind', 'dream', 'vision', 'hope', 'wish', 'magic', 'spell', 'charm', 'rune', 'symbol', 'token', 'key', 'door', 'gate', 'bridge', 'tower', 'castle', 'fortress', 'shield', 'dolphin', 'whale', 'penguin', 'butterfly', 'hummingbird', 'deer', 'rabbit', 'fox', 'otter', 'panda', 'koala', 'zebra', 'giraffe', 'elephant', 'valley', 'canyon', 'meadow', 'prairie', 'island', 'lake', 'pond', 'stream', 'waterfall', 'cliff', 'peak', 'hill', 'grove', 'garden', 'sunlight', 'breeze', 'melody', 'sparkle', 'whirlpool', 'windmill', 'carousel', 'spiral', 'glow']
verbs = ['runs', 'flies', 'jumps', 'builds', 'creates', 'flows', 'shines', 'grows', 'moves', 'works', 'dances', 'sings', 'plays', 'dreams', 'thinks', 'learns', 'teaches', 'helps', 'heals', 'saves', 'protects', 'guards', 'watches', 'sees', 'hears', 'feels', 'knows', 'understands', 'discovers', 'explores', 'searches', 'finds', 'seeks', 'holds', 'carries', 'lifts', 'pushes', 'pulls', 'makes', 'crafts', 'forges', 'shapes', 'forms', 'molds', 'carves', 'joins', 'connects', 'links', 'binds', 'ties', 'opens', 'closes', 'starts', 'stops', 'begins', 'ends', 'finishes', 'completes', 'wins', 'triumphs', 'succeeds', 'achieves', 'accomplishes', 'reaches', 'arrives', 'departs', 'leaves', 'returns', 'comes', 'goes', 'travels', 'journeys', 'walks', 'sprints', 'races', 'speeds', 'rushes', 'hurries', 'waits', 'pauses', 'rests', 'sleeps', 'wakes', 'rises', 'climbs', 'ascends', 'descends', 'swims', 'dives', 'surfs', 'sails', 'paddles', 'hikes', 'treks', 'wanders', 'roams', 'ventures', 'navigates', 'glides', 'soars', 'floats', 'drifts', 'tosses', 'divides', 'shares', 'secures', 'settles', 'places', 'wonders', 'questions']
adverbs = ['quickly', 'gracefully', 'gently', 'boldly', 'quietly', 'swiftly', 'carefully', 'eagerly', 'smoothly', 'brightly', 'softly', 'steadily', 'cleverly', 'proudly', 'calmly', 'freely', 'wisely', 'kindly', 'firmly', 'lightly', 'deeply', 'clearly', 'warmly', 'coolly', 'sharply', 'slowly', 'rapidly', 'silently', 'loudly', 'perfectly']
suffix = ''.join(random.choices(string.ascii_lowercase + string.digits, k=suffix))
words = [random.choice(o) for o in (adjectives,nouns,verbs,adverbs)[:levels]]
return f"{'-'.join(words)}-{suffix}"
# %% ../nbs/03_xtras.ipynb #998e08a0
def n_friendly_names(levels=3, suffix=4):
"Number of possible combos for `friendly_names"
ns = [102,116,110,30]
return product(ns[:levels])*36**suffix
# %% ../nbs/03_xtras.ipynb #b4d1831f
def exec_eval(
code, # Code to exec/eval
g=None, # Globals namespace dict
l=None # Locals namespace dict
):
"Evaluate `code` in `g` (defaults to `globals()`) and `l` (defaults to `locals()`)"
import ast, inspect
frame = inspect.currentframe().f_back
if g is None: g = frame.f_globals
if l is None: l = g
tree = ast.parse(code, mode='exec')
if tree.body and isinstance(tree.body[-1], ast.Expr):
*statements, expr = tree.body
exec_code = compile(ast.Module(statements, []), filename="<string>", mode="exec")
expr_code = compile(ast.Expression(expr.value), filename="<string>", mode="eval")
exec(exec_code, g, l)
return eval(expr_code, g, l)
else: exec(code, g, l)
# %% ../nbs/03_xtras.ipynb #bdaa78a0
def _unwrapped_type_dispatch_func(x):
# use isinstance_str to avoid adding plum-dispatch as dependency to fastcore
return x.methods[0].implementation if isinstance_str(x,"Function") else x
# %% ../nbs/03_xtras.ipynb #bb4d3fe2
def _is_property(x): return type(x)==property
def _has_property_getter(x): return _is_property(x) and hasattr(x, 'fget') and hasattr(x.fget, 'func')
def _property_getter(x): return x.fget.func if _has_property_getter(x) else x
def _unwrapped_func(x):
x = _unwrapped_type_dispatch_func(x)
x = _property_getter(x)
return x
def get_source_link(func):
"Return link to `func` in source code"
import inspect
func = _unwrapped_func(func)
try: line = inspect.getsourcelines(func)[1]
except Exception: return ''
mod = inspect.getmodule(func)
module = mod.__name__.replace('.', '/') + '.py'
try:
nbdev_mod = import_module(mod.__package__.split('.')[0] + '._modidx')
ghurl = nested_idx(nbdev_mod.d, 'settings', 'git_url')
return f"{ghurl}{module}#L{line}"
except: return f"{module}#L{line}"
# %% ../nbs/03_xtras.ipynb #31a380eb
spark_chars = '▁▂▃▅▆▇'
# %% ../nbs/03_xtras.ipynb #a6371687
def _ceil(x, lim=None): return x if (not lim or x <= lim) else lim
def _sparkchar(x, mn, mx, incr, empty_zero):
if x is None or (empty_zero and not x): return ' '
if incr == 0: return spark_chars[0]
res = int((_ceil(x,mx)-mn)/incr-0.5)
return spark_chars[res]
# %% ../nbs/03_xtras.ipynb #189818ca
def sparkline(data, mn=None, mx=None, empty_zero=False):
"Sparkline for `data`, with `None`s (and zero, if `empty_zero`) shown as empty column"
valid = [o for o in data if o is not None]
if not valid: return ' '
mn,mx,n = ifnone(mn,min(valid)),ifnone(mx,max(valid)),len(spark_chars)
res = [_sparkchar(x=o, mn=mn, mx=mx, incr=(mx-mn)/n, empty_zero=empty_zero) for o in data]
return ''.join(res)
# %% ../nbs/03_xtras.ipynb #81d193dd
def modify_exception(
e:Exception, # An exception
msg:str=None, # A custom message
replace:bool=False, # Whether to replace e.args with [msg]
) -> Exception:
"Modifies `e` with a custom message attached"
e.args = [f'{e.args[0]} {msg}'] if not replace and len(e.args) > 0 else [msg]
return e
# %% ../nbs/03_xtras.ipynb #6eed0273
def round_multiple(x, mult, round_down=False):
"Round `x` to nearest multiple of `mult`"
def _f(x_): return (int if round_down else round)(x_/mult)*mult
res = L(x).map(_f)
return res if is_listy(x) else res[0]
# %% ../nbs/03_xtras.ipynb #aa966f19
def set_num_threads(nt):
"Get numpy (and others) to use `nt` threads"
try: import mkl; mkl.set_num_threads(nt)
except: pass
try: import torch; torch.set_num_threads(nt)
except: pass
os.environ['IPC_ENABLE']='1'
for o in ['OPENBLAS_NUM_THREADS','NUMEXPR_NUM_THREADS','OMP_NUM_THREADS','MKL_NUM_THREADS']:
os.environ[o] = str(nt)
# %% ../nbs/03_xtras.ipynb #4dac8b41
def join_path_file(file, path, ext=''):
"Return `path/file` if file is a string or a `Path`, file otherwise"
if not isinstance(file, (str, Path)): return file
path.mkdir(parents=True, exist_ok=True)
return path/f'{file}{ext}'
# %% ../nbs/03_xtras.ipynb #205987ad
def autostart(g):
"Decorator that automatically starts a generator"
@functools.wraps(g)
def f():
r = g()
next(r)
return r
return f
# %% ../nbs/03_xtras.ipynb #713d7560
class EventTimer:
"An event timer with history of `store` items of time `span`"
def __init__(self, store=5, span=60):
import collections
self.hist,self.span,self.last = collections.deque(maxlen=store),span,perf_counter()
self._reset()
def _reset(self): self.start,self.events = self.last,0
def add(self, n=1):
"Record `n` events"
if self.duration>self.span:
self.hist.append(self.freq)
self._reset()
self.events +=n
self.last = perf_counter()
@property
def duration(self): return perf_counter()-self.start
@property
def freq(self): return self.events/self.duration
# %% ../nbs/03_xtras.ipynb #a79aa5d5
_fmt = string.Formatter()
# %% ../nbs/03_xtras.ipynb #b5bc6dd4
def stringfmt_names(s:str)->list:
"Unique brace-delimited names in `s`"
return uniqueify(o[1] for o in _fmt.parse(s) if o[1])
# %% ../nbs/03_xtras.ipynb #14ea0571
class PartialFormatter(string.Formatter):
"A `string.Formatter` that doesn't error on missing fields, and tracks missing fields and unused args"
def __init__(self):
self.missing = set()
super().__init__()
def get_field(self, nm, args, kwargs):
try: return super().get_field(nm, args, kwargs)
except KeyError:
self.missing.add(nm)
return '{'+nm+'}',nm
def check_unused_args(self, used, args, kwargs):
self.xtra = filter_keys(kwargs, lambda o: o not in used)
# %% ../nbs/03_xtras.ipynb #eb9cb738
def partial_format(s:str, **kwargs):
"string format `s`, ignoring missing field errors, returning missing and extra fields"
fmt = PartialFormatter()
res = fmt.format(s, **kwargs)
return res,list(fmt.missing),fmt.xtra