Python Snippets

Published: Sunday, March 24, 2024
Last Modified: Saturday, November 30, 2024

I always find myself writing these snippets over and over again. Maybe they already exist in some libraries I haven’t discovered yet?

Recursive File Path Generator

def get_dir_paths(root_dir: str, valid_extensions: list[str], recursive: bool=True) -> Generator:
    """Note: exts in valid_extensions must include leading '.'"""
    if recursive:
        return (str(p) for p in Path(root_dir).rglob('*') if p.suffix.lower() in valid_extensions)
    return (str(p) for p in Path(root_dir).glob('*') if p.suffix.lower() in valid_extensions)


def is_valid_file(p: Path, valid_extensions: list[str]) -> bool:
    """Note: exts in valid_extensions must include leading '.'"""
    return p.is_file() and p.suffix.lower() in valid_extensions


def get_image_files(image_path: str|list[str], valid_extensions: list[str]) -> Generator | list:
    if isinstance(image_path, list):
        return [f for f in image_path if is_valid_file(Path(f), valid_extensions)]

    if os.path.isfile(image_path):
        return [image_path] if is_valid_file(Path(image_path), valid_extensions) else []

    elif os.path.isdir(image_path):
        return get_dir_paths(image_path, valid_extensions)

    raise ValueError("The provided path is neither a file nor a directory.")

Make Current Directory File Path

import os
def make_path(*filepaths):
    return os.path.join(os.path.abspath(os.path.dirname(__file__)), *filepaths)

Current Datetime TZ

import datetime, pytz
def get_current_datetime(timezone_str='America/Toronto'):
    utc_now = datetime.datetime.now()
    timezone = pytz.timezone(timezone_str)
    now_tz = utc_now.replace(tzinfo=pytz.utc).astimezone(timezone)
    return now_tz

Search YouTube, Download First Result as MP3

import os
searches = """Saturnalias - JSUK
SHOEGAZER - spiral"""
os.chdir(os.path.dirname(__file__))
for search in searches.split('\n'):
    search = search.strip()
    try:
        command = f"""yt-dlp -f 'ba' -x --audio-format mp3 --playlist-item 1 ytsearch:"{search}" -o "./songs/%(title)s___%(id)s.%(ext)s" """
        os.system(command)
    except:
        pass

Vocaroo Download

import os
d = {
    'name': 'https://voca.ro/string',
}
for name, link in d.items():
    print(name)
    os.system(f'yt-dlp {link} -o {name}.mp3')

Random 2 Decimal Float

import random
def get_random_float(N, M):
    assert N <= M
    return round(random.uniform(N, M), 2)

Create a List of JSON objects for /music

import os
import subprocess

def is_audio_file(file_name):
    audio_extensions = ['.mp3', '.opus', '.m4a', '.wav', '.flac', '.aac', '.ogg']
    return any(file_name.lower().endswith(ext) for ext in audio_extensions)

def convert_to_mp3(input_file, output_file):
    subprocess.run(['ffmpeg', '-i', input_file, output_file], check=True)

def generate_music_library(root_directory):
    music_library = []
    for artist in os.listdir(root_directory):
        artist_path = os.path.join(root_directory, artist)
        if os.path.isdir(artist_path):
            for album in os.listdir(artist_path):
                album_path = os.path.join(artist_path, album)
                if os.path.isdir(album_path):
                    songs = []
                    for song in os.listdir(album_path):
                        song_path = os.path.join(album_path, song)
                        if is_audio_file(song):
                            if not song.lower().endswith('.mp3'):
                                mp3_file = os.path.splitext(song)[0] + '.mp3'
                                mp3_path = os.path.join(album_path, mp3_file)
                                convert_to_mp3(song_path, mp3_path)
                                song = mp3_file
                            songs.append(song)
                    music_library.append({
                        'artist': artist,
                        'album': album,
                        'songs': songs
                    })
    return music_library

if __name__ == "__main__":
    root_directory = '' # set your root dir
    music_library = generate_music_library(root_directory)
    print()
    print(music_library)
    print()

Compress Images In A Directory (Non-Recurive)

#!/bin/bash
if [ -z "$1" ]; then
    echo "Usage: $0 /path/to/your/images"
    exit 1
fi
INPUT_DIR="$1"
for img in "$INPUT_DIR"/*.{jpg,JPG,jpeg,JPEG,png,PNG}; do
    if [[ -f "$img" ]]; then

        if [[ $img == *.jpg || $img == *.jpeg || $img == *.JPG || $img == *.JPEG ]]; then
            ffmpeg -hide_banner -loglevel error -i "$img" -q:v 15 -y "$img" # (better quality) 1 - 31 (lower quality)
        fi

        if [[ $img == *.png || $img == *.PNG ]]; then
            ffmpeg -hide_banner -loglevel error -i "$img" -compression_level 8 -y "$img" # (better quality) 1 - 10 (lower quality)
        fi
        
        echo "Processed and overwrote $img"
    fi
done

I’ll add more here as time goes on, and I work on my projects. Feel free to share yours too, and I can include them in this post!

Comment
Optional
No comments yet...