Mr_Noodle wrote:You can use AppleScript to create custom attributes which can be returned back to Hazel. The manual has more details on how to do that.
I struggled with that a bit. I wasn't sure how to use the string returned by the script and use it as a tag.
As an alternate option, I created a shell script that extracts the Genre using
ffmpeg (again, it requires that you have
ffmpeg installed), then uses that to apply the tag directly in the Finder.
AppleScript is unable to properly manipulate tags apparently so I had to use
xattr.
I asked ChatGPT for help (but the code failed!), and eventually got it to work after some significant editing. My solution is
not elegant (I could have used the
plist command, but it ended up easier to just do it the blunt way and type the plist structure in instead), and is only designed for files that only have one Genre (but from what I can tell they should not have more than one), but it works

I'm not a good scripter so if anyone wants to revise it, I sure won’t take offense

In case anyone needs it, here it is:
- Code: Select all
#!/bin/bash
# Function to extract genre from video file
get_genre() {
local file="$1"
local genre
# Extract metadata, grep for genre, and remove unnecessary text
genre=$(ffmpeg -i "$file" 2>&1 | grep -i "genre" | cut -d':' -f2 | tr -d '[:space:]')
echo "$genre"
}
# Function to set Finder tag using xattr
set_finder_tag() {
local file="$1"
local tag="$2"
if [[ -z "$tag" ]]; then
echo "No genre found; no tag will be applied."
else
# Set the Finder tag
TagCmd="xattr -w com.apple.metadata:_kMDItemUserTags"
leadingStr="'<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\"><plist version=\"1.0\"><array><string>"
closingStr="</string></array></plist>'"
eval "$TagCmd $leadingStr$tag$closingStr '$file'"
echo "Set Finder tag: '$tag' for file: $file"
fi
}
# Check for required commands
if ! command -v ffmpeg &> /dev/null; then
echo "ffmpeg is required but it’s not installed. Exiting."
exit 1
fi
if [[ $# -eq 0 ]]; then
echo "Usage: $0 <video-file>"
exit 1
fi
video_file="$1"
# Get genre of the video file
genre=$(get_genre "$video_file")
# Set Finder tag based on genre
set_finder_tag "$video_file" "$genre"
It echoes some of the results along the script, and if you ever need to troubleshoot, you can see the output in the Hazel logs.