Skip to content

Instantly share code, notes, and snippets.

@yfli
Created May 23, 2019 18:49
Show Gist options
  • Save yfli/7bea4ee5cd50fa1dd57c0d321b66875f to your computer and use it in GitHub Desktop.
Save yfli/7bea4ee5cd50fa1dd57c0d321b66875f to your computer and use it in GitHub Desktop.
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Convert MP3 ID3 tag from hanzi to pinyin
#
# Copyright © 2019 Yefei Li
#
# Requirements
# eyeD3==0.8.10
# pypinyin==0.35.3
#
# Distributed under terms of the MIT license.
"""
"""
import os
import argparse
from eyed3 import load, id3
from pypinyin import lazy_pinyin
parser = argparse.ArgumentParser(
description='Convert mp3 ID3 tags from hanzi to pinyin.')
parser.add_argument(
'filename', type=str,
help='mp3 file')
args = parser.parse_args()
audiofile = os.fsdecode(args.filename)
audio = load(audiofile)
status = id3.Tag.remove(
audiofile,
id3.ID3_V1,
)
def hanzi2pinyin(hanzi):
if not hanzi:
return None
isascii = lambda s: len(s) == len(s.encode())
if isascii(hanzi):
return hanzi
output = lazy_pinyin(hanzi)
return ''.join([s.capitalize() for s in output if s.isalnum()])
oa = audio.tag.artist
ot = audio.tag.title
oal = audio.tag.album
audio.tag.artist = hanzi2pinyin(audio.tag.artist)
audio.tag.title = hanzi2pinyin(audio.tag.title)
audio.tag.album = hanzi2pinyin(audio.tag.album)
print("{}: {}=>{} {}=>{} {}=>{}".format(
args.filename,
oa, audio.tag.artist,
ot, audio.tag.title,
oal, audio.tag.album,
))
audio.tag.save()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment