partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
valid
GeoIP.time_zone_by_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)
pygeoip/__init__.py
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' raise GeoIPError(message) ipnum = util.ip2long(addr) return self._get_record(ipnum).get('time_zone')
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' raise GeoIPError(message) ipnum = util.ip2long(addr) return self._get_record(ipnum).get('time_zone')
[ "Returns", "time", "zone", "in", "tzdata", "format", "(", "e", ".", "g", ".", "America", "/", "New_York", "or", "Europe", "/", "Paris", ")" ]
appliedsec/pygeoip
python
https://github.com/appliedsec/pygeoip/blob/2a725df0b727e8b08f217ab84f7b8243c42554f5/pygeoip/__init__.py#L586-L597
[ "def", "time_zone_by_addr", "(", "self", ",", "addr", ")", ":", "if", "self", ".", "_databaseType", "not", "in", "const", ".", "CITY_EDITIONS", ":", "message", "=", "'Invalid database type, expected City'", "raise", "GeoIPError", "(", "message", ")", "ipnum", "=", "util", ".", "ip2long", "(", "addr", ")", "return", "self", ".", "_get_record", "(", "ipnum", ")", ".", "get", "(", "'time_zone'", ")" ]
2a725df0b727e8b08f217ab84f7b8243c42554f5
valid
GeoIP.time_zone_by_name
Returns time zone in tzdata format (e.g. America/New_York or Europe/Paris) :arg hostname: Hostname (e.g. example.com)
pygeoip/__init__.py
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)
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", "in", "tzdata", "format", "(", "e", ".", "g", ".", "America", "/", "New_York", "or", "Europe", "/", "Paris", ")" ]
appliedsec/pygeoip
python
https://github.com/appliedsec/pygeoip/blob/2a725df0b727e8b08f217ab84f7b8243c42554f5/pygeoip/__init__.py#L599-L606
[ "def", "time_zone_by_name", "(", "self", ",", "hostname", ")", ":", "addr", "=", "self", ".", "_gethostbyname", "(", "hostname", ")", "return", "self", ".", "time_zone_by_addr", "(", "addr", ")" ]
2a725df0b727e8b08f217ab84f7b8243c42554f5
valid
time_zone_by_country_and_region
Returns time zone from country and region code. :arg country_code: Country code :arg region_code: Region code
pygeoip/timezone.py
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(timezone, str): return timezone return timezone.get(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(timezone, str): return timezone return timezone.get(region_code)
[ "Returns", "time", "zone", "from", "country", "and", "region", "code", "." ]
appliedsec/pygeoip
python
https://github.com/appliedsec/pygeoip/blob/2a725df0b727e8b08f217ab84f7b8243c42554f5/pygeoip/timezone.py#L19-L33
[ "def", "time_zone_by_country_and_region", "(", "country_code", ",", "region_code", "=", "None", ")", ":", "timezone", "=", "country_dict", ".", "get", "(", "country_code", ")", "if", "not", "timezone", ":", "return", "None", "if", "isinstance", "(", "timezone", ",", "str", ")", ":", "return", "timezone", "return", "timezone", ".", "get", "(", "region_code", ")" ]
2a725df0b727e8b08f217ab84f7b8243c42554f5
valid
BaseCompressor.compress
Compress a file, only if needed.
sigal/plugins/compress_assets.py
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)
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)
[ "Compress", "a", "file", "only", "if", "needed", "." ]
saimn/sigal
python
https://github.com/saimn/sigal/blob/912ca39991355d358dc85fd55c7aeabdd7acc386/sigal/plugins/compress_assets.py#L60-L66
[ "def", "compress", "(", "self", ",", "filename", ")", ":", "compressed_filename", "=", "self", ".", "get_compressed_filename", "(", "filename", ")", "if", "not", "compressed_filename", ":", "return", "self", ".", "do_compress", "(", "filename", ",", "compressed_filename", ")" ]
912ca39991355d358dc85fd55c7aeabdd7acc386
valid
BaseCompressor.get_compressed_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 the file itself Otherwise, it returns False.
sigal/plugins/compress_assets.py
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 the file itself Otherwise, it returns False. """ if not os.path.splitext(filename)[1][1:] in self.suffixes_to_compress: return False file_stats = None compressed_stats = None compressed_filename = '{}.{}'.format(filename, self.suffix) try: file_stats = os.stat(filename) compressed_stats = os.stat(compressed_filename) except OSError: # FileNotFoundError is for Python3 only pass if file_stats and compressed_stats: return (compressed_filename if file_stats.st_mtime > compressed_stats.st_mtime else False) else: return 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 the file itself Otherwise, it returns False. """ if not os.path.splitext(filename)[1][1:] in self.suffixes_to_compress: return False file_stats = None compressed_stats = None compressed_filename = '{}.{}'.format(filename, self.suffix) try: file_stats = os.stat(filename) compressed_stats = os.stat(compressed_filename) except OSError: # FileNotFoundError is for Python3 only pass if file_stats and compressed_stats: return (compressed_filename if file_stats.st_mtime > compressed_stats.st_mtime else False) else: return compressed_filename
[ "If", "the", "given", "filename", "should", "be", "compressed", "returns", "the", "compressed", "filename", "." ]
saimn/sigal
python
https://github.com/saimn/sigal/blob/912ca39991355d358dc85fd55c7aeabdd7acc386/sigal/plugins/compress_assets.py#L68-L98
[ "def", "get_compressed_filename", "(", "self", ",", "filename", ")", ":", "if", "not", "os", ".", "path", ".", "splitext", "(", "filename", ")", "[", "1", "]", "[", "1", ":", "]", "in", "self", ".", "suffixes_to_compress", ":", "return", "False", "file_stats", "=", "None", "compressed_stats", "=", "None", "compressed_filename", "=", "'{}.{}'", ".", "format", "(", "filename", ",", "self", ".", "suffix", ")", "try", ":", "file_stats", "=", "os", ".", "stat", "(", "filename", ")", "compressed_stats", "=", "os", ".", "stat", "(", "compressed_filename", ")", "except", "OSError", ":", "# FileNotFoundError is for Python3 only", "pass", "if", "file_stats", "and", "compressed_stats", ":", "return", "(", "compressed_filename", "if", "file_stats", ".", "st_mtime", ">", "compressed_stats", ".", "st_mtime", "else", "False", ")", "else", ":", "return", "compressed_filename" ]
912ca39991355d358dc85fd55c7aeabdd7acc386
valid
copy
Copy or symlink the file.
sigal/utils.py
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: func(src, dst)
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: func(src, dst)
[ "Copy", "or", "symlink", "the", "file", "." ]
saimn/sigal
python
https://github.com/saimn/sigal/blob/912ca39991355d358dc85fd55c7aeabdd7acc386/sigal/utils.py#L45-L53
[ "def", "copy", "(", "src", ",", "dst", ",", "symlink", "=", "False", ",", "rellink", "=", "False", ")", ":", "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", ":", "func", "(", "src", ",", "dst", ")" ]
912ca39991355d358dc85fd55c7aeabdd7acc386
valid
url_from_path
Transform path to url, converting backslashes to slashes if needed.
sigal/utils.py
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)
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)
[ "Transform", "path", "to", "url", "converting", "backslashes", "to", "slashes", "if", "needed", "." ]
saimn/sigal
python
https://github.com/saimn/sigal/blob/912ca39991355d358dc85fd55c7aeabdd7acc386/sigal/utils.py#L63-L68
[ "def", "url_from_path", "(", "path", ")", ":", "if", "os", ".", "sep", "!=", "'/'", ":", "path", "=", "'/'", ".", "join", "(", "path", ".", "split", "(", "os", ".", "sep", ")", ")", "return", "quote", "(", "path", ")" ]
912ca39991355d358dc85fd55c7aeabdd7acc386
valid
read_markdown
Reads markdown file, converts output and fetches title and meta-data for further processing.
sigal/utils.py
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 # also default to pure utf-8) with open(filename, 'r', encoding='utf-8-sig') as f: text = f.read() if MD is None: MD = Markdown(extensions=['markdown.extensions.meta', 'markdown.extensions.tables'], output_format='html5') else: MD.reset() # When https://github.com/Python-Markdown/markdown/pull/672 # will be available, this can be removed. MD.Meta = {} # Mark HTML with Markup to prevent jinja2 autoescaping output = {'description': Markup(MD.convert(text))} try: meta = MD.Meta.copy() except AttributeError: pass else: output['meta'] = meta try: output['title'] = MD.Meta['title'][0] except KeyError: pass return output
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 # also default to pure utf-8) with open(filename, 'r', encoding='utf-8-sig') as f: text = f.read() if MD is None: MD = Markdown(extensions=['markdown.extensions.meta', 'markdown.extensions.tables'], output_format='html5') else: MD.reset() # When https://github.com/Python-Markdown/markdown/pull/672 # will be available, this can be removed. MD.Meta = {} # Mark HTML with Markup to prevent jinja2 autoescaping output = {'description': Markup(MD.convert(text))} try: meta = MD.Meta.copy() except AttributeError: pass else: output['meta'] = meta try: output['title'] = MD.Meta['title'][0] except KeyError: pass return output
[ "Reads", "markdown", "file", "converts", "output", "and", "fetches", "title", "and", "meta", "-", "data", "for", "further", "processing", "." ]
saimn/sigal
python
https://github.com/saimn/sigal/blob/912ca39991355d358dc85fd55c7aeabdd7acc386/sigal/utils.py#L71-L106
[ "def", "read_markdown", "(", "filename", ")", ":", "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", "# also default to pure utf-8)", "with", "open", "(", "filename", ",", "'r'", ",", "encoding", "=", "'utf-8-sig'", ")", "as", "f", ":", "text", "=", "f", ".", "read", "(", ")", "if", "MD", "is", "None", ":", "MD", "=", "Markdown", "(", "extensions", "=", "[", "'markdown.extensions.meta'", ",", "'markdown.extensions.tables'", "]", ",", "output_format", "=", "'html5'", ")", "else", ":", "MD", ".", "reset", "(", ")", "# When https://github.com/Python-Markdown/markdown/pull/672", "# will be available, this can be removed.", "MD", ".", "Meta", "=", "{", "}", "# Mark HTML with Markup to prevent jinja2 autoescaping", "output", "=", "{", "'description'", ":", "Markup", "(", "MD", ".", "convert", "(", "text", ")", ")", "}", "try", ":", "meta", "=", "MD", ".", "Meta", ".", "copy", "(", ")", "except", "AttributeError", ":", "pass", "else", ":", "output", "[", "'meta'", "]", "=", "meta", "try", ":", "output", "[", "'title'", "]", "=", "MD", ".", "Meta", "[", "'title'", "]", "[", "0", "]", "except", "KeyError", ":", "pass", "return", "output" ]
912ca39991355d358dc85fd55c7aeabdd7acc386
valid
load_exif
Loads the exif data of all images in an album from cache
sigal/plugins/extended_caching.py
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, media.filename) if key in cache: media.exif = cache[key]
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, media.filename) if key in cache: media.exif = cache[key]
[ "Loads", "the", "exif", "data", "of", "all", "images", "in", "an", "album", "from", "cache" ]
saimn/sigal
python
https://github.com/saimn/sigal/blob/912ca39991355d358dc85fd55c7aeabdd7acc386/sigal/plugins/extended_caching.py#L40-L50
[ "def", "load_exif", "(", "album", ")", ":", "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", ",", "media", ".", "filename", ")", "if", "key", "in", "cache", ":", "media", ".", "exif", "=", "cache", "[", "key", "]" ]
912ca39991355d358dc85fd55c7aeabdd7acc386
valid
_restore_cache
Restores the exif data cache from the cache file
sigal/plugins/extended_caching.py
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(cacheFile) logger.debug("Loaded cache with %d entries", len(gallery.exifCache)) else: gallery.exifCache = {} except Exception as e: logger.warn("Could not load cache: %s", e) gallery.exifCache = {}
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(cacheFile) logger.debug("Loaded cache with %d entries", len(gallery.exifCache)) else: gallery.exifCache = {} except Exception as e: logger.warn("Could not load cache: %s", e) gallery.exifCache = {}
[ "Restores", "the", "exif", "data", "cache", "from", "the", "cache", "file" ]
saimn/sigal
python
https://github.com/saimn/sigal/blob/912ca39991355d358dc85fd55c7aeabdd7acc386/sigal/plugins/extended_caching.py#L53-L65
[ "def", "_restore_cache", "(", "gallery", ")", ":", "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", "(", "cacheFile", ")", "logger", ".", "debug", "(", "\"Loaded cache with %d entries\"", ",", "len", "(", "gallery", ".", "exifCache", ")", ")", "else", ":", "gallery", ".", "exifCache", "=", "{", "}", "except", "Exception", "as", "e", ":", "logger", ".", "warn", "(", "\"Could not load cache: %s\"", ",", "e", ")", "gallery", ".", "exifCache", "=", "{", "}" ]
912ca39991355d358dc85fd55c7aeabdd7acc386
valid
save_cache
Stores the exif data of all images in the gallery
sigal/plugins/extended_caching.py
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(image.path, image.filename)] = image.exif cachePath = os.path.join(gallery.settings["destination"], ".exif_cache") if len(cache) == 0: if os.path.exists(cachePath): os.remove(cachePath) return try: with open(cachePath, "wb") as cacheFile: pickle.dump(cache, cacheFile) logger.debug("Stored cache with %d entries", len(gallery.exifCache)) except Exception as e: logger.warn("Could not store cache: %s", e) os.remove(cachePath)
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(image.path, image.filename)] = image.exif cachePath = os.path.join(gallery.settings["destination"], ".exif_cache") if len(cache) == 0: if os.path.exists(cachePath): os.remove(cachePath) return try: with open(cachePath, "wb") as cacheFile: pickle.dump(cache, cacheFile) logger.debug("Stored cache with %d entries", len(gallery.exifCache)) except Exception as e: logger.warn("Could not store cache: %s", e) os.remove(cachePath)
[ "Stores", "the", "exif", "data", "of", "all", "images", "in", "the", "gallery" ]
saimn/sigal
python
https://github.com/saimn/sigal/blob/912ca39991355d358dc85fd55c7aeabdd7acc386/sigal/plugins/extended_caching.py#L68-L93
[ "def", "save_cache", "(", "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", "(", "image", ".", "path", ",", "image", ".", "filename", ")", "]", "=", "image", ".", "exif", "cachePath", "=", "os", ".", "path", ".", "join", "(", "gallery", ".", "settings", "[", "\"destination\"", "]", ",", "\".exif_cache\"", ")", "if", "len", "(", "cache", ")", "==", "0", ":", "if", "os", ".", "path", ".", "exists", "(", "cachePath", ")", ":", "os", ".", "remove", "(", "cachePath", ")", "return", "try", ":", "with", "open", "(", "cachePath", ",", "\"wb\"", ")", "as", "cacheFile", ":", "pickle", ".", "dump", "(", "cache", ",", "cacheFile", ")", "logger", ".", "debug", "(", "\"Stored cache with %d entries\"", ",", "len", "(", "gallery", ".", "exifCache", ")", ")", "except", "Exception", "as", "e", ":", "logger", ".", "warn", "(", "\"Could not store cache: %s\"", ",", "e", ")", "os", ".", "remove", "(", "cachePath", ")" ]
912ca39991355d358dc85fd55c7aeabdd7acc386
valid
filter_nomedia
Removes all filtered Media and subdirs from an Album
sigal/plugins/nomedia.py
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 " ".nomedia file", album.name) # subdirs have been added to the gallery already, remove them # there, too _remove_albums_with_subdirs(album.gallery.albums, [album.path]) try: os.rmdir(album.dst_path) except OSError as e: # directory was created and populated with images in a # previous run => keep it pass # cannot set albums => empty subdirs so that no albums are # generated album.subdirs = [] album.medias = [] else: with open(nomediapath, "r") as nomediaFile: logger.info("Found a .nomedia file in %s, ignoring its " "entries", album.name) ignored = nomediaFile.read().split("\n") album.medias = [media for media in album.medias if media.src_filename not in ignored] album.subdirs = [dirname for dirname in album.subdirs if dirname not in ignored] # subdirs have been added to the gallery already, remove # them there, too _remove_albums_with_subdirs(album.gallery.albums, ignored, album.path + os.path.sep)
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 " ".nomedia file", album.name) # subdirs have been added to the gallery already, remove them # there, too _remove_albums_with_subdirs(album.gallery.albums, [album.path]) try: os.rmdir(album.dst_path) except OSError as e: # directory was created and populated with images in a # previous run => keep it pass # cannot set albums => empty subdirs so that no albums are # generated album.subdirs = [] album.medias = [] else: with open(nomediapath, "r") as nomediaFile: logger.info("Found a .nomedia file in %s, ignoring its " "entries", album.name) ignored = nomediaFile.read().split("\n") album.medias = [media for media in album.medias if media.src_filename not in ignored] album.subdirs = [dirname for dirname in album.subdirs if dirname not in ignored] # subdirs have been added to the gallery already, remove # them there, too _remove_albums_with_subdirs(album.gallery.albums, ignored, album.path + os.path.sep)
[ "Removes", "all", "filtered", "Media", "and", "subdirs", "from", "an", "Album" ]
saimn/sigal
python
https://github.com/saimn/sigal/blob/912ca39991355d358dc85fd55c7aeabdd7acc386/sigal/plugins/nomedia.py#L82-L120
[ "def", "filter_nomedia", "(", "album", ",", "settings", "=", "None", ")", ":", "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 \"", "\".nomedia file\"", ",", "album", ".", "name", ")", "# subdirs have been added to the gallery already, remove them", "# there, too", "_remove_albums_with_subdirs", "(", "album", ".", "gallery", ".", "albums", ",", "[", "album", ".", "path", "]", ")", "try", ":", "os", ".", "rmdir", "(", "album", ".", "dst_path", ")", "except", "OSError", "as", "e", ":", "# directory was created and populated with images in a", "# previous run => keep it", "pass", "# cannot set albums => empty subdirs so that no albums are", "# generated", "album", ".", "subdirs", "=", "[", "]", "album", ".", "medias", "=", "[", "]", "else", ":", "with", "open", "(", "nomediapath", ",", "\"r\"", ")", "as", "nomediaFile", ":", "logger", ".", "info", "(", "\"Found a .nomedia file in %s, ignoring its \"", "\"entries\"", ",", "album", ".", "name", ")", "ignored", "=", "nomediaFile", ".", "read", "(", ")", ".", "split", "(", "\"\\n\"", ")", "album", ".", "medias", "=", "[", "media", "for", "media", "in", "album", ".", "medias", "if", "media", ".", "src_filename", "not", "in", "ignored", "]", "album", ".", "subdirs", "=", "[", "dirname", "for", "dirname", "in", "album", ".", "subdirs", "if", "dirname", "not", "in", "ignored", "]", "# subdirs have been added to the gallery already, remove", "# them there, too", "_remove_albums_with_subdirs", "(", "album", ".", "gallery", ".", "albums", ",", "ignored", ",", "album", ".", "path", "+", "os", ".", "path", ".", "sep", ")" ]
912ca39991355d358dc85fd55c7aeabdd7acc386
valid
init
Copy a sample config file in the current directory (default to 'sigal.conf.py'), or use the provided 'path'.
sigal/__init__.py
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 = resource_string(__name__, 'templates/sigal.conf.py') with open(path, 'w', encoding='utf-8') as f: f.write(conf.decode('utf8')) print("Sample config file created: {}".format(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 = resource_string(__name__, 'templates/sigal.conf.py') with open(path, 'w', encoding='utf-8') as f: f.write(conf.decode('utf8')) print("Sample config file created: {}".format(path))
[ "Copy", "a", "sample", "config", "file", "in", "the", "current", "directory", "(", "default", "to", "sigal", ".", "conf", ".", "py", ")", "or", "use", "the", "provided", "path", "." ]
saimn/sigal
python
https://github.com/saimn/sigal/blob/912ca39991355d358dc85fd55c7aeabdd7acc386/sigal/__init__.py#L67-L80
[ "def", "init", "(", "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", "=", "resource_string", "(", "__name__", ",", "'templates/sigal.conf.py'", ")", "with", "open", "(", "path", ",", "'w'", ",", "encoding", "=", "'utf-8'", ")", "as", "f", ":", "f", ".", "write", "(", "conf", ".", "decode", "(", "'utf8'", ")", ")", "print", "(", "\"Sample config file created: {}\"", ".", "format", "(", "path", ")", ")" ]
912ca39991355d358dc85fd55c7aeabdd7acc386
valid
build
Run sigal to process a directory. If provided, 'source', 'destination' and 'theme' will override the corresponding values from the settings file.
sigal/__init__.py
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 logging.INFO) or logging.WARNING) init_logging(__name__, level=level) logger = logging.getLogger(__name__) if not os.path.isfile(config): logger.error("Settings file not found: %s", config) sys.exit(1) start_time = time.time() settings = read_settings(config) for key in ('source', 'destination', 'theme'): arg = locals()[key] if arg is not None: settings[key] = os.path.abspath(arg) logger.info("%12s : %s", key.capitalize(), settings[key]) if not settings['source'] or not os.path.isdir(settings['source']): logger.error("Input directory not found: %s", settings['source']) sys.exit(1) # on windows os.path.relpath raises a ValueError if the two paths are on # different drives, in that case we just ignore the exception as the two # paths are anyway not relative relative_check = True try: relative_check = os.path.relpath(settings['destination'], settings['source']).startswith('..') except ValueError: pass if not relative_check: logger.error("Output directory should be outside of the input " "directory.") sys.exit(1) if title: settings['title'] = title locale.setlocale(locale.LC_ALL, settings['locale']) init_plugins(settings) gal = Gallery(settings, ncpu=ncpu) gal.build(force=force) # copy extra files for src, dst in settings['files_to_copy']: src = os.path.join(settings['source'], src) dst = os.path.join(settings['destination'], dst) logger.debug('Copy %s to %s', src, dst) copy(src, dst, symlink=settings['orig_link'], rellink=settings['rel_link']) stats = gal.stats def format_stats(_type): opt = ["{} {}".format(stats[_type + '_' + subtype], subtype) for subtype in ('skipped', 'failed') if stats[_type + '_' + subtype] > 0] opt = ' ({})'.format(', '.join(opt)) if opt else '' return '{} {}s{}'.format(stats[_type], _type, opt) print('Done.\nProcessed {} and {} in {:.2f} seconds.' .format(format_stats('image'), format_stats('video'), time.time() - start_time))
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 logging.INFO) or logging.WARNING) init_logging(__name__, level=level) logger = logging.getLogger(__name__) if not os.path.isfile(config): logger.error("Settings file not found: %s", config) sys.exit(1) start_time = time.time() settings = read_settings(config) for key in ('source', 'destination', 'theme'): arg = locals()[key] if arg is not None: settings[key] = os.path.abspath(arg) logger.info("%12s : %s", key.capitalize(), settings[key]) if not settings['source'] or not os.path.isdir(settings['source']): logger.error("Input directory not found: %s", settings['source']) sys.exit(1) # on windows os.path.relpath raises a ValueError if the two paths are on # different drives, in that case we just ignore the exception as the two # paths are anyway not relative relative_check = True try: relative_check = os.path.relpath(settings['destination'], settings['source']).startswith('..') except ValueError: pass if not relative_check: logger.error("Output directory should be outside of the input " "directory.") sys.exit(1) if title: settings['title'] = title locale.setlocale(locale.LC_ALL, settings['locale']) init_plugins(settings) gal = Gallery(settings, ncpu=ncpu) gal.build(force=force) # copy extra files for src, dst in settings['files_to_copy']: src = os.path.join(settings['source'], src) dst = os.path.join(settings['destination'], dst) logger.debug('Copy %s to %s', src, dst) copy(src, dst, symlink=settings['orig_link'], rellink=settings['rel_link']) stats = gal.stats def format_stats(_type): opt = ["{} {}".format(stats[_type + '_' + subtype], subtype) for subtype in ('skipped', 'failed') if stats[_type + '_' + subtype] > 0] opt = ' ({})'.format(', '.join(opt)) if opt else '' return '{} {}s{}'.format(stats[_type], _type, opt) print('Done.\nProcessed {} and {} in {:.2f} seconds.' .format(format_stats('image'), format_stats('video'), time.time() - start_time))
[ "Run", "sigal", "to", "process", "a", "directory", "." ]
saimn/sigal
python
https://github.com/saimn/sigal/blob/912ca39991355d358dc85fd55c7aeabdd7acc386/sigal/__init__.py#L97-L169
[ "def", "build", "(", "source", ",", "destination", ",", "debug", ",", "verbose", ",", "force", ",", "config", ",", "theme", ",", "title", ",", "ncpu", ")", ":", "level", "=", "(", "(", "debug", "and", "logging", ".", "DEBUG", ")", "or", "(", "verbose", "and", "logging", ".", "INFO", ")", "or", "logging", ".", "WARNING", ")", "init_logging", "(", "__name__", ",", "level", "=", "level", ")", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "if", "not", "os", ".", "path", ".", "isfile", "(", "config", ")", ":", "logger", ".", "error", "(", "\"Settings file not found: %s\"", ",", "config", ")", "sys", ".", "exit", "(", "1", ")", "start_time", "=", "time", ".", "time", "(", ")", "settings", "=", "read_settings", "(", "config", ")", "for", "key", "in", "(", "'source'", ",", "'destination'", ",", "'theme'", ")", ":", "arg", "=", "locals", "(", ")", "[", "key", "]", "if", "arg", "is", "not", "None", ":", "settings", "[", "key", "]", "=", "os", ".", "path", ".", "abspath", "(", "arg", ")", "logger", ".", "info", "(", "\"%12s : %s\"", ",", "key", ".", "capitalize", "(", ")", ",", "settings", "[", "key", "]", ")", "if", "not", "settings", "[", "'source'", "]", "or", "not", "os", ".", "path", ".", "isdir", "(", "settings", "[", "'source'", "]", ")", ":", "logger", ".", "error", "(", "\"Input directory not found: %s\"", ",", "settings", "[", "'source'", "]", ")", "sys", ".", "exit", "(", "1", ")", "# on windows os.path.relpath raises a ValueError if the two paths are on", "# different drives, in that case we just ignore the exception as the two", "# paths are anyway not relative", "relative_check", "=", "True", "try", ":", "relative_check", "=", "os", ".", "path", ".", "relpath", "(", "settings", "[", "'destination'", "]", ",", "settings", "[", "'source'", "]", ")", ".", "startswith", "(", "'..'", ")", "except", "ValueError", ":", "pass", "if", "not", "relative_check", ":", "logger", ".", "error", "(", "\"Output directory should be outside of the input \"", "\"directory.\"", ")", "sys", ".", "exit", "(", "1", ")", "if", "title", ":", "settings", "[", "'title'", "]", "=", "title", "locale", ".", "setlocale", "(", "locale", ".", "LC_ALL", ",", "settings", "[", "'locale'", "]", ")", "init_plugins", "(", "settings", ")", "gal", "=", "Gallery", "(", "settings", ",", "ncpu", "=", "ncpu", ")", "gal", ".", "build", "(", "force", "=", "force", ")", "# copy extra files", "for", "src", ",", "dst", "in", "settings", "[", "'files_to_copy'", "]", ":", "src", "=", "os", ".", "path", ".", "join", "(", "settings", "[", "'source'", "]", ",", "src", ")", "dst", "=", "os", ".", "path", ".", "join", "(", "settings", "[", "'destination'", "]", ",", "dst", ")", "logger", ".", "debug", "(", "'Copy %s to %s'", ",", "src", ",", "dst", ")", "copy", "(", "src", ",", "dst", ",", "symlink", "=", "settings", "[", "'orig_link'", "]", ",", "rellink", "=", "settings", "[", "'rel_link'", "]", ")", "stats", "=", "gal", ".", "stats", "def", "format_stats", "(", "_type", ")", ":", "opt", "=", "[", "\"{} {}\"", ".", "format", "(", "stats", "[", "_type", "+", "'_'", "+", "subtype", "]", ",", "subtype", ")", "for", "subtype", "in", "(", "'skipped'", ",", "'failed'", ")", "if", "stats", "[", "_type", "+", "'_'", "+", "subtype", "]", ">", "0", "]", "opt", "=", "' ({})'", ".", "format", "(", "', '", ".", "join", "(", "opt", ")", ")", "if", "opt", "else", "''", "return", "'{} {}s{}'", ".", "format", "(", "stats", "[", "_type", "]", ",", "_type", ",", "opt", ")", "print", "(", "'Done.\\nProcessed {} and {} in {:.2f} seconds.'", ".", "format", "(", "format_stats", "(", "'image'", ")", ",", "format_stats", "(", "'video'", ")", ",", "time", ".", "time", "(", ")", "-", "start_time", ")", ")" ]
912ca39991355d358dc85fd55c7aeabdd7acc386
valid
init_plugins
Load plugins and call register().
sigal/__init__.py
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 isinstance(plugin, str): mod = importlib.import_module(plugin) mod.register(settings) else: plugin.register(settings) logger.debug('Registered plugin %s', plugin) except Exception as e: logger.error('Failed to load plugin %s: %r', plugin, e) for path in settings['plugin_paths']: sys.path.remove(path)
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 isinstance(plugin, str): mod = importlib.import_module(plugin) mod.register(settings) else: plugin.register(settings) logger.debug('Registered plugin %s', plugin) except Exception as e: logger.error('Failed to load plugin %s: %r', plugin, e) for path in settings['plugin_paths']: sys.path.remove(path)
[ "Load", "plugins", "and", "call", "register", "()", "." ]
saimn/sigal
python
https://github.com/saimn/sigal/blob/912ca39991355d358dc85fd55c7aeabdd7acc386/sigal/__init__.py#L172-L193
[ "def", "init_plugins", "(", "settings", ")", ":", "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", "isinstance", "(", "plugin", ",", "str", ")", ":", "mod", "=", "importlib", ".", "import_module", "(", "plugin", ")", "mod", ".", "register", "(", "settings", ")", "else", ":", "plugin", ".", "register", "(", "settings", ")", "logger", ".", "debug", "(", "'Registered plugin %s'", ",", "plugin", ")", "except", "Exception", "as", "e", ":", "logger", ".", "error", "(", "'Failed to load plugin %s: %r'", ",", "plugin", ",", "e", ")", "for", "path", "in", "settings", "[", "'plugin_paths'", "]", ":", "sys", ".", "path", ".", "remove", "(", "path", ")" ]
912ca39991355d358dc85fd55c7aeabdd7acc386
valid
serve
Run a simple web server.
sigal/__init__.py
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("The '{}' directory doesn't exist, maybe try " "building first?\n".format(destination)) sys.exit(1) else: sys.stderr.write("The {destination} directory doesn't exist " "and the config file ({config}) could not be read.\n" .format(destination=destination, config=config)) sys.exit(2) print('DESTINATION : {}'.format(destination)) os.chdir(destination) Handler = server.SimpleHTTPRequestHandler httpd = socketserver.TCPServer(("", port), Handler, False) print(" * Running on http://127.0.0.1:{}/".format(port)) try: httpd.allow_reuse_address = True httpd.server_bind() httpd.server_activate() httpd.serve_forever() except KeyboardInterrupt: print('\nAll done!')
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("The '{}' directory doesn't exist, maybe try " "building first?\n".format(destination)) sys.exit(1) else: sys.stderr.write("The {destination} directory doesn't exist " "and the config file ({config}) could not be read.\n" .format(destination=destination, config=config)) sys.exit(2) print('DESTINATION : {}'.format(destination)) os.chdir(destination) Handler = server.SimpleHTTPRequestHandler httpd = socketserver.TCPServer(("", port), Handler, False) print(" * Running on http://127.0.0.1:{}/".format(port)) try: httpd.allow_reuse_address = True httpd.server_bind() httpd.server_activate() httpd.serve_forever() except KeyboardInterrupt: print('\nAll done!')
[ "Run", "a", "simple", "web", "server", "." ]
saimn/sigal
python
https://github.com/saimn/sigal/blob/912ca39991355d358dc85fd55c7aeabdd7acc386/sigal/__init__.py#L201-L230
[ "def", "serve", "(", "destination", ",", "port", ",", "config", ")", ":", "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", "(", "\"The '{}' directory doesn't exist, maybe try \"", "\"building first?\\n\"", ".", "format", "(", "destination", ")", ")", "sys", ".", "exit", "(", "1", ")", "else", ":", "sys", ".", "stderr", ".", "write", "(", "\"The {destination} directory doesn't exist \"", "\"and the config file ({config}) could not be read.\\n\"", ".", "format", "(", "destination", "=", "destination", ",", "config", "=", "config", ")", ")", "sys", ".", "exit", "(", "2", ")", "print", "(", "'DESTINATION : {}'", ".", "format", "(", "destination", ")", ")", "os", ".", "chdir", "(", "destination", ")", "Handler", "=", "server", ".", "SimpleHTTPRequestHandler", "httpd", "=", "socketserver", ".", "TCPServer", "(", "(", "\"\"", ",", "port", ")", ",", "Handler", ",", "False", ")", "print", "(", "\" * Running on http://127.0.0.1:{}/\"", ".", "format", "(", "port", ")", ")", "try", ":", "httpd", ".", "allow_reuse_address", "=", "True", "httpd", ".", "server_bind", "(", ")", "httpd", ".", "server_activate", "(", ")", "httpd", ".", "serve_forever", "(", ")", "except", "KeyboardInterrupt", ":", "print", "(", "'\\nAll done!'", ")" ]
912ca39991355d358dc85fd55c7aeabdd7acc386
valid
set_meta
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"
sigal/__init__.py
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): sys.stderr.write("The target {} does not exist.\n".format(target)) sys.exit(1) if len(keys) < 2 or len(keys) % 2 > 0: sys.stderr.write("Need an even number of arguments.\n") sys.exit(1) if os.path.isdir(target): descfile = os.path.join(target, 'index.md') else: descfile = os.path.splitext(target)[0] + '.md' if os.path.exists(descfile) and not overwrite: sys.stderr.write("Description file '{}' already exists. " "Use --overwrite to overwrite it.\n".format(descfile)) sys.exit(2) with open(descfile, "w") as fp: for i in range(len(keys) // 2): k, v = keys[i * 2:(i + 1) * 2] fp.write("{}: {}\n".format(k.capitalize(), v)) print("{} metadata key(s) written to {}".format(len(keys) // 2, descfile))
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): sys.stderr.write("The target {} does not exist.\n".format(target)) sys.exit(1) if len(keys) < 2 or len(keys) % 2 > 0: sys.stderr.write("Need an even number of arguments.\n") sys.exit(1) if os.path.isdir(target): descfile = os.path.join(target, 'index.md') else: descfile = os.path.splitext(target)[0] + '.md' if os.path.exists(descfile) and not overwrite: sys.stderr.write("Description file '{}' already exists. " "Use --overwrite to overwrite it.\n".format(descfile)) sys.exit(2) with open(descfile, "w") as fp: for i in range(len(keys) // 2): k, v = keys[i * 2:(i + 1) * 2] fp.write("{}: {}\n".format(k.capitalize(), v)) print("{} metadata key(s) written to {}".format(len(keys) // 2, descfile))
[ "Write", "metadata", "keys", "to", ".", "md", "file", "." ]
saimn/sigal
python
https://github.com/saimn/sigal/blob/912ca39991355d358dc85fd55c7aeabdd7acc386/sigal/__init__.py#L238-L268
[ "def", "set_meta", "(", "target", ",", "keys", ",", "overwrite", "=", "False", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "target", ")", ":", "sys", ".", "stderr", ".", "write", "(", "\"The target {} does not exist.\\n\"", ".", "format", "(", "target", ")", ")", "sys", ".", "exit", "(", "1", ")", "if", "len", "(", "keys", ")", "<", "2", "or", "len", "(", "keys", ")", "%", "2", ">", "0", ":", "sys", ".", "stderr", ".", "write", "(", "\"Need an even number of arguments.\\n\"", ")", "sys", ".", "exit", "(", "1", ")", "if", "os", ".", "path", ".", "isdir", "(", "target", ")", ":", "descfile", "=", "os", ".", "path", ".", "join", "(", "target", ",", "'index.md'", ")", "else", ":", "descfile", "=", "os", ".", "path", ".", "splitext", "(", "target", ")", "[", "0", "]", "+", "'.md'", "if", "os", ".", "path", ".", "exists", "(", "descfile", ")", "and", "not", "overwrite", ":", "sys", ".", "stderr", ".", "write", "(", "\"Description file '{}' already exists. \"", "\"Use --overwrite to overwrite it.\\n\"", ".", "format", "(", "descfile", ")", ")", "sys", ".", "exit", "(", "2", ")", "with", "open", "(", "descfile", ",", "\"w\"", ")", "as", "fp", ":", "for", "i", "in", "range", "(", "len", "(", "keys", ")", "//", "2", ")", ":", "k", ",", "v", "=", "keys", "[", "i", "*", "2", ":", "(", "i", "+", "1", ")", "*", "2", "]", "fp", ".", "write", "(", "\"{}: {}\\n\"", ".", "format", "(", "k", ".", "capitalize", "(", ")", ",", "v", ")", ")", "print", "(", "\"{} metadata key(s) written to {}\"", ".", "format", "(", "len", "(", "keys", ")", "//", "2", ",", "descfile", ")", ")" ]
912ca39991355d358dc85fd55c7aeabdd7acc386
valid
generate_image
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)
sigal/image.py
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 = logging.getLogger(__name__) if settings['use_orig'] or source.endswith('.gif'): utils.copy(source, outname, symlink=settings['orig_link']) return img = _read_image(source) original_format = img.format if settings['copy_exif_data'] and settings['autorotate_images']: logger.warning("The 'autorotate_images' and 'copy_exif_data' settings " "are not compatible because Sigal can't save the " "modified Orientation tag.") # Preserve EXIF data if settings['copy_exif_data'] and _has_exif_tags(img): if options is not None: options = deepcopy(options) else: options = {} options['exif'] = img.info['exif'] # Rotate the img, and catch IOError when PIL fails to read EXIF if settings['autorotate_images']: try: img = Transpose().process(img) except (IOError, IndexError): pass # Resize the image if settings['img_processor']: try: logger.debug('Processor: %s', settings['img_processor']) processor_cls = getattr(pilkit.processors, settings['img_processor']) except AttributeError: logger.error('Wrong processor name: %s', settings['img_processor']) sys.exit() width, height = settings['img_size'] if img.size[0] < img.size[1]: # swap target size if image is in portrait mode height, width = width, height processor = processor_cls(width, height, upscale=False) img = processor.process(img) # signal.send() does not work here as plugins can modify the image, so we # iterate other the receivers to call them with the image. for receiver in signals.img_resized.receivers_for(img): img = receiver(img, settings=settings) outformat = img.format or original_format or 'JPEG' logger.debug('Save resized image to %s (%s)', outname, outformat) save_image(img, outname, outformat, options=options, autoconvert=True)
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 = logging.getLogger(__name__) if settings['use_orig'] or source.endswith('.gif'): utils.copy(source, outname, symlink=settings['orig_link']) return img = _read_image(source) original_format = img.format if settings['copy_exif_data'] and settings['autorotate_images']: logger.warning("The 'autorotate_images' and 'copy_exif_data' settings " "are not compatible because Sigal can't save the " "modified Orientation tag.") # Preserve EXIF data if settings['copy_exif_data'] and _has_exif_tags(img): if options is not None: options = deepcopy(options) else: options = {} options['exif'] = img.info['exif'] # Rotate the img, and catch IOError when PIL fails to read EXIF if settings['autorotate_images']: try: img = Transpose().process(img) except (IOError, IndexError): pass # Resize the image if settings['img_processor']: try: logger.debug('Processor: %s', settings['img_processor']) processor_cls = getattr(pilkit.processors, settings['img_processor']) except AttributeError: logger.error('Wrong processor name: %s', settings['img_processor']) sys.exit() width, height = settings['img_size'] if img.size[0] < img.size[1]: # swap target size if image is in portrait mode height, width = width, height processor = processor_cls(width, height, upscale=False) img = processor.process(img) # signal.send() does not work here as plugins can modify the image, so we # iterate other the receivers to call them with the image. for receiver in signals.img_resized.receivers_for(img): img = receiver(img, settings=settings) outformat = img.format or original_format or 'JPEG' logger.debug('Save resized image to %s (%s)', outname, outformat) save_image(img, outname, outformat, options=options, autoconvert=True)
[ "Image", "processor", "rotate", "and", "resize", "the", "image", "." ]
saimn/sigal
python
https://github.com/saimn/sigal/blob/912ca39991355d358dc85fd55c7aeabdd7acc386/sigal/image.py#L72-L137
[ "def", "generate_image", "(", "source", ",", "outname", ",", "settings", ",", "options", "=", "None", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "if", "settings", "[", "'use_orig'", "]", "or", "source", ".", "endswith", "(", "'.gif'", ")", ":", "utils", ".", "copy", "(", "source", ",", "outname", ",", "symlink", "=", "settings", "[", "'orig_link'", "]", ")", "return", "img", "=", "_read_image", "(", "source", ")", "original_format", "=", "img", ".", "format", "if", "settings", "[", "'copy_exif_data'", "]", "and", "settings", "[", "'autorotate_images'", "]", ":", "logger", ".", "warning", "(", "\"The 'autorotate_images' and 'copy_exif_data' settings \"", "\"are not compatible because Sigal can't save the \"", "\"modified Orientation tag.\"", ")", "# Preserve EXIF data", "if", "settings", "[", "'copy_exif_data'", "]", "and", "_has_exif_tags", "(", "img", ")", ":", "if", "options", "is", "not", "None", ":", "options", "=", "deepcopy", "(", "options", ")", "else", ":", "options", "=", "{", "}", "options", "[", "'exif'", "]", "=", "img", ".", "info", "[", "'exif'", "]", "# Rotate the img, and catch IOError when PIL fails to read EXIF", "if", "settings", "[", "'autorotate_images'", "]", ":", "try", ":", "img", "=", "Transpose", "(", ")", ".", "process", "(", "img", ")", "except", "(", "IOError", ",", "IndexError", ")", ":", "pass", "# Resize the image", "if", "settings", "[", "'img_processor'", "]", ":", "try", ":", "logger", ".", "debug", "(", "'Processor: %s'", ",", "settings", "[", "'img_processor'", "]", ")", "processor_cls", "=", "getattr", "(", "pilkit", ".", "processors", ",", "settings", "[", "'img_processor'", "]", ")", "except", "AttributeError", ":", "logger", ".", "error", "(", "'Wrong processor name: %s'", ",", "settings", "[", "'img_processor'", "]", ")", "sys", ".", "exit", "(", ")", "width", ",", "height", "=", "settings", "[", "'img_size'", "]", "if", "img", ".", "size", "[", "0", "]", "<", "img", ".", "size", "[", "1", "]", ":", "# swap target size if image is in portrait mode", "height", ",", "width", "=", "width", ",", "height", "processor", "=", "processor_cls", "(", "width", ",", "height", ",", "upscale", "=", "False", ")", "img", "=", "processor", ".", "process", "(", "img", ")", "# signal.send() does not work here as plugins can modify the image, so we", "# iterate other the receivers to call them with the image.", "for", "receiver", "in", "signals", ".", "img_resized", ".", "receivers_for", "(", "img", ")", ":", "img", "=", "receiver", "(", "img", ",", "settings", "=", "settings", ")", "outformat", "=", "img", ".", "format", "or", "original_format", "or", "'JPEG'", "logger", ".", "debug", "(", "'Save resized image to %s (%s)'", ",", "outname", ",", "outformat", ")", "save_image", "(", "img", ",", "outname", ",", "outformat", ",", "options", "=", "options", ",", "autoconvert", "=", "True", ")" ]
912ca39991355d358dc85fd55c7aeabdd7acc386
valid
generate_thumbnail
Create a thumbnail image.
sigal/image.py
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, PILImage.ANTIALIAS, centering=thumb_fit_centering) else: img.thumbnail(box, PILImage.ANTIALIAS) outformat = img.format or original_format or 'JPEG' logger.debug('Save thumnail image: %s (%s)', outname, outformat) save_image(img, outname, outformat, options=options, autoconvert=True)
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, PILImage.ANTIALIAS, centering=thumb_fit_centering) else: img.thumbnail(box, PILImage.ANTIALIAS) outformat = img.format or original_format or 'JPEG' logger.debug('Save thumnail image: %s (%s)', outname, outformat) save_image(img, outname, outformat, options=options, autoconvert=True)
[ "Create", "a", "thumbnail", "image", "." ]
saimn/sigal
python
https://github.com/saimn/sigal/blob/912ca39991355d358dc85fd55c7aeabdd7acc386/sigal/image.py#L140-L156
[ "def", "generate_thumbnail", "(", "source", ",", "outname", ",", "box", ",", "fit", "=", "True", ",", "options", "=", "None", ",", "thumb_fit_centering", "=", "(", "0.5", ",", "0.5", ")", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "img", "=", "_read_image", "(", "source", ")", "original_format", "=", "img", ".", "format", "if", "fit", ":", "img", "=", "ImageOps", ".", "fit", "(", "img", ",", "box", ",", "PILImage", ".", "ANTIALIAS", ",", "centering", "=", "thumb_fit_centering", ")", "else", ":", "img", ".", "thumbnail", "(", "box", ",", "PILImage", ".", "ANTIALIAS", ")", "outformat", "=", "img", ".", "format", "or", "original_format", "or", "'JPEG'", "logger", ".", "debug", "(", "'Save thumnail image: %s (%s)'", ",", "outname", ",", "outformat", ")", "save_image", "(", "img", ",", "outname", ",", "outformat", ",", "options", "=", "options", ",", "autoconvert", "=", "True", ")" ]
912ca39991355d358dc85fd55c7aeabdd7acc386
valid
process_image
Process one image: resize, create thumbnail.
sigal/image.py
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] if ext in ('.jpg', '.jpeg', '.JPG', '.JPEG'): options = settings['jpg_options'] elif ext == '.png': options = {'optimize': True} else: options = {} try: generate_image(filepath, outname, settings, options=options) if settings['make_thumbs']: thumb_name = os.path.join(outpath, get_thumb(settings, filename)) generate_thumbnail( outname, thumb_name, settings['thumb_size'], fit=settings['thumb_fit'], options=options, thumb_fit_centering=settings["thumb_fit_centering"]) except Exception as e: logger.info('Failed to process: %r', e) if logger.getEffectiveLevel() == logging.DEBUG: raise else: return Status.FAILURE return Status.SUCCESS
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] if ext in ('.jpg', '.jpeg', '.JPG', '.JPEG'): options = settings['jpg_options'] elif ext == '.png': options = {'optimize': True} else: options = {} try: generate_image(filepath, outname, settings, options=options) if settings['make_thumbs']: thumb_name = os.path.join(outpath, get_thumb(settings, filename)) generate_thumbnail( outname, thumb_name, settings['thumb_size'], fit=settings['thumb_fit'], options=options, thumb_fit_centering=settings["thumb_fit_centering"]) except Exception as e: logger.info('Failed to process: %r', e) if logger.getEffectiveLevel() == logging.DEBUG: raise else: return Status.FAILURE return Status.SUCCESS
[ "Process", "one", "image", ":", "resize", "create", "thumbnail", "." ]
saimn/sigal
python
https://github.com/saimn/sigal/blob/912ca39991355d358dc85fd55c7aeabdd7acc386/sigal/image.py#L159-L191
[ "def", "process_image", "(", "filepath", ",", "outpath", ",", "settings", ")", ":", "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", "]", "if", "ext", "in", "(", "'.jpg'", ",", "'.jpeg'", ",", "'.JPG'", ",", "'.JPEG'", ")", ":", "options", "=", "settings", "[", "'jpg_options'", "]", "elif", "ext", "==", "'.png'", ":", "options", "=", "{", "'optimize'", ":", "True", "}", "else", ":", "options", "=", "{", "}", "try", ":", "generate_image", "(", "filepath", ",", "outname", ",", "settings", ",", "options", "=", "options", ")", "if", "settings", "[", "'make_thumbs'", "]", ":", "thumb_name", "=", "os", ".", "path", ".", "join", "(", "outpath", ",", "get_thumb", "(", "settings", ",", "filename", ")", ")", "generate_thumbnail", "(", "outname", ",", "thumb_name", ",", "settings", "[", "'thumb_size'", "]", ",", "fit", "=", "settings", "[", "'thumb_fit'", "]", ",", "options", "=", "options", ",", "thumb_fit_centering", "=", "settings", "[", "\"thumb_fit_centering\"", "]", ")", "except", "Exception", "as", "e", ":", "logger", ".", "info", "(", "'Failed to process: %r'", ",", "e", ")", "if", "logger", ".", "getEffectiveLevel", "(", ")", "==", "logging", ".", "DEBUG", ":", "raise", "else", ":", "return", "Status", ".", "FAILURE", "return", "Status", ".", "SUCCESS" ]
912ca39991355d358dc85fd55c7aeabdd7acc386
valid
get_size
Return image size (width and height).
sigal/image.py
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: width, height = im.size return { 'width': width, 'height': 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: width, height = im.size return { 'width': width, 'height': height }
[ "Return", "image", "size", "(", "width", "and", "height", ")", "." ]
saimn/sigal
python
https://github.com/saimn/sigal/blob/912ca39991355d358dc85fd55c7aeabdd7acc386/sigal/image.py#L194-L206
[ "def", "get_size", "(", "file_path", ")", ":", "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", ":", "width", ",", "height", "=", "im", ".", "size", "return", "{", "'width'", ":", "width", ",", "'height'", ":", "height", "}" ]
912ca39991355d358dc85fd55c7aeabdd7acc386
valid
get_exif_data
Return a dict with the raw EXIF data.
sigal/image.py
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.get(tag, tag): value for tag, value in exif.items()} if 'GPSInfo' in data: try: data['GPSInfo'] = {GPSTAGS.get(tag, tag): value for tag, value in data['GPSInfo'].items()} except AttributeError: logger = logging.getLogger(__name__) logger.info('Failed to get GPS Info') del data['GPSInfo'] return 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.get(tag, tag): value for tag, value in exif.items()} if 'GPSInfo' in data: try: data['GPSInfo'] = {GPSTAGS.get(tag, tag): value for tag, value in data['GPSInfo'].items()} except AttributeError: logger = logging.getLogger(__name__) logger.info('Failed to get GPS Info') del data['GPSInfo'] return data
[ "Return", "a", "dict", "with", "the", "raw", "EXIF", "data", "." ]
saimn/sigal
python
https://github.com/saimn/sigal/blob/912ca39991355d358dc85fd55c7aeabdd7acc386/sigal/image.py#L209-L232
[ "def", "get_exif_data", "(", "filename", ")", ":", "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", ".", "get", "(", "tag", ",", "tag", ")", ":", "value", "for", "tag", ",", "value", "in", "exif", ".", "items", "(", ")", "}", "if", "'GPSInfo'", "in", "data", ":", "try", ":", "data", "[", "'GPSInfo'", "]", "=", "{", "GPSTAGS", ".", "get", "(", "tag", ",", "tag", ")", ":", "value", "for", "tag", ",", "value", "in", "data", "[", "'GPSInfo'", "]", ".", "items", "(", ")", "}", "except", "AttributeError", ":", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "logger", ".", "info", "(", "'Failed to get GPS Info'", ")", "del", "data", "[", "'GPSInfo'", "]", "return", "data" ]
912ca39991355d358dc85fd55c7aeabdd7acc386
valid
get_iptc_data
Return a dict with the raw IPTC data.
sigal/image.py
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://github.com/python-pillow/Pillow/blob/9dd0348be2751beb2c617e32ff9985aa2f92ae5f/src/PIL/IptcImagePlugin.py#L71 ) try: img = _read_image(filename) raw_iptc = IptcImagePlugin.getiptcinfo(img) except SyntaxError: logger.info('IPTC Error in %s', filename) # IPTC fields are catalogued in: # https://www.iptc.org/std/photometadata/specification/IPTC-PhotoMetadata # 2:05 is the IPTC title property if raw_iptc and (2, 5) in raw_iptc: iptc_data["title"] = raw_iptc[(2, 5)].decode('utf-8', errors='replace') # 2:120 is the IPTC description property if raw_iptc and (2, 120) in raw_iptc: iptc_data["description"] = raw_iptc[(2, 120)].decode('utf-8', errors='replace') # 2:105 is the IPTC headline property if raw_iptc and (2, 105) in raw_iptc: iptc_data["headline"] = raw_iptc[(2, 105)].decode('utf-8', errors='replace') return 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://github.com/python-pillow/Pillow/blob/9dd0348be2751beb2c617e32ff9985aa2f92ae5f/src/PIL/IptcImagePlugin.py#L71 ) try: img = _read_image(filename) raw_iptc = IptcImagePlugin.getiptcinfo(img) except SyntaxError: logger.info('IPTC Error in %s', filename) # IPTC fields are catalogued in: # https://www.iptc.org/std/photometadata/specification/IPTC-PhotoMetadata # 2:05 is the IPTC title property if raw_iptc and (2, 5) in raw_iptc: iptc_data["title"] = raw_iptc[(2, 5)].decode('utf-8', errors='replace') # 2:120 is the IPTC description property if raw_iptc and (2, 120) in raw_iptc: iptc_data["description"] = raw_iptc[(2, 120)].decode('utf-8', errors='replace') # 2:105 is the IPTC headline property if raw_iptc and (2, 105) in raw_iptc: iptc_data["headline"] = raw_iptc[(2, 105)].decode('utf-8', errors='replace') return iptc_data
[ "Return", "a", "dict", "with", "the", "raw", "IPTC", "data", "." ]
saimn/sigal
python
https://github.com/saimn/sigal/blob/912ca39991355d358dc85fd55c7aeabdd7acc386/sigal/image.py#L235-L268
[ "def", "get_iptc_data", "(", "filename", ")", ":", "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://github.com/python-pillow/Pillow/blob/9dd0348be2751beb2c617e32ff9985aa2f92ae5f/src/PIL/IptcImagePlugin.py#L71 )", "try", ":", "img", "=", "_read_image", "(", "filename", ")", "raw_iptc", "=", "IptcImagePlugin", ".", "getiptcinfo", "(", "img", ")", "except", "SyntaxError", ":", "logger", ".", "info", "(", "'IPTC Error in %s'", ",", "filename", ")", "# IPTC fields are catalogued in:", "# https://www.iptc.org/std/photometadata/specification/IPTC-PhotoMetadata", "# 2:05 is the IPTC title property", "if", "raw_iptc", "and", "(", "2", ",", "5", ")", "in", "raw_iptc", ":", "iptc_data", "[", "\"title\"", "]", "=", "raw_iptc", "[", "(", "2", ",", "5", ")", "]", ".", "decode", "(", "'utf-8'", ",", "errors", "=", "'replace'", ")", "# 2:120 is the IPTC description property", "if", "raw_iptc", "and", "(", "2", ",", "120", ")", "in", "raw_iptc", ":", "iptc_data", "[", "\"description\"", "]", "=", "raw_iptc", "[", "(", "2", ",", "120", ")", "]", ".", "decode", "(", "'utf-8'", ",", "errors", "=", "'replace'", ")", "# 2:105 is the IPTC headline property", "if", "raw_iptc", "and", "(", "2", ",", "105", ")", "in", "raw_iptc", ":", "iptc_data", "[", "\"headline\"", "]", "=", "raw_iptc", "[", "(", "2", ",", "105", ")", "]", ".", "decode", "(", "'utf-8'", ",", "errors", "=", "'replace'", ")", "return", "iptc_data" ]
912ca39991355d358dc85fd55c7aeabdd7acc386
valid
dms_to_degrees
Convert degree/minute/second to decimal degrees.
sigal/image.py
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)
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)
[ "Convert", "degree", "/", "minute", "/", "second", "to", "decimal", "degrees", "." ]
saimn/sigal
python
https://github.com/saimn/sigal/blob/912ca39991355d358dc85fd55c7aeabdd7acc386/sigal/image.py#L271-L277
[ "def", "dms_to_degrees", "(", "v", ")", ":", "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", ")" ]
912ca39991355d358dc85fd55c7aeabdd7acc386
valid
get_exif_tags
Make a simplified version with common tags from raw EXIF data.
sigal/image.py
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[tag] = data[tag][0].strip() else: simple[tag] = data[tag].strip() if 'FNumber' in data: fnumber = data['FNumber'] try: simple['fstop'] = float(fnumber[0]) / fnumber[1] except Exception: logger.debug('Skipped invalid FNumber: %r', fnumber, exc_info=True) if 'FocalLength' in data: focal = data['FocalLength'] try: simple['focal'] = round(float(focal[0]) / focal[1]) except Exception: logger.debug('Skipped invalid FocalLength: %r', focal, exc_info=True) if 'ExposureTime' in data: exptime = data['ExposureTime'] if isinstance(exptime, tuple): try: simple['exposure'] = str(fractions.Fraction(exptime[0], exptime[1])) except ZeroDivisionError: logger.info('Invalid ExposureTime: %r', exptime) elif isinstance(exptime, int): simple['exposure'] = str(exptime) else: logger.info('Unknown format for ExposureTime: %r', exptime) if data.get('ISOSpeedRatings'): simple['iso'] = data['ISOSpeedRatings'] if 'DateTimeOriginal' in data: # Remove null bytes at the end if necessary date = data['DateTimeOriginal'].rsplit('\x00')[0] try: simple['dateobj'] = datetime.strptime(date, '%Y:%m:%d %H:%M:%S') simple['datetime'] = simple['dateobj'].strftime(datetime_format) except (ValueError, TypeError) as e: logger.info('Could not parse DateTimeOriginal: %s', e) if 'GPSInfo' in data: info = data['GPSInfo'] lat_info = info.get('GPSLatitude') lon_info = info.get('GPSLongitude') lat_ref_info = info.get('GPSLatitudeRef') lon_ref_info = info.get('GPSLongitudeRef') if lat_info and lon_info and lat_ref_info and lon_ref_info: try: lat = dms_to_degrees(lat_info) lon = dms_to_degrees(lon_info) except (ZeroDivisionError, ValueError, TypeError): logger.info('Failed to read GPS info') else: simple['gps'] = { 'lat': - lat if lat_ref_info != 'N' else lat, 'lon': - lon if lon_ref_info != 'E' else lon, } return simple
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[tag] = data[tag][0].strip() else: simple[tag] = data[tag].strip() if 'FNumber' in data: fnumber = data['FNumber'] try: simple['fstop'] = float(fnumber[0]) / fnumber[1] except Exception: logger.debug('Skipped invalid FNumber: %r', fnumber, exc_info=True) if 'FocalLength' in data: focal = data['FocalLength'] try: simple['focal'] = round(float(focal[0]) / focal[1]) except Exception: logger.debug('Skipped invalid FocalLength: %r', focal, exc_info=True) if 'ExposureTime' in data: exptime = data['ExposureTime'] if isinstance(exptime, tuple): try: simple['exposure'] = str(fractions.Fraction(exptime[0], exptime[1])) except ZeroDivisionError: logger.info('Invalid ExposureTime: %r', exptime) elif isinstance(exptime, int): simple['exposure'] = str(exptime) else: logger.info('Unknown format for ExposureTime: %r', exptime) if data.get('ISOSpeedRatings'): simple['iso'] = data['ISOSpeedRatings'] if 'DateTimeOriginal' in data: # Remove null bytes at the end if necessary date = data['DateTimeOriginal'].rsplit('\x00')[0] try: simple['dateobj'] = datetime.strptime(date, '%Y:%m:%d %H:%M:%S') simple['datetime'] = simple['dateobj'].strftime(datetime_format) except (ValueError, TypeError) as e: logger.info('Could not parse DateTimeOriginal: %s', e) if 'GPSInfo' in data: info = data['GPSInfo'] lat_info = info.get('GPSLatitude') lon_info = info.get('GPSLongitude') lat_ref_info = info.get('GPSLatitudeRef') lon_ref_info = info.get('GPSLongitudeRef') if lat_info and lon_info and lat_ref_info and lon_ref_info: try: lat = dms_to_degrees(lat_info) lon = dms_to_degrees(lon_info) except (ZeroDivisionError, ValueError, TypeError): logger.info('Failed to read GPS info') else: simple['gps'] = { 'lat': - lat if lat_ref_info != 'N' else lat, 'lon': - lon if lon_ref_info != 'E' else lon, } return simple
[ "Make", "a", "simplified", "version", "with", "common", "tags", "from", "raw", "EXIF", "data", "." ]
saimn/sigal
python
https://github.com/saimn/sigal/blob/912ca39991355d358dc85fd55c7aeabdd7acc386/sigal/image.py#L280-L353
[ "def", "get_exif_tags", "(", "data", ",", "datetime_format", "=", "'%c'", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "simple", "=", "{", "}", "for", "tag", "in", "(", "'Model'", ",", "'Make'", ",", "'LensModel'", ")", ":", "if", "tag", "in", "data", ":", "if", "isinstance", "(", "data", "[", "tag", "]", ",", "tuple", ")", ":", "simple", "[", "tag", "]", "=", "data", "[", "tag", "]", "[", "0", "]", ".", "strip", "(", ")", "else", ":", "simple", "[", "tag", "]", "=", "data", "[", "tag", "]", ".", "strip", "(", ")", "if", "'FNumber'", "in", "data", ":", "fnumber", "=", "data", "[", "'FNumber'", "]", "try", ":", "simple", "[", "'fstop'", "]", "=", "float", "(", "fnumber", "[", "0", "]", ")", "/", "fnumber", "[", "1", "]", "except", "Exception", ":", "logger", ".", "debug", "(", "'Skipped invalid FNumber: %r'", ",", "fnumber", ",", "exc_info", "=", "True", ")", "if", "'FocalLength'", "in", "data", ":", "focal", "=", "data", "[", "'FocalLength'", "]", "try", ":", "simple", "[", "'focal'", "]", "=", "round", "(", "float", "(", "focal", "[", "0", "]", ")", "/", "focal", "[", "1", "]", ")", "except", "Exception", ":", "logger", ".", "debug", "(", "'Skipped invalid FocalLength: %r'", ",", "focal", ",", "exc_info", "=", "True", ")", "if", "'ExposureTime'", "in", "data", ":", "exptime", "=", "data", "[", "'ExposureTime'", "]", "if", "isinstance", "(", "exptime", ",", "tuple", ")", ":", "try", ":", "simple", "[", "'exposure'", "]", "=", "str", "(", "fractions", ".", "Fraction", "(", "exptime", "[", "0", "]", ",", "exptime", "[", "1", "]", ")", ")", "except", "ZeroDivisionError", ":", "logger", ".", "info", "(", "'Invalid ExposureTime: %r'", ",", "exptime", ")", "elif", "isinstance", "(", "exptime", ",", "int", ")", ":", "simple", "[", "'exposure'", "]", "=", "str", "(", "exptime", ")", "else", ":", "logger", ".", "info", "(", "'Unknown format for ExposureTime: %r'", ",", "exptime", ")", "if", "data", ".", "get", "(", "'ISOSpeedRatings'", ")", ":", "simple", "[", "'iso'", "]", "=", "data", "[", "'ISOSpeedRatings'", "]", "if", "'DateTimeOriginal'", "in", "data", ":", "# Remove null bytes at the end if necessary", "date", "=", "data", "[", "'DateTimeOriginal'", "]", ".", "rsplit", "(", "'\\x00'", ")", "[", "0", "]", "try", ":", "simple", "[", "'dateobj'", "]", "=", "datetime", ".", "strptime", "(", "date", ",", "'%Y:%m:%d %H:%M:%S'", ")", "simple", "[", "'datetime'", "]", "=", "simple", "[", "'dateobj'", "]", ".", "strftime", "(", "datetime_format", ")", "except", "(", "ValueError", ",", "TypeError", ")", "as", "e", ":", "logger", ".", "info", "(", "'Could not parse DateTimeOriginal: %s'", ",", "e", ")", "if", "'GPSInfo'", "in", "data", ":", "info", "=", "data", "[", "'GPSInfo'", "]", "lat_info", "=", "info", ".", "get", "(", "'GPSLatitude'", ")", "lon_info", "=", "info", ".", "get", "(", "'GPSLongitude'", ")", "lat_ref_info", "=", "info", ".", "get", "(", "'GPSLatitudeRef'", ")", "lon_ref_info", "=", "info", ".", "get", "(", "'GPSLongitudeRef'", ")", "if", "lat_info", "and", "lon_info", "and", "lat_ref_info", "and", "lon_ref_info", ":", "try", ":", "lat", "=", "dms_to_degrees", "(", "lat_info", ")", "lon", "=", "dms_to_degrees", "(", "lon_info", ")", "except", "(", "ZeroDivisionError", ",", "ValueError", ",", "TypeError", ")", ":", "logger", ".", "info", "(", "'Failed to read GPS info'", ")", "else", ":", "simple", "[", "'gps'", "]", "=", "{", "'lat'", ":", "-", "lat", "if", "lat_ref_info", "!=", "'N'", "else", "lat", ",", "'lon'", ":", "-", "lon", "if", "lon_ref_info", "!=", "'E'", "else", "lon", ",", "}", "return", "simple" ]
912ca39991355d358dc85fd55c7aeabdd7acc386
valid
Media.big
Path to the original image, if ``keep_orig`` is set (relative to the album directory). Copy the file if needed.
sigal/gallery.py
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 return self.filename orig_path = join(s['destination'], self.path, s['orig_dir']) check_or_create_dir(orig_path) big_path = join(orig_path, self.src_filename) if not isfile(big_path): copy(self.src_path, big_path, symlink=s['orig_link'], rellink=self.settings['rel_link']) return join(s['orig_dir'], self.src_filename)
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 return self.filename orig_path = join(s['destination'], self.path, s['orig_dir']) check_or_create_dir(orig_path) big_path = join(orig_path, self.src_filename) if not isfile(big_path): copy(self.src_path, big_path, symlink=s['orig_link'], rellink=self.settings['rel_link']) return join(s['orig_dir'], self.src_filename)
[ "Path", "to", "the", "original", "image", "if", "keep_orig", "is", "set", "(", "relative", "to", "the", "album", "directory", ")", ".", "Copy", "the", "file", "if", "needed", "." ]
saimn/sigal
python
https://github.com/saimn/sigal/blob/912ca39991355d358dc85fd55c7aeabdd7acc386/sigal/gallery.py#L103-L118
[ "def", "big", "(", "self", ")", ":", "if", "self", ".", "settings", "[", "'keep_orig'", "]", ":", "s", "=", "self", ".", "settings", "if", "s", "[", "'use_orig'", "]", ":", "# The image *is* the original, just use it", "return", "self", ".", "filename", "orig_path", "=", "join", "(", "s", "[", "'destination'", "]", ",", "self", ".", "path", ",", "s", "[", "'orig_dir'", "]", ")", "check_or_create_dir", "(", "orig_path", ")", "big_path", "=", "join", "(", "orig_path", ",", "self", ".", "src_filename", ")", "if", "not", "isfile", "(", "big_path", ")", ":", "copy", "(", "self", ".", "src_path", ",", "big_path", ",", "symlink", "=", "s", "[", "'orig_link'", "]", ",", "rellink", "=", "self", ".", "settings", "[", "'rel_link'", "]", ")", "return", "join", "(", "s", "[", "'orig_dir'", "]", ",", "self", ".", "src_filename", ")" ]
912ca39991355d358dc85fd55c7aeabdd7acc386
valid
Media.thumbnail
Path to the thumbnail image (relative to the album directory).
sigal/gallery.py
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) try: # if thumbnail is missing (if settings['make_thumbs'] is False) s = self.settings if self.type == 'image': image.generate_thumbnail( path, self.thumb_path, s['thumb_size'], fit=s['thumb_fit']) elif self.type == 'video': video.generate_thumbnail( path, self.thumb_path, s['thumb_size'], s['thumb_video_delay'], fit=s['thumb_fit'], converter=s['video_converter']) except Exception as e: self.logger.error('Failed to generate thumbnail: %s', e) return return url_from_path(self.thumb_name)
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) try: # if thumbnail is missing (if settings['make_thumbs'] is False) s = self.settings if self.type == 'image': image.generate_thumbnail( path, self.thumb_path, s['thumb_size'], fit=s['thumb_fit']) elif self.type == 'video': video.generate_thumbnail( path, self.thumb_path, s['thumb_size'], s['thumb_video_delay'], fit=s['thumb_fit'], converter=s['video_converter']) except Exception as e: self.logger.error('Failed to generate thumbnail: %s', e) return return url_from_path(self.thumb_name)
[ "Path", "to", "the", "thumbnail", "image", "(", "relative", "to", "the", "album", "directory", ")", "." ]
saimn/sigal
python
https://github.com/saimn/sigal/blob/912ca39991355d358dc85fd55c7aeabdd7acc386/sigal/gallery.py#L127-L149
[ "def", "thumbnail", "(", "self", ")", ":", "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", ")", "try", ":", "# if thumbnail is missing (if settings['make_thumbs'] is False)", "s", "=", "self", ".", "settings", "if", "self", ".", "type", "==", "'image'", ":", "image", ".", "generate_thumbnail", "(", "path", ",", "self", ".", "thumb_path", ",", "s", "[", "'thumb_size'", "]", ",", "fit", "=", "s", "[", "'thumb_fit'", "]", ")", "elif", "self", ".", "type", "==", "'video'", ":", "video", ".", "generate_thumbnail", "(", "path", ",", "self", ".", "thumb_path", ",", "s", "[", "'thumb_size'", "]", ",", "s", "[", "'thumb_video_delay'", "]", ",", "fit", "=", "s", "[", "'thumb_fit'", "]", ",", "converter", "=", "s", "[", "'video_converter'", "]", ")", "except", "Exception", "as", "e", ":", "self", ".", "logger", ".", "error", "(", "'Failed to generate thumbnail: %s'", ",", "e", ")", "return", "return", "url_from_path", "(", "self", ".", "thumb_name", ")" ]
912ca39991355d358dc85fd55c7aeabdd7acc386
valid
Media._get_metadata
Get image metadata from filename.md: title, description, meta.
sigal/gallery.py
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) for key, val in meta.items(): setattr(self, key, val)
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) for key, val in meta.items(): setattr(self, key, val)
[ "Get", "image", "metadata", "from", "filename", ".", "md", ":", "title", "description", "meta", "." ]
saimn/sigal
python
https://github.com/saimn/sigal/blob/912ca39991355d358dc85fd55c7aeabdd7acc386/sigal/gallery.py#L151-L161
[ "def", "_get_metadata", "(", "self", ")", ":", "self", ".", "description", "=", "''", "self", ".", "meta", "=", "{", "}", "self", ".", "title", "=", "''", "descfile", "=", "splitext", "(", "self", ".", "src_path", ")", "[", "0", "]", "+", "'.md'", "if", "isfile", "(", "descfile", ")", ":", "meta", "=", "read_markdown", "(", "descfile", ")", "for", "key", ",", "val", "in", "meta", ".", "items", "(", ")", ":", "setattr", "(", "self", ",", "key", ",", "val", ")" ]
912ca39991355d358dc85fd55c7aeabdd7acc386
valid
Album._get_metadata
Get album metadata from `description_file` (`index.md`): -> title, thumbnail image, description
sigal/gallery.py
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 self.title = os.path.basename(self.path if self.path != '.' else self.src_path) if isfile(descfile): meta = read_markdown(descfile) for key, val in meta.items(): setattr(self, key, val) try: self.author = self.meta['author'][0] except KeyError: self.author = self.settings.get('author')
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 self.title = os.path.basename(self.path if self.path != '.' else self.src_path) if isfile(descfile): meta = read_markdown(descfile) for key, val in meta.items(): setattr(self, key, val) try: self.author = self.meta['author'][0] except KeyError: self.author = self.settings.get('author')
[ "Get", "album", "metadata", "from", "description_file", "(", "index", ".", "md", ")", ":" ]
saimn/sigal
python
https://github.com/saimn/sigal/blob/912ca39991355d358dc85fd55c7aeabdd7acc386/sigal/gallery.py#L322-L343
[ "def", "_get_metadata", "(", "self", ")", ":", "descfile", "=", "join", "(", "self", ".", "src_path", ",", "self", ".", "description_file", ")", "self", ".", "description", "=", "''", "self", ".", "meta", "=", "{", "}", "# default: get title from directory name", "self", ".", "title", "=", "os", ".", "path", ".", "basename", "(", "self", ".", "path", "if", "self", ".", "path", "!=", "'.'", "else", "self", ".", "src_path", ")", "if", "isfile", "(", "descfile", ")", ":", "meta", "=", "read_markdown", "(", "descfile", ")", "for", "key", ",", "val", "in", "meta", ".", "items", "(", ")", ":", "setattr", "(", "self", ",", "key", ",", "val", ")", "try", ":", "self", ".", "author", "=", "self", ".", "meta", "[", "'author'", "]", "[", "0", "]", "except", "KeyError", ":", "self", ".", "author", "=", "self", ".", "settings", ".", "get", "(", "'author'", ")" ]
912ca39991355d358dc85fd55c7aeabdd7acc386
valid
Album.create_output_directories
Create output directories for thumbnails and original images.
sigal/gallery.py
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.medias and self.settings['keep_orig']: self.orig_path = join(self.dst_path, self.settings['orig_dir']) check_or_create_dir(self.orig_path)
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.medias and self.settings['keep_orig']: self.orig_path = join(self.dst_path, self.settings['orig_dir']) check_or_create_dir(self.orig_path)
[ "Create", "output", "directories", "for", "thumbnails", "and", "original", "images", "." ]
saimn/sigal
python
https://github.com/saimn/sigal/blob/912ca39991355d358dc85fd55c7aeabdd7acc386/sigal/gallery.py#L345-L355
[ "def", "create_output_directories", "(", "self", ")", ":", "check_or_create_dir", "(", "self", ".", "dst_path", ")", "if", "self", ".", "medias", ":", "check_or_create_dir", "(", "join", "(", "self", ".", "dst_path", ",", "self", ".", "settings", "[", "'thumb_dir'", "]", ")", ")", "if", "self", ".", "medias", "and", "self", ".", "settings", "[", "'keep_orig'", "]", ":", "self", ".", "orig_path", "=", "join", "(", "self", ".", "dst_path", ",", "self", ".", "settings", "[", "'orig_dir'", "]", ")", "check_or_create_dir", "(", "self", ".", "orig_path", ")" ]
912ca39991355d358dc85fd55c7aeabdd7acc386
valid
Album.albums
List of :class:`~sigal.gallery.Album` objects for each sub-directory.
sigal/gallery.py
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]
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]
[ "List", "of", ":", "class", ":", "~sigal", ".", "gallery", ".", "Album", "objects", "for", "each", "sub", "-", "directory", "." ]
saimn/sigal
python
https://github.com/saimn/sigal/blob/912ca39991355d358dc85fd55c7aeabdd7acc386/sigal/gallery.py#L407-L413
[ "def", "albums", "(", "self", ")", ":", "root_path", "=", "self", ".", "path", "if", "self", ".", "path", "!=", "'.'", "else", "''", "return", "[", "self", ".", "gallery", ".", "albums", "[", "join", "(", "root_path", ",", "path", ")", "]", "for", "path", "in", "self", ".", "subdirs", "]" ]
912ca39991355d358dc85fd55c7aeabdd7acc386
valid
Album.url
URL of the album, relative to its parent.
sigal/gallery.py
def url(self): """URL of the album, relative to its parent.""" url = self.name.encode('utf-8') return url_quote(url) + '/' + self.url_ext
def url(self): """URL of the album, relative to its parent.""" url = self.name.encode('utf-8') return url_quote(url) + '/' + self.url_ext
[ "URL", "of", "the", "album", "relative", "to", "its", "parent", "." ]
saimn/sigal
python
https://github.com/saimn/sigal/blob/912ca39991355d358dc85fd55c7aeabdd7acc386/sigal/gallery.py#L416-L419
[ "def", "url", "(", "self", ")", ":", "url", "=", "self", ".", "name", ".", "encode", "(", "'utf-8'", ")", "return", "url_quote", "(", "url", ")", "+", "'/'", "+", "self", ".", "url_ext" ]
912ca39991355d358dc85fd55c7aeabdd7acc386
valid
Album.thumbnail
Path to the thumbnail of the album.
sigal/gallery.py
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(join(self.src_path, thumbnail)): self._thumbnail = url_from_path(join( self.name, get_thumb(self.settings, thumbnail))) self.logger.debug("Thumbnail for %r : %s", self, self._thumbnail) return self._thumbnail else: # find and return the first landscape image for f in self.medias: ext = splitext(f.filename)[1] if ext.lower() in self.settings['img_extensions']: # Use f.size if available as it is quicker (in cache), but # fallback to the size of src_path if dst_path is missing size = f.size if size is None: size = get_size(f.src_path) if size['width'] > size['height']: self._thumbnail = (url_quote(self.name) + '/' + f.thumbnail) self.logger.debug( "Use 1st landscape image as thumbnail for %r : %s", self, self._thumbnail) return self._thumbnail # else simply return the 1st media file if not self._thumbnail and self.medias: for media in self.medias: if media.thumbnail is not None: self._thumbnail = (url_quote(self.name) + '/' + media.thumbnail) break else: self.logger.warning("No thumbnail found for %r", self) return None self.logger.debug("Use the 1st image as thumbnail for %r : %s", self, self._thumbnail) return self._thumbnail # use the thumbnail of their sub-directories if not self._thumbnail: for path, album in self.gallery.get_albums(self.path): if album.thumbnail: self._thumbnail = (url_quote(self.name) + '/' + album.thumbnail) self.logger.debug( "Using thumbnail from sub-directory for %r : %s", self, self._thumbnail) return self._thumbnail self.logger.error('Thumbnail not found for %r', self) return None
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(join(self.src_path, thumbnail)): self._thumbnail = url_from_path(join( self.name, get_thumb(self.settings, thumbnail))) self.logger.debug("Thumbnail for %r : %s", self, self._thumbnail) return self._thumbnail else: # find and return the first landscape image for f in self.medias: ext = splitext(f.filename)[1] if ext.lower() in self.settings['img_extensions']: # Use f.size if available as it is quicker (in cache), but # fallback to the size of src_path if dst_path is missing size = f.size if size is None: size = get_size(f.src_path) if size['width'] > size['height']: self._thumbnail = (url_quote(self.name) + '/' + f.thumbnail) self.logger.debug( "Use 1st landscape image as thumbnail for %r : %s", self, self._thumbnail) return self._thumbnail # else simply return the 1st media file if not self._thumbnail and self.medias: for media in self.medias: if media.thumbnail is not None: self._thumbnail = (url_quote(self.name) + '/' + media.thumbnail) break else: self.logger.warning("No thumbnail found for %r", self) return None self.logger.debug("Use the 1st image as thumbnail for %r : %s", self, self._thumbnail) return self._thumbnail # use the thumbnail of their sub-directories if not self._thumbnail: for path, album in self.gallery.get_albums(self.path): if album.thumbnail: self._thumbnail = (url_quote(self.name) + '/' + album.thumbnail) self.logger.debug( "Using thumbnail from sub-directory for %r : %s", self, self._thumbnail) return self._thumbnail self.logger.error('Thumbnail not found for %r', self) return None
[ "Path", "to", "the", "thumbnail", "of", "the", "album", "." ]
saimn/sigal
python
https://github.com/saimn/sigal/blob/912ca39991355d358dc85fd55c7aeabdd7acc386/sigal/gallery.py#L422-L483
[ "def", "thumbnail", "(", "self", ")", ":", "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", "(", "join", "(", "self", ".", "src_path", ",", "thumbnail", ")", ")", ":", "self", ".", "_thumbnail", "=", "url_from_path", "(", "join", "(", "self", ".", "name", ",", "get_thumb", "(", "self", ".", "settings", ",", "thumbnail", ")", ")", ")", "self", ".", "logger", ".", "debug", "(", "\"Thumbnail for %r : %s\"", ",", "self", ",", "self", ".", "_thumbnail", ")", "return", "self", ".", "_thumbnail", "else", ":", "# find and return the first landscape image", "for", "f", "in", "self", ".", "medias", ":", "ext", "=", "splitext", "(", "f", ".", "filename", ")", "[", "1", "]", "if", "ext", ".", "lower", "(", ")", "in", "self", ".", "settings", "[", "'img_extensions'", "]", ":", "# Use f.size if available as it is quicker (in cache), but", "# fallback to the size of src_path if dst_path is missing", "size", "=", "f", ".", "size", "if", "size", "is", "None", ":", "size", "=", "get_size", "(", "f", ".", "src_path", ")", "if", "size", "[", "'width'", "]", ">", "size", "[", "'height'", "]", ":", "self", ".", "_thumbnail", "=", "(", "url_quote", "(", "self", ".", "name", ")", "+", "'/'", "+", "f", ".", "thumbnail", ")", "self", ".", "logger", ".", "debug", "(", "\"Use 1st landscape image as thumbnail for %r : %s\"", ",", "self", ",", "self", ".", "_thumbnail", ")", "return", "self", ".", "_thumbnail", "# else simply return the 1st media file", "if", "not", "self", ".", "_thumbnail", "and", "self", ".", "medias", ":", "for", "media", "in", "self", ".", "medias", ":", "if", "media", ".", "thumbnail", "is", "not", "None", ":", "self", ".", "_thumbnail", "=", "(", "url_quote", "(", "self", ".", "name", ")", "+", "'/'", "+", "media", ".", "thumbnail", ")", "break", "else", ":", "self", ".", "logger", ".", "warning", "(", "\"No thumbnail found for %r\"", ",", "self", ")", "return", "None", "self", ".", "logger", ".", "debug", "(", "\"Use the 1st image as thumbnail for %r : %s\"", ",", "self", ",", "self", ".", "_thumbnail", ")", "return", "self", ".", "_thumbnail", "# use the thumbnail of their sub-directories", "if", "not", "self", ".", "_thumbnail", ":", "for", "path", ",", "album", "in", "self", ".", "gallery", ".", "get_albums", "(", "self", ".", "path", ")", ":", "if", "album", ".", "thumbnail", ":", "self", ".", "_thumbnail", "=", "(", "url_quote", "(", "self", ".", "name", ")", "+", "'/'", "+", "album", ".", "thumbnail", ")", "self", ".", "logger", ".", "debug", "(", "\"Using thumbnail from sub-directory for %r : %s\"", ",", "self", ",", "self", ".", "_thumbnail", ")", "return", "self", ".", "_thumbnail", "self", ".", "logger", ".", "error", "(", "'Thumbnail not found for %r'", ",", "self", ")", "return", "None" ]
912ca39991355d358dc85fd55c7aeabdd7acc386
valid
Album.breadcrumb
List of ``(url, title)`` tuples defining the current breadcrumb path.
sigal/gallery.py
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.path.join(path, '..')) if path == '.': break url = (url_from_path(os.path.relpath(path, self.path)) + '/' + self.url_ext) breadcrumb.append((url, self.gallery.albums[path].title)) breadcrumb.reverse() return breadcrumb
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.path.join(path, '..')) if path == '.': break url = (url_from_path(os.path.relpath(path, self.path)) + '/' + self.url_ext) breadcrumb.append((url, self.gallery.albums[path].title)) breadcrumb.reverse() return breadcrumb
[ "List", "of", "(", "url", "title", ")", "tuples", "defining", "the", "current", "breadcrumb", "path", "." ]
saimn/sigal
python
https://github.com/saimn/sigal/blob/912ca39991355d358dc85fd55c7aeabdd7acc386/sigal/gallery.py#L494-L514
[ "def", "breadcrumb", "(", "self", ")", ":", "if", "self", ".", "path", "==", "'.'", ":", "return", "[", "]", "path", "=", "self", ".", "path", "breadcrumb", "=", "[", "(", "(", "self", ".", "url_ext", "or", "'.'", ")", ",", "self", ".", "title", ")", "]", "while", "True", ":", "path", "=", "os", ".", "path", ".", "normpath", "(", "os", ".", "path", ".", "join", "(", "path", ",", "'..'", ")", ")", "if", "path", "==", "'.'", ":", "break", "url", "=", "(", "url_from_path", "(", "os", ".", "path", ".", "relpath", "(", "path", ",", "self", ".", "path", ")", ")", "+", "'/'", "+", "self", ".", "url_ext", ")", "breadcrumb", ".", "append", "(", "(", "url", ",", "self", ".", "gallery", ".", "albums", "[", "path", "]", ".", "title", ")", ")", "breadcrumb", ".", "reverse", "(", ")", "return", "breadcrumb" ]
912ca39991355d358dc85fd55c7aeabdd7acc386
valid
Album.zip
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.
sigal/gallery.py
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_gallery and len(self) > 0: zip_gallery = zip_gallery.format(album=self) archive_path = join(self.dst_path, zip_gallery) if (self.settings.get('zip_skip_if_exists', False) and isfile(archive_path)): self.logger.debug("Archive %s already created, passing", archive_path) return zip_gallery archive = zipfile.ZipFile(archive_path, 'w', allowZip64=True) attr = ('src_path' if self.settings['zip_media_format'] == 'orig' else 'dst_path') for p in self: path = getattr(p, attr) try: archive.write(path, os.path.split(path)[1]) except OSError as e: self.logger.warn('Failed to add %s to the ZIP: %s', p, e) archive.close() self.logger.debug('Created ZIP archive %s', archive_path) return zip_gallery
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_gallery and len(self) > 0: zip_gallery = zip_gallery.format(album=self) archive_path = join(self.dst_path, zip_gallery) if (self.settings.get('zip_skip_if_exists', False) and isfile(archive_path)): self.logger.debug("Archive %s already created, passing", archive_path) return zip_gallery archive = zipfile.ZipFile(archive_path, 'w', allowZip64=True) attr = ('src_path' if self.settings['zip_media_format'] == 'orig' else 'dst_path') for p in self: path = getattr(p, attr) try: archive.write(path, os.path.split(path)[1]) except OSError as e: self.logger.warn('Failed to add %s to the ZIP: %s', p, e) archive.close() self.logger.debug('Created ZIP archive %s', archive_path) return zip_gallery
[ "Make", "a", "ZIP", "archive", "with", "all", "media", "files", "and", "return", "its", "path", "." ]
saimn/sigal
python
https://github.com/saimn/sigal/blob/912ca39991355d358dc85fd55c7aeabdd7acc386/sigal/gallery.py#L523-L554
[ "def", "zip", "(", "self", ")", ":", "zip_gallery", "=", "self", ".", "settings", "[", "'zip_gallery'", "]", "if", "zip_gallery", "and", "len", "(", "self", ")", ">", "0", ":", "zip_gallery", "=", "zip_gallery", ".", "format", "(", "album", "=", "self", ")", "archive_path", "=", "join", "(", "self", ".", "dst_path", ",", "zip_gallery", ")", "if", "(", "self", ".", "settings", ".", "get", "(", "'zip_skip_if_exists'", ",", "False", ")", "and", "isfile", "(", "archive_path", ")", ")", ":", "self", ".", "logger", ".", "debug", "(", "\"Archive %s already created, passing\"", ",", "archive_path", ")", "return", "zip_gallery", "archive", "=", "zipfile", ".", "ZipFile", "(", "archive_path", ",", "'w'", ",", "allowZip64", "=", "True", ")", "attr", "=", "(", "'src_path'", "if", "self", ".", "settings", "[", "'zip_media_format'", "]", "==", "'orig'", "else", "'dst_path'", ")", "for", "p", "in", "self", ":", "path", "=", "getattr", "(", "p", ",", "attr", ")", "try", ":", "archive", ".", "write", "(", "path", ",", "os", ".", "path", ".", "split", "(", "path", ")", "[", "1", "]", ")", "except", "OSError", "as", "e", ":", "self", ".", "logger", ".", "warn", "(", "'Failed to add %s to the ZIP: %s'", ",", "p", ",", "e", ")", "archive", ".", "close", "(", ")", "self", ".", "logger", ".", "debug", "(", "'Created ZIP archive %s'", ",", "archive_path", ")", "return", "zip_gallery" ]
912ca39991355d358dc85fd55c7aeabdd7acc386
valid
Gallery.get_albums
Return the list of all sub-directories of path.
sigal/gallery.py
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 subname, self.albums[subdir]
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 subname, self.albums[subdir]
[ "Return", "the", "list", "of", "all", "sub", "-", "directories", "of", "path", "." ]
saimn/sigal
python
https://github.com/saimn/sigal/blob/912ca39991355d358dc85fd55c7aeabdd7acc386/sigal/gallery.py#L657-L664
[ "def", "get_albums", "(", "self", ",", "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", "subname", ",", "self", ".", "albums", "[", "subdir", "]" ]
912ca39991355d358dc85fd55c7aeabdd7acc386
valid
Gallery.build
Create the image gallery
sigal/gallery.py
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] - 64 if x and available_length > 10: return x.name[:available_length] else: return "" try: with progressbar(self.albums.values(), label="Collecting files", item_show_func=log_func, show_eta=False, file=self.progressbar_target) as albums: media_list = [f for album in albums for f in self.process_dir(album, force=force)] except KeyboardInterrupt: sys.exit('Interrupted') bar_opt = {'label': "Processing files", 'show_pos': True, 'file': self.progressbar_target} failed_files = [] if self.pool: try: with progressbar(length=len(media_list), **bar_opt) as bar: for res in self.pool.imap_unordered(worker, media_list): if res: failed_files.append(res) bar.update(1) self.pool.close() self.pool.join() except KeyboardInterrupt: self.pool.terminate() sys.exit('Interrupted') except pickle.PicklingError: self.logger.critical( "Failed to process files with the multiprocessing feature." " This can be caused by some module import or object " "defined in the settings file, which can't be serialized.", exc_info=True) sys.exit('Abort') else: with progressbar(media_list, **bar_opt) as medias: for media_item in medias: res = process_file(media_item) if res: failed_files.append(res) if failed_files: self.remove_files(failed_files) if self.settings['write_html']: album_writer = AlbumPageWriter(self.settings, index_title=self.title) album_list_writer = AlbumListPageWriter(self.settings, index_title=self.title) with progressbar(self.albums.values(), label="%16s" % "Writing files", item_show_func=log_func, show_eta=False, file=self.progressbar_target) as albums: for album in albums: if album.albums: if album.medias: self.logger.warning( "Album %s contains sub-albums and images. " "Please move images to their own sub-album. " "Images in album %s will not be visible.", album.title, album.title ) album_list_writer.write(album) else: album_writer.write(album) print('') signals.gallery_build.send(self)
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] - 64 if x and available_length > 10: return x.name[:available_length] else: return "" try: with progressbar(self.albums.values(), label="Collecting files", item_show_func=log_func, show_eta=False, file=self.progressbar_target) as albums: media_list = [f for album in albums for f in self.process_dir(album, force=force)] except KeyboardInterrupt: sys.exit('Interrupted') bar_opt = {'label': "Processing files", 'show_pos': True, 'file': self.progressbar_target} failed_files = [] if self.pool: try: with progressbar(length=len(media_list), **bar_opt) as bar: for res in self.pool.imap_unordered(worker, media_list): if res: failed_files.append(res) bar.update(1) self.pool.close() self.pool.join() except KeyboardInterrupt: self.pool.terminate() sys.exit('Interrupted') except pickle.PicklingError: self.logger.critical( "Failed to process files with the multiprocessing feature." " This can be caused by some module import or object " "defined in the settings file, which can't be serialized.", exc_info=True) sys.exit('Abort') else: with progressbar(media_list, **bar_opt) as medias: for media_item in medias: res = process_file(media_item) if res: failed_files.append(res) if failed_files: self.remove_files(failed_files) if self.settings['write_html']: album_writer = AlbumPageWriter(self.settings, index_title=self.title) album_list_writer = AlbumListPageWriter(self.settings, index_title=self.title) with progressbar(self.albums.values(), label="%16s" % "Writing files", item_show_func=log_func, show_eta=False, file=self.progressbar_target) as albums: for album in albums: if album.albums: if album.medias: self.logger.warning( "Album %s contains sub-albums and images. " "Please move images to their own sub-album. " "Images in album %s will not be visible.", album.title, album.title ) album_list_writer.write(album) else: album_writer.write(album) print('') signals.gallery_build.send(self)
[ "Create", "the", "image", "gallery" ]
saimn/sigal
python
https://github.com/saimn/sigal/blob/912ca39991355d358dc85fd55c7aeabdd7acc386/sigal/gallery.py#L666-L747
[ "def", "build", "(", "self", ",", "force", "=", "False", ")", ":", "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", "]", "-", "64", "if", "x", "and", "available_length", ">", "10", ":", "return", "x", ".", "name", "[", ":", "available_length", "]", "else", ":", "return", "\"\"", "try", ":", "with", "progressbar", "(", "self", ".", "albums", ".", "values", "(", ")", ",", "label", "=", "\"Collecting files\"", ",", "item_show_func", "=", "log_func", ",", "show_eta", "=", "False", ",", "file", "=", "self", ".", "progressbar_target", ")", "as", "albums", ":", "media_list", "=", "[", "f", "for", "album", "in", "albums", "for", "f", "in", "self", ".", "process_dir", "(", "album", ",", "force", "=", "force", ")", "]", "except", "KeyboardInterrupt", ":", "sys", ".", "exit", "(", "'Interrupted'", ")", "bar_opt", "=", "{", "'label'", ":", "\"Processing files\"", ",", "'show_pos'", ":", "True", ",", "'file'", ":", "self", ".", "progressbar_target", "}", "failed_files", "=", "[", "]", "if", "self", ".", "pool", ":", "try", ":", "with", "progressbar", "(", "length", "=", "len", "(", "media_list", ")", ",", "*", "*", "bar_opt", ")", "as", "bar", ":", "for", "res", "in", "self", ".", "pool", ".", "imap_unordered", "(", "worker", ",", "media_list", ")", ":", "if", "res", ":", "failed_files", ".", "append", "(", "res", ")", "bar", ".", "update", "(", "1", ")", "self", ".", "pool", ".", "close", "(", ")", "self", ".", "pool", ".", "join", "(", ")", "except", "KeyboardInterrupt", ":", "self", ".", "pool", ".", "terminate", "(", ")", "sys", ".", "exit", "(", "'Interrupted'", ")", "except", "pickle", ".", "PicklingError", ":", "self", ".", "logger", ".", "critical", "(", "\"Failed to process files with the multiprocessing feature.\"", "\" This can be caused by some module import or object \"", "\"defined in the settings file, which can't be serialized.\"", ",", "exc_info", "=", "True", ")", "sys", ".", "exit", "(", "'Abort'", ")", "else", ":", "with", "progressbar", "(", "media_list", ",", "*", "*", "bar_opt", ")", "as", "medias", ":", "for", "media_item", "in", "medias", ":", "res", "=", "process_file", "(", "media_item", ")", "if", "res", ":", "failed_files", ".", "append", "(", "res", ")", "if", "failed_files", ":", "self", ".", "remove_files", "(", "failed_files", ")", "if", "self", ".", "settings", "[", "'write_html'", "]", ":", "album_writer", "=", "AlbumPageWriter", "(", "self", ".", "settings", ",", "index_title", "=", "self", ".", "title", ")", "album_list_writer", "=", "AlbumListPageWriter", "(", "self", ".", "settings", ",", "index_title", "=", "self", ".", "title", ")", "with", "progressbar", "(", "self", ".", "albums", ".", "values", "(", ")", ",", "label", "=", "\"%16s\"", "%", "\"Writing files\"", ",", "item_show_func", "=", "log_func", ",", "show_eta", "=", "False", ",", "file", "=", "self", ".", "progressbar_target", ")", "as", "albums", ":", "for", "album", "in", "albums", ":", "if", "album", ".", "albums", ":", "if", "album", ".", "medias", ":", "self", ".", "logger", ".", "warning", "(", "\"Album %s contains sub-albums and images. \"", "\"Please move images to their own sub-album. \"", "\"Images in album %s will not be visible.\"", ",", "album", ".", "title", ",", "album", ".", "title", ")", "album_list_writer", ".", "write", "(", "album", ")", "else", ":", "album_writer", ".", "write", "(", "album", ")", "print", "(", "''", ")", "signals", ".", "gallery_build", ".", "send", "(", "self", ")" ]
912ca39991355d358dc85fd55c7aeabdd7acc386
valid
Gallery.process_dir
Process a list of images in a directory.
sigal/gallery.py
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: self.stats[f.type] += 1 yield (f.type, f.path, f.filename, f.src_path, album.dst_path, self.settings)
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: self.stats[f.type] += 1 yield (f.type, f.path, f.filename, f.src_path, album.dst_path, self.settings)
[ "Process", "a", "list", "of", "images", "in", "a", "directory", "." ]
saimn/sigal
python
https://github.com/saimn/sigal/blob/912ca39991355d358dc85fd55c7aeabdd7acc386/sigal/gallery.py#L762-L771
[ "def", "process_dir", "(", "self", ",", "album", ",", "force", "=", "False", ")", ":", "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", ":", "self", ".", "stats", "[", "f", ".", "type", "]", "+=", "1", "yield", "(", "f", ".", "type", ",", "f", ".", "path", ",", "f", ".", "filename", ",", "f", ".", "src_path", ",", "album", ".", "dst_path", ",", "self", ".", "settings", ")" ]
912ca39991355d358dc85fd55c7aeabdd7acc386
valid
reduce_opacity
Returns an image with reduced opacity.
sigal/plugins/watermark.py
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(alpha) return im
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(alpha) return im
[ "Returns", "an", "image", "with", "reduced", "opacity", "." ]
saimn/sigal
python
https://github.com/saimn/sigal/blob/912ca39991355d358dc85fd55c7aeabdd7acc386/sigal/plugins/watermark.py#L42-L52
[ "def", "reduce_opacity", "(", "im", ",", "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", "(", "alpha", ")", "return", "im" ]
912ca39991355d358dc85fd55c7aeabdd7acc386
valid
watermark
Adds a watermark to an image.
sigal/plugins/watermark.py
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 = Image.new('RGBA', im.size, (0, 0, 0, 0)) if position == 'tile': for y in range(0, im.size[1], mark.size[1]): for x in range(0, im.size[0], mark.size[0]): layer.paste(mark, (x, y)) elif position == 'scale': # scale, but preserve the aspect ratio ratio = min( float(im.size[0]) / mark.size[0], float(im.size[1]) / mark.size[1]) w = int(mark.size[0] * ratio) h = int(mark.size[1] * ratio) mark = mark.resize((w, h)) layer.paste(mark, (int((im.size[0] - w) / 2), int((im.size[1] - h) / 2))) else: layer.paste(mark, position) # composite the watermark with the layer return Image.composite(layer, im, layer)
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 = Image.new('RGBA', im.size, (0, 0, 0, 0)) if position == 'tile': for y in range(0, im.size[1], mark.size[1]): for x in range(0, im.size[0], mark.size[0]): layer.paste(mark, (x, y)) elif position == 'scale': # scale, but preserve the aspect ratio ratio = min( float(im.size[0]) / mark.size[0], float(im.size[1]) / mark.size[1]) w = int(mark.size[0] * ratio) h = int(mark.size[1] * ratio) mark = mark.resize((w, h)) layer.paste(mark, (int((im.size[0] - w) / 2), int((im.size[1] - h) / 2))) else: layer.paste(mark, position) # composite the watermark with the layer return Image.composite(layer, im, layer)
[ "Adds", "a", "watermark", "to", "an", "image", "." ]
saimn/sigal
python
https://github.com/saimn/sigal/blob/912ca39991355d358dc85fd55c7aeabdd7acc386/sigal/plugins/watermark.py#L55-L80
[ "def", "watermark", "(", "im", ",", "mark", ",", "position", ",", "opacity", "=", "1", ")", ":", "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", "=", "Image", ".", "new", "(", "'RGBA'", ",", "im", ".", "size", ",", "(", "0", ",", "0", ",", "0", ",", "0", ")", ")", "if", "position", "==", "'tile'", ":", "for", "y", "in", "range", "(", "0", ",", "im", ".", "size", "[", "1", "]", ",", "mark", ".", "size", "[", "1", "]", ")", ":", "for", "x", "in", "range", "(", "0", ",", "im", ".", "size", "[", "0", "]", ",", "mark", ".", "size", "[", "0", "]", ")", ":", "layer", ".", "paste", "(", "mark", ",", "(", "x", ",", "y", ")", ")", "elif", "position", "==", "'scale'", ":", "# scale, but preserve the aspect ratio", "ratio", "=", "min", "(", "float", "(", "im", ".", "size", "[", "0", "]", ")", "/", "mark", ".", "size", "[", "0", "]", ",", "float", "(", "im", ".", "size", "[", "1", "]", ")", "/", "mark", ".", "size", "[", "1", "]", ")", "w", "=", "int", "(", "mark", ".", "size", "[", "0", "]", "*", "ratio", ")", "h", "=", "int", "(", "mark", ".", "size", "[", "1", "]", "*", "ratio", ")", "mark", "=", "mark", ".", "resize", "(", "(", "w", ",", "h", ")", ")", "layer", ".", "paste", "(", "mark", ",", "(", "int", "(", "(", "im", ".", "size", "[", "0", "]", "-", "w", ")", "/", "2", ")", ",", "int", "(", "(", "im", ".", "size", "[", "1", "]", "-", "h", ")", "/", "2", ")", ")", ")", "else", ":", "layer", ".", "paste", "(", "mark", ",", "position", ")", "# composite the watermark with the layer", "return", "Image", ".", "composite", "(", "layer", ",", "im", ",", "layer", ")" ]
912ca39991355d358dc85fd55c7aeabdd7acc386
valid
check_subprocess
Run the command to resize the video and remove the output file if the processing fails.
sigal/video.py
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) except KeyboardInterrupt: logger.debug('Process terminated, removing file %s', outname) if os.path.isfile(outname): os.remove(outname) raise if res.returncode: logger.debug('STDOUT:\n %s', res.stdout.decode('utf8')) logger.debug('STDERR:\n %s', res.stderr.decode('utf8')) if os.path.isfile(outname): logger.debug('Removing file %s', outname) os.remove(outname) raise SubprocessException('Failed to process ' + source)
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) except KeyboardInterrupt: logger.debug('Process terminated, removing file %s', outname) if os.path.isfile(outname): os.remove(outname) raise if res.returncode: logger.debug('STDOUT:\n %s', res.stdout.decode('utf8')) logger.debug('STDERR:\n %s', res.stderr.decode('utf8')) if os.path.isfile(outname): logger.debug('Removing file %s', outname) os.remove(outname) raise SubprocessException('Failed to process ' + source)
[ "Run", "the", "command", "to", "resize", "the", "video", "and", "remove", "the", "output", "file", "if", "the", "processing", "fails", "." ]
saimn/sigal
python
https://github.com/saimn/sigal/blob/912ca39991355d358dc85fd55c7aeabdd7acc386/sigal/video.py#L38-L59
[ "def", "check_subprocess", "(", "cmd", ",", "source", ",", "outname", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "try", ":", "res", "=", "subprocess", ".", "run", "(", "cmd", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "PIPE", ")", "except", "KeyboardInterrupt", ":", "logger", ".", "debug", "(", "'Process terminated, removing file %s'", ",", "outname", ")", "if", "os", ".", "path", ".", "isfile", "(", "outname", ")", ":", "os", ".", "remove", "(", "outname", ")", "raise", "if", "res", ".", "returncode", ":", "logger", ".", "debug", "(", "'STDOUT:\\n %s'", ",", "res", ".", "stdout", ".", "decode", "(", "'utf8'", ")", ")", "logger", ".", "debug", "(", "'STDERR:\\n %s'", ",", "res", ".", "stderr", ".", "decode", "(", "'utf8'", ")", ")", "if", "os", ".", "path", ".", "isfile", "(", "outname", ")", ":", "logger", ".", "debug", "(", "'Removing file %s'", ",", "outname", ")", "os", ".", "remove", "(", "outname", ")", "raise", "SubprocessException", "(", "'Failed to process '", "+", "source", ")" ]
912ca39991355d358dc85fd55c7aeabdd7acc386
valid
video_size
Returns the dimensions of the video.
sigal/video.py
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 = re.compile(r'rotate\s*:\s*-?(90|270)') rot_match = rot_pattern.search(stderr) if match: x, y = int(match.groups()[0]), int(match.groups()[1]) else: x = y = 0 if rot_match: x, y = y, x return x, y
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 = re.compile(r'rotate\s*:\s*-?(90|270)') rot_match = rot_pattern.search(stderr) if match: x, y = int(match.groups()[0]), int(match.groups()[1]) else: x = y = 0 if rot_match: x, y = y, x return x, y
[ "Returns", "the", "dimensions", "of", "the", "video", "." ]
saimn/sigal
python
https://github.com/saimn/sigal/blob/912ca39991355d358dc85fd55c7aeabdd7acc386/sigal/video.py#L62-L78
[ "def", "video_size", "(", "source", ",", "converter", "=", "'ffmpeg'", ")", ":", "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", "=", "re", ".", "compile", "(", "r'rotate\\s*:\\s*-?(90|270)'", ")", "rot_match", "=", "rot_pattern", ".", "search", "(", "stderr", ")", "if", "match", ":", "x", ",", "y", "=", "int", "(", "match", ".", "groups", "(", ")", "[", "0", "]", ")", ",", "int", "(", "match", ".", "groups", "(", ")", "[", "1", "]", ")", "else", ":", "x", "=", "y", "=", "0", "if", "rot_match", ":", "x", ",", "y", "=", "y", ",", "x", "return", "x", ",", "y" ]
912ca39991355d358dc85fd55c7aeabdd7acc386
valid
generate_video
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
sigal/video.py
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 transcode if source is in the required format and # has fitting datedimensions, copy instead. converter = settings['video_converter'] w_src, h_src = video_size(source, converter=converter) w_dst, h_dst = settings['video_size'] logger.debug('Video size: %i, %i -> %i, %i', w_src, h_src, w_dst, h_dst) base, src_ext = splitext(source) base, dst_ext = splitext(outname) if dst_ext == src_ext and w_src <= w_dst and h_src <= h_dst: logger.debug('Video is smaller than the max size, copying it instead') shutil.copy(source, outname) return # http://stackoverflow.com/questions/8218363/maintaining-ffmpeg-aspect-ratio # + I made a drawing on paper to figure this out if h_dst * w_src < h_src * w_dst: # biggest fitting dimension is height resize_opt = ['-vf', "scale=trunc(oh*a/2)*2:%i" % h_dst] else: # biggest fitting dimension is width resize_opt = ['-vf', "scale=%i:trunc(ow/a/2)*2" % w_dst] # do not resize if input dimensions are smaller than output dimensions if w_src <= w_dst and h_src <= h_dst: resize_opt = [] # Encoding options improved, thanks to # http://ffmpeg.org/trac/ffmpeg/wiki/vpxEncodingGuide cmd = [converter, '-i', source, '-y'] # -y to overwrite output files if options is not None: cmd += options cmd += resize_opt + [outname] logger.debug('Processing video: %s', ' '.join(cmd)) check_subprocess(cmd, source, outname)
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 transcode if source is in the required format and # has fitting datedimensions, copy instead. converter = settings['video_converter'] w_src, h_src = video_size(source, converter=converter) w_dst, h_dst = settings['video_size'] logger.debug('Video size: %i, %i -> %i, %i', w_src, h_src, w_dst, h_dst) base, src_ext = splitext(source) base, dst_ext = splitext(outname) if dst_ext == src_ext and w_src <= w_dst and h_src <= h_dst: logger.debug('Video is smaller than the max size, copying it instead') shutil.copy(source, outname) return # http://stackoverflow.com/questions/8218363/maintaining-ffmpeg-aspect-ratio # + I made a drawing on paper to figure this out if h_dst * w_src < h_src * w_dst: # biggest fitting dimension is height resize_opt = ['-vf', "scale=trunc(oh*a/2)*2:%i" % h_dst] else: # biggest fitting dimension is width resize_opt = ['-vf', "scale=%i:trunc(ow/a/2)*2" % w_dst] # do not resize if input dimensions are smaller than output dimensions if w_src <= w_dst and h_src <= h_dst: resize_opt = [] # Encoding options improved, thanks to # http://ffmpeg.org/trac/ffmpeg/wiki/vpxEncodingGuide cmd = [converter, '-i', source, '-y'] # -y to overwrite output files if options is not None: cmd += options cmd += resize_opt + [outname] logger.debug('Processing video: %s', ' '.join(cmd)) check_subprocess(cmd, source, outname)
[ "Video", "processor", "." ]
saimn/sigal
python
https://github.com/saimn/sigal/blob/912ca39991355d358dc85fd55c7aeabdd7acc386/sigal/video.py#L81-L127
[ "def", "generate_video", "(", "source", ",", "outname", ",", "settings", ",", "options", "=", "None", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "# Don't transcode if source is in the required format and", "# has fitting datedimensions, copy instead.", "converter", "=", "settings", "[", "'video_converter'", "]", "w_src", ",", "h_src", "=", "video_size", "(", "source", ",", "converter", "=", "converter", ")", "w_dst", ",", "h_dst", "=", "settings", "[", "'video_size'", "]", "logger", ".", "debug", "(", "'Video size: %i, %i -> %i, %i'", ",", "w_src", ",", "h_src", ",", "w_dst", ",", "h_dst", ")", "base", ",", "src_ext", "=", "splitext", "(", "source", ")", "base", ",", "dst_ext", "=", "splitext", "(", "outname", ")", "if", "dst_ext", "==", "src_ext", "and", "w_src", "<=", "w_dst", "and", "h_src", "<=", "h_dst", ":", "logger", ".", "debug", "(", "'Video is smaller than the max size, copying it instead'", ")", "shutil", ".", "copy", "(", "source", ",", "outname", ")", "return", "# http://stackoverflow.com/questions/8218363/maintaining-ffmpeg-aspect-ratio", "# + I made a drawing on paper to figure this out", "if", "h_dst", "*", "w_src", "<", "h_src", "*", "w_dst", ":", "# biggest fitting dimension is height", "resize_opt", "=", "[", "'-vf'", ",", "\"scale=trunc(oh*a/2)*2:%i\"", "%", "h_dst", "]", "else", ":", "# biggest fitting dimension is width", "resize_opt", "=", "[", "'-vf'", ",", "\"scale=%i:trunc(ow/a/2)*2\"", "%", "w_dst", "]", "# do not resize if input dimensions are smaller than output dimensions", "if", "w_src", "<=", "w_dst", "and", "h_src", "<=", "h_dst", ":", "resize_opt", "=", "[", "]", "# Encoding options improved, thanks to", "# http://ffmpeg.org/trac/ffmpeg/wiki/vpxEncodingGuide", "cmd", "=", "[", "converter", ",", "'-i'", ",", "source", ",", "'-y'", "]", "# -y to overwrite output files", "if", "options", "is", "not", "None", ":", "cmd", "+=", "options", "cmd", "+=", "resize_opt", "+", "[", "outname", "]", "logger", ".", "debug", "(", "'Processing video: %s'", ",", "' '", ".", "join", "(", "cmd", ")", ")", "check_subprocess", "(", "cmd", ",", "source", ",", "outname", ")" ]
912ca39991355d358dc85fd55c7aeabdd7acc386
valid
generate_thumbnail
Create a thumbnail image for the video source, based on ffmpeg.
sigal/video.py
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 = [converter, '-i', source, '-an', '-r', '1', '-ss', delay, '-vframes', '1', '-y', tmpfile] logger.debug('Create thumbnail for video: %s', ' '.join(cmd)) check_subprocess(cmd, source, outname) # use the generate_thumbnail function from sigal.image image.generate_thumbnail(tmpfile, outname, box, fit=fit, options=options) # remove the image os.unlink(tmpfile)
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 = [converter, '-i', source, '-an', '-r', '1', '-ss', delay, '-vframes', '1', '-y', tmpfile] logger.debug('Create thumbnail for video: %s', ' '.join(cmd)) check_subprocess(cmd, source, outname) # use the generate_thumbnail function from sigal.image image.generate_thumbnail(tmpfile, outname, box, fit=fit, options=options) # remove the image os.unlink(tmpfile)
[ "Create", "a", "thumbnail", "image", "for", "the", "video", "source", "based", "on", "ffmpeg", "." ]
saimn/sigal
python
https://github.com/saimn/sigal/blob/912ca39991355d358dc85fd55c7aeabdd7acc386/sigal/video.py#L130-L146
[ "def", "generate_thumbnail", "(", "source", ",", "outname", ",", "box", ",", "delay", ",", "fit", "=", "True", ",", "options", "=", "None", ",", "converter", "=", "'ffmpeg'", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "tmpfile", "=", "outname", "+", "\".tmp.jpg\"", "# dump an image of the video", "cmd", "=", "[", "converter", ",", "'-i'", ",", "source", ",", "'-an'", ",", "'-r'", ",", "'1'", ",", "'-ss'", ",", "delay", ",", "'-vframes'", ",", "'1'", ",", "'-y'", ",", "tmpfile", "]", "logger", ".", "debug", "(", "'Create thumbnail for video: %s'", ",", "' '", ".", "join", "(", "cmd", ")", ")", "check_subprocess", "(", "cmd", ",", "source", ",", "outname", ")", "# use the generate_thumbnail function from sigal.image", "image", ".", "generate_thumbnail", "(", "tmpfile", ",", "outname", ",", "box", ",", "fit", "=", "fit", ",", "options", "=", "options", ")", "# remove the image", "os", ".", "unlink", "(", "tmpfile", ")" ]
912ca39991355d358dc85fd55c7aeabdd7acc386
valid
process_video
Process a video: resize, create thumbnail.
sigal/video.py
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 = os.path.join(outpath, filename) utils.copy(filepath, outname, symlink=settings['orig_link']) else: valid_formats = ['mp4', 'webm'] video_format = settings['video_format'] if video_format not in valid_formats: logger.error('Invalid video_format. Please choose one of: %s', valid_formats) raise ValueError outname = os.path.join(outpath, basename + '.' + video_format) generate_video(filepath, outname, settings, options=settings.get(video_format + '_options')) except Exception: if logger.getEffectiveLevel() == logging.DEBUG: raise else: return Status.FAILURE if settings['make_thumbs']: thumb_name = os.path.join(outpath, get_thumb(settings, filename)) try: generate_thumbnail( outname, thumb_name, settings['thumb_size'], settings['thumb_video_delay'], fit=settings['thumb_fit'], options=settings['jpg_options'], converter=settings['video_converter']) except Exception: if logger.getEffectiveLevel() == logging.DEBUG: raise else: return Status.FAILURE return Status.SUCCESS
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 = os.path.join(outpath, filename) utils.copy(filepath, outname, symlink=settings['orig_link']) else: valid_formats = ['mp4', 'webm'] video_format = settings['video_format'] if video_format not in valid_formats: logger.error('Invalid video_format. Please choose one of: %s', valid_formats) raise ValueError outname = os.path.join(outpath, basename + '.' + video_format) generate_video(filepath, outname, settings, options=settings.get(video_format + '_options')) except Exception: if logger.getEffectiveLevel() == logging.DEBUG: raise else: return Status.FAILURE if settings['make_thumbs']: thumb_name = os.path.join(outpath, get_thumb(settings, filename)) try: generate_thumbnail( outname, thumb_name, settings['thumb_size'], settings['thumb_video_delay'], fit=settings['thumb_fit'], options=settings['jpg_options'], converter=settings['video_converter']) except Exception: if logger.getEffectiveLevel() == logging.DEBUG: raise else: return Status.FAILURE return Status.SUCCESS
[ "Process", "a", "video", ":", "resize", "create", "thumbnail", "." ]
saimn/sigal
python
https://github.com/saimn/sigal/blob/912ca39991355d358dc85fd55c7aeabdd7acc386/sigal/video.py#L149-L192
[ "def", "process_video", "(", "filepath", ",", "outpath", ",", "settings", ")", ":", "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", "=", "os", ".", "path", ".", "join", "(", "outpath", ",", "filename", ")", "utils", ".", "copy", "(", "filepath", ",", "outname", ",", "symlink", "=", "settings", "[", "'orig_link'", "]", ")", "else", ":", "valid_formats", "=", "[", "'mp4'", ",", "'webm'", "]", "video_format", "=", "settings", "[", "'video_format'", "]", "if", "video_format", "not", "in", "valid_formats", ":", "logger", ".", "error", "(", "'Invalid video_format. Please choose one of: %s'", ",", "valid_formats", ")", "raise", "ValueError", "outname", "=", "os", ".", "path", ".", "join", "(", "outpath", ",", "basename", "+", "'.'", "+", "video_format", ")", "generate_video", "(", "filepath", ",", "outname", ",", "settings", ",", "options", "=", "settings", ".", "get", "(", "video_format", "+", "'_options'", ")", ")", "except", "Exception", ":", "if", "logger", ".", "getEffectiveLevel", "(", ")", "==", "logging", ".", "DEBUG", ":", "raise", "else", ":", "return", "Status", ".", "FAILURE", "if", "settings", "[", "'make_thumbs'", "]", ":", "thumb_name", "=", "os", ".", "path", ".", "join", "(", "outpath", ",", "get_thumb", "(", "settings", ",", "filename", ")", ")", "try", ":", "generate_thumbnail", "(", "outname", ",", "thumb_name", ",", "settings", "[", "'thumb_size'", "]", ",", "settings", "[", "'thumb_video_delay'", "]", ",", "fit", "=", "settings", "[", "'thumb_fit'", "]", ",", "options", "=", "settings", "[", "'jpg_options'", "]", ",", "converter", "=", "settings", "[", "'video_converter'", "]", ")", "except", "Exception", ":", "if", "logger", ".", "getEffectiveLevel", "(", ")", "==", "logging", ".", "DEBUG", ":", "raise", "else", ":", "return", "Status", ".", "FAILURE", "return", "Status", ".", "SUCCESS" ]
912ca39991355d358dc85fd55c7aeabdd7acc386
valid
init_logging
Logging config Set the level and create a more detailed formatter for debug mode.
sigal/log.py
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'): formatter = ColoredFormatter() elif level == logging.DEBUG: formatter = Formatter('%(levelname)s - %(message)s') else: formatter = Formatter('%(message)s') except Exception: # This fails when running tests with click (test_build) formatter = Formatter('%(message)s') handler = logging.StreamHandler() handler.setFormatter(formatter) logger.addHandler(handler)
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'): formatter = ColoredFormatter() elif level == logging.DEBUG: formatter = Formatter('%(levelname)s - %(message)s') else: formatter = Formatter('%(message)s') except Exception: # This fails when running tests with click (test_build) formatter = Formatter('%(message)s') handler = logging.StreamHandler() handler.setFormatter(formatter) logger.addHandler(handler)
[ "Logging", "config" ]
saimn/sigal
python
https://github.com/saimn/sigal/blob/912ca39991355d358dc85fd55c7aeabdd7acc386/sigal/log.py#L57-L80
[ "def", "init_logging", "(", "name", ",", "level", "=", "logging", ".", "INFO", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "name", ")", "logger", ".", "setLevel", "(", "level", ")", "try", ":", "if", "os", ".", "isatty", "(", "sys", ".", "stdout", ".", "fileno", "(", ")", ")", "and", "not", "sys", ".", "platform", ".", "startswith", "(", "'win'", ")", ":", "formatter", "=", "ColoredFormatter", "(", ")", "elif", "level", "==", "logging", ".", "DEBUG", ":", "formatter", "=", "Formatter", "(", "'%(levelname)s - %(message)s'", ")", "else", ":", "formatter", "=", "Formatter", "(", "'%(message)s'", ")", "except", "Exception", ":", "# This fails when running tests with click (test_build)", "formatter", "=", "Formatter", "(", "'%(message)s'", ")", "handler", "=", "logging", ".", "StreamHandler", "(", ")", "handler", ".", "setFormatter", "(", "formatter", ")", "logger", ".", "addHandler", "(", "handler", ")" ]
912ca39991355d358dc85fd55c7aeabdd7acc386
valid
AbstractWriter.generate_context
Generate the context dict for the given path.
sigal/writer.py
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, 'sigal_link': sigal_link, 'theme': {'name': os.path.basename(self.theme), 'url': url_from_path(os.path.relpath(self.theme_path, album.dst_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, 'sigal_link': sigal_link, 'theme': {'name': os.path.basename(self.theme), 'url': url_from_path(os.path.relpath(self.theme_path, album.dst_path))}, }
[ "Generate", "the", "context", "dict", "for", "the", "given", "path", "." ]
saimn/sigal
python
https://github.com/saimn/sigal/blob/912ca39991355d358dc85fd55c7aeabdd7acc386/sigal/writer.py#L98-L111
[ "def", "generate_context", "(", "self", ",", "album", ")", ":", "from", ".", "import", "__url__", "as", "sigal_link", "self", ".", "logger", ".", "info", "(", "\"Output album : %r\"", ",", "album", ")", "return", "{", "'album'", ":", "album", ",", "'index_title'", ":", "self", ".", "index_title", ",", "'settings'", ":", "self", ".", "settings", ",", "'sigal_link'", ":", "sigal_link", ",", "'theme'", ":", "{", "'name'", ":", "os", ".", "path", ".", "basename", "(", "self", ".", "theme", ")", ",", "'url'", ":", "url_from_path", "(", "os", ".", "path", ".", "relpath", "(", "self", ".", "theme_path", ",", "album", ".", "dst_path", ")", ")", "}", ",", "}" ]
912ca39991355d358dc85fd55c7aeabdd7acc386
valid
AbstractWriter.write
Generate the HTML page and save it.
sigal/writer.py
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)
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)
[ "Generate", "the", "HTML", "page", "and", "save", "it", "." ]
saimn/sigal
python
https://github.com/saimn/sigal/blob/912ca39991355d358dc85fd55c7aeabdd7acc386/sigal/writer.py#L113-L120
[ "def", "write", "(", "self", ",", "album", ")", ":", "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", ")" ]
912ca39991355d358dc85fd55c7aeabdd7acc386
valid
get_thumb
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 a jpg file: >>> get_thumb(default_settings, "bar/foo.webm") "bar/thumbnails/foo.jpg"
sigal/settings.py
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 a jpg file: >>> get_thumb(default_settings, "bar/foo.webm") "bar/thumbnails/foo.jpg" """ path, filen = os.path.split(filename) name, ext = os.path.splitext(filen) if ext.lower() in settings['video_extensions']: ext = '.jpg' return join(path, settings['thumb_dir'], settings['thumb_prefix'] + name + settings['thumb_suffix'] + ext)
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 a jpg file: >>> get_thumb(default_settings, "bar/foo.webm") "bar/thumbnails/foo.jpg" """ path, filen = os.path.split(filename) name, ext = os.path.splitext(filen) if ext.lower() in settings['video_extensions']: ext = '.jpg' return join(path, settings['thumb_dir'], settings['thumb_prefix'] + name + settings['thumb_suffix'] + ext)
[ "Return", "the", "path", "to", "the", "thumb", "." ]
saimn/sigal
python
https://github.com/saimn/sigal/blob/912ca39991355d358dc85fd55c7aeabdd7acc386/sigal/settings.py#L94-L115
[ "def", "get_thumb", "(", "settings", ",", "filename", ")", ":", "path", ",", "filen", "=", "os", ".", "path", ".", "split", "(", "filename", ")", "name", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "filen", ")", "if", "ext", ".", "lower", "(", ")", "in", "settings", "[", "'video_extensions'", "]", ":", "ext", "=", "'.jpg'", "return", "join", "(", "path", ",", "settings", "[", "'thumb_dir'", "]", ",", "settings", "[", "'thumb_prefix'", "]", "+", "name", "+", "settings", "[", "'thumb_suffix'", "]", "+", "ext", ")" ]
912ca39991355d358dc85fd55c7aeabdd7acc386
valid
read_settings
Read settings from a config file in the source_dir root.
sigal/settings.py
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.path.dirname(filename) tempdict = {} with open(filename) as f: code = compile(f.read(), filename, 'exec') exec(code, tempdict) settings.update((k, v) for k, v in tempdict.items() if k not in ['__builtins__']) # Make the paths relative to the settings file paths = ['source', 'destination', 'watermark'] if os.path.isdir(join(settings_path, settings['theme'])) and \ os.path.isdir(join(settings_path, settings['theme'], 'templates')): paths.append('theme') for p in paths: path = settings[p] if path and not isabs(path): settings[p] = abspath(normpath(join(settings_path, path))) logger.debug("Rewrite %s : %s -> %s", p, path, settings[p]) for key in ('img_size', 'thumb_size', 'video_size'): w, h = settings[key] if h > w: settings[key] = (h, w) logger.warning("The %s setting should be specified with the " "largest value first.", key) if not settings['img_processor']: logger.info('No Processor, images will not be resized') logger.debug('Settings:\n%s', pformat(settings, width=120)) return settings
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.path.dirname(filename) tempdict = {} with open(filename) as f: code = compile(f.read(), filename, 'exec') exec(code, tempdict) settings.update((k, v) for k, v in tempdict.items() if k not in ['__builtins__']) # Make the paths relative to the settings file paths = ['source', 'destination', 'watermark'] if os.path.isdir(join(settings_path, settings['theme'])) and \ os.path.isdir(join(settings_path, settings['theme'], 'templates')): paths.append('theme') for p in paths: path = settings[p] if path and not isabs(path): settings[p] = abspath(normpath(join(settings_path, path))) logger.debug("Rewrite %s : %s -> %s", p, path, settings[p]) for key in ('img_size', 'thumb_size', 'video_size'): w, h = settings[key] if h > w: settings[key] = (h, w) logger.warning("The %s setting should be specified with the " "largest value first.", key) if not settings['img_processor']: logger.info('No Processor, images will not be resized') logger.debug('Settings:\n%s', pformat(settings, width=120)) return settings
[ "Read", "settings", "from", "a", "config", "file", "in", "the", "source_dir", "root", "." ]
saimn/sigal
python
https://github.com/saimn/sigal/blob/912ca39991355d358dc85fd55c7aeabdd7acc386/sigal/settings.py#L118-L162
[ "def", "read_settings", "(", "filename", "=", "None", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "logger", ".", "info", "(", "\"Reading settings ...\"", ")", "settings", "=", "_DEFAULT_CONFIG", ".", "copy", "(", ")", "if", "filename", ":", "logger", ".", "debug", "(", "\"Settings file: %s\"", ",", "filename", ")", "settings_path", "=", "os", ".", "path", ".", "dirname", "(", "filename", ")", "tempdict", "=", "{", "}", "with", "open", "(", "filename", ")", "as", "f", ":", "code", "=", "compile", "(", "f", ".", "read", "(", ")", ",", "filename", ",", "'exec'", ")", "exec", "(", "code", ",", "tempdict", ")", "settings", ".", "update", "(", "(", "k", ",", "v", ")", "for", "k", ",", "v", "in", "tempdict", ".", "items", "(", ")", "if", "k", "not", "in", "[", "'__builtins__'", "]", ")", "# Make the paths relative to the settings file", "paths", "=", "[", "'source'", ",", "'destination'", ",", "'watermark'", "]", "if", "os", ".", "path", ".", "isdir", "(", "join", "(", "settings_path", ",", "settings", "[", "'theme'", "]", ")", ")", "and", "os", ".", "path", ".", "isdir", "(", "join", "(", "settings_path", ",", "settings", "[", "'theme'", "]", ",", "'templates'", ")", ")", ":", "paths", ".", "append", "(", "'theme'", ")", "for", "p", "in", "paths", ":", "path", "=", "settings", "[", "p", "]", "if", "path", "and", "not", "isabs", "(", "path", ")", ":", "settings", "[", "p", "]", "=", "abspath", "(", "normpath", "(", "join", "(", "settings_path", ",", "path", ")", ")", ")", "logger", ".", "debug", "(", "\"Rewrite %s : %s -> %s\"", ",", "p", ",", "path", ",", "settings", "[", "p", "]", ")", "for", "key", "in", "(", "'img_size'", ",", "'thumb_size'", ",", "'video_size'", ")", ":", "w", ",", "h", "=", "settings", "[", "key", "]", "if", "h", ">", "w", ":", "settings", "[", "key", "]", "=", "(", "h", ",", "w", ")", "logger", ".", "warning", "(", "\"The %s setting should be specified with the \"", "\"largest value first.\"", ",", "key", ")", "if", "not", "settings", "[", "'img_processor'", "]", ":", "logger", ".", "info", "(", "'No Processor, images will not be resized'", ")", "logger", ".", "debug", "(", "'Settings:\\n%s'", ",", "pformat", "(", "settings", ",", "width", "=", "120", ")", ")", "return", "settings" ]
912ca39991355d358dc85fd55c7aeabdd7acc386
valid
generate_media_pages
Generates and writes the media pages for all media in the gallery
sigal/plugins/media_page.py
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 = [None] + medias[:-1] # The media group allows us to easily get next and previous links media_groups = zip(medias, next_medias, previous_medias) for media_group in media_groups: writer.write(album, media_group)
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 = [None] + medias[:-1] # The media group allows us to easily get next and previous links media_groups = zip(medias, next_medias, previous_medias) for media_group in media_groups: writer.write(album, media_group)
[ "Generates", "and", "writes", "the", "media", "pages", "for", "all", "media", "in", "the", "gallery" ]
saimn/sigal
python
https://github.com/saimn/sigal/blob/912ca39991355d358dc85fd55c7aeabdd7acc386/sigal/plugins/media_page.py#L69-L83
[ "def", "generate_media_pages", "(", "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", "=", "[", "None", "]", "+", "medias", "[", ":", "-", "1", "]", "# The media group allows us to easily get next and previous links", "media_groups", "=", "zip", "(", "medias", ",", "next_medias", ",", "previous_medias", ")", "for", "media_group", "in", "media_groups", ":", "writer", ".", "write", "(", "album", ",", "media_group", ")" ]
912ca39991355d358dc85fd55c7aeabdd7acc386
valid
PageWriter.write
Generate the media page and save it
sigal/plugins/media_page.py
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], 'previous_media': media_group[-1], 'next_media': media_group[1], 'index_title': self.index_title, 'settings': self.settings, 'sigal_link': sigal_link, 'theme': {'name': os.path.basename(self.theme), 'url': url_from_path(os.path.relpath(self.theme_path, album.dst_path))}, }) output_file = "%s.html" % file_path with open(output_file, 'w', encoding='utf-8') as f: f.write(page)
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], 'previous_media': media_group[-1], 'next_media': media_group[1], 'index_title': self.index_title, 'settings': self.settings, 'sigal_link': sigal_link, 'theme': {'name': os.path.basename(self.theme), 'url': url_from_path(os.path.relpath(self.theme_path, album.dst_path))}, }) output_file = "%s.html" % file_path with open(output_file, 'w', encoding='utf-8') as f: f.write(page)
[ "Generate", "the", "media", "page", "and", "save", "it" ]
saimn/sigal
python
https://github.com/saimn/sigal/blob/912ca39991355d358dc85fd55c7aeabdd7acc386/sigal/plugins/media_page.py#L44-L66
[ "def", "write", "(", "self", ",", "album", ",", "media_group", ")", ":", "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", "]", ",", "'previous_media'", ":", "media_group", "[", "-", "1", "]", ",", "'next_media'", ":", "media_group", "[", "1", "]", ",", "'index_title'", ":", "self", ".", "index_title", ",", "'settings'", ":", "self", ".", "settings", ",", "'sigal_link'", ":", "sigal_link", ",", "'theme'", ":", "{", "'name'", ":", "os", ".", "path", ".", "basename", "(", "self", ".", "theme", ")", ",", "'url'", ":", "url_from_path", "(", "os", ".", "path", ".", "relpath", "(", "self", ".", "theme_path", ",", "album", ".", "dst_path", ")", ")", "}", ",", "}", ")", "output_file", "=", "\"%s.html\"", "%", "file_path", "with", "open", "(", "output_file", ",", "'w'", ",", "encoding", "=", "'utf-8'", ")", "as", "f", ":", "f", ".", "write", "(", "page", ")" ]
912ca39991355d358dc85fd55c7aeabdd7acc386
valid
check_install
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
djangocms_installer/install/__init__.py
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 tests try: from PIL import Image try: im = Image.open(os.path.join(os.path.dirname(__file__), '../share/test_image.png')) im.load() except IOError: # pragma: no cover errors.append( 'Pillow is not compiled with PNG support, see "Libraries installation issues" ' 'documentation section: https://djangocms-installer.readthedocs.io/en/latest/' 'libraries.html.' ) try: im = Image.open(os.path.join(os.path.dirname(__file__), '../share/test_image.jpg')) im.load() except IOError: # pragma: no cover errors.append( 'Pillow is not compiled with JPEG support, see "Libraries installation issues" ' 'documentation section: https://djangocms-installer.readthedocs.io/en/latest/' 'libraries.html' ) except ImportError: # pragma: no cover errors.append( 'Pillow is not installed check for installation errors and see "Libraries installation' ' issues" documentation section: https://djangocms-installer.readthedocs.io/en/latest/' 'libraries.html' ) # PostgreSQL test if config_data.db_driver == 'psycopg2' and not config_data.no_db_driver: # pragma: no cover try: import psycopg2 # NOQA except ImportError: errors.append( 'PostgreSQL driver is not installed, but you configured a PostgreSQL database, ' 'please check your installation and see "Libraries installation issues" ' 'documentation section: https://djangocms-installer.readthedocs.io/en/latest/' 'libraries.html' ) # MySQL test if config_data.db_driver == 'mysqlclient' and not config_data.no_db_driver: # pragma: no cover # NOQA try: import MySQLdb # NOQA except ImportError: errors.append( 'MySQL driver is not installed, but you configured a MySQL database, please check ' 'your installation and see "Libraries installation issues" documentation section: ' 'https://djangocms-installer.readthedocs.io/en/latest/libraries.html' ) if errors: # pragma: no cover raise EnvironmentError('\n'.join(errors))
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 tests try: from PIL import Image try: im = Image.open(os.path.join(os.path.dirname(__file__), '../share/test_image.png')) im.load() except IOError: # pragma: no cover errors.append( 'Pillow is not compiled with PNG support, see "Libraries installation issues" ' 'documentation section: https://djangocms-installer.readthedocs.io/en/latest/' 'libraries.html.' ) try: im = Image.open(os.path.join(os.path.dirname(__file__), '../share/test_image.jpg')) im.load() except IOError: # pragma: no cover errors.append( 'Pillow is not compiled with JPEG support, see "Libraries installation issues" ' 'documentation section: https://djangocms-installer.readthedocs.io/en/latest/' 'libraries.html' ) except ImportError: # pragma: no cover errors.append( 'Pillow is not installed check for installation errors and see "Libraries installation' ' issues" documentation section: https://djangocms-installer.readthedocs.io/en/latest/' 'libraries.html' ) # PostgreSQL test if config_data.db_driver == 'psycopg2' and not config_data.no_db_driver: # pragma: no cover try: import psycopg2 # NOQA except ImportError: errors.append( 'PostgreSQL driver is not installed, but you configured a PostgreSQL database, ' 'please check your installation and see "Libraries installation issues" ' 'documentation section: https://djangocms-installer.readthedocs.io/en/latest/' 'libraries.html' ) # MySQL test if config_data.db_driver == 'mysqlclient' and not config_data.no_db_driver: # pragma: no cover # NOQA try: import MySQLdb # NOQA except ImportError: errors.append( 'MySQL driver is not installed, but you configured a MySQL database, please check ' 'your installation and see "Libraries installation issues" documentation section: ' 'https://djangocms-installer.readthedocs.io/en/latest/libraries.html' ) if errors: # pragma: no cover raise EnvironmentError('\n'.join(errors))
[ "Here", "we", "do", "some", "**", "really", "**", "basic", "environment", "sanity", "checks", "." ]
nephila/djangocms-installer
python
https://github.com/nephila/djangocms-installer/blob/9fec66d5f8b1e9a0f3c0ec66dd777db578fab07e/djangocms_installer/install/__init__.py#L15-L79
[ "def", "check_install", "(", "config_data", ")", ":", "errors", "=", "[", "]", "# PIL tests", "try", ":", "from", "PIL", "import", "Image", "try", ":", "im", "=", "Image", ".", "open", "(", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "'../share/test_image.png'", ")", ")", "im", ".", "load", "(", ")", "except", "IOError", ":", "# pragma: no cover", "errors", ".", "append", "(", "'Pillow is not compiled with PNG support, see \"Libraries installation issues\" '", "'documentation section: https://djangocms-installer.readthedocs.io/en/latest/'", "'libraries.html.'", ")", "try", ":", "im", "=", "Image", ".", "open", "(", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "'../share/test_image.jpg'", ")", ")", "im", ".", "load", "(", ")", "except", "IOError", ":", "# pragma: no cover", "errors", ".", "append", "(", "'Pillow is not compiled with JPEG support, see \"Libraries installation issues\" '", "'documentation section: https://djangocms-installer.readthedocs.io/en/latest/'", "'libraries.html'", ")", "except", "ImportError", ":", "# pragma: no cover", "errors", ".", "append", "(", "'Pillow is not installed check for installation errors and see \"Libraries installation'", "' issues\" documentation section: https://djangocms-installer.readthedocs.io/en/latest/'", "'libraries.html'", ")", "# PostgreSQL test", "if", "config_data", ".", "db_driver", "==", "'psycopg2'", "and", "not", "config_data", ".", "no_db_driver", ":", "# pragma: no cover", "try", ":", "import", "psycopg2", "# NOQA", "except", "ImportError", ":", "errors", ".", "append", "(", "'PostgreSQL driver is not installed, but you configured a PostgreSQL database, '", "'please check your installation and see \"Libraries installation issues\" '", "'documentation section: https://djangocms-installer.readthedocs.io/en/latest/'", "'libraries.html'", ")", "# MySQL test", "if", "config_data", ".", "db_driver", "==", "'mysqlclient'", "and", "not", "config_data", ".", "no_db_driver", ":", "# pragma: no cover # NOQA", "try", ":", "import", "MySQLdb", "# NOQA", "except", "ImportError", ":", "errors", ".", "append", "(", "'MySQL driver is not installed, but you configured a MySQL database, please check '", "'your installation and see \"Libraries installation issues\" documentation section: '", "'https://djangocms-installer.readthedocs.io/en/latest/libraries.html'", ")", "if", "errors", ":", "# pragma: no cover", "raise", "EnvironmentError", "(", "'\\n'", ".", "join", "(", "errors", ")", ")" ]
9fec66d5f8b1e9a0f3c0ec66dd777db578fab07e
valid
cleanup_directory
Asks user for removal of project directory and eventually removes it
djangocms_installer/install/__init__.py
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( 'The installation failed.\n' 'Do you want to clean up by removing {0}?\n' '\tWarning: this will delete all files in:\n' '\t\t{0}\n' 'Do you want to cleanup?'.format( os.path.abspath(config_data.project_directory) ), 'no' ) else: sys.stdout.write('The installation has failed.\n') if config_data.skip_project_dir_check is False and (choice or (config_data.noinput and config_data.delete_project_dir)): sys.stdout.write('Removing everything under {0}\n'.format( os.path.abspath(config_data.project_directory) )) shutil.rmtree(config_data.project_directory, True)
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( 'The installation failed.\n' 'Do you want to clean up by removing {0}?\n' '\tWarning: this will delete all files in:\n' '\t\t{0}\n' 'Do you want to cleanup?'.format( os.path.abspath(config_data.project_directory) ), 'no' ) else: sys.stdout.write('The installation has failed.\n') if config_data.skip_project_dir_check is False and (choice or (config_data.noinput and config_data.delete_project_dir)): sys.stdout.write('Removing everything under {0}\n'.format( os.path.abspath(config_data.project_directory) )) shutil.rmtree(config_data.project_directory, True)
[ "Asks", "user", "for", "removal", "of", "project", "directory", "and", "eventually", "removes", "it" ]
nephila/djangocms-installer
python
https://github.com/nephila/djangocms-installer/blob/9fec66d5f8b1e9a0f3c0ec66dd777db578fab07e/djangocms_installer/install/__init__.py#L121-L146
[ "def", "cleanup_directory", "(", "config_data", ")", ":", "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", "(", "'The installation failed.\\n'", "'Do you want to clean up by removing {0}?\\n'", "'\\tWarning: this will delete all files in:\\n'", "'\\t\\t{0}\\n'", "'Do you want to cleanup?'", ".", "format", "(", "os", ".", "path", ".", "abspath", "(", "config_data", ".", "project_directory", ")", ")", ",", "'no'", ")", "else", ":", "sys", ".", "stdout", ".", "write", "(", "'The installation has failed.\\n'", ")", "if", "config_data", ".", "skip_project_dir_check", "is", "False", "and", "(", "choice", "or", "(", "config_data", ".", "noinput", "and", "config_data", ".", "delete_project_dir", ")", ")", ":", "sys", ".", "stdout", ".", "write", "(", "'Removing everything under {0}\\n'", ".", "format", "(", "os", ".", "path", ".", "abspath", "(", "config_data", ".", "project_directory", ")", ")", ")", "shutil", ".", "rmtree", "(", "config_data", ".", "project_directory", ",", "True", ")" ]
9fec66d5f8b1e9a0f3c0ec66dd777db578fab07e
valid
validate_project
Check the defined project name against keywords, builtins and existing modules to avoid name clashing
djangocms_installer/config/internal.py
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__): return None try: __import__(project_name) return None except ImportError: return project_name
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__): return None try: __import__(project_name) return None except ImportError: return project_name
[ "Check", "the", "defined", "project", "name", "against", "keywords", "builtins", "and", "existing", "modules", "to", "avoid", "name", "clashing" ]
nephila/djangocms-installer
python
https://github.com/nephila/djangocms-installer/blob/9fec66d5f8b1e9a0f3c0ec66dd777db578fab07e/djangocms_installer/config/internal.py#L28-L43
[ "def", "validate_project", "(", "project_name", ")", ":", "if", "'-'", "in", "project_name", ":", "return", "None", "if", "keyword", ".", "iskeyword", "(", "project_name", ")", ":", "return", "None", "if", "project_name", "in", "dir", "(", "__builtins__", ")", ":", "return", "None", "try", ":", "__import__", "(", "project_name", ")", "return", "None", "except", "ImportError", ":", "return", "project_name" ]
9fec66d5f8b1e9a0f3c0ec66dd777db578fab07e
valid
parse
Define the available arguments
djangocms_installer/config/__init__.py
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 == 'local': timezone = 'UTC' parser = argparse.ArgumentParser(description="""Bootstrap a django CMS project. Major usage modes: - wizard: djangocms -w -p /path/whatever project_name: ask for all the options through a CLI wizard. - batch: djangocms project_name: runs with the default values plus any additional option provided (see below) with no question asked. - config file: djangocms_installer --config-file /path/to/config.ini project_name: reads values from an ini-style config file. Check https://djangocms-installer.readthedocs.io/en/latest/usage.html for detailed usage information. """, formatter_class=argparse.RawTextHelpFormatter) parser.add_argument('--config-file', dest='config_file', action='store', default=None, help='Configuration file for djangocms_installer') parser.add_argument('--config-dump', dest='config_dump', action='store', default=None, help='Dump configuration file with current args') parser.add_argument('--db', '-d', dest='db', action=DbAction, default='sqlite://localhost/project.db', help='Database configuration (in URL format). ' 'Example: sqlite://localhost/project.db') parser.add_argument('--i18n', '-i', dest='i18n', action='store', choices=('yes', 'no'), default='yes', help='Activate Django I18N / L10N setting; this is ' 'automatically activated if more than ' 'language is provided') parser.add_argument('--use-tz', '-z', dest='use_timezone', action='store', choices=('yes', 'no'), default='yes', help='Activate Django timezone support') parser.add_argument('--timezone', '-t', dest='timezone', required=False, default=timezone, action='store', help='Optional default time zone. Example: Europe/Rome') parser.add_argument('--reversion', '-e', dest='reversion', action='store', choices=('yes', 'no'), default='yes', help='Install and configure reversion support ' '(only for django CMS 3.2 and 3.3)') parser.add_argument('--permissions', dest='permissions', action='store', choices=('yes', 'no'), default='no', help='Activate CMS permission management') parser.add_argument('--pip-options', help='pass custom pip options', default='') parser.add_argument('--languages', '-l', dest='languages', action='append', help='Languages to enable. Option can be provided multiple times, or as a ' 'comma separated list. Only language codes supported by Django can ' 'be used here. Example: en, fr-FR, it-IT') parser.add_argument('--django-version', dest='django_version', action='store', choices=data.DJANGO_SUPPORTED, default=data.DJANGO_DEFAULT, help='Django version') parser.add_argument('--cms-version', '-v', dest='cms_version', action='store', choices=data.DJANGOCMS_SUPPORTED, default=data.DJANGOCMS_DEFAULT, help='django CMS version') parser.add_argument('--parent-dir', '-p', dest='project_directory', default='', action='store', help='Optional project parent directory') parser.add_argument('--bootstrap', dest='bootstrap', action='store', choices=('yes', 'no'), default='no', help='Use Twitter Bootstrap Theme') parser.add_argument('--templates', dest='templates', action='store', default='no', help='Use custom template set') parser.add_argument('--starting-page', dest='starting_page', action='store', choices=('yes', 'no'), default='no', help='Load a starting page with examples after installation ' '(english language only). Choose "no" if you use a ' 'custom template set.') parser.add_argument(dest='project_name', action='store', help='Name of the project to be created') # Command that lists the supported plugins in verbose description parser.add_argument('--list-plugins', '-P', dest='plugins', action='store_true', help='List plugins that\'s going to be installed and configured') # Command that lists the supported plugins in verbose description parser.add_argument('--dump-requirements', '-R', dest='dump_reqs', action='store_true', help='It dumps the requirements that would be installed according to ' 'parameters given. Together with --requirements argument is useful ' 'for customizing the virtualenv') # Advanced options. These have a predefined default and are not asked # by config wizard. parser.add_argument('--no-input', '-q', dest='noinput', action='store_true', default=True, help='Don\'t run the configuration wizard, just use the ' 'provided values') parser.add_argument('--wizard', '-w', dest='wizard', action='store_true', default=False, help='Run the configuration wizard') parser.add_argument('--verbose', dest='verbose', action='store_true', default=False, help='Be more verbose and don\'t swallow subcommands output') parser.add_argument('--filer', '-f', dest='filer', action='store_true', default=True, help='Install and configure django-filer plugins ' '- Always enabled') parser.add_argument('--requirements', '-r', dest='requirements_file', action='store', default=None, help='Externally defined requirements file') parser.add_argument('--no-deps', '-n', dest='no_deps', action='store_true', default=False, help='Don\'t install package dependencies') parser.add_argument('--no-plugins', dest='no_plugins', action='store_true', default=False, help='Don\'t install plugins') parser.add_argument('--no-db-driver', dest='no_db_driver', action='store_true', default=False, help='Don\'t install database package') parser.add_argument('--no-sync', '-m', dest='no_sync', action='store_true', default=False, help='Don\'t run syncdb / migrate after bootstrapping') parser.add_argument('--no-user', '-u', dest='no_user', action='store_true', default=False, help='Don\'t create the admin user') parser.add_argument('--template', dest='template', action='store', default=None, help='The path or URL to load the django project ' 'template from.') parser.add_argument('--extra-settings', dest='extra_settings', action='store', default=None, help='The path to an file that contains extra settings.') parser.add_argument('--skip-empty-check', '-s', dest='skip_project_dir_check', action='store_true', default=False, help='Skip the check if project dir is empty.') parser.add_argument('--delete-project-dir', '-c', dest='delete_project_dir', action='store_true', default=False, help='Delete project directory on creation failure.') parser.add_argument('--utc', dest='utc', action='store_true', default=False, help='Use UTC timezone.') if '--utc' in args: for action in parser._positionals._actions: if action.dest == 'timezone': action.default = 'UTC' # If config_args then pretend that config args came from the stdin and run parser again. config_args = ini.parse_config_file(parser, args) args = parser.parse_args(config_args + args) if not args.wizard: args.noinput = True else: args.noinput = False if not args.project_directory: args.project_directory = args.project_name args.project_directory = os.path.abspath(args.project_directory) # First of all, check if the project name is valid if not validate_project(args.project_name): sys.stderr.write( 'Project name "{0}" is not a valid app name, or it\'s already defined. ' 'Please use only numbers, letters and underscores.\n'.format(args.project_name) ) sys.exit(3) # Checking the given path setattr(args, 'project_path', os.path.join(args.project_directory, args.project_name).strip()) if not args.skip_project_dir_check: if (os.path.exists(args.project_directory) and [path for path in os.listdir(args.project_directory) if not path.startswith('.')]): sys.stderr.write( 'Path "{0}" already exists and is not empty, please choose a different one\n' 'If you want to use this path anyway use the -s flag to skip this check.\n' ''.format(args.project_directory) ) sys.exit(4) if os.path.exists(args.project_path): sys.stderr.write( 'Path "{0}" already exists, please choose a different one\n'.format(args.project_path) ) sys.exit(4) if args.config_dump and os.path.isfile(args.config_dump): sys.stdout.write( 'Cannot dump because given configuration file "{0}" exists.\n'.format(args.config_dump) ) sys.exit(8) args = _manage_args(parser, args) # what do we want here?! # * if languages are given as multiple arguments, let's use it as is # * if no languages are given, use a default and stop handling it further # * if languages are given as a comma-separated list, split it and use the # resulting list. if not args.languages: try: args.languages = [locale.getdefaultlocale()[0].split('_')[0]] except Exception: # pragma: no cover args.languages = ['en'] elif isinstance(args.languages, six.string_types): args.languages = args.languages.split(',') elif len(args.languages) == 1 and isinstance(args.languages[0], six.string_types): args.languages = args.languages[0].split(',') args.languages = [lang.strip().lower() for lang in args.languages] if len(args.languages) > 1: args.i18n = 'yes' args.aldryn = False args.filer = True # Convert version to numeric format for easier checking try: django_version, cms_version = supported_versions(args.django_version, args.cms_version) cms_package = data.PACKAGE_MATRIX.get( cms_version, data.PACKAGE_MATRIX[data.DJANGOCMS_LTS] ) except RuntimeError as e: # pragma: no cover sys.stderr.write(compat.unicode(e)) sys.exit(6) if django_version is None: # pragma: no cover sys.stderr.write( 'Please provide a Django supported version: {0}. Only Major.Minor ' 'version selector is accepted\n'.format(', '.join(data.DJANGO_SUPPORTED)) ) sys.exit(6) if cms_version is None: # pragma: no cover sys.stderr.write( 'Please provide a django CMS supported version: {0}. Only Major.Minor ' 'version selector is accepted\n'.format(', '.join(data.DJANGOCMS_SUPPORTED)) ) sys.exit(6) default_settings = '{}.settings'.format(args.project_name) env_settings = os.environ.get('DJANGO_SETTINGS_MODULE', default_settings) if env_settings != default_settings: sys.stderr.write( '`DJANGO_SETTINGS_MODULE` is currently set to \'{0}\' which is not compatible with ' 'djangocms installer.\nPlease unset `DJANGO_SETTINGS_MODULE` and re-run the installer ' '\n'.format(env_settings) ) sys.exit(10) if not getattr(args, 'requirements_file'): requirements = [] # django CMS version check if args.cms_version == 'develop': requirements.append(cms_package) warnings.warn(data.VERSION_WARNING.format('develop', 'django CMS')) elif args.cms_version == 'rc': # pragma: no cover requirements.append(cms_package) elif args.cms_version == 'beta': # pragma: no cover requirements.append(cms_package) warnings.warn(data.VERSION_WARNING.format('beta', 'django CMS')) else: requirements.append(cms_package) if args.cms_version in ('rc', 'develop'): requirements.extend(data.REQUIREMENTS['cms-master']) elif LooseVersion(cms_version) >= LooseVersion('3.6'): requirements.extend(data.REQUIREMENTS['cms-3.6']) elif LooseVersion(cms_version) >= LooseVersion('3.5'): requirements.extend(data.REQUIREMENTS['cms-3.5']) elif LooseVersion(cms_version) >= LooseVersion('3.4'): requirements.extend(data.REQUIREMENTS['cms-3.4']) if not args.no_db_driver: requirements.append(args.db_driver) if not args.no_plugins: if args.cms_version in ('rc', 'develop'): requirements.extend(data.REQUIREMENTS['plugins-master']) elif LooseVersion(cms_version) >= LooseVersion('3.6'): requirements.extend(data.REQUIREMENTS['plugins-3.6']) elif LooseVersion(cms_version) >= LooseVersion('3.5'): requirements.extend(data.REQUIREMENTS['plugins-3.5']) elif LooseVersion(cms_version) >= LooseVersion('3.4'): requirements.extend(data.REQUIREMENTS['plugins-3.4']) requirements.extend(data.REQUIREMENTS['filer']) if args.aldryn: # pragma: no cover requirements.extend(data.REQUIREMENTS['aldryn']) # Django version check if args.django_version == 'develop': # pragma: no cover requirements.append(data.DJANGO_DEVELOP) warnings.warn(data.VERSION_WARNING.format('develop', 'Django')) elif args.django_version == 'beta': # pragma: no cover requirements.append(data.DJANGO_BETA) warnings.warn(data.VERSION_WARNING.format('beta', 'Django')) else: requirements.append('Django<{0}'.format(less_than_version(django_version))) if django_version == '1.8': requirements.extend(data.REQUIREMENTS['django-1.8']) elif django_version == '1.9': requirements.extend(data.REQUIREMENTS['django-1.9']) elif django_version == '1.10': requirements.extend(data.REQUIREMENTS['django-1.10']) elif django_version == '1.11': requirements.extend(data.REQUIREMENTS['django-1.11']) elif django_version == '2.0': requirements.extend(data.REQUIREMENTS['django-2.0']) elif django_version == '2.1': requirements.extend(data.REQUIREMENTS['django-2.1']) requirements.extend(data.REQUIREMENTS['default']) setattr(args, 'requirements', '\n'.join(requirements).strip()) # Convenient shortcuts setattr(args, 'cms_version', cms_version) setattr(args, 'django_version', django_version) setattr(args, 'settings_path', os.path.join(args.project_directory, args.project_name, 'settings.py').strip()) setattr(args, 'urlconf_path', os.path.join(args.project_directory, args.project_name, 'urls.py').strip()) if args.config_dump: ini.dump_config_file(args.config_dump, args, parser) return args
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 == 'local': timezone = 'UTC' parser = argparse.ArgumentParser(description="""Bootstrap a django CMS project. Major usage modes: - wizard: djangocms -w -p /path/whatever project_name: ask for all the options through a CLI wizard. - batch: djangocms project_name: runs with the default values plus any additional option provided (see below) with no question asked. - config file: djangocms_installer --config-file /path/to/config.ini project_name: reads values from an ini-style config file. Check https://djangocms-installer.readthedocs.io/en/latest/usage.html for detailed usage information. """, formatter_class=argparse.RawTextHelpFormatter) parser.add_argument('--config-file', dest='config_file', action='store', default=None, help='Configuration file for djangocms_installer') parser.add_argument('--config-dump', dest='config_dump', action='store', default=None, help='Dump configuration file with current args') parser.add_argument('--db', '-d', dest='db', action=DbAction, default='sqlite://localhost/project.db', help='Database configuration (in URL format). ' 'Example: sqlite://localhost/project.db') parser.add_argument('--i18n', '-i', dest='i18n', action='store', choices=('yes', 'no'), default='yes', help='Activate Django I18N / L10N setting; this is ' 'automatically activated if more than ' 'language is provided') parser.add_argument('--use-tz', '-z', dest='use_timezone', action='store', choices=('yes', 'no'), default='yes', help='Activate Django timezone support') parser.add_argument('--timezone', '-t', dest='timezone', required=False, default=timezone, action='store', help='Optional default time zone. Example: Europe/Rome') parser.add_argument('--reversion', '-e', dest='reversion', action='store', choices=('yes', 'no'), default='yes', help='Install and configure reversion support ' '(only for django CMS 3.2 and 3.3)') parser.add_argument('--permissions', dest='permissions', action='store', choices=('yes', 'no'), default='no', help='Activate CMS permission management') parser.add_argument('--pip-options', help='pass custom pip options', default='') parser.add_argument('--languages', '-l', dest='languages', action='append', help='Languages to enable. Option can be provided multiple times, or as a ' 'comma separated list. Only language codes supported by Django can ' 'be used here. Example: en, fr-FR, it-IT') parser.add_argument('--django-version', dest='django_version', action='store', choices=data.DJANGO_SUPPORTED, default=data.DJANGO_DEFAULT, help='Django version') parser.add_argument('--cms-version', '-v', dest='cms_version', action='store', choices=data.DJANGOCMS_SUPPORTED, default=data.DJANGOCMS_DEFAULT, help='django CMS version') parser.add_argument('--parent-dir', '-p', dest='project_directory', default='', action='store', help='Optional project parent directory') parser.add_argument('--bootstrap', dest='bootstrap', action='store', choices=('yes', 'no'), default='no', help='Use Twitter Bootstrap Theme') parser.add_argument('--templates', dest='templates', action='store', default='no', help='Use custom template set') parser.add_argument('--starting-page', dest='starting_page', action='store', choices=('yes', 'no'), default='no', help='Load a starting page with examples after installation ' '(english language only). Choose "no" if you use a ' 'custom template set.') parser.add_argument(dest='project_name', action='store', help='Name of the project to be created') # Command that lists the supported plugins in verbose description parser.add_argument('--list-plugins', '-P', dest='plugins', action='store_true', help='List plugins that\'s going to be installed and configured') # Command that lists the supported plugins in verbose description parser.add_argument('--dump-requirements', '-R', dest='dump_reqs', action='store_true', help='It dumps the requirements that would be installed according to ' 'parameters given. Together with --requirements argument is useful ' 'for customizing the virtualenv') # Advanced options. These have a predefined default and are not asked # by config wizard. parser.add_argument('--no-input', '-q', dest='noinput', action='store_true', default=True, help='Don\'t run the configuration wizard, just use the ' 'provided values') parser.add_argument('--wizard', '-w', dest='wizard', action='store_true', default=False, help='Run the configuration wizard') parser.add_argument('--verbose', dest='verbose', action='store_true', default=False, help='Be more verbose and don\'t swallow subcommands output') parser.add_argument('--filer', '-f', dest='filer', action='store_true', default=True, help='Install and configure django-filer plugins ' '- Always enabled') parser.add_argument('--requirements', '-r', dest='requirements_file', action='store', default=None, help='Externally defined requirements file') parser.add_argument('--no-deps', '-n', dest='no_deps', action='store_true', default=False, help='Don\'t install package dependencies') parser.add_argument('--no-plugins', dest='no_plugins', action='store_true', default=False, help='Don\'t install plugins') parser.add_argument('--no-db-driver', dest='no_db_driver', action='store_true', default=False, help='Don\'t install database package') parser.add_argument('--no-sync', '-m', dest='no_sync', action='store_true', default=False, help='Don\'t run syncdb / migrate after bootstrapping') parser.add_argument('--no-user', '-u', dest='no_user', action='store_true', default=False, help='Don\'t create the admin user') parser.add_argument('--template', dest='template', action='store', default=None, help='The path or URL to load the django project ' 'template from.') parser.add_argument('--extra-settings', dest='extra_settings', action='store', default=None, help='The path to an file that contains extra settings.') parser.add_argument('--skip-empty-check', '-s', dest='skip_project_dir_check', action='store_true', default=False, help='Skip the check if project dir is empty.') parser.add_argument('--delete-project-dir', '-c', dest='delete_project_dir', action='store_true', default=False, help='Delete project directory on creation failure.') parser.add_argument('--utc', dest='utc', action='store_true', default=False, help='Use UTC timezone.') if '--utc' in args: for action in parser._positionals._actions: if action.dest == 'timezone': action.default = 'UTC' # If config_args then pretend that config args came from the stdin and run parser again. config_args = ini.parse_config_file(parser, args) args = parser.parse_args(config_args + args) if not args.wizard: args.noinput = True else: args.noinput = False if not args.project_directory: args.project_directory = args.project_name args.project_directory = os.path.abspath(args.project_directory) # First of all, check if the project name is valid if not validate_project(args.project_name): sys.stderr.write( 'Project name "{0}" is not a valid app name, or it\'s already defined. ' 'Please use only numbers, letters and underscores.\n'.format(args.project_name) ) sys.exit(3) # Checking the given path setattr(args, 'project_path', os.path.join(args.project_directory, args.project_name).strip()) if not args.skip_project_dir_check: if (os.path.exists(args.project_directory) and [path for path in os.listdir(args.project_directory) if not path.startswith('.')]): sys.stderr.write( 'Path "{0}" already exists and is not empty, please choose a different one\n' 'If you want to use this path anyway use the -s flag to skip this check.\n' ''.format(args.project_directory) ) sys.exit(4) if os.path.exists(args.project_path): sys.stderr.write( 'Path "{0}" already exists, please choose a different one\n'.format(args.project_path) ) sys.exit(4) if args.config_dump and os.path.isfile(args.config_dump): sys.stdout.write( 'Cannot dump because given configuration file "{0}" exists.\n'.format(args.config_dump) ) sys.exit(8) args = _manage_args(parser, args) # what do we want here?! # * if languages are given as multiple arguments, let's use it as is # * if no languages are given, use a default and stop handling it further # * if languages are given as a comma-separated list, split it and use the # resulting list. if not args.languages: try: args.languages = [locale.getdefaultlocale()[0].split('_')[0]] except Exception: # pragma: no cover args.languages = ['en'] elif isinstance(args.languages, six.string_types): args.languages = args.languages.split(',') elif len(args.languages) == 1 and isinstance(args.languages[0], six.string_types): args.languages = args.languages[0].split(',') args.languages = [lang.strip().lower() for lang in args.languages] if len(args.languages) > 1: args.i18n = 'yes' args.aldryn = False args.filer = True # Convert version to numeric format for easier checking try: django_version, cms_version = supported_versions(args.django_version, args.cms_version) cms_package = data.PACKAGE_MATRIX.get( cms_version, data.PACKAGE_MATRIX[data.DJANGOCMS_LTS] ) except RuntimeError as e: # pragma: no cover sys.stderr.write(compat.unicode(e)) sys.exit(6) if django_version is None: # pragma: no cover sys.stderr.write( 'Please provide a Django supported version: {0}. Only Major.Minor ' 'version selector is accepted\n'.format(', '.join(data.DJANGO_SUPPORTED)) ) sys.exit(6) if cms_version is None: # pragma: no cover sys.stderr.write( 'Please provide a django CMS supported version: {0}. Only Major.Minor ' 'version selector is accepted\n'.format(', '.join(data.DJANGOCMS_SUPPORTED)) ) sys.exit(6) default_settings = '{}.settings'.format(args.project_name) env_settings = os.environ.get('DJANGO_SETTINGS_MODULE', default_settings) if env_settings != default_settings: sys.stderr.write( '`DJANGO_SETTINGS_MODULE` is currently set to \'{0}\' which is not compatible with ' 'djangocms installer.\nPlease unset `DJANGO_SETTINGS_MODULE` and re-run the installer ' '\n'.format(env_settings) ) sys.exit(10) if not getattr(args, 'requirements_file'): requirements = [] # django CMS version check if args.cms_version == 'develop': requirements.append(cms_package) warnings.warn(data.VERSION_WARNING.format('develop', 'django CMS')) elif args.cms_version == 'rc': # pragma: no cover requirements.append(cms_package) elif args.cms_version == 'beta': # pragma: no cover requirements.append(cms_package) warnings.warn(data.VERSION_WARNING.format('beta', 'django CMS')) else: requirements.append(cms_package) if args.cms_version in ('rc', 'develop'): requirements.extend(data.REQUIREMENTS['cms-master']) elif LooseVersion(cms_version) >= LooseVersion('3.6'): requirements.extend(data.REQUIREMENTS['cms-3.6']) elif LooseVersion(cms_version) >= LooseVersion('3.5'): requirements.extend(data.REQUIREMENTS['cms-3.5']) elif LooseVersion(cms_version) >= LooseVersion('3.4'): requirements.extend(data.REQUIREMENTS['cms-3.4']) if not args.no_db_driver: requirements.append(args.db_driver) if not args.no_plugins: if args.cms_version in ('rc', 'develop'): requirements.extend(data.REQUIREMENTS['plugins-master']) elif LooseVersion(cms_version) >= LooseVersion('3.6'): requirements.extend(data.REQUIREMENTS['plugins-3.6']) elif LooseVersion(cms_version) >= LooseVersion('3.5'): requirements.extend(data.REQUIREMENTS['plugins-3.5']) elif LooseVersion(cms_version) >= LooseVersion('3.4'): requirements.extend(data.REQUIREMENTS['plugins-3.4']) requirements.extend(data.REQUIREMENTS['filer']) if args.aldryn: # pragma: no cover requirements.extend(data.REQUIREMENTS['aldryn']) # Django version check if args.django_version == 'develop': # pragma: no cover requirements.append(data.DJANGO_DEVELOP) warnings.warn(data.VERSION_WARNING.format('develop', 'Django')) elif args.django_version == 'beta': # pragma: no cover requirements.append(data.DJANGO_BETA) warnings.warn(data.VERSION_WARNING.format('beta', 'Django')) else: requirements.append('Django<{0}'.format(less_than_version(django_version))) if django_version == '1.8': requirements.extend(data.REQUIREMENTS['django-1.8']) elif django_version == '1.9': requirements.extend(data.REQUIREMENTS['django-1.9']) elif django_version == '1.10': requirements.extend(data.REQUIREMENTS['django-1.10']) elif django_version == '1.11': requirements.extend(data.REQUIREMENTS['django-1.11']) elif django_version == '2.0': requirements.extend(data.REQUIREMENTS['django-2.0']) elif django_version == '2.1': requirements.extend(data.REQUIREMENTS['django-2.1']) requirements.extend(data.REQUIREMENTS['default']) setattr(args, 'requirements', '\n'.join(requirements).strip()) # Convenient shortcuts setattr(args, 'cms_version', cms_version) setattr(args, 'django_version', django_version) setattr(args, 'settings_path', os.path.join(args.project_directory, args.project_name, 'settings.py').strip()) setattr(args, 'urlconf_path', os.path.join(args.project_directory, args.project_name, 'urls.py').strip()) if args.config_dump: ini.dump_config_file(args.config_dump, args, parser) return args
[ "Define", "the", "available", "arguments" ]
nephila/djangocms-installer
python
https://github.com/nephila/djangocms-installer/blob/9fec66d5f8b1e9a0f3c0ec66dd777db578fab07e/djangocms_installer/config/__init__.py#L20-L337
[ "def", "parse", "(", "args", ")", ":", "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", "==", "'local'", ":", "timezone", "=", "'UTC'", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "\"\"\"Bootstrap a django CMS project.\nMajor usage modes:\n\n- wizard: djangocms -w -p /path/whatever project_name: ask for all the options through a\n CLI wizard.\n\n- batch: djangocms project_name: runs with the default values plus any\n additional option provided (see below) with no question asked.\n\n- config file: djangocms_installer --config-file /path/to/config.ini project_name: reads values\n from an ini-style config file.\n\nCheck https://djangocms-installer.readthedocs.io/en/latest/usage.html for detailed usage\ninformation.\n\"\"\"", ",", "formatter_class", "=", "argparse", ".", "RawTextHelpFormatter", ")", "parser", ".", "add_argument", "(", "'--config-file'", ",", "dest", "=", "'config_file'", ",", "action", "=", "'store'", ",", "default", "=", "None", ",", "help", "=", "'Configuration file for djangocms_installer'", ")", "parser", ".", "add_argument", "(", "'--config-dump'", ",", "dest", "=", "'config_dump'", ",", "action", "=", "'store'", ",", "default", "=", "None", ",", "help", "=", "'Dump configuration file with current args'", ")", "parser", ".", "add_argument", "(", "'--db'", ",", "'-d'", ",", "dest", "=", "'db'", ",", "action", "=", "DbAction", ",", "default", "=", "'sqlite://localhost/project.db'", ",", "help", "=", "'Database configuration (in URL format). '", "'Example: sqlite://localhost/project.db'", ")", "parser", ".", "add_argument", "(", "'--i18n'", ",", "'-i'", ",", "dest", "=", "'i18n'", ",", "action", "=", "'store'", ",", "choices", "=", "(", "'yes'", ",", "'no'", ")", ",", "default", "=", "'yes'", ",", "help", "=", "'Activate Django I18N / L10N setting; this is '", "'automatically activated if more than '", "'language is provided'", ")", "parser", ".", "add_argument", "(", "'--use-tz'", ",", "'-z'", ",", "dest", "=", "'use_timezone'", ",", "action", "=", "'store'", ",", "choices", "=", "(", "'yes'", ",", "'no'", ")", ",", "default", "=", "'yes'", ",", "help", "=", "'Activate Django timezone support'", ")", "parser", ".", "add_argument", "(", "'--timezone'", ",", "'-t'", ",", "dest", "=", "'timezone'", ",", "required", "=", "False", ",", "default", "=", "timezone", ",", "action", "=", "'store'", ",", "help", "=", "'Optional default time zone. Example: Europe/Rome'", ")", "parser", ".", "add_argument", "(", "'--reversion'", ",", "'-e'", ",", "dest", "=", "'reversion'", ",", "action", "=", "'store'", ",", "choices", "=", "(", "'yes'", ",", "'no'", ")", ",", "default", "=", "'yes'", ",", "help", "=", "'Install and configure reversion support '", "'(only for django CMS 3.2 and 3.3)'", ")", "parser", ".", "add_argument", "(", "'--permissions'", ",", "dest", "=", "'permissions'", ",", "action", "=", "'store'", ",", "choices", "=", "(", "'yes'", ",", "'no'", ")", ",", "default", "=", "'no'", ",", "help", "=", "'Activate CMS permission management'", ")", "parser", ".", "add_argument", "(", "'--pip-options'", ",", "help", "=", "'pass custom pip options'", ",", "default", "=", "''", ")", "parser", ".", "add_argument", "(", "'--languages'", ",", "'-l'", ",", "dest", "=", "'languages'", ",", "action", "=", "'append'", ",", "help", "=", "'Languages to enable. Option can be provided multiple times, or as a '", "'comma separated list. Only language codes supported by Django can '", "'be used here. Example: en, fr-FR, it-IT'", ")", "parser", ".", "add_argument", "(", "'--django-version'", ",", "dest", "=", "'django_version'", ",", "action", "=", "'store'", ",", "choices", "=", "data", ".", "DJANGO_SUPPORTED", ",", "default", "=", "data", ".", "DJANGO_DEFAULT", ",", "help", "=", "'Django version'", ")", "parser", ".", "add_argument", "(", "'--cms-version'", ",", "'-v'", ",", "dest", "=", "'cms_version'", ",", "action", "=", "'store'", ",", "choices", "=", "data", ".", "DJANGOCMS_SUPPORTED", ",", "default", "=", "data", ".", "DJANGOCMS_DEFAULT", ",", "help", "=", "'django CMS version'", ")", "parser", ".", "add_argument", "(", "'--parent-dir'", ",", "'-p'", ",", "dest", "=", "'project_directory'", ",", "default", "=", "''", ",", "action", "=", "'store'", ",", "help", "=", "'Optional project parent directory'", ")", "parser", ".", "add_argument", "(", "'--bootstrap'", ",", "dest", "=", "'bootstrap'", ",", "action", "=", "'store'", ",", "choices", "=", "(", "'yes'", ",", "'no'", ")", ",", "default", "=", "'no'", ",", "help", "=", "'Use Twitter Bootstrap Theme'", ")", "parser", ".", "add_argument", "(", "'--templates'", ",", "dest", "=", "'templates'", ",", "action", "=", "'store'", ",", "default", "=", "'no'", ",", "help", "=", "'Use custom template set'", ")", "parser", ".", "add_argument", "(", "'--starting-page'", ",", "dest", "=", "'starting_page'", ",", "action", "=", "'store'", ",", "choices", "=", "(", "'yes'", ",", "'no'", ")", ",", "default", "=", "'no'", ",", "help", "=", "'Load a starting page with examples after installation '", "'(english language only). Choose \"no\" if you use a '", "'custom template set.'", ")", "parser", ".", "add_argument", "(", "dest", "=", "'project_name'", ",", "action", "=", "'store'", ",", "help", "=", "'Name of the project to be created'", ")", "# Command that lists the supported plugins in verbose description", "parser", ".", "add_argument", "(", "'--list-plugins'", ",", "'-P'", ",", "dest", "=", "'plugins'", ",", "action", "=", "'store_true'", ",", "help", "=", "'List plugins that\\'s going to be installed and configured'", ")", "# Command that lists the supported plugins in verbose description", "parser", ".", "add_argument", "(", "'--dump-requirements'", ",", "'-R'", ",", "dest", "=", "'dump_reqs'", ",", "action", "=", "'store_true'", ",", "help", "=", "'It dumps the requirements that would be installed according to '", "'parameters given. Together with --requirements argument is useful '", "'for customizing the virtualenv'", ")", "# Advanced options. These have a predefined default and are not asked", "# by config wizard.", "parser", ".", "add_argument", "(", "'--no-input'", ",", "'-q'", ",", "dest", "=", "'noinput'", ",", "action", "=", "'store_true'", ",", "default", "=", "True", ",", "help", "=", "'Don\\'t run the configuration wizard, just use the '", "'provided values'", ")", "parser", ".", "add_argument", "(", "'--wizard'", ",", "'-w'", ",", "dest", "=", "'wizard'", ",", "action", "=", "'store_true'", ",", "default", "=", "False", ",", "help", "=", "'Run the configuration wizard'", ")", "parser", ".", "add_argument", "(", "'--verbose'", ",", "dest", "=", "'verbose'", ",", "action", "=", "'store_true'", ",", "default", "=", "False", ",", "help", "=", "'Be more verbose and don\\'t swallow subcommands output'", ")", "parser", ".", "add_argument", "(", "'--filer'", ",", "'-f'", ",", "dest", "=", "'filer'", ",", "action", "=", "'store_true'", ",", "default", "=", "True", ",", "help", "=", "'Install and configure django-filer plugins '", "'- Always enabled'", ")", "parser", ".", "add_argument", "(", "'--requirements'", ",", "'-r'", ",", "dest", "=", "'requirements_file'", ",", "action", "=", "'store'", ",", "default", "=", "None", ",", "help", "=", "'Externally defined requirements file'", ")", "parser", ".", "add_argument", "(", "'--no-deps'", ",", "'-n'", ",", "dest", "=", "'no_deps'", ",", "action", "=", "'store_true'", ",", "default", "=", "False", ",", "help", "=", "'Don\\'t install package dependencies'", ")", "parser", ".", "add_argument", "(", "'--no-plugins'", ",", "dest", "=", "'no_plugins'", ",", "action", "=", "'store_true'", ",", "default", "=", "False", ",", "help", "=", "'Don\\'t install plugins'", ")", "parser", ".", "add_argument", "(", "'--no-db-driver'", ",", "dest", "=", "'no_db_driver'", ",", "action", "=", "'store_true'", ",", "default", "=", "False", ",", "help", "=", "'Don\\'t install database package'", ")", "parser", ".", "add_argument", "(", "'--no-sync'", ",", "'-m'", ",", "dest", "=", "'no_sync'", ",", "action", "=", "'store_true'", ",", "default", "=", "False", ",", "help", "=", "'Don\\'t run syncdb / migrate after bootstrapping'", ")", "parser", ".", "add_argument", "(", "'--no-user'", ",", "'-u'", ",", "dest", "=", "'no_user'", ",", "action", "=", "'store_true'", ",", "default", "=", "False", ",", "help", "=", "'Don\\'t create the admin user'", ")", "parser", ".", "add_argument", "(", "'--template'", ",", "dest", "=", "'template'", ",", "action", "=", "'store'", ",", "default", "=", "None", ",", "help", "=", "'The path or URL to load the django project '", "'template from.'", ")", "parser", ".", "add_argument", "(", "'--extra-settings'", ",", "dest", "=", "'extra_settings'", ",", "action", "=", "'store'", ",", "default", "=", "None", ",", "help", "=", "'The path to an file that contains extra settings.'", ")", "parser", ".", "add_argument", "(", "'--skip-empty-check'", ",", "'-s'", ",", "dest", "=", "'skip_project_dir_check'", ",", "action", "=", "'store_true'", ",", "default", "=", "False", ",", "help", "=", "'Skip the check if project dir is empty.'", ")", "parser", ".", "add_argument", "(", "'--delete-project-dir'", ",", "'-c'", ",", "dest", "=", "'delete_project_dir'", ",", "action", "=", "'store_true'", ",", "default", "=", "False", ",", "help", "=", "'Delete project directory on creation failure.'", ")", "parser", ".", "add_argument", "(", "'--utc'", ",", "dest", "=", "'utc'", ",", "action", "=", "'store_true'", ",", "default", "=", "False", ",", "help", "=", "'Use UTC timezone.'", ")", "if", "'--utc'", "in", "args", ":", "for", "action", "in", "parser", ".", "_positionals", ".", "_actions", ":", "if", "action", ".", "dest", "==", "'timezone'", ":", "action", ".", "default", "=", "'UTC'", "# If config_args then pretend that config args came from the stdin and run parser again.", "config_args", "=", "ini", ".", "parse_config_file", "(", "parser", ",", "args", ")", "args", "=", "parser", ".", "parse_args", "(", "config_args", "+", "args", ")", "if", "not", "args", ".", "wizard", ":", "args", ".", "noinput", "=", "True", "else", ":", "args", ".", "noinput", "=", "False", "if", "not", "args", ".", "project_directory", ":", "args", ".", "project_directory", "=", "args", ".", "project_name", "args", ".", "project_directory", "=", "os", ".", "path", ".", "abspath", "(", "args", ".", "project_directory", ")", "# First of all, check if the project name is valid", "if", "not", "validate_project", "(", "args", ".", "project_name", ")", ":", "sys", ".", "stderr", ".", "write", "(", "'Project name \"{0}\" is not a valid app name, or it\\'s already defined. '", "'Please use only numbers, letters and underscores.\\n'", ".", "format", "(", "args", ".", "project_name", ")", ")", "sys", ".", "exit", "(", "3", ")", "# Checking the given path", "setattr", "(", "args", ",", "'project_path'", ",", "os", ".", "path", ".", "join", "(", "args", ".", "project_directory", ",", "args", ".", "project_name", ")", ".", "strip", "(", ")", ")", "if", "not", "args", ".", "skip_project_dir_check", ":", "if", "(", "os", ".", "path", ".", "exists", "(", "args", ".", "project_directory", ")", "and", "[", "path", "for", "path", "in", "os", ".", "listdir", "(", "args", ".", "project_directory", ")", "if", "not", "path", ".", "startswith", "(", "'.'", ")", "]", ")", ":", "sys", ".", "stderr", ".", "write", "(", "'Path \"{0}\" already exists and is not empty, please choose a different one\\n'", "'If you want to use this path anyway use the -s flag to skip this check.\\n'", "''", ".", "format", "(", "args", ".", "project_directory", ")", ")", "sys", ".", "exit", "(", "4", ")", "if", "os", ".", "path", ".", "exists", "(", "args", ".", "project_path", ")", ":", "sys", ".", "stderr", ".", "write", "(", "'Path \"{0}\" already exists, please choose a different one\\n'", ".", "format", "(", "args", ".", "project_path", ")", ")", "sys", ".", "exit", "(", "4", ")", "if", "args", ".", "config_dump", "and", "os", ".", "path", ".", "isfile", "(", "args", ".", "config_dump", ")", ":", "sys", ".", "stdout", ".", "write", "(", "'Cannot dump because given configuration file \"{0}\" exists.\\n'", ".", "format", "(", "args", ".", "config_dump", ")", ")", "sys", ".", "exit", "(", "8", ")", "args", "=", "_manage_args", "(", "parser", ",", "args", ")", "# what do we want here?!", "# * if languages are given as multiple arguments, let's use it as is", "# * if no languages are given, use a default and stop handling it further", "# * if languages are given as a comma-separated list, split it and use the", "# resulting list.", "if", "not", "args", ".", "languages", ":", "try", ":", "args", ".", "languages", "=", "[", "locale", ".", "getdefaultlocale", "(", ")", "[", "0", "]", ".", "split", "(", "'_'", ")", "[", "0", "]", "]", "except", "Exception", ":", "# pragma: no cover", "args", ".", "languages", "=", "[", "'en'", "]", "elif", "isinstance", "(", "args", ".", "languages", ",", "six", ".", "string_types", ")", ":", "args", ".", "languages", "=", "args", ".", "languages", ".", "split", "(", "','", ")", "elif", "len", "(", "args", ".", "languages", ")", "==", "1", "and", "isinstance", "(", "args", ".", "languages", "[", "0", "]", ",", "six", ".", "string_types", ")", ":", "args", ".", "languages", "=", "args", ".", "languages", "[", "0", "]", ".", "split", "(", "','", ")", "args", ".", "languages", "=", "[", "lang", ".", "strip", "(", ")", ".", "lower", "(", ")", "for", "lang", "in", "args", ".", "languages", "]", "if", "len", "(", "args", ".", "languages", ")", ">", "1", ":", "args", ".", "i18n", "=", "'yes'", "args", ".", "aldryn", "=", "False", "args", ".", "filer", "=", "True", "# Convert version to numeric format for easier checking", "try", ":", "django_version", ",", "cms_version", "=", "supported_versions", "(", "args", ".", "django_version", ",", "args", ".", "cms_version", ")", "cms_package", "=", "data", ".", "PACKAGE_MATRIX", ".", "get", "(", "cms_version", ",", "data", ".", "PACKAGE_MATRIX", "[", "data", ".", "DJANGOCMS_LTS", "]", ")", "except", "RuntimeError", "as", "e", ":", "# pragma: no cover", "sys", ".", "stderr", ".", "write", "(", "compat", ".", "unicode", "(", "e", ")", ")", "sys", ".", "exit", "(", "6", ")", "if", "django_version", "is", "None", ":", "# pragma: no cover", "sys", ".", "stderr", ".", "write", "(", "'Please provide a Django supported version: {0}. Only Major.Minor '", "'version selector is accepted\\n'", ".", "format", "(", "', '", ".", "join", "(", "data", ".", "DJANGO_SUPPORTED", ")", ")", ")", "sys", ".", "exit", "(", "6", ")", "if", "cms_version", "is", "None", ":", "# pragma: no cover", "sys", ".", "stderr", ".", "write", "(", "'Please provide a django CMS supported version: {0}. Only Major.Minor '", "'version selector is accepted\\n'", ".", "format", "(", "', '", ".", "join", "(", "data", ".", "DJANGOCMS_SUPPORTED", ")", ")", ")", "sys", ".", "exit", "(", "6", ")", "default_settings", "=", "'{}.settings'", ".", "format", "(", "args", ".", "project_name", ")", "env_settings", "=", "os", ".", "environ", ".", "get", "(", "'DJANGO_SETTINGS_MODULE'", ",", "default_settings", ")", "if", "env_settings", "!=", "default_settings", ":", "sys", ".", "stderr", ".", "write", "(", "'`DJANGO_SETTINGS_MODULE` is currently set to \\'{0}\\' which is not compatible with '", "'djangocms installer.\\nPlease unset `DJANGO_SETTINGS_MODULE` and re-run the installer '", "'\\n'", ".", "format", "(", "env_settings", ")", ")", "sys", ".", "exit", "(", "10", ")", "if", "not", "getattr", "(", "args", ",", "'requirements_file'", ")", ":", "requirements", "=", "[", "]", "# django CMS version check", "if", "args", ".", "cms_version", "==", "'develop'", ":", "requirements", ".", "append", "(", "cms_package", ")", "warnings", ".", "warn", "(", "data", ".", "VERSION_WARNING", ".", "format", "(", "'develop'", ",", "'django CMS'", ")", ")", "elif", "args", ".", "cms_version", "==", "'rc'", ":", "# pragma: no cover", "requirements", ".", "append", "(", "cms_package", ")", "elif", "args", ".", "cms_version", "==", "'beta'", ":", "# pragma: no cover", "requirements", ".", "append", "(", "cms_package", ")", "warnings", ".", "warn", "(", "data", ".", "VERSION_WARNING", ".", "format", "(", "'beta'", ",", "'django CMS'", ")", ")", "else", ":", "requirements", ".", "append", "(", "cms_package", ")", "if", "args", ".", "cms_version", "in", "(", "'rc'", ",", "'develop'", ")", ":", "requirements", ".", "extend", "(", "data", ".", "REQUIREMENTS", "[", "'cms-master'", "]", ")", "elif", "LooseVersion", "(", "cms_version", ")", ">=", "LooseVersion", "(", "'3.6'", ")", ":", "requirements", ".", "extend", "(", "data", ".", "REQUIREMENTS", "[", "'cms-3.6'", "]", ")", "elif", "LooseVersion", "(", "cms_version", ")", ">=", "LooseVersion", "(", "'3.5'", ")", ":", "requirements", ".", "extend", "(", "data", ".", "REQUIREMENTS", "[", "'cms-3.5'", "]", ")", "elif", "LooseVersion", "(", "cms_version", ")", ">=", "LooseVersion", "(", "'3.4'", ")", ":", "requirements", ".", "extend", "(", "data", ".", "REQUIREMENTS", "[", "'cms-3.4'", "]", ")", "if", "not", "args", ".", "no_db_driver", ":", "requirements", ".", "append", "(", "args", ".", "db_driver", ")", "if", "not", "args", ".", "no_plugins", ":", "if", "args", ".", "cms_version", "in", "(", "'rc'", ",", "'develop'", ")", ":", "requirements", ".", "extend", "(", "data", ".", "REQUIREMENTS", "[", "'plugins-master'", "]", ")", "elif", "LooseVersion", "(", "cms_version", ")", ">=", "LooseVersion", "(", "'3.6'", ")", ":", "requirements", ".", "extend", "(", "data", ".", "REQUIREMENTS", "[", "'plugins-3.6'", "]", ")", "elif", "LooseVersion", "(", "cms_version", ")", ">=", "LooseVersion", "(", "'3.5'", ")", ":", "requirements", ".", "extend", "(", "data", ".", "REQUIREMENTS", "[", "'plugins-3.5'", "]", ")", "elif", "LooseVersion", "(", "cms_version", ")", ">=", "LooseVersion", "(", "'3.4'", ")", ":", "requirements", ".", "extend", "(", "data", ".", "REQUIREMENTS", "[", "'plugins-3.4'", "]", ")", "requirements", ".", "extend", "(", "data", ".", "REQUIREMENTS", "[", "'filer'", "]", ")", "if", "args", ".", "aldryn", ":", "# pragma: no cover", "requirements", ".", "extend", "(", "data", ".", "REQUIREMENTS", "[", "'aldryn'", "]", ")", "# Django version check", "if", "args", ".", "django_version", "==", "'develop'", ":", "# pragma: no cover", "requirements", ".", "append", "(", "data", ".", "DJANGO_DEVELOP", ")", "warnings", ".", "warn", "(", "data", ".", "VERSION_WARNING", ".", "format", "(", "'develop'", ",", "'Django'", ")", ")", "elif", "args", ".", "django_version", "==", "'beta'", ":", "# pragma: no cover", "requirements", ".", "append", "(", "data", ".", "DJANGO_BETA", ")", "warnings", ".", "warn", "(", "data", ".", "VERSION_WARNING", ".", "format", "(", "'beta'", ",", "'Django'", ")", ")", "else", ":", "requirements", ".", "append", "(", "'Django<{0}'", ".", "format", "(", "less_than_version", "(", "django_version", ")", ")", ")", "if", "django_version", "==", "'1.8'", ":", "requirements", ".", "extend", "(", "data", ".", "REQUIREMENTS", "[", "'django-1.8'", "]", ")", "elif", "django_version", "==", "'1.9'", ":", "requirements", ".", "extend", "(", "data", ".", "REQUIREMENTS", "[", "'django-1.9'", "]", ")", "elif", "django_version", "==", "'1.10'", ":", "requirements", ".", "extend", "(", "data", ".", "REQUIREMENTS", "[", "'django-1.10'", "]", ")", "elif", "django_version", "==", "'1.11'", ":", "requirements", ".", "extend", "(", "data", ".", "REQUIREMENTS", "[", "'django-1.11'", "]", ")", "elif", "django_version", "==", "'2.0'", ":", "requirements", ".", "extend", "(", "data", ".", "REQUIREMENTS", "[", "'django-2.0'", "]", ")", "elif", "django_version", "==", "'2.1'", ":", "requirements", ".", "extend", "(", "data", ".", "REQUIREMENTS", "[", "'django-2.1'", "]", ")", "requirements", ".", "extend", "(", "data", ".", "REQUIREMENTS", "[", "'default'", "]", ")", "setattr", "(", "args", ",", "'requirements'", ",", "'\\n'", ".", "join", "(", "requirements", ")", ".", "strip", "(", ")", ")", "# Convenient shortcuts", "setattr", "(", "args", ",", "'cms_version'", ",", "cms_version", ")", "setattr", "(", "args", ",", "'django_version'", ",", "django_version", ")", "setattr", "(", "args", ",", "'settings_path'", ",", "os", ".", "path", ".", "join", "(", "args", ".", "project_directory", ",", "args", ".", "project_name", ",", "'settings.py'", ")", ".", "strip", "(", ")", ")", "setattr", "(", "args", ",", "'urlconf_path'", ",", "os", ".", "path", ".", "join", "(", "args", ".", "project_directory", ",", "args", ".", "project_name", ",", "'urls.py'", ")", ".", "strip", "(", ")", ")", "if", "args", ".", "config_dump", ":", "ini", ".", "dump_config_file", "(", "args", ".", "config_dump", ",", "args", ",", "parser", ")", "return", "args" ]
9fec66d5f8b1e9a0f3c0ec66dd777db578fab07e
valid
_manage_args
Checks and validate provided input
djangocms_installer/config/__init__.py
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 we find a way to test input if not args.noinput: # pragma: no cover if action.choices: choices = ' (choices: {0})'.format(', '.join(action.choices)) if input_value: if type(input_value) == list: default = ' [default {0}]'.format(', '.join(input_value)) else: default = ' [default {0}]'.format(input_value) while not new_val: prompt = '{0}{1}{2}: '.format(action.help, choices, default) if action.choices in ('yes', 'no'): new_val = utils.query_yes_no(prompt) else: new_val = compat.input(prompt) new_val = compat.clean(new_val) if not new_val and input_value: new_val = input_value if new_val and action.dest == 'templates': if new_val != 'no' and not os.path.isdir(new_val): sys.stdout.write('Given directory does not exists, retry\n') new_val = False if new_val and action.dest == 'db': action(parser, args, new_val, action.option_strings) new_val = getattr(args, action.dest) else: if not input_value and action.required: raise ValueError( 'Option {0} is required when in no-input mode'.format(action.dest) ) new_val = input_value if action.dest == 'db': action(parser, args, new_val, action.option_strings) new_val = getattr(args, action.dest) if action.dest == 'templates' and (new_val == 'no' or not os.path.isdir(new_val)): new_val = False if action.dest in ('bootstrap', 'starting_page'): new_val = (new_val == 'yes') setattr(args, action.dest, new_val) return args
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 we find a way to test input if not args.noinput: # pragma: no cover if action.choices: choices = ' (choices: {0})'.format(', '.join(action.choices)) if input_value: if type(input_value) == list: default = ' [default {0}]'.format(', '.join(input_value)) else: default = ' [default {0}]'.format(input_value) while not new_val: prompt = '{0}{1}{2}: '.format(action.help, choices, default) if action.choices in ('yes', 'no'): new_val = utils.query_yes_no(prompt) else: new_val = compat.input(prompt) new_val = compat.clean(new_val) if not new_val and input_value: new_val = input_value if new_val and action.dest == 'templates': if new_val != 'no' and not os.path.isdir(new_val): sys.stdout.write('Given directory does not exists, retry\n') new_val = False if new_val and action.dest == 'db': action(parser, args, new_val, action.option_strings) new_val = getattr(args, action.dest) else: if not input_value and action.required: raise ValueError( 'Option {0} is required when in no-input mode'.format(action.dest) ) new_val = input_value if action.dest == 'db': action(parser, args, new_val, action.option_strings) new_val = getattr(args, action.dest) if action.dest == 'templates' and (new_val == 'no' or not os.path.isdir(new_val)): new_val = False if action.dest in ('bootstrap', 'starting_page'): new_val = (new_val == 'yes') setattr(args, action.dest, new_val) return args
[ "Checks", "and", "validate", "provided", "input" ]
nephila/djangocms-installer
python
https://github.com/nephila/djangocms-installer/blob/9fec66d5f8b1e9a0f3c0ec66dd777db578fab07e/djangocms_installer/config/__init__.py#L363-L412
[ "def", "_manage_args", "(", "parser", ",", "args", ")", ":", "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 we find a way to test input", "if", "not", "args", ".", "noinput", ":", "# pragma: no cover", "if", "action", ".", "choices", ":", "choices", "=", "' (choices: {0})'", ".", "format", "(", "', '", ".", "join", "(", "action", ".", "choices", ")", ")", "if", "input_value", ":", "if", "type", "(", "input_value", ")", "==", "list", ":", "default", "=", "' [default {0}]'", ".", "format", "(", "', '", ".", "join", "(", "input_value", ")", ")", "else", ":", "default", "=", "' [default {0}]'", ".", "format", "(", "input_value", ")", "while", "not", "new_val", ":", "prompt", "=", "'{0}{1}{2}: '", ".", "format", "(", "action", ".", "help", ",", "choices", ",", "default", ")", "if", "action", ".", "choices", "in", "(", "'yes'", ",", "'no'", ")", ":", "new_val", "=", "utils", ".", "query_yes_no", "(", "prompt", ")", "else", ":", "new_val", "=", "compat", ".", "input", "(", "prompt", ")", "new_val", "=", "compat", ".", "clean", "(", "new_val", ")", "if", "not", "new_val", "and", "input_value", ":", "new_val", "=", "input_value", "if", "new_val", "and", "action", ".", "dest", "==", "'templates'", ":", "if", "new_val", "!=", "'no'", "and", "not", "os", ".", "path", ".", "isdir", "(", "new_val", ")", ":", "sys", ".", "stdout", ".", "write", "(", "'Given directory does not exists, retry\\n'", ")", "new_val", "=", "False", "if", "new_val", "and", "action", ".", "dest", "==", "'db'", ":", "action", "(", "parser", ",", "args", ",", "new_val", ",", "action", ".", "option_strings", ")", "new_val", "=", "getattr", "(", "args", ",", "action", ".", "dest", ")", "else", ":", "if", "not", "input_value", "and", "action", ".", "required", ":", "raise", "ValueError", "(", "'Option {0} is required when in no-input mode'", ".", "format", "(", "action", ".", "dest", ")", ")", "new_val", "=", "input_value", "if", "action", ".", "dest", "==", "'db'", ":", "action", "(", "parser", ",", "args", ",", "new_val", ",", "action", ".", "option_strings", ")", "new_val", "=", "getattr", "(", "args", ",", "action", ".", "dest", ")", "if", "action", ".", "dest", "==", "'templates'", "and", "(", "new_val", "==", "'no'", "or", "not", "os", ".", "path", ".", "isdir", "(", "new_val", ")", ")", ":", "new_val", "=", "False", "if", "action", ".", "dest", "in", "(", "'bootstrap'", ",", "'starting_page'", ")", ":", "new_val", "=", "(", "new_val", "==", "'yes'", ")", "setattr", "(", "args", ",", "action", ".", "dest", ",", "new_val", ")", "return", "args" ]
9fec66d5f8b1e9a0f3c0ec66dd777db578fab07e
valid
query_yes_no
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 default), "no" or None (meaning an answer is required of the user). The "answer" return value is one of "yes" or "no". Code borrowed from cookiecutter https://github.com/audreyr/cookiecutter/blob/master/cookiecutter/prompt.py
djangocms_installer/utils.py
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 default), "no" or None (meaning an answer is required of the user). The "answer" return value is one of "yes" or "no". Code borrowed from cookiecutter https://github.com/audreyr/cookiecutter/blob/master/cookiecutter/prompt.py """ valid = {'yes': True, 'y': True, 'ye': True, 'no': False, 'n': False} if default is None: prompt = ' [y/n] ' elif default == 'yes': prompt = ' [Y/n] ' elif default == 'no': prompt = ' [y/N] ' else: raise ValueError('invalid default answer: "{0}"'.format(default)) while True: sys.stdout.write(question + prompt) choice = compat.input().lower() if default is not None and choice == '': return valid[default] elif choice in valid: return valid[choice] else: sys.stdout.write('Please answer with "yes" or "no" (or "y" or "n").\n')
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 default), "no" or None (meaning an answer is required of the user). The "answer" return value is one of "yes" or "no". Code borrowed from cookiecutter https://github.com/audreyr/cookiecutter/blob/master/cookiecutter/prompt.py """ valid = {'yes': True, 'y': True, 'ye': True, 'no': False, 'n': False} if default is None: prompt = ' [y/n] ' elif default == 'yes': prompt = ' [Y/n] ' elif default == 'no': prompt = ' [y/N] ' else: raise ValueError('invalid default answer: "{0}"'.format(default)) while True: sys.stdout.write(question + prompt) choice = compat.input().lower() if default is not None and choice == '': return valid[default] elif choice in valid: return valid[choice] else: sys.stdout.write('Please answer with "yes" or "no" (or "y" or "n").\n')
[ "Ask", "a", "yes", "/", "no", "question", "via", "raw_input", "()", "and", "return", "their", "answer", "." ]
nephila/djangocms-installer
python
https://github.com/nephila/djangocms-installer/blob/9fec66d5f8b1e9a0f3c0ec66dd777db578fab07e/djangocms_installer/utils.py#L15-L48
[ "def", "query_yes_no", "(", "question", ",", "default", "=", "None", ")", ":", "# pragma: no cover", "valid", "=", "{", "'yes'", ":", "True", ",", "'y'", ":", "True", ",", "'ye'", ":", "True", ",", "'no'", ":", "False", ",", "'n'", ":", "False", "}", "if", "default", "is", "None", ":", "prompt", "=", "' [y/n] '", "elif", "default", "==", "'yes'", ":", "prompt", "=", "' [Y/n] '", "elif", "default", "==", "'no'", ":", "prompt", "=", "' [y/N] '", "else", ":", "raise", "ValueError", "(", "'invalid default answer: \"{0}\"'", ".", "format", "(", "default", ")", ")", "while", "True", ":", "sys", ".", "stdout", ".", "write", "(", "question", "+", "prompt", ")", "choice", "=", "compat", ".", "input", "(", ")", ".", "lower", "(", ")", "if", "default", "is", "not", "None", "and", "choice", "==", "''", ":", "return", "valid", "[", "default", "]", "elif", "choice", "in", "valid", ":", "return", "valid", "[", "choice", "]", "else", ":", "sys", ".", "stdout", ".", "write", "(", "'Please answer with \"yes\" or \"no\" (or \"y\" or \"n\").\\n'", ")" ]
9fec66d5f8b1e9a0f3c0ec66dd777db578fab07e
valid
supported_versions
Convert numeric and literal version information to numeric format
djangocms_installer/utils.py
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[str(cms)] except KeyError: pass try: django_version = Decimal(django) except (ValueError, InvalidOperation): try: django_version = DJANGO_VERSION_MATRIX[str(django)] except KeyError: # pragma: no cover pass try: if ( cms_version and django_version and not (LooseVersion(VERSION_MATRIX[compat.unicode(cms_version)][0]) <= LooseVersion(compat.unicode(django_version)) <= LooseVersion(VERSION_MATRIX[compat.unicode(cms_version)][1])) ): raise RuntimeError( 'Django and django CMS versions doesn\'t match: ' 'Django {0} is not supported by django CMS {1}'.format(django_version, cms_version) ) except KeyError: raise RuntimeError( 'Django and django CMS versions doesn\'t match: ' 'Django {0} is not supported by django CMS {1}'.format(django_version, cms_version) ) return ( compat.unicode(django_version) if django_version else django_version, compat.unicode(cms_version) if cms_version else cms_version )
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[str(cms)] except KeyError: pass try: django_version = Decimal(django) except (ValueError, InvalidOperation): try: django_version = DJANGO_VERSION_MATRIX[str(django)] except KeyError: # pragma: no cover pass try: if ( cms_version and django_version and not (LooseVersion(VERSION_MATRIX[compat.unicode(cms_version)][0]) <= LooseVersion(compat.unicode(django_version)) <= LooseVersion(VERSION_MATRIX[compat.unicode(cms_version)][1])) ): raise RuntimeError( 'Django and django CMS versions doesn\'t match: ' 'Django {0} is not supported by django CMS {1}'.format(django_version, cms_version) ) except KeyError: raise RuntimeError( 'Django and django CMS versions doesn\'t match: ' 'Django {0} is not supported by django CMS {1}'.format(django_version, cms_version) ) return ( compat.unicode(django_version) if django_version else django_version, compat.unicode(cms_version) if cms_version else cms_version )
[ "Convert", "numeric", "and", "literal", "version", "information", "to", "numeric", "format" ]
nephila/djangocms-installer
python
https://github.com/nephila/djangocms-installer/blob/9fec66d5f8b1e9a0f3c0ec66dd777db578fab07e/djangocms_installer/utils.py#L51-L93
[ "def", "supported_versions", "(", "django", ",", "cms", ")", ":", "cms_version", "=", "None", "django_version", "=", "None", "try", ":", "cms_version", "=", "Decimal", "(", "cms", ")", "except", "(", "ValueError", ",", "InvalidOperation", ")", ":", "try", ":", "cms_version", "=", "CMS_VERSION_MATRIX", "[", "str", "(", "cms", ")", "]", "except", "KeyError", ":", "pass", "try", ":", "django_version", "=", "Decimal", "(", "django", ")", "except", "(", "ValueError", ",", "InvalidOperation", ")", ":", "try", ":", "django_version", "=", "DJANGO_VERSION_MATRIX", "[", "str", "(", "django", ")", "]", "except", "KeyError", ":", "# pragma: no cover", "pass", "try", ":", "if", "(", "cms_version", "and", "django_version", "and", "not", "(", "LooseVersion", "(", "VERSION_MATRIX", "[", "compat", ".", "unicode", "(", "cms_version", ")", "]", "[", "0", "]", ")", "<=", "LooseVersion", "(", "compat", ".", "unicode", "(", "django_version", ")", ")", "<=", "LooseVersion", "(", "VERSION_MATRIX", "[", "compat", ".", "unicode", "(", "cms_version", ")", "]", "[", "1", "]", ")", ")", ")", ":", "raise", "RuntimeError", "(", "'Django and django CMS versions doesn\\'t match: '", "'Django {0} is not supported by django CMS {1}'", ".", "format", "(", "django_version", ",", "cms_version", ")", ")", "except", "KeyError", ":", "raise", "RuntimeError", "(", "'Django and django CMS versions doesn\\'t match: '", "'Django {0} is not supported by django CMS {1}'", ".", "format", "(", "django_version", ",", "cms_version", ")", ")", "return", "(", "compat", ".", "unicode", "(", "django_version", ")", "if", "django_version", "else", "django_version", ",", "compat", ".", "unicode", "(", "cms_version", ")", "if", "cms_version", "else", "cms_version", ")" ]
9fec66d5f8b1e9a0f3c0ec66dd777db578fab07e
valid
less_than_version
Converts the current version to the next one for inserting into requirements in the ' < version' format
djangocms_installer/utils.py
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' else: return '.'.join(map(str, items))
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' else: return '.'.join(map(str, items))
[ "Converts", "the", "current", "version", "to", "the", "next", "one", "for", "inserting", "into", "requirements", "in", "the", "<", "version", "format" ]
nephila/djangocms-installer
python
https://github.com/nephila/djangocms-installer/blob/9fec66d5f8b1e9a0f3c0ec66dd777db578fab07e/djangocms_installer/utils.py#L96-L108
[ "def", "less_than_version", "(", "value", ")", ":", "items", "=", "list", "(", "map", "(", "int", ",", "str", "(", "value", ")", ".", "split", "(", "'.'", ")", ")", ")", "if", "len", "(", "items", ")", "==", "1", ":", "items", ".", "append", "(", "0", ")", "items", "[", "1", "]", "+=", "1", "if", "value", "==", "'1.11'", ":", "return", "'2.0'", "else", ":", "return", "'.'", ".", "join", "(", "map", "(", "str", ",", "items", ")", ")" ]
9fec66d5f8b1e9a0f3c0ec66dd777db578fab07e
valid
format_val
Returns val as integer or as escaped string according to its value :param val: any value :return: formatted string
djangocms_installer/utils.py
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)
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)
[ "Returns", "val", "as", "integer", "or", "as", "escaped", "string", "according", "to", "its", "value", ":", "param", "val", ":", "any", "value", ":", "return", ":", "formatted", "string" ]
nephila/djangocms-installer
python
https://github.com/nephila/djangocms-installer/blob/9fec66d5f8b1e9a0f3c0ec66dd777db578fab07e/djangocms_installer/utils.py#L126-L136
[ "def", "format_val", "(", "val", ")", ":", "val", "=", "text_type", "(", "val", ")", "if", "val", ".", "isdigit", "(", ")", ":", "return", "int", "(", "val", ")", "else", ":", "return", "'\\'{0}\\''", ".", "format", "(", "val", ")" ]
9fec66d5f8b1e9a0f3c0ec66dd777db578fab07e
valid
parse_config_file
Parse config file. Returns a list of additional args.
djangocms_installer/config/ini.py
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(action) action.required = False parsed_args = parser.parse_args(stdin_args) # Restore required args. for action in required_args: action.required = True if not parsed_args.config_file: return config_args config = ConfigParser() if not config.read(parsed_args.config_file): sys.stderr.write('Config file "{0}" doesn\'t exists\n'.format(parsed_args.config_file)) sys.exit(7) # It isn't used anywhere. config_args = _convert_config_to_stdin(config, parser) return config_args
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(action) action.required = False parsed_args = parser.parse_args(stdin_args) # Restore required args. for action in required_args: action.required = True if not parsed_args.config_file: return config_args config = ConfigParser() if not config.read(parsed_args.config_file): sys.stderr.write('Config file "{0}" doesn\'t exists\n'.format(parsed_args.config_file)) sys.exit(7) # It isn't used anywhere. config_args = _convert_config_to_stdin(config, parser) return config_args
[ "Parse", "config", "file", "." ]
nephila/djangocms-installer
python
https://github.com/nephila/djangocms-installer/blob/9fec66d5f8b1e9a0f3c0ec66dd777db578fab07e/djangocms_installer/config/ini.py#L17-L46
[ "def", "parse_config_file", "(", "parser", ",", "stdin_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", "(", "action", ")", "action", ".", "required", "=", "False", "parsed_args", "=", "parser", ".", "parse_args", "(", "stdin_args", ")", "# Restore required args.", "for", "action", "in", "required_args", ":", "action", ".", "required", "=", "True", "if", "not", "parsed_args", ".", "config_file", ":", "return", "config_args", "config", "=", "ConfigParser", "(", ")", "if", "not", "config", ".", "read", "(", "parsed_args", ".", "config_file", ")", ":", "sys", ".", "stderr", ".", "write", "(", "'Config file \"{0}\" doesn\\'t exists\\n'", ".", "format", "(", "parsed_args", ".", "config_file", ")", ")", "sys", ".", "exit", "(", "7", ")", "# It isn't used anywhere.", "config_args", "=", "_convert_config_to_stdin", "(", "config", ",", "parser", ")", "return", "config_args" ]
9fec66d5f8b1e9a0f3c0ec66dd777db578fab07e
valid
dump_config_file
Dump args to config file.
djangocms_installer/config/ini.py
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-settings', '--languages', '--requirements', '--template', '--timezone') # positionals._option_string_actions for action in parser._actions: if action.dest in ('help', 'config_file', 'config_dump', 'project_name'): continue keyp = action.option_strings[0] option_name = keyp.lstrip('-') option_value = getattr(args, action.dest) if any([i for i in keys_empty_values_not_pass if i in action.option_strings]): if action.dest == 'languages': if len(option_value) == 1 and option_value[0] == 'en': config.set(SECTION, option_name, '') else: config.set(SECTION, option_name, ','.join(option_value)) else: config.set(SECTION, option_name, option_value if option_value else '') elif action.choices == ('yes', 'no'): config.set(SECTION, option_name, 'yes' if option_value else 'no') elif action.dest == 'templates': config.set(SECTION, option_name, option_value if option_value else 'no') elif action.dest == 'cms_version': version = ('stable' if option_value == CMS_VERSION_MATRIX['stable'] else option_value) config.set(SECTION, option_name, version) elif action.dest == 'django_version': version = ('stable' if option_value == DJANGO_VERSION_MATRIX['stable'] else option_value) config.set(SECTION, option_name, version) elif action.const: config.set(SECTION, option_name, 'true' if option_value else 'false') else: config.set(SECTION, option_name, str(option_value)) with open(filename, 'w') as fp: config.write(fp)
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-settings', '--languages', '--requirements', '--template', '--timezone') # positionals._option_string_actions for action in parser._actions: if action.dest in ('help', 'config_file', 'config_dump', 'project_name'): continue keyp = action.option_strings[0] option_name = keyp.lstrip('-') option_value = getattr(args, action.dest) if any([i for i in keys_empty_values_not_pass if i in action.option_strings]): if action.dest == 'languages': if len(option_value) == 1 and option_value[0] == 'en': config.set(SECTION, option_name, '') else: config.set(SECTION, option_name, ','.join(option_value)) else: config.set(SECTION, option_name, option_value if option_value else '') elif action.choices == ('yes', 'no'): config.set(SECTION, option_name, 'yes' if option_value else 'no') elif action.dest == 'templates': config.set(SECTION, option_name, option_value if option_value else 'no') elif action.dest == 'cms_version': version = ('stable' if option_value == CMS_VERSION_MATRIX['stable'] else option_value) config.set(SECTION, option_name, version) elif action.dest == 'django_version': version = ('stable' if option_value == DJANGO_VERSION_MATRIX['stable'] else option_value) config.set(SECTION, option_name, version) elif action.const: config.set(SECTION, option_name, 'true' if option_value else 'false') else: config.set(SECTION, option_name, str(option_value)) with open(filename, 'w') as fp: config.write(fp)
[ "Dump", "args", "to", "config", "file", "." ]
nephila/djangocms-installer
python
https://github.com/nephila/djangocms-installer/blob/9fec66d5f8b1e9a0f3c0ec66dd777db578fab07e/djangocms_installer/config/ini.py#L49-L93
[ "def", "dump_config_file", "(", "filename", ",", "args", ",", "parser", "=", "None", ")", ":", "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-settings'", ",", "'--languages'", ",", "'--requirements'", ",", "'--template'", ",", "'--timezone'", ")", "# positionals._option_string_actions", "for", "action", "in", "parser", ".", "_actions", ":", "if", "action", ".", "dest", "in", "(", "'help'", ",", "'config_file'", ",", "'config_dump'", ",", "'project_name'", ")", ":", "continue", "keyp", "=", "action", ".", "option_strings", "[", "0", "]", "option_name", "=", "keyp", ".", "lstrip", "(", "'-'", ")", "option_value", "=", "getattr", "(", "args", ",", "action", ".", "dest", ")", "if", "any", "(", "[", "i", "for", "i", "in", "keys_empty_values_not_pass", "if", "i", "in", "action", ".", "option_strings", "]", ")", ":", "if", "action", ".", "dest", "==", "'languages'", ":", "if", "len", "(", "option_value", ")", "==", "1", "and", "option_value", "[", "0", "]", "==", "'en'", ":", "config", ".", "set", "(", "SECTION", ",", "option_name", ",", "''", ")", "else", ":", "config", ".", "set", "(", "SECTION", ",", "option_name", ",", "','", ".", "join", "(", "option_value", ")", ")", "else", ":", "config", ".", "set", "(", "SECTION", ",", "option_name", ",", "option_value", "if", "option_value", "else", "''", ")", "elif", "action", ".", "choices", "==", "(", "'yes'", ",", "'no'", ")", ":", "config", ".", "set", "(", "SECTION", ",", "option_name", ",", "'yes'", "if", "option_value", "else", "'no'", ")", "elif", "action", ".", "dest", "==", "'templates'", ":", "config", ".", "set", "(", "SECTION", ",", "option_name", ",", "option_value", "if", "option_value", "else", "'no'", ")", "elif", "action", ".", "dest", "==", "'cms_version'", ":", "version", "=", "(", "'stable'", "if", "option_value", "==", "CMS_VERSION_MATRIX", "[", "'stable'", "]", "else", "option_value", ")", "config", ".", "set", "(", "SECTION", ",", "option_name", ",", "version", ")", "elif", "action", ".", "dest", "==", "'django_version'", ":", "version", "=", "(", "'stable'", "if", "option_value", "==", "DJANGO_VERSION_MATRIX", "[", "'stable'", "]", "else", "option_value", ")", "config", ".", "set", "(", "SECTION", ",", "option_name", ",", "version", ")", "elif", "action", ".", "const", ":", "config", ".", "set", "(", "SECTION", ",", "option_name", ",", "'true'", "if", "option_value", "else", "'false'", ")", "else", ":", "config", ".", "set", "(", "SECTION", ",", "option_name", ",", "str", "(", "option_value", ")", ")", "with", "open", "(", "filename", ",", "'w'", ")", "as", "fp", ":", "config", ".", "write", "(", "fp", ")" ]
9fec66d5f8b1e9a0f3c0ec66dd777db578fab07e
valid
_convert_config_to_stdin
Convert config options to stdin args. Especially boolean values, for more information @see https://docs.python.org/3.4/library/configparser.html#supported-datatypes
djangocms_installer/config/ini.py
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', '--requirements', '--template', '--timezone') args = [] for key, val in config.items(SECTION): keyp = '--{0}'.format(key) action = parser._option_string_actions[keyp] if action.const: try: if config.getboolean(SECTION, key): args.append(keyp) except ValueError: args.extend([keyp, val]) # Pass it as is to get the error from ArgumentParser. elif any([i for i in keys_empty_values_not_pass if i in action.option_strings]): # Some keys with empty values shouldn't be passed into args to use their defaults # from ArgumentParser. if val != '': args.extend([keyp, val]) else: args.extend([keyp, val]) return 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', '--requirements', '--template', '--timezone') args = [] for key, val in config.items(SECTION): keyp = '--{0}'.format(key) action = parser._option_string_actions[keyp] if action.const: try: if config.getboolean(SECTION, key): args.append(keyp) except ValueError: args.extend([keyp, val]) # Pass it as is to get the error from ArgumentParser. elif any([i for i in keys_empty_values_not_pass if i in action.option_strings]): # Some keys with empty values shouldn't be passed into args to use their defaults # from ArgumentParser. if val != '': args.extend([keyp, val]) else: args.extend([keyp, val]) return args
[ "Convert", "config", "options", "to", "stdin", "args", "." ]
nephila/djangocms-installer
python
https://github.com/nephila/djangocms-installer/blob/9fec66d5f8b1e9a0f3c0ec66dd777db578fab07e/djangocms_installer/config/ini.py#L96-L123
[ "def", "_convert_config_to_stdin", "(", "config", ",", "parser", ")", ":", "keys_empty_values_not_pass", "=", "(", "'--extra-settings'", ",", "'--languages'", ",", "'--requirements'", ",", "'--template'", ",", "'--timezone'", ")", "args", "=", "[", "]", "for", "key", ",", "val", "in", "config", ".", "items", "(", "SECTION", ")", ":", "keyp", "=", "'--{0}'", ".", "format", "(", "key", ")", "action", "=", "parser", ".", "_option_string_actions", "[", "keyp", "]", "if", "action", ".", "const", ":", "try", ":", "if", "config", ".", "getboolean", "(", "SECTION", ",", "key", ")", ":", "args", ".", "append", "(", "keyp", ")", "except", "ValueError", ":", "args", ".", "extend", "(", "[", "keyp", ",", "val", "]", ")", "# Pass it as is to get the error from ArgumentParser.", "elif", "any", "(", "[", "i", "for", "i", "in", "keys_empty_values_not_pass", "if", "i", "in", "action", ".", "option_strings", "]", ")", ":", "# Some keys with empty values shouldn't be passed into args to use their defaults", "# from ArgumentParser.", "if", "val", "!=", "''", ":", "args", ".", "extend", "(", "[", "keyp", ",", "val", "]", ")", "else", ":", "args", ".", "extend", "(", "[", "keyp", ",", "val", "]", ")", "return", "args" ]
9fec66d5f8b1e9a0f3c0ec66dd777db578fab07e
valid
create_project
Call django-admin to create the project structure :param config_data: configuration data
djangocms_installer/django/__init__.py
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.pathsep.join(map(shlex_quote, sys.path))) kwargs = {} args = [] if config_data.template: kwargs['template'] = config_data.template args.append(config_data.project_name) if config_data.project_directory: args.append(config_data.project_directory) if not os.path.exists(config_data.project_directory): os.makedirs(config_data.project_directory) base_cmd = 'django-admin.py' start_cmds = [os.path.join(os.path.dirname(sys.executable), base_cmd)] start_cmd_pnodes = ['Scripts'] start_cmds.extend([ os.path.join(os.path.dirname(sys.executable), pnode, base_cmd) for pnode in start_cmd_pnodes ]) start_cmd = [base_cmd] for p in start_cmds: if os.path.exists(p): start_cmd = [sys.executable, p] break cmd_args = start_cmd + ['startproject'] + args if config_data.verbose: sys.stdout.write('Project creation command: {0}\n'.format(' '.join(cmd_args))) try: output = subprocess.check_output(cmd_args, stderr=subprocess.STDOUT) sys.stdout.write(output.decode('utf-8')) except subprocess.CalledProcessError as e: # pragma: no cover if config_data.verbose: sys.stdout.write(e.output.decode('utf-8')) raise
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.pathsep.join(map(shlex_quote, sys.path))) kwargs = {} args = [] if config_data.template: kwargs['template'] = config_data.template args.append(config_data.project_name) if config_data.project_directory: args.append(config_data.project_directory) if not os.path.exists(config_data.project_directory): os.makedirs(config_data.project_directory) base_cmd = 'django-admin.py' start_cmds = [os.path.join(os.path.dirname(sys.executable), base_cmd)] start_cmd_pnodes = ['Scripts'] start_cmds.extend([ os.path.join(os.path.dirname(sys.executable), pnode, base_cmd) for pnode in start_cmd_pnodes ]) start_cmd = [base_cmd] for p in start_cmds: if os.path.exists(p): start_cmd = [sys.executable, p] break cmd_args = start_cmd + ['startproject'] + args if config_data.verbose: sys.stdout.write('Project creation command: {0}\n'.format(' '.join(cmd_args))) try: output = subprocess.check_output(cmd_args, stderr=subprocess.STDOUT) sys.stdout.write(output.decode('utf-8')) except subprocess.CalledProcessError as e: # pragma: no cover if config_data.verbose: sys.stdout.write(e.output.decode('utf-8')) raise
[ "Call", "django", "-", "admin", "to", "create", "the", "project", "structure" ]
nephila/djangocms-installer
python
https://github.com/nephila/djangocms-installer/blob/9fec66d5f8b1e9a0f3c0ec66dd777db578fab07e/djangocms_installer/django/__init__.py#L27-L66
[ "def", "create_project", "(", "config_data", ")", ":", "env", "=", "deepcopy", "(", "dict", "(", "os", ".", "environ", ")", ")", "env", "[", "str", "(", "'DJANGO_SETTINGS_MODULE'", ")", "]", "=", "str", "(", "'{0}.settings'", ".", "format", "(", "config_data", ".", "project_name", ")", ")", "env", "[", "str", "(", "'PYTHONPATH'", ")", "]", "=", "str", "(", "os", ".", "pathsep", ".", "join", "(", "map", "(", "shlex_quote", ",", "sys", ".", "path", ")", ")", ")", "kwargs", "=", "{", "}", "args", "=", "[", "]", "if", "config_data", ".", "template", ":", "kwargs", "[", "'template'", "]", "=", "config_data", ".", "template", "args", ".", "append", "(", "config_data", ".", "project_name", ")", "if", "config_data", ".", "project_directory", ":", "args", ".", "append", "(", "config_data", ".", "project_directory", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "config_data", ".", "project_directory", ")", ":", "os", ".", "makedirs", "(", "config_data", ".", "project_directory", ")", "base_cmd", "=", "'django-admin.py'", "start_cmds", "=", "[", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "sys", ".", "executable", ")", ",", "base_cmd", ")", "]", "start_cmd_pnodes", "=", "[", "'Scripts'", "]", "start_cmds", ".", "extend", "(", "[", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "sys", ".", "executable", ")", ",", "pnode", ",", "base_cmd", ")", "for", "pnode", "in", "start_cmd_pnodes", "]", ")", "start_cmd", "=", "[", "base_cmd", "]", "for", "p", "in", "start_cmds", ":", "if", "os", ".", "path", ".", "exists", "(", "p", ")", ":", "start_cmd", "=", "[", "sys", ".", "executable", ",", "p", "]", "break", "cmd_args", "=", "start_cmd", "+", "[", "'startproject'", "]", "+", "args", "if", "config_data", ".", "verbose", ":", "sys", ".", "stdout", ".", "write", "(", "'Project creation command: {0}\\n'", ".", "format", "(", "' '", ".", "join", "(", "cmd_args", ")", ")", ")", "try", ":", "output", "=", "subprocess", ".", "check_output", "(", "cmd_args", ",", "stderr", "=", "subprocess", ".", "STDOUT", ")", "sys", ".", "stdout", ".", "write", "(", "output", ".", "decode", "(", "'utf-8'", ")", ")", "except", "subprocess", ".", "CalledProcessError", "as", "e", ":", "# pragma: no cover", "if", "config_data", ".", "verbose", ":", "sys", ".", "stdout", ".", "write", "(", "e", ".", "output", ".", "decode", "(", "'utf-8'", ")", ")", "raise" ]
9fec66d5f8b1e9a0f3c0ec66dd777db578fab07e
valid
_detect_migration_layout
Detect migrations layout for plugins :param vars: installer settings :param apps: installed applications
djangocms_installer/django/__init__.py
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 = __import__('{0}.migrations_django'.format(module)) # NOQA DJANGO_MODULES[module] = '{0}.migrations_django'.format(module) except Exception: pass return DJANGO_MODULES
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 = __import__('{0}.migrations_django'.format(module)) # NOQA DJANGO_MODULES[module] = '{0}.migrations_django'.format(module) except Exception: pass return DJANGO_MODULES
[ "Detect", "migrations", "layout", "for", "plugins", ":", "param", "vars", ":", "installer", "settings", ":", "param", "apps", ":", "installed", "applications" ]
nephila/djangocms-installer
python
https://github.com/nephila/djangocms-installer/blob/9fec66d5f8b1e9a0f3c0ec66dd777db578fab07e/djangocms_installer/django/__init__.py#L69-L84
[ "def", "_detect_migration_layout", "(", "vars", ",", "apps", ")", ":", "DJANGO_MODULES", "=", "{", "}", "for", "module", "in", "vars", ".", "MIGRATIONS_CHECK_MODULES", ":", "if", "module", "in", "apps", ":", "try", ":", "mod", "=", "__import__", "(", "'{0}.migrations_django'", ".", "format", "(", "module", ")", ")", "# NOQA", "DJANGO_MODULES", "[", "module", "]", "=", "'{0}.migrations_django'", ".", "format", "(", "module", ")", "except", "Exception", ":", "pass", "return", "DJANGO_MODULES" ]
9fec66d5f8b1e9a0f3c0ec66dd777db578fab07e
valid
_install_aldryn
Install aldryn boilerplate :param config_data: configuration data
djangocms_installer/django/__init__.py
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.project_directory, 'dist', 'static') template_target = os.path.join(config_data.project_directory, 'templates') tmpdir = tempfile.mkdtemp() aldrynzip = requests.get(data.ALDRYN_BOILERPLATE) zip_open = zipfile.ZipFile(BytesIO(aldrynzip.content)) zip_open.extractall(path=tmpdir) for component in os.listdir(os.path.join(tmpdir, 'aldryn-boilerplate-standard-master')): src = os.path.join(tmpdir, 'aldryn-boilerplate-standard-master', component) dst = os.path.join(config_data.project_directory, component) if os.path.isfile(src): shutil.copy(src, dst) else: shutil.copytree(src, dst) shutil.rmtree(tmpdir) return media_project, static_main, static_project, template_target
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.project_directory, 'dist', 'static') template_target = os.path.join(config_data.project_directory, 'templates') tmpdir = tempfile.mkdtemp() aldrynzip = requests.get(data.ALDRYN_BOILERPLATE) zip_open = zipfile.ZipFile(BytesIO(aldrynzip.content)) zip_open.extractall(path=tmpdir) for component in os.listdir(os.path.join(tmpdir, 'aldryn-boilerplate-standard-master')): src = os.path.join(tmpdir, 'aldryn-boilerplate-standard-master', component) dst = os.path.join(config_data.project_directory, component) if os.path.isfile(src): shutil.copy(src, dst) else: shutil.copytree(src, dst) shutil.rmtree(tmpdir) return media_project, static_main, static_project, template_target
[ "Install", "aldryn", "boilerplate" ]
nephila/djangocms-installer
python
https://github.com/nephila/djangocms-installer/blob/9fec66d5f8b1e9a0f3c0ec66dd777db578fab07e/djangocms_installer/django/__init__.py#L87-L110
[ "def", "_install_aldryn", "(", "config_data", ")", ":", "# pragma: no cover", "import", "requests", "media_project", "=", "os", ".", "path", ".", "join", "(", "config_data", ".", "project_directory", ",", "'dist'", ",", "'media'", ")", "static_main", "=", "False", "static_project", "=", "os", ".", "path", ".", "join", "(", "config_data", ".", "project_directory", ",", "'dist'", ",", "'static'", ")", "template_target", "=", "os", ".", "path", ".", "join", "(", "config_data", ".", "project_directory", ",", "'templates'", ")", "tmpdir", "=", "tempfile", ".", "mkdtemp", "(", ")", "aldrynzip", "=", "requests", ".", "get", "(", "data", ".", "ALDRYN_BOILERPLATE", ")", "zip_open", "=", "zipfile", ".", "ZipFile", "(", "BytesIO", "(", "aldrynzip", ".", "content", ")", ")", "zip_open", ".", "extractall", "(", "path", "=", "tmpdir", ")", "for", "component", "in", "os", ".", "listdir", "(", "os", ".", "path", ".", "join", "(", "tmpdir", ",", "'aldryn-boilerplate-standard-master'", ")", ")", ":", "src", "=", "os", ".", "path", ".", "join", "(", "tmpdir", ",", "'aldryn-boilerplate-standard-master'", ",", "component", ")", "dst", "=", "os", ".", "path", ".", "join", "(", "config_data", ".", "project_directory", ",", "component", ")", "if", "os", ".", "path", ".", "isfile", "(", "src", ")", ":", "shutil", ".", "copy", "(", "src", ",", "dst", ")", "else", ":", "shutil", ".", "copytree", "(", "src", ",", "dst", ")", "shutil", ".", "rmtree", "(", "tmpdir", ")", "return", "media_project", ",", "static_main", ",", "static_project", ",", "template_target" ]
9fec66d5f8b1e9a0f3c0ec66dd777db578fab07e
valid
copy_files
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
djangocms_installer/django/__init__.py
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.dirname(__file__), '../config/urls_i18n.py') else: urlconf_path = os.path.join(os.path.dirname(__file__), '../config/urls_noi18n.py') share_path = os.path.join(os.path.dirname(__file__), '../share') template_path = os.path.join(share_path, 'templates') if config_data.aldryn: # pragma: no cover media_project, static_main, static_project, template_target = _install_aldryn(config_data) else: media_project = os.path.join(config_data.project_directory, 'media') static_main = os.path.join(config_data.project_path, 'static') static_project = os.path.join(config_data.project_directory, 'static') template_target = os.path.join(config_data.project_path, 'templates') if config_data.templates and os.path.isdir(config_data.templates): template_path = config_data.templates elif config_data.bootstrap: template_path = os.path.join(template_path, 'bootstrap') else: template_path = os.path.join(template_path, 'basic') shutil.copy(urlconf_path, config_data.urlconf_path) if media_project: os.makedirs(media_project) if static_main: os.makedirs(static_main) if not os.path.exists(static_project): os.makedirs(static_project) if not os.path.exists(template_target): os.makedirs(template_target) for filename in glob.glob(os.path.join(template_path, '*.html')): if os.path.isfile(filename): shutil.copy(filename, template_target) if config_data.noinput and not config_data.no_user: script_path = os.path.join(share_path, 'create_user.py') if os.path.isfile(script_path): shutil.copy(script_path, os.path.join(config_data.project_path, '..')) if config_data.starting_page: for filename in glob.glob(os.path.join(share_path, 'starting_page.*')): if os.path.isfile(filename): shutil.copy(filename, os.path.join(config_data.project_path, '..'))
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.dirname(__file__), '../config/urls_i18n.py') else: urlconf_path = os.path.join(os.path.dirname(__file__), '../config/urls_noi18n.py') share_path = os.path.join(os.path.dirname(__file__), '../share') template_path = os.path.join(share_path, 'templates') if config_data.aldryn: # pragma: no cover media_project, static_main, static_project, template_target = _install_aldryn(config_data) else: media_project = os.path.join(config_data.project_directory, 'media') static_main = os.path.join(config_data.project_path, 'static') static_project = os.path.join(config_data.project_directory, 'static') template_target = os.path.join(config_data.project_path, 'templates') if config_data.templates and os.path.isdir(config_data.templates): template_path = config_data.templates elif config_data.bootstrap: template_path = os.path.join(template_path, 'bootstrap') else: template_path = os.path.join(template_path, 'basic') shutil.copy(urlconf_path, config_data.urlconf_path) if media_project: os.makedirs(media_project) if static_main: os.makedirs(static_main) if not os.path.exists(static_project): os.makedirs(static_project) if not os.path.exists(template_target): os.makedirs(template_target) for filename in glob.glob(os.path.join(template_path, '*.html')): if os.path.isfile(filename): shutil.copy(filename, template_target) if config_data.noinput and not config_data.no_user: script_path = os.path.join(share_path, 'create_user.py') if os.path.isfile(script_path): shutil.copy(script_path, os.path.join(config_data.project_path, '..')) if config_data.starting_page: for filename in glob.glob(os.path.join(share_path, 'starting_page.*')): if os.path.isfile(filename): shutil.copy(filename, os.path.join(config_data.project_path, '..'))
[ "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", "." ]
nephila/djangocms-installer
python
https://github.com/nephila/djangocms-installer/blob/9fec66d5f8b1e9a0f3c0ec66dd777db578fab07e/djangocms_installer/django/__init__.py#L113-L161
[ "def", "copy_files", "(", "config_data", ")", ":", "if", "config_data", ".", "i18n", "==", "'yes'", ":", "urlconf_path", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "'../config/urls_i18n.py'", ")", "else", ":", "urlconf_path", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "'../config/urls_noi18n.py'", ")", "share_path", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "'../share'", ")", "template_path", "=", "os", ".", "path", ".", "join", "(", "share_path", ",", "'templates'", ")", "if", "config_data", ".", "aldryn", ":", "# pragma: no cover", "media_project", ",", "static_main", ",", "static_project", ",", "template_target", "=", "_install_aldryn", "(", "config_data", ")", "else", ":", "media_project", "=", "os", ".", "path", ".", "join", "(", "config_data", ".", "project_directory", ",", "'media'", ")", "static_main", "=", "os", ".", "path", ".", "join", "(", "config_data", ".", "project_path", ",", "'static'", ")", "static_project", "=", "os", ".", "path", ".", "join", "(", "config_data", ".", "project_directory", ",", "'static'", ")", "template_target", "=", "os", ".", "path", ".", "join", "(", "config_data", ".", "project_path", ",", "'templates'", ")", "if", "config_data", ".", "templates", "and", "os", ".", "path", ".", "isdir", "(", "config_data", ".", "templates", ")", ":", "template_path", "=", "config_data", ".", "templates", "elif", "config_data", ".", "bootstrap", ":", "template_path", "=", "os", ".", "path", ".", "join", "(", "template_path", ",", "'bootstrap'", ")", "else", ":", "template_path", "=", "os", ".", "path", ".", "join", "(", "template_path", ",", "'basic'", ")", "shutil", ".", "copy", "(", "urlconf_path", ",", "config_data", ".", "urlconf_path", ")", "if", "media_project", ":", "os", ".", "makedirs", "(", "media_project", ")", "if", "static_main", ":", "os", ".", "makedirs", "(", "static_main", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "static_project", ")", ":", "os", ".", "makedirs", "(", "static_project", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "template_target", ")", ":", "os", ".", "makedirs", "(", "template_target", ")", "for", "filename", "in", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "template_path", ",", "'*.html'", ")", ")", ":", "if", "os", ".", "path", ".", "isfile", "(", "filename", ")", ":", "shutil", ".", "copy", "(", "filename", ",", "template_target", ")", "if", "config_data", ".", "noinput", "and", "not", "config_data", ".", "no_user", ":", "script_path", "=", "os", ".", "path", ".", "join", "(", "share_path", ",", "'create_user.py'", ")", "if", "os", ".", "path", ".", "isfile", "(", "script_path", ")", ":", "shutil", ".", "copy", "(", "script_path", ",", "os", ".", "path", ".", "join", "(", "config_data", ".", "project_path", ",", "'..'", ")", ")", "if", "config_data", ".", "starting_page", ":", "for", "filename", "in", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "share_path", ",", "'starting_page.*'", ")", ")", ":", "if", "os", ".", "path", ".", "isfile", "(", "filename", ")", ":", "shutil", ".", "copy", "(", "filename", ",", "os", ".", "path", ".", "join", "(", "config_data", ".", "project_path", ",", "'..'", ")", ")" ]
9fec66d5f8b1e9a0f3c0ec66dd777db578fab07e
valid
patch_settings
Modify the settings file created by Django injecting the django CMS configuration :param config_data: configuration data
djangocms_installer/django/__init__.py
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.django_version) if not os.path.exists(config_data.settings_path): sys.stderr.write( 'Error while creating target project, ' 'please check the given configuration: {0}\n'.format(config_data.settings_path) ) return sys.exit(5) if current_django_version.version[:2] != declared_django_version.version[:2]: sys.stderr.write( 'Currently installed Django version {} differs from the declared {}. ' 'Please check the given `--django-version` installer argument, your virtualenv ' 'configuration and any package forcing a different Django version' '\n'.format( current_django_version, declared_django_version ) ) return sys.exit(9) overridden_settings = ( 'MIDDLEWARE_CLASSES', 'MIDDLEWARE', 'INSTALLED_APPS', 'TEMPLATE_LOADERS', 'TEMPLATE_CONTEXT_PROCESSORS', 'TEMPLATE_DIRS', 'LANGUAGES' ) extra_settings = '' with open(config_data.settings_path, 'r') as fd_original: original = fd_original.read() # extra settings reading if config_data.extra_settings and os.path.exists(config_data.extra_settings): with open(config_data.extra_settings, 'r') as fd_extra: extra_settings = fd_extra.read() original = original.replace('# -*- coding: utf-8 -*-\n', '') if config_data.aldryn: # pragma: no cover DATA_DIR = ( 'DATA_DIR = os.path.join(os.path.dirname(os.path.dirname(__file__)), \'dist\')\n' ) STATICFILES_DIR = 'os.path.join(BASE_DIR, \'static\'),' else: DATA_DIR = 'DATA_DIR = os.path.dirname(os.path.dirname(__file__))\n' STATICFILES_DIR = 'os.path.join(BASE_DIR, \'{0}\', \'static\'),'.format( config_data.project_name ) original = data.DEFAULT_PROJECT_HEADER + DATA_DIR + original original += 'MEDIA_URL = \'/media/\'\n' original += 'MEDIA_ROOT = os.path.join(DATA_DIR, \'media\')\n' original += 'STATIC_ROOT = os.path.join(DATA_DIR, \'static\')\n' original += """ STATICFILES_DIRS = ( {0} ) """.format(STATICFILES_DIR) original = original.replace('# -*- coding: utf-8 -*-\n', '') # I18N if config_data.i18n == 'no': original = original.replace('I18N = True', 'I18N = False') original = original.replace('L10N = True', 'L10N = False') # TZ if config_data.use_timezone == 'no': original = original.replace('USE_TZ = True', 'USE_TZ = False') if config_data.languages: original = original.replace( 'LANGUAGE_CODE = \'en-us\'', 'LANGUAGE_CODE = \'{0}\''.format(config_data.languages[0]) ) if config_data.timezone: original = original.replace( 'TIME_ZONE = \'UTC\'', 'TIME_ZONE = \'{0}\''.format(config_data.timezone) ) for item in overridden_settings: if declared_django_version >= LooseVersion('1.9'): item_re = re.compile(r'{0} = [^\]]+\]'.format(item), re.DOTALL | re.MULTILINE) else: item_re = re.compile(r'{0} = [^\)]+\)'.format(item), re.DOTALL | re.MULTILINE) original = item_re.sub('', original) # TEMPLATES is special, so custom regexp needed if declared_django_version >= LooseVersion('2.0'): item_re = re.compile(r'TEMPLATES = .+\},\n\s+\},\n]$', re.DOTALL | re.MULTILINE) else: item_re = re.compile(r'TEMPLATES = .+\]$', re.DOTALL | re.MULTILINE) original = item_re.sub('', original) # DATABASES is a dictionary, so different regexp needed item_re = re.compile(r'DATABASES = [^\}]+\}[^\}]+\}', re.DOTALL | re.MULTILINE) original = item_re.sub('', original) if original.find('SITE_ID') == -1: original += 'SITE_ID = 1\n\n' original += _build_settings(config_data) # Append extra settings at the end of the file original += ('\n' + extra_settings) with open(config_data.settings_path, 'w') as fd_dest: fd_dest.write(original)
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.django_version) if not os.path.exists(config_data.settings_path): sys.stderr.write( 'Error while creating target project, ' 'please check the given configuration: {0}\n'.format(config_data.settings_path) ) return sys.exit(5) if current_django_version.version[:2] != declared_django_version.version[:2]: sys.stderr.write( 'Currently installed Django version {} differs from the declared {}. ' 'Please check the given `--django-version` installer argument, your virtualenv ' 'configuration and any package forcing a different Django version' '\n'.format( current_django_version, declared_django_version ) ) return sys.exit(9) overridden_settings = ( 'MIDDLEWARE_CLASSES', 'MIDDLEWARE', 'INSTALLED_APPS', 'TEMPLATE_LOADERS', 'TEMPLATE_CONTEXT_PROCESSORS', 'TEMPLATE_DIRS', 'LANGUAGES' ) extra_settings = '' with open(config_data.settings_path, 'r') as fd_original: original = fd_original.read() # extra settings reading if config_data.extra_settings and os.path.exists(config_data.extra_settings): with open(config_data.extra_settings, 'r') as fd_extra: extra_settings = fd_extra.read() original = original.replace('# -*- coding: utf-8 -*-\n', '') if config_data.aldryn: # pragma: no cover DATA_DIR = ( 'DATA_DIR = os.path.join(os.path.dirname(os.path.dirname(__file__)), \'dist\')\n' ) STATICFILES_DIR = 'os.path.join(BASE_DIR, \'static\'),' else: DATA_DIR = 'DATA_DIR = os.path.dirname(os.path.dirname(__file__))\n' STATICFILES_DIR = 'os.path.join(BASE_DIR, \'{0}\', \'static\'),'.format( config_data.project_name ) original = data.DEFAULT_PROJECT_HEADER + DATA_DIR + original original += 'MEDIA_URL = \'/media/\'\n' original += 'MEDIA_ROOT = os.path.join(DATA_DIR, \'media\')\n' original += 'STATIC_ROOT = os.path.join(DATA_DIR, \'static\')\n' original += """ STATICFILES_DIRS = ( {0} ) """.format(STATICFILES_DIR) original = original.replace('# -*- coding: utf-8 -*-\n', '') # I18N if config_data.i18n == 'no': original = original.replace('I18N = True', 'I18N = False') original = original.replace('L10N = True', 'L10N = False') # TZ if config_data.use_timezone == 'no': original = original.replace('USE_TZ = True', 'USE_TZ = False') if config_data.languages: original = original.replace( 'LANGUAGE_CODE = \'en-us\'', 'LANGUAGE_CODE = \'{0}\''.format(config_data.languages[0]) ) if config_data.timezone: original = original.replace( 'TIME_ZONE = \'UTC\'', 'TIME_ZONE = \'{0}\''.format(config_data.timezone) ) for item in overridden_settings: if declared_django_version >= LooseVersion('1.9'): item_re = re.compile(r'{0} = [^\]]+\]'.format(item), re.DOTALL | re.MULTILINE) else: item_re = re.compile(r'{0} = [^\)]+\)'.format(item), re.DOTALL | re.MULTILINE) original = item_re.sub('', original) # TEMPLATES is special, so custom regexp needed if declared_django_version >= LooseVersion('2.0'): item_re = re.compile(r'TEMPLATES = .+\},\n\s+\},\n]$', re.DOTALL | re.MULTILINE) else: item_re = re.compile(r'TEMPLATES = .+\]$', re.DOTALL | re.MULTILINE) original = item_re.sub('', original) # DATABASES is a dictionary, so different regexp needed item_re = re.compile(r'DATABASES = [^\}]+\}[^\}]+\}', re.DOTALL | re.MULTILINE) original = item_re.sub('', original) if original.find('SITE_ID') == -1: original += 'SITE_ID = 1\n\n' original += _build_settings(config_data) # Append extra settings at the end of the file original += ('\n' + extra_settings) with open(config_data.settings_path, 'w') as fd_dest: fd_dest.write(original)
[ "Modify", "the", "settings", "file", "created", "by", "Django", "injecting", "the", "django", "CMS", "configuration" ]
nephila/djangocms-installer
python
https://github.com/nephila/djangocms-installer/blob/9fec66d5f8b1e9a0f3c0ec66dd777db578fab07e/djangocms_installer/django/__init__.py#L164-L272
[ "def", "patch_settings", "(", "config_data", ")", ":", "import", "django", "current_django_version", "=", "LooseVersion", "(", "django", ".", "__version__", ")", "declared_django_version", "=", "LooseVersion", "(", "config_data", ".", "django_version", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "config_data", ".", "settings_path", ")", ":", "sys", ".", "stderr", ".", "write", "(", "'Error while creating target project, '", "'please check the given configuration: {0}\\n'", ".", "format", "(", "config_data", ".", "settings_path", ")", ")", "return", "sys", ".", "exit", "(", "5", ")", "if", "current_django_version", ".", "version", "[", ":", "2", "]", "!=", "declared_django_version", ".", "version", "[", ":", "2", "]", ":", "sys", ".", "stderr", ".", "write", "(", "'Currently installed Django version {} differs from the declared {}. '", "'Please check the given `--django-version` installer argument, your virtualenv '", "'configuration and any package forcing a different Django version'", "'\\n'", ".", "format", "(", "current_django_version", ",", "declared_django_version", ")", ")", "return", "sys", ".", "exit", "(", "9", ")", "overridden_settings", "=", "(", "'MIDDLEWARE_CLASSES'", ",", "'MIDDLEWARE'", ",", "'INSTALLED_APPS'", ",", "'TEMPLATE_LOADERS'", ",", "'TEMPLATE_CONTEXT_PROCESSORS'", ",", "'TEMPLATE_DIRS'", ",", "'LANGUAGES'", ")", "extra_settings", "=", "''", "with", "open", "(", "config_data", ".", "settings_path", ",", "'r'", ")", "as", "fd_original", ":", "original", "=", "fd_original", ".", "read", "(", ")", "# extra settings reading", "if", "config_data", ".", "extra_settings", "and", "os", ".", "path", ".", "exists", "(", "config_data", ".", "extra_settings", ")", ":", "with", "open", "(", "config_data", ".", "extra_settings", ",", "'r'", ")", "as", "fd_extra", ":", "extra_settings", "=", "fd_extra", ".", "read", "(", ")", "original", "=", "original", ".", "replace", "(", "'# -*- coding: utf-8 -*-\\n'", ",", "''", ")", "if", "config_data", ".", "aldryn", ":", "# pragma: no cover", "DATA_DIR", "=", "(", "'DATA_DIR = os.path.join(os.path.dirname(os.path.dirname(__file__)), \\'dist\\')\\n'", ")", "STATICFILES_DIR", "=", "'os.path.join(BASE_DIR, \\'static\\'),'", "else", ":", "DATA_DIR", "=", "'DATA_DIR = os.path.dirname(os.path.dirname(__file__))\\n'", "STATICFILES_DIR", "=", "'os.path.join(BASE_DIR, \\'{0}\\', \\'static\\'),'", ".", "format", "(", "config_data", ".", "project_name", ")", "original", "=", "data", ".", "DEFAULT_PROJECT_HEADER", "+", "DATA_DIR", "+", "original", "original", "+=", "'MEDIA_URL = \\'/media/\\'\\n'", "original", "+=", "'MEDIA_ROOT = os.path.join(DATA_DIR, \\'media\\')\\n'", "original", "+=", "'STATIC_ROOT = os.path.join(DATA_DIR, \\'static\\')\\n'", "original", "+=", "\"\"\"\nSTATICFILES_DIRS = (\n {0}\n)\n\"\"\"", ".", "format", "(", "STATICFILES_DIR", ")", "original", "=", "original", ".", "replace", "(", "'# -*- coding: utf-8 -*-\\n'", ",", "''", ")", "# I18N", "if", "config_data", ".", "i18n", "==", "'no'", ":", "original", "=", "original", ".", "replace", "(", "'I18N = True'", ",", "'I18N = False'", ")", "original", "=", "original", ".", "replace", "(", "'L10N = True'", ",", "'L10N = False'", ")", "# TZ", "if", "config_data", ".", "use_timezone", "==", "'no'", ":", "original", "=", "original", ".", "replace", "(", "'USE_TZ = True'", ",", "'USE_TZ = False'", ")", "if", "config_data", ".", "languages", ":", "original", "=", "original", ".", "replace", "(", "'LANGUAGE_CODE = \\'en-us\\''", ",", "'LANGUAGE_CODE = \\'{0}\\''", ".", "format", "(", "config_data", ".", "languages", "[", "0", "]", ")", ")", "if", "config_data", ".", "timezone", ":", "original", "=", "original", ".", "replace", "(", "'TIME_ZONE = \\'UTC\\''", ",", "'TIME_ZONE = \\'{0}\\''", ".", "format", "(", "config_data", ".", "timezone", ")", ")", "for", "item", "in", "overridden_settings", ":", "if", "declared_django_version", ">=", "LooseVersion", "(", "'1.9'", ")", ":", "item_re", "=", "re", ".", "compile", "(", "r'{0} = [^\\]]+\\]'", ".", "format", "(", "item", ")", ",", "re", ".", "DOTALL", "|", "re", ".", "MULTILINE", ")", "else", ":", "item_re", "=", "re", ".", "compile", "(", "r'{0} = [^\\)]+\\)'", ".", "format", "(", "item", ")", ",", "re", ".", "DOTALL", "|", "re", ".", "MULTILINE", ")", "original", "=", "item_re", ".", "sub", "(", "''", ",", "original", ")", "# TEMPLATES is special, so custom regexp needed", "if", "declared_django_version", ">=", "LooseVersion", "(", "'2.0'", ")", ":", "item_re", "=", "re", ".", "compile", "(", "r'TEMPLATES = .+\\},\\n\\s+\\},\\n]$'", ",", "re", ".", "DOTALL", "|", "re", ".", "MULTILINE", ")", "else", ":", "item_re", "=", "re", ".", "compile", "(", "r'TEMPLATES = .+\\]$'", ",", "re", ".", "DOTALL", "|", "re", ".", "MULTILINE", ")", "original", "=", "item_re", ".", "sub", "(", "''", ",", "original", ")", "# DATABASES is a dictionary, so different regexp needed", "item_re", "=", "re", ".", "compile", "(", "r'DATABASES = [^\\}]+\\}[^\\}]+\\}'", ",", "re", ".", "DOTALL", "|", "re", ".", "MULTILINE", ")", "original", "=", "item_re", ".", "sub", "(", "''", ",", "original", ")", "if", "original", ".", "find", "(", "'SITE_ID'", ")", "==", "-", "1", ":", "original", "+=", "'SITE_ID = 1\\n\\n'", "original", "+=", "_build_settings", "(", "config_data", ")", "# Append extra settings at the end of the file", "original", "+=", "(", "'\\n'", "+", "extra_settings", ")", "with", "open", "(", "config_data", ".", "settings_path", ",", "'w'", ")", "as", "fd_dest", ":", "fd_dest", ".", "write", "(", "original", ")" ]
9fec66d5f8b1e9a0f3c0ec66dd777db578fab07e
valid
_build_settings
Build the django CMS settings dictionary :param config_data: configuration data
djangocms_installer/django/__init__.py
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_PROCESSORS + vars.TEMPLATE_CONTEXT_PROCESSORS_3 text.append(data.TEMPLATES_1_8.format( loaders=(',\n' + spacer * 4).join([ "'{0}'".format(var) for var in vars.TEMPLATE_LOADERS if ( LooseVersion(config_data.django_version) < LooseVersion('2.0') or 'eggs' not in var ) ]), processors=(',\n' + spacer * 4).join(["'{0}'".format(var) for var in processors]), dirs="os.path.join(BASE_DIR, '{0}', 'templates'),".format(config_data.project_name) )) if LooseVersion(config_data.django_version) >= LooseVersion('1.10'): text.append('MIDDLEWARE = [\n{0}{1}\n]'.format( spacer, (',\n' + spacer).join(['\'{0}\''.format(var) for var in vars.MIDDLEWARE_CLASSES]) )) else: text.append('MIDDLEWARE_CLASSES = [\n{0}{1}\n]'.format( spacer, (',\n' + spacer).join(["'{0}'".format(var) for var in vars.MIDDLEWARE_CLASSES]) )) apps = list(vars.INSTALLED_APPS) apps = list(vars.CMS_3_HEAD) + apps apps.extend(vars.TREEBEARD_APPS) apps.extend(vars.CMS_3_APPLICATIONS) if not config_data.no_plugins: apps.extend(vars.FILER_PLUGINS_3) if config_data.aldryn: # pragma: no cover apps.extend(vars.ALDRYN_APPLICATIONS) if config_data.reversion and LooseVersion(config_data.cms_version) < LooseVersion('3.4'): apps.extend(vars.REVERSION_APPLICATIONS) text.append('INSTALLED_APPS = [\n{0}{1}\n]'.format( spacer, (',\n' + spacer).join(['\'{0}\''.format(var) for var in apps] + ['\'{0}\''.format(config_data.project_name)]) )) text.append('LANGUAGES = (\n{0}{1}\n{0}{2}\n)'.format( spacer, '## Customize this', ('\n' + spacer).join(['(\'{0}\', gettext(\'{0}\')),'.format(item) for item in config_data.languages]) # NOQA )) cms_langs = deepcopy(vars.CMS_LANGUAGES) for lang in config_data.languages: lang_dict = {'code': lang, 'name': lang} lang_dict.update(copy(cms_langs['default'])) cms_langs[1].append(lang_dict) cms_text = ['CMS_LANGUAGES = {'] cms_text.append('{0}{1}'.format(spacer, '## Customize this')) for key, value in iteritems(cms_langs): if key == 'default': cms_text.append('{0}\'{1}\': {{'.format(spacer, key)) for config_name, config_value in iteritems(value): cms_text.append('{0}\'{1}\': {2},'.format(spacer * 2, config_name, config_value)) cms_text.append('{0}}},'.format(spacer)) else: cms_text.append('{0}{1}: ['.format(spacer, key)) for lang in value: cms_text.append('{0}{{'.format(spacer * 2)) for config_name, config_value in iteritems(lang): if config_name == 'code': cms_text.append('{0}\'{1}\': \'{2}\','.format(spacer * 3, config_name, config_value)) # NOQA elif config_name == 'name': cms_text.append('{0}\'{1}\': gettext(\'{2}\'),'.format(spacer * 3, config_name, config_value)) # NOQA else: cms_text.append('{0}\'{1}\': {2},'.format( spacer * 3, config_name, config_value )) cms_text.append('{0}}},'.format(spacer * 2)) cms_text.append('{0}],'.format(spacer)) cms_text.append('}') text.append('\n'.join(cms_text)) if config_data.bootstrap: cms_templates = 'CMS_TEMPLATES_BOOTSTRAP' else: cms_templates = 'CMS_TEMPLATES' text.append('CMS_TEMPLATES = (\n{0}{1}\n{0}{2}\n)'.format( spacer, '## Customize this', (',\n' + spacer).join( ['(\'{0}\', \'{1}\')'.format(*item) for item in getattr(vars, cms_templates)] ) )) text.append('CMS_PERMISSION = {0}'.format(vars.CMS_PERMISSION)) text.append('CMS_PLACEHOLDER_CONF = {0}'.format(vars.CMS_PLACEHOLDER_CONF)) database = ['\'{0}\': {1}'.format(key, format_val(val)) for key, val in sorted(config_data.db_parsed.items(), key=lambda x: x[0])] # NOQA text.append(textwrap.dedent(""" DATABASES = {{ 'default': {{ {0} }} }}""").strip().format((',\n' + spacer * 2).join(database))) # NOQA DJANGO_MIGRATION_MODULES = _detect_migration_layout(vars, apps) text.append('MIGRATION_MODULES = {{\n{0}{1}\n}}'.format( spacer, (',\n' + spacer).join( ['\'{0}\': \'{1}\''.format(*item) for item in DJANGO_MIGRATION_MODULES.items()] ) )) if config_data.filer: text.append('THUMBNAIL_PROCESSORS = (\n{0}{1}\n)'.format( spacer, (',\n' + spacer).join( ['\'{0}\''.format(var) for var in vars.THUMBNAIL_PROCESSORS] ) )) return '\n\n'.join(text)
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_PROCESSORS + vars.TEMPLATE_CONTEXT_PROCESSORS_3 text.append(data.TEMPLATES_1_8.format( loaders=(',\n' + spacer * 4).join([ "'{0}'".format(var) for var in vars.TEMPLATE_LOADERS if ( LooseVersion(config_data.django_version) < LooseVersion('2.0') or 'eggs' not in var ) ]), processors=(',\n' + spacer * 4).join(["'{0}'".format(var) for var in processors]), dirs="os.path.join(BASE_DIR, '{0}', 'templates'),".format(config_data.project_name) )) if LooseVersion(config_data.django_version) >= LooseVersion('1.10'): text.append('MIDDLEWARE = [\n{0}{1}\n]'.format( spacer, (',\n' + spacer).join(['\'{0}\''.format(var) for var in vars.MIDDLEWARE_CLASSES]) )) else: text.append('MIDDLEWARE_CLASSES = [\n{0}{1}\n]'.format( spacer, (',\n' + spacer).join(["'{0}'".format(var) for var in vars.MIDDLEWARE_CLASSES]) )) apps = list(vars.INSTALLED_APPS) apps = list(vars.CMS_3_HEAD) + apps apps.extend(vars.TREEBEARD_APPS) apps.extend(vars.CMS_3_APPLICATIONS) if not config_data.no_plugins: apps.extend(vars.FILER_PLUGINS_3) if config_data.aldryn: # pragma: no cover apps.extend(vars.ALDRYN_APPLICATIONS) if config_data.reversion and LooseVersion(config_data.cms_version) < LooseVersion('3.4'): apps.extend(vars.REVERSION_APPLICATIONS) text.append('INSTALLED_APPS = [\n{0}{1}\n]'.format( spacer, (',\n' + spacer).join(['\'{0}\''.format(var) for var in apps] + ['\'{0}\''.format(config_data.project_name)]) )) text.append('LANGUAGES = (\n{0}{1}\n{0}{2}\n)'.format( spacer, '## Customize this', ('\n' + spacer).join(['(\'{0}\', gettext(\'{0}\')),'.format(item) for item in config_data.languages]) # NOQA )) cms_langs = deepcopy(vars.CMS_LANGUAGES) for lang in config_data.languages: lang_dict = {'code': lang, 'name': lang} lang_dict.update(copy(cms_langs['default'])) cms_langs[1].append(lang_dict) cms_text = ['CMS_LANGUAGES = {'] cms_text.append('{0}{1}'.format(spacer, '## Customize this')) for key, value in iteritems(cms_langs): if key == 'default': cms_text.append('{0}\'{1}\': {{'.format(spacer, key)) for config_name, config_value in iteritems(value): cms_text.append('{0}\'{1}\': {2},'.format(spacer * 2, config_name, config_value)) cms_text.append('{0}}},'.format(spacer)) else: cms_text.append('{0}{1}: ['.format(spacer, key)) for lang in value: cms_text.append('{0}{{'.format(spacer * 2)) for config_name, config_value in iteritems(lang): if config_name == 'code': cms_text.append('{0}\'{1}\': \'{2}\','.format(spacer * 3, config_name, config_value)) # NOQA elif config_name == 'name': cms_text.append('{0}\'{1}\': gettext(\'{2}\'),'.format(spacer * 3, config_name, config_value)) # NOQA else: cms_text.append('{0}\'{1}\': {2},'.format( spacer * 3, config_name, config_value )) cms_text.append('{0}}},'.format(spacer * 2)) cms_text.append('{0}],'.format(spacer)) cms_text.append('}') text.append('\n'.join(cms_text)) if config_data.bootstrap: cms_templates = 'CMS_TEMPLATES_BOOTSTRAP' else: cms_templates = 'CMS_TEMPLATES' text.append('CMS_TEMPLATES = (\n{0}{1}\n{0}{2}\n)'.format( spacer, '## Customize this', (',\n' + spacer).join( ['(\'{0}\', \'{1}\')'.format(*item) for item in getattr(vars, cms_templates)] ) )) text.append('CMS_PERMISSION = {0}'.format(vars.CMS_PERMISSION)) text.append('CMS_PLACEHOLDER_CONF = {0}'.format(vars.CMS_PLACEHOLDER_CONF)) database = ['\'{0}\': {1}'.format(key, format_val(val)) for key, val in sorted(config_data.db_parsed.items(), key=lambda x: x[0])] # NOQA text.append(textwrap.dedent(""" DATABASES = {{ 'default': {{ {0} }} }}""").strip().format((',\n' + spacer * 2).join(database))) # NOQA DJANGO_MIGRATION_MODULES = _detect_migration_layout(vars, apps) text.append('MIGRATION_MODULES = {{\n{0}{1}\n}}'.format( spacer, (',\n' + spacer).join( ['\'{0}\': \'{1}\''.format(*item) for item in DJANGO_MIGRATION_MODULES.items()] ) )) if config_data.filer: text.append('THUMBNAIL_PROCESSORS = (\n{0}{1}\n)'.format( spacer, (',\n' + spacer).join( ['\'{0}\''.format(var) for var in vars.THUMBNAIL_PROCESSORS] ) )) return '\n\n'.join(text)
[ "Build", "the", "django", "CMS", "settings", "dictionary" ]
nephila/djangocms-installer
python
https://github.com/nephila/djangocms-installer/blob/9fec66d5f8b1e9a0f3c0ec66dd777db578fab07e/djangocms_installer/django/__init__.py#L275-L402
[ "def", "_build_settings", "(", "config_data", ")", ":", "spacer", "=", "' '", "text", "=", "[", "]", "vars", "=", "get_settings", "(", ")", "vars", ".", "MIDDLEWARE_CLASSES", ".", "insert", "(", "0", ",", "vars", ".", "APPHOOK_RELOAD_MIDDLEWARE_CLASS", ")", "processors", "=", "vars", ".", "TEMPLATE_CONTEXT_PROCESSORS", "+", "vars", ".", "TEMPLATE_CONTEXT_PROCESSORS_3", "text", ".", "append", "(", "data", ".", "TEMPLATES_1_8", ".", "format", "(", "loaders", "=", "(", "',\\n'", "+", "spacer", "*", "4", ")", ".", "join", "(", "[", "\"'{0}'\"", ".", "format", "(", "var", ")", "for", "var", "in", "vars", ".", "TEMPLATE_LOADERS", "if", "(", "LooseVersion", "(", "config_data", ".", "django_version", ")", "<", "LooseVersion", "(", "'2.0'", ")", "or", "'eggs'", "not", "in", "var", ")", "]", ")", ",", "processors", "=", "(", "',\\n'", "+", "spacer", "*", "4", ")", ".", "join", "(", "[", "\"'{0}'\"", ".", "format", "(", "var", ")", "for", "var", "in", "processors", "]", ")", ",", "dirs", "=", "\"os.path.join(BASE_DIR, '{0}', 'templates'),\"", ".", "format", "(", "config_data", ".", "project_name", ")", ")", ")", "if", "LooseVersion", "(", "config_data", ".", "django_version", ")", ">=", "LooseVersion", "(", "'1.10'", ")", ":", "text", ".", "append", "(", "'MIDDLEWARE = [\\n{0}{1}\\n]'", ".", "format", "(", "spacer", ",", "(", "',\\n'", "+", "spacer", ")", ".", "join", "(", "[", "'\\'{0}\\''", ".", "format", "(", "var", ")", "for", "var", "in", "vars", ".", "MIDDLEWARE_CLASSES", "]", ")", ")", ")", "else", ":", "text", ".", "append", "(", "'MIDDLEWARE_CLASSES = [\\n{0}{1}\\n]'", ".", "format", "(", "spacer", ",", "(", "',\\n'", "+", "spacer", ")", ".", "join", "(", "[", "\"'{0}'\"", ".", "format", "(", "var", ")", "for", "var", "in", "vars", ".", "MIDDLEWARE_CLASSES", "]", ")", ")", ")", "apps", "=", "list", "(", "vars", ".", "INSTALLED_APPS", ")", "apps", "=", "list", "(", "vars", ".", "CMS_3_HEAD", ")", "+", "apps", "apps", ".", "extend", "(", "vars", ".", "TREEBEARD_APPS", ")", "apps", ".", "extend", "(", "vars", ".", "CMS_3_APPLICATIONS", ")", "if", "not", "config_data", ".", "no_plugins", ":", "apps", ".", "extend", "(", "vars", ".", "FILER_PLUGINS_3", ")", "if", "config_data", ".", "aldryn", ":", "# pragma: no cover", "apps", ".", "extend", "(", "vars", ".", "ALDRYN_APPLICATIONS", ")", "if", "config_data", ".", "reversion", "and", "LooseVersion", "(", "config_data", ".", "cms_version", ")", "<", "LooseVersion", "(", "'3.4'", ")", ":", "apps", ".", "extend", "(", "vars", ".", "REVERSION_APPLICATIONS", ")", "text", ".", "append", "(", "'INSTALLED_APPS = [\\n{0}{1}\\n]'", ".", "format", "(", "spacer", ",", "(", "',\\n'", "+", "spacer", ")", ".", "join", "(", "[", "'\\'{0}\\''", ".", "format", "(", "var", ")", "for", "var", "in", "apps", "]", "+", "[", "'\\'{0}\\''", ".", "format", "(", "config_data", ".", "project_name", ")", "]", ")", ")", ")", "text", ".", "append", "(", "'LANGUAGES = (\\n{0}{1}\\n{0}{2}\\n)'", ".", "format", "(", "spacer", ",", "'## Customize this'", ",", "(", "'\\n'", "+", "spacer", ")", ".", "join", "(", "[", "'(\\'{0}\\', gettext(\\'{0}\\')),'", ".", "format", "(", "item", ")", "for", "item", "in", "config_data", ".", "languages", "]", ")", "# NOQA", ")", ")", "cms_langs", "=", "deepcopy", "(", "vars", ".", "CMS_LANGUAGES", ")", "for", "lang", "in", "config_data", ".", "languages", ":", "lang_dict", "=", "{", "'code'", ":", "lang", ",", "'name'", ":", "lang", "}", "lang_dict", ".", "update", "(", "copy", "(", "cms_langs", "[", "'default'", "]", ")", ")", "cms_langs", "[", "1", "]", ".", "append", "(", "lang_dict", ")", "cms_text", "=", "[", "'CMS_LANGUAGES = {'", "]", "cms_text", ".", "append", "(", "'{0}{1}'", ".", "format", "(", "spacer", ",", "'## Customize this'", ")", ")", "for", "key", ",", "value", "in", "iteritems", "(", "cms_langs", ")", ":", "if", "key", "==", "'default'", ":", "cms_text", ".", "append", "(", "'{0}\\'{1}\\': {{'", ".", "format", "(", "spacer", ",", "key", ")", ")", "for", "config_name", ",", "config_value", "in", "iteritems", "(", "value", ")", ":", "cms_text", ".", "append", "(", "'{0}\\'{1}\\': {2},'", ".", "format", "(", "spacer", "*", "2", ",", "config_name", ",", "config_value", ")", ")", "cms_text", ".", "append", "(", "'{0}}},'", ".", "format", "(", "spacer", ")", ")", "else", ":", "cms_text", ".", "append", "(", "'{0}{1}: ['", ".", "format", "(", "spacer", ",", "key", ")", ")", "for", "lang", "in", "value", ":", "cms_text", ".", "append", "(", "'{0}{{'", ".", "format", "(", "spacer", "*", "2", ")", ")", "for", "config_name", ",", "config_value", "in", "iteritems", "(", "lang", ")", ":", "if", "config_name", "==", "'code'", ":", "cms_text", ".", "append", "(", "'{0}\\'{1}\\': \\'{2}\\','", ".", "format", "(", "spacer", "*", "3", ",", "config_name", ",", "config_value", ")", ")", "# NOQA", "elif", "config_name", "==", "'name'", ":", "cms_text", ".", "append", "(", "'{0}\\'{1}\\': gettext(\\'{2}\\'),'", ".", "format", "(", "spacer", "*", "3", ",", "config_name", ",", "config_value", ")", ")", "# NOQA", "else", ":", "cms_text", ".", "append", "(", "'{0}\\'{1}\\': {2},'", ".", "format", "(", "spacer", "*", "3", ",", "config_name", ",", "config_value", ")", ")", "cms_text", ".", "append", "(", "'{0}}},'", ".", "format", "(", "spacer", "*", "2", ")", ")", "cms_text", ".", "append", "(", "'{0}],'", ".", "format", "(", "spacer", ")", ")", "cms_text", ".", "append", "(", "'}'", ")", "text", ".", "append", "(", "'\\n'", ".", "join", "(", "cms_text", ")", ")", "if", "config_data", ".", "bootstrap", ":", "cms_templates", "=", "'CMS_TEMPLATES_BOOTSTRAP'", "else", ":", "cms_templates", "=", "'CMS_TEMPLATES'", "text", ".", "append", "(", "'CMS_TEMPLATES = (\\n{0}{1}\\n{0}{2}\\n)'", ".", "format", "(", "spacer", ",", "'## Customize this'", ",", "(", "',\\n'", "+", "spacer", ")", ".", "join", "(", "[", "'(\\'{0}\\', \\'{1}\\')'", ".", "format", "(", "*", "item", ")", "for", "item", "in", "getattr", "(", "vars", ",", "cms_templates", ")", "]", ")", ")", ")", "text", ".", "append", "(", "'CMS_PERMISSION = {0}'", ".", "format", "(", "vars", ".", "CMS_PERMISSION", ")", ")", "text", ".", "append", "(", "'CMS_PLACEHOLDER_CONF = {0}'", ".", "format", "(", "vars", ".", "CMS_PLACEHOLDER_CONF", ")", ")", "database", "=", "[", "'\\'{0}\\': {1}'", ".", "format", "(", "key", ",", "format_val", "(", "val", ")", ")", "for", "key", ",", "val", "in", "sorted", "(", "config_data", ".", "db_parsed", ".", "items", "(", ")", ",", "key", "=", "lambda", "x", ":", "x", "[", "0", "]", ")", "]", "# NOQA", "text", ".", "append", "(", "textwrap", ".", "dedent", "(", "\"\"\"\n DATABASES = {{\n 'default': {{\n {0}\n }}\n }}\"\"\"", ")", ".", "strip", "(", ")", ".", "format", "(", "(", "',\\n'", "+", "spacer", "*", "2", ")", ".", "join", "(", "database", ")", ")", ")", "# NOQA", "DJANGO_MIGRATION_MODULES", "=", "_detect_migration_layout", "(", "vars", ",", "apps", ")", "text", ".", "append", "(", "'MIGRATION_MODULES = {{\\n{0}{1}\\n}}'", ".", "format", "(", "spacer", ",", "(", "',\\n'", "+", "spacer", ")", ".", "join", "(", "[", "'\\'{0}\\': \\'{1}\\''", ".", "format", "(", "*", "item", ")", "for", "item", "in", "DJANGO_MIGRATION_MODULES", ".", "items", "(", ")", "]", ")", ")", ")", "if", "config_data", ".", "filer", ":", "text", ".", "append", "(", "'THUMBNAIL_PROCESSORS = (\\n{0}{1}\\n)'", ".", "format", "(", "spacer", ",", "(", "',\\n'", "+", "spacer", ")", ".", "join", "(", "[", "'\\'{0}\\''", ".", "format", "(", "var", ")", "for", "var", "in", "vars", ".", "THUMBNAIL_PROCESSORS", "]", ")", ")", ")", "return", "'\\n\\n'", ".", "join", "(", "text", ")" ]
9fec66d5f8b1e9a0f3c0ec66dd777db578fab07e
valid
setup_database
Run the migrate command to create the database schema :param config_data: configuration data
djangocms_installer/django/__init__.py
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_data.project_name)) env[str('PYTHONPATH')] = str(os.pathsep.join(map(shlex_quote, sys.path))) commands = [] commands.append( [sys.executable, '-W', 'ignore', 'manage.py', 'migrate'], ) if config_data.verbose: sys.stdout.write( 'Database setup commands: {0}\n'.format( ', '.join([' '.join(cmd) for cmd in commands]) ) ) for command in commands: try: output = subprocess.check_output( command, env=env, stderr=subprocess.STDOUT ) sys.stdout.write(output.decode('utf-8')) except subprocess.CalledProcessError as e: # pragma: no cover if config_data.verbose: sys.stdout.write(e.output.decode('utf-8')) raise if not config_data.no_user: sys.stdout.write('Creating admin user\n') if config_data.noinput: create_user(config_data) else: subprocess.check_call(' '.join( [sys.executable, '-W', 'ignore', 'manage.py', 'createsuperuser'] ), shell=True, stderr=subprocess.STDOUT)
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_data.project_name)) env[str('PYTHONPATH')] = str(os.pathsep.join(map(shlex_quote, sys.path))) commands = [] commands.append( [sys.executable, '-W', 'ignore', 'manage.py', 'migrate'], ) if config_data.verbose: sys.stdout.write( 'Database setup commands: {0}\n'.format( ', '.join([' '.join(cmd) for cmd in commands]) ) ) for command in commands: try: output = subprocess.check_output( command, env=env, stderr=subprocess.STDOUT ) sys.stdout.write(output.decode('utf-8')) except subprocess.CalledProcessError as e: # pragma: no cover if config_data.verbose: sys.stdout.write(e.output.decode('utf-8')) raise if not config_data.no_user: sys.stdout.write('Creating admin user\n') if config_data.noinput: create_user(config_data) else: subprocess.check_call(' '.join( [sys.executable, '-W', 'ignore', 'manage.py', 'createsuperuser'] ), shell=True, stderr=subprocess.STDOUT)
[ "Run", "the", "migrate", "command", "to", "create", "the", "database", "schema" ]
nephila/djangocms-installer
python
https://github.com/nephila/djangocms-installer/blob/9fec66d5f8b1e9a0f3c0ec66dd777db578fab07e/djangocms_installer/django/__init__.py#L405-L445
[ "def", "setup_database", "(", "config_data", ")", ":", "with", "chdir", "(", "config_data", ".", "project_directory", ")", ":", "env", "=", "deepcopy", "(", "dict", "(", "os", ".", "environ", ")", ")", "env", "[", "str", "(", "'DJANGO_SETTINGS_MODULE'", ")", "]", "=", "str", "(", "'{0}.settings'", ".", "format", "(", "config_data", ".", "project_name", ")", ")", "env", "[", "str", "(", "'PYTHONPATH'", ")", "]", "=", "str", "(", "os", ".", "pathsep", ".", "join", "(", "map", "(", "shlex_quote", ",", "sys", ".", "path", ")", ")", ")", "commands", "=", "[", "]", "commands", ".", "append", "(", "[", "sys", ".", "executable", ",", "'-W'", ",", "'ignore'", ",", "'manage.py'", ",", "'migrate'", "]", ",", ")", "if", "config_data", ".", "verbose", ":", "sys", ".", "stdout", ".", "write", "(", "'Database setup commands: {0}\\n'", ".", "format", "(", "', '", ".", "join", "(", "[", "' '", ".", "join", "(", "cmd", ")", "for", "cmd", "in", "commands", "]", ")", ")", ")", "for", "command", "in", "commands", ":", "try", ":", "output", "=", "subprocess", ".", "check_output", "(", "command", ",", "env", "=", "env", ",", "stderr", "=", "subprocess", ".", "STDOUT", ")", "sys", ".", "stdout", ".", "write", "(", "output", ".", "decode", "(", "'utf-8'", ")", ")", "except", "subprocess", ".", "CalledProcessError", "as", "e", ":", "# pragma: no cover", "if", "config_data", ".", "verbose", ":", "sys", ".", "stdout", ".", "write", "(", "e", ".", "output", ".", "decode", "(", "'utf-8'", ")", ")", "raise", "if", "not", "config_data", ".", "no_user", ":", "sys", ".", "stdout", ".", "write", "(", "'Creating admin user\\n'", ")", "if", "config_data", ".", "noinput", ":", "create_user", "(", "config_data", ")", "else", ":", "subprocess", ".", "check_call", "(", "' '", ".", "join", "(", "[", "sys", ".", "executable", ",", "'-W'", ",", "'ignore'", ",", "'manage.py'", ",", "'createsuperuser'", "]", ")", ",", "shell", "=", "True", ",", "stderr", "=", "subprocess", ".", "STDOUT", ")" ]
9fec66d5f8b1e9a0f3c0ec66dd777db578fab07e
valid
create_user
Create admin user without user input :param config_data: configuration data
djangocms_installer/django/__init__.py
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.project_name)) env[str('PYTHONPATH')] = str(os.pathsep.join(map(shlex_quote, sys.path))) subprocess.check_call( [sys.executable, 'create_user.py'], env=env, stderr=subprocess.STDOUT ) for ext in ['py', 'pyc']: try: os.remove('create_user.{0}'.format(ext)) except OSError: pass
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.project_name)) env[str('PYTHONPATH')] = str(os.pathsep.join(map(shlex_quote, sys.path))) subprocess.check_call( [sys.executable, 'create_user.py'], env=env, stderr=subprocess.STDOUT ) for ext in ['py', 'pyc']: try: os.remove('create_user.{0}'.format(ext)) except OSError: pass
[ "Create", "admin", "user", "without", "user", "input" ]
nephila/djangocms-installer
python
https://github.com/nephila/djangocms-installer/blob/9fec66d5f8b1e9a0f3c0ec66dd777db578fab07e/djangocms_installer/django/__init__.py#L448-L465
[ "def", "create_user", "(", "config_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", ".", "project_name", ")", ")", "env", "[", "str", "(", "'PYTHONPATH'", ")", "]", "=", "str", "(", "os", ".", "pathsep", ".", "join", "(", "map", "(", "shlex_quote", ",", "sys", ".", "path", ")", ")", ")", "subprocess", ".", "check_call", "(", "[", "sys", ".", "executable", ",", "'create_user.py'", "]", ",", "env", "=", "env", ",", "stderr", "=", "subprocess", ".", "STDOUT", ")", "for", "ext", "in", "[", "'py'", ",", "'pyc'", "]", ":", "try", ":", "os", ".", "remove", "(", "'create_user.{0}'", ".", "format", "(", "ext", ")", ")", "except", "OSError", ":", "pass" ]
9fec66d5f8b1e9a0f3c0ec66dd777db578fab07e
valid
sox
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.
sox/core.py
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.insert(0, "sox") else: args[0] = "sox" try: logger.info("Executing: %s", ' '.join(args)) process_handle = subprocess.Popen( args, stdout=subprocess.PIPE, stderr=subprocess.PIPE ) out, err = process_handle.communicate() out = out.decode("utf-8") err = err.decode("utf-8") status = process_handle.returncode return status, out, err except OSError as error_msg: logger.error("OSError: SoX failed! %s", error_msg) except TypeError as error_msg: logger.error("TypeError: %s", error_msg) return 1, None, None
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.insert(0, "sox") else: args[0] = "sox" try: logger.info("Executing: %s", ' '.join(args)) process_handle = subprocess.Popen( args, stdout=subprocess.PIPE, stderr=subprocess.PIPE ) out, err = process_handle.communicate() out = out.decode("utf-8") err = err.decode("utf-8") status = process_handle.returncode return status, out, err except OSError as error_msg: logger.error("OSError: SoX failed! %s", error_msg) except TypeError as error_msg: logger.error("TypeError: %s", error_msg) return 1, None, None
[ "Pass", "an", "argument", "list", "to", "SoX", "." ]
rabitt/pysox
python
https://github.com/rabitt/pysox/blob/eae89bde74567136ec3f723c3e6b369916d9b837/sox/core.py#L17-L55
[ "def", "sox", "(", "args", ")", ":", "if", "args", "[", "0", "]", ".", "lower", "(", ")", "!=", "\"sox\"", ":", "args", ".", "insert", "(", "0", ",", "\"sox\"", ")", "else", ":", "args", "[", "0", "]", "=", "\"sox\"", "try", ":", "logger", ".", "info", "(", "\"Executing: %s\"", ",", "' '", ".", "join", "(", "args", ")", ")", "process_handle", "=", "subprocess", ".", "Popen", "(", "args", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "PIPE", ")", "out", ",", "err", "=", "process_handle", ".", "communicate", "(", ")", "out", "=", "out", ".", "decode", "(", "\"utf-8\"", ")", "err", "=", "err", ".", "decode", "(", "\"utf-8\"", ")", "status", "=", "process_handle", ".", "returncode", "return", "status", ",", "out", ",", "err", "except", "OSError", "as", "error_msg", ":", "logger", ".", "error", "(", "\"OSError: SoX failed! %s\"", ",", "error_msg", ")", "except", "TypeError", "as", "error_msg", ":", "logger", ".", "error", "(", "\"TypeError: %s\"", ",", "error_msg", ")", "return", "1", ",", "None", ",", "None" ]
eae89bde74567136ec3f723c3e6b369916d9b837
valid
_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.
sox/core.py
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']) if type(so) is not str: so = str(so, encoding='UTF-8') so = so.split('\n') idx = [i for i in range(len(so)) if 'AUDIO FILE FORMATS:' in so[i]][0] formats = so[idx].split(' ')[3:] return formats
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']) if type(so) is not str: so = str(so, encoding='UTF-8') so = so.split('\n') idx = [i for i in range(len(so)) if 'AUDIO FILE FORMATS:' in so[i]][0] formats = so[idx].split(' ')[3:] return formats
[ "Calls", "SoX", "help", "for", "a", "lists", "of", "audio", "formats", "available", "with", "the", "current", "install", "of", "SoX", "." ]
rabitt/pysox
python
https://github.com/rabitt/pysox/blob/eae89bde74567136ec3f723c3e6b369916d9b837/sox/core.py#L65-L85
[ "def", "_get_valid_formats", "(", ")", ":", "if", "NO_SOX", ":", "return", "[", "]", "so", "=", "subprocess", ".", "check_output", "(", "[", "'sox'", ",", "'-h'", "]", ")", "if", "type", "(", "so", ")", "is", "not", "str", ":", "so", "=", "str", "(", "so", ",", "encoding", "=", "'UTF-8'", ")", "so", "=", "so", ".", "split", "(", "'\\n'", ")", "idx", "=", "[", "i", "for", "i", "in", "range", "(", "len", "(", "so", ")", ")", "if", "'AUDIO FILE FORMATS:'", "in", "so", "[", "i", "]", "]", "[", "0", "]", "formats", "=", "so", "[", "idx", "]", ".", "split", "(", "' '", ")", "[", "3", ":", "]", "return", "formats" ]
eae89bde74567136ec3f723c3e6b369916d9b837
valid
soxi
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
sox/core.py
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: raise ValueError("Invalid argument '{}' to SoXI".format(argument)) args = ['sox', '--i'] args.append("-{}".format(argument)) args.append(filepath) try: shell_output = subprocess.check_output( args, stderr=subprocess.PIPE ) except CalledProcessError as cpe: logger.info("SoXI error message: {}".format(cpe.output)) raise SoxiError("SoXI failed with exit code {}".format(cpe.returncode)) shell_output = shell_output.decode("utf-8") return str(shell_output).strip('\n')
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: raise ValueError("Invalid argument '{}' to SoXI".format(argument)) args = ['sox', '--i'] args.append("-{}".format(argument)) args.append(filepath) try: shell_output = subprocess.check_output( args, stderr=subprocess.PIPE ) except CalledProcessError as cpe: logger.info("SoXI error message: {}".format(cpe.output)) raise SoxiError("SoXI failed with exit code {}".format(cpe.returncode)) shell_output = shell_output.decode("utf-8") return str(shell_output).strip('\n')
[ "Base", "call", "to", "SoXI", "." ]
rabitt/pysox
python
https://github.com/rabitt/pysox/blob/eae89bde74567136ec3f723c3e6b369916d9b837/sox/core.py#L91-L126
[ "def", "soxi", "(", "filepath", ",", "argument", ")", ":", "if", "argument", "not", "in", "SOXI_ARGS", ":", "raise", "ValueError", "(", "\"Invalid argument '{}' to SoXI\"", ".", "format", "(", "argument", ")", ")", "args", "=", "[", "'sox'", ",", "'--i'", "]", "args", ".", "append", "(", "\"-{}\"", ".", "format", "(", "argument", ")", ")", "args", ".", "append", "(", "filepath", ")", "try", ":", "shell_output", "=", "subprocess", ".", "check_output", "(", "args", ",", "stderr", "=", "subprocess", ".", "PIPE", ")", "except", "CalledProcessError", "as", "cpe", ":", "logger", ".", "info", "(", "\"SoXI error message: {}\"", ".", "format", "(", "cpe", ".", "output", ")", ")", "raise", "SoxiError", "(", "\"SoXI failed with exit code {}\"", ".", "format", "(", "cpe", ".", "returncode", ")", ")", "shell_output", "=", "shell_output", ".", "decode", "(", "\"utf-8\"", ")", "return", "str", "(", "shell_output", ")", ".", "strip", "(", "'\\n'", ")" ]
eae89bde74567136ec3f723c3e6b369916d9b837
valid
play
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.
sox/core.py
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": args.insert(0, "play") else: args[0] = "play" try: logger.info("Executing: %s", " ".join(args)) process_handle = subprocess.Popen( args, stdout=subprocess.PIPE, stderr=subprocess.PIPE ) status = process_handle.wait() if process_handle.stderr is not None: logger.info(process_handle.stderr) if status == 0: return True else: logger.info("Play returned with error code %s", status) return False except OSError as error_msg: logger.error("OSError: Play failed! %s", error_msg) except TypeError as error_msg: logger.error("TypeError: %s", error_msg) return False
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": args.insert(0, "play") else: args[0] = "play" try: logger.info("Executing: %s", " ".join(args)) process_handle = subprocess.Popen( args, stdout=subprocess.PIPE, stderr=subprocess.PIPE ) status = process_handle.wait() if process_handle.stderr is not None: logger.info(process_handle.stderr) if status == 0: return True else: logger.info("Play returned with error code %s", status) return False except OSError as error_msg: logger.error("OSError: Play failed! %s", error_msg) except TypeError as error_msg: logger.error("TypeError: %s", error_msg) return False
[ "Pass", "an", "argument", "list", "to", "play", "." ]
rabitt/pysox
python
https://github.com/rabitt/pysox/blob/eae89bde74567136ec3f723c3e6b369916d9b837/sox/core.py#L129-L168
[ "def", "play", "(", "args", ")", ":", "if", "args", "[", "0", "]", ".", "lower", "(", ")", "!=", "\"play\"", ":", "args", ".", "insert", "(", "0", ",", "\"play\"", ")", "else", ":", "args", "[", "0", "]", "=", "\"play\"", "try", ":", "logger", ".", "info", "(", "\"Executing: %s\"", ",", "\" \"", ".", "join", "(", "args", ")", ")", "process_handle", "=", "subprocess", ".", "Popen", "(", "args", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "PIPE", ")", "status", "=", "process_handle", ".", "wait", "(", ")", "if", "process_handle", ".", "stderr", "is", "not", "None", ":", "logger", ".", "info", "(", "process_handle", ".", "stderr", ")", "if", "status", "==", "0", ":", "return", "True", "else", ":", "logger", ".", "info", "(", "\"Play returned with error code %s\"", ",", "status", ")", "return", "False", "except", "OSError", "as", "error_msg", ":", "logger", ".", "error", "(", "\"OSError: Play failed! %s\"", ",", "error_msg", ")", "except", "TypeError", "as", "error_msg", ":", "logger", ".", "error", "(", "\"TypeError: %s\"", ",", "error_msg", ")", "return", "False" ]
eae89bde74567136ec3f723c3e6b369916d9b837
valid
_validate_file_formats
Validate that combine method can be performed with given files. Raises IOError if input file formats are incompatible.
sox/combine.py
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_num_channels(input_filepath_list, combine_type)
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_num_channels(input_filepath_list, combine_type)
[ "Validate", "that", "combine", "method", "can", "be", "performed", "with", "given", "files", ".", "Raises", "IOError", "if", "input", "file", "formats", "are", "incompatible", "." ]
rabitt/pysox
python
https://github.com/rabitt/pysox/blob/eae89bde74567136ec3f723c3e6b369916d9b837/sox/combine.py#L308-L315
[ "def", "_validate_file_formats", "(", "input_filepath_list", ",", "combine_type", ")", ":", "_validate_sample_rates", "(", "input_filepath_list", ",", "combine_type", ")", "if", "combine_type", "==", "'concatenate'", ":", "_validate_num_channels", "(", "input_filepath_list", ",", "combine_type", ")" ]
eae89bde74567136ec3f723c3e6b369916d9b837
valid
_validate_sample_rates
Check if files in input file list have the same sample rate
sox/combine.py
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 not have the same sample rate. The {} combine " "type requires that all files have the same sample rate" .format(combine_type) )
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 not have the same sample rate. The {} combine " "type requires that all files have the same sample rate" .format(combine_type) )
[ "Check", "if", "files", "in", "input", "file", "list", "have", "the", "same", "sample", "rate" ]
rabitt/pysox
python
https://github.com/rabitt/pysox/blob/eae89bde74567136ec3f723c3e6b369916d9b837/sox/combine.py#L318-L329
[ "def", "_validate_sample_rates", "(", "input_filepath_list", ",", "combine_type", ")", ":", "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 not have the same sample rate. The {} combine \"", "\"type requires that all files have the same sample rate\"", ".", "format", "(", "combine_type", ")", ")" ]
eae89bde74567136ec3f723c3e6b369916d9b837
valid
_validate_num_channels
Check if files in input file list have the same number of channels
sox/combine.py
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 have the same number of channels. The " "{} combine type requires that all files have the same " "number of channels" .format(combine_type) )
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 have the same number of channels. The " "{} combine type requires that all files have the same " "number of channels" .format(combine_type) )
[ "Check", "if", "files", "in", "input", "file", "list", "have", "the", "same", "number", "of", "channels" ]
rabitt/pysox
python
https://github.com/rabitt/pysox/blob/eae89bde74567136ec3f723c3e6b369916d9b837/sox/combine.py#L332-L344
[ "def", "_validate_num_channels", "(", "input_filepath_list", ",", "combine_type", ")", ":", "channels", "=", "[", "file_info", ".", "channels", "(", "f", ")", "for", "f", "in", "input_filepath_list", "]", "if", "not", "core", ".", "all_equal", "(", "channels", ")", ":", "raise", "IOError", "(", "\"Input files do not have the same number of channels. The \"", "\"{} combine type requires that all files have the same \"", "\"number of channels\"", ".", "format", "(", "combine_type", ")", ")" ]
eae89bde74567136ec3f723c3e6b369916d9b837
valid
_build_input_format_list
Set input formats given input_volumes. Parameters ---------- input_filepath_list : list of str List of input files input_volumes : list of float, default=None List of volumes to be applied upon combining input files. Volumes are applied to the input files in order. If None, input files will be combined at their original volumes. input_format : list of lists, default=None List of input formats to be applied to each input file. Formatting arguments are applied to the input files in order. If None, the input formats will be inferred from the file header.
sox/combine.py
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 List of volumes to be applied upon combining input files. Volumes are applied to the input files in order. If None, input files will be combined at their original volumes. input_format : list of lists, default=None List of input formats to be applied to each input file. Formatting arguments are applied to the input files in order. If None, the input formats will be inferred from the file header. ''' n_inputs = len(input_filepath_list) input_format_list = [] for _ in range(n_inputs): input_format_list.append([]) # Adjust length of input_volumes list if input_volumes is None: vols = [1] * n_inputs else: n_volumes = len(input_volumes) if n_volumes < n_inputs: logger.warning( 'Volumes were only specified for %s out of %s files.' 'The last %s files will remain at their original volumes.', n_volumes, n_inputs, n_inputs - n_volumes ) vols = input_volumes + [1] * (n_inputs - n_volumes) elif n_volumes > n_inputs: logger.warning( '%s volumes were specified but only %s input files exist.' 'The last %s volumes will be ignored.', n_volumes, n_inputs, n_volumes - n_inputs ) vols = input_volumes[:n_inputs] else: vols = [v for v in input_volumes] # Adjust length of input_format list if input_format is None: fmts = [[] for _ in range(n_inputs)] else: n_fmts = len(input_format) if n_fmts < n_inputs: logger.warning( 'Input formats were only specified for %s out of %s files.' 'The last %s files will remain unformatted.', n_fmts, n_inputs, n_inputs - n_fmts ) fmts = [f for f in input_format] fmts.extend([[] for _ in range(n_inputs - n_fmts)]) elif n_fmts > n_inputs: logger.warning( '%s Input formats were specified but only %s input files exist' '. The last %s formats will be ignored.', n_fmts, n_inputs, n_fmts - n_inputs ) fmts = input_format[:n_inputs] else: fmts = [f for f in input_format] for i, (vol, fmt) in enumerate(zip(vols, fmts)): input_format_list[i].extend(['-v', '{}'.format(vol)]) input_format_list[i].extend(fmt) return input_format_list
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 List of volumes to be applied upon combining input files. Volumes are applied to the input files in order. If None, input files will be combined at their original volumes. input_format : list of lists, default=None List of input formats to be applied to each input file. Formatting arguments are applied to the input files in order. If None, the input formats will be inferred from the file header. ''' n_inputs = len(input_filepath_list) input_format_list = [] for _ in range(n_inputs): input_format_list.append([]) # Adjust length of input_volumes list if input_volumes is None: vols = [1] * n_inputs else: n_volumes = len(input_volumes) if n_volumes < n_inputs: logger.warning( 'Volumes were only specified for %s out of %s files.' 'The last %s files will remain at their original volumes.', n_volumes, n_inputs, n_inputs - n_volumes ) vols = input_volumes + [1] * (n_inputs - n_volumes) elif n_volumes > n_inputs: logger.warning( '%s volumes were specified but only %s input files exist.' 'The last %s volumes will be ignored.', n_volumes, n_inputs, n_volumes - n_inputs ) vols = input_volumes[:n_inputs] else: vols = [v for v in input_volumes] # Adjust length of input_format list if input_format is None: fmts = [[] for _ in range(n_inputs)] else: n_fmts = len(input_format) if n_fmts < n_inputs: logger.warning( 'Input formats were only specified for %s out of %s files.' 'The last %s files will remain unformatted.', n_fmts, n_inputs, n_inputs - n_fmts ) fmts = [f for f in input_format] fmts.extend([[] for _ in range(n_inputs - n_fmts)]) elif n_fmts > n_inputs: logger.warning( '%s Input formats were specified but only %s input files exist' '. The last %s formats will be ignored.', n_fmts, n_inputs, n_fmts - n_inputs ) fmts = input_format[:n_inputs] else: fmts = [f for f in input_format] for i, (vol, fmt) in enumerate(zip(vols, fmts)): input_format_list[i].extend(['-v', '{}'.format(vol)]) input_format_list[i].extend(fmt) return input_format_list
[ "Set", "input", "formats", "given", "input_volumes", "." ]
rabitt/pysox
python
https://github.com/rabitt/pysox/blob/eae89bde74567136ec3f723c3e6b369916d9b837/sox/combine.py#L347-L419
[ "def", "_build_input_format_list", "(", "input_filepath_list", ",", "input_volumes", "=", "None", ",", "input_format", "=", "None", ")", ":", "n_inputs", "=", "len", "(", "input_filepath_list", ")", "input_format_list", "=", "[", "]", "for", "_", "in", "range", "(", "n_inputs", ")", ":", "input_format_list", ".", "append", "(", "[", "]", ")", "# Adjust length of input_volumes list", "if", "input_volumes", "is", "None", ":", "vols", "=", "[", "1", "]", "*", "n_inputs", "else", ":", "n_volumes", "=", "len", "(", "input_volumes", ")", "if", "n_volumes", "<", "n_inputs", ":", "logger", ".", "warning", "(", "'Volumes were only specified for %s out of %s files.'", "'The last %s files will remain at their original volumes.'", ",", "n_volumes", ",", "n_inputs", ",", "n_inputs", "-", "n_volumes", ")", "vols", "=", "input_volumes", "+", "[", "1", "]", "*", "(", "n_inputs", "-", "n_volumes", ")", "elif", "n_volumes", ">", "n_inputs", ":", "logger", ".", "warning", "(", "'%s volumes were specified but only %s input files exist.'", "'The last %s volumes will be ignored.'", ",", "n_volumes", ",", "n_inputs", ",", "n_volumes", "-", "n_inputs", ")", "vols", "=", "input_volumes", "[", ":", "n_inputs", "]", "else", ":", "vols", "=", "[", "v", "for", "v", "in", "input_volumes", "]", "# Adjust length of input_format list", "if", "input_format", "is", "None", ":", "fmts", "=", "[", "[", "]", "for", "_", "in", "range", "(", "n_inputs", ")", "]", "else", ":", "n_fmts", "=", "len", "(", "input_format", ")", "if", "n_fmts", "<", "n_inputs", ":", "logger", ".", "warning", "(", "'Input formats were only specified for %s out of %s files.'", "'The last %s files will remain unformatted.'", ",", "n_fmts", ",", "n_inputs", ",", "n_inputs", "-", "n_fmts", ")", "fmts", "=", "[", "f", "for", "f", "in", "input_format", "]", "fmts", ".", "extend", "(", "[", "[", "]", "for", "_", "in", "range", "(", "n_inputs", "-", "n_fmts", ")", "]", ")", "elif", "n_fmts", ">", "n_inputs", ":", "logger", ".", "warning", "(", "'%s Input formats were specified but only %s input files exist'", "'. The last %s formats will be ignored.'", ",", "n_fmts", ",", "n_inputs", ",", "n_fmts", "-", "n_inputs", ")", "fmts", "=", "input_format", "[", ":", "n_inputs", "]", "else", ":", "fmts", "=", "[", "f", "for", "f", "in", "input_format", "]", "for", "i", ",", "(", "vol", ",", "fmt", ")", "in", "enumerate", "(", "zip", "(", "vols", ",", "fmts", ")", ")", ":", "input_format_list", "[", "i", "]", ".", "extend", "(", "[", "'-v'", ",", "'{}'", ".", "format", "(", "vol", ")", "]", ")", "input_format_list", "[", "i", "]", ".", "extend", "(", "fmt", ")", "return", "input_format_list" ]
eae89bde74567136ec3f723c3e6b369916d9b837
valid
_build_input_args
Builds input arguments by stitching input filepaths and input formats together.
sox/combine.py
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 size" ) input_args = [] zipped = zip(input_filepath_list, input_format_list) for input_file, input_fmt in zipped: input_args.extend(input_fmt) input_args.append(input_file) return input_args
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 size" ) input_args = [] zipped = zip(input_filepath_list, input_format_list) for input_file, input_fmt in zipped: input_args.extend(input_fmt) input_args.append(input_file) return input_args
[ "Builds", "input", "arguments", "by", "stitching", "input", "filepaths", "and", "input", "formats", "together", "." ]
rabitt/pysox
python
https://github.com/rabitt/pysox/blob/eae89bde74567136ec3f723c3e6b369916d9b837/sox/combine.py#L422-L437
[ "def", "_build_input_args", "(", "input_filepath_list", ",", "input_format_list", ")", ":", "if", "len", "(", "input_format_list", ")", "!=", "len", "(", "input_filepath_list", ")", ":", "raise", "ValueError", "(", "\"input_format_list & input_filepath_list are not the same size\"", ")", "input_args", "=", "[", "]", "zipped", "=", "zip", "(", "input_filepath_list", ",", "input_format_list", ")", "for", "input_file", ",", "input_fmt", "in", "zipped", ":", "input_args", ".", "extend", "(", "input_fmt", ")", "input_args", ".", "append", "(", "input_file", ")", "return", "input_args" ]
eae89bde74567136ec3f723c3e6b369916d9b837
valid
_validate_volumes
Check input_volumes contains a valid list of volumes. Parameters ---------- input_volumes : list list of volume values. Castable to numbers.
sox/combine.py
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_volumes must be None or a list.") if isinstance(input_volumes, list): for vol in input_volumes: if not core.is_number(vol): raise ValueError( "Elements of input_volumes must be numbers: found {}" .format(vol) )
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_volumes must be None or a list.") if isinstance(input_volumes, list): for vol in input_volumes: if not core.is_number(vol): raise ValueError( "Elements of input_volumes must be numbers: found {}" .format(vol) )
[ "Check", "input_volumes", "contains", "a", "valid", "list", "of", "volumes", "." ]
rabitt/pysox
python
https://github.com/rabitt/pysox/blob/eae89bde74567136ec3f723c3e6b369916d9b837/sox/combine.py#L456-L474
[ "def", "_validate_volumes", "(", "input_volumes", ")", ":", "if", "not", "(", "input_volumes", "is", "None", "or", "isinstance", "(", "input_volumes", ",", "list", ")", ")", ":", "raise", "TypeError", "(", "\"input_volumes must be None or a list.\"", ")", "if", "isinstance", "(", "input_volumes", ",", "list", ")", ":", "for", "vol", "in", "input_volumes", ":", "if", "not", "core", ".", "is_number", "(", "vol", ")", ":", "raise", "ValueError", "(", "\"Elements of input_volumes must be numbers: found {}\"", ".", "format", "(", "vol", ")", ")" ]
eae89bde74567136ec3f723c3e6b369916d9b837
valid
Combiner.build
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. output_filepath : str Path to desired output file. If a file already exists at the given path, the file will be overwritten. combine_type : str Input file combining method. One of the following values: * concatenate : combine input files by concatenating in the order given. * merge : combine input files by stacking each input file into a new channel of the output file. * mix : combine input files by summing samples in corresponding channels. * mix-power : combine input files with volume adjustments such that the output volume is roughly equivlent to one of the input signals. * multiply : combine input files by multiplying samples in corresponding samples. input_volumes : list of float, default=None List of volumes to be applied upon combining input files. Volumes are applied to the input files in order. If None, input files will be combined at their original volumes.
sox/combine.py
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. output_filepath : str Path to desired output file. If a file already exists at the given path, the file will be overwritten. combine_type : str Input file combining method. One of the following values: * concatenate : combine input files by concatenating in the order given. * merge : combine input files by stacking each input file into a new channel of the output file. * mix : combine input files by summing samples in corresponding channels. * mix-power : combine input files with volume adjustments such that the output volume is roughly equivlent to one of the input signals. * multiply : combine input files by multiplying samples in corresponding samples. input_volumes : list of float, default=None List of volumes to be applied upon combining input files. Volumes are applied to the input files in order. If None, input files will be combined at their original volumes. ''' file_info.validate_input_file_list(input_filepath_list) file_info.validate_output_file(output_filepath) _validate_combine_type(combine_type) _validate_volumes(input_volumes) input_format_list = _build_input_format_list( input_filepath_list, input_volumes, self.input_format ) try: _validate_file_formats(input_filepath_list, combine_type) except SoxiError: logger.warning("unable to validate file formats.") args = [] args.extend(self.globals) args.extend(['--combine', combine_type]) input_args = _build_input_args(input_filepath_list, input_format_list) args.extend(input_args) args.extend(self.output_format) args.append(output_filepath) args.extend(self.effects) status, out, err = sox(args) if status != 0: raise SoxError( "Stdout: {}\nStderr: {}".format(out, err) ) else: logger.info( "Created %s with combiner %s and effects: %s", output_filepath, combine_type, " ".join(self.effects_log) ) if out is not None: logger.info("[SoX] {}".format(out)) return True
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. output_filepath : str Path to desired output file. If a file already exists at the given path, the file will be overwritten. combine_type : str Input file combining method. One of the following values: * concatenate : combine input files by concatenating in the order given. * merge : combine input files by stacking each input file into a new channel of the output file. * mix : combine input files by summing samples in corresponding channels. * mix-power : combine input files with volume adjustments such that the output volume is roughly equivlent to one of the input signals. * multiply : combine input files by multiplying samples in corresponding samples. input_volumes : list of float, default=None List of volumes to be applied upon combining input files. Volumes are applied to the input files in order. If None, input files will be combined at their original volumes. ''' file_info.validate_input_file_list(input_filepath_list) file_info.validate_output_file(output_filepath) _validate_combine_type(combine_type) _validate_volumes(input_volumes) input_format_list = _build_input_format_list( input_filepath_list, input_volumes, self.input_format ) try: _validate_file_formats(input_filepath_list, combine_type) except SoxiError: logger.warning("unable to validate file formats.") args = [] args.extend(self.globals) args.extend(['--combine', combine_type]) input_args = _build_input_args(input_filepath_list, input_format_list) args.extend(input_args) args.extend(self.output_format) args.append(output_filepath) args.extend(self.effects) status, out, err = sox(args) if status != 0: raise SoxError( "Stdout: {}\nStderr: {}".format(out, err) ) else: logger.info( "Created %s with combiner %s and effects: %s", output_filepath, combine_type, " ".join(self.effects_log) ) if out is not None: logger.info("[SoX] {}".format(out)) return True
[ "Builds", "the", "output_file", "by", "executing", "the", "current", "set", "of", "commands", "." ]
rabitt/pysox
python
https://github.com/rabitt/pysox/blob/eae89bde74567136ec3f723c3e6b369916d9b837/sox/combine.py#L40-L110
[ "def", "build", "(", "self", ",", "input_filepath_list", ",", "output_filepath", ",", "combine_type", ",", "input_volumes", "=", "None", ")", ":", "file_info", ".", "validate_input_file_list", "(", "input_filepath_list", ")", "file_info", ".", "validate_output_file", "(", "output_filepath", ")", "_validate_combine_type", "(", "combine_type", ")", "_validate_volumes", "(", "input_volumes", ")", "input_format_list", "=", "_build_input_format_list", "(", "input_filepath_list", ",", "input_volumes", ",", "self", ".", "input_format", ")", "try", ":", "_validate_file_formats", "(", "input_filepath_list", ",", "combine_type", ")", "except", "SoxiError", ":", "logger", ".", "warning", "(", "\"unable to validate file formats.\"", ")", "args", "=", "[", "]", "args", ".", "extend", "(", "self", ".", "globals", ")", "args", ".", "extend", "(", "[", "'--combine'", ",", "combine_type", "]", ")", "input_args", "=", "_build_input_args", "(", "input_filepath_list", ",", "input_format_list", ")", "args", ".", "extend", "(", "input_args", ")", "args", ".", "extend", "(", "self", ".", "output_format", ")", "args", ".", "append", "(", "output_filepath", ")", "args", ".", "extend", "(", "self", ".", "effects", ")", "status", ",", "out", ",", "err", "=", "sox", "(", "args", ")", "if", "status", "!=", "0", ":", "raise", "SoxError", "(", "\"Stdout: {}\\nStderr: {}\"", ".", "format", "(", "out", ",", "err", ")", ")", "else", ":", "logger", ".", "info", "(", "\"Created %s with combiner %s and effects: %s\"", ",", "output_filepath", ",", "combine_type", ",", "\" \"", ".", "join", "(", "self", ".", "effects_log", ")", ")", "if", "out", "is", "not", "None", ":", "logger", ".", "info", "(", "\"[SoX] {}\"", ".", "format", "(", "out", ")", ")", "return", "True" ]
eae89bde74567136ec3f723c3e6b369916d9b837
valid
Combiner.preview
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 file combining method. One of the following values: * concatenate : combine input files by concatenating in the order given. * merge : combine input files by stacking each input file into a new channel of the output file. * mix : combine input files by summing samples in corresponding channels. * mix-power : combine input files with volume adjustments such that the output volume is roughly equivlent to one of the input signals. * multiply : combine input files by multiplying samples in corresponding samples. input_volumes : list of float, default=None List of volumes to be applied upon combining input files. Volumes are applied to the input files in order. If None, input files will be combined at their original volumes.
sox/combine.py
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 file combining method. One of the following values: * concatenate : combine input files by concatenating in the order given. * merge : combine input files by stacking each input file into a new channel of the output file. * mix : combine input files by summing samples in corresponding channels. * mix-power : combine input files with volume adjustments such that the output volume is roughly equivlent to one of the input signals. * multiply : combine input files by multiplying samples in corresponding samples. input_volumes : list of float, default=None List of volumes to be applied upon combining input files. Volumes are applied to the input files in order. If None, input files will be combined at their original volumes. ''' args = ["play", "--no-show-progress"] args.extend(self.globals) args.extend(['--combine', combine_type]) input_format_list = _build_input_format_list( input_filepath_list, input_volumes, self.input_format ) input_args = _build_input_args(input_filepath_list, input_format_list) args.extend(input_args) args.extend(self.effects) play(args)
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 file combining method. One of the following values: * concatenate : combine input files by concatenating in the order given. * merge : combine input files by stacking each input file into a new channel of the output file. * mix : combine input files by summing samples in corresponding channels. * mix-power : combine input files with volume adjustments such that the output volume is roughly equivlent to one of the input signals. * multiply : combine input files by multiplying samples in corresponding samples. input_volumes : list of float, default=None List of volumes to be applied upon combining input files. Volumes are applied to the input files in order. If None, input files will be combined at their original volumes. ''' args = ["play", "--no-show-progress"] args.extend(self.globals) args.extend(['--combine', combine_type]) input_format_list = _build_input_format_list( input_filepath_list, input_volumes, self.input_format ) input_args = _build_input_args(input_filepath_list, input_format_list) args.extend(input_args) args.extend(self.effects) play(args)
[ "Play", "a", "preview", "of", "the", "output", "with", "the", "current", "set", "of", "effects" ]
rabitt/pysox
python
https://github.com/rabitt/pysox/blob/eae89bde74567136ec3f723c3e6b369916d9b837/sox/combine.py#L112-L149
[ "def", "preview", "(", "self", ",", "input_filepath_list", ",", "combine_type", ",", "input_volumes", "=", "None", ")", ":", "args", "=", "[", "\"play\"", ",", "\"--no-show-progress\"", "]", "args", ".", "extend", "(", "self", ".", "globals", ")", "args", ".", "extend", "(", "[", "'--combine'", ",", "combine_type", "]", ")", "input_format_list", "=", "_build_input_format_list", "(", "input_filepath_list", ",", "input_volumes", ",", "self", ".", "input_format", ")", "input_args", "=", "_build_input_args", "(", "input_filepath_list", ",", "input_format_list", ")", "args", ".", "extend", "(", "input_args", ")", "args", ".", "extend", "(", "self", ".", "effects", ")", "play", "(", "args", ")" ]
eae89bde74567136ec3f723c3e6b369916d9b837
valid
Combiner.set_input_format
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. If this function is not explicity called the input format is inferred from the file extension or the file's header. Parameters ---------- file_type : list of str or None, default=None The file type of the input audio file. Should be the same as what the file extension would be, for ex. 'mp3' or 'wav'. rate : list of float or None, default=None The sample rate of the input audio file. If None the sample rate is inferred. bits : list of int or None, default=None The number of bits per sample. If None, the number of bits per sample is inferred. channels : list of int or None, default=None The number of channels in the audio file. If None the number of channels is inferred. encoding : list of str or None, default=None The audio encoding type. Sometimes needed with file-types that support more than one encoding type. One of: * signed-integer : PCM data stored as signed (‘two’s complement’) integers. Commonly used with a 16 or 24−bit encoding size. A value of 0 represents minimum signal power. * unsigned-integer : PCM data stored as unsigned integers. Commonly used with an 8-bit encoding size. A value of 0 represents maximum signal power. * floating-point : PCM data stored as IEEE 753 single precision (32-bit) or double precision (64-bit) floating-point (‘real’) numbers. A value of 0 represents minimum signal power. * a-law : International telephony standard for logarithmic encoding to 8 bits per sample. It has a precision equivalent to roughly 13-bit PCM and is sometimes encoded with reversed bit-ordering. * u-law : North American telephony standard for logarithmic encoding to 8 bits per sample. A.k.a. μ-law. It has a precision equivalent to roughly 14-bit PCM and is sometimes encoded with reversed bit-ordering. * oki-adpcm : OKI (a.k.a. VOX, Dialogic, or Intel) 4-bit ADPCM; it has a precision equivalent to roughly 12-bit PCM. ADPCM is a form of audio compression that has a good compromise between audio quality and encoding/decoding speed. * ima-adpcm : IMA (a.k.a. DVI) 4-bit ADPCM; it has a precision equivalent to roughly 13-bit PCM. * ms-adpcm : Microsoft 4-bit ADPCM; it has a precision equivalent to roughly 14-bit PCM. * gsm-full-rate : GSM is currently used for the vast majority of the world’s digital wireless telephone calls. It utilises several audio formats with different bit-rates and associated speech quality. SoX has support for GSM’s original 13kbps ‘Full Rate’ audio format. It is usually CPU-intensive to work with GSM audio. ignore_length : list of bool or None, default=None If True, overrides an (incorrect) audio length given in an audio file’s header. If this option is given then SoX will keep reading audio until it reaches the end of the input file.
sox/combine.py
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 file arguments. If this function is not explicity called the input format is inferred from the file extension or the file's header. Parameters ---------- file_type : list of str or None, default=None The file type of the input audio file. Should be the same as what the file extension would be, for ex. 'mp3' or 'wav'. rate : list of float or None, default=None The sample rate of the input audio file. If None the sample rate is inferred. bits : list of int or None, default=None The number of bits per sample. If None, the number of bits per sample is inferred. channels : list of int or None, default=None The number of channels in the audio file. If None the number of channels is inferred. encoding : list of str or None, default=None The audio encoding type. Sometimes needed with file-types that support more than one encoding type. One of: * signed-integer : PCM data stored as signed (‘two’s complement’) integers. Commonly used with a 16 or 24−bit encoding size. A value of 0 represents minimum signal power. * unsigned-integer : PCM data stored as unsigned integers. Commonly used with an 8-bit encoding size. A value of 0 represents maximum signal power. * floating-point : PCM data stored as IEEE 753 single precision (32-bit) or double precision (64-bit) floating-point (‘real’) numbers. A value of 0 represents minimum signal power. * a-law : International telephony standard for logarithmic encoding to 8 bits per sample. It has a precision equivalent to roughly 13-bit PCM and is sometimes encoded with reversed bit-ordering. * u-law : North American telephony standard for logarithmic encoding to 8 bits per sample. A.k.a. μ-law. It has a precision equivalent to roughly 14-bit PCM and is sometimes encoded with reversed bit-ordering. * oki-adpcm : OKI (a.k.a. VOX, Dialogic, or Intel) 4-bit ADPCM; it has a precision equivalent to roughly 12-bit PCM. ADPCM is a form of audio compression that has a good compromise between audio quality and encoding/decoding speed. * ima-adpcm : IMA (a.k.a. DVI) 4-bit ADPCM; it has a precision equivalent to roughly 13-bit PCM. * ms-adpcm : Microsoft 4-bit ADPCM; it has a precision equivalent to roughly 14-bit PCM. * gsm-full-rate : GSM is currently used for the vast majority of the world’s digital wireless telephone calls. It utilises several audio formats with different bit-rates and associated speech quality. SoX has support for GSM’s original 13kbps ‘Full Rate’ audio format. It is usually CPU-intensive to work with GSM audio. ignore_length : list of bool or None, default=None If True, overrides an (incorrect) audio length given in an audio file’s header. If this option is given then SoX will keep reading audio until it reaches the end of the input file. ''' if file_type is not None and not isinstance(file_type, list): raise ValueError("file_type must be a list or None.") if file_type is not None: if not all([f in VALID_FORMATS for f in file_type]): raise ValueError( 'file_type elements ' 'must be one of {}'.format(VALID_FORMATS) ) else: file_type = [] if rate is not None and not isinstance(rate, list): raise ValueError("rate must be a list or None.") if rate is not None: if not all([is_number(r) and r > 0 for r in rate]): raise ValueError('rate elements must be positive floats.') else: rate = [] if bits is not None and not isinstance(bits, list): raise ValueError("bits must be a list or None.") if bits is not None: if not all([isinstance(b, int) and b > 0 for b in bits]): raise ValueError('bit elements must be positive ints.') else: bits = [] if channels is not None and not isinstance(channels, list): raise ValueError("channels must be a list or None.") if channels is not None: if not all([isinstance(c, int) and c > 0 for c in channels]): raise ValueError('channel elements must be positive ints.') else: channels = [] if encoding is not None and not isinstance(encoding, list): raise ValueError("encoding must be a list or None.") if encoding is not None: if not all([e in ENCODING_VALS for e in encoding]): raise ValueError( 'elements of encoding must ' 'be one of {}'.format(ENCODING_VALS) ) else: encoding = [] if ignore_length is not None and not isinstance(ignore_length, list): raise ValueError("ignore_length must be a list or None.") if ignore_length is not None: if not all([isinstance(l, bool) for l in ignore_length]): raise ValueError("ignore_length elements must be booleans.") else: ignore_length = [] max_input_arg_len = max([ len(file_type), len(rate), len(bits), len(channels), len(encoding), len(ignore_length) ]) input_format = [] for _ in range(max_input_arg_len): input_format.append([]) for i, f in enumerate(file_type): input_format[i].extend(['-t', '{}'.format(f)]) for i, r in enumerate(rate): input_format[i].extend(['-r', '{}'.format(r)]) for i, b in enumerate(bits): input_format[i].extend(['-b', '{}'.format(b)]) for i, c in enumerate(channels): input_format[i].extend(['-c', '{}'.format(c)]) for i, e in enumerate(encoding): input_format[i].extend(['-e', '{}'.format(e)]) for i, l in enumerate(ignore_length): if l is True: input_format[i].append('--ignore-length') self.input_format = input_format return self
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 file arguments. If this function is not explicity called the input format is inferred from the file extension or the file's header. Parameters ---------- file_type : list of str or None, default=None The file type of the input audio file. Should be the same as what the file extension would be, for ex. 'mp3' or 'wav'. rate : list of float or None, default=None The sample rate of the input audio file. If None the sample rate is inferred. bits : list of int or None, default=None The number of bits per sample. If None, the number of bits per sample is inferred. channels : list of int or None, default=None The number of channels in the audio file. If None the number of channels is inferred. encoding : list of str or None, default=None The audio encoding type. Sometimes needed with file-types that support more than one encoding type. One of: * signed-integer : PCM data stored as signed (‘two’s complement’) integers. Commonly used with a 16 or 24−bit encoding size. A value of 0 represents minimum signal power. * unsigned-integer : PCM data stored as unsigned integers. Commonly used with an 8-bit encoding size. A value of 0 represents maximum signal power. * floating-point : PCM data stored as IEEE 753 single precision (32-bit) or double precision (64-bit) floating-point (‘real’) numbers. A value of 0 represents minimum signal power. * a-law : International telephony standard for logarithmic encoding to 8 bits per sample. It has a precision equivalent to roughly 13-bit PCM and is sometimes encoded with reversed bit-ordering. * u-law : North American telephony standard for logarithmic encoding to 8 bits per sample. A.k.a. μ-law. It has a precision equivalent to roughly 14-bit PCM and is sometimes encoded with reversed bit-ordering. * oki-adpcm : OKI (a.k.a. VOX, Dialogic, or Intel) 4-bit ADPCM; it has a precision equivalent to roughly 12-bit PCM. ADPCM is a form of audio compression that has a good compromise between audio quality and encoding/decoding speed. * ima-adpcm : IMA (a.k.a. DVI) 4-bit ADPCM; it has a precision equivalent to roughly 13-bit PCM. * ms-adpcm : Microsoft 4-bit ADPCM; it has a precision equivalent to roughly 14-bit PCM. * gsm-full-rate : GSM is currently used for the vast majority of the world’s digital wireless telephone calls. It utilises several audio formats with different bit-rates and associated speech quality. SoX has support for GSM’s original 13kbps ‘Full Rate’ audio format. It is usually CPU-intensive to work with GSM audio. ignore_length : list of bool or None, default=None If True, overrides an (incorrect) audio length given in an audio file’s header. If this option is given then SoX will keep reading audio until it reaches the end of the input file. ''' if file_type is not None and not isinstance(file_type, list): raise ValueError("file_type must be a list or None.") if file_type is not None: if not all([f in VALID_FORMATS for f in file_type]): raise ValueError( 'file_type elements ' 'must be one of {}'.format(VALID_FORMATS) ) else: file_type = [] if rate is not None and not isinstance(rate, list): raise ValueError("rate must be a list or None.") if rate is not None: if not all([is_number(r) and r > 0 for r in rate]): raise ValueError('rate elements must be positive floats.') else: rate = [] if bits is not None and not isinstance(bits, list): raise ValueError("bits must be a list or None.") if bits is not None: if not all([isinstance(b, int) and b > 0 for b in bits]): raise ValueError('bit elements must be positive ints.') else: bits = [] if channels is not None and not isinstance(channels, list): raise ValueError("channels must be a list or None.") if channels is not None: if not all([isinstance(c, int) and c > 0 for c in channels]): raise ValueError('channel elements must be positive ints.') else: channels = [] if encoding is not None and not isinstance(encoding, list): raise ValueError("encoding must be a list or None.") if encoding is not None: if not all([e in ENCODING_VALS for e in encoding]): raise ValueError( 'elements of encoding must ' 'be one of {}'.format(ENCODING_VALS) ) else: encoding = [] if ignore_length is not None and not isinstance(ignore_length, list): raise ValueError("ignore_length must be a list or None.") if ignore_length is not None: if not all([isinstance(l, bool) for l in ignore_length]): raise ValueError("ignore_length elements must be booleans.") else: ignore_length = [] max_input_arg_len = max([ len(file_type), len(rate), len(bits), len(channels), len(encoding), len(ignore_length) ]) input_format = [] for _ in range(max_input_arg_len): input_format.append([]) for i, f in enumerate(file_type): input_format[i].extend(['-t', '{}'.format(f)]) for i, r in enumerate(rate): input_format[i].extend(['-r', '{}'.format(r)]) for i, b in enumerate(bits): input_format[i].extend(['-b', '{}'.format(b)]) for i, c in enumerate(channels): input_format[i].extend(['-c', '{}'.format(c)]) for i, e in enumerate(encoding): input_format[i].extend(['-e', '{}'.format(e)]) for i, l in enumerate(ignore_length): if l is True: input_format[i].append('--ignore-length') self.input_format = input_format return self
[ "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", "." ]
rabitt/pysox
python
https://github.com/rabitt/pysox/blob/eae89bde74567136ec3f723c3e6b369916d9b837/sox/combine.py#L151-L305
[ "def", "set_input_format", "(", "self", ",", "file_type", "=", "None", ",", "rate", "=", "None", ",", "bits", "=", "None", ",", "channels", "=", "None", ",", "encoding", "=", "None", ",", "ignore_length", "=", "None", ")", ":", "if", "file_type", "is", "not", "None", "and", "not", "isinstance", "(", "file_type", ",", "list", ")", ":", "raise", "ValueError", "(", "\"file_type must be a list or None.\"", ")", "if", "file_type", "is", "not", "None", ":", "if", "not", "all", "(", "[", "f", "in", "VALID_FORMATS", "for", "f", "in", "file_type", "]", ")", ":", "raise", "ValueError", "(", "'file_type elements '", "'must be one of {}'", ".", "format", "(", "VALID_FORMATS", ")", ")", "else", ":", "file_type", "=", "[", "]", "if", "rate", "is", "not", "None", "and", "not", "isinstance", "(", "rate", ",", "list", ")", ":", "raise", "ValueError", "(", "\"rate must be a list or None.\"", ")", "if", "rate", "is", "not", "None", ":", "if", "not", "all", "(", "[", "is_number", "(", "r", ")", "and", "r", ">", "0", "for", "r", "in", "rate", "]", ")", ":", "raise", "ValueError", "(", "'rate elements must be positive floats.'", ")", "else", ":", "rate", "=", "[", "]", "if", "bits", "is", "not", "None", "and", "not", "isinstance", "(", "bits", ",", "list", ")", ":", "raise", "ValueError", "(", "\"bits must be a list or None.\"", ")", "if", "bits", "is", "not", "None", ":", "if", "not", "all", "(", "[", "isinstance", "(", "b", ",", "int", ")", "and", "b", ">", "0", "for", "b", "in", "bits", "]", ")", ":", "raise", "ValueError", "(", "'bit elements must be positive ints.'", ")", "else", ":", "bits", "=", "[", "]", "if", "channels", "is", "not", "None", "and", "not", "isinstance", "(", "channels", ",", "list", ")", ":", "raise", "ValueError", "(", "\"channels must be a list or None.\"", ")", "if", "channels", "is", "not", "None", ":", "if", "not", "all", "(", "[", "isinstance", "(", "c", ",", "int", ")", "and", "c", ">", "0", "for", "c", "in", "channels", "]", ")", ":", "raise", "ValueError", "(", "'channel elements must be positive ints.'", ")", "else", ":", "channels", "=", "[", "]", "if", "encoding", "is", "not", "None", "and", "not", "isinstance", "(", "encoding", ",", "list", ")", ":", "raise", "ValueError", "(", "\"encoding must be a list or None.\"", ")", "if", "encoding", "is", "not", "None", ":", "if", "not", "all", "(", "[", "e", "in", "ENCODING_VALS", "for", "e", "in", "encoding", "]", ")", ":", "raise", "ValueError", "(", "'elements of encoding must '", "'be one of {}'", ".", "format", "(", "ENCODING_VALS", ")", ")", "else", ":", "encoding", "=", "[", "]", "if", "ignore_length", "is", "not", "None", "and", "not", "isinstance", "(", "ignore_length", ",", "list", ")", ":", "raise", "ValueError", "(", "\"ignore_length must be a list or None.\"", ")", "if", "ignore_length", "is", "not", "None", ":", "if", "not", "all", "(", "[", "isinstance", "(", "l", ",", "bool", ")", "for", "l", "in", "ignore_length", "]", ")", ":", "raise", "ValueError", "(", "\"ignore_length elements must be booleans.\"", ")", "else", ":", "ignore_length", "=", "[", "]", "max_input_arg_len", "=", "max", "(", "[", "len", "(", "file_type", ")", ",", "len", "(", "rate", ")", ",", "len", "(", "bits", ")", ",", "len", "(", "channels", ")", ",", "len", "(", "encoding", ")", ",", "len", "(", "ignore_length", ")", "]", ")", "input_format", "=", "[", "]", "for", "_", "in", "range", "(", "max_input_arg_len", ")", ":", "input_format", ".", "append", "(", "[", "]", ")", "for", "i", ",", "f", "in", "enumerate", "(", "file_type", ")", ":", "input_format", "[", "i", "]", ".", "extend", "(", "[", "'-t'", ",", "'{}'", ".", "format", "(", "f", ")", "]", ")", "for", "i", ",", "r", "in", "enumerate", "(", "rate", ")", ":", "input_format", "[", "i", "]", ".", "extend", "(", "[", "'-r'", ",", "'{}'", ".", "format", "(", "r", ")", "]", ")", "for", "i", ",", "b", "in", "enumerate", "(", "bits", ")", ":", "input_format", "[", "i", "]", ".", "extend", "(", "[", "'-b'", ",", "'{}'", ".", "format", "(", "b", ")", "]", ")", "for", "i", ",", "c", "in", "enumerate", "(", "channels", ")", ":", "input_format", "[", "i", "]", ".", "extend", "(", "[", "'-c'", ",", "'{}'", ".", "format", "(", "c", ")", "]", ")", "for", "i", ",", "e", "in", "enumerate", "(", "encoding", ")", ":", "input_format", "[", "i", "]", ".", "extend", "(", "[", "'-e'", ",", "'{}'", ".", "format", "(", "e", ")", "]", ")", "for", "i", ",", "l", "in", "enumerate", "(", "ignore_length", ")", ":", "if", "l", "is", "True", ":", "input_format", "[", "i", "]", ".", "append", "(", "'--ignore-length'", ")", "self", ".", "input_format", "=", "input_format", "return", "self" ]
eae89bde74567136ec3f723c3e6b369916d9b837
valid
bitrate
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
sox/file_info.py
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(input_filepath) output = soxi(input_filepath, 'b') if output == '0': logger.warning("Bitrate unavailable for %s", input_filepath) return int(output)
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(input_filepath) output = soxi(input_filepath, 'b') if output == '0': logger.warning("Bitrate unavailable for %s", input_filepath) return int(output)
[ "Number", "of", "bits", "per", "sample", "(", "0", "if", "not", "applicable", ")", "." ]
rabitt/pysox
python
https://github.com/rabitt/pysox/blob/eae89bde74567136ec3f723c3e6b369916d9b837/sox/file_info.py#L12-L31
[ "def", "bitrate", "(", "input_filepath", ")", ":", "validate_input_file", "(", "input_filepath", ")", "output", "=", "soxi", "(", "input_filepath", ",", "'b'", ")", "if", "output", "==", "'0'", ":", "logger", ".", "warning", "(", "\"Bitrate unavailable for %s\"", ",", "input_filepath", ")", "return", "int", "(", "output", ")" ]
eae89bde74567136ec3f723c3e6b369916d9b837
valid
duration
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.
sox/file_info.py
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. ''' validate_input_file(input_filepath) output = soxi(input_filepath, 'D') if output == '0': logger.warning("Duration unavailable for %s", input_filepath) return float(output)
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. ''' validate_input_file(input_filepath) output = soxi(input_filepath, 'D') if output == '0': logger.warning("Duration unavailable for %s", input_filepath) return float(output)
[ "Show", "duration", "in", "seconds", "(", "0", "if", "unavailable", ")", "." ]
rabitt/pysox
python
https://github.com/rabitt/pysox/blob/eae89bde74567136ec3f723c3e6b369916d9b837/sox/file_info.py#L73-L93
[ "def", "duration", "(", "input_filepath", ")", ":", "validate_input_file", "(", "input_filepath", ")", "output", "=", "soxi", "(", "input_filepath", ",", "'D'", ")", "if", "output", "==", "'0'", ":", "logger", ".", "warning", "(", "\"Duration unavailable for %s\"", ",", "input_filepath", ")", "return", "float", "(", "output", ")" ]
eae89bde74567136ec3f723c3e6b369916d9b837
valid
num_samples
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
sox/file_info.py
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 ''' validate_input_file(input_filepath) output = soxi(input_filepath, 's') if output == '0': logger.warning("Number of samples unavailable for %s", input_filepath) return int(output)
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 ''' validate_input_file(input_filepath) output = soxi(input_filepath, 's') if output == '0': logger.warning("Number of samples unavailable for %s", input_filepath) return int(output)
[ "Show", "number", "of", "samples", "(", "0", "if", "unavailable", ")", "." ]
rabitt/pysox
python
https://github.com/rabitt/pysox/blob/eae89bde74567136ec3f723c3e6b369916d9b837/sox/file_info.py#L134-L153
[ "def", "num_samples", "(", "input_filepath", ")", ":", "validate_input_file", "(", "input_filepath", ")", "output", "=", "soxi", "(", "input_filepath", ",", "'s'", ")", "if", "output", "==", "'0'", ":", "logger", ".", "warning", "(", "\"Number of samples unavailable for %s\"", ",", "input_filepath", ")", "return", "int", "(", "output", ")" ]
eae89bde74567136ec3f723c3e6b369916d9b837
valid
silent
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 determined silent.
sox/file_info.py
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 determined silent. ''' validate_input_file(input_filepath) stat_dictionary = stat(input_filepath) mean_norm = stat_dictionary['Mean norm'] if mean_norm is not float('nan'): if mean_norm >= threshold: return False else: return True else: return True
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 determined silent. ''' validate_input_file(input_filepath) stat_dictionary = stat(input_filepath) mean_norm = stat_dictionary['Mean norm'] if mean_norm is not float('nan'): if mean_norm >= threshold: return False else: return True else: return True
[ "Determine", "if", "an", "input", "file", "is", "silent", "." ]
rabitt/pysox
python
https://github.com/rabitt/pysox/blob/eae89bde74567136ec3f723c3e6b369916d9b837/sox/file_info.py#L175-L200
[ "def", "silent", "(", "input_filepath", ",", "threshold", "=", "0.001", ")", ":", "validate_input_file", "(", "input_filepath", ")", "stat_dictionary", "=", "stat", "(", "input_filepath", ")", "mean_norm", "=", "stat_dictionary", "[", "'Mean norm'", "]", "if", "mean_norm", "is", "not", "float", "(", "'nan'", ")", ":", "if", "mean_norm", ">=", "threshold", ":", "return", "False", "else", ":", "return", "True", "else", ":", "return", "True" ]
eae89bde74567136ec3f723c3e6b369916d9b837
valid
validate_input_file
Input file validation function. Checks that file exists and can be processed by SoX. Parameters ---------- input_filepath : str The input filepath.
sox/file_info.py
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_filepath {} does not exist.".format(input_filepath) ) ext = file_extension(input_filepath) if ext not in VALID_FORMATS: logger.info("Valid formats: %s", " ".join(VALID_FORMATS)) logger.warning( "This install of SoX cannot process .{} files.".format(ext) )
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_filepath {} does not exist.".format(input_filepath) ) ext = file_extension(input_filepath) if ext not in VALID_FORMATS: logger.info("Valid formats: %s", " ".join(VALID_FORMATS)) logger.warning( "This install of SoX cannot process .{} files.".format(ext) )
[ "Input", "file", "validation", "function", ".", "Checks", "that", "file", "exists", "and", "can", "be", "processed", "by", "SoX", "." ]
rabitt/pysox
python
https://github.com/rabitt/pysox/blob/eae89bde74567136ec3f723c3e6b369916d9b837/sox/file_info.py#L203-L222
[ "def", "validate_input_file", "(", "input_filepath", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "input_filepath", ")", ":", "raise", "IOError", "(", "\"input_filepath {} does not exist.\"", ".", "format", "(", "input_filepath", ")", ")", "ext", "=", "file_extension", "(", "input_filepath", ")", "if", "ext", "not", "in", "VALID_FORMATS", ":", "logger", ".", "info", "(", "\"Valid formats: %s\"", ",", "\" \"", ".", "join", "(", "VALID_FORMATS", ")", ")", "logger", ".", "warning", "(", "\"This install of SoX cannot process .{} files.\"", ".", "format", "(", "ext", ")", ")" ]
eae89bde74567136ec3f723c3e6b369916d9b837
valid
validate_input_file_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.
sox/file_info.py
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_filepath_list, list): raise TypeError("input_filepath_list must be a list.") elif len(input_filepath_list) < 2: raise ValueError("input_filepath_list must have at least 2 files.") for input_filepath in input_filepath_list: validate_input_file(input_filepath)
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_filepath_list, list): raise TypeError("input_filepath_list must be a list.") elif len(input_filepath_list) < 2: raise ValueError("input_filepath_list must have at least 2 files.") for input_filepath in input_filepath_list: validate_input_file(input_filepath)
[ "Input", "file", "list", "validation", "function", ".", "Checks", "that", "object", "is", "a", "list", "and", "contains", "valid", "filepaths", "that", "can", "be", "processed", "by", "SoX", "." ]
rabitt/pysox
python
https://github.com/rabitt/pysox/blob/eae89bde74567136ec3f723c3e6b369916d9b837/sox/file_info.py#L225-L241
[ "def", "validate_input_file_list", "(", "input_filepath_list", ")", ":", "if", "not", "isinstance", "(", "input_filepath_list", ",", "list", ")", ":", "raise", "TypeError", "(", "\"input_filepath_list must be a list.\"", ")", "elif", "len", "(", "input_filepath_list", ")", "<", "2", ":", "raise", "ValueError", "(", "\"input_filepath_list must have at least 2 files.\"", ")", "for", "input_filepath", "in", "input_filepath_list", ":", "validate_input_file", "(", "input_filepath", ")" ]
eae89bde74567136ec3f723c3e6b369916d9b837
valid
validate_output_file
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 filepath. Returns: -------- output_filepath : str The output filepath.
sox/file_info.py
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 filepath. Returns: -------- output_filepath : str The output filepath. ''' nowrite_conditions = [ bool(os.path.dirname(output_filepath)) or\ not os.access(os.getcwd(), os.W_OK), not os.access(os.path.dirname(output_filepath), os.W_OK)] if all(nowrite_conditions): raise IOError( "SoX cannot write to output_filepath {}".format(output_filepath) ) ext = file_extension(output_filepath) if ext not in VALID_FORMATS: logger.info("Valid formats: %s", " ".join(VALID_FORMATS)) logger.warning( "This install of SoX cannot process .{} files.".format(ext) ) if os.path.exists(output_filepath): logger.warning( 'output_file: %s already exists and will be overwritten on build', output_filepath )
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 filepath. Returns: -------- output_filepath : str The output filepath. ''' nowrite_conditions = [ bool(os.path.dirname(output_filepath)) or\ not os.access(os.getcwd(), os.W_OK), not os.access(os.path.dirname(output_filepath), os.W_OK)] if all(nowrite_conditions): raise IOError( "SoX cannot write to output_filepath {}".format(output_filepath) ) ext = file_extension(output_filepath) if ext not in VALID_FORMATS: logger.info("Valid formats: %s", " ".join(VALID_FORMATS)) logger.warning( "This install of SoX cannot process .{} files.".format(ext) ) if os.path.exists(output_filepath): logger.warning( 'output_file: %s already exists and will be overwritten on build', 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", "." ]
rabitt/pysox
python
https://github.com/rabitt/pysox/blob/eae89bde74567136ec3f723c3e6b369916d9b837/sox/file_info.py#L244-L282
[ "def", "validate_output_file", "(", "output_filepath", ")", ":", "nowrite_conditions", "=", "[", "bool", "(", "os", ".", "path", ".", "dirname", "(", "output_filepath", ")", ")", "or", "not", "os", ".", "access", "(", "os", ".", "getcwd", "(", ")", ",", "os", ".", "W_OK", ")", ",", "not", "os", ".", "access", "(", "os", ".", "path", ".", "dirname", "(", "output_filepath", ")", ",", "os", ".", "W_OK", ")", "]", "if", "all", "(", "nowrite_conditions", ")", ":", "raise", "IOError", "(", "\"SoX cannot write to output_filepath {}\"", ".", "format", "(", "output_filepath", ")", ")", "ext", "=", "file_extension", "(", "output_filepath", ")", "if", "ext", "not", "in", "VALID_FORMATS", ":", "logger", ".", "info", "(", "\"Valid formats: %s\"", ",", "\" \"", ".", "join", "(", "VALID_FORMATS", ")", ")", "logger", ".", "warning", "(", "\"This install of SoX cannot process .{} files.\"", ".", "format", "(", "ext", ")", ")", "if", "os", ".", "path", ".", "exists", "(", "output_filepath", ")", ":", "logger", ".", "warning", "(", "'output_file: %s already exists and will be overwritten on build'", ",", "output_filepath", ")" ]
eae89bde74567136ec3f723c3e6b369916d9b837
valid
info
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 * duration * num_samples * encoding * silent
sox/file_info.py
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 * duration * num_samples * encoding * silent ''' info_dictionary = { 'channels': channels(filepath), 'sample_rate': sample_rate(filepath), 'bitrate': bitrate(filepath), 'duration': duration(filepath), 'num_samples': num_samples(filepath), 'encoding': encoding(filepath), 'silent': silent(filepath) } return info_dictionary
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 * duration * num_samples * encoding * silent ''' info_dictionary = { 'channels': channels(filepath), 'sample_rate': sample_rate(filepath), 'bitrate': bitrate(filepath), 'duration': duration(filepath), 'num_samples': num_samples(filepath), 'encoding': encoding(filepath), 'silent': silent(filepath) } return info_dictionary
[ "Get", "a", "dictionary", "of", "file", "information" ]
rabitt/pysox
python
https://github.com/rabitt/pysox/blob/eae89bde74567136ec3f723c3e6b369916d9b837/sox/file_info.py#L301-L330
[ "def", "info", "(", "filepath", ")", ":", "info_dictionary", "=", "{", "'channels'", ":", "channels", "(", "filepath", ")", ",", "'sample_rate'", ":", "sample_rate", "(", "filepath", ")", ",", "'bitrate'", ":", "bitrate", "(", "filepath", ")", ",", "'duration'", ":", "duration", "(", "filepath", ")", ",", "'num_samples'", ":", "num_samples", "(", "filepath", ")", ",", "'encoding'", ":", "encoding", "(", "filepath", ")", ",", "'silent'", ":", "silent", "(", "filepath", ")", "}", "return", "info_dictionary" ]
eae89bde74567136ec3f723c3e6b369916d9b837
valid
_stat_call
Call sox's stat function. Parameters ---------- filepath : str File path. Returns ------- stat_output : str Sox output from stderr.
sox/file_info.py
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(args) return stat_output
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(args) return stat_output
[ "Call", "sox", "s", "stat", "function", "." ]
rabitt/pysox
python
https://github.com/rabitt/pysox/blob/eae89bde74567136ec3f723c3e6b369916d9b837/sox/file_info.py#L351-L367
[ "def", "_stat_call", "(", "filepath", ")", ":", "validate_input_file", "(", "filepath", ")", "args", "=", "[", "'sox'", ",", "filepath", ",", "'-n'", ",", "'stat'", "]", "_", ",", "_", ",", "stat_output", "=", "sox", "(", "args", ")", "return", "stat_output" ]
eae89bde74567136ec3f723c3e6b369916d9b837
valid
_parse_stat
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.
sox/file_info.py
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 = {} for line in lines: split_line = line.split(':') if len(split_line) == 2: key = split_line[0] val = split_line[1].strip(' ') try: val = float(val) except ValueError: val = None stat_dict[key] = val return stat_dict
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 = {} for line in lines: split_line = line.split(':') if len(split_line) == 2: key = split_line[0] val = split_line[1].strip(' ') try: val = float(val) except ValueError: val = None stat_dict[key] = val return stat_dict
[ "Parse", "the", "string", "output", "from", "sox", "s", "stat", "function" ]
rabitt/pysox
python
https://github.com/rabitt/pysox/blob/eae89bde74567136ec3f723c3e6b369916d9b837/sox/file_info.py#L370-L396
[ "def", "_parse_stat", "(", "stat_output", ")", ":", "lines", "=", "stat_output", ".", "split", "(", "'\\n'", ")", "stat_dict", "=", "{", "}", "for", "line", "in", "lines", ":", "split_line", "=", "line", ".", "split", "(", "':'", ")", "if", "len", "(", "split_line", ")", "==", "2", ":", "key", "=", "split_line", "[", "0", "]", "val", "=", "split_line", "[", "1", "]", ".", "strip", "(", "' '", ")", "try", ":", "val", "=", "float", "(", "val", ")", "except", "ValueError", ":", "val", "=", "None", "stat_dict", "[", "key", "]", "=", "val", "return", "stat_dict" ]
eae89bde74567136ec3f723c3e6b369916d9b837
valid
Transformer.set_globals
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. Parameters ---------- dither : bool, default=False If True, dithering is applied for low files with low bit rates. guard : bool, default=False If True, invokes the gain effect to guard against clipping. multithread : bool, default=False If True, each channel is processed in parallel. replay_gain : bool, default=False If True, applies replay-gain adjustment to input-files. verbosity : int, default=2 SoX's verbosity level. One of: * 0 : No messages are shown at all * 1 : Only error messages are shown. These are generated if SoX cannot complete the requested commands. * 2 : Warning messages are also shown. These are generated if SoX can complete the requested commands, but not exactly according to the requested command parameters, or if clipping occurs. * 3 : Descriptions of SoX’s processing phases are also shown. Useful for seeing exactly how SoX is processing your audio. * 4, >4 : Messages to help with debugging SoX are also shown.
sox/transform.py
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. Parameters ---------- dither : bool, default=False If True, dithering is applied for low files with low bit rates. guard : bool, default=False If True, invokes the gain effect to guard against clipping. multithread : bool, default=False If True, each channel is processed in parallel. replay_gain : bool, default=False If True, applies replay-gain adjustment to input-files. verbosity : int, default=2 SoX's verbosity level. One of: * 0 : No messages are shown at all * 1 : Only error messages are shown. These are generated if SoX cannot complete the requested commands. * 2 : Warning messages are also shown. These are generated if SoX can complete the requested commands, but not exactly according to the requested command parameters, or if clipping occurs. * 3 : Descriptions of SoX’s processing phases are also shown. Useful for seeing exactly how SoX is processing your audio. * 4, >4 : Messages to help with debugging SoX are also shown. ''' if not isinstance(dither, bool): raise ValueError('dither must be a boolean.') if not isinstance(guard, bool): raise ValueError('guard must be a boolean.') if not isinstance(multithread, bool): raise ValueError('multithread must be a boolean.') if not isinstance(replay_gain, bool): raise ValueError('replay_gain must be a boolean.') if verbosity not in VERBOSITY_VALS: raise ValueError( 'Invalid value for VERBOSITY. Must be one {}'.format( VERBOSITY_VALS) ) global_args = [] if not dither: global_args.append('-D') if guard: global_args.append('-G') if multithread: global_args.append('--multi-threaded') if replay_gain: global_args.append('--replay-gain') global_args.append('track') global_args.append('-V{}'.format(verbosity)) self.globals = global_args return self
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. Parameters ---------- dither : bool, default=False If True, dithering is applied for low files with low bit rates. guard : bool, default=False If True, invokes the gain effect to guard against clipping. multithread : bool, default=False If True, each channel is processed in parallel. replay_gain : bool, default=False If True, applies replay-gain adjustment to input-files. verbosity : int, default=2 SoX's verbosity level. One of: * 0 : No messages are shown at all * 1 : Only error messages are shown. These are generated if SoX cannot complete the requested commands. * 2 : Warning messages are also shown. These are generated if SoX can complete the requested commands, but not exactly according to the requested command parameters, or if clipping occurs. * 3 : Descriptions of SoX’s processing phases are also shown. Useful for seeing exactly how SoX is processing your audio. * 4, >4 : Messages to help with debugging SoX are also shown. ''' if not isinstance(dither, bool): raise ValueError('dither must be a boolean.') if not isinstance(guard, bool): raise ValueError('guard must be a boolean.') if not isinstance(multithread, bool): raise ValueError('multithread must be a boolean.') if not isinstance(replay_gain, bool): raise ValueError('replay_gain must be a boolean.') if verbosity not in VERBOSITY_VALS: raise ValueError( 'Invalid value for VERBOSITY. Must be one {}'.format( VERBOSITY_VALS) ) global_args = [] if not dither: global_args.append('-D') if guard: global_args.append('-G') if multithread: global_args.append('--multi-threaded') if replay_gain: global_args.append('--replay-gain') global_args.append('track') global_args.append('-V{}'.format(verbosity)) self.globals = global_args return self
[ "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", "." ]
rabitt/pysox
python
https://github.com/rabitt/pysox/blob/eae89bde74567136ec3f723c3e6b369916d9b837/sox/transform.py#L67-L134
[ "def", "set_globals", "(", "self", ",", "dither", "=", "False", ",", "guard", "=", "False", ",", "multithread", "=", "False", ",", "replay_gain", "=", "False", ",", "verbosity", "=", "2", ")", ":", "if", "not", "isinstance", "(", "dither", ",", "bool", ")", ":", "raise", "ValueError", "(", "'dither must be a boolean.'", ")", "if", "not", "isinstance", "(", "guard", ",", "bool", ")", ":", "raise", "ValueError", "(", "'guard must be a boolean.'", ")", "if", "not", "isinstance", "(", "multithread", ",", "bool", ")", ":", "raise", "ValueError", "(", "'multithread must be a boolean.'", ")", "if", "not", "isinstance", "(", "replay_gain", ",", "bool", ")", ":", "raise", "ValueError", "(", "'replay_gain must be a boolean.'", ")", "if", "verbosity", "not", "in", "VERBOSITY_VALS", ":", "raise", "ValueError", "(", "'Invalid value for VERBOSITY. Must be one {}'", ".", "format", "(", "VERBOSITY_VALS", ")", ")", "global_args", "=", "[", "]", "if", "not", "dither", ":", "global_args", ".", "append", "(", "'-D'", ")", "if", "guard", ":", "global_args", ".", "append", "(", "'-G'", ")", "if", "multithread", ":", "global_args", ".", "append", "(", "'--multi-threaded'", ")", "if", "replay_gain", ":", "global_args", ".", "append", "(", "'--replay-gain'", ")", "global_args", ".", "append", "(", "'track'", ")", "global_args", ".", "append", "(", "'-V{}'", ".", "format", "(", "verbosity", ")", ")", "self", ".", "globals", "=", "global_args", "return", "self" ]
eae89bde74567136ec3f723c3e6b369916d9b837
valid
Transformer.set_input_format
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. If this function is not explicity called the input format is inferred from the file extension or the file's header. Parameters ---------- file_type : str or None, default=None The file type of the input audio file. Should be the same as what the file extension would be, for ex. 'mp3' or 'wav'. rate : float or None, default=None The sample rate of the input audio file. If None the sample rate is inferred. bits : int or None, default=None The number of bits per sample. If None, the number of bits per sample is inferred. channels : int or None, default=None The number of channels in the audio file. If None the number of channels is inferred. encoding : str or None, default=None The audio encoding type. Sometimes needed with file-types that support more than one encoding type. One of: * signed-integer : PCM data stored as signed (‘two’s complement’) integers. Commonly used with a 16 or 24−bit encoding size. A value of 0 represents minimum signal power. * unsigned-integer : PCM data stored as unsigned integers. Commonly used with an 8-bit encoding size. A value of 0 represents maximum signal power. * floating-point : PCM data stored as IEEE 753 single precision (32-bit) or double precision (64-bit) floating-point (‘real’) numbers. A value of 0 represents minimum signal power. * a-law : International telephony standard for logarithmic encoding to 8 bits per sample. It has a precision equivalent to roughly 13-bit PCM and is sometimes encoded with reversed bit-ordering. * u-law : North American telephony standard for logarithmic encoding to 8 bits per sample. A.k.a. μ-law. It has a precision equivalent to roughly 14-bit PCM and is sometimes encoded with reversed bit-ordering. * oki-adpcm : OKI (a.k.a. VOX, Dialogic, or Intel) 4-bit ADPCM; it has a precision equivalent to roughly 12-bit PCM. ADPCM is a form of audio compression that has a good compromise between audio quality and encoding/decoding speed. * ima-adpcm : IMA (a.k.a. DVI) 4-bit ADPCM; it has a precision equivalent to roughly 13-bit PCM. * ms-adpcm : Microsoft 4-bit ADPCM; it has a precision equivalent to roughly 14-bit PCM. * gsm-full-rate : GSM is currently used for the vast majority of the world’s digital wireless telephone calls. It utilises several audio formats with different bit-rates and associated speech quality. SoX has support for GSM’s original 13kbps ‘Full Rate’ audio format. It is usually CPU-intensive to work with GSM audio. ignore_length : bool, default=False If True, overrides an (incorrect) audio length given in an audio file’s header. If this option is given then SoX will keep reading audio until it reaches the end of the input file.
sox/transform.py
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 file arguments. If this function is not explicity called the input format is inferred from the file extension or the file's header. Parameters ---------- file_type : str or None, default=None The file type of the input audio file. Should be the same as what the file extension would be, for ex. 'mp3' or 'wav'. rate : float or None, default=None The sample rate of the input audio file. If None the sample rate is inferred. bits : int or None, default=None The number of bits per sample. If None, the number of bits per sample is inferred. channels : int or None, default=None The number of channels in the audio file. If None the number of channels is inferred. encoding : str or None, default=None The audio encoding type. Sometimes needed with file-types that support more than one encoding type. One of: * signed-integer : PCM data stored as signed (‘two’s complement’) integers. Commonly used with a 16 or 24−bit encoding size. A value of 0 represents minimum signal power. * unsigned-integer : PCM data stored as unsigned integers. Commonly used with an 8-bit encoding size. A value of 0 represents maximum signal power. * floating-point : PCM data stored as IEEE 753 single precision (32-bit) or double precision (64-bit) floating-point (‘real’) numbers. A value of 0 represents minimum signal power. * a-law : International telephony standard for logarithmic encoding to 8 bits per sample. It has a precision equivalent to roughly 13-bit PCM and is sometimes encoded with reversed bit-ordering. * u-law : North American telephony standard for logarithmic encoding to 8 bits per sample. A.k.a. μ-law. It has a precision equivalent to roughly 14-bit PCM and is sometimes encoded with reversed bit-ordering. * oki-adpcm : OKI (a.k.a. VOX, Dialogic, or Intel) 4-bit ADPCM; it has a precision equivalent to roughly 12-bit PCM. ADPCM is a form of audio compression that has a good compromise between audio quality and encoding/decoding speed. * ima-adpcm : IMA (a.k.a. DVI) 4-bit ADPCM; it has a precision equivalent to roughly 13-bit PCM. * ms-adpcm : Microsoft 4-bit ADPCM; it has a precision equivalent to roughly 14-bit PCM. * gsm-full-rate : GSM is currently used for the vast majority of the world’s digital wireless telephone calls. It utilises several audio formats with different bit-rates and associated speech quality. SoX has support for GSM’s original 13kbps ‘Full Rate’ audio format. It is usually CPU-intensive to work with GSM audio. ignore_length : bool, default=False If True, overrides an (incorrect) audio length given in an audio file’s header. If this option is given then SoX will keep reading audio until it reaches the end of the input file. ''' if file_type not in VALID_FORMATS + [None]: raise ValueError( 'Invalid file_type. Must be one of {}'.format(VALID_FORMATS) ) if not is_number(rate) and rate is not None: raise ValueError('rate must be a float or None') if rate is not None and rate <= 0: raise ValueError('rate must be a positive number') if not isinstance(bits, int) and bits is not None: raise ValueError('bits must be an int or None') if bits is not None and bits <= 0: raise ValueError('bits must be a positive number') if not isinstance(channels, int) and channels is not None: raise ValueError('channels must be an int or None') if channels is not None and channels <= 0: raise ValueError('channels must be a positive number') if encoding not in ENCODING_VALS + [None]: raise ValueError( 'Invalid encoding. Must be one of {}'.format(ENCODING_VALS) ) if not isinstance(ignore_length, bool): raise ValueError('ignore_length must be a boolean') input_format = [] if file_type is not None: input_format.extend(['-t', '{}'.format(file_type)]) if rate is not None: input_format.extend(['-r', '{:f}'.format(rate)]) if bits is not None: input_format.extend(['-b', '{}'.format(bits)]) if channels is not None: input_format.extend(['-c', '{}'.format(channels)]) if encoding is not None: input_format.extend(['-e', '{}'.format(encoding)]) if ignore_length: input_format.append('--ignore-length') self.input_format = input_format return self
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 file arguments. If this function is not explicity called the input format is inferred from the file extension or the file's header. Parameters ---------- file_type : str or None, default=None The file type of the input audio file. Should be the same as what the file extension would be, for ex. 'mp3' or 'wav'. rate : float or None, default=None The sample rate of the input audio file. If None the sample rate is inferred. bits : int or None, default=None The number of bits per sample. If None, the number of bits per sample is inferred. channels : int or None, default=None The number of channels in the audio file. If None the number of channels is inferred. encoding : str or None, default=None The audio encoding type. Sometimes needed with file-types that support more than one encoding type. One of: * signed-integer : PCM data stored as signed (‘two’s complement’) integers. Commonly used with a 16 or 24−bit encoding size. A value of 0 represents minimum signal power. * unsigned-integer : PCM data stored as unsigned integers. Commonly used with an 8-bit encoding size. A value of 0 represents maximum signal power. * floating-point : PCM data stored as IEEE 753 single precision (32-bit) or double precision (64-bit) floating-point (‘real’) numbers. A value of 0 represents minimum signal power. * a-law : International telephony standard for logarithmic encoding to 8 bits per sample. It has a precision equivalent to roughly 13-bit PCM and is sometimes encoded with reversed bit-ordering. * u-law : North American telephony standard for logarithmic encoding to 8 bits per sample. A.k.a. μ-law. It has a precision equivalent to roughly 14-bit PCM and is sometimes encoded with reversed bit-ordering. * oki-adpcm : OKI (a.k.a. VOX, Dialogic, or Intel) 4-bit ADPCM; it has a precision equivalent to roughly 12-bit PCM. ADPCM is a form of audio compression that has a good compromise between audio quality and encoding/decoding speed. * ima-adpcm : IMA (a.k.a. DVI) 4-bit ADPCM; it has a precision equivalent to roughly 13-bit PCM. * ms-adpcm : Microsoft 4-bit ADPCM; it has a precision equivalent to roughly 14-bit PCM. * gsm-full-rate : GSM is currently used for the vast majority of the world’s digital wireless telephone calls. It utilises several audio formats with different bit-rates and associated speech quality. SoX has support for GSM’s original 13kbps ‘Full Rate’ audio format. It is usually CPU-intensive to work with GSM audio. ignore_length : bool, default=False If True, overrides an (incorrect) audio length given in an audio file’s header. If this option is given then SoX will keep reading audio until it reaches the end of the input file. ''' if file_type not in VALID_FORMATS + [None]: raise ValueError( 'Invalid file_type. Must be one of {}'.format(VALID_FORMATS) ) if not is_number(rate) and rate is not None: raise ValueError('rate must be a float or None') if rate is not None and rate <= 0: raise ValueError('rate must be a positive number') if not isinstance(bits, int) and bits is not None: raise ValueError('bits must be an int or None') if bits is not None and bits <= 0: raise ValueError('bits must be a positive number') if not isinstance(channels, int) and channels is not None: raise ValueError('channels must be an int or None') if channels is not None and channels <= 0: raise ValueError('channels must be a positive number') if encoding not in ENCODING_VALS + [None]: raise ValueError( 'Invalid encoding. Must be one of {}'.format(ENCODING_VALS) ) if not isinstance(ignore_length, bool): raise ValueError('ignore_length must be a boolean') input_format = [] if file_type is not None: input_format.extend(['-t', '{}'.format(file_type)]) if rate is not None: input_format.extend(['-r', '{:f}'.format(rate)]) if bits is not None: input_format.extend(['-b', '{}'.format(bits)]) if channels is not None: input_format.extend(['-c', '{}'.format(channels)]) if encoding is not None: input_format.extend(['-e', '{}'.format(encoding)]) if ignore_length: input_format.append('--ignore-length') self.input_format = input_format return self
[ "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", "." ]
rabitt/pysox
python
https://github.com/rabitt/pysox/blob/eae89bde74567136ec3f723c3e6b369916d9b837/sox/transform.py#L136-L253
[ "def", "set_input_format", "(", "self", ",", "file_type", "=", "None", ",", "rate", "=", "None", ",", "bits", "=", "None", ",", "channels", "=", "None", ",", "encoding", "=", "None", ",", "ignore_length", "=", "False", ")", ":", "if", "file_type", "not", "in", "VALID_FORMATS", "+", "[", "None", "]", ":", "raise", "ValueError", "(", "'Invalid file_type. Must be one of {}'", ".", "format", "(", "VALID_FORMATS", ")", ")", "if", "not", "is_number", "(", "rate", ")", "and", "rate", "is", "not", "None", ":", "raise", "ValueError", "(", "'rate must be a float or None'", ")", "if", "rate", "is", "not", "None", "and", "rate", "<=", "0", ":", "raise", "ValueError", "(", "'rate must be a positive number'", ")", "if", "not", "isinstance", "(", "bits", ",", "int", ")", "and", "bits", "is", "not", "None", ":", "raise", "ValueError", "(", "'bits must be an int or None'", ")", "if", "bits", "is", "not", "None", "and", "bits", "<=", "0", ":", "raise", "ValueError", "(", "'bits must be a positive number'", ")", "if", "not", "isinstance", "(", "channels", ",", "int", ")", "and", "channels", "is", "not", "None", ":", "raise", "ValueError", "(", "'channels must be an int or None'", ")", "if", "channels", "is", "not", "None", "and", "channels", "<=", "0", ":", "raise", "ValueError", "(", "'channels must be a positive number'", ")", "if", "encoding", "not", "in", "ENCODING_VALS", "+", "[", "None", "]", ":", "raise", "ValueError", "(", "'Invalid encoding. Must be one of {}'", ".", "format", "(", "ENCODING_VALS", ")", ")", "if", "not", "isinstance", "(", "ignore_length", ",", "bool", ")", ":", "raise", "ValueError", "(", "'ignore_length must be a boolean'", ")", "input_format", "=", "[", "]", "if", "file_type", "is", "not", "None", ":", "input_format", ".", "extend", "(", "[", "'-t'", ",", "'{}'", ".", "format", "(", "file_type", ")", "]", ")", "if", "rate", "is", "not", "None", ":", "input_format", ".", "extend", "(", "[", "'-r'", ",", "'{:f}'", ".", "format", "(", "rate", ")", "]", ")", "if", "bits", "is", "not", "None", ":", "input_format", ".", "extend", "(", "[", "'-b'", ",", "'{}'", ".", "format", "(", "bits", ")", "]", ")", "if", "channels", "is", "not", "None", ":", "input_format", ".", "extend", "(", "[", "'-c'", ",", "'{}'", ".", "format", "(", "channels", ")", "]", ")", "if", "encoding", "is", "not", "None", ":", "input_format", ".", "extend", "(", "[", "'-e'", ",", "'{}'", ".", "format", "(", "encoding", ")", "]", ")", "if", "ignore_length", ":", "input_format", ".", "append", "(", "'--ignore-length'", ")", "self", ".", "input_format", "=", "input_format", "return", "self" ]
eae89bde74567136ec3f723c3e6b369916d9b837
valid
Transformer.set_output_format
Sets output file format arguments. These arguments will overwrite any format related arguments supplied by other effects (e.g. rate). If this function is not explicity called the output format is inferred from the file extension or the file's header. Parameters ---------- file_type : str or None, default=None The file type of the output audio file. Should be the same as what the file extension would be, for ex. 'mp3' or 'wav'. rate : float or None, default=None The sample rate of the output audio file. If None the sample rate is inferred. bits : int or None, default=None The number of bits per sample. If None, the number of bits per sample is inferred. channels : int or None, default=None The number of channels in the audio file. If None the number of channels is inferred. encoding : str or None, default=None The audio encoding type. Sometimes needed with file-types that support more than one encoding type. One of: * signed-integer : PCM data stored as signed (‘two’s complement’) integers. Commonly used with a 16 or 24−bit encoding size. A value of 0 represents minimum signal power. * unsigned-integer : PCM data stored as unsigned integers. Commonly used with an 8-bit encoding size. A value of 0 represents maximum signal power. * floating-point : PCM data stored as IEEE 753 single precision (32-bit) or double precision (64-bit) floating-point (‘real’) numbers. A value of 0 represents minimum signal power. * a-law : International telephony standard for logarithmic encoding to 8 bits per sample. It has a precision equivalent to roughly 13-bit PCM and is sometimes encoded with reversed bit-ordering. * u-law : North American telephony standard for logarithmic encoding to 8 bits per sample. A.k.a. μ-law. It has a precision equivalent to roughly 14-bit PCM and is sometimes encoded with reversed bit-ordering. * oki-adpcm : OKI (a.k.a. VOX, Dialogic, or Intel) 4-bit ADPCM; it has a precision equivalent to roughly 12-bit PCM. ADPCM is a form of audio compression that has a good compromise between audio quality and encoding/decoding speed. * ima-adpcm : IMA (a.k.a. DVI) 4-bit ADPCM; it has a precision equivalent to roughly 13-bit PCM. * ms-adpcm : Microsoft 4-bit ADPCM; it has a precision equivalent to roughly 14-bit PCM. * gsm-full-rate : GSM is currently used for the vast majority of the world’s digital wireless telephone calls. It utilises several audio formats with different bit-rates and associated speech quality. SoX has support for GSM’s original 13kbps ‘Full Rate’ audio format. It is usually CPU-intensive to work with GSM audio. comments : str or None, default=None If not None, the string is added as a comment in the header of the output audio file. If None, no comments are added. append_comments : bool, default=True If True, comment strings are appended to SoX's default comments. If False, the supplied comment replaces the existing comment.
sox/transform.py
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 effects (e.g. rate). If this function is not explicity called the output format is inferred from the file extension or the file's header. Parameters ---------- file_type : str or None, default=None The file type of the output audio file. Should be the same as what the file extension would be, for ex. 'mp3' or 'wav'. rate : float or None, default=None The sample rate of the output audio file. If None the sample rate is inferred. bits : int or None, default=None The number of bits per sample. If None, the number of bits per sample is inferred. channels : int or None, default=None The number of channels in the audio file. If None the number of channels is inferred. encoding : str or None, default=None The audio encoding type. Sometimes needed with file-types that support more than one encoding type. One of: * signed-integer : PCM data stored as signed (‘two’s complement’) integers. Commonly used with a 16 or 24−bit encoding size. A value of 0 represents minimum signal power. * unsigned-integer : PCM data stored as unsigned integers. Commonly used with an 8-bit encoding size. A value of 0 represents maximum signal power. * floating-point : PCM data stored as IEEE 753 single precision (32-bit) or double precision (64-bit) floating-point (‘real’) numbers. A value of 0 represents minimum signal power. * a-law : International telephony standard for logarithmic encoding to 8 bits per sample. It has a precision equivalent to roughly 13-bit PCM and is sometimes encoded with reversed bit-ordering. * u-law : North American telephony standard for logarithmic encoding to 8 bits per sample. A.k.a. μ-law. It has a precision equivalent to roughly 14-bit PCM and is sometimes encoded with reversed bit-ordering. * oki-adpcm : OKI (a.k.a. VOX, Dialogic, or Intel) 4-bit ADPCM; it has a precision equivalent to roughly 12-bit PCM. ADPCM is a form of audio compression that has a good compromise between audio quality and encoding/decoding speed. * ima-adpcm : IMA (a.k.a. DVI) 4-bit ADPCM; it has a precision equivalent to roughly 13-bit PCM. * ms-adpcm : Microsoft 4-bit ADPCM; it has a precision equivalent to roughly 14-bit PCM. * gsm-full-rate : GSM is currently used for the vast majority of the world’s digital wireless telephone calls. It utilises several audio formats with different bit-rates and associated speech quality. SoX has support for GSM’s original 13kbps ‘Full Rate’ audio format. It is usually CPU-intensive to work with GSM audio. comments : str or None, default=None If not None, the string is added as a comment in the header of the output audio file. If None, no comments are added. append_comments : bool, default=True If True, comment strings are appended to SoX's default comments. If False, the supplied comment replaces the existing comment. ''' if file_type not in VALID_FORMATS + [None]: raise ValueError( 'Invalid file_type. Must be one of {}'.format(VALID_FORMATS) ) if not is_number(rate) and rate is not None: raise ValueError('rate must be a float or None') if rate is not None and rate <= 0: raise ValueError('rate must be a positive number') if not isinstance(bits, int) and bits is not None: raise ValueError('bits must be an int or None') if bits is not None and bits <= 0: raise ValueError('bits must be a positive number') if not isinstance(channels, int) and channels is not None: raise ValueError('channels must be an int or None') if channels is not None and channels <= 0: raise ValueError('channels must be a positive number') if encoding not in ENCODING_VALS + [None]: raise ValueError( 'Invalid encoding. Must be one of {}'.format(ENCODING_VALS) ) if comments is not None and not isinstance(comments, str): raise ValueError('comments must be a string or None') if not isinstance(append_comments, bool): raise ValueError('append_comments must be a boolean') output_format = [] if file_type is not None: output_format.extend(['-t', '{}'.format(file_type)]) if rate is not None: output_format.extend(['-r', '{:f}'.format(rate)]) if bits is not None: output_format.extend(['-b', '{}'.format(bits)]) if channels is not None: output_format.extend(['-c', '{}'.format(channels)]) if encoding is not None: output_format.extend(['-e', '{}'.format(encoding)]) if comments is not None: if append_comments: output_format.extend(['--add-comment', comments]) else: output_format.extend(['--comment', comments]) self.output_format = output_format return self
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 effects (e.g. rate). If this function is not explicity called the output format is inferred from the file extension or the file's header. Parameters ---------- file_type : str or None, default=None The file type of the output audio file. Should be the same as what the file extension would be, for ex. 'mp3' or 'wav'. rate : float or None, default=None The sample rate of the output audio file. If None the sample rate is inferred. bits : int or None, default=None The number of bits per sample. If None, the number of bits per sample is inferred. channels : int or None, default=None The number of channels in the audio file. If None the number of channels is inferred. encoding : str or None, default=None The audio encoding type. Sometimes needed with file-types that support more than one encoding type. One of: * signed-integer : PCM data stored as signed (‘two’s complement’) integers. Commonly used with a 16 or 24−bit encoding size. A value of 0 represents minimum signal power. * unsigned-integer : PCM data stored as unsigned integers. Commonly used with an 8-bit encoding size. A value of 0 represents maximum signal power. * floating-point : PCM data stored as IEEE 753 single precision (32-bit) or double precision (64-bit) floating-point (‘real’) numbers. A value of 0 represents minimum signal power. * a-law : International telephony standard for logarithmic encoding to 8 bits per sample. It has a precision equivalent to roughly 13-bit PCM and is sometimes encoded with reversed bit-ordering. * u-law : North American telephony standard for logarithmic encoding to 8 bits per sample. A.k.a. μ-law. It has a precision equivalent to roughly 14-bit PCM and is sometimes encoded with reversed bit-ordering. * oki-adpcm : OKI (a.k.a. VOX, Dialogic, or Intel) 4-bit ADPCM; it has a precision equivalent to roughly 12-bit PCM. ADPCM is a form of audio compression that has a good compromise between audio quality and encoding/decoding speed. * ima-adpcm : IMA (a.k.a. DVI) 4-bit ADPCM; it has a precision equivalent to roughly 13-bit PCM. * ms-adpcm : Microsoft 4-bit ADPCM; it has a precision equivalent to roughly 14-bit PCM. * gsm-full-rate : GSM is currently used for the vast majority of the world’s digital wireless telephone calls. It utilises several audio formats with different bit-rates and associated speech quality. SoX has support for GSM’s original 13kbps ‘Full Rate’ audio format. It is usually CPU-intensive to work with GSM audio. comments : str or None, default=None If not None, the string is added as a comment in the header of the output audio file. If None, no comments are added. append_comments : bool, default=True If True, comment strings are appended to SoX's default comments. If False, the supplied comment replaces the existing comment. ''' if file_type not in VALID_FORMATS + [None]: raise ValueError( 'Invalid file_type. Must be one of {}'.format(VALID_FORMATS) ) if not is_number(rate) and rate is not None: raise ValueError('rate must be a float or None') if rate is not None and rate <= 0: raise ValueError('rate must be a positive number') if not isinstance(bits, int) and bits is not None: raise ValueError('bits must be an int or None') if bits is not None and bits <= 0: raise ValueError('bits must be a positive number') if not isinstance(channels, int) and channels is not None: raise ValueError('channels must be an int or None') if channels is not None and channels <= 0: raise ValueError('channels must be a positive number') if encoding not in ENCODING_VALS + [None]: raise ValueError( 'Invalid encoding. Must be one of {}'.format(ENCODING_VALS) ) if comments is not None and not isinstance(comments, str): raise ValueError('comments must be a string or None') if not isinstance(append_comments, bool): raise ValueError('append_comments must be a boolean') output_format = [] if file_type is not None: output_format.extend(['-t', '{}'.format(file_type)]) if rate is not None: output_format.extend(['-r', '{:f}'.format(rate)]) if bits is not None: output_format.extend(['-b', '{}'.format(bits)]) if channels is not None: output_format.extend(['-c', '{}'.format(channels)]) if encoding is not None: output_format.extend(['-e', '{}'.format(encoding)]) if comments is not None: if append_comments: output_format.extend(['--add-comment', comments]) else: output_format.extend(['--comment', comments]) self.output_format = output_format return self
[ "Sets", "output", "file", "format", "arguments", ".", "These", "arguments", "will", "overwrite", "any", "format", "related", "arguments", "supplied", "by", "other", "effects", "(", "e", ".", "g", ".", "rate", ")", "." ]
rabitt/pysox
python
https://github.com/rabitt/pysox/blob/eae89bde74567136ec3f723c3e6b369916d9b837/sox/transform.py#L255-L380
[ "def", "set_output_format", "(", "self", ",", "file_type", "=", "None", ",", "rate", "=", "None", ",", "bits", "=", "None", ",", "channels", "=", "None", ",", "encoding", "=", "None", ",", "comments", "=", "None", ",", "append_comments", "=", "True", ")", ":", "if", "file_type", "not", "in", "VALID_FORMATS", "+", "[", "None", "]", ":", "raise", "ValueError", "(", "'Invalid file_type. Must be one of {}'", ".", "format", "(", "VALID_FORMATS", ")", ")", "if", "not", "is_number", "(", "rate", ")", "and", "rate", "is", "not", "None", ":", "raise", "ValueError", "(", "'rate must be a float or None'", ")", "if", "rate", "is", "not", "None", "and", "rate", "<=", "0", ":", "raise", "ValueError", "(", "'rate must be a positive number'", ")", "if", "not", "isinstance", "(", "bits", ",", "int", ")", "and", "bits", "is", "not", "None", ":", "raise", "ValueError", "(", "'bits must be an int or None'", ")", "if", "bits", "is", "not", "None", "and", "bits", "<=", "0", ":", "raise", "ValueError", "(", "'bits must be a positive number'", ")", "if", "not", "isinstance", "(", "channels", ",", "int", ")", "and", "channels", "is", "not", "None", ":", "raise", "ValueError", "(", "'channels must be an int or None'", ")", "if", "channels", "is", "not", "None", "and", "channels", "<=", "0", ":", "raise", "ValueError", "(", "'channels must be a positive number'", ")", "if", "encoding", "not", "in", "ENCODING_VALS", "+", "[", "None", "]", ":", "raise", "ValueError", "(", "'Invalid encoding. Must be one of {}'", ".", "format", "(", "ENCODING_VALS", ")", ")", "if", "comments", "is", "not", "None", "and", "not", "isinstance", "(", "comments", ",", "str", ")", ":", "raise", "ValueError", "(", "'comments must be a string or None'", ")", "if", "not", "isinstance", "(", "append_comments", ",", "bool", ")", ":", "raise", "ValueError", "(", "'append_comments must be a boolean'", ")", "output_format", "=", "[", "]", "if", "file_type", "is", "not", "None", ":", "output_format", ".", "extend", "(", "[", "'-t'", ",", "'{}'", ".", "format", "(", "file_type", ")", "]", ")", "if", "rate", "is", "not", "None", ":", "output_format", ".", "extend", "(", "[", "'-r'", ",", "'{:f}'", ".", "format", "(", "rate", ")", "]", ")", "if", "bits", "is", "not", "None", ":", "output_format", ".", "extend", "(", "[", "'-b'", ",", "'{}'", ".", "format", "(", "bits", ")", "]", ")", "if", "channels", "is", "not", "None", ":", "output_format", ".", "extend", "(", "[", "'-c'", ",", "'{}'", ".", "format", "(", "channels", ")", "]", ")", "if", "encoding", "is", "not", "None", ":", "output_format", ".", "extend", "(", "[", "'-e'", ",", "'{}'", ".", "format", "(", "encoding", ")", "]", ")", "if", "comments", "is", "not", "None", ":", "if", "append_comments", ":", "output_format", ".", "extend", "(", "[", "'--add-comment'", ",", "comments", "]", ")", "else", ":", "output_format", ".", "extend", "(", "[", "'--comment'", ",", "comments", "]", ")", "self", ".", "output_format", "=", "output_format", "return", "self" ]
eae89bde74567136ec3f723c3e6b369916d9b837
valid
Transformer.build
Builds the output_file by executing the current set of commands. Parameters ---------- input_filepath : str Path to input audio file. output_filepath : str or None Path to desired output file. If a file already exists at the given path, the file will be overwritten. If None, no file will be created. extra_args : list or None, default=None If a list is given, these additional arguments are passed to SoX at the end of the list of effects. Don't use this argument unless you know exactly what you're doing! return_output : bool, default=False If True, returns the status and information sent to stderr and stdout as a tuple (status, stdout, stderr). Otherwise returns True on success.
sox/transform.py
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 None Path to desired output file. If a file already exists at the given path, the file will be overwritten. If None, no file will be created. extra_args : list or None, default=None If a list is given, these additional arguments are passed to SoX at the end of the list of effects. Don't use this argument unless you know exactly what you're doing! return_output : bool, default=False If True, returns the status and information sent to stderr and stdout as a tuple (status, stdout, stderr). Otherwise returns True on success. ''' file_info.validate_input_file(input_filepath) if output_filepath is not None: file_info.validate_output_file(output_filepath) else: output_filepath = '-n' if input_filepath == output_filepath: raise ValueError( "input_filepath must be different from output_filepath." ) args = [] args.extend(self.globals) args.extend(self.input_format) args.append(input_filepath) args.extend(self.output_format) args.append(output_filepath) args.extend(self.effects) if extra_args is not None: if not isinstance(extra_args, list): raise ValueError("extra_args must be a list.") args.extend(extra_args) status, out, err = sox(args) if status != 0: raise SoxError( "Stdout: {}\nStderr: {}".format(out, err) ) else: logger.info( "Created %s with effects: %s", output_filepath, " ".join(self.effects_log) ) if out is not None: logger.info("[SoX] {}".format(out)) if return_output: return status, out, err else: return True
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 None Path to desired output file. If a file already exists at the given path, the file will be overwritten. If None, no file will be created. extra_args : list or None, default=None If a list is given, these additional arguments are passed to SoX at the end of the list of effects. Don't use this argument unless you know exactly what you're doing! return_output : bool, default=False If True, returns the status and information sent to stderr and stdout as a tuple (status, stdout, stderr). Otherwise returns True on success. ''' file_info.validate_input_file(input_filepath) if output_filepath is not None: file_info.validate_output_file(output_filepath) else: output_filepath = '-n' if input_filepath == output_filepath: raise ValueError( "input_filepath must be different from output_filepath." ) args = [] args.extend(self.globals) args.extend(self.input_format) args.append(input_filepath) args.extend(self.output_format) args.append(output_filepath) args.extend(self.effects) if extra_args is not None: if not isinstance(extra_args, list): raise ValueError("extra_args must be a list.") args.extend(extra_args) status, out, err = sox(args) if status != 0: raise SoxError( "Stdout: {}\nStderr: {}".format(out, err) ) else: logger.info( "Created %s with effects: %s", output_filepath, " ".join(self.effects_log) ) if out is not None: logger.info("[SoX] {}".format(out)) if return_output: return status, out, err else: return True
[ "Builds", "the", "output_file", "by", "executing", "the", "current", "set", "of", "commands", "." ]
rabitt/pysox
python
https://github.com/rabitt/pysox/blob/eae89bde74567136ec3f723c3e6b369916d9b837/sox/transform.py#L390-L455
[ "def", "build", "(", "self", ",", "input_filepath", ",", "output_filepath", ",", "extra_args", "=", "None", ",", "return_output", "=", "False", ")", ":", "file_info", ".", "validate_input_file", "(", "input_filepath", ")", "if", "output_filepath", "is", "not", "None", ":", "file_info", ".", "validate_output_file", "(", "output_filepath", ")", "else", ":", "output_filepath", "=", "'-n'", "if", "input_filepath", "==", "output_filepath", ":", "raise", "ValueError", "(", "\"input_filepath must be different from output_filepath.\"", ")", "args", "=", "[", "]", "args", ".", "extend", "(", "self", ".", "globals", ")", "args", ".", "extend", "(", "self", ".", "input_format", ")", "args", ".", "append", "(", "input_filepath", ")", "args", ".", "extend", "(", "self", ".", "output_format", ")", "args", ".", "append", "(", "output_filepath", ")", "args", ".", "extend", "(", "self", ".", "effects", ")", "if", "extra_args", "is", "not", "None", ":", "if", "not", "isinstance", "(", "extra_args", ",", "list", ")", ":", "raise", "ValueError", "(", "\"extra_args must be a list.\"", ")", "args", ".", "extend", "(", "extra_args", ")", "status", ",", "out", ",", "err", "=", "sox", "(", "args", ")", "if", "status", "!=", "0", ":", "raise", "SoxError", "(", "\"Stdout: {}\\nStderr: {}\"", ".", "format", "(", "out", ",", "err", ")", ")", "else", ":", "logger", ".", "info", "(", "\"Created %s with effects: %s\"", ",", "output_filepath", ",", "\" \"", ".", "join", "(", "self", ".", "effects_log", ")", ")", "if", "out", "is", "not", "None", ":", "logger", ".", "info", "(", "\"[SoX] {}\"", ".", "format", "(", "out", ")", ")", "if", "return_output", ":", "return", "status", ",", "out", ",", "err", "else", ":", "return", "True" ]
eae89bde74567136ec3f723c3e6b369916d9b837
valid
Transformer.preview
Play a preview of the output with the current set of effects Parameters ---------- input_filepath : str Path to input audio file.
sox/transform.py
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.extend(self.input_format) args.append(input_filepath) args.extend(self.effects) play(args)
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.extend(self.input_format) args.append(input_filepath) args.extend(self.effects) play(args)
[ "Play", "a", "preview", "of", "the", "output", "with", "the", "current", "set", "of", "effects" ]
rabitt/pysox
python
https://github.com/rabitt/pysox/blob/eae89bde74567136ec3f723c3e6b369916d9b837/sox/transform.py#L457-L472
[ "def", "preview", "(", "self", ",", "input_filepath", ")", ":", "args", "=", "[", "\"play\"", ",", "\"--no-show-progress\"", "]", "args", ".", "extend", "(", "self", ".", "globals", ")", "args", ".", "extend", "(", "self", ".", "input_format", ")", "args", ".", "append", "(", "input_filepath", ")", "args", ".", "extend", "(", "self", ".", "effects", ")", "play", "(", "args", ")" ]
eae89bde74567136ec3f723c3e6b369916d9b837