Konst12 commited on
Commit
787fa2c
·
1 Parent(s): 6b19e15

Upload tag_autocomplete_helper.py

Browse files
Files changed (1) hide show
  1. tag_autocomplete_helper.py +50 -0
tag_autocomplete_helper.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This helper script scans folders for wildcards and embeddings and writes them
2
+ # to a temporary file to expose it to the javascript side
3
+
4
+ from pathlib import Path
5
+
6
+ # The path to the folder containing the wildcards and embeddings
7
+ FILE_DIR = Path().absolute()
8
+ WILDCARD_PATH = FILE_DIR.joinpath('scripts/wildcards')
9
+ EMB_PATH = FILE_DIR.joinpath('embeddings')
10
+ # The path to the temporary file
11
+ TEMP_PATH = FILE_DIR.joinpath('tags/temp')
12
+
13
+
14
+ def get_wildcards():
15
+ """Returns a list of all wildcards. Works on nested folders."""
16
+ wildcard_files = list(WILDCARD_PATH.rglob("*.txt"))
17
+ resolved = [str(w.relative_to(WILDCARD_PATH)) for w in wildcard_files]
18
+ return resolved
19
+
20
+
21
+ def get_embeddings():
22
+ """Returns a list of all embeddings"""
23
+ return [str(e.relative_to(EMB_PATH)) for e in EMB_PATH.glob("**/*") if e.suffix in {".bin", ".pt"}]
24
+
25
+
26
+ def write_to_temp_file(name, data):
27
+ """Writes the given data to a temporary file"""
28
+ with open(TEMP_PATH.joinpath(name), 'w', encoding="utf-8") as f:
29
+ f.write(('\n'.join(data)))
30
+
31
+
32
+ # Check if the temp path exists and create it if not
33
+ if not TEMP_PATH.exists():
34
+ TEMP_PATH.mkdir(parents=True, exist_ok=True)
35
+ # Set up files to ensure the script doesn't fail to load them
36
+ # even if no wildcards or embeddings are found
37
+ write_to_temp_file('wc.txt', [])
38
+ write_to_temp_file('emb.txt', [])
39
+
40
+ # Write wildcards to wc.txt if found
41
+ if WILDCARD_PATH.exists():
42
+ wildcards = get_wildcards()
43
+ if wildcards:
44
+ write_to_temp_file('wc.txt', wildcards)
45
+
46
+ # Write embeddings to emb.txt if found
47
+ if EMB_PATH.exists():
48
+ embeddings = get_embeddings()
49
+ if embeddings:
50
+ write_to_temp_file('emb.txt', embeddings)