Fix _find_file to prioritize exact matches and word count
This commit is contained in:
@@ -189,17 +189,50 @@ class Tools:
|
|||||||
if os.path.exists(path):
|
if os.path.exists(path):
|
||||||
return 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:
|
for directory in search_dirs:
|
||||||
all_files = glob.glob(os.path.join(directory, "*"))
|
all_files = glob.glob(os.path.join(directory, "*"))
|
||||||
for f in all_files:
|
for f in all_files:
|
||||||
basename = os.path.basename(f).lower()
|
basename = os.path.basename(f)
|
||||||
search_name = filename.lower()
|
basename_lower = basename.lower()
|
||||||
if search_name in basename or basename.startswith(search_name):
|
|
||||||
return f
|
if search_name == basename_lower:
|
||||||
parts = search_name.replace('.jpeg', '').replace('.jpg', '').replace('.png', '').split()
|
exact_matches.append((f, 1000 + len(basename)))
|
||||||
for part in parts:
|
continue
|
||||||
if len(part) > 3 and part in basename:
|
|
||||||
return f
|
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
|
return None
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user