import os import psutil from datetime import datetime from PyQt5.QtWidgets import QMessageBox def get_relative_date(past_date, reference_date=None): """ Return how long before reference_date past_date is as string. Params: @past_date: datetime @reference_date: datetime, defaults to current date and time @return: string """ if not past_date: return "Never" if not reference_date: reference_date = datetime.now() # Check parameters if past_date > reference_date: return "get_relative_date() past_date is after relative_date" weeks, days = divmod((reference_date.date() - past_date.date()).days, 7) if weeks == days == 0: # Played today, so return time instead return past_date.strftime("%H:%M") if weeks == 1: weeks_str = "week" else: weeks_str = "weeks" if days == 1: days_str = "day" else: days_str = "days" return f"{weeks} {weeks_str}, {days} {days_str} ago" def open_in_audacity(path): """ Open passed file in Audacity Return True if apparently opened successfully, else False """ # Return if audacity not running if "audacity" not in [i.name() for i in psutil.process_iter()]: return False to_pipe = '/tmp/audacity_script_pipe.to.' + str(os.getuid()) from_pipe = '/tmp/audacity_script_pipe.from.' + str(os.getuid()) EOL = '\n' def send_command(command): """Send a single command.""" to_audacity.write(command + EOL) to_audacity.flush() def get_response(): """Return the command response.""" result = '' line = '' while True: result += line line = from_audacity.readline() if line == '\n' and len(result) > 0: break return result def do_command(command): """Send one command, and return the response.""" send_command(command) response = get_response() return response with open(to_pipe, 'w') as to_audacity, open( from_pipe, 'rt') as from_audacity: do_command(f'Import2: Filename="{path}"') def show_warning(title, msg): "Display a warning to user" QMessageBox.warning(None, title, msg, buttons=QMessageBox.Cancel) def ms_to_mmss(ms, decimals=0, negative=False): if not ms: return "-" sign = "" if ms < 0: if negative: sign = "-" else: ms = 0 minutes, remainder = divmod(ms, 60 * 1000) seconds = remainder / 1000 # if seconds >= 59.5, it will be represented as 60, which looks odd. # So, fake it under those circumstances if seconds >= 59.5: seconds = 59.0 return f"{sign}{minutes:.0f}:{seconds:02.{decimals}f}"