Fix _find_file to prioritize exact matches and word count

This commit is contained in:
Folzo
2026-04-11 03:27:17 +02:00
parent 58b439cf1d
commit 2ab1efd7e4
+41 -8
View File
@@ -189,17 +189,50 @@ class Tools:
if os.path.exists(path):
return path
exact_matches = []
substring_matches = []
word_matches = []
search_name = filename.lower()
search_parts = search_name.replace('.jpeg', ' ').replace('.jpg', ' ').replace('.png', ' ').replace('(1)', ' ').replace('(2)', ' ').replace('(3)', ' ').split()
search_parts = [p for p in search_parts if len(p) > 2]
for directory in search_dirs:
all_files = glob.glob(os.path.join(directory, "*"))
for f in all_files:
basename = os.path.basename(f).lower()
search_name = filename.lower()
if search_name in basename or basename.startswith(search_name):
return f
parts = search_name.replace('.jpeg', '').replace('.jpg', '').replace('.png', '').split()
for part in parts:
if len(part) > 3 and part in basename:
return f
basename = os.path.basename(f)
basename_lower = basename.lower()
if search_name == basename_lower:
exact_matches.append((f, 1000 + len(basename)))
continue
if search_name in basename_lower:
substring_matches.append((f, len(basename)))
continue
if '(' in filename and ')' in filename:
base_no_suffix = search_name.split('(')[0].strip()
if base_no_suffix in basename_lower:
word_matches.append((f, 500 + len(basename)))
continue
if search_parts:
match_count = sum(1 for part in search_parts if part in basename_lower)
if match_count >= len(search_parts) * 0.7:
word_matches.append((f, match_count * 100 + len(basename)))
if exact_matches:
exact_matches.sort(key=lambda x: x[1], reverse=True)
return exact_matches[0][0]
if substring_matches:
substring_matches.sort(key=lambda x: x[1], reverse=True)
return substring_matches[0][0]
if word_matches:
word_matches.sort(key=lambda x: x[1], reverse=True)
return word_matches[0][0]
return None