To handle discrepancies in filenames between the source and destination folders, such as trailing or leading characters, we can enhance the script to perform a match based on a more flexible criterion. Here's a strategy to find closely matching filenames:
- Strip or Normalize Strings: Remove any extraneous characters such as trailing hyphens or spaces.
- Partial Matching: Use a regex or similar logic to match filenames more flexibly, allowing minimal differences like dashes or extra characters at the end.
Let's adjust the script by incorporating logic to systematically identify matching files when their names aren't exact but are similar:
import os
import tkinter as tk
from tkinter import filedialog, messagebox, ttk
import subprocess
import re
class MetadataCopierApp:
def __init__(self, root):
self.root = root
self.root.title("Batch Metadata Copier")
self.src_folder = None
self.dest_folder = None
self.create_widgets()
def create_widgets(self):
frame = ttk.Frame(self.root, padding="10")
frame.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
ttk.Label(frame, text="Source Folder:").grid(row=0, column=0, sticky=tk.W)
self.src_folder_entry = ttk.Entry(frame, width=50)
self.src_folder_entry.grid(row=0, column=1, sticky=tk.W)
ttk.Button(frame, text="Browse", command=self.select_src_folder).grid(row=0, column=2, sticky=tk.W)
ttk.Label(frame, text="Destination Folder:").grid(row=1, column=0, sticky=tk.W)
self.dest_folder_entry = ttk.Entry(frame, width=50)
self.dest_folder_entry.grid(row=1, column=1, sticky=tk.W)
ttk.Button(frame, text="Browse", command=self.select_dest_folder).grid(row=1, column=2, sticky=tk.W)
self.progress = ttk.Progressbar(frame, orient='horizontal', mode='determinate', length=300)
self.progress.grid(row=2, column=0, columnspan=3, pady=10)
ttk.Button(frame, text="Copy Metadata", command=self.copy_metadata).grid(row=3, column=0, columnspan=3, pady=5)
self.log_text = tk.Text(frame, width=70, height=15, wrap='word')
self.log_text.grid(row=4, column=0, columnspan=3, pady=5)
self.log_text.config(state=tk.DISABLED)
def append_log(self, message):
self.log_text.config(state=tk.NORMAL)
self.log_text.insert(tk.END, message + "\n")
self.log_text.see(tk.END)
self.log_text.config(state=tk.DISABLED)
def select_src_folder(self):
self.src_folder = filedialog.askdirectory(title="Select Source Folder")
self.src_folder_entry.delete(0, tk.END)
self.src_folder_entry.insert(0, self.src_folder)
def select_dest_folder(self):
self.dest_folder = filedialog.askdirectory(title="Select Destination Folder")
self.dest_folder_entry.delete(0, tk.END)
self.dest_folder_entry.insert(0, self.dest_folder)
def find_best_match(self, src_name, dest_files):
# Regular expression to normalize filename, stripping trailing special characters
src_base = re.sub(r'[^\w]', '', os.path.splitext(src_name)[0])
for dest_file in dest_files:
dest_base = re.sub(r'[^\w]', '', os.path.splitext(dest_file)[0])
if src_base == dest_base:
return dest_file
return None
def copy_metadata(self):
if not self.src_folder or not self.dest_folder:
messagebox.showerror("Error", "Please select both source and destination folders.")
return
src_files = os.listdir(self.src_folder)
dest_files = os.listdir(self.dest_folder)
total_files = len(src_files)
self.progress["maximum"] = total_files
self.progress["value"] = 0
self.append_log("Starting metadata copy process...")
for i, filename in enumerate(src_files):
src_file = os.path.join(self.src_folder, filename.strip())
match = self.find_best_match(filename, dest_files)
if match:
dest_file = os.path.join(self.dest_folder, match)
if os.path.isfile(src_file) and os.path.isfile(dest_file):
try:
subprocess.run(['exiftool', '-tagsFromFile', src_file, dest_file], check=True)
self.append_log(f"Copied metadata from {filename} to {match}")
except Exception as e:
self.append_log(f"Error copying metadata for {filename}: {e}")
else:
self.append_log(f"No matching destination file found for {filename}")
self.progress["value"] = i + 1
self.root.update_idletasks()
self.append_log("Metadata copy process completed.")
def main():
root = tk.Tk()
app = MetadataCopierApp(root)
root.mainloop()
if __name__ == "__main__":
main()
Explanation:
-
Normalize Filenames: The find_best_match method uses regular expressions to strip non-alphanumeric characters from the base filenames. This allows it to perform matching based purely on core alphanumeric content.
-
Matching Logic: It identifies the best match in the destination folder for a given source file's core name, ignoring trailing and certain custom leading characters.
-
Exeiftool Usage: The script utilizes exiftool to perform metadata copying once a match is found.
-
Improved Logging: It logs all operations, highlighting successes and any missing matches, which can help debug mismatches if needed.
Make sure you have ExifTool installed and accessible from your command line to execute this script properly. You can download ExifTool from its official website and ensure it is part of your system's PATH.