wiki_music.utilities module

Warning

Documentation is stil under construction some things might not be up to date.

utilities.gui_utils

Utility functions used by GUI classes.

wiki_music.utilities.gui_utils.get_music_path() → pathlib.Path

Returns the default music path for linux or windows.

Returns:string path pointing to music library location
Return type:Path
wiki_music.utilities.gui_utils.abstract_warning()

Raises error when abstract method is called directly.

Raises:NotImplementedError – this is the sole purpose of this function
wiki_music.utilities.gui_utils.get_image(address: Union[Path, str]) → bytes

Based on addres decides if the image is online or local.

If address is string, image is downloaded from internet. If it is Path object it is read from disk.

Parameters:address – string with path to picture on local PC or with http address
Returns:bytes repesentation of image loaded to memory or None if address is not valid
Return type:bytes
wiki_music.utilities.gui_utils.get_sizes(uri: Union[str, pathlib.Path]) → Tuple[Optional[int], Optional[Tuple[int, int]]]

Get file size and image size of internet or disk picture.

Information is retrieved without downloading the whole picture in case of interner pic and without reading the whole picture from disk in case of local picture.

Parameters:uri (Union[str, Path]) – picture url addres or disk address

References

https://stackoverflow.com/questions/15800704/get-image-size-without-loading-image-into-memory

Returns:if the size can be obtained result is a tuple with picture size in Kb and dimensions tuple as a second element
Return type:tuple
wiki_music.utilities.gui_utils.comp_res(image: bytes, quality: int, x: int = 0, y: int = 0) → bytes

Compress and/or change image resolution.

If x and y dimension are both specified than image is resized to these dimension otherwise it is only compressed

Parameters:
  • image (bytes) – bytes representation of image loaded to memory
  • quality (int) – target quality to which we wanto compress the limits are (1, 99)
  • x (int) – horizontal image dimension
  • y (int) – vertical iage dimension
Returns:

bytes image compressed and resized than reloaded to memory

Return type:

bytes

wiki_music.utilities.gui_utils.get_image_size(image: bytes) → str

Get size of image in memory.

Parameters:image (bytes) – bytes image in loaded in memory
Returns:string with image size in Kb rounded to 2 decimal places
Return type:str
wiki_music.utilities.gui_utils.get_icon() → str

Returns application icon path.

Raises:FileNotFoundError – if the path does not exist
Returns:string with icon path
Return type:str

utilities.exceptions

Defines exceptions for whole package.

exception wiki_music.utilities.exceptions.NoTracklistException

Bases: wiki_music.utilities.exceptions.ExceptionBase

Raised when no tracklist is found on wikipedia page.

exception wiki_music.utilities.exceptions.NoReleaseDateException

Bases: wiki_music.utilities.exceptions.ExceptionBase

Raised when release date could not be extracted.

exception wiki_music.utilities.exceptions.NoGenreException

Bases: wiki_music.utilities.exceptions.ExceptionBase

Raised when genres could not be extracted.

exception wiki_music.utilities.exceptions.NoCoverArtException

Bases: wiki_music.utilities.exceptions.ExceptionBase

Raised when cover art could not be extracted.

exception wiki_music.utilities.exceptions.NoNames2ExtractException

Bases: wiki_music.utilities.exceptions.ExceptionBase

Raised when cover art could not be extracted.

exception wiki_music.utilities.exceptions.NoContentsException

Bases: wiki_music.utilities.exceptions.ExceptionBase

Raised when page contents could not be extracted.

exception wiki_music.utilities.exceptions.NoPersonnelException

Bases: wiki_music.utilities.exceptions.ExceptionBase

Raised when page contents could not be extracted.

exception wiki_music.utilities.exceptions.Mp3tagNotFoundException

Bases: wiki_music.utilities.exceptions.ExceptionBase

Raised when Mp3tag could not be run.

exception wiki_music.utilities.exceptions.NltkUnavailableException

Bases: wiki_music.utilities.exceptions.ExceptionBase

Raised when Mp3tag could not be run.

exception wiki_music.utilities.exceptions.TagReadException

Bases: wiki_music.utilities.exceptions.ExceptionBase

Raised when tags could not be read from file.

exception wiki_music.utilities.exceptions.TagSaveException

Bases: wiki_music.utilities.exceptions.ExceptionBase

Raised when tags could not be saved to file.

exception wiki_music.utilities.exceptions.ExceptionBase

Bases: Exception

Base exception class for all package exceptions.

exception wiki_music.utilities.exceptions.UnsupportedFileType

Bases: wiki_music.utilities.exceptions.ExceptionBase

Raised when wiki_music cannot handle tags for given file type.

exception wiki_music.utilities.exceptions.ImageDecodeError

Bases: wiki_music.utilities.exceptions.ExceptionBase

Raised when wiki_music cannot get image dimensions and/or size.

utilities.loggers

Logger initialization for package.

wiki_music.utilities.loggers.set_log_handles(level: int)

Set desired level for package loggers and add file handlers.

Parameters:level (int) – logging level

utilities.parser_utils

These are utility modules and classes used exclusively by library.parser.

Utility functions and classes used by parser.

class wiki_music.utilities.parser_utils.ThreadWithTrace(*args, **keywords)

Bases: threading.Thread

Subclass of threading.thread, which can be killed from main thread.

Sets trace to thread by means of which it can be later killed from outside

Parameters:
  • args (Any) – same as threading.Thread
  • kwargs (Any) – same as threading.Thread

References

https://www.geeksforgeeks.org/python-different-ways-to-kill-a-thread/

start()

Start the thread’s activity.

It must be called at most once per thread object. It arranges for the object’s run() method to be invoked in a separate thread of control.

This method will raise a RuntimeError if called more than once on the same thread object.

wiki_music.utilities.parser_utils.bracket(data: List[str]) → List[str]

Puts elements of the list in brackets.

Parameters:data (List[str]) – input data
Returns:list of strings with brackets at the ends
Return type:List[str]
wiki_music.utilities.parser_utils.write_roman(num: Union[int, str])

Convert integer to roman number.

Parameters:num (int) – integer to convert to roman number

References

https://stackoverflow.com/questions/52554702/roman-numerals-to-integers-converter-with-python-using-a-dictionary

Returns:roman number converted from integer
Return type:str
wiki_music.utilities.parser_utils.normalize(text: str) → str

NFKD string normalization.

Parameters:text (str) – text to normalize
Returns:normalized version of text
Return type:str
wiki_music.utilities.parser_utils.normalize_caseless(text: str) → str

NFKD casefold string normalization.

Parameters:text (str) – string to normalize
Returns:normalized caseless version of string
Return type:str
wiki_music.utilities.parser_utils.caseless_equal(left: str, right: str) → bool

Check for normalized string equality.

Parameters:
  • left (str) – string to compare
  • right (str) – string to compare
Returns:

true if normalized caseless strings are equal

Return type:

bool

wiki_music.utilities.parser_utils.caseless_contains(string: str, in_text: str) → bool

Check if string is contained in text.

Parameters:
  • string (str) – string to search for
  • in_text (str) – string to search in
Returns:

True if string is in text

Return type:

bool

wiki_music.utilities.parser_utils.count_spaces(*lists) → Tuple[List[str], int]

Counts max length of elements in list and coresponding spaces for each item to fit that length.

Parameters:lists (Tuple[List[str]]) – data on which to count spaces, all lists in tuple must be of same length
Returns:list of number os apces to append to list elements to make them span max length
Return type:tuple
wiki_music.utilities.parser_utils.json_dump(dict_data: List[Dict[str, str]], save_dir: Path)

Save json tracklist file to disk.

Parameters:
  • dict_data (List[Dict[str, str]]) – list of dictionarie to save to disk, each dictionary in list contains tags of one album track
  • save_dir (Path) – directory to save to
wiki_music.utilities.parser_utils.complete_N_dim(to_complete: list, to_find: list)

Compares all elements fromm both lists and leaves the longer version.

Recursive function with two list as input, one list contains incomplete versions of strings and the other has full versions. Lists can be nested. both are then traversed and the strings in the first list are completed with strings from the second list. Changes are made in place.

Parameters:
  • to_complete (list) – argument is a list which elements are not complete. Changes to this list are made in-place.
  • to_find (list) – argument is the list which contains full strings. All uncomplete strings in to_complete will be replaced by their longer version from to_find

See also

_find_N_dim()

wiki_music.utilities.parser_utils.delete_N_dim(to_delete: list, to_find: list) → list

Deletes any items from to find in to_delete.

Recursive function with nested lists as input. The nested list elements are traversed and each that is equal to one of the elements in to_find list is deleted. Changes are made in place.

Parameters:
  • to_replace (list) – argument is a nested list which contains unwanted elements.
  • to_find (str) – list of unwanted elements
class wiki_music.utilities.parser_utils.ThreadPool(target: Callable[[...], list] = <function ThreadPool.<lambda>>, args: List[tuple] = [()])

Bases: object

Spawns pool of threads to excecute function.

If the list of arguments contains only one tuple, run the function in the calling thread to avoid unnecessary overhead as a result of spawning a new thread.

Parameters:
  • target (Callable) – callable that each thread should run
  • args (List[tuple]) – each tuple in list contains args for one thread running target
_progress_tracker(index, *args, **kwargs)

Wrap the callable passed to class constructor and report progress.

Parameters:
  • args (tuple) – arguments needed by callable
  • kwargs (dict) – keyword arguments needed by callable
run(timeout: Optional[float] = 60, serial: bool = False)

Starts the execution of threads in pool.

Returns after all threads join() metod has returned.

Note

To get the result results() must be called

See also

wiki_music.utilities.sync.ThreadPoolProgress
inform GUI of threadpool progress
results()
holds results values from threadpool
Parameters:
  • timeout (Optional[float]) – timeout after which waiting for results will be abandoned
  • serial (bool) – run threadpool in orderly fasion, mainly for debugging
run_async(timeout: Optional[float] = 60) → Generator[Any, None, None]

Starts the execution of threads in pool. Returns asynchronously.

This method yields resuls in order threds finish execution. Suitable for long running tasks. Results can be processed in main thread until other threads finish.

Note

For this method to make sense, tasks need to be longer running, and each should take at least slightly different time to complete and the folowwing processing of the results must take some time too.

See also

wiki_music.utilities.sync.ThreadPoolProgress
inform GUI of threadpool progress
Parameters:timeout (Optional[float]) – timeout after which waiting for results will be abandoned
Yields:list – list of returned values from the functions run by the ThreadPool
run_serial()

Starts the execution of threads in pool in serial fasion.

Note

To get the result results() must be called

See also

wiki_music.utilities.sync.ThreadPoolProgress
inform GUI of threadpool progress
results()
holds results values from threadpool

utilities.sync

Module for variable synchronization between application and GUI.

class wiki_music.utilities.sync.GuiLoggger

Bases: object

Class Implementing logging facility for GUI.

API copies that of python logging.Logger

progress

controlls main gui progressbar

Type:int
classmethod exception(msg: Union[Exception, str])

Exceptions to be displayed in GUI.

Exceptions can interupt running program, based on their severity.

Parameters:msg (str) – message text
classmethod info(msg: str)

Messages to be displayed in GUI progressbar.

Parameters:msg (str) – message text
classmethod warning(msg: Union[Exception, str])

Warnings to be displayed in GUI.

Warnings, only inform user but do not interupt the program.

Parameters:msg (str) – message text
class wiki_music.utilities.sync.IniSettings

Bases: object

Holds all package settings. All new settings are witten to disc.

All methods are thraed safe.

_parser: ConfigParser
dictionary-like object holding all settings
classmethod _dump()

Syncronize in-memory settings ini-parser object with disk file.

Has to be called in locked context.

classmethod delete(key: Hashable)

Delete specified key for settings dictionary.

Parameters:key (Hashable) – key to delete
classmethod read(key: Hashable, default: Any = None, _type: type = <class 'str'>) → Any

Get value from settings dictionary.

Parameters:
  • key (Hashable) – dictionary key
  • default (Any) – default value to return if key is not present
  • _type (type) – after read variable is cast to specisied type, as configparser always stores variables to string
Returns:

value found under key if it was found or default

Return type:

Any

classmethod write(key: Hashable, value: Any)

Write new value to settings dictionary and to disk.

Parameters:
  • key (Hashable) – dictionary key
  • value – value to write under key
class wiki_music.utilities.sync.Action(switch: str, message: Optional[str] = None, load: bool = False, options: list = [])

Bases: object

Represents action that should be taken by GUI.

Parameters:
  • switch (str) – type of action
  • message (Optional[str]) – message to show in GUI
  • load (bool) – whether to load data to GUI from parser prior to any action
  • options (list) – list of options to display in GUI for user to choose
  • response – property that caches GUI response
_queue

queue with actions gui should take

Type:Queue[Action]
_response_queue

GUI response to actions taken

Type:Queue[Action]

Warning

Action may be used only once, the response is cached and GUI will not be asked for new response on each call of response

classmethod get_nowait() → Optional[wiki_music.utilities.sync.Action]

Get the latest entry in the response queue or None if it is empty.

Returns:instance of the Action class or None
Return type:Optional[Action]
response

Pass Action to GUI, wait for response than return it.

Type:Any
class wiki_music.utilities.sync.Control(switch: str, message: Optional[str] = None, load: bool = False, options: list = [])

Bases: wiki_music.utilities.sync.Action

Passes flow control actions to GUI.

See also

Action

class wiki_music.utilities.sync.Progress(description: str = '', actual: int = 0, maximum: int = 0, finished: bool = False, busy: bool = False)

Bases: object

Class that informs GUI of parser progress.

Parameters:
  • desctiption (str) – desctiption of the ongoing action
  • actual_progress (int) – actual progress value
  • max_progress (int) – max progress value
  • finished (bool) – flag indicating that the background process has finished work
_queue

queue which describes parser progress

Type:Queue[Action]
classmethod get_actual_nowait() → Optional[wiki_music.utilities.sync.Progress]

Get the latest entry in the Progress queue or None if it is empty.

The method empties whole queue.

Returns:instance of the Progress class or None
Return type:Optional[Progress]
classmethod get_nowait() → Optional[wiki_music.utilities.sync.Progress]

Get the first entry in the Progress queue or None if it is empty.

Returns:instance of the Progress class or None
Return type:Optional[Progress]
class wiki_music.utilities.sync.ThreadPoolProgress(description: str = '', actual: int = 0, maximum: int = 0, finished: bool = False, busy: bool = False)

Bases: wiki_music.utilities.sync.Progress

Class that informs GUI of threadpool progress.

See also

Progress

utilities.utils

Basic utilities used by the whole package.

wiki_music.utilities.utils.list_files(work_dir: pathlib.Path, file_type: str = 'music', recurse: bool = True) → List[pathlib.Path]

List music files in directory.

Parameters:
  • work_dir (Path) – directory to search
  • file_type (str) – type of files to search
  • recurse (bool) – whether to preform the search recursively
Raises:

NotImplementedError – if file_type is unsupported

Note

supported music formats are: .m4a, .mp3, .flac, .alac, .wav, .wma, .ogg supprted image formats are: .jpg, .png Qt library has trouble reading other formats.

Returns:returns list of Path objects in folder with specified file_type
Return type:list
wiki_music.utilities.utils.to_bool(string: Union[str, bool]) → bool

Coverts string (yes, no, y, n adn capitalized versions) to bool.

Parameters:string (str) – Input value.

Note

all these values and their uprercase variants are considered true: y, yes, t, true, on, 1 <empty string>

Returns:truth value of given string
Return type:bool
wiki_music.utilities.utils.normalize(text: str) → str

NFKD string normalization.

Parameters:text (str) – text to normalize
Returns:normalized version of text
Return type:str
wiki_music.utilities.utils.we_are_frozen() → bool

Checks if the running code is frozen (e.g by cx-Freeze, pyinstaller).

Returns:True if the code is frozen
Return type:bool
wiki_music.utilities.utils.win_naming_convetion(string: str, dir_name=False) → str

Returns Windows normalized path name.

Forbiden characters are removed. If platworm is not windows string is returned without changes.

Parameters:
  • string (str) – Input path to normalize
  • dir_name (bool) – whether to use aditional normalization for directories
Returns:

normalized string for use in windows

Return type:

str

wiki_music.utilities.utils.flatten_set(array: List[list]) → set

Converst 2D list to 1D set.

Parameters:array (list) – 2D list to flatten
Returns:1D set made of serialized lists
Return type:set
wiki_music.utilities.utils.input_parser() → Tuple[bool, bool, bool, str, str, str, bool]

Parse command line input parameters.

Parameters:log (bool) – true when logger asks for argument parsing, to set the right level

Note

command line arguments are parsed and honoured only when running in CLI mode

Returns:
  • bool – json switch for outputing in json format
  • bool – offline_debug switch to turn on offline debugging
  • bool – lyrics_only search only for lyrics switch
  • str – album name
  • str – artist name
  • str – path to working directorym, default is current dir
  • bool – with_log switch on logging
  • bool – true if logging level is debug
class wiki_music.utilities.utils.MultiLog(logger)

Bases: object

Passes the messages to logger instance and to GuiLoggger.

Only where applicable as GuiLoggger does not implement whole Logger API

See also

wiki_music.utilities.sync.GuiLoggger
class passing the messages to GUI
Parameters:logger (logging.Logger) – Logger instance
critical(message: Any)

Issue a critical message.

debug(message: Any)

Issue a debug message.

error(message: Any)

Issue a error message.

exception(message: Any)

Issue a exception message.

info(message: Any)

Issue a info message.

warning(message: Any)

Issue a warning message.

wiki_music.utilities.utils.limited_input(dont_bother: bool) → Union[bool, str]

Prompt for cli input with limited options: y, n, d(dont bother me).

Returns:can be True, False or d for dont bother
Return type:Union[bool, str]
wiki_music.utilities.utils.set_signal_handler()

Registers signal handler for Ctrl-C (KeyboardInterupt) signals.

wiki_music.utilities.utils.lrange(iterable: Sized) → range

Returns iterable that spans list indices.

Parameters:iterable (Sized) – indices of this iterable will be looped through
Returns:range iterable running from 0 -> len(iterable)
Return type:range

utilities.wrappers

Fancy wrapper functions used in whole package.

wiki_music.utilities.wrappers.exception(logger: Logger, show_GUI: bool = True) → Callable

Wraps the passed in function and logs exceptions should one occure.

Messages are sent to gui through GuiLoggger and to logger. Application is not interupted.

Warning

Use with caution, only on critical parts of the code and not in early development stage as it will hide code errors

Parameters:
  • logger (logging.Logger) – logger instance whih will be recording occured errors
  • show_GUI (bool) – whether to show the exception message in GUI messagebox
Returns:

wrapped callable which will not crash app when it raises error

Return type:

Callable

wiki_music.utilities.wrappers.warning(logger: Logger, show_GUI: bool = True) → Callable

Catch and inform user of module defined exceptions.

A decorator that wraps the passed in function and logs wiki_music defined errors to logger warning. Messages are sent to gui through GuiLoggger.

Warning

Use with caution, only on critical parts of the code and not in early development stage as it will hide code errors

Parameters:
  • logger (logging.Logger) – logger instance whih will be recording occured errors
  • show_GUI (bool) – whether to show the warning message in GUI messagebox
Returns:

wrapped callable which will not crash app when it raises error

Return type:

Callable