"""
Deletes all data files not mentioned in the labels file.
This allows the user to delete individual images by removing the line in the labels file.
Use filenum/labelsnum/featuresnum after to fix numbering.
"""
from os import listdir, unlink
from os.path import isfile, join, basename, splitext

print("Welcome to the filter-by-labels tool!")

print("'Labels' file path:")
labels = input()

det = open(labels)

lines = det.readlines()[1:]
det.close()

valid = {x.split()[0] for x in lines}

print("Data directory to process:")
dir = input()

dirs = [join(dir, d) for d in listdir(dir) if not isfile(join(dir, d))]

files = []
for d in dirs:
    files.extend([join(d, f) for f in listdir(d) if isfile(join(d, f))])

total = 0

for file in files:
    name, ext = splitext(basename(file))
    
    if name not in valid:
        unlink(file)
        total += 1
        
print (str(total) + " files deleted.")