INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Returns time zone in tzdata format ( e. g. America/ New_York or Europe/ Paris )
def time_zone_by_addr(self, addr): """ Returns time zone in tzdata format (e.g. America/New_York or Europe/Paris) :arg addr: IP address (e.g. 203.0.113.30) """ if self._databaseType not in const.CITY_EDITIONS: message = 'Invalid database type, expected City' ...
Returns time zone in tzdata format ( e. g. America/ New_York or Europe/ Paris )
def time_zone_by_name(self, hostname): """ Returns time zone in tzdata format (e.g. America/New_York or Europe/Paris) :arg hostname: Hostname (e.g. example.com) """ addr = self._gethostbyname(hostname) return self.time_zone_by_addr(addr)
Returns time zone from country and region code.
def time_zone_by_country_and_region(country_code, region_code=None): """ Returns time zone from country and region code. :arg country_code: Country code :arg region_code: Region code """ timezone = country_dict.get(country_code) if not timezone: return None if isinstance(timezo...
Compress a file only if needed.
def compress(self, filename): """Compress a file, only if needed.""" compressed_filename = self.get_compressed_filename(filename) if not compressed_filename: return self.do_compress(filename, compressed_filename)
If the given filename should be compressed returns the compressed filename.
def get_compressed_filename(self, filename): """If the given filename should be compressed, returns the compressed filename. A file can be compressed if: - It is a whitelisted extension - The compressed file does not exist - The compressed file exists by is older than t...
Copy or symlink the file.
def copy(src, dst, symlink=False, rellink=False): """Copy or symlink the file.""" func = os.symlink if symlink else shutil.copy2 if symlink and os.path.lexists(dst): os.remove(dst) if rellink: # relative symlink from dst func(os.path.relpath(src, os.path.dirname(dst)), dst) else: ...
Transform path to url converting backslashes to slashes if needed.
def url_from_path(path): """Transform path to url, converting backslashes to slashes if needed.""" if os.sep != '/': path = '/'.join(path.split(os.sep)) return quote(path)
Reads markdown file converts output and fetches title and meta - data for further processing.
def read_markdown(filename): """Reads markdown file, converts output and fetches title and meta-data for further processing. """ global MD # Use utf-8-sig codec to remove BOM if it is present. This is only possible # this way prior to feeding the text to the markdown parser (which would # al...
Loads the exif data of all images in an album from cache
def load_exif(album): """Loads the exif data of all images in an album from cache""" if not hasattr(album.gallery, "exifCache"): _restore_cache(album.gallery) cache = album.gallery.exifCache for media in album.medias: if media.type == "image": key = os.path.join(media.path, ...
Restores the exif data cache from the cache file
def _restore_cache(gallery): """Restores the exif data cache from the cache file""" cachePath = os.path.join(gallery.settings["destination"], ".exif_cache") try: if os.path.exists(cachePath): with open(cachePath, "rb") as cacheFile: gallery.exifCache = pickle.load(cacheFi...
Stores the exif data of all images in the gallery
def save_cache(gallery): """Stores the exif data of all images in the gallery""" if hasattr(gallery, "exifCache"): cache = gallery.exifCache else: cache = gallery.exifCache = {} for album in gallery.albums.values(): for image in album.images: cache[os.path.join(imag...
Removes all filtered Media and subdirs from an Album
def filter_nomedia(album, settings=None): """Removes all filtered Media and subdirs from an Album""" nomediapath = os.path.join(album.src_path, ".nomedia") if os.path.isfile(nomediapath): if os.path.getsize(nomediapath) == 0: logger.info("Ignoring album '%s' because of present 0-byte " ...
Copy a sample config file in the current directory ( default to sigal. conf. py ) or use the provided path.
def init(path): """Copy a sample config file in the current directory (default to 'sigal.conf.py'), or use the provided 'path'.""" if os.path.isfile(path): print("Found an existing config file, will abort to keep it safe.") sys.exit(1) from pkg_resources import resource_string conf...
Run sigal to process a directory.
def build(source, destination, debug, verbose, force, config, theme, title, ncpu): """Run sigal to process a directory. If provided, 'source', 'destination' and 'theme' will override the corresponding values from the settings file. """ level = ((debug and logging.DEBUG) or (verbose and l...
Load plugins and call register ().
def init_plugins(settings): """Load plugins and call register().""" logger = logging.getLogger(__name__) logger.debug('Plugin paths: %s', settings['plugin_paths']) for path in settings['plugin_paths']: sys.path.insert(0, path) for plugin in settings['plugins']: try: if...
Run a simple web server.
def serve(destination, port, config): """Run a simple web server.""" if os.path.exists(destination): pass elif os.path.exists(config): settings = read_settings(config) destination = settings.get('destination') if not os.path.exists(destination): sys.stderr.write("...
Write metadata keys to. md file.
def set_meta(target, keys, overwrite=False): """Write metadata keys to .md file. TARGET can be a media file or an album directory. KEYS are key/value pairs. Ex, to set the title of test.jpg to "My test image": sigal set_meta test.jpg title "My test image" """ if not os.path.exists(target): ...
Image processor rotate and resize the image.
def generate_image(source, outname, settings, options=None): """Image processor, rotate and resize the image. :param source: path to an image :param outname: output filename :param settings: settings dict :param options: dict with PIL options (quality, optimize, progressive) """ logger = ...
Create a thumbnail image.
def generate_thumbnail(source, outname, box, fit=True, options=None, thumb_fit_centering=(0.5, 0.5)): """Create a thumbnail image.""" logger = logging.getLogger(__name__) img = _read_image(source) original_format = img.format if fit: img = ImageOps.fit(img, box, PILI...
Process one image: resize create thumbnail.
def process_image(filepath, outpath, settings): """Process one image: resize, create thumbnail.""" logger = logging.getLogger(__name__) logger.info('Processing %s', filepath) filename = os.path.split(filepath)[1] outname = os.path.join(outpath, filename) ext = os.path.splitext(filename)[1] ...
Return image size ( width and height ).
def get_size(file_path): """Return image size (width and height).""" try: im = _read_image(file_path) except (IOError, IndexError, TypeError, AttributeError) as e: logger = logging.getLogger(__name__) logger.error("Could not read size of %s due to %r", file_path, e) else: ...
Return a dict with the raw EXIF data.
def get_exif_data(filename): """Return a dict with the raw EXIF data.""" logger = logging.getLogger(__name__) img = _read_image(filename) try: exif = img._getexif() or {} except ZeroDivisionError: logger.warning('Failed to read EXIF data.') return None data = {TAGS.ge...
Return a dict with the raw IPTC data.
def get_iptc_data(filename): """Return a dict with the raw IPTC data.""" logger = logging.getLogger(__name__) iptc_data = {} raw_iptc = {} # PILs IptcImagePlugin issues a SyntaxError in certain circumstances # with malformed metadata, see PIL/IptcImagePlugin.py", line 71. # ( https://gith...
Convert degree/ minute/ second to decimal degrees.
def dms_to_degrees(v): """Convert degree/minute/second to decimal degrees.""" d = float(v[0][0]) / float(v[0][1]) m = float(v[1][0]) / float(v[1][1]) s = float(v[2][0]) / float(v[2][1]) return d + (m / 60.0) + (s / 3600.0)
Make a simplified version with common tags from raw EXIF data.
def get_exif_tags(data, datetime_format='%c'): """Make a simplified version with common tags from raw EXIF data.""" logger = logging.getLogger(__name__) simple = {} for tag in ('Model', 'Make', 'LensModel'): if tag in data: if isinstance(data[tag], tuple): simple[ta...
Path to the original image if keep_orig is set ( relative to the album directory ). Copy the file if needed.
def big(self): """Path to the original image, if ``keep_orig`` is set (relative to the album directory). Copy the file if needed. """ if self.settings['keep_orig']: s = self.settings if s['use_orig']: # The image *is* the original, just use it ...
Path to the thumbnail image ( relative to the album directory ).
def thumbnail(self): """Path to the thumbnail image (relative to the album directory).""" if not isfile(self.thumb_path): self.logger.debug('Generating thumbnail for %r', self) path = (self.dst_path if os.path.exists(self.dst_path) else self.src_path) ...
Get image metadata from filename. md: title description meta.
def _get_metadata(self): """ Get image metadata from filename.md: title, description, meta.""" self.description = '' self.meta = {} self.title = '' descfile = splitext(self.src_path)[0] + '.md' if isfile(descfile): meta = read_markdown(descfile) f...
Get album metadata from description_file ( index. md ):
def _get_metadata(self): """Get album metadata from `description_file` (`index.md`): -> title, thumbnail image, description """ descfile = join(self.src_path, self.description_file) self.description = '' self.meta = {} # default: get title from directory name ...
Create output directories for thumbnails and original images.
def create_output_directories(self): """Create output directories for thumbnails and original images.""" check_or_create_dir(self.dst_path) if self.medias: check_or_create_dir(join(self.dst_path, self.settings['thumb_dir'])) if self.medi...
List of: class: ~sigal. gallery. Album objects for each sub - directory.
def albums(self): """List of :class:`~sigal.gallery.Album` objects for each sub-directory. """ root_path = self.path if self.path != '.' else '' return [self.gallery.albums[join(root_path, path)] for path in self.subdirs]
URL of the album relative to its parent.
def url(self): """URL of the album, relative to its parent.""" url = self.name.encode('utf-8') return url_quote(url) + '/' + self.url_ext
Path to the thumbnail of the album.
def thumbnail(self): """Path to the thumbnail of the album.""" if self._thumbnail: # stop if it is already set return self._thumbnail # Test the thumbnail from the Markdown file. thumbnail = self.meta.get('thumbnail', [''])[0] if thumbnail and isfile(jo...
List of ( url title ) tuples defining the current breadcrumb path.
def breadcrumb(self): """List of ``(url, title)`` tuples defining the current breadcrumb path. """ if self.path == '.': return [] path = self.path breadcrumb = [((self.url_ext or '.'), self.title)] while True: path = os.path.normpath(os.p...
Make a ZIP archive with all media files and return its path.
def zip(self): """Make a ZIP archive with all media files and return its path. If the ``zip_gallery`` setting is set,it contains the location of a zip archive with all original images of the corresponding directory. """ zip_gallery = self.settings['zip_gallery'] if zip...
Return the list of all sub - directories of path.
def get_albums(self, path): """Return the list of all sub-directories of path.""" for name in self.albums[path].subdirs: subdir = os.path.normpath(join(path, name)) yield subdir, self.albums[subdir] for subname, album in self.get_albums(subdir): yield...
Create the image gallery
def build(self, force=False): "Create the image gallery" if not self.albums: self.logger.warning("No albums found.") return def log_func(x): # 63 is the total length of progressbar, label, percentage, etc available_length = get_terminal_size()[0]...
Process a list of images in a directory.
def process_dir(self, album, force=False): """Process a list of images in a directory.""" for f in album: if isfile(f.dst_path) and not force: self.logger.info("%s exists - skipping", f.filename) self.stats[f.type + '_skipped'] += 1 else: ...
Returns an image with reduced opacity.
def reduce_opacity(im, opacity): """Returns an image with reduced opacity.""" assert opacity >= 0 and opacity <= 1 if im.mode != 'RGBA': im = im.convert('RGBA') else: im = im.copy() alpha = im.split()[3] alpha = ImageEnhance.Brightness(alpha).enhance(opacity) im.putalpha(alph...
Adds a watermark to an image.
def watermark(im, mark, position, opacity=1): """Adds a watermark to an image.""" if opacity < 1: mark = reduce_opacity(mark, opacity) if im.mode != 'RGBA': im = im.convert('RGBA') # create a transparent layer the size of the image and draw the # watermark in that layer. layer = ...
Run the command to resize the video and remove the output file if the processing fails.
def check_subprocess(cmd, source, outname): """Run the command to resize the video and remove the output file if the processing fails. """ logger = logging.getLogger(__name__) try: res = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) exc...
Returns the dimensions of the video.
def video_size(source, converter='ffmpeg'): """Returns the dimensions of the video.""" res = subprocess.run([converter, '-i', source], stderr=subprocess.PIPE) stderr = res.stderr.decode('utf8') pattern = re.compile(r'Stream.*Video.* ([0-9]+)x([0-9]+)') match = pattern.search(stderr) rot_pattern...
Video processor.
def generate_video(source, outname, settings, options=None): """Video processor. :param source: path to a video :param outname: path to the generated video :param settings: settings dict :param options: array of options passed to ffmpeg """ logger = logging.getLogger(__name__) # Don't...
Create a thumbnail image for the video source based on ffmpeg.
def generate_thumbnail(source, outname, box, delay, fit=True, options=None, converter='ffmpeg'): """Create a thumbnail image for the video source, based on ffmpeg.""" logger = logging.getLogger(__name__) tmpfile = outname + ".tmp.jpg" # dump an image of the video cmd = [conv...
Process a video: resize create thumbnail.
def process_video(filepath, outpath, settings): """Process a video: resize, create thumbnail.""" logger = logging.getLogger(__name__) filename = os.path.split(filepath)[1] basename, ext = splitext(filename) try: if settings['use_orig'] and is_valid_html5_video(ext): outname = o...
Logging config
def init_logging(name, level=logging.INFO): """Logging config Set the level and create a more detailed formatter for debug mode. """ logger = logging.getLogger(name) logger.setLevel(level) try: if os.isatty(sys.stdout.fileno()) and \ not sys.platform.startswith('win'):...
Generate the context dict for the given path.
def generate_context(self, album): """Generate the context dict for the given path.""" from . import __url__ as sigal_link self.logger.info("Output album : %r", album) return { 'album': album, 'index_title': self.index_title, 'settings': self.settings...
Generate the HTML page and save it.
def write(self, album): """Generate the HTML page and save it.""" page = self.template.render(**self.generate_context(album)) output_file = os.path.join(album.dst_path, album.output_file) with open(output_file, 'w', encoding='utf-8') as f: f.write(page)
Return the path to the thumb.
def get_thumb(settings, filename): """Return the path to the thumb. examples: >>> default_settings = create_settings() >>> get_thumb(default_settings, "bar/foo.jpg") "bar/thumbnails/foo.jpg" >>> get_thumb(default_settings, "bar/foo.png") "bar/thumbnails/foo.png" for videos, it returns ...
Read settings from a config file in the source_dir root.
def read_settings(filename=None): """Read settings from a config file in the source_dir root.""" logger = logging.getLogger(__name__) logger.info("Reading settings ...") settings = _DEFAULT_CONFIG.copy() if filename: logger.debug("Settings file: %s", filename) settings_path = os.pa...
Generates and writes the media pages for all media in the gallery
def generate_media_pages(gallery): '''Generates and writes the media pages for all media in the gallery''' writer = PageWriter(gallery.settings, index_title=gallery.title) for album in gallery.albums.values(): medias = album.medias next_medias = medias[1:] + [None] previous_medias ...
Generate the media page and save it
def write(self, album, media_group): ''' Generate the media page and save it ''' from sigal import __url__ as sigal_link file_path = os.path.join(album.dst_path, media_group[0].filename) page = self.template.render({ 'album': album, 'media': media_group[0], ...
Here we do some ** really ** basic environment sanity checks.
def check_install(config_data): """ Here we do some **really** basic environment sanity checks. Basically we test for the more delicate and failing-prone dependencies: * database driver * Pillow image format support Many other errors will go undetected """ errors = [] # PIL test...
Asks user for removal of project directory and eventually removes it
def cleanup_directory(config_data): """ Asks user for removal of project directory and eventually removes it """ if os.path.exists(config_data.project_directory): choice = False if config_data.noinput is False and not config_data.verbose: choice = query_yes_no( ...
Check the defined project name against keywords builtins and existing modules to avoid name clashing
def validate_project(project_name): """ Check the defined project name against keywords, builtins and existing modules to avoid name clashing """ if '-' in project_name: return None if keyword.iskeyword(project_name): return None if project_name in dir(__builtins__): ...
Define the available arguments
def parse(args): """ Define the available arguments """ from tzlocal import get_localzone try: timezone = get_localzone() if isinstance(timezone, pytz.BaseTzInfo): timezone = timezone.zone except Exception: # pragma: no cover timezone = 'UTC' if timezone...
Checks and validate provided input
def _manage_args(parser, args): """ Checks and validate provided input """ for item in data.CONFIGURABLE_OPTIONS: action = parser._option_string_actions[item] choices = default = '' input_value = getattr(args, action.dest) new_val = None # cannot count this until...
Ask a yes/ no question via raw_input () and return their answer.
def query_yes_no(question, default=None): # pragma: no cover """ Ask a yes/no question via `raw_input()` and return their answer. :param question: A string that is presented to the user. :param default: The presumed answer if the user just hits <Enter>. It must be "yes" (the defaul...
Convert numeric and literal version information to numeric format
def supported_versions(django, cms): """ Convert numeric and literal version information to numeric format """ cms_version = None django_version = None try: cms_version = Decimal(cms) except (ValueError, InvalidOperation): try: cms_version = CMS_VERSION_MATRIX[st...
Converts the current version to the next one for inserting into requirements in the < version format
def less_than_version(value): """ Converts the current version to the next one for inserting into requirements in the ' < version' format """ items = list(map(int, str(value).split('.'))) if len(items) == 1: items.append(0) items[1] += 1 if value == '1.11': return '2.0' ...
Returns val as integer or as escaped string according to its value: param val: any value: return: formatted string
def format_val(val): """ Returns val as integer or as escaped string according to its value :param val: any value :return: formatted string """ val = text_type(val) if val.isdigit(): return int(val) else: return '\'{0}\''.format(val)
Parse config file.
def parse_config_file(parser, stdin_args): """Parse config file. Returns a list of additional args. """ config_args = [] # Temporary switch required args and save them to restore. required_args = [] for action in parser._actions: if action.required: required_args.append...
Dump args to config file.
def dump_config_file(filename, args, parser=None): """Dump args to config file.""" config = ConfigParser() config.add_section(SECTION) if parser is None: for attr in args: config.set(SECTION, attr, args.attr) else: keys_empty_values_not_pass = ( '--extra-setti...
Convert config options to stdin args.
def _convert_config_to_stdin(config, parser): """Convert config options to stdin args. Especially boolean values, for more information @see https://docs.python.org/3.4/library/configparser.html#supported-datatypes """ keys_empty_values_not_pass = ( '--extra-settings', '--languages', '--requ...
Call django - admin to create the project structure
def create_project(config_data): """ Call django-admin to create the project structure :param config_data: configuration data """ env = deepcopy(dict(os.environ)) env[str('DJANGO_SETTINGS_MODULE')] = str('{0}.settings'.format(config_data.project_name)) env[str('PYTHONPATH')] = str(os.pathse...
Detect migrations layout for plugins: param vars: installer settings: param apps: installed applications
def _detect_migration_layout(vars, apps): """ Detect migrations layout for plugins :param vars: installer settings :param apps: installed applications """ DJANGO_MODULES = {} for module in vars.MIGRATIONS_CHECK_MODULES: if module in apps: try: mod = __imp...
Install aldryn boilerplate
def _install_aldryn(config_data): # pragma: no cover """ Install aldryn boilerplate :param config_data: configuration data """ import requests media_project = os.path.join(config_data.project_directory, 'dist', 'media') static_main = False static_project = os.path.join(config_data.proj...
It s a little rude actually: it just overwrites the django - generated urls. py with a custom version and put other files in the project directory.
def copy_files(config_data): """ It's a little rude actually: it just overwrites the django-generated urls.py with a custom version and put other files in the project directory. :param config_data: configuration data """ if config_data.i18n == 'yes': urlconf_path = os.path.join(os.path....
Modify the settings file created by Django injecting the django CMS configuration
def patch_settings(config_data): """ Modify the settings file created by Django injecting the django CMS configuration :param config_data: configuration data """ import django current_django_version = LooseVersion(django.__version__) declared_django_version = LooseVersion(config_data.dj...
Build the django CMS settings dictionary
def _build_settings(config_data): """ Build the django CMS settings dictionary :param config_data: configuration data """ spacer = ' ' text = [] vars = get_settings() vars.MIDDLEWARE_CLASSES.insert(0, vars.APPHOOK_RELOAD_MIDDLEWARE_CLASS) processors = vars.TEMPLATE_CONTEXT_PROC...
Run the migrate command to create the database schema
def setup_database(config_data): """ Run the migrate command to create the database schema :param config_data: configuration data """ with chdir(config_data.project_directory): env = deepcopy(dict(os.environ)) env[str('DJANGO_SETTINGS_MODULE')] = str('{0}.settings'.format(config_dat...
Create admin user without user input
def create_user(config_data): """ Create admin user without user input :param config_data: configuration data """ with chdir(os.path.abspath(config_data.project_directory)): env = deepcopy(dict(os.environ)) env[str('DJANGO_SETTINGS_MODULE')] = str('{0}.settings'.format(config_data.p...
Pass an argument list to SoX.
def sox(args): '''Pass an argument list to SoX. Parameters ---------- args : iterable Argument list for SoX. The first item can, but does not need to, be 'sox'. Returns: -------- status : bool True on success. ''' if args[0].lower() != "sox": args.i...
Calls SoX help for a lists of audio formats available with the current install of SoX.
def _get_valid_formats(): ''' Calls SoX help for a lists of audio formats available with the current install of SoX. Returns: -------- formats : list List of audio file extensions that SoX can process. ''' if NO_SOX: return [] so = subprocess.check_output(['sox', '-h']...
Base call to SoXI.
def soxi(filepath, argument): ''' Base call to SoXI. Parameters ---------- filepath : str Path to audio file. argument : str Argument to pass to SoXI. Returns ------- shell_output : str Command line output of SoXI ''' if argument not in SOXI_ARGS: ...
Pass an argument list to play.
def play(args): '''Pass an argument list to play. Parameters ---------- args : iterable Argument list for play. The first item can, but does not need to, be 'play'. Returns: -------- status : bool True on success. ''' if args[0].lower() != "play": a...
Validate that combine method can be performed with given files. Raises IOError if input file formats are incompatible.
def _validate_file_formats(input_filepath_list, combine_type): '''Validate that combine method can be performed with given files. Raises IOError if input file formats are incompatible. ''' _validate_sample_rates(input_filepath_list, combine_type) if combine_type == 'concatenate': _validate_...
Check if files in input file list have the same sample rate
def _validate_sample_rates(input_filepath_list, combine_type): ''' Check if files in input file list have the same sample rate ''' sample_rates = [ file_info.sample_rate(f) for f in input_filepath_list ] if not core.all_equal(sample_rates): raise IOError( "Input files do ...
Check if files in input file list have the same number of channels
def _validate_num_channels(input_filepath_list, combine_type): ''' Check if files in input file list have the same number of channels ''' channels = [ file_info.channels(f) for f in input_filepath_list ] if not core.all_equal(channels): raise IOError( "Input files do not ...
Set input formats given input_volumes.
def _build_input_format_list(input_filepath_list, input_volumes=None, input_format=None): '''Set input formats given input_volumes. Parameters ---------- input_filepath_list : list of str List of input files input_volumes : list of float, default=None Li...
Builds input arguments by stitching input filepaths and input formats together.
def _build_input_args(input_filepath_list, input_format_list): ''' Builds input arguments by stitching input filepaths and input formats together. ''' if len(input_format_list) != len(input_filepath_list): raise ValueError( "input_format_list & input_filepath_list are not the same si...
Check input_volumes contains a valid list of volumes.
def _validate_volumes(input_volumes): '''Check input_volumes contains a valid list of volumes. Parameters ---------- input_volumes : list list of volume values. Castable to numbers. ''' if not (input_volumes is None or isinstance(input_volumes, list)): raise TypeError("input_vo...
Builds the output_file by executing the current set of commands.
def build(self, input_filepath_list, output_filepath, combine_type, input_volumes=None): '''Builds the output_file by executing the current set of commands. Parameters ---------- input_filepath_list : list of str List of paths to input audio files. outp...
Play a preview of the output with the current set of effects
def preview(self, input_filepath_list, combine_type, input_volumes=None): '''Play a preview of the output with the current set of effects Parameters ---------- input_filepath_list : list of str List of paths to input audio files. combine_type : str Input ...
Sets input file format arguments. This is primarily useful when dealing with audio files without a file extension. Overwrites any previously set input file arguments.
def set_input_format(self, file_type=None, rate=None, bits=None, channels=None, encoding=None, ignore_length=None): '''Sets input file format arguments. This is primarily useful when dealing with audio files without a file extension. Overwrites any previously set input f...
Number of bits per sample ( 0 if not applicable ).
def bitrate(input_filepath): ''' Number of bits per sample (0 if not applicable). Parameters ---------- input_filepath : str Path to audio file. Returns ------- bitrate : int number of bits per sample returns 0 if not applicable ''' validate_input_file(i...
Show duration in seconds ( 0 if unavailable ).
def duration(input_filepath): ''' Show duration in seconds (0 if unavailable). Parameters ---------- input_filepath : str Path to audio file. Returns ------- duration : float Duration of audio file in seconds. If unavailable or empty, returns 0. ''' vali...
Show number of samples ( 0 if unavailable ).
def num_samples(input_filepath): ''' Show number of samples (0 if unavailable). Parameters ---------- input_filepath : str Path to audio file. Returns ------- n_samples : int total number of samples in audio file. Returns 0 if empty or unavailable ''' va...
Determine if an input file is silent.
def silent(input_filepath, threshold=0.001): ''' Determine if an input file is silent. Parameters ---------- input_filepath : str The input filepath. threshold : float Threshold for determining silence Returns ------- is_silent : bool True if file is determi...
Input file validation function. Checks that file exists and can be processed by SoX.
def validate_input_file(input_filepath): '''Input file validation function. Checks that file exists and can be processed by SoX. Parameters ---------- input_filepath : str The input filepath. ''' if not os.path.exists(input_filepath): raise IOError( "input_filep...
Input file list validation function. Checks that object is a list and contains valid filepaths that can be processed by SoX.
def validate_input_file_list(input_filepath_list): '''Input file list validation function. Checks that object is a list and contains valid filepaths that can be processed by SoX. Parameters ---------- input_filepath_list : list A list of filepaths. ''' if not isinstance(input_filep...
Output file validation function. Checks that file can be written and has a valid file extension. Throws a warning if the path already exists as it will be overwritten on build.
def validate_output_file(output_filepath): '''Output file validation function. Checks that file can be written, and has a valid file extension. Throws a warning if the path already exists, as it will be overwritten on build. Parameters ---------- output_filepath : str The output filepat...
Get a dictionary of file information
def info(filepath): '''Get a dictionary of file information Parameters ---------- filepath : str File path. Returns: -------- info_dictionary : dict Dictionary of file information. Fields are: * channels * sample_rate * bitrate ...
Call sox s stat function.
def _stat_call(filepath): '''Call sox's stat function. Parameters ---------- filepath : str File path. Returns ------- stat_output : str Sox output from stderr. ''' validate_input_file(filepath) args = ['sox', filepath, '-n', 'stat'] _, _, stat_output = sox(...
Parse the string output from sox s stat function
def _parse_stat(stat_output): '''Parse the string output from sox's stat function Parameters ---------- stat_output : str Sox output from stderr. Returns ------- stat_dictionary : dict Dictionary of audio statistics. ''' lines = stat_output.split('\n') stat_dict...
Sets SoX s global arguments. Overwrites any previously set global arguments. If this function is not explicity called globals are set to this function s defaults.
def set_globals(self, dither=False, guard=False, multithread=False, replay_gain=False, verbosity=2): '''Sets SoX's global arguments. Overwrites any previously set global arguments. If this function is not explicity called, globals are set to this function's defaults. ...
Sets input file format arguments. This is primarily useful when dealing with audio files without a file extension. Overwrites any previously set input file arguments.
def set_input_format(self, file_type=None, rate=None, bits=None, channels=None, encoding=None, ignore_length=False): '''Sets input file format arguments. This is primarily useful when dealing with audio files without a file extension. Overwrites any previously set input ...
Sets output file format arguments. These arguments will overwrite any format related arguments supplied by other effects ( e. g. rate ).
def set_output_format(self, file_type=None, rate=None, bits=None, channels=None, encoding=None, comments=None, append_comments=True): '''Sets output file format arguments. These arguments will overwrite any format related arguments supplied by other ef...
Builds the output_file by executing the current set of commands.
def build(self, input_filepath, output_filepath, extra_args=None, return_output=False): '''Builds the output_file by executing the current set of commands. Parameters ---------- input_filepath : str Path to input audio file. output_filepath : str or Non...
Play a preview of the output with the current set of effects
def preview(self, input_filepath): '''Play a preview of the output with the current set of effects Parameters ---------- input_filepath : str Path to input audio file. ''' args = ["play", "--no-show-progress"] args.extend(self.globals) args.e...