forked from socketteer/loom
-
Notifications
You must be signed in to change notification settings - Fork 0
/
model.py
2540 lines (2161 loc) · 92.4 KB
/
model.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
import functools
import os
import threading
import time
import math
import uuid
from asyncio import Queue
from pprint import pprint
import bisect
import numpy as np
from collections import defaultdict, ChainMap
from multiprocessing.pool import ThreadPool
import codecs
import json
from util.frames_util import frame_merger, frame_merger_append, frame_merger_override
from copy import deepcopy
import jsonlines
from gpt import openAI_generate, search, gen
from util.util import json_create, timestamp, json_open, clip_num, index_clip, diff
from util.util_tree import fix_miro_tree, flatten_tree, node_ancestry, in_ancestry, get_inherited_attribute, \
subtree_list, generate_conditional_tree, filtered_children, \
new_node, add_immutable_root, make_simple_tree, fix_tree, ancestry_in_range, ancestry_plaintext, ancestor_text_indices, \
node_index, ancestor_text_list, tree_subset
from util.gpt_util import conditional_logprob, tokenize_ada, prompt_probs, logprobs_to_probs, parse_logit_bias, parse_stop
from util.multiverse_util import greedy_word_multiverse
from util.node_conditions import conditions, condition_lambda
# Calls any callbacks associated with the wrapped function
# class must have a defaultdict(list)[func_name] = [*callbacks]
# https://stackoverflow.com/questions/11731136/class-method-decorator-with-self-arguments
# TODO Flag to skip callbacks
def event(func):
@functools.wraps(func)
def wrapper(self, *args, **kwargs):
output = func(self, *args, **kwargs)
[callback(**kwargs) if kwargs else callback() for callback in self.callbacks[func.__name__]]
return output
return wrapper
DEFAULT_PREFERENCES = {
# Nav tree
'reverse': False,
# Navigation
'walk': 'descendents', # 'leaves', 'uniform'
'nav_tag': 'bookmark',
# Story frame
'editable': True,
'history_conflict': 'overwrite', # 'branch', 'ask', 'forbid'
'coloring': 'edit', # 'read', 'none'
'bold_prompt': True,
'font_size': 12,
'line_spacing': 8,
'paragraph_spacing': 10,
# Saving
'revision_history': False,
'autosave': False,
#'save_counterfactuals': False,
'model_response': 'backup', #'discard', #'save'
# generation data
'prob': True,
# darkmode
}
DEFAULT_WORKSPACE = {
'side_pane': {'open': True,
'modules': ["minimap"]},
'bottom_pane': {'open': False,
'modules': []},
'buttons': ["Edit", "Delete", "Generate", "New Child", "Next", "Prev", "Visualize", "Wavefunction", "Map"],
'alt_textbox': False,
'show_search': False
}
DEFAULT_MODULE_SETTINGS = {
'edit': {'node_id': None,},
'input': {'auto_response': True, 'submit_template': "{input}"},
'minimap': {'level_offset': 70,
'leaf_offset': 40,
'node_radius': 10,
'line_thickness': 2,
'horizontal': False,
'prune_mode': 'open_in_nav', #'in_nav', 'ancestry_dist', 'wavefunction_collapse', 'selected_dist', 'all'
'path_length_limit': 10,
},
'read children': {'filter': 'in_nav', #'all', 'uncleared', or name of tag TODO hide condition
'show_continue': 'no alternatives', #no choice, always, never, or name of tag
'show_options': 'always'}, #always, never, or name of tag
'children': {'toggle_tag': 'bookmark'}
}
DEFAULT_GENERATION_SETTINGS = {
'num_continuations': 4,
'temperature': 0.9,
'top_p': 1,
'response_length': 100,
'prompt_length': 6000,
'logprobs': 0,
#"adaptive": False,
"model": "davinci",
"stop": '', # separated by '|'
"start": '',
"restart": '',
'preset': 'None',
'global_context': '',
'logit_bias': '',
'template': 'Default',
}
DEFAULT_MODEL_CONFIG = {
'models': {
'ada': {
'model': 'ada',
'type': 'openai',
'api_base': 'https://api.openai.com/v1'
},
'babbage': {
'model': 'babbage',
'type': 'openai',
'api_base': 'https://api.openai.com/v1'
},
# 'content-filter-alpha-c4': {'type': 'openai'},
# 'content-filter-dev': {'type': 'openai'},
'curie': {
'model': 'curie',
'type': 'openai',
'api_base': 'https://api.openai.com/v1'
},
# 'cursing-filter-v6': {'type': 'openai'},
'davinci': {
'model': 'davinci',
'type': 'openai',
'api_base': 'https://api.openai.com/v1'
},
'text-davinci-002': {
'model': 'text-davinci-002',
'type': 'openai',
'api_base': 'https://api.openai.com/v1'
},
'text-davinci-003': {
'model': 'text-davinci-003',
'type': 'openai',
'api_base': 'https://api.openai.com/v1'
},
# 'code-davinci-002': {
# 'model': 'code-davinci-002',
# 'type': 'openai',
# 'api_base': 'https://api.openai.com/v1'
# },
'instruct-curie-beta': {
'model': 'instruct-curie-beta',
'type': 'openai',
'api_base': 'https://api.openai.com/v1'
},
'instruct-davinci-beta': {
'model': 'instruct-davinci-beta',
'type': 'openai',
'api_base': 'https://api.openai.com/v1'
},
'gpt-3.5-turbo': {
'model': 'gpt-3.5-turbo',
'type': 'openai-chat',
'api_base': 'https://api.openai.com/v1'
},
'gpt-4': {
'model': 'gpt-4',
'type': 'openai-chat',
'api_base': 'https://api.openai.com/v1'
},
'j1-large': {
'model': 'j1-large',
'type': 'ai21',
'api_base': None,
},
'j1-jumbo': {
'model': 'j1-jumbo',
'type': 'ai21',
'api_base': None,
},
'gpt-neo-1-3b': {
'model': 'gpt-neo-1.3B',
'type': 'gooseai',
'api_base': None,
},
'gpt-neo-2-7b': {
'model': 'gpt-neo-2.7B',
'type': 'gooseai',
'api_base': None,
},
'gpt-j-6b': {
'model': 'gpt-j-6B',
'type': 'gooseai',
'api_base': None,
},
'gpt-neo-20b': {
'model': 'gpt-neo-20B',
'type': 'gooseai',
'api_base': None,
},
},
# 'api_base': None,
# 'api_key': os.environ.get("API_KEY", ''),
# 'OPENAI_API_KEY': os.environ.get("OPENAI_API_KEY", None),
# 'AI21_API_KEY': os.environ.get("AI21_API_KEY", None),
# 'GOOSEAI_API_KEY': os.environ.get("GOOSEAI_API_KEY", None),
}
DEFAULT_INLINE_GENERATION_SETTINGS = {
"model": "davinci",
"num_continuations": 8,
"temperature": 1,
"top_p": 1,
"response_length": 60,
"prompt_length": 6000,
"logprobs": 0,
"stop": "\\n|.|?|!",
"start": "",
"restart": "",
"preset": "Single Line",
"global_context": "",
"logit_bias": "",
"template": "Default",
}
DEFAULT_VISUALIZATION_SETTINGS = {
'text_width': 450,
'leaf_distance': 200,
'level_distance': 150,
'text_size': 10,
'horizontal': True,
'display_text': True,
'show_buttons': True,
'chapter_mode': False
# show chapters only
# show canonical only
# highlight canonical
# auto collapse
}
DEFAULT_VARS = {}
# new tags should be added to the root level by default
DEFAULT_TAGS = {
"bookmark": {
"name": "bookmark",
"scope": "node",
"hide": False,
"show_only": False,
"toggle_key": "b",
"icon": "bookmark-black",
},
"canonical": {
"name": "canonical",
"scope": "ancestry",
"hide": False,
"show_only": False,
"toggle_key": '*',
"icon": "book-white",
},
"archived": {
"name": "archived",
"scope": "node",
"hide": True,
"show_only": False,
"toggle_key": "!",
"icon": "archive-yellow",
},
"note": {
"name": "note",
"scope": "node",
"hide": True,
"show_only": False,
"toggle_key": "#",
"icon": "note-black",
},
"pinned": {
"name": "pinned",
"scope": "node",
"hide": False,
"show_only": False,
"toggle_key": "^",
"icon": "pin-red",
}
}
EMPTY_TREE = {
"root": {
"mutable": False,
"visited": True,
"text": "",
"children": [
{
"text": "",
"children": [],
}
],
}
}
class TreeModel:
def __init__(self, root):
self.app = root
self.app.bind("<<TreeUpdated>>", lambda _: self.tree_updated())
self.app.bind("<<NewNodes>>", lambda _: self.edit_new_nodes())
# All variables initialized below
self.tree_filename = None
# tree with all data
self.tree_raw_data = None
# CALCULATED {node_id: node}
self.tree_node_dict = None
# {chapter_id: chapter}
self.chapters = None
#self.memories = None
self.summaries = None
self.checkpoint = None
self.canonical = None
#self.tags = None
self.model_responses = None
self.selected_node_id = None
self.callbacks = defaultdict(list)
self.conditions = defaultdict(list)
self.new_nodes = []
self.OPENAI_API_KEY = None
self.AI21_API_KEY = None
self.GOOSEAI_API_KEY = None
@property
def visualization_settings(self):
return self.tree_raw_data.get("visualization_settings") \
if self.tree_raw_data and "visualization_settings" in self.tree_raw_data \
else DEFAULT_VISUALIZATION_SETTINGS
@property
def tags(self):
return self.tree_raw_data.get("tags") \
if self.tree_raw_data and "tags" in self.tree_raw_data \
else DEFAULT_TAGS
@property
def model_config(self):
return self.state["model_config"]
@property
def generation_settings(self):
return self.state['generation_settings']
@property
def inline_generation_settings(self):
return self.state['inline_generation_settings']
@property
def preferences(self):
return self.state['preferences']
@property
def module_settings(self):
return self.state['module_settings']
@property
def workspace(self):
return self.state['workspace']
@property
def memories(self):
return self.state['memories']
@property
def vars(self):
return self.state['vars']
# user frame
@property
def user_preferences(self):
return self.user_frame.get("preferences") \
if "preferences" in self.user_frame \
else {}
@property
def user_generation_settings(self):
return self.user_frame.get("generation_settings") \
if "generation_settings" in self.user_frame \
else {}
@property
def user_inline_generation_settings(self):
return self.user_frame.get("inline_generation_settings") \
if "inline_generation_settings" in self.user_frame \
else {}
@property
def user_module_settings(self):
return self.user_frame.get("module_settings") \
if "module_settings" in self.user_frame \
else {}
@property
def user_workspace(self):
return self.user_frame.get("workspace") \
if "workspace" in self.user_frame \
else {}
@property
def user_frame(self):
return self.tree_raw_data.get("frame") \
if self.tree_raw_data and "frame" in self.tree_raw_data \
else {}
@property
def state(self):
state = {}
state["memories"] = {}
state["vars"] = deepcopy(DEFAULT_VARS)
state["preferences"] = deepcopy(DEFAULT_PREFERENCES)
state["generation_settings"] = deepcopy(DEFAULT_GENERATION_SETTINGS)
state["inline_generation_settings"] = deepcopy(DEFAULT_INLINE_GENERATION_SETTINGS)
state["workspace"] = deepcopy(DEFAULT_WORKSPACE)
state["module_settings"] = deepcopy(DEFAULT_MODULE_SETTINGS)
state["model_config"] = deepcopy(DEFAULT_MODEL_CONFIG)
frames = self.accumulate_frames(self.selected_node) if self.selected_node else {}
frame_merger.merge(state, frames)
frame_merger.merge(state, self.user_frame)
return state
def name(self):
return os.path.splitext(os.path.basename(self.tree_filename))[0] if self.tree_filename else 'Untitled'
#################################
# Frames
#################################
"""
Frames are updates to the state applied by nodes in the tree.
At any node in the multiverse, the state of the tree is the accumulation of all frames from its ancestry,
applied in chronological order (the future can override the past).
A frame is a dictionary which is merged into the state of the tree using deepmerge.
"""
def accumulate_frames(self, node):
frames = []
for ancestor in self.ancestry(node):
if 'frame' in ancestor:
frames.append(ancestor['frame'])
frame_accumulator = {}
for frame in frames:
frame_merger.merge(frame_accumulator, deepcopy(frame))
return frame_accumulator
def set_frame(self, frame_parent, frame):
frame_parent['frame'] = deepcopy(frame)
# def overwrite_frame(self, frame, new_frame):
# frame = deepcopy(new_frame)
def update(self, dict, update, append=False):
if append:
frame_merger_append.merge(dict, deepcopy(update))
else:
frame_merger.merge(dict, deepcopy(update))
def set_path(self, dict, value, path):
update_path = dict
for key in path[:-1]:
if key not in update_path:
update_path[key] = {}
update_path = update_path[key]
update_path[path[-1]] = deepcopy(value)
def get_path(self, dict, path):
update_path = dict
for key in path:
if key not in update_path:
return None
update_path = update_path[key]
return update_path
def update_frame(self, node, update, append=False):
if 'frame' in node:
self.update(node['frame'], update, append)
else:
node['frame'] = deepcopy(update)
self.tree_updated(write=False)
def get_frame(self, node):
return node.get('frame', {})
def set_user_frame(self, state):
self.tree_raw_data['frame'] = deepcopy(state)
def update_user_frame(self, update, append=False):
if 'frame' in self.tree_raw_data:
self.update(self.tree_raw_data['frame'], update, append)
else:
self.tree_raw_data['frame'] = deepcopy(update)
self.tree_updated(write=False)
# TODO merge with frame
def set_user_frame_partial(self, value, path):
if 'frame' not in self.tree_raw_data:
self.tree_raw_data['frame'] = {}
self.set_path(self.tree_raw_data['frame'], value, path)
def set_frame_partial(self, node, value, path):
if 'frame' not in node:
node['frame'] = {}
self.set_path(node['frame'], value, path)
def clear_user_frame(self):
self.set_user_frame({})
self.tree_updated(write=False)
def write_user_frame_to_node(self):
# saves current user settings as a frame at the selected node
self.set_frame(self.selected_node, self.user_frame)
self.clear_user_frame()
#################################
# Hooks
#################################
def register_callback(self, func, callback):
self.callbacks[func.__name__].append(callback)
# Decorator calls callbacks
@event
def tree_updated(self, rebuild_dict=True, **kwargs):
if self.tree_raw_data and rebuild_dict:
self.rebuild_tree()
# def tree_updated_silent(self):
# self.rebuild_tree()
@event
def rebuild_tree(self):
add_immutable_root(self.tree_raw_data)
self.tree_node_dict = {d["id"]: d for d in flatten_tree(self.tree_raw_data["root"])}
fix_miro_tree(self.nodes)
@event
def edit_new_nodes(self):
print('new nodes:', self.new_nodes)
self.tree_updated()
time.sleep(0.5)
for node_id in self.new_nodes[0]:
self.node(node_id)['mutable'] = True
self.tree_updated(edit=self.new_nodes[0])
del self.new_nodes[0]
@event
def pre_selection_updated(self, **kwargs):
pass
@event
def selection_updated(self, **kwargs):
pass
@event
def io_update(self):
pass
#################################
# Access
#################################
def root(self):
return self.tree_raw_data['root']
# return the node in tree_node_dict with id
def node(self, node_id):
# if type(node_id).__name__ != 'str':
# breakpoint()
return self.tree_node_dict.get(node_id, None)
# Get a nodes chapter by finding its chapter or its nearest parent's chapter
def chapter(self, node):
chapter_id = get_inherited_attribute("chapter_id", node, self.tree_node_dict)
return self.chapters[chapter_id] if chapter_id else None
@property
def selected_node(self):
if self.tree_node_dict is None or self.selected_node_id not in self.tree_node_dict:
return None
# if self.selected_node_id is None or self.selected_node_id not in self.tree_node_dict:
# self.select_node(self.nodes[0]["id"])
return self.node(self.selected_node_id)
@property
def selected_chapter(self):
return self.chapter(self.selected_node) if self.selected_node is not None else None
@property
def nodes(self):
return list(self.tree_node_dict.values()) if self.tree_node_dict else None
@property
def tree_traversal_idx(self):
return self.nodes.index(self.selected_node)
def nodes_list(self, filter=None):
#tree = tree if tree else self.tree_node_dict
if not filter:
return list(self.tree_node_dict.values())
else:
return [n for n in list(self.tree_node_dict.values()) if filter(n)]
def nodes_dict(self, filter=None):
nodes = self.nodes_list(filter)
return {d['id']: d for d in nodes}
def traversal_idx(self, node, filter=None):
#tree = tree if tree else self.tree_node_dict
nodes = self.nodes_list(filter) if filter else self.nodes
return nodes.index(node)
# for i, node in enumerate(nodes):
# if node['id'] == node_id:
# return i
def filter_indices(self, nodes, filter=None):
if filter:
return {idx: d for idx, d in enumerate(nodes) if filter(d)}
else:
return {idx: d for idx, d in enumerate(nodes)}
# Returns [{chapter: {}, id, children: []}, ...]
def _build_chapter_trees(self, node):
# Returns a 1 element list if the node is a chapter, else a list of children chapters
children_chapter_lists = [self._build_chapter_trees(child) for child in node["children"]]
children_chapters = [item for sublist in children_chapter_lists for item in sublist]
if "chapter_id" in node:
chapter = self.chapters[node["chapter_id"]]
return [{
"chapter": chapter,
"id": chapter["id"],
"children": children_chapters
}]
else:
return children_chapters
# Returns tuple of
# [ {chapter{}, id, parent_id, children[]}, ... ]
# {chapter_id: {chapter: {id:1, title:""}, id:1, parent_id, children[]}]
def build_chapter_trees(self):
node = self.tree_raw_data["root"]
chapter_trees = self._build_chapter_trees(node)
flat_trees = [flatten_tree(chapter_tree) for chapter_tree in chapter_trees]
flat_maps = [{d["id"]: d for d in flat_tree} for flat_tree in flat_trees]
chapter_tree_nodes = dict(ChainMap(*flat_maps))
return chapter_trees, chapter_tree_nodes
#################################
# Ancestry
#################################
def ancestry(self, node, root=None):
if not root:
return node_ancestry(node, self.tree_node_dict)
else:
return ancestry_in_range(root=root, node=node, node_dict=self.tree_node_dict)
def ancestry_text(self, node, root=None):
ancestry = self.ancestry(node, root)
return ancestry_plaintext(ancestry, text_callback=self.text)
def ancestor_text_list(self, node, root=None):
ancestry = self.ancestry(node, root)
return ancestor_text_list(ancestry, text_callback=self.text)
def ancestor_text_indices(self, node, root=None):
ancestry = self.ancestry(node, root)
return ancestor_text_indices(ancestry, text_callback=self.text)
def chain_uninterrupted(self, start, end):
# returns true if chain of nodes has no other siblings
chain = ancestry_in_range(start, end, self.tree_node_dict)
for ancestor in chain[:-1]:
if len(ancestor["children"]) > 1:
return False
return True
#################################
# Subtree
#################################
def children_text_list(self, node, filter=None):
return [self.text(child) for child in filtered_children(node, filter)]
def children_text(self, node, delimiter='\n', filter=None):
return delimiter.join(self.children_text_list(node, filter))
#################################
# Traversal
#################################
# Update the selected node, the nav tree selection, and possibly the position in the tree traversal
def select_node(self, node_id, fire_callbacks=True, reveal_node=False, **kwargs):
if self.selected_node_id != node_id and self.tree_node_dict and node_id in self.tree_node_dict:
self.pre_selection_updated(**kwargs)
self.selected_node_id = node_id
self.selected_node["visited"] = True
self.tree_raw_data["selected_node_id"] = self.selected_node_id
if reveal_node:
self.reveal_nodes([self.selected_node])
# Open all parents but not the node itself
ancestors = node_ancestry(self.selected_node, self.tree_node_dict)
for ancestor in ancestors[:-1]:
ancestor["open"] = True
# Always open the root
self.tree_raw_data["root"]["open"] = True
if fire_callbacks:
self.selection_updated(**kwargs)
return self.selected_node
#TODO move out of model
# def traverse_tree(self, offset=1, visible_only=True):
# if self.tree_node_dict:
# new_node_id = self.next_id(offset, visible_only)
# return self.select_node(new_node_id)
# this only works if node is in filter
def next_id(self, node, offset=1, filter=None):
nodes = self.nodes_list(filter)
traversal_idx = self.traversal_idx(node, filter)
new_idx = clip_num(traversal_idx + offset, 0, len(nodes) - 1)
return nodes[new_idx]["id"]
# return id of next node which satisfies filter condition
def find_next(self, node, filter=None, visible_filter=None):
nodes = self.nodes_list(visible_filter) if visible_filter else self.nodes
current_idx = self.traversal_idx(node, visible_filter)
true_indices = self.filter_indices(nodes, filter)
if len(true_indices) < 1:
return
try:
go_to_true = next(i for i, idx in enumerate(true_indices.keys()) if idx > current_idx)
except StopIteration:
go_to_true = 0
return list(true_indices.values())[go_to_true]["id"]
def find_prev(self, node, filter=None, visible_filter=None):
nodes = self.nodes_list(visible_filter) if visible_filter else self.nodes
current_idx = self.traversal_idx(node, visible_filter)
true_indices = self.filter_indices(nodes, filter)
if len(true_indices) < 1:
return
earlier_true = list(i for i, idx in enumerate(true_indices.keys()) if idx < current_idx)
go_to_true = earlier_true[-1] if len(earlier_true) > 0 else -1
return list(true_indices.values())[go_to_true]["id"]
def parent(self, node):
return self.node(node['parent_id']) if 'parent_id' in node else None
# return child
def child(self, node, child_num, filter=None):
children = filtered_children(node, filter)
if len(children) > 0:
return index_clip(children, child_num)
else:
return None
# return next sibling
def sibling(self, node, offset=1, filter=None, wrap=True):
siblings = self.siblings(node, filter)
if node not in siblings:
new_idx = 0
else:
new_idx = (siblings.index(node) + offset) % len(siblings)
if not wrap and new_idx == 0:
return self.parent(node)
return siblings[new_idx]
def siblings(self, node, filter=None):
if not self.has_parent(node):
return None
parent = self.parent(node)
return filtered_children(parent, filter)
def siblings_index(self, node, filter=None):
if not self.has_parent(node):
return 0
parent = self.parent(node)
siblings = filtered_children(parent, filter)
if node in siblings:
return siblings.index(node)
else:
return len(siblings)
#################################
# Conditionals
#################################
def has_parent(self, node):
return 'parent_id' in node and node['parent_id']
def is_compound(self, node):
return 'masked_head' in node
def is_hoisted(self, node):
return node.get('hoisted', False)
def is_mutable(self, node):
return node.get('mutable', True)
def is_root(self, node):
return node == self.root()
def visible(self, node):
return self.visible_conditions()(node) or self.is_root(node) #or self.is_compound(node)
def id_visible(self, node_id):
return self.visible(self.node(node_id))
def is_AI_generated(self, node):
if 'meta' in node:
if 'source' in node['meta']:
return node["meta"]["source"] == "AI"
return False
def is_template(self, node):
return node.get('template', False)
def construct_node_condition(self, info_dict):
name = info_dict['name']
params = info_dict.get('params', {})
params['tree_node_dict'] = self.tree_node_dict
return lambda node: conditions[name](node=node, **params)
def generate_filtered_tree(self, root=None):
root = root if root else self.tree_raw_data["root"]
condition = self.visible_conditions()
if not condition:
return self.tree_node_dict
else:
return generate_conditional_tree(root, condition)
def visible_conditions(self):
and_conditions = []
or_conditions = []
for tag, attributes in self.tags.items():
if attributes['hide']:
and_conditions.append(lambda node, _tag=tag: not self.has_tag(node, _tag))
if attributes['show_only']:
or_conditions.append(lambda node, _tag=tag: self.has_tag(node, _tag))
return lambda node: condition_lambda(node, and_conditions, or_conditions)
#################################
# Updates
#################################
def node_creation_metadata(self, node, source='prompt'):
if 'meta' not in node:
node["meta"] = {}
node["meta"]["creation_timestamp"] = timestamp()
node["meta"]["source"] = source
# TODO replace with history
node["meta"]["modified"] = False
def create_child(self, parent, expand=True):
if not parent:
return
new_child = new_node()
parent["children"].append(new_child)
if expand:
new_child["open"] = True
self.rebuild_tree()
return new_child
# if refresh_nav:
# self.tree_updated(add=[new_child['id']])
# else:
# self.rebuild_tree()
# if update_selection:
# self.select_node(new_child["id"])
def create_sibling(self, node):
if not node:
return
parent = self.parent(node)
return self.create_child(parent=parent)
def create_parent(self, node):
if not node:
return
new_parent = {
"id": str(uuid.uuid1()),
"text": "",
"children": [node]
}
if "parent_id" not in node:
assert self.tree_raw_data["root"] == node
self.tree_raw_data["root"] = new_parent
else:
old_siblings = self.parent(node)["children"]
old_siblings[old_siblings.index(node)] = new_parent
new_parent["parent_id"] = node["parent_id"]
node["parent_id"] = new_parent["id"]
new_parent["open"] = True
self.rebuild_tree()
return new_parent
def merge_with_parent(self, node):
if not node:
return
assert 'parent_id' in node, self.is_mutable(node)
parent = self.parent(node)
assert self.is_mutable(parent)
parent["text"] += node["text"]
index_in_parent = parent["children"].index(node)
parent["children"][index_in_parent:index_in_parent + 1] = node["children"]
for i, c in enumerate(node["children"]):
# parent["children"].insert(index_in_parent+i, c)
c["parent_id"] = parent["id"]
self.rebuild_tree()
# if node == self.selected_node:
# self.select_node(parent["id"])
# if refresh_nav:
# self.tree_updated(add=[n['id'] for n in subtree_list(parent)])
# else:
# self.rebuild_tree()
def merge_with_children(self, node=None):
node = node if node else self.selected_node
assert self.is_mutable(node)
if not node:
return
children = node["children"]
for child in children:
child["text"] = node["text"] + child["text"]
self.delete_node(node, reassign_children=True)
# TODO indicate that change parent has been toggled
def change_parent(self, node, new_parent_id=None):
if not node:
return
if node["id"] == new_parent_id:
return
if "parent_id" not in node:
assert self.tree_raw_data["root"] == node
print('ERROR: node is root')
return
elif new_parent_id == node["parent_id"]:
return
new_parent = self.node(new_parent_id)
if in_ancestry(node, new_parent, self.tree_node_dict):
print('error: node is ancestor of new parent')
return
old_siblings = self.parent(node)["children"]
old_siblings.remove(node)
node["parent_id"] = new_parent_id
new_parent["children"].append(node)
# TODO does this cause bugs
self.rebuild_tree()
# adds node to ghostchildren of new ghostparent
def add_parent(self, node=None, new_ghostparent=None):
pass
# changes parent id to new main parent, adds node to new main parent's children list, removes node from old parent's
# children list and adds to ghostchildren list
def change_main_parent(self, node=None, new_main_parent=None):
pass
def shift(self, node, interval):
siblings = self.parent(node)["children"]