Difference between revisions of "Audio Tags editor script"

From Vifm Wiki
Jump to navigation Jump to search
(Fix Comma Rules)
m (Correct syntax highlighting tags)
 
(3 intermediate revisions by 2 users not shown)
Line 7: Line 7:
 
== Source Code ==
 
== Source Code ==
  
<source lang="python">
+
<syntaxhighlight lang="python">
 
#!/usr/bin/env python3
 
#!/usr/bin/env python3
  
Line 24: Line 24:
 
song_attrs = [] # Dictionaries containing attributes to be inspected
 
song_attrs = [] # Dictionaries containing attributes to be inspected
  
 +
ff = sys.argv[1]
 +
default_album_name = os.path.basename(os.path.dirname(os.path.abspath(ff)))
 
# Make sure mutagen uses the easy version, as
 
# Make sure mutagen uses the easy version, as
 
# it uses the normal one by default
 
# it uses the normal one by default
if os.path.splitext(sys.argv[1])[1] == ".mp3":
+
extension = os.path.splitext(ff)[1]  
 +
if extension == ".mp3":
 
     import mutagen.easyid3
 
     import mutagen.easyid3
 
     mut_init = mutagen.easyid3.EasyID3
 
     mut_init = mutagen.easyid3.EasyID3
 +
elif extension == ".m4a":
 +
    import mutagen.easymp4
 +
    mut_init = mutagen.easymp4.EasyMP4
 
else:
 
else:
 
     mut_init = mutagen.File
 
     mut_init = mutagen.File
Line 37: Line 43:
 
     for attr in attrs:
 
     for attr in attrs:
 
         song_attrs[-1][attr] = songs[-1].get(attr, [''])[0]
 
         song_attrs[-1][attr] = songs[-1].get(attr, [''])[0]
         if attr == 'artist' and not song_attrs[-1][attr]:
+
         if not song_attrs[-1][attr]:
             del song_attrs[-1][attr]
+
             if attr == 'artist':
            _attr = 'albumartist'
+
                _attr = 'albumartist'
            song_attrs[-1][attr] = songs[-1].get(_attr, [''])[0]
+
                song_attrs[-1][attr] = songs[-1].get(_attr, [''])[0]
 +
            if attr == 'title':
 +
                song_attrs[-1][attr] = os.path.splitext(f)[0]
 +
            if attr == 'album':
 +
                song_attrs[-1][attr] = default_album_name
  
 
with tempfile.NamedTemporaryFile('w+', suffix='.csv') as tmpf:
 
with tempfile.NamedTemporaryFile('w+', suffix='.csv') as tmpf:
     csvwriter = csv.writer(tmpf, quoting=csv.QUOTE_NONE, escapechar=escape)
+
     csvwriter = csv.writer(tmpf, quoting=csv.QUOTE_NONE, escapechar=escape,
 +
            skipinitialspace=True)
 
     csvwriter.writerows([row.values() for row in song_attrs])
 
     csvwriter.writerows([row.values() for row in song_attrs])
 
     # Ensure that the file has been written to disk
 
     # Ensure that the file has been written to disk
Line 49: Line 60:
 
     os.system("{} {}".format(editor, tmpf.name))
 
     os.system("{} {}".format(editor, tmpf.name))
 
     tmpf.seek(0)
 
     tmpf.seek(0)
     csvreader = csv.reader(tmpf, quoting=csv.QUOTE_NONE, escapechar=escape)
+
     csvreader = csv.reader(tmpf, quoting=csv.QUOTE_NONE,
 +
            escapechar=escape, skipinitialspace=True)
 
     for song,row in zip(songs, csvreader):
 
     for song,row in zip(songs, csvreader):
 
         new_song_metadata = dict(zip(attrs, row))
 
         new_song_metadata = dict(zip(attrs, row))
 
         song.update(new_song_metadata)
 
         song.update(new_song_metadata)
 
         song.save()
 
         song.save()
</source>
+
</syntaxhighlight>
  
 
== Installation ==
 
== Installation ==
Line 63: Line 75:
 
Then place the following into your vifm rc:
 
Then place the following into your vifm rc:
  
<source>
+
<syntaxhighlight lang="vim">
 
filetype {*.flac,*.mp3,*.ogg,*.m4a} mtags.py %f
 
filetype {*.flac,*.mp3,*.ogg,*.m4a} mtags.py %f
</source>
+
</syntaxhighlight>
  
 
== Tips ==
 
== Tips ==
Line 74: Line 86:
 
Place the following into your vim rc file once installed:
 
Place the following into your vim rc file once installed:
  
<source lang="vim">
+
<syntaxhighlight lang="vim">
 
augroup csv
 
augroup csv
 
autocmd BufWritePre *.csv %EasyAlign *, {'a': 'r'}
 
autocmd BufWritePre *.csv %EasyAlign *, {'a': 'r'}
 
autocmd BufReadPost *.csv %EasyAlign *, {'a': 'r'}
 
autocmd BufReadPost *.csv %EasyAlign *, {'a': 'r'}
 
augroup end
 
augroup end
</source>
+
</syntaxhighlight>
  
 
This will auto-align the commas.
 
This will auto-align the commas.
Line 89: Line 101:
 
For example, output for the first song of [https://en.wikipedia.org/wiki/Never,_Neverland Never, Neverland] by Annihilator will show up like this:
 
For example, output for the first song of [https://en.wikipedia.org/wiki/Never,_Neverland Never, Neverland] by Annihilator will show up like this:
  
<source>
+
<pre>
 
Annihilator, Never*, Neverland, The Fun Palace
 
Annihilator, Never*, Neverland, The Fun Palace
</source>
+
</pre>
  
 
If for whatever reason you want to change the escape character you can do so in the source.
 
If for whatever reason you want to change the escape character you can do so in the source.

Latest revision as of 12:02, 31 August 2021

This scripts allows one to edit the metadata of audio files using mutagen.

It takes the selected files and spits out a temporary csv file of the artist, album, and song title in that order. You then make your changes and write to the file to apply them. This script will not delete any info except for the stuff you overwrite. It simply updates the fields that are shown to the user.

If you want to edit other attributes of the file, then it's very easy to do so by changing a single variable yourself.

Source Code[edit]

#!/usr/bin/env python3

import sys
import os
import tempfile
import csv
import mutagen

# Options
editor = os.environ['EDITOR']
attrs = ['artist', 'album', 'title']
escape = '*'

songs = [] # List of mutagen objects
song_attrs = [] # Dictionaries containing attributes to be inspected

ff = sys.argv[1]
default_album_name = os.path.basename(os.path.dirname(os.path.abspath(ff)))
# Make sure mutagen uses the easy version, as
# it uses the normal one by default
extension = os.path.splitext(ff)[1] 
if extension == ".mp3":
    import mutagen.easyid3
    mut_init = mutagen.easyid3.EasyID3
elif extension == ".m4a":
    import mutagen.easymp4
    mut_init = mutagen.easymp4.EasyMP4
else:
    mut_init = mutagen.File

for f in sys.argv[1:]:
    songs.append(mut_init(f))
    song_attrs.append({})
    for attr in attrs:
        song_attrs[-1][attr] = songs[-1].get(attr, [''])[0]
        if not song_attrs[-1][attr]:
            if attr == 'artist':
                _attr = 'albumartist'
                song_attrs[-1][attr] = songs[-1].get(_attr, [''])[0]
            if attr == 'title':
                song_attrs[-1][attr] = os.path.splitext(f)[0]
            if attr == 'album':
                song_attrs[-1][attr] = default_album_name

with tempfile.NamedTemporaryFile('w+', suffix='.csv') as tmpf:
    csvwriter = csv.writer(tmpf, quoting=csv.QUOTE_NONE, escapechar=escape,
            skipinitialspace=True)
    csvwriter.writerows([row.values() for row in song_attrs])
    # Ensure that the file has been written to disk
    tmpf.flush()
    os.system("{} {}".format(editor, tmpf.name))
    tmpf.seek(0)
    csvreader = csv.reader(tmpf, quoting=csv.QUOTE_NONE,
            escapechar=escape, skipinitialspace=True)
    for song,row in zip(songs, csvreader):
        new_song_metadata = dict(zip(attrs, row))
        song.update(new_song_metadata)
        song.save()

Installation[edit]

Pyhton 3 is required. You will also need the mutagen python package which can be installed using pip: sudo pip install mutagen, or you can probably obtain it through your package manager.

Save the file as mtags.py in either your $PATH or your $VIFM/scripts directory. Make sure that the file is executable. Then place the following into your vifm rc:

filetype {*.flac,*.mp3,*.ogg,*.m4a} mtags.py %f

Tips[edit]

Aligning Entries[edit]

It's much easier to work with csv files when the commas are aligned. If you use vim, then this is very easy to do with the easy-align plugin. Place the following into your vim rc file once installed:

augroup csv
autocmd BufWritePre *.csv %EasyAlign *, {'a': 'r'}
autocmd BufReadPost *.csv %EasyAlign *, {'a': 'r'}
augroup end

This will auto-align the commas.

Fields with Commas in Them[edit]

If a field has a comma in it, then escape that character with an asterisk. A field with an asterisk in it will show up as a double asterisk **

For example, output for the first song of Never, Neverland by Annihilator will show up like this:

Annihilator, Never*, Neverland, The Fun Palace

If for whatever reason you want to change the escape character you can do so in the source.