-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathsweep.py
executable file
·3111 lines (2661 loc) · 96 KB
/
sweep.py
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
#!/usr/bin/env python3
"""Sweep is a command line fuzzy finer (fzf analog)
"""
from __future__ import annotations
import array
import asyncio
import codecs
import fcntl
import heapq
import io
import itertools as it
import math
import operator as op
import os
import re
import signal
import string
import sys
import termios
import time
import traceback
import tty
import warnings
from collections import deque
from concurrent.futures import ProcessPoolExecutor
from contextlib import ExitStack
from functools import partial, reduce
from typing import (
Any,
Deque,
Dict,
Generator,
Generic,
Iterable,
NamedTuple,
Optional,
Callable,
List,
Sequence,
Set,
Tuple,
TypeVar,
)
# ------------------------------------------------------------------------------
# Utils
# ------------------------------------------------------------------------------
T = TypeVar("T")
def apply(fn: Callable[..., T], *args: Any, **kwargs: Any) -> T:
return fn(*args, **kwargs)
def const(value: T) -> Callable[[Any], T]:
return lambda _: value
def debug(fn: Callable[..., T]) -> Callable[..., T]:
def fn_debug(*args: Any, **kwargs: Any) -> T:
try:
return fn(*args, **kwargs)
except Exception as error:
sys.stderr.write(f"\x1b[31;01m{repr(error)}\x1b[m\n")
pdb.post_mortem()
raise
import sys
import pdb
return fn_debug
def thunk(fn: Callable[..., T]) -> Callable[..., T]:
"""Decorate function, it will be executed only once"""
def fn_thunk(*args: Any, **kwargs: Any):
if not cell:
cell.append(fn(*args, **kwargs))
return cell[0]
cell: List[T] = []
return fn_thunk
# ------------------------------------------------------------------------------
# Matcher
# ------------------------------------------------------------------------------
class Pattern:
STATE_START = 0
STATE_FAIL = -1
def __init__(self, table, finals, epsilons: Optional[Dict[int, Set[int]]] = None):
assert all(
-1 <= s < len(table) for ss in table for s in ss.values()
), f"invalid transition state found: {table}"
assert all(
-1 <= s <= len(table) for s in finals
), f"invalid final state found: {finals}"
self.table: List[Dict[int, int]] = table
self.finals = finals
self.epsilons: Dict[int, Set[int]] = epsilons or {}
def check(self, string: str | bytes):
if not string:
return
if isinstance(string, str):
string = string.encode()
matcher = self()
matcher(None)
for i, c in enumerate(string):
alive, results, unconsumed = matcher(c)
if not alive:
break
unconsumed.extend(string[i + 1 :])
return alive, results, unconsumed
def __call__(self):
"""Create parse function"""
pattern = self
if self.epsilons:
pattern = self.optimize()
table = pattern.table
finals = pattern.finals
STATE_START, STATE_FAIL = self.STATE_START, self.STATE_FAIL
def parse(input: Optional[int]) -> Tuple[bool, List[bytearray], bytearray]:
"""Accepts byte value, and returns current state of the matcher
Returns state, is a tuple of three elements:
- boolean indicating if matcher is alive
- list containing results of the match
- bytearray that contains unconsumed part
"""
nonlocal state, results, buffer, consumed
if input is None:
# initialize state
state = STATE_START
results = []
buffer = bytearray()
consumed = 0
else:
buffer.append(input)
if state != STATE_FAIL:
state = table[state].get(input, STATE_FAIL)
fs = finals.get(state)
if fs:
results.extend(f(buffer) for f in fs)
consumed = len(buffer)
elif fs is not None:
results.append(buffer)
consumed = len(buffer)
return (
state != STATE_FAIL and bool(table[state]), # alive
results,
buffer[consumed:],
)
# state variables
state = STATE_FAIL # expect first input as `None`
results = None
buffer = None
consumed = None
return parse
def map(self, fn) -> Pattern:
"""Replace mappers for finals (can not use `sequence` after this)"""
table, _, (finals,), epsilons = self._merge((self,))
return Pattern(table, {f: (fn,) for f, _ in finals.items()}, epsilons)
@classmethod
def choice(cls, patterns: Sequence[Pattern]) -> Pattern:
assert len(patterns) > 0, "pattern set must be non empyt"
table, starts, finals, epsilons = cls._merge(patterns, table=[{}])
epsilons[0] = set(starts)
return Pattern(
table, {f: cb for fs in finals for f, cb in fs.items()}, epsilons
)
def __or__(self, other: Pattern) -> Pattern:
return self.choice((self, other))
@classmethod
def sequence(cls, patterns: Sequence[Pattern]) -> Pattern:
assert len(patterns) > 0, "patterns set must be non empyt"
table, starts, finals, epsilons = cls._merge(patterns)
for s, fs in zip(starts[1:], finals):
for f, cb in fs.items():
assert not cb, "only last pattern can have callback"
epsilons.setdefault(f, set()).add(s)
finals = finals[-1]
return Pattern(table, finals, epsilons)
def __add__(self, other):
return self.sequence((self, other))
def some(self) -> Pattern:
table, _, (finals,), epsilons = self._merge((self,))
for final in finals:
epsilons.setdefault(final, set()).add(0)
return Pattern(table, finals, epsilons)
def many(self) -> Pattern:
pattern = self.some()
for final in pattern.finals:
pattern.epsilons.setdefault(0, set()).add(final)
return pattern
@classmethod
def _merge(cls, patterns: Sequence[Pattern], table=None):
"""(Merge|Copy) multiple patterns into single one
Puts all states from all patterns into a single table, and updates
all states with appropriate offset.
"""
table = table or []
starts = []
finals = []
epsilons = {}
for pattern in patterns:
offset = len(table)
starts.append(offset)
for tran in pattern.table:
table.append({i: s + offset for i, s in tran.items()})
for s_in, s_outs in pattern.epsilons.items():
epsilons[s_in + offset] = {s_out + offset for s_out in s_outs}
finals.append({final + offset: cb for final, cb in pattern.finals.items()})
return (table, starts, finals, epsilons)
def optimize(self) -> Pattern:
"""Convert NFA to DFA (eliminate epsilons) using power-set construction"""
# NOTE:
# - `n_` contains NFA states (indices in table)
# - `d_` contains DFA state (subset of all indices in table)
def epsilon_closure(n_states):
"""Epsilon closure (reachable with epsilon move) of set of states"""
d_state = set()
queue = set(n_states)
while queue:
n_out = queue.pop()
n_ins = self.epsilons.get(n_out)
if n_ins is not None:
for n_in in n_ins:
if n_in in d_state:
continue
queue.add(n_in)
d_state.add(n_out)
return tuple(sorted(d_state))
d_start = epsilon_closure({0})
d_table = {}
d_finals = {}
d_queue = [d_start]
d_found = set()
while d_queue:
d_state = d_queue.pop()
# finals
for n_state in d_state:
if n_state in self.finals:
(d_finals.setdefault(d_state, []).append(self.finals[n_state]))
# transitions
n_trans = [self.table[n_state] for n_state in d_state]
d_tran = {}
for i in {i for n_tran in n_trans for i in n_tran}:
d_state_new = epsilon_closure(
{n_tran[i] for n_tran in n_trans if i in n_tran}
)
if d_state_new not in d_found:
d_found.add(d_state_new)
d_queue.append(d_state_new)
d_tran[i] = d_state_new
d_table[d_state] = d_tran
# normalize (use indicies instead of sets to identify states)
d_ss_sn = {d_start: 0} # state-set -> state-norm
for d_state in d_table.keys():
d_ss_sn.setdefault(d_state, len(d_ss_sn))
d_sn_ss = {v: k for k, v in d_ss_sn.items()} # state-norm -> state-set
d_table_norm = [
{i: d_ss_sn[ss] for i, ss in d_table[d_sn_ss[sn]].items()} for sn in d_sn_ss
]
d_finals_norm = {
d_ss_sn[ss]: tuple(it.chain.from_iterable(cb))
for ss, cb in d_finals.items()
}
return Pattern(d_table_norm, d_finals_norm)
def show(self, render=True, size=384):
from graphviz import Digraph
dot = Digraph(format="png")
dot.graph_attr["rankdir"] = "LR"
for state in range(len(self.table)):
attrs = {"shape": "circle"}
if state in self.finals:
attrs["shape"] = "doublecircle"
dot.node(str(state), **attrs)
edges = {}
for state, row in enumerate(self.table):
for input, state_new in row.items():
edges.setdefault((state, state_new), []).append(chr(input))
for (src, dst), inputs in edges.items():
dot.edge(str(src), str(dst), label="".join(inputs))
for epsilon_out, epsilon_ins in self.epsilons.items():
for epsilon_in in epsilon_ins:
dot.edge(str(epsilon_out), str(epsilon_in), color="red")
if sys.platform == "darwin" and os.environ["TERM"] and render:
import base64
iterm_format = "\x1b]1337;File=inline=1;width={width}px:{data}\a\n"
with open(dot.render(), "rb") as file:
sys.stdout.write(
iterm_format.format(
width=size, data=base64.b64encode(file.read()).decode()
)
)
else:
return dot
def p_byte(b: int) -> Pattern:
assert 0 <= b <= 255, f"byte expected: {b}"
return Pattern([{b: 1}, {}], {1: tuple()})
def p_byte_pred(pred: Callable[[int], bool]) -> Pattern:
return Pattern([{b: 1 for b in range(256) if pred(b)}, {}], {1: tuple()})
@apply
def p_utf8() -> Pattern:
printable_set = set(
ord(c)
for c in (string.ascii_letters + string.digits + string.punctuation + " ")
)
printable = p_byte_pred(lambda b: b in printable_set)
utf8_two = p_byte_pred(lambda b: b >> 5 == 0b110)
utf8_three = p_byte_pred(lambda b: b >> 4 == 0b1110)
utf8_four = p_byte_pred(lambda b: b >> 3 == 0b11110)
utf8_tail = p_byte_pred(lambda b: b >> 6 == 0b10)
return Pattern.choice(
(
printable,
utf8_two + utf8_tail,
utf8_three + utf8_tail + utf8_tail,
utf8_four + utf8_tail + utf8_tail + utf8_tail,
)
)
@apply
def p_digit() -> Pattern:
return p_byte_pred(lambda b: ord("0") <= b <= ord("9"))
@apply
def p_number() -> Pattern:
return p_digit.some()
def p_string(bs: bytes | str) -> Pattern:
if isinstance(bs, str):
bs = bs.encode()
table = [{b: i + 1} for i, b in enumerate(bs)] + [{}]
return Pattern(table, {len(table) - 1: tuple()})
# ------------------------------------------------------------------------------
# Coroutine
# ------------------------------------------------------------------------------
R = TypeVar("R")
ExcInfo = Tuple[Any, Any, Any] # sys.exc_info
Cont = Callable[[Callable[[R], T], Callable[[ExcInfo], T]], T]
def coro(fn: Callable[..., Generator]) -> Callable[..., Cont[R, T]]:
"""Create lite double barrel continuation from generator
- continuation type is `ContT r a = ((a -> r), (e -> r)) -> r`
- fn must be a generator yielding continuation
- coro(fn) will return continuation
"""
def coro_fn(*args: Any, **kwargs: Any) -> Cont[R, T]:
def cont_fn(on_done: Callable[[R], T], on_error: Callable[[ExcInfo], T]) -> T:
def coro_next(
ticket: int,
is_error: bool,
result: Optional[ExcInfo | R] = None,
) -> T:
nonlocal gen_ticket
if gen_ticket != ticket:
raise RuntimeError(
f"coro_next called with incorrect ticket: "
f"{ticket} != {gen_ticket} "
f"[{fn}(*{args}, **{kwargs})]",
)
gen_ticket += 1
try:
cont = gen.throw(*result) if is_error else gen.send(result)
except StopIteration as ret:
gen.close()
return on_done(ret.value)
except Exception:
gen.close()
return on_error(sys.exc_info())
else:
return cont(
partial(coro_next, ticket + 1, False),
partial(coro_next, ticket + 1, True),
)
try:
gen = fn(*args, **kwargs)
gen_ticket = 0
return coro_next(0, False, None)
except Exception:
return on_error(sys.exc_info())
return cont_fn
return coro_fn
def cont(in_done, in_error=None) -> Cont[R, None]:
"""Create continuation from (done, error) pair"""
def cont(out_done: Callable[[R], T], out_error: Callable[[ExcInfo], T]) -> None:
def safe_out_done(result=None):
return out_done(result)
in_done(safe_out_done)
if in_error is not None:
def safe_out_error(error=None):
if error is None:
try:
raise asyncio.CancelledError()
except Exception:
out_error(sys.exc_info())
else:
out_error(error)
in_error(safe_out_error)
return cont
def cont_print_exception(name, source, error):
et, eo, tb = error
message = io.StringIO()
message.write(f'coroutine <{name or ""}> at:\n')
message.write(source)
message.write(f"failed with {et.__name__}: {eo}\n")
traceback.print_tb(tb, file=message)
sys.stderr.write(message.getvalue())
def cont_run(cont, on_done=None, on_error=None, name=None):
if on_error is None:
source = traceback.format_stack()[-2]
on_error = partial(cont_print_exception, name, source)
return cont(const(None) if on_done is None else on_done, on_error)
def cont_any(*conts):
"""Create continuation which is equal to first completed continuation"""
def cont_any(out_done, out_error):
@thunk
def callback(is_error, result=None):
return out_error(result) if is_error else out_done(result)
on_error = partial(callback, True)
on_done = partial(callback, False)
for cont in conts:
cont(on_done, on_error)
return cont_any
def cont_finally(cont, callback):
"""Add `finally` callback to continuation
Executed on_{done|error} before actual continuation
"""
def cont_finally(out_done, out_error):
def with_callback(fn, arg):
callback()
return fn(arg)
return cont(partial(with_callback, out_done), partial(with_callback, out_error))
return cont_finally
def cont_from_future(future):
"""Create continuation from `Future` object"""
def cont_from_future(out_done, out_error):
def done_callback(future):
try:
out_done(future.result())
except Exception:
out_error(sys.exc_info())
future.add_done_callback(done_callback)
return cont_from_future
# ------------------------------------------------------------------------------
# Events
# ------------------------------------------------------------------------------
Handler = Callable[[T], bool]
class EventBase(Generic[T]):
def __call__(self, event: T) -> EventBase[T]:
"""Raise provided event"""
raise NotImplementedError("This event does support raising events")
def on(self, handler: Handler[T]) -> Handler[T]:
"""Subscribe handler to event
If handler returns True it will keep received events until it returns false.
"""
raise NotImplementedError("This event does not support subscribing")
def on_once(self, handler: Handler[T]) -> Handler[T]:
"""Subscribe handler to receive just one event"""
def handler_once(event):
handler(event)
return False
return self.on(handler_once)
def __await__(self) -> Generator[Any, None, T]:
"""Await for next event"""
future: asyncio.Future[T] = asyncio.get_running_loop().create_future()
self.on_once(future.set_result)
return future.__await__()
def __aiter__(self):
return EventIterator(self)
class EventIterator:
"""Asynchronous iterator created by EventBase::__aiter__"""
__slots__ = ("queue", "event")
def __init__(self, event):
self.event = event
self.queue = deque()
@self.event.on
def _process_item(item):
self.queue.append(item)
return True
def __aiter__(self):
return self
async def __anext__(self):
while not self.queue:
await self.event
item = self.queue.popleft()
if item is None:
raise StopAsyncIteration()
return item
class Event(EventBase[T]):
__slots__ = ("_handlers",)
def __init__(self):
self._handlers = []
def __call__(self, event: T) -> Event[T]:
handlers, self._handlers = self._handlers, []
for handler in handlers:
if handler(event):
self._handlers.append(handler)
return self
def on(self, handler: Handler[T]) -> Handler[T]:
self._handlers.append(handler)
return handler
class EventBuffered(EventBase[T]):
"""This implementation of even ensures that at least on handler handled event"""
__slots__ = ("_handlers", "_queue")
def __init__(self) -> None:
self._handlers: List[Handler[T]] = []
self._queue: Deque[T] = deque()
self._handling_events = False
def __call__(self, event: T) -> EventBase[T]:
self._queue.append(event)
self._handle_events()
return self
def on(self, handler: Handler[T]) -> Handler[T]:
self._handlers.append(handler)
self._handle_events()
return handler
def _handle_events(self) -> None:
if self._handling_events:
return
try:
self._handling_evens = True
while self._queue and self._handlers:
event = self._queue.popleft()
handlers, self._handlers = self._handlers, []
for handler in handlers:
if handler(event):
self._handlers.append(handler)
finally:
self._hanlding_events = False
class EventFramed(EventBase[T]):
"""Create buffered frame reader from file and decoder
Once stream is stopped (either by `stop` method or by processing all input)
it will fire `None` event. Nothing is read from the stream until `start` is
called or context entered.
Decoder is a function `Option[bytes] -> List[Frame]`, `None` argument indicates
last chunk, and decoder must flush all remaining content.
"""
__slots__ = ("fd", "decoder", "loop", "running", "buffered")
def __init__(self, file, decoder, loop=None):
super().__init__()
self.loop = loop or asyncio.get_running_loop()
self.fd: int = file if isinstance(file, int) else file.fileno()
self.decoder = decoder
self.buffered = EventBuffered()
self.running: bool = False
def on(self, handler: Handler[T]) -> Handler[T]:
self.buffered.on(handler)
return handler
def start(self) -> None:
running, self.running = self.running, True
if running:
return
os.set_blocking(self.fd, False)
self.loop.add_reader(self.fd, self._read_callback)
def stop(self) -> None:
running, self.running = self.running, False
if not running:
return
self.loop.remove_reader(self.fd)
os.set_blocking(self.fd, True)
self.buffered(None) # indicate last event
def __enter__(self) -> EventFramed[T]:
self.start()
return self
def __exit__(self, et: Any, eo: Any, tb: Any) -> bool:
self.stop()
return False
def _read_callback(self):
try:
chunk = os.read(self.fd, 4096)
if not chunk:
for frame in self.decoder(None):
self.buffered(frame)
self.stop()
return
except BlockingIOError:
pass
except Exception:
traceback.print_exc(file=sys.stderr)
self.stop()
else:
for frame in self.decoder(chunk):
self.buffered(frame)
class EventDone(EventBase[T]):
__slots__ = ("_value",)
def __init__(self, value: T) -> None:
self._value = value
def __call__(self, event: T) -> None:
raise ValueError("EventDone can not be raise")
def on(self, handler: Callable[[T], bool]) -> EventBase[T]:
handler(self._value)
return self
# ------------------------------------------------------------------------------
# Scorers
# ------------------------------------------------------------------------------
Score = Tuple[float, Optional[List[int]]]
Scorer = Callable[[str, str], Score]
@apply
def _fuzzy_scorer():
"""Fuzzy matching for `fzy` utility
source: https://github.com/jhawthorn/fzy/blob/master/src/match.c
"""
SCORE_MIN = float("-inf")
SCORE_MAX = float("inf")
SCORE_GAP_LEADING = -0.005
SCORE_GAP_TRAILING = -0.005
SCORE_GAP_INNER = -0.01
SCORE_MATCH_CONSECUTIVE = 1.0
def char_range_with(c_start, c_stop, v, d):
d = d.copy()
d.update((chr(c), v) for c in range(ord(c_start), ord(c_stop) + 1))
return d
lower_with = partial(char_range_with, "a", "z")
upper_with = partial(char_range_with, "A", "Z")
digit_with = partial(char_range_with, "0", "9")
SCORE_MATCH_SLASH = 0.9
SCORE_MATCH_WORD = 0.8
SCORE_MATCH_CAPITAL = 0.7
SCORE_MATCH_DOT = 0.6
BONUS_MAP = {
"/": SCORE_MATCH_SLASH,
"-": SCORE_MATCH_WORD,
"_": SCORE_MATCH_WORD,
" ": SCORE_MATCH_WORD,
".": SCORE_MATCH_DOT,
}
BONUS_STATES = [{}, BONUS_MAP, lower_with(SCORE_MATCH_CAPITAL, BONUS_MAP)]
BONUS_INDEX = digit_with(1, lower_with(1, upper_with(2, {})))
def bonus(haystack: str) -> List[float]:
"""Additional bonus based on previous char in haystack"""
c_prev = "/"
bonus = []
for c in haystack:
bonus.append(BONUS_STATES[BONUS_INDEX.get(c, 0)].get(c_prev, 0))
c_prev = c
return bonus
def subsequence(needle: str, haystack: str) -> bool:
"""Check if needle is subsequence of haystack"""
needle, haystack = needle.lower(), haystack.lower()
if not needle:
return True
offset = 0
for char in needle:
offset = haystack.find(char, offset) + 1
if offset <= 0:
return False
return True
def score(needle: str, haystack: str) -> Score:
"""Calculate score, and positions of haystack"""
n, m = len(needle), len(haystack)
bonus_score = bonus(haystack)
needle, haystack = needle.lower(), haystack.lower()
if n == 0 or n == m:
return SCORE_MAX, list(range(n))
D = [[0.0] * m for _ in range(n)] # best score ending with `needle[:i]`
M = [[0.0] * m for _ in range(n)] # best score for `needle[:i]`
for i in range(n):
prev_score = SCORE_MIN
gap_score = SCORE_GAP_TRAILING if i == n - 1 else SCORE_GAP_INNER
for j in range(m):
if needle[i] == haystack[j]:
score = SCORE_MIN
if i == 0:
score = j * SCORE_GAP_LEADING + bonus_score[j]
elif j != 0:
score = max(
M[i - 1][j - 1] + bonus_score[j],
D[i - 1][j - 1] + SCORE_MATCH_CONSECUTIVE,
)
D[i][j] = score
M[i][j] = prev_score = max(score, prev_score + gap_score)
else:
D[i][j] = SCORE_MIN
M[i][j] = prev_score = prev_score + gap_score
match_required = False
position = [0] * n
i, j = n - 1, m - 1
while i >= 0:
while j >= 0:
if (match_required or D[i][j] == M[i][j]) and D[i][j] != SCORE_MIN:
match_required = (
i > 0
and j > 0
and M[i][j] == D[i - 1][j - 1] + SCORE_MATCH_CONSECUTIVE
)
position[i] = j
j -= 1
break
else:
j -= 1
i -= 1
return M[n - 1][m - 1], position
def fuzzy_scorer(needle: str, haystack: str) -> Score:
if subsequence(needle, haystack):
return score(needle, haystack)
else:
return SCORE_MIN, None
return fuzzy_scorer
def fuzzy_scorer(needle: str, haystack: str) -> Score:
return _fuzzy_scorer(needle, haystack)
def substr_scorer(needle: str, haystack: str) -> Score:
positions, offset = [], 0
needle, haystack = needle.lower(), haystack.lower()
for needle in needle.split(" "):
if not needle:
continue
offset = haystack.find(needle, offset)
if offset < 0:
return float("-inf"), None
needle_len = len(needle)
positions.extend(range(offset, offset + needle_len))
offset += needle_len
if not positions:
return 0, positions
match_len = positions[-1] + 1 - positions[0]
return -match_len + 2 / (positions[0] + 1) + 1 / (positions[-1] + 1), positions
SCORER_DEFAULT = "fuzzy"
SCORERS = {"fuzzy": fuzzy_scorer, "substr": substr_scorer}
class RankResult(NamedTuple):
score: float
index: int
haystack: str
positions: Optional[List[int]]
def to_text(self, theme=None):
theme = theme or THEME_DEFAULT
if isinstance(self.haystack, Candidate):
return self.haystack.with_positions(self.positions).to_text(theme)
else:
return Text(self.haystack).mark_mask(theme.match, self.positions)
def _rank_task(
scorer: Scorer,
needle: str,
haystack: List[str],
offset,
keep_order: bool,
) -> List[RankResult]:
result = []
for index, item in enumerate(haystack):
score, positions = scorer(needle, str(item))
if positions is None:
continue
result.append(RankResult(score, index + offset, item, positions))
if not keep_order:
result.sort(reverse=True) # from higher score to lower
return result
async def rank(
scorer: Scorer,
needle: str,
haystack: List[str],
*,
keep_order: Optional[bool] = None,
executor=None,
loop=None,
):
"""Score haystack against needle in executor and return sorted result"""
loop = loop or asyncio.get_running_loop()
batch_size = 4096
haystack = haystack if isinstance(haystack, list) else list(haystack)
batches = await asyncio.gather(
*(
loop.run_in_executor(
executor,
_rank_task,
scorer,
needle,
haystack[offset : offset + batch_size],
offset,
keep_order,
)
for offset in range(0, len(haystack), batch_size)
),
)
if not keep_order:
# from higher score to lower
results = list(heapq.merge(*batches, reverse=True))
else:
results = [item for batch in batches for item in batch]
return results
# ------------------------------------------------------------------------------
# TTY
# ------------------------------------------------------------------------------
TTY_KEY = 0
TTY_CHAR = 1
TTY_CPR = 2
TTY_SIZE = 3
TTY_CLOSE = 4
TTY_MOUSE = 5
TTY_SIZE_PIXELS = 6
TTY_SIZE_CELLS = 7
KEY_MODE_SHIFT = 0b001
KEY_MODE_ALT = 0b010
KEY_MODE_CTRL = 0b100
KEY_MODE_PRESS = 0b1000
KEY_MODE_BITS = 4
KEY_MOUSE_LEFT = 1
KEY_MOUSE_RIGHT = 2
KEY_MOUSE_MIDDLE = 3
KEY_MOUSE_WHEEL_UP = 4
KEY_MOUSE_WHEEL_DOWN = 5
class TTYEvent(NamedTuple):
type: int
attrs: Sequence[Any]
def __repr__(self):
type, attrs = self
if type == TTY_KEY:
key_name, mode = attrs
names = []
for mask, mode_name in (
(KEY_MODE_ALT, "alt"),
(KEY_MODE_CTRL, "ctrl"),
(KEY_MODE_SHIFT, "shift"),
):
if mode & mask:
names.append(mode_name)
names.append(key_name)
return f'Key({"-".join(names)})'
elif type == TTY_CHAR:
return f"Char({attrs})"
elif type == TTY_CPR:
line, column = attrs
return f"Postion(line={line}, column={column})"
elif type == TTY_CLOSE:
return "Close()"
elif type == TTY_SIZE:
rows, columns = attrs
return f"Size(rows={rows}, columns={columns})"
elif type == TTY_MOUSE:
button, mode, (line, column) = attrs
names = []