-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
345 lines (299 loc) · 12.1 KB
/
Copy pathmain.py
File metadata and controls
345 lines (299 loc) · 12.1 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
import sys, csv, pathlib, json, os
from collections.abc import Callable
VERSION = "v0.1"
ARGS = sys.argv
DATA_PATH = "."
try:
DATA_PATH = sys._MEIPASS
except:pass
TAB = " "
if "--help" in ARGS or "-h" in ARGS:
print(
f"""
PylessDetective {VERSION} Help:
{TAB}Variables:
{TAB}{TAB}--help, -h | Show this message.
{TAB}{TAB}--map, -m=<map_name> | Specify a map.
{TAB}{TAB}--clue, -c=<clue_name> | Specify a clue. [Repeatable]
{TAB}{TAB}--non-interactive, -y | Skip asking to re-run/continue program (answers "n").
{TAB}{TAB}--output, -o=<output_path> | Specify output file path/name (JSON formatted). No output file if not specified.
{TAB}{TAB}{TAB}> eg.: `--output=result.json` => `./result.json`
{TAB}{TAB}--simple-print, -s | Prints in a basic headerless CSV format.
{TAB}{TAB}--mode, -f=<mode> | Program mode/function. ["suspect","clue","map"]
{TAB}{TAB}{TAB}> suspect | Finds suspects and outputs them.
{TAB}{TAB}{TAB}> map | Finds all map names and outputs them.
{TAB}{TAB}{TAB}> clue | Finds all clues of the given map and outputs them.
{TAB}{TAB}{TAB}> map-data | Finds data of the given map and output it. (Suspects and their respective clues.)
{TAB}{TAB}--maps-dir, -d=<map_dir> | Specify a custom map directory.
{TAB}{TAB}{TAB}> Sample directory tree:
{TAB}{TAB}{TAB}{TAB}maps/
{TAB}{TAB}{TAB}{TAB}├── map1.csv
{TAB}{TAB}{TAB}{TAB}├── map2.csv
{TAB}{TAB}{TAB}{TAB}└── map3.csv
{TAB}{TAB}--prettify, -p | Output prettified json format.
{TAB}Information:
{TAB}{TAB}[Repeatable] | This variable can be specified multiple times.
{TAB}{TAB}{TAB}> eg.: `--clue=tooth --clue=forgotten shoe`
"""
)
sys.exit(0)
NO_INTERACT = "--non-interactive" in ARGS or "-y" in ARGS
OUTPUT_PATH = None
SIMPLE_PRINT = "--simple-print" in ARGS or "-s" in ARGS
PRETTIFY = "--prettify" in ARGS or "-p" in ARGS
MODE = None
MAP_DIR = None
MAPS = {}
MAP = None
CLUES = []
EVIDENCE = {}
SUSPECTS = []
def p(*x:str) -> str:
return os.path.join(DATA_PATH,*x)
def get_path(x:str):
return os.path.expandvars(os.path.expanduser(x))
def write_output(*x:any):
if not OUTPUT_PATH or len(x) == 0: return
if len(x) == 1: x = x[0]
with open(get_path(OUTPUT_PATH),"w") as f:
json.dump(x,f,indent=4 if PRETTIFY else None)
def output(*x:any,no_write:bool=False) -> None:
if not OUTPUT_PATH or no_write:
return print(*x)
data = [v for v in x if not isinstance(v, str)]
write_output(*data)
def clear_term():
if OUTPUT_PATH: return
if sys.platform == "win32":
os.system("cls")
else:
os.system("clear")
def safe_len(x:any,offset:int=0) -> int|None:
try:
return len(x)+offset
except:
return None
def safe_int(x:str, offset:int=0) -> int|None:
try:
return int(x)+offset
except:
return None
def prettify_map_name(x:str):
data = x.split("-")
for i, v in enumerate(data):
data[i] = v[:1].upper()+v[1:]
return " ".join(data)
def uglify_map_name(x:str):
data = x.split(" ")
for i, v in enumerate(data):
data[i] = v.lower()
return "-".join(data)
def format_ls_item(x:str, index:int=0, length:int=1, show_index:bool=False, index_text:str="%d.", custom_index:int=None) -> str:
if not custom_index: custom_index = index+1
if not SIMPLE_PRINT:
return f"{"-" if not show_index else index_text % (custom_index)} {x}\n"
return f"{"[" if index == 0 else ""}{x}{"," if index<length-1 else "]"}"
def format_dict_item(x:str, index:int=0, length:int=1, key:str="", show_key:bool=True, key_text:str="%s:", custom_key:str=None) -> str:
if not custom_key: custom_key = key
if not SIMPLE_PRINT:
return f"{"" if not show_key else key_text % (custom_key)} {x}\n"
return f"{"{" if index == 0 else ""}{key}: {x}{"," if index<length-1 else "}"}"
def str_ls(l:list,header:str=None,show_index:bool=False,index_text:str="%d.",custom_index_func:Callable[[str,int],int]=None) -> str:
string = f"{header}:\n" if header and not SIMPLE_PRINT else ""
length = len(l)
for i,x in enumerate(l):
string+=format_ls_item(x,i,length,show_index,index_text,custom_index_func(x,i) if custom_index_func else None)
return string
def str_dict(d:dict,header:str=None,show_key:bool=True,key_text:str="%s:",custom_key_func:Callable[[str,str],str]=None) -> str:
string = f"{header}:\n" if header and not SIMPLE_PRINT else ""
length = len(d.keys())
for k,v in d.items():
string+=format_dict_item(v,list(d.keys()).index(k),length,k,show_key,key_text,custom_key_func(v,k) if custom_key_func else None)
def get_maps() -> list[str]:
x = [x for x in MAPS.keys()]
x.sort()
return x
def gen_map_data(map:str=None):
if not map: map = MAP
global MAPS, CLUES
change_clues = True
CLUES.clear()
with open(p("maps" if not MAP_DIR else MAP_DIR,f"{map}.csv")) as f:
reader = csv.DictReader(f)
for row in reader:
data = {}
for k,v in row.items():
if k == "Name": continue
if change_clues: CLUES.append(k)
data[k] = v=="1"
MAPS[map][row["Name"]] = data
if change_clues: change_clues = False
CLUES.sort()
def get_map_data(map:str=None) -> dict[str:dict[str:bool]]:
if not map: map = MAP
if not MAPS[map]: gen_map_data(map)
return MAPS[map]
def get_clues(map:str=None) -> list[str]:
if not map: map = MAP
if not CLUES: gen_map_data(map)
return CLUES
def get_suspects(map:str=None, evidence:dict[str:bool]=None) -> list[str]:
global SUSPECTS
if not map: map = MAP
if not evidence: evidence = EVIDENCE
if not MAPS[map]: gen_map_data(map)
SUSPECTS.clear()
for name in MAPS[map]:
person:dict = MAPS[map][name]
not_it = False
for clue, present in evidence.items():
if (present and not person.get(clue)) or (not present and person.get(clue)):
not_it = True
break
if not_it: continue
SUSPECTS.append(name)
return SUSPECTS
def input_yn(q:str, default_value:bool=None, header:str=None) -> bool:
if NO_INTERACT: return False
default_inputs = {
"y": True,
"n": False
}
if header:
output(header)
x = default_inputs.get(input(f"{q} ({"Y" if default_value else "y"}/{"n" if default_value else "N"}): ").lower())
if x == None: x = default_value
clear_term()
return x
def get_value_from_str(x:str) -> bool:
return not x.startswith("!")
def bool_dict_ls(d:dict[str:bool]):
l = []
for k, v in d.items():
l.append(f"{"!" if not v else ""}{k}")
return l
def input_strict(q:str, header:str=None, req_data:list[str]=[], req_func:Callable[[str,list[str]],bool]=lambda x, y : x in y, req_data_show_index:bool=False,run_forever:bool=False,run_forever_terminator:str="",starting_data:list[str]=None,starting_data_display_previous:bool=True,data_type:type=list,data_dict_not_enabled:bool=False) -> str|list[str]:
x = ""
data = starting_data or ([] if data_type == list else {})
i = safe_len(starting_data,1) or 1
if header:
output(str_ls(req_data,header,req_data_show_index))
if data_type == dict and data_dict_not_enabled:
output(f"Prefix with '!' to indicate NOT.\n> Eg.: '!{req_data[0]}'")
if run_forever:
output(f'Enter "{run_forever_terminator}" to confirm.' if run_forever_terminator != "" else 'Leave blank and press Enter to confirm.',no_write=True)
if starting_data and starting_data_display_previous:
string = str_ls(starting_data if type(starting_data) == list else bool_dict_ls(starting_data),show_index=True,index_text="Enter clue #%d:")
if string.endswith("\n"):
string = string[:-1]
output(string)
while True:
x = input(f"{q if not run_forever else q % (i)}: ")
if run_forever and x == run_forever_terminator: break
if req_func(x,req_data):
if not run_forever: break
if data_type == list:
data.append(x)
else:
present = get_value_from_str(x) if data_dict_not_enabled else True
data[x if present else x[1:]] = present
i+=1
clear_term()
return x if not run_forever else data
def mode_map():
output(str_ls(get_maps(),"Maps") if not OUTPUT_PATH else get_maps())
sys.exit(0)
def mode_clue():
output(str_ls(get_clues(),"Clues") if not OUTPUT_PATH else get_clues())
sys.exit(0)
def mode_mapdata():
if not MAPS.get(MAP):
gen_map_data()
output(str_dict(MAPS[MAP],f"{prettify_map_name(MAP)} Map Data") if not OUTPUT_PATH else MAPS[MAP])
sys.exit(0)
for x in ARGS:
if not x.startswith("--maps-dir=") and not x.startswith("-d="):
continue
MAP_DIR = x[11 if x.startswith("--maps-dir=") else 3:]
break
def gen_map_dict():
global MAPS
MAPS.clear()
for map in pathlib.Path(MAP_DIR if MAP_DIR else p("maps")).iterdir():
if not map.name.endswith(".csv"): continue
MAPS[map.name[:-4]] = {}
gen_map_dict()
for x in ARGS:
if not MAP and x.startswith("--map=") or x.startswith("-m="):
name = x[6 if x.startswith("--map=") else 3:].lower()
if MAPS.get(name) != None:
MAP = name
gen_map_data()
continue
if x.startswith("--clue=") or x.startswith("-c="):
clue = [x[7 if x.startswith("--clue=") else 3:].lower(),True]
if clue.startswith("!"):
clue[0] = clue[0][1:]
clue[1] = False
EVIDENCE[clue[0]] = clue[1]
continue
if not OUTPUT_PATH and x.startswith("--output=") or x.startswith("-o="):
OUTPUT_PATH = x[9 if x.startswith("--output=") else 3:]
continue
if not MODE and x.startswith("--mode=") or x.startswith("-f="):
MODE = x[7 if x.startswith("--mode=") else 3:].lower()
continue
if not MODE: MODE = "suspect"
if MODE == "map":
mode_map()
if MAP:
if MODE == "clue":
mode_clue()
if MODE == "map-data":
mode_mapdata()
if EVIDENCE:
if not MAP:
EVIDENCE.clear()
if MAP:
if not CLUES: CLUES = get_clues()
evidence = {}
for clue, present in EVIDENCE.items():
if clue in CLUES:
if not present and clue.startswith("!"):
clue = clue[1:]
evidence[clue] = present
EVIDENCE = evidence.copy()
del evidence
def prompt_map():
maps = get_maps()
return maps[int(input_strict("Enter map number","Maps",maps,lambda x, y: True if safe_int(x) and y[safe_int(x,-1)] else False,True))-1]
def prompt_evidence():
return input_strict("Enter clue #%d",f"{prettify_map_name(MAP)} Clues",CLUES,lambda x, y: (x in y) if not x.startswith("!") else (x[1:] in y),run_forever=True,starting_data=EVIDENCE,data_type=dict,data_dict_not_enabled=True)
def run(root_call:bool=False, clear_evidence:bool=False):
global MAP, CLUES, EVIDENCE, SUSPECTS
clear_term()
if not root_call:
if clear_evidence:
EVIDENCE.clear()
SUSPECTS.clear()
if not MAP:
MAP = prompt_map()
gen_map_data()
if MAP:
if MODE == "clue":
mode_clue()
if MODE == "map-data":
mode_mapdata()
if not root_call or not EVIDENCE:
EVIDENCE = prompt_evidence()
SUSPECTS = get_suspects()
keys = list(MAPS[MAP].keys())
output((str_ls(SUSPECTS,"Possible Suspects",True,f"- (#%d/{len(keys)})",lambda x, i: keys.index(x)+1) if SUSPECTS else "- No suspects found!") if not OUTPUT_PATH else SUSPECTS)
if len(SUSPECTS) <= 1:
if input_yn("Run again?",True):
return run(clear_evidence=True)
return
if not input_yn("Continue?",True,"Press Enter to continue."): return
return run()
if __name__ == "__main__":
run(True)