From 4a632c1c94ba771ac5a17df28d39bbfd20184ba6 Mon Sep 17 00:00:00 2001 From: Bob Mottram Date: Fri, 20 May 2022 16:18:02 +0100 Subject: [PATCH] Convert ID3 metadata field on audio attachments into hashtags --- media.py | 32 ++++++++++++++++++++++++++++++++ posts.py | 20 ++++++++++++++++++++ 2 files changed, 52 insertions(+) diff --git a/media.py b/media.py index 1f84f7a10..c5c61b195 100644 --- a/media.py +++ b/media.py @@ -162,6 +162,38 @@ def _spoof_meta_data(base_dir: str, nickname: str, domain: str, return +def get_music_metadata(filename: str) -> {}: + """Returns metadata for a music file + """ + result = None + try: + result = subprocess.run(['exiftool', '-v3', filename], + stdout=subprocess.PIPE) + except BaseException as ex: + print('EX: get_music_metadata failed ' + str(ex)) + if not result: + return {} + if not result.stdout: + return {} + try: + id3_lines = result.stdout.decode('utf-8').split('\n') + except BaseException: + print('EX: get_music_metadata unable to decode output') + return {} + fieldnames = ( + 'Title', 'Artist', 'Genre', 'Track', 'Album', 'Length', 'Band' + ) + music_metadata = {} + for line in id3_lines: + for field in fieldnames: + if field + ' = ' in line: + field_value = line.split(field + ' = ')[1] + if '>' in field_value: + field_value = field_value.split('>')[0].strip() + music_metadata[field.lower()] = field_value + return music_metadata + + def convert_image_to_low_bandwidth(image_filename: str) -> None: """Converts an image to a low bandwidth version """ diff --git a/posts.py b/posts.py index 1780999d7..da64d85fd 100644 --- a/posts.py +++ b/posts.py @@ -32,6 +32,8 @@ from webfinger import webfinger_handle from httpsig import create_signed_header from siteactive import site_is_active from languages import understood_post_language +from utils import valid_hash_tag +from utils import get_audio_extensions from utils import get_summary_from_post from utils import get_user_paths from utils import invalid_ciphertext @@ -70,6 +72,7 @@ from utils import remove_html from utils import dangerous_markup from utils import acct_dir from utils import local_actor_url +from media import get_music_metadata from media import attach_media from media import replace_you_tube from media import replace_twitter @@ -1423,6 +1426,23 @@ def _create_post_base(base_dir: str, else: mentioned_recipients = '' + # add hashtags from audio file ID3 tags, such as Artist, Album, etc + if attach_image_filename and media_type: + audio_types = get_audio_extensions() + music_metadata = None + for ext in audio_types: + if ext in media_type: + music_metadata = get_music_metadata(attach_image_filename) + break + if music_metadata: + for audio_tag, audio_value in music_metadata.items(): + if audio_tag == 'title' or audio_tag == 'track': + continue + audio_value = audio_value.title().replace(' ', '') + if valid_hash_tag(audio_value) and \ + '#' + audio_value not in content: + content += ' #' + audio_value + tags = [] hashtags_dict = {}