Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Logs and codestyle #32

Merged
merged 3 commits into from
Jun 3, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
pydocstyle
  • Loading branch information
sezanzeb committed May 30, 2020
commit ea379142243a820f6cd048635785f86c09a0470a
19 changes: 7 additions & 12 deletions bin/soundconverter.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,7 @@
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
# USA

"""
SoundConverter Launcher.
"""

"""SoundConverter Launcher."""

# imports and package setup

Expand Down Expand Up @@ -67,8 +64,7 @@


def _add_soundconverter_path():
""" Makes the soundconverter package importable, which
has been installed to LIBDIR during make install """
"""Make the soundconverter package importable, which has been installed to LIBDIR during make install."""
root = os.path.join(LIBDIR, 'soundconverter', 'python')
if root not in sys.path:
sys.path.insert(0, root)
Expand Down Expand Up @@ -109,22 +105,21 @@ def mode_callback(option, opt, value, parser, **kwargs):


class ModifiedOptionParser(OptionParser):
"""
A OptionParser class that doesn't remove newlines on the epilog in order
to show usage examples https://stackoverflow.com/questions/1857346/
"""An OptionParser class that doesn't remove newlines on the epilog in order to show usage examples.

https://stackoverflow.com/questions/1857346/

See optparse.OptionParser for the original docstring
"""

def format_epilog(self, formatter):
if self.epilog is None:
return ""
return self.epilog


def parse_command_line():
""" Creates and returns the OptionParser, which parse the
command line arguments and displays help with --help. """

"""Create and return the OptionParser, which parse the command line arguments and displays help with --help."""
parser = ModifiedOptionParser(
epilog='\nExample:\n'
' soundconverter -b [file] [dir] -r -m audio/x-vorbis -s .ogg -o [output dir] -Q 4\n'
Expand Down
40 changes: 24 additions & 16 deletions soundconverter/batch.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
# USA

"""Batch mode to run soundconverter in a console."""

import os
import sys
Expand All @@ -37,11 +38,11 @@


def prepare_files_list(input_files):
""" Takes in a list of paths and returns a list of all the files in those paths, converted to URIs.
"""Take in a list of paths and return a list of all the files in those paths, converted to URIs.

Also returns a list of relative directories. This is used to reconstruct the directory structure in
the output path if -o is provided. """

the output path if -o is provided.
"""
# The GUI has its own way of going through subdirectories.
# Provide similar functionality to the cli.
# If one of the files is a directory, walk over the files in that
Expand Down Expand Up @@ -94,13 +95,13 @@ def prepare_files_list(input_files):


def cli_tags_main(input_files):
""" This function displays all the tags of the specified files in input_files in the console.
"""Display all the tags of the specified files in input_files in the console.

To go into subdirectories of paths provided, the -r command line argument should be provided,
which is stored in the global 'settings' variable.

input_files is an array of string paths. """

input_files is an array of string paths.
"""
input_files, _ = prepare_files_list(input_files)
error.set_error_handler(error.ErrorPrinter())
loop = GLib.MainLoop()
Expand All @@ -123,12 +124,17 @@ def cli_tags_main(input_files):


class CliProgress:
"""Class to overwrite a progress indication in the console without printing new lines."""

def __init__(self):
"""Initialize the class without printing anything yet."""
self.current_text = ''

def show(self, *msgs):
""" Update the progress in the console. Example: show(1, "%") """
"""Update the progress in the console.

Example: show(1, "%").
"""
new_text = ' '.join([str(msg) for msg in msgs])
if new_text != self.current_text:
self.clear()
Expand All @@ -137,21 +143,22 @@ def show(self, *msgs):
self.current_text = new_text

def clear(self):
""" Reverts the previously written message. Used in `show` """
"""Revert the previously written message. Used in `show`."""
sys.stdout.write('\b \b' * len(self.current_text))
sys.stdout.flush()


class CLI_Convert():
"""Main class that runs the conversion."""

def __init__(self, input_files):
""" This function starts the conversion of all the files specified in input_files.
"""Start the conversion of all the files specified in input_files.

To control the conversion and the handling of directories, command line arguments have to be
provided which are stored in the global 'settings' variable.

input_files is an array of string paths. """

input_files is an array of string paths.
"""
# check which files should be converted. The result is
# stored in file_checker.good_files
log('\nchecking files and walking dirs in the specified paths…')
Expand Down Expand Up @@ -206,7 +213,7 @@ def __init__(self, input_files):
continue

c = Converter(input_file, output_name, output_type)
c.add_listener('started', self.progress)
c.add_listener('started', self.print_progress)

if 'quality' in settings:
quality_setting = settings.get('quality')
Expand Down Expand Up @@ -236,7 +243,8 @@ def __init__(self, input_files):
# do another one to print the queue done message
context.iteration(True)

def progress(self, c):
def print_progress(self, c):
"""Print the filename that is currently being converted and how many files are left."""
self.started_tasks += 1
path = unquote_filename(beautify_uri(c.sound_file.uri))
log('{}/{}: \'{}\''.format(self.started_tasks, self.num_conversions, path))
Expand All @@ -245,7 +253,7 @@ def progress(self, c):
class CLI_Check():

def __init__(self, input_files, silent=False):
""" This class prints all the tags of the specified files in input_files to the console.
"""Print all the tags of the specified files in input_files to the console.

To go into subdirectories of paths provided, the -r command line argument should be provided,
which is stored in the global 'settings' variable.
Expand All @@ -255,8 +263,8 @@ def __init__(self, input_files, silent=False):
silent=True makes this print no output, no matter the -q argument of soundconverter

It will exit the tool if input_files contains no files
(maybe because -r is missing and the specified path is a dir) """

(maybe because -r is missing and the specified path is a dir)
"""
input_files, subdirectories = prepare_files_list(input_files)

if len(input_files) == 0:
Expand Down
11 changes: 6 additions & 5 deletions soundconverter/fileoperations.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ def beautify_uri(uri):


def vfs_walk(uri):
""" similar to os.path.walk, but with Gio.
"""Similar to os.path.walk, but with Gio.

uri -- the base folder uri.
return a list of uri.
Expand All @@ -58,19 +58,19 @@ def vfs_walk(uri):


def vfs_getparent(path):
""" Get folder name. """
"""Get folder name."""
gfile = Gio.file_parse_name(path)
return gfile.get_parent()


def vfs_unlink(filename):
""" Delete a gnomevfs file. """
"""Delete a gnomevfs file."""
gfile = Gio.file_parse_name(filename)
return gfile.delete(None)


def vfs_rename(original, newname):
""" Rename a gnomevfs file """
"""Rename a gnomevfs file."""
gforiginal = Gio.file_parse_name(original)
gfnew = Gio.file_parse_name(newname)
debug('Creating folder \'%s\'?' % gfnew.get_parent().get_uri())
Expand All @@ -86,7 +86,8 @@ def vfs_exists(filename):


def filename_to_uri(filename):
""" Convert a filename to a valid uri.
"""Convert a filename to a valid uri.

Filename can be a relative or absolute path, or an uri.
"""
if ':https://' not in filename:
Expand Down
33 changes: 17 additions & 16 deletions soundconverter/gstreamer.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ def gtk_sleep(duration):


class Pipeline(BackgroundTask):
""" A background task for running a GstPipeline. """
"""A background task for running a GstPipeline."""

def __init__(self):
BackgroundTask.__init__(self)
Expand Down Expand Up @@ -237,7 +237,7 @@ def on_message(self, bus, message):
self.error = error
self.on_error(error)
self.done()
""" XXX elif Gst.pbutils.is_missing_plugin_message(message):
"""XXX elif Gst.pbutils.is_missing_plugin_message(message):
global user_canceled_codec_installation
detail = Gst.pbutils.missing_plugin_message_get_installer_detail(message)
debug('missing plugin:', detail.split('|')[3], self.sound_file.uri)
Expand Down Expand Up @@ -307,7 +307,7 @@ def get_position(self):
return NotImplementedError

def query_duration(self):
""" Ask for the duration of the current pipeline. """
"""Ask for the duration of the current pipeline."""
try:
if not self.sound_file.duration and self.pipeline:
self.sound_file.duration = self.pipeline.query_duration(Gst.Format.TIME)[1] / Gst.SECOND
Expand All @@ -333,9 +333,10 @@ def __init__(self, sound_file, silent=False):
self.silent = silent

def log(self, *args):
""" the output of TypeFinder can be disabled either with
the -q command line option or by setting self.silent to
True """
"""Print a line to the console, but only when the TypeFinder itself is not set to silent.

It can also be disabled with the -q command line option.
"""
if not self.silent:
log(*args)

Expand All @@ -347,7 +348,7 @@ def set_found_type_hook(self, found_type_hook):
self.found_type_hook = found_type_hook

def pad_added(self, decoder, pad):
""" called when a decoded pad is created """
"""Called when a decoded pad is created."""
self.query_duration()
self.done()

Expand Down Expand Up @@ -377,7 +378,7 @@ def finished(self):


class Decoder(Pipeline):
""" A GstPipeline background task that decodes data and finds tags. """
"""A GstPipeline background task that decodes data and finds tags."""

def __init__(self, sound_file):
Pipeline.__init__(self)
Expand All @@ -394,7 +395,7 @@ def have_type(self, typefind, probability, caps):
pass

def query_position(self):
""" Ask for the stream position of the current pipeline. """
"""Ask for the stream position of the current pipeline."""
try:
if self.pipeline:
self.position = max(0, self.pipeline.query_position(
Expand All @@ -403,7 +404,7 @@ def query_position(self):
self.position = 0

def found_tag(self, decoder, something, taglist):
""" Called when the decoder reads a tag. """
"""Called when the decoder reads a tag."""
debug('found_tags:', self.sound_file.filename_for_display)
taglist.foreach(self.append_tag, None)

Expand Down Expand Up @@ -448,7 +449,7 @@ def append_tag(self, taglist, tag, unused_udata):
self.sound_file.tags.update(tags)

def pad_added(self, decoder, pad):
""" called when a decoded pad is created """
"""Called when a decoded pad is created."""
self.processing = True
self.query_duration()

Expand All @@ -462,17 +463,17 @@ def get_input_uri(self):
return self.sound_file.uri

def get_duration(self):
""" return the total duration of the sound file """
"""Return the total duration of the sound file."""
return self.sound_file.duration

def get_position(self):
""" return the current pipeline position in the stream """
"""Return the current pipeline position in the stream."""
self.query_position()
return self.position


class TagReader(Decoder):
""" A GstPipeline background task for finding meta tags in a file. """
"""A GstPipeline background task for finding meta tags in a file."""

def __init__(self, sound_file):
Decoder.__init__(self, sound_file)
Expand Down Expand Up @@ -502,7 +503,7 @@ def finished(self):


class Converter(Decoder):
""" A background task for converting files to another format. """
"""A background task for converting files to another format."""

def __init__(self, sound_file, output_filename, output_type,
delete_original=False, output_resample=False,
Expand Down Expand Up @@ -680,7 +681,7 @@ def add_audio_profile(self):


class ConverterQueue(TaskQueue):
""" Background task for converting many files. """
"""Background task for converting many files."""

def __init__(self, window):
TaskQueue.__init__(self)
Expand Down
2 changes: 1 addition & 1 deletion soundconverter/namegenerator.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@


class TargetNameGenerator:
""" Generator for creating the target name from an input name. """
"""Generator for creating the target name from an input name."""

def __init__(self):
self.folder = None
Expand Down
10 changes: 5 additions & 5 deletions soundconverter/queue.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@


class TaskQueue(BackgroundTask):
""" A queue of tasks.
"""A queue of tasks.

A task queue is a queue of other tasks. If you need, for example, to
do simple tasks A, B, and C, you can create a TaskQueue and add the
Expand All @@ -39,7 +39,7 @@ class TaskQueue(BackgroundTask):
q.start()

The task queue behaves as a single task. It will execute the
tasks in order and start the next one when the previous finishes. """
tasks in order and start the next one when the previous finishes."""

def __init__(self):
BackgroundTask.__init__(self)
Expand All @@ -53,7 +53,7 @@ def __init__(self):
self.jobs = self.jobs or settings['cpu-count']

def add_task(self, task):
""" Add a task to the queue. """
"""Add a task to the queue."""
self.waiting_tasks.append(task)
# if self.start_time and not self.running_tasks:
if self.start_time:
Expand Down Expand Up @@ -82,7 +82,7 @@ def start_next_task(self):
self.progress = float(self.finished_tasks) / total if total else 0

def started(self):
""" BackgroundTask setup callback """
"""BackgroundTask setup callback."""
log('Queue start: %d tasks, %d thread(s).' % (
len(self.waiting_tasks) + len(self.running_tasks), self.jobs))
self.count = 0
Expand All @@ -92,7 +92,7 @@ def started(self):
self.start_next_task()

def finished(self):
""" BackgroundTask finish callback """
"""BackgroundTask finish callback."""
log('Queue done in %.3fs (%s tasks)' % (time.time() - self.start_time, self.count))
self.queue_ended()
self.count = 0
Expand Down
Loading