repository_name
stringclasses 316
values | func_path_in_repository
stringlengths 6
223
| func_name
stringlengths 1
134
| language
stringclasses 1
value | func_code_string
stringlengths 57
65.5k
| func_documentation_string
stringlengths 1
46.3k
| split_name
stringclasses 1
value | func_code_url
stringlengths 91
315
| called_functions
listlengths 1
156
⌀ | enclosing_scope
stringlengths 2
1.48M
|
|---|---|---|---|---|---|---|---|---|---|
storax/jinjaapidoc
|
src/jinjaapidoc/gendoc.py
|
_get_submodules
|
python
|
def _get_submodules(app, module):
if inspect.ismodule(module):
if hasattr(module, '__path__'):
p = module.__path__
else:
return []
elif isinstance(module, str):
p = module
else:
raise TypeError("Only Module or String accepted. %s given." % type(module))
logger.debug('Getting submodules of %s', p)
submodules = [(name, ispkg) for loader, name, ispkg in pkgutil.iter_modules(p)]
logger.debug('Found submodules of %s: %s', module, submodules)
return submodules
|
Get all submodules for the given module/package
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param module: the module to query or module path
:type module: module | str
:returns: list of module names and boolean whether its a package
:rtype: list
:raises: TypeError
|
train
|
https://github.com/storax/jinjaapidoc/blob/f1eeb6ab5bd1a96c4130306718c6423f37c76856/src/jinjaapidoc/gendoc.py#L221-L244
| null |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""This is a modification of sphinx.apidoc by David.Zuber.
It uses jinja templates to render the rst files.
Parses a directory tree looking for Python modules and packages and creates
ReST files appropriately to create code documentation with Sphinx.
This is derived form the "sphinx-apidoc" script, which is:
Copyright 2007-2014 by the Sphinx team, see http://sphinx-doc.org/latest/authors.html.
"""
import os
import inspect
import pkgutil
import pkg_resources
import shutil
import jinja2
from sphinx.util.osutil import walk
from sphinx.util import logging
from sphinx.ext import autosummary
logger = logging.getLogger(__name__)
INITPY = '__init__.py'
PY_SUFFIXES = set(['.py', '.pyx'])
TEMPLATE_DIR = 'templates'
"""Built-in template dir for jinjaapi rendering"""
AUTOSUMMARYTEMPLATE_DIR = 'autosummarytemplates'
"""Templates for autosummary"""
MODULE_TEMPLATE_NAME = 'jinjaapi_module.rst'
"""Name of the template that is used for rendering modules."""
PACKAGE_TEMPLATE_NAME = 'jinjaapi_package.rst'
"""Name of the template that is used for rendering packages."""
def prepare_dir(app, directory, delete=False):
"""Create apidoc dir, delete contents if delete is True.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param directory: the apidoc directory. you can use relative paths here
:type directory: str
:param delete: if True, deletes the contents of apidoc. This acts like an override switch.
:type delete: bool
:returns: None
:rtype: None
:raises: None
"""
logger.info("Preparing output directories for jinjaapidoc.")
if os.path.exists(directory):
if delete:
logger.debug("Deleting dir %s", directory)
shutil.rmtree(directory)
logger.debug("Creating dir %s", directory)
os.mkdir(directory)
else:
logger.debug("Creating %s", directory)
os.mkdir(directory)
def make_loader(template_dirs):
"""Return a new :class:`jinja2.FileSystemLoader` that uses the template_dirs
:param template_dirs: directories to search for templates
:type template_dirs: None | :class:`list`
:returns: a new loader
:rtype: :class:`jinja2.FileSystemLoader`
:raises: None
"""
return jinja2.FileSystemLoader(searchpath=template_dirs)
def make_environment(loader):
"""Return a new :class:`jinja2.Environment` with the given loader
:param loader: a jinja2 loader
:type loader: :class:`jinja2.BaseLoader`
:returns: a new environment
:rtype: :class:`jinja2.Environment`
:raises: None
"""
return jinja2.Environment(loader=loader)
def makename(package, module):
"""Join package and module with a dot.
Package or Module can be empty.
:param package: the package name
:type package: :class:`str`
:param module: the module name
:type module: :class:`str`
:returns: the joined name
:rtype: :class:`str`
:raises: :class:`AssertionError`, if both package and module are empty
"""
# Both package and module can be None/empty.
assert package or module, "Specify either package or module"
if package:
name = package
if module:
name += '.' + module
else:
name = module
return name
def write_file(app, name, text, dest, suffix, dryrun, force):
"""Write the output file for module/package <name>.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param name: the file name without file extension
:type name: :class:`str`
:param text: the content of the file
:type text: :class:`str`
:param dest: the output directory
:type dest: :class:`str`
:param suffix: the file extension
:type suffix: :class:`str`
:param dryrun: If True, do not create any files, just log the potential location.
:type dryrun: :class:`bool`
:param force: Overwrite existing files
:type force: :class:`bool`
:returns: None
:raises: None
"""
fname = os.path.join(dest, '%s.%s' % (name, suffix))
if dryrun:
logger.info('Would create file %s.' % fname)
return
if not force and os.path.isfile(fname):
logger.info('File %s already exists, skipping.' % fname)
else:
logger.info('Creating file %s.' % fname)
f = open(fname, 'w')
try:
f.write(text)
relpath = os.path.relpath(fname, start=app.env.srcdir)
abspath = os.sep + relpath
docpath = app.env.relfn2path(abspath)[0]
docpath = docpath.rsplit(os.path.extsep, 1)[0]
logger.debug('Adding document %s' % docpath)
app.env.found_docs.add(docpath)
finally:
f.close()
def import_name(app, name):
"""Import the given name and return name, obj, parent, mod_name
:param name: name to import
:type name: str
:returns: the imported object or None
:rtype: object | None
:raises: None
"""
try:
logger.debug('Importing %r', name)
name, obj = autosummary.import_by_name(name)[:2]
logger.debug('Imported %s', obj)
return obj
except ImportError as e:
logger.warn("Jinjapidoc failed to import %r: %s", name, e)
def get_members(app, mod, typ, include_public=None):
"""Return the members of mod of the given type
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param mod: the module with members
:type mod: module
:param typ: the typ, ``'class'``, ``'function'``, ``'exception'``, ``'data'``, ``'members'``
:type typ: str
:param include_public: list of private members to include to publics
:type include_public: list | None
:returns: None
:rtype: None
:raises: None
"""
def include_here(x):
"""Return true if the member should be included in mod.
A member will be included if it is declared in this module or package.
If the `jinjaapidoc_include_from_all` option is `True` then the member
can also be included if it is listed in `__all__`.
:param x: The member
:type x: A class, exception, or function.
:returns: True if the member should be included in mod. False otherwise.
:rtype: bool
"""
return (x.__module__ == mod.__name__ or (include_from_all and x.__name__ in all_list))
all_list = getattr(mod, '__all__', [])
include_from_all = app.config.jinjaapi_include_from_all
include_public = include_public or []
tests = {'class': lambda x: inspect.isclass(x) and not issubclass(x, BaseException) and include_here(x),
'function': lambda x: inspect.isfunction(x) and include_here(x),
'exception': lambda x: inspect.isclass(x) and issubclass(x, BaseException) and include_here(x),
'data': lambda x: not inspect.ismodule(x) and not inspect.isclass(x) and not inspect.isfunction(x),
'members': lambda x: True}
items = []
for name in dir(mod):
i = getattr(mod, name)
inspect.ismodule(i)
if tests.get(typ, lambda x: False)(i):
items.append(name)
public = [x for x in items
if x in include_public or not x.startswith('_')]
logger.debug('Got members of %s of type %s: public %s and %s', mod, typ, public, items)
return public, items
def get_submodules(app, module):
"""Get all submodules without packages for the given module/package
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param module: the module to query or module path
:type module: module | str
:returns: list of module names excluding packages
:rtype: list
:raises: TypeError
"""
submodules = _get_submodules(app, module)
return [name for name, ispkg in submodules if not ispkg]
def get_subpackages(app, module):
"""Get all subpackages for the given module/package
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param module: the module to query or module path
:type module: module | str
:returns: list of packages names
:rtype: list
:raises: TypeError
"""
submodules = _get_submodules(app, module)
return [name for name, ispkg in submodules if ispkg]
def get_context(app, package, module, fullname):
"""Return a dict for template rendering
Variables:
* :package: The top package
* :module: the module
* :fullname: package.module
* :subpkgs: packages beneath module
* :submods: modules beneath module
* :classes: public classes in module
* :allclasses: public and private classes in module
* :exceptions: public exceptions in module
* :allexceptions: public and private exceptions in module
* :functions: public functions in module
* :allfunctions: public and private functions in module
* :data: public data in module
* :alldata: public and private data in module
* :members: dir(module)
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param package: the parent package name
:type package: str
:param module: the module name
:type module: str
:param fullname: package.module
:type fullname: str
:returns: a dict with variables for template rendering
:rtype: :class:`dict`
:raises: None
"""
var = {'package': package,
'module': module,
'fullname': fullname}
logger.debug('Creating context for: package %s, module %s, fullname %s', package, module, fullname)
obj = import_name(app, fullname)
if not obj:
for k in ('subpkgs', 'submods', 'classes', 'allclasses',
'exceptions', 'allexceptions', 'functions', 'allfunctions',
'data', 'alldata', 'memebers'):
var[k] = []
return var
var['subpkgs'] = get_subpackages(app, obj)
var['submods'] = get_submodules(app, obj)
var['classes'], var['allclasses'] = get_members(app, obj, 'class')
var['exceptions'], var['allexceptions'] = get_members(app, obj, 'exception')
var['functions'], var['allfunctions'] = get_members(app, obj, 'function')
var['data'], var['alldata'] = get_members(app, obj, 'data')
var['members'] = get_members(app, obj, 'members')
logger.debug('Created context: %s', var)
return var
def create_module_file(app, env, package, module, dest, suffix, dryrun, force):
"""Build the text of the file and write the file.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param env: the jinja environment for the templates
:type env: :class:`jinja2.Environment`
:param package: the package name
:type package: :class:`str`
:param module: the module name
:type module: :class:`str`
:param dest: the output directory
:type dest: :class:`str`
:param suffix: the file extension
:type suffix: :class:`str`
:param dryrun: If True, do not create any files, just log the potential location.
:type dryrun: :class:`bool`
:param force: Overwrite existing files
:type force: :class:`bool`
:returns: None
:raises: None
"""
logger.debug('Create module file: package %s, module %s', package, module)
template_file = MODULE_TEMPLATE_NAME
template = env.get_template(template_file)
fn = makename(package, module)
var = get_context(app, package, module, fn)
var['ispkg'] = False
rendered = template.render(var)
write_file(app, makename(package, module), rendered, dest, suffix, dryrun, force)
def create_package_file(app, env, root_package, sub_package, private,
dest, suffix, dryrun, force):
"""Build the text of the file and write the file.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param env: the jinja environment for the templates
:type env: :class:`jinja2.Environment`
:param root_package: the parent package
:type root_package: :class:`str`
:param sub_package: the package name without root
:type sub_package: :class:`str`
:param private: Include \"_private\" modules
:type private: :class:`bool`
:param dest: the output directory
:type dest: :class:`str`
:param suffix: the file extension
:type suffix: :class:`str`
:param dryrun: If True, do not create any files, just log the potential location.
:type dryrun: :class:`bool`
:param force: Overwrite existing files
:type force: :class:`bool`
:returns: None
:raises: None
"""
logger.debug('Create package file: rootpackage %s, sub_package %s', root_package, sub_package)
template_file = PACKAGE_TEMPLATE_NAME
template = env.get_template(template_file)
fn = makename(root_package, sub_package)
var = get_context(app, root_package, sub_package, fn)
var['ispkg'] = True
for submod in var['submods']:
if shall_skip(app, submod, private):
continue
create_module_file(app, env, fn, submod, dest, suffix, dryrun, force)
rendered = template.render(var)
write_file(app, fn, rendered, dest, suffix, dryrun, force)
def shall_skip(app, module, private):
"""Check if we want to skip this module.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param module: the module name
:type module: :class:`str`
:param private: True, if privates are allowed
:type private: :class:`bool`
"""
logger.debug('Testing if %s should be skipped.', module)
# skip if it has a "private" name and this is selected
if module != '__init__.py' and module.startswith('_') and \
not private:
logger.debug('Skip %s because its either private or __init__.', module)
return True
logger.debug('Do not skip %s', module)
return False
def recurse_tree(app, env, src, dest, excludes, followlinks, force, dryrun, private, suffix):
"""Look for every file in the directory tree and create the corresponding
ReST files.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param env: the jinja environment
:type env: :class:`jinja2.Environment`
:param src: the path to the python source files
:type src: :class:`str`
:param dest: the output directory
:type dest: :class:`str`
:param excludes: the paths to exclude
:type excludes: :class:`list`
:param followlinks: follow symbolic links
:type followlinks: :class:`bool`
:param force: overwrite existing files
:type force: :class:`bool`
:param dryrun: do not generate files
:type dryrun: :class:`bool`
:param private: include "_private" modules
:type private: :class:`bool`
:param suffix: the file extension
:type suffix: :class:`str`
"""
# check if the base directory is a package and get its name
if INITPY in os.listdir(src):
root_package = src.split(os.path.sep)[-1]
else:
# otherwise, the base is a directory with packages
root_package = None
toplevels = []
for root, subs, files in walk(src, followlinks=followlinks):
# document only Python module files (that aren't excluded)
py_files = sorted(f for f in files
if os.path.splitext(f)[1] in PY_SUFFIXES and # noqa: W504
not is_excluded(os.path.join(root, f), excludes))
is_pkg = INITPY in py_files
if is_pkg:
py_files.remove(INITPY)
py_files.insert(0, INITPY)
elif root != src:
# only accept non-package at toplevel
del subs[:]
continue
# remove hidden ('.') and private ('_') directories, as well as
# excluded dirs
if private:
exclude_prefixes = ('.',)
else:
exclude_prefixes = ('.', '_')
subs[:] = sorted(sub for sub in subs if not sub.startswith(exclude_prefixes) and not
is_excluded(os.path.join(root, sub), excludes))
if is_pkg:
# we are in a package with something to document
if subs or len(py_files) > 1 or not \
shall_skip(app, os.path.join(root, INITPY), private):
subpackage = root[len(src):].lstrip(os.path.sep).\
replace(os.path.sep, '.')
create_package_file(app, env, root_package, subpackage,
private, dest, suffix, dryrun, force)
toplevels.append(makename(root_package, subpackage))
else:
# if we are at the root level, we don't require it to be a package
assert root == src and root_package is None
for py_file in py_files:
if not shall_skip(app, os.path.join(src, py_file), private):
module = os.path.splitext(py_file)[0]
create_module_file(app, env, root_package, module, dest, suffix, dryrun, force)
toplevels.append(module)
return toplevels
def normalize_excludes(excludes):
"""Normalize the excluded directory list."""
return [os.path.normpath(os.path.abspath(exclude)) for exclude in excludes]
def is_excluded(root, excludes):
"""Check if the directory is in the exclude list.
Note: by having trailing slashes, we avoid common prefix issues, like
e.g. an exlude "foo" also accidentally excluding "foobar".
"""
root = os.path.normpath(root)
for exclude in excludes:
if root == exclude:
return True
return False
def generate(app, src, dest, exclude=[], followlinks=False,
force=False, dryrun=False, private=False, suffix='rst',
template_dirs=None):
"""Generage the rst files
Raises an :class:`OSError` if the source path is not a directory.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param src: path to python source files
:type src: :class:`str`
:param dest: output directory
:type dest: :class:`str`
:param exclude: list of paths to exclude
:type exclude: :class:`list`
:param followlinks: follow symbolic links
:type followlinks: :class:`bool`
:param force: overwrite existing files
:type force: :class:`bool`
:param dryrun: do not create any files
:type dryrun: :class:`bool`
:param private: include \"_private\" modules
:type private: :class:`bool`
:param suffix: file suffix
:type suffix: :class:`str`
:param template_dirs: directories to search for user templates
:type template_dirs: None | :class:`list`
:returns: None
:rtype: None
:raises: OSError
"""
suffix = suffix.strip('.')
if not os.path.isdir(src):
raise OSError("%s is not a directory" % src)
if not os.path.isdir(dest) and not dryrun:
os.makedirs(dest)
src = os.path.normpath(os.path.abspath(src))
exclude = normalize_excludes(exclude)
loader = make_loader(template_dirs)
env = make_environment(loader)
recurse_tree(app, env, src, dest, exclude, followlinks, force, dryrun, private, suffix)
def main(app):
"""Parse the config of the app and initiate the generation process
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:returns: None
:rtype: None
:raises: None
"""
c = app.config
src = c.jinjaapi_srcdir
if not src:
return
suffix = "rst"
out = c.jinjaapi_outputdir or app.env.srcdir
if c.jinjaapi_addsummarytemplate:
tpath = pkg_resources.resource_filename(__package__, AUTOSUMMARYTEMPLATE_DIR)
c.templates_path.append(tpath)
tpath = pkg_resources.resource_filename(__package__, TEMPLATE_DIR)
c.templates_path.append(tpath)
prepare_dir(app, out, not c.jinjaapi_nodelete)
generate(app, src, out,
exclude=c.jinjaapi_exclude_paths,
force=c.jinjaapi_force,
followlinks=c.jinjaapi_followlinks,
dryrun=c.jinjaapi_dryrun,
private=c.jinjaapi_includeprivate,
suffix=suffix,
template_dirs=c.templates_path)
|
storax/jinjaapidoc
|
src/jinjaapidoc/gendoc.py
|
get_submodules
|
python
|
def get_submodules(app, module):
submodules = _get_submodules(app, module)
return [name for name, ispkg in submodules if not ispkg]
|
Get all submodules without packages for the given module/package
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param module: the module to query or module path
:type module: module | str
:returns: list of module names excluding packages
:rtype: list
:raises: TypeError
|
train
|
https://github.com/storax/jinjaapidoc/blob/f1eeb6ab5bd1a96c4130306718c6423f37c76856/src/jinjaapidoc/gendoc.py#L247-L259
|
[
"def _get_submodules(app, module):\n \"\"\"Get all submodules for the given module/package\n\n :param app: the sphinx app\n :type app: :class:`sphinx.application.Sphinx`\n :param module: the module to query or module path\n :type module: module | str\n :returns: list of module names and boolean whether its a package\n :rtype: list\n :raises: TypeError\n \"\"\"\n if inspect.ismodule(module):\n if hasattr(module, '__path__'):\n p = module.__path__\n else:\n return []\n elif isinstance(module, str):\n p = module\n else:\n raise TypeError(\"Only Module or String accepted. %s given.\" % type(module))\n logger.debug('Getting submodules of %s', p)\n submodules = [(name, ispkg) for loader, name, ispkg in pkgutil.iter_modules(p)]\n logger.debug('Found submodules of %s: %s', module, submodules)\n return submodules\n"
] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""This is a modification of sphinx.apidoc by David.Zuber.
It uses jinja templates to render the rst files.
Parses a directory tree looking for Python modules and packages and creates
ReST files appropriately to create code documentation with Sphinx.
This is derived form the "sphinx-apidoc" script, which is:
Copyright 2007-2014 by the Sphinx team, see http://sphinx-doc.org/latest/authors.html.
"""
import os
import inspect
import pkgutil
import pkg_resources
import shutil
import jinja2
from sphinx.util.osutil import walk
from sphinx.util import logging
from sphinx.ext import autosummary
logger = logging.getLogger(__name__)
INITPY = '__init__.py'
PY_SUFFIXES = set(['.py', '.pyx'])
TEMPLATE_DIR = 'templates'
"""Built-in template dir for jinjaapi rendering"""
AUTOSUMMARYTEMPLATE_DIR = 'autosummarytemplates'
"""Templates for autosummary"""
MODULE_TEMPLATE_NAME = 'jinjaapi_module.rst'
"""Name of the template that is used for rendering modules."""
PACKAGE_TEMPLATE_NAME = 'jinjaapi_package.rst'
"""Name of the template that is used for rendering packages."""
def prepare_dir(app, directory, delete=False):
"""Create apidoc dir, delete contents if delete is True.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param directory: the apidoc directory. you can use relative paths here
:type directory: str
:param delete: if True, deletes the contents of apidoc. This acts like an override switch.
:type delete: bool
:returns: None
:rtype: None
:raises: None
"""
logger.info("Preparing output directories for jinjaapidoc.")
if os.path.exists(directory):
if delete:
logger.debug("Deleting dir %s", directory)
shutil.rmtree(directory)
logger.debug("Creating dir %s", directory)
os.mkdir(directory)
else:
logger.debug("Creating %s", directory)
os.mkdir(directory)
def make_loader(template_dirs):
"""Return a new :class:`jinja2.FileSystemLoader` that uses the template_dirs
:param template_dirs: directories to search for templates
:type template_dirs: None | :class:`list`
:returns: a new loader
:rtype: :class:`jinja2.FileSystemLoader`
:raises: None
"""
return jinja2.FileSystemLoader(searchpath=template_dirs)
def make_environment(loader):
"""Return a new :class:`jinja2.Environment` with the given loader
:param loader: a jinja2 loader
:type loader: :class:`jinja2.BaseLoader`
:returns: a new environment
:rtype: :class:`jinja2.Environment`
:raises: None
"""
return jinja2.Environment(loader=loader)
def makename(package, module):
"""Join package and module with a dot.
Package or Module can be empty.
:param package: the package name
:type package: :class:`str`
:param module: the module name
:type module: :class:`str`
:returns: the joined name
:rtype: :class:`str`
:raises: :class:`AssertionError`, if both package and module are empty
"""
# Both package and module can be None/empty.
assert package or module, "Specify either package or module"
if package:
name = package
if module:
name += '.' + module
else:
name = module
return name
def write_file(app, name, text, dest, suffix, dryrun, force):
"""Write the output file for module/package <name>.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param name: the file name without file extension
:type name: :class:`str`
:param text: the content of the file
:type text: :class:`str`
:param dest: the output directory
:type dest: :class:`str`
:param suffix: the file extension
:type suffix: :class:`str`
:param dryrun: If True, do not create any files, just log the potential location.
:type dryrun: :class:`bool`
:param force: Overwrite existing files
:type force: :class:`bool`
:returns: None
:raises: None
"""
fname = os.path.join(dest, '%s.%s' % (name, suffix))
if dryrun:
logger.info('Would create file %s.' % fname)
return
if not force and os.path.isfile(fname):
logger.info('File %s already exists, skipping.' % fname)
else:
logger.info('Creating file %s.' % fname)
f = open(fname, 'w')
try:
f.write(text)
relpath = os.path.relpath(fname, start=app.env.srcdir)
abspath = os.sep + relpath
docpath = app.env.relfn2path(abspath)[0]
docpath = docpath.rsplit(os.path.extsep, 1)[0]
logger.debug('Adding document %s' % docpath)
app.env.found_docs.add(docpath)
finally:
f.close()
def import_name(app, name):
"""Import the given name and return name, obj, parent, mod_name
:param name: name to import
:type name: str
:returns: the imported object or None
:rtype: object | None
:raises: None
"""
try:
logger.debug('Importing %r', name)
name, obj = autosummary.import_by_name(name)[:2]
logger.debug('Imported %s', obj)
return obj
except ImportError as e:
logger.warn("Jinjapidoc failed to import %r: %s", name, e)
def get_members(app, mod, typ, include_public=None):
"""Return the members of mod of the given type
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param mod: the module with members
:type mod: module
:param typ: the typ, ``'class'``, ``'function'``, ``'exception'``, ``'data'``, ``'members'``
:type typ: str
:param include_public: list of private members to include to publics
:type include_public: list | None
:returns: None
:rtype: None
:raises: None
"""
def include_here(x):
"""Return true if the member should be included in mod.
A member will be included if it is declared in this module or package.
If the `jinjaapidoc_include_from_all` option is `True` then the member
can also be included if it is listed in `__all__`.
:param x: The member
:type x: A class, exception, or function.
:returns: True if the member should be included in mod. False otherwise.
:rtype: bool
"""
return (x.__module__ == mod.__name__ or (include_from_all and x.__name__ in all_list))
all_list = getattr(mod, '__all__', [])
include_from_all = app.config.jinjaapi_include_from_all
include_public = include_public or []
tests = {'class': lambda x: inspect.isclass(x) and not issubclass(x, BaseException) and include_here(x),
'function': lambda x: inspect.isfunction(x) and include_here(x),
'exception': lambda x: inspect.isclass(x) and issubclass(x, BaseException) and include_here(x),
'data': lambda x: not inspect.ismodule(x) and not inspect.isclass(x) and not inspect.isfunction(x),
'members': lambda x: True}
items = []
for name in dir(mod):
i = getattr(mod, name)
inspect.ismodule(i)
if tests.get(typ, lambda x: False)(i):
items.append(name)
public = [x for x in items
if x in include_public or not x.startswith('_')]
logger.debug('Got members of %s of type %s: public %s and %s', mod, typ, public, items)
return public, items
def _get_submodules(app, module):
"""Get all submodules for the given module/package
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param module: the module to query or module path
:type module: module | str
:returns: list of module names and boolean whether its a package
:rtype: list
:raises: TypeError
"""
if inspect.ismodule(module):
if hasattr(module, '__path__'):
p = module.__path__
else:
return []
elif isinstance(module, str):
p = module
else:
raise TypeError("Only Module or String accepted. %s given." % type(module))
logger.debug('Getting submodules of %s', p)
submodules = [(name, ispkg) for loader, name, ispkg in pkgutil.iter_modules(p)]
logger.debug('Found submodules of %s: %s', module, submodules)
return submodules
def get_subpackages(app, module):
"""Get all subpackages for the given module/package
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param module: the module to query or module path
:type module: module | str
:returns: list of packages names
:rtype: list
:raises: TypeError
"""
submodules = _get_submodules(app, module)
return [name for name, ispkg in submodules if ispkg]
def get_context(app, package, module, fullname):
"""Return a dict for template rendering
Variables:
* :package: The top package
* :module: the module
* :fullname: package.module
* :subpkgs: packages beneath module
* :submods: modules beneath module
* :classes: public classes in module
* :allclasses: public and private classes in module
* :exceptions: public exceptions in module
* :allexceptions: public and private exceptions in module
* :functions: public functions in module
* :allfunctions: public and private functions in module
* :data: public data in module
* :alldata: public and private data in module
* :members: dir(module)
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param package: the parent package name
:type package: str
:param module: the module name
:type module: str
:param fullname: package.module
:type fullname: str
:returns: a dict with variables for template rendering
:rtype: :class:`dict`
:raises: None
"""
var = {'package': package,
'module': module,
'fullname': fullname}
logger.debug('Creating context for: package %s, module %s, fullname %s', package, module, fullname)
obj = import_name(app, fullname)
if not obj:
for k in ('subpkgs', 'submods', 'classes', 'allclasses',
'exceptions', 'allexceptions', 'functions', 'allfunctions',
'data', 'alldata', 'memebers'):
var[k] = []
return var
var['subpkgs'] = get_subpackages(app, obj)
var['submods'] = get_submodules(app, obj)
var['classes'], var['allclasses'] = get_members(app, obj, 'class')
var['exceptions'], var['allexceptions'] = get_members(app, obj, 'exception')
var['functions'], var['allfunctions'] = get_members(app, obj, 'function')
var['data'], var['alldata'] = get_members(app, obj, 'data')
var['members'] = get_members(app, obj, 'members')
logger.debug('Created context: %s', var)
return var
def create_module_file(app, env, package, module, dest, suffix, dryrun, force):
"""Build the text of the file and write the file.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param env: the jinja environment for the templates
:type env: :class:`jinja2.Environment`
:param package: the package name
:type package: :class:`str`
:param module: the module name
:type module: :class:`str`
:param dest: the output directory
:type dest: :class:`str`
:param suffix: the file extension
:type suffix: :class:`str`
:param dryrun: If True, do not create any files, just log the potential location.
:type dryrun: :class:`bool`
:param force: Overwrite existing files
:type force: :class:`bool`
:returns: None
:raises: None
"""
logger.debug('Create module file: package %s, module %s', package, module)
template_file = MODULE_TEMPLATE_NAME
template = env.get_template(template_file)
fn = makename(package, module)
var = get_context(app, package, module, fn)
var['ispkg'] = False
rendered = template.render(var)
write_file(app, makename(package, module), rendered, dest, suffix, dryrun, force)
def create_package_file(app, env, root_package, sub_package, private,
dest, suffix, dryrun, force):
"""Build the text of the file and write the file.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param env: the jinja environment for the templates
:type env: :class:`jinja2.Environment`
:param root_package: the parent package
:type root_package: :class:`str`
:param sub_package: the package name without root
:type sub_package: :class:`str`
:param private: Include \"_private\" modules
:type private: :class:`bool`
:param dest: the output directory
:type dest: :class:`str`
:param suffix: the file extension
:type suffix: :class:`str`
:param dryrun: If True, do not create any files, just log the potential location.
:type dryrun: :class:`bool`
:param force: Overwrite existing files
:type force: :class:`bool`
:returns: None
:raises: None
"""
logger.debug('Create package file: rootpackage %s, sub_package %s', root_package, sub_package)
template_file = PACKAGE_TEMPLATE_NAME
template = env.get_template(template_file)
fn = makename(root_package, sub_package)
var = get_context(app, root_package, sub_package, fn)
var['ispkg'] = True
for submod in var['submods']:
if shall_skip(app, submod, private):
continue
create_module_file(app, env, fn, submod, dest, suffix, dryrun, force)
rendered = template.render(var)
write_file(app, fn, rendered, dest, suffix, dryrun, force)
def shall_skip(app, module, private):
"""Check if we want to skip this module.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param module: the module name
:type module: :class:`str`
:param private: True, if privates are allowed
:type private: :class:`bool`
"""
logger.debug('Testing if %s should be skipped.', module)
# skip if it has a "private" name and this is selected
if module != '__init__.py' and module.startswith('_') and \
not private:
logger.debug('Skip %s because its either private or __init__.', module)
return True
logger.debug('Do not skip %s', module)
return False
def recurse_tree(app, env, src, dest, excludes, followlinks, force, dryrun, private, suffix):
"""Look for every file in the directory tree and create the corresponding
ReST files.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param env: the jinja environment
:type env: :class:`jinja2.Environment`
:param src: the path to the python source files
:type src: :class:`str`
:param dest: the output directory
:type dest: :class:`str`
:param excludes: the paths to exclude
:type excludes: :class:`list`
:param followlinks: follow symbolic links
:type followlinks: :class:`bool`
:param force: overwrite existing files
:type force: :class:`bool`
:param dryrun: do not generate files
:type dryrun: :class:`bool`
:param private: include "_private" modules
:type private: :class:`bool`
:param suffix: the file extension
:type suffix: :class:`str`
"""
# check if the base directory is a package and get its name
if INITPY in os.listdir(src):
root_package = src.split(os.path.sep)[-1]
else:
# otherwise, the base is a directory with packages
root_package = None
toplevels = []
for root, subs, files in walk(src, followlinks=followlinks):
# document only Python module files (that aren't excluded)
py_files = sorted(f for f in files
if os.path.splitext(f)[1] in PY_SUFFIXES and # noqa: W504
not is_excluded(os.path.join(root, f), excludes))
is_pkg = INITPY in py_files
if is_pkg:
py_files.remove(INITPY)
py_files.insert(0, INITPY)
elif root != src:
# only accept non-package at toplevel
del subs[:]
continue
# remove hidden ('.') and private ('_') directories, as well as
# excluded dirs
if private:
exclude_prefixes = ('.',)
else:
exclude_prefixes = ('.', '_')
subs[:] = sorted(sub for sub in subs if not sub.startswith(exclude_prefixes) and not
is_excluded(os.path.join(root, sub), excludes))
if is_pkg:
# we are in a package with something to document
if subs or len(py_files) > 1 or not \
shall_skip(app, os.path.join(root, INITPY), private):
subpackage = root[len(src):].lstrip(os.path.sep).\
replace(os.path.sep, '.')
create_package_file(app, env, root_package, subpackage,
private, dest, suffix, dryrun, force)
toplevels.append(makename(root_package, subpackage))
else:
# if we are at the root level, we don't require it to be a package
assert root == src and root_package is None
for py_file in py_files:
if not shall_skip(app, os.path.join(src, py_file), private):
module = os.path.splitext(py_file)[0]
create_module_file(app, env, root_package, module, dest, suffix, dryrun, force)
toplevels.append(module)
return toplevels
def normalize_excludes(excludes):
"""Normalize the excluded directory list."""
return [os.path.normpath(os.path.abspath(exclude)) for exclude in excludes]
def is_excluded(root, excludes):
"""Check if the directory is in the exclude list.
Note: by having trailing slashes, we avoid common prefix issues, like
e.g. an exlude "foo" also accidentally excluding "foobar".
"""
root = os.path.normpath(root)
for exclude in excludes:
if root == exclude:
return True
return False
def generate(app, src, dest, exclude=[], followlinks=False,
force=False, dryrun=False, private=False, suffix='rst',
template_dirs=None):
"""Generage the rst files
Raises an :class:`OSError` if the source path is not a directory.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param src: path to python source files
:type src: :class:`str`
:param dest: output directory
:type dest: :class:`str`
:param exclude: list of paths to exclude
:type exclude: :class:`list`
:param followlinks: follow symbolic links
:type followlinks: :class:`bool`
:param force: overwrite existing files
:type force: :class:`bool`
:param dryrun: do not create any files
:type dryrun: :class:`bool`
:param private: include \"_private\" modules
:type private: :class:`bool`
:param suffix: file suffix
:type suffix: :class:`str`
:param template_dirs: directories to search for user templates
:type template_dirs: None | :class:`list`
:returns: None
:rtype: None
:raises: OSError
"""
suffix = suffix.strip('.')
if not os.path.isdir(src):
raise OSError("%s is not a directory" % src)
if not os.path.isdir(dest) and not dryrun:
os.makedirs(dest)
src = os.path.normpath(os.path.abspath(src))
exclude = normalize_excludes(exclude)
loader = make_loader(template_dirs)
env = make_environment(loader)
recurse_tree(app, env, src, dest, exclude, followlinks, force, dryrun, private, suffix)
def main(app):
"""Parse the config of the app and initiate the generation process
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:returns: None
:rtype: None
:raises: None
"""
c = app.config
src = c.jinjaapi_srcdir
if not src:
return
suffix = "rst"
out = c.jinjaapi_outputdir or app.env.srcdir
if c.jinjaapi_addsummarytemplate:
tpath = pkg_resources.resource_filename(__package__, AUTOSUMMARYTEMPLATE_DIR)
c.templates_path.append(tpath)
tpath = pkg_resources.resource_filename(__package__, TEMPLATE_DIR)
c.templates_path.append(tpath)
prepare_dir(app, out, not c.jinjaapi_nodelete)
generate(app, src, out,
exclude=c.jinjaapi_exclude_paths,
force=c.jinjaapi_force,
followlinks=c.jinjaapi_followlinks,
dryrun=c.jinjaapi_dryrun,
private=c.jinjaapi_includeprivate,
suffix=suffix,
template_dirs=c.templates_path)
|
storax/jinjaapidoc
|
src/jinjaapidoc/gendoc.py
|
get_subpackages
|
python
|
def get_subpackages(app, module):
submodules = _get_submodules(app, module)
return [name for name, ispkg in submodules if ispkg]
|
Get all subpackages for the given module/package
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param module: the module to query or module path
:type module: module | str
:returns: list of packages names
:rtype: list
:raises: TypeError
|
train
|
https://github.com/storax/jinjaapidoc/blob/f1eeb6ab5bd1a96c4130306718c6423f37c76856/src/jinjaapidoc/gendoc.py#L262-L274
|
[
"def _get_submodules(app, module):\n \"\"\"Get all submodules for the given module/package\n\n :param app: the sphinx app\n :type app: :class:`sphinx.application.Sphinx`\n :param module: the module to query or module path\n :type module: module | str\n :returns: list of module names and boolean whether its a package\n :rtype: list\n :raises: TypeError\n \"\"\"\n if inspect.ismodule(module):\n if hasattr(module, '__path__'):\n p = module.__path__\n else:\n return []\n elif isinstance(module, str):\n p = module\n else:\n raise TypeError(\"Only Module or String accepted. %s given.\" % type(module))\n logger.debug('Getting submodules of %s', p)\n submodules = [(name, ispkg) for loader, name, ispkg in pkgutil.iter_modules(p)]\n logger.debug('Found submodules of %s: %s', module, submodules)\n return submodules\n"
] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""This is a modification of sphinx.apidoc by David.Zuber.
It uses jinja templates to render the rst files.
Parses a directory tree looking for Python modules and packages and creates
ReST files appropriately to create code documentation with Sphinx.
This is derived form the "sphinx-apidoc" script, which is:
Copyright 2007-2014 by the Sphinx team, see http://sphinx-doc.org/latest/authors.html.
"""
import os
import inspect
import pkgutil
import pkg_resources
import shutil
import jinja2
from sphinx.util.osutil import walk
from sphinx.util import logging
from sphinx.ext import autosummary
logger = logging.getLogger(__name__)
INITPY = '__init__.py'
PY_SUFFIXES = set(['.py', '.pyx'])
TEMPLATE_DIR = 'templates'
"""Built-in template dir for jinjaapi rendering"""
AUTOSUMMARYTEMPLATE_DIR = 'autosummarytemplates'
"""Templates for autosummary"""
MODULE_TEMPLATE_NAME = 'jinjaapi_module.rst'
"""Name of the template that is used for rendering modules."""
PACKAGE_TEMPLATE_NAME = 'jinjaapi_package.rst'
"""Name of the template that is used for rendering packages."""
def prepare_dir(app, directory, delete=False):
"""Create apidoc dir, delete contents if delete is True.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param directory: the apidoc directory. you can use relative paths here
:type directory: str
:param delete: if True, deletes the contents of apidoc. This acts like an override switch.
:type delete: bool
:returns: None
:rtype: None
:raises: None
"""
logger.info("Preparing output directories for jinjaapidoc.")
if os.path.exists(directory):
if delete:
logger.debug("Deleting dir %s", directory)
shutil.rmtree(directory)
logger.debug("Creating dir %s", directory)
os.mkdir(directory)
else:
logger.debug("Creating %s", directory)
os.mkdir(directory)
def make_loader(template_dirs):
"""Return a new :class:`jinja2.FileSystemLoader` that uses the template_dirs
:param template_dirs: directories to search for templates
:type template_dirs: None | :class:`list`
:returns: a new loader
:rtype: :class:`jinja2.FileSystemLoader`
:raises: None
"""
return jinja2.FileSystemLoader(searchpath=template_dirs)
def make_environment(loader):
"""Return a new :class:`jinja2.Environment` with the given loader
:param loader: a jinja2 loader
:type loader: :class:`jinja2.BaseLoader`
:returns: a new environment
:rtype: :class:`jinja2.Environment`
:raises: None
"""
return jinja2.Environment(loader=loader)
def makename(package, module):
"""Join package and module with a dot.
Package or Module can be empty.
:param package: the package name
:type package: :class:`str`
:param module: the module name
:type module: :class:`str`
:returns: the joined name
:rtype: :class:`str`
:raises: :class:`AssertionError`, if both package and module are empty
"""
# Both package and module can be None/empty.
assert package or module, "Specify either package or module"
if package:
name = package
if module:
name += '.' + module
else:
name = module
return name
def write_file(app, name, text, dest, suffix, dryrun, force):
"""Write the output file for module/package <name>.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param name: the file name without file extension
:type name: :class:`str`
:param text: the content of the file
:type text: :class:`str`
:param dest: the output directory
:type dest: :class:`str`
:param suffix: the file extension
:type suffix: :class:`str`
:param dryrun: If True, do not create any files, just log the potential location.
:type dryrun: :class:`bool`
:param force: Overwrite existing files
:type force: :class:`bool`
:returns: None
:raises: None
"""
fname = os.path.join(dest, '%s.%s' % (name, suffix))
if dryrun:
logger.info('Would create file %s.' % fname)
return
if not force and os.path.isfile(fname):
logger.info('File %s already exists, skipping.' % fname)
else:
logger.info('Creating file %s.' % fname)
f = open(fname, 'w')
try:
f.write(text)
relpath = os.path.relpath(fname, start=app.env.srcdir)
abspath = os.sep + relpath
docpath = app.env.relfn2path(abspath)[0]
docpath = docpath.rsplit(os.path.extsep, 1)[0]
logger.debug('Adding document %s' % docpath)
app.env.found_docs.add(docpath)
finally:
f.close()
def import_name(app, name):
"""Import the given name and return name, obj, parent, mod_name
:param name: name to import
:type name: str
:returns: the imported object or None
:rtype: object | None
:raises: None
"""
try:
logger.debug('Importing %r', name)
name, obj = autosummary.import_by_name(name)[:2]
logger.debug('Imported %s', obj)
return obj
except ImportError as e:
logger.warn("Jinjapidoc failed to import %r: %s", name, e)
def get_members(app, mod, typ, include_public=None):
"""Return the members of mod of the given type
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param mod: the module with members
:type mod: module
:param typ: the typ, ``'class'``, ``'function'``, ``'exception'``, ``'data'``, ``'members'``
:type typ: str
:param include_public: list of private members to include to publics
:type include_public: list | None
:returns: None
:rtype: None
:raises: None
"""
def include_here(x):
"""Return true if the member should be included in mod.
A member will be included if it is declared in this module or package.
If the `jinjaapidoc_include_from_all` option is `True` then the member
can also be included if it is listed in `__all__`.
:param x: The member
:type x: A class, exception, or function.
:returns: True if the member should be included in mod. False otherwise.
:rtype: bool
"""
return (x.__module__ == mod.__name__ or (include_from_all and x.__name__ in all_list))
all_list = getattr(mod, '__all__', [])
include_from_all = app.config.jinjaapi_include_from_all
include_public = include_public or []
tests = {'class': lambda x: inspect.isclass(x) and not issubclass(x, BaseException) and include_here(x),
'function': lambda x: inspect.isfunction(x) and include_here(x),
'exception': lambda x: inspect.isclass(x) and issubclass(x, BaseException) and include_here(x),
'data': lambda x: not inspect.ismodule(x) and not inspect.isclass(x) and not inspect.isfunction(x),
'members': lambda x: True}
items = []
for name in dir(mod):
i = getattr(mod, name)
inspect.ismodule(i)
if tests.get(typ, lambda x: False)(i):
items.append(name)
public = [x for x in items
if x in include_public or not x.startswith('_')]
logger.debug('Got members of %s of type %s: public %s and %s', mod, typ, public, items)
return public, items
def _get_submodules(app, module):
"""Get all submodules for the given module/package
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param module: the module to query or module path
:type module: module | str
:returns: list of module names and boolean whether its a package
:rtype: list
:raises: TypeError
"""
if inspect.ismodule(module):
if hasattr(module, '__path__'):
p = module.__path__
else:
return []
elif isinstance(module, str):
p = module
else:
raise TypeError("Only Module or String accepted. %s given." % type(module))
logger.debug('Getting submodules of %s', p)
submodules = [(name, ispkg) for loader, name, ispkg in pkgutil.iter_modules(p)]
logger.debug('Found submodules of %s: %s', module, submodules)
return submodules
def get_submodules(app, module):
"""Get all submodules without packages for the given module/package
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param module: the module to query or module path
:type module: module | str
:returns: list of module names excluding packages
:rtype: list
:raises: TypeError
"""
submodules = _get_submodules(app, module)
return [name for name, ispkg in submodules if not ispkg]
def get_context(app, package, module, fullname):
"""Return a dict for template rendering
Variables:
* :package: The top package
* :module: the module
* :fullname: package.module
* :subpkgs: packages beneath module
* :submods: modules beneath module
* :classes: public classes in module
* :allclasses: public and private classes in module
* :exceptions: public exceptions in module
* :allexceptions: public and private exceptions in module
* :functions: public functions in module
* :allfunctions: public and private functions in module
* :data: public data in module
* :alldata: public and private data in module
* :members: dir(module)
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param package: the parent package name
:type package: str
:param module: the module name
:type module: str
:param fullname: package.module
:type fullname: str
:returns: a dict with variables for template rendering
:rtype: :class:`dict`
:raises: None
"""
var = {'package': package,
'module': module,
'fullname': fullname}
logger.debug('Creating context for: package %s, module %s, fullname %s', package, module, fullname)
obj = import_name(app, fullname)
if not obj:
for k in ('subpkgs', 'submods', 'classes', 'allclasses',
'exceptions', 'allexceptions', 'functions', 'allfunctions',
'data', 'alldata', 'memebers'):
var[k] = []
return var
var['subpkgs'] = get_subpackages(app, obj)
var['submods'] = get_submodules(app, obj)
var['classes'], var['allclasses'] = get_members(app, obj, 'class')
var['exceptions'], var['allexceptions'] = get_members(app, obj, 'exception')
var['functions'], var['allfunctions'] = get_members(app, obj, 'function')
var['data'], var['alldata'] = get_members(app, obj, 'data')
var['members'] = get_members(app, obj, 'members')
logger.debug('Created context: %s', var)
return var
def create_module_file(app, env, package, module, dest, suffix, dryrun, force):
"""Build the text of the file and write the file.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param env: the jinja environment for the templates
:type env: :class:`jinja2.Environment`
:param package: the package name
:type package: :class:`str`
:param module: the module name
:type module: :class:`str`
:param dest: the output directory
:type dest: :class:`str`
:param suffix: the file extension
:type suffix: :class:`str`
:param dryrun: If True, do not create any files, just log the potential location.
:type dryrun: :class:`bool`
:param force: Overwrite existing files
:type force: :class:`bool`
:returns: None
:raises: None
"""
logger.debug('Create module file: package %s, module %s', package, module)
template_file = MODULE_TEMPLATE_NAME
template = env.get_template(template_file)
fn = makename(package, module)
var = get_context(app, package, module, fn)
var['ispkg'] = False
rendered = template.render(var)
write_file(app, makename(package, module), rendered, dest, suffix, dryrun, force)
def create_package_file(app, env, root_package, sub_package, private,
dest, suffix, dryrun, force):
"""Build the text of the file and write the file.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param env: the jinja environment for the templates
:type env: :class:`jinja2.Environment`
:param root_package: the parent package
:type root_package: :class:`str`
:param sub_package: the package name without root
:type sub_package: :class:`str`
:param private: Include \"_private\" modules
:type private: :class:`bool`
:param dest: the output directory
:type dest: :class:`str`
:param suffix: the file extension
:type suffix: :class:`str`
:param dryrun: If True, do not create any files, just log the potential location.
:type dryrun: :class:`bool`
:param force: Overwrite existing files
:type force: :class:`bool`
:returns: None
:raises: None
"""
logger.debug('Create package file: rootpackage %s, sub_package %s', root_package, sub_package)
template_file = PACKAGE_TEMPLATE_NAME
template = env.get_template(template_file)
fn = makename(root_package, sub_package)
var = get_context(app, root_package, sub_package, fn)
var['ispkg'] = True
for submod in var['submods']:
if shall_skip(app, submod, private):
continue
create_module_file(app, env, fn, submod, dest, suffix, dryrun, force)
rendered = template.render(var)
write_file(app, fn, rendered, dest, suffix, dryrun, force)
def shall_skip(app, module, private):
"""Check if we want to skip this module.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param module: the module name
:type module: :class:`str`
:param private: True, if privates are allowed
:type private: :class:`bool`
"""
logger.debug('Testing if %s should be skipped.', module)
# skip if it has a "private" name and this is selected
if module != '__init__.py' and module.startswith('_') and \
not private:
logger.debug('Skip %s because its either private or __init__.', module)
return True
logger.debug('Do not skip %s', module)
return False
def recurse_tree(app, env, src, dest, excludes, followlinks, force, dryrun, private, suffix):
"""Look for every file in the directory tree and create the corresponding
ReST files.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param env: the jinja environment
:type env: :class:`jinja2.Environment`
:param src: the path to the python source files
:type src: :class:`str`
:param dest: the output directory
:type dest: :class:`str`
:param excludes: the paths to exclude
:type excludes: :class:`list`
:param followlinks: follow symbolic links
:type followlinks: :class:`bool`
:param force: overwrite existing files
:type force: :class:`bool`
:param dryrun: do not generate files
:type dryrun: :class:`bool`
:param private: include "_private" modules
:type private: :class:`bool`
:param suffix: the file extension
:type suffix: :class:`str`
"""
# check if the base directory is a package and get its name
if INITPY in os.listdir(src):
root_package = src.split(os.path.sep)[-1]
else:
# otherwise, the base is a directory with packages
root_package = None
toplevels = []
for root, subs, files in walk(src, followlinks=followlinks):
# document only Python module files (that aren't excluded)
py_files = sorted(f for f in files
if os.path.splitext(f)[1] in PY_SUFFIXES and # noqa: W504
not is_excluded(os.path.join(root, f), excludes))
is_pkg = INITPY in py_files
if is_pkg:
py_files.remove(INITPY)
py_files.insert(0, INITPY)
elif root != src:
# only accept non-package at toplevel
del subs[:]
continue
# remove hidden ('.') and private ('_') directories, as well as
# excluded dirs
if private:
exclude_prefixes = ('.',)
else:
exclude_prefixes = ('.', '_')
subs[:] = sorted(sub for sub in subs if not sub.startswith(exclude_prefixes) and not
is_excluded(os.path.join(root, sub), excludes))
if is_pkg:
# we are in a package with something to document
if subs or len(py_files) > 1 or not \
shall_skip(app, os.path.join(root, INITPY), private):
subpackage = root[len(src):].lstrip(os.path.sep).\
replace(os.path.sep, '.')
create_package_file(app, env, root_package, subpackage,
private, dest, suffix, dryrun, force)
toplevels.append(makename(root_package, subpackage))
else:
# if we are at the root level, we don't require it to be a package
assert root == src and root_package is None
for py_file in py_files:
if not shall_skip(app, os.path.join(src, py_file), private):
module = os.path.splitext(py_file)[0]
create_module_file(app, env, root_package, module, dest, suffix, dryrun, force)
toplevels.append(module)
return toplevels
def normalize_excludes(excludes):
"""Normalize the excluded directory list."""
return [os.path.normpath(os.path.abspath(exclude)) for exclude in excludes]
def is_excluded(root, excludes):
"""Check if the directory is in the exclude list.
Note: by having trailing slashes, we avoid common prefix issues, like
e.g. an exlude "foo" also accidentally excluding "foobar".
"""
root = os.path.normpath(root)
for exclude in excludes:
if root == exclude:
return True
return False
def generate(app, src, dest, exclude=[], followlinks=False,
force=False, dryrun=False, private=False, suffix='rst',
template_dirs=None):
"""Generage the rst files
Raises an :class:`OSError` if the source path is not a directory.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param src: path to python source files
:type src: :class:`str`
:param dest: output directory
:type dest: :class:`str`
:param exclude: list of paths to exclude
:type exclude: :class:`list`
:param followlinks: follow symbolic links
:type followlinks: :class:`bool`
:param force: overwrite existing files
:type force: :class:`bool`
:param dryrun: do not create any files
:type dryrun: :class:`bool`
:param private: include \"_private\" modules
:type private: :class:`bool`
:param suffix: file suffix
:type suffix: :class:`str`
:param template_dirs: directories to search for user templates
:type template_dirs: None | :class:`list`
:returns: None
:rtype: None
:raises: OSError
"""
suffix = suffix.strip('.')
if not os.path.isdir(src):
raise OSError("%s is not a directory" % src)
if not os.path.isdir(dest) and not dryrun:
os.makedirs(dest)
src = os.path.normpath(os.path.abspath(src))
exclude = normalize_excludes(exclude)
loader = make_loader(template_dirs)
env = make_environment(loader)
recurse_tree(app, env, src, dest, exclude, followlinks, force, dryrun, private, suffix)
def main(app):
"""Parse the config of the app and initiate the generation process
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:returns: None
:rtype: None
:raises: None
"""
c = app.config
src = c.jinjaapi_srcdir
if not src:
return
suffix = "rst"
out = c.jinjaapi_outputdir or app.env.srcdir
if c.jinjaapi_addsummarytemplate:
tpath = pkg_resources.resource_filename(__package__, AUTOSUMMARYTEMPLATE_DIR)
c.templates_path.append(tpath)
tpath = pkg_resources.resource_filename(__package__, TEMPLATE_DIR)
c.templates_path.append(tpath)
prepare_dir(app, out, not c.jinjaapi_nodelete)
generate(app, src, out,
exclude=c.jinjaapi_exclude_paths,
force=c.jinjaapi_force,
followlinks=c.jinjaapi_followlinks,
dryrun=c.jinjaapi_dryrun,
private=c.jinjaapi_includeprivate,
suffix=suffix,
template_dirs=c.templates_path)
|
storax/jinjaapidoc
|
src/jinjaapidoc/gendoc.py
|
get_context
|
python
|
def get_context(app, package, module, fullname):
var = {'package': package,
'module': module,
'fullname': fullname}
logger.debug('Creating context for: package %s, module %s, fullname %s', package, module, fullname)
obj = import_name(app, fullname)
if not obj:
for k in ('subpkgs', 'submods', 'classes', 'allclasses',
'exceptions', 'allexceptions', 'functions', 'allfunctions',
'data', 'alldata', 'memebers'):
var[k] = []
return var
var['subpkgs'] = get_subpackages(app, obj)
var['submods'] = get_submodules(app, obj)
var['classes'], var['allclasses'] = get_members(app, obj, 'class')
var['exceptions'], var['allexceptions'] = get_members(app, obj, 'exception')
var['functions'], var['allfunctions'] = get_members(app, obj, 'function')
var['data'], var['alldata'] = get_members(app, obj, 'data')
var['members'] = get_members(app, obj, 'members')
logger.debug('Created context: %s', var)
return var
|
Return a dict for template rendering
Variables:
* :package: The top package
* :module: the module
* :fullname: package.module
* :subpkgs: packages beneath module
* :submods: modules beneath module
* :classes: public classes in module
* :allclasses: public and private classes in module
* :exceptions: public exceptions in module
* :allexceptions: public and private exceptions in module
* :functions: public functions in module
* :allfunctions: public and private functions in module
* :data: public data in module
* :alldata: public and private data in module
* :members: dir(module)
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param package: the parent package name
:type package: str
:param module: the module name
:type module: str
:param fullname: package.module
:type fullname: str
:returns: a dict with variables for template rendering
:rtype: :class:`dict`
:raises: None
|
train
|
https://github.com/storax/jinjaapidoc/blob/f1eeb6ab5bd1a96c4130306718c6423f37c76856/src/jinjaapidoc/gendoc.py#L277-L330
|
[
"def import_name(app, name):\n \"\"\"Import the given name and return name, obj, parent, mod_name\n\n :param name: name to import\n :type name: str\n :returns: the imported object or None\n :rtype: object | None\n :raises: None\n \"\"\"\n try:\n logger.debug('Importing %r', name)\n name, obj = autosummary.import_by_name(name)[:2]\n logger.debug('Imported %s', obj)\n return obj\n except ImportError as e:\n logger.warn(\"Jinjapidoc failed to import %r: %s\", name, e)\n",
"def get_members(app, mod, typ, include_public=None):\n \"\"\"Return the members of mod of the given type\n\n :param app: the sphinx app\n :type app: :class:`sphinx.application.Sphinx`\n :param mod: the module with members\n :type mod: module\n :param typ: the typ, ``'class'``, ``'function'``, ``'exception'``, ``'data'``, ``'members'``\n :type typ: str\n :param include_public: list of private members to include to publics\n :type include_public: list | None\n :returns: None\n :rtype: None\n :raises: None\n \"\"\"\n def include_here(x):\n \"\"\"Return true if the member should be included in mod.\n\n A member will be included if it is declared in this module or package.\n If the `jinjaapidoc_include_from_all` option is `True` then the member\n can also be included if it is listed in `__all__`.\n\n :param x: The member\n :type x: A class, exception, or function.\n :returns: True if the member should be included in mod. False otherwise.\n :rtype: bool\n \"\"\"\n return (x.__module__ == mod.__name__ or (include_from_all and x.__name__ in all_list))\n\n all_list = getattr(mod, '__all__', [])\n include_from_all = app.config.jinjaapi_include_from_all\n\n include_public = include_public or []\n tests = {'class': lambda x: inspect.isclass(x) and not issubclass(x, BaseException) and include_here(x),\n 'function': lambda x: inspect.isfunction(x) and include_here(x),\n 'exception': lambda x: inspect.isclass(x) and issubclass(x, BaseException) and include_here(x),\n 'data': lambda x: not inspect.ismodule(x) and not inspect.isclass(x) and not inspect.isfunction(x),\n 'members': lambda x: True}\n items = []\n for name in dir(mod):\n i = getattr(mod, name)\n inspect.ismodule(i)\n\n if tests.get(typ, lambda x: False)(i):\n items.append(name)\n public = [x for x in items\n if x in include_public or not x.startswith('_')]\n logger.debug('Got members of %s of type %s: public %s and %s', mod, typ, public, items)\n return public, items\n",
"def get_submodules(app, module):\n \"\"\"Get all submodules without packages for the given module/package\n\n :param app: the sphinx app\n :type app: :class:`sphinx.application.Sphinx`\n :param module: the module to query or module path\n :type module: module | str\n :returns: list of module names excluding packages\n :rtype: list\n :raises: TypeError\n \"\"\"\n submodules = _get_submodules(app, module)\n return [name for name, ispkg in submodules if not ispkg]\n",
"def get_subpackages(app, module):\n \"\"\"Get all subpackages for the given module/package\n\n :param app: the sphinx app\n :type app: :class:`sphinx.application.Sphinx`\n :param module: the module to query or module path\n :type module: module | str\n :returns: list of packages names\n :rtype: list\n :raises: TypeError\n \"\"\"\n submodules = _get_submodules(app, module)\n return [name for name, ispkg in submodules if ispkg]\n"
] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""This is a modification of sphinx.apidoc by David.Zuber.
It uses jinja templates to render the rst files.
Parses a directory tree looking for Python modules and packages and creates
ReST files appropriately to create code documentation with Sphinx.
This is derived form the "sphinx-apidoc" script, which is:
Copyright 2007-2014 by the Sphinx team, see http://sphinx-doc.org/latest/authors.html.
"""
import os
import inspect
import pkgutil
import pkg_resources
import shutil
import jinja2
from sphinx.util.osutil import walk
from sphinx.util import logging
from sphinx.ext import autosummary
logger = logging.getLogger(__name__)
INITPY = '__init__.py'
PY_SUFFIXES = set(['.py', '.pyx'])
TEMPLATE_DIR = 'templates'
"""Built-in template dir for jinjaapi rendering"""
AUTOSUMMARYTEMPLATE_DIR = 'autosummarytemplates'
"""Templates for autosummary"""
MODULE_TEMPLATE_NAME = 'jinjaapi_module.rst'
"""Name of the template that is used for rendering modules."""
PACKAGE_TEMPLATE_NAME = 'jinjaapi_package.rst'
"""Name of the template that is used for rendering packages."""
def prepare_dir(app, directory, delete=False):
"""Create apidoc dir, delete contents if delete is True.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param directory: the apidoc directory. you can use relative paths here
:type directory: str
:param delete: if True, deletes the contents of apidoc. This acts like an override switch.
:type delete: bool
:returns: None
:rtype: None
:raises: None
"""
logger.info("Preparing output directories for jinjaapidoc.")
if os.path.exists(directory):
if delete:
logger.debug("Deleting dir %s", directory)
shutil.rmtree(directory)
logger.debug("Creating dir %s", directory)
os.mkdir(directory)
else:
logger.debug("Creating %s", directory)
os.mkdir(directory)
def make_loader(template_dirs):
"""Return a new :class:`jinja2.FileSystemLoader` that uses the template_dirs
:param template_dirs: directories to search for templates
:type template_dirs: None | :class:`list`
:returns: a new loader
:rtype: :class:`jinja2.FileSystemLoader`
:raises: None
"""
return jinja2.FileSystemLoader(searchpath=template_dirs)
def make_environment(loader):
"""Return a new :class:`jinja2.Environment` with the given loader
:param loader: a jinja2 loader
:type loader: :class:`jinja2.BaseLoader`
:returns: a new environment
:rtype: :class:`jinja2.Environment`
:raises: None
"""
return jinja2.Environment(loader=loader)
def makename(package, module):
"""Join package and module with a dot.
Package or Module can be empty.
:param package: the package name
:type package: :class:`str`
:param module: the module name
:type module: :class:`str`
:returns: the joined name
:rtype: :class:`str`
:raises: :class:`AssertionError`, if both package and module are empty
"""
# Both package and module can be None/empty.
assert package or module, "Specify either package or module"
if package:
name = package
if module:
name += '.' + module
else:
name = module
return name
def write_file(app, name, text, dest, suffix, dryrun, force):
"""Write the output file for module/package <name>.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param name: the file name without file extension
:type name: :class:`str`
:param text: the content of the file
:type text: :class:`str`
:param dest: the output directory
:type dest: :class:`str`
:param suffix: the file extension
:type suffix: :class:`str`
:param dryrun: If True, do not create any files, just log the potential location.
:type dryrun: :class:`bool`
:param force: Overwrite existing files
:type force: :class:`bool`
:returns: None
:raises: None
"""
fname = os.path.join(dest, '%s.%s' % (name, suffix))
if dryrun:
logger.info('Would create file %s.' % fname)
return
if not force and os.path.isfile(fname):
logger.info('File %s already exists, skipping.' % fname)
else:
logger.info('Creating file %s.' % fname)
f = open(fname, 'w')
try:
f.write(text)
relpath = os.path.relpath(fname, start=app.env.srcdir)
abspath = os.sep + relpath
docpath = app.env.relfn2path(abspath)[0]
docpath = docpath.rsplit(os.path.extsep, 1)[0]
logger.debug('Adding document %s' % docpath)
app.env.found_docs.add(docpath)
finally:
f.close()
def import_name(app, name):
"""Import the given name and return name, obj, parent, mod_name
:param name: name to import
:type name: str
:returns: the imported object or None
:rtype: object | None
:raises: None
"""
try:
logger.debug('Importing %r', name)
name, obj = autosummary.import_by_name(name)[:2]
logger.debug('Imported %s', obj)
return obj
except ImportError as e:
logger.warn("Jinjapidoc failed to import %r: %s", name, e)
def get_members(app, mod, typ, include_public=None):
"""Return the members of mod of the given type
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param mod: the module with members
:type mod: module
:param typ: the typ, ``'class'``, ``'function'``, ``'exception'``, ``'data'``, ``'members'``
:type typ: str
:param include_public: list of private members to include to publics
:type include_public: list | None
:returns: None
:rtype: None
:raises: None
"""
def include_here(x):
"""Return true if the member should be included in mod.
A member will be included if it is declared in this module or package.
If the `jinjaapidoc_include_from_all` option is `True` then the member
can also be included if it is listed in `__all__`.
:param x: The member
:type x: A class, exception, or function.
:returns: True if the member should be included in mod. False otherwise.
:rtype: bool
"""
return (x.__module__ == mod.__name__ or (include_from_all and x.__name__ in all_list))
all_list = getattr(mod, '__all__', [])
include_from_all = app.config.jinjaapi_include_from_all
include_public = include_public or []
tests = {'class': lambda x: inspect.isclass(x) and not issubclass(x, BaseException) and include_here(x),
'function': lambda x: inspect.isfunction(x) and include_here(x),
'exception': lambda x: inspect.isclass(x) and issubclass(x, BaseException) and include_here(x),
'data': lambda x: not inspect.ismodule(x) and not inspect.isclass(x) and not inspect.isfunction(x),
'members': lambda x: True}
items = []
for name in dir(mod):
i = getattr(mod, name)
inspect.ismodule(i)
if tests.get(typ, lambda x: False)(i):
items.append(name)
public = [x for x in items
if x in include_public or not x.startswith('_')]
logger.debug('Got members of %s of type %s: public %s and %s', mod, typ, public, items)
return public, items
def _get_submodules(app, module):
"""Get all submodules for the given module/package
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param module: the module to query or module path
:type module: module | str
:returns: list of module names and boolean whether its a package
:rtype: list
:raises: TypeError
"""
if inspect.ismodule(module):
if hasattr(module, '__path__'):
p = module.__path__
else:
return []
elif isinstance(module, str):
p = module
else:
raise TypeError("Only Module or String accepted. %s given." % type(module))
logger.debug('Getting submodules of %s', p)
submodules = [(name, ispkg) for loader, name, ispkg in pkgutil.iter_modules(p)]
logger.debug('Found submodules of %s: %s', module, submodules)
return submodules
def get_submodules(app, module):
"""Get all submodules without packages for the given module/package
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param module: the module to query or module path
:type module: module | str
:returns: list of module names excluding packages
:rtype: list
:raises: TypeError
"""
submodules = _get_submodules(app, module)
return [name for name, ispkg in submodules if not ispkg]
def get_subpackages(app, module):
"""Get all subpackages for the given module/package
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param module: the module to query or module path
:type module: module | str
:returns: list of packages names
:rtype: list
:raises: TypeError
"""
submodules = _get_submodules(app, module)
return [name for name, ispkg in submodules if ispkg]
def create_module_file(app, env, package, module, dest, suffix, dryrun, force):
"""Build the text of the file and write the file.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param env: the jinja environment for the templates
:type env: :class:`jinja2.Environment`
:param package: the package name
:type package: :class:`str`
:param module: the module name
:type module: :class:`str`
:param dest: the output directory
:type dest: :class:`str`
:param suffix: the file extension
:type suffix: :class:`str`
:param dryrun: If True, do not create any files, just log the potential location.
:type dryrun: :class:`bool`
:param force: Overwrite existing files
:type force: :class:`bool`
:returns: None
:raises: None
"""
logger.debug('Create module file: package %s, module %s', package, module)
template_file = MODULE_TEMPLATE_NAME
template = env.get_template(template_file)
fn = makename(package, module)
var = get_context(app, package, module, fn)
var['ispkg'] = False
rendered = template.render(var)
write_file(app, makename(package, module), rendered, dest, suffix, dryrun, force)
def create_package_file(app, env, root_package, sub_package, private,
dest, suffix, dryrun, force):
"""Build the text of the file and write the file.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param env: the jinja environment for the templates
:type env: :class:`jinja2.Environment`
:param root_package: the parent package
:type root_package: :class:`str`
:param sub_package: the package name without root
:type sub_package: :class:`str`
:param private: Include \"_private\" modules
:type private: :class:`bool`
:param dest: the output directory
:type dest: :class:`str`
:param suffix: the file extension
:type suffix: :class:`str`
:param dryrun: If True, do not create any files, just log the potential location.
:type dryrun: :class:`bool`
:param force: Overwrite existing files
:type force: :class:`bool`
:returns: None
:raises: None
"""
logger.debug('Create package file: rootpackage %s, sub_package %s', root_package, sub_package)
template_file = PACKAGE_TEMPLATE_NAME
template = env.get_template(template_file)
fn = makename(root_package, sub_package)
var = get_context(app, root_package, sub_package, fn)
var['ispkg'] = True
for submod in var['submods']:
if shall_skip(app, submod, private):
continue
create_module_file(app, env, fn, submod, dest, suffix, dryrun, force)
rendered = template.render(var)
write_file(app, fn, rendered, dest, suffix, dryrun, force)
def shall_skip(app, module, private):
"""Check if we want to skip this module.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param module: the module name
:type module: :class:`str`
:param private: True, if privates are allowed
:type private: :class:`bool`
"""
logger.debug('Testing if %s should be skipped.', module)
# skip if it has a "private" name and this is selected
if module != '__init__.py' and module.startswith('_') and \
not private:
logger.debug('Skip %s because its either private or __init__.', module)
return True
logger.debug('Do not skip %s', module)
return False
def recurse_tree(app, env, src, dest, excludes, followlinks, force, dryrun, private, suffix):
"""Look for every file in the directory tree and create the corresponding
ReST files.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param env: the jinja environment
:type env: :class:`jinja2.Environment`
:param src: the path to the python source files
:type src: :class:`str`
:param dest: the output directory
:type dest: :class:`str`
:param excludes: the paths to exclude
:type excludes: :class:`list`
:param followlinks: follow symbolic links
:type followlinks: :class:`bool`
:param force: overwrite existing files
:type force: :class:`bool`
:param dryrun: do not generate files
:type dryrun: :class:`bool`
:param private: include "_private" modules
:type private: :class:`bool`
:param suffix: the file extension
:type suffix: :class:`str`
"""
# check if the base directory is a package and get its name
if INITPY in os.listdir(src):
root_package = src.split(os.path.sep)[-1]
else:
# otherwise, the base is a directory with packages
root_package = None
toplevels = []
for root, subs, files in walk(src, followlinks=followlinks):
# document only Python module files (that aren't excluded)
py_files = sorted(f for f in files
if os.path.splitext(f)[1] in PY_SUFFIXES and # noqa: W504
not is_excluded(os.path.join(root, f), excludes))
is_pkg = INITPY in py_files
if is_pkg:
py_files.remove(INITPY)
py_files.insert(0, INITPY)
elif root != src:
# only accept non-package at toplevel
del subs[:]
continue
# remove hidden ('.') and private ('_') directories, as well as
# excluded dirs
if private:
exclude_prefixes = ('.',)
else:
exclude_prefixes = ('.', '_')
subs[:] = sorted(sub for sub in subs if not sub.startswith(exclude_prefixes) and not
is_excluded(os.path.join(root, sub), excludes))
if is_pkg:
# we are in a package with something to document
if subs or len(py_files) > 1 or not \
shall_skip(app, os.path.join(root, INITPY), private):
subpackage = root[len(src):].lstrip(os.path.sep).\
replace(os.path.sep, '.')
create_package_file(app, env, root_package, subpackage,
private, dest, suffix, dryrun, force)
toplevels.append(makename(root_package, subpackage))
else:
# if we are at the root level, we don't require it to be a package
assert root == src and root_package is None
for py_file in py_files:
if not shall_skip(app, os.path.join(src, py_file), private):
module = os.path.splitext(py_file)[0]
create_module_file(app, env, root_package, module, dest, suffix, dryrun, force)
toplevels.append(module)
return toplevels
def normalize_excludes(excludes):
"""Normalize the excluded directory list."""
return [os.path.normpath(os.path.abspath(exclude)) for exclude in excludes]
def is_excluded(root, excludes):
"""Check if the directory is in the exclude list.
Note: by having trailing slashes, we avoid common prefix issues, like
e.g. an exlude "foo" also accidentally excluding "foobar".
"""
root = os.path.normpath(root)
for exclude in excludes:
if root == exclude:
return True
return False
def generate(app, src, dest, exclude=[], followlinks=False,
force=False, dryrun=False, private=False, suffix='rst',
template_dirs=None):
"""Generage the rst files
Raises an :class:`OSError` if the source path is not a directory.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param src: path to python source files
:type src: :class:`str`
:param dest: output directory
:type dest: :class:`str`
:param exclude: list of paths to exclude
:type exclude: :class:`list`
:param followlinks: follow symbolic links
:type followlinks: :class:`bool`
:param force: overwrite existing files
:type force: :class:`bool`
:param dryrun: do not create any files
:type dryrun: :class:`bool`
:param private: include \"_private\" modules
:type private: :class:`bool`
:param suffix: file suffix
:type suffix: :class:`str`
:param template_dirs: directories to search for user templates
:type template_dirs: None | :class:`list`
:returns: None
:rtype: None
:raises: OSError
"""
suffix = suffix.strip('.')
if not os.path.isdir(src):
raise OSError("%s is not a directory" % src)
if not os.path.isdir(dest) and not dryrun:
os.makedirs(dest)
src = os.path.normpath(os.path.abspath(src))
exclude = normalize_excludes(exclude)
loader = make_loader(template_dirs)
env = make_environment(loader)
recurse_tree(app, env, src, dest, exclude, followlinks, force, dryrun, private, suffix)
def main(app):
"""Parse the config of the app and initiate the generation process
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:returns: None
:rtype: None
:raises: None
"""
c = app.config
src = c.jinjaapi_srcdir
if not src:
return
suffix = "rst"
out = c.jinjaapi_outputdir or app.env.srcdir
if c.jinjaapi_addsummarytemplate:
tpath = pkg_resources.resource_filename(__package__, AUTOSUMMARYTEMPLATE_DIR)
c.templates_path.append(tpath)
tpath = pkg_resources.resource_filename(__package__, TEMPLATE_DIR)
c.templates_path.append(tpath)
prepare_dir(app, out, not c.jinjaapi_nodelete)
generate(app, src, out,
exclude=c.jinjaapi_exclude_paths,
force=c.jinjaapi_force,
followlinks=c.jinjaapi_followlinks,
dryrun=c.jinjaapi_dryrun,
private=c.jinjaapi_includeprivate,
suffix=suffix,
template_dirs=c.templates_path)
|
storax/jinjaapidoc
|
src/jinjaapidoc/gendoc.py
|
create_module_file
|
python
|
def create_module_file(app, env, package, module, dest, suffix, dryrun, force):
logger.debug('Create module file: package %s, module %s', package, module)
template_file = MODULE_TEMPLATE_NAME
template = env.get_template(template_file)
fn = makename(package, module)
var = get_context(app, package, module, fn)
var['ispkg'] = False
rendered = template.render(var)
write_file(app, makename(package, module), rendered, dest, suffix, dryrun, force)
|
Build the text of the file and write the file.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param env: the jinja environment for the templates
:type env: :class:`jinja2.Environment`
:param package: the package name
:type package: :class:`str`
:param module: the module name
:type module: :class:`str`
:param dest: the output directory
:type dest: :class:`str`
:param suffix: the file extension
:type suffix: :class:`str`
:param dryrun: If True, do not create any files, just log the potential location.
:type dryrun: :class:`bool`
:param force: Overwrite existing files
:type force: :class:`bool`
:returns: None
:raises: None
|
train
|
https://github.com/storax/jinjaapidoc/blob/f1eeb6ab5bd1a96c4130306718c6423f37c76856/src/jinjaapidoc/gendoc.py#L333-L362
|
[
"def get_context(app, package, module, fullname):\n \"\"\"Return a dict for template rendering\n\n Variables:\n\n * :package: The top package\n * :module: the module\n * :fullname: package.module\n * :subpkgs: packages beneath module\n * :submods: modules beneath module\n * :classes: public classes in module\n * :allclasses: public and private classes in module\n * :exceptions: public exceptions in module\n * :allexceptions: public and private exceptions in module\n * :functions: public functions in module\n * :allfunctions: public and private functions in module\n * :data: public data in module\n * :alldata: public and private data in module\n * :members: dir(module)\n\n\n :param app: the sphinx app\n :type app: :class:`sphinx.application.Sphinx`\n :param package: the parent package name\n :type package: str\n :param module: the module name\n :type module: str\n :param fullname: package.module\n :type fullname: str\n :returns: a dict with variables for template rendering\n :rtype: :class:`dict`\n :raises: None\n \"\"\"\n var = {'package': package,\n 'module': module,\n 'fullname': fullname}\n logger.debug('Creating context for: package %s, module %s, fullname %s', package, module, fullname)\n obj = import_name(app, fullname)\n if not obj:\n for k in ('subpkgs', 'submods', 'classes', 'allclasses',\n 'exceptions', 'allexceptions', 'functions', 'allfunctions',\n 'data', 'alldata', 'memebers'):\n var[k] = []\n return var\n\n var['subpkgs'] = get_subpackages(app, obj)\n var['submods'] = get_submodules(app, obj)\n var['classes'], var['allclasses'] = get_members(app, obj, 'class')\n var['exceptions'], var['allexceptions'] = get_members(app, obj, 'exception')\n var['functions'], var['allfunctions'] = get_members(app, obj, 'function')\n var['data'], var['alldata'] = get_members(app, obj, 'data')\n var['members'] = get_members(app, obj, 'members')\n logger.debug('Created context: %s', var)\n return var\n",
"def write_file(app, name, text, dest, suffix, dryrun, force):\n \"\"\"Write the output file for module/package <name>.\n\n :param app: the sphinx app\n :type app: :class:`sphinx.application.Sphinx`\n :param name: the file name without file extension\n :type name: :class:`str`\n :param text: the content of the file\n :type text: :class:`str`\n :param dest: the output directory\n :type dest: :class:`str`\n :param suffix: the file extension\n :type suffix: :class:`str`\n :param dryrun: If True, do not create any files, just log the potential location.\n :type dryrun: :class:`bool`\n :param force: Overwrite existing files\n :type force: :class:`bool`\n :returns: None\n :raises: None\n \"\"\"\n fname = os.path.join(dest, '%s.%s' % (name, suffix))\n if dryrun:\n logger.info('Would create file %s.' % fname)\n return\n if not force and os.path.isfile(fname):\n logger.info('File %s already exists, skipping.' % fname)\n else:\n logger.info('Creating file %s.' % fname)\n f = open(fname, 'w')\n try:\n f.write(text)\n relpath = os.path.relpath(fname, start=app.env.srcdir)\n abspath = os.sep + relpath\n docpath = app.env.relfn2path(abspath)[0]\n docpath = docpath.rsplit(os.path.extsep, 1)[0]\n logger.debug('Adding document %s' % docpath)\n app.env.found_docs.add(docpath)\n finally:\n f.close()\n",
"def makename(package, module):\n \"\"\"Join package and module with a dot.\n\n Package or Module can be empty.\n\n :param package: the package name\n :type package: :class:`str`\n :param module: the module name\n :type module: :class:`str`\n :returns: the joined name\n :rtype: :class:`str`\n :raises: :class:`AssertionError`, if both package and module are empty\n \"\"\"\n # Both package and module can be None/empty.\n assert package or module, \"Specify either package or module\"\n if package:\n name = package\n if module:\n name += '.' + module\n else:\n name = module\n return name\n"
] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""This is a modification of sphinx.apidoc by David.Zuber.
It uses jinja templates to render the rst files.
Parses a directory tree looking for Python modules and packages and creates
ReST files appropriately to create code documentation with Sphinx.
This is derived form the "sphinx-apidoc" script, which is:
Copyright 2007-2014 by the Sphinx team, see http://sphinx-doc.org/latest/authors.html.
"""
import os
import inspect
import pkgutil
import pkg_resources
import shutil
import jinja2
from sphinx.util.osutil import walk
from sphinx.util import logging
from sphinx.ext import autosummary
logger = logging.getLogger(__name__)
INITPY = '__init__.py'
PY_SUFFIXES = set(['.py', '.pyx'])
TEMPLATE_DIR = 'templates'
"""Built-in template dir for jinjaapi rendering"""
AUTOSUMMARYTEMPLATE_DIR = 'autosummarytemplates'
"""Templates for autosummary"""
MODULE_TEMPLATE_NAME = 'jinjaapi_module.rst'
"""Name of the template that is used for rendering modules."""
PACKAGE_TEMPLATE_NAME = 'jinjaapi_package.rst'
"""Name of the template that is used for rendering packages."""
def prepare_dir(app, directory, delete=False):
"""Create apidoc dir, delete contents if delete is True.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param directory: the apidoc directory. you can use relative paths here
:type directory: str
:param delete: if True, deletes the contents of apidoc. This acts like an override switch.
:type delete: bool
:returns: None
:rtype: None
:raises: None
"""
logger.info("Preparing output directories for jinjaapidoc.")
if os.path.exists(directory):
if delete:
logger.debug("Deleting dir %s", directory)
shutil.rmtree(directory)
logger.debug("Creating dir %s", directory)
os.mkdir(directory)
else:
logger.debug("Creating %s", directory)
os.mkdir(directory)
def make_loader(template_dirs):
"""Return a new :class:`jinja2.FileSystemLoader` that uses the template_dirs
:param template_dirs: directories to search for templates
:type template_dirs: None | :class:`list`
:returns: a new loader
:rtype: :class:`jinja2.FileSystemLoader`
:raises: None
"""
return jinja2.FileSystemLoader(searchpath=template_dirs)
def make_environment(loader):
"""Return a new :class:`jinja2.Environment` with the given loader
:param loader: a jinja2 loader
:type loader: :class:`jinja2.BaseLoader`
:returns: a new environment
:rtype: :class:`jinja2.Environment`
:raises: None
"""
return jinja2.Environment(loader=loader)
def makename(package, module):
"""Join package and module with a dot.
Package or Module can be empty.
:param package: the package name
:type package: :class:`str`
:param module: the module name
:type module: :class:`str`
:returns: the joined name
:rtype: :class:`str`
:raises: :class:`AssertionError`, if both package and module are empty
"""
# Both package and module can be None/empty.
assert package or module, "Specify either package or module"
if package:
name = package
if module:
name += '.' + module
else:
name = module
return name
def write_file(app, name, text, dest, suffix, dryrun, force):
"""Write the output file for module/package <name>.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param name: the file name without file extension
:type name: :class:`str`
:param text: the content of the file
:type text: :class:`str`
:param dest: the output directory
:type dest: :class:`str`
:param suffix: the file extension
:type suffix: :class:`str`
:param dryrun: If True, do not create any files, just log the potential location.
:type dryrun: :class:`bool`
:param force: Overwrite existing files
:type force: :class:`bool`
:returns: None
:raises: None
"""
fname = os.path.join(dest, '%s.%s' % (name, suffix))
if dryrun:
logger.info('Would create file %s.' % fname)
return
if not force and os.path.isfile(fname):
logger.info('File %s already exists, skipping.' % fname)
else:
logger.info('Creating file %s.' % fname)
f = open(fname, 'w')
try:
f.write(text)
relpath = os.path.relpath(fname, start=app.env.srcdir)
abspath = os.sep + relpath
docpath = app.env.relfn2path(abspath)[0]
docpath = docpath.rsplit(os.path.extsep, 1)[0]
logger.debug('Adding document %s' % docpath)
app.env.found_docs.add(docpath)
finally:
f.close()
def import_name(app, name):
"""Import the given name and return name, obj, parent, mod_name
:param name: name to import
:type name: str
:returns: the imported object or None
:rtype: object | None
:raises: None
"""
try:
logger.debug('Importing %r', name)
name, obj = autosummary.import_by_name(name)[:2]
logger.debug('Imported %s', obj)
return obj
except ImportError as e:
logger.warn("Jinjapidoc failed to import %r: %s", name, e)
def get_members(app, mod, typ, include_public=None):
"""Return the members of mod of the given type
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param mod: the module with members
:type mod: module
:param typ: the typ, ``'class'``, ``'function'``, ``'exception'``, ``'data'``, ``'members'``
:type typ: str
:param include_public: list of private members to include to publics
:type include_public: list | None
:returns: None
:rtype: None
:raises: None
"""
def include_here(x):
"""Return true if the member should be included in mod.
A member will be included if it is declared in this module or package.
If the `jinjaapidoc_include_from_all` option is `True` then the member
can also be included if it is listed in `__all__`.
:param x: The member
:type x: A class, exception, or function.
:returns: True if the member should be included in mod. False otherwise.
:rtype: bool
"""
return (x.__module__ == mod.__name__ or (include_from_all and x.__name__ in all_list))
all_list = getattr(mod, '__all__', [])
include_from_all = app.config.jinjaapi_include_from_all
include_public = include_public or []
tests = {'class': lambda x: inspect.isclass(x) and not issubclass(x, BaseException) and include_here(x),
'function': lambda x: inspect.isfunction(x) and include_here(x),
'exception': lambda x: inspect.isclass(x) and issubclass(x, BaseException) and include_here(x),
'data': lambda x: not inspect.ismodule(x) and not inspect.isclass(x) and not inspect.isfunction(x),
'members': lambda x: True}
items = []
for name in dir(mod):
i = getattr(mod, name)
inspect.ismodule(i)
if tests.get(typ, lambda x: False)(i):
items.append(name)
public = [x for x in items
if x in include_public or not x.startswith('_')]
logger.debug('Got members of %s of type %s: public %s and %s', mod, typ, public, items)
return public, items
def _get_submodules(app, module):
"""Get all submodules for the given module/package
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param module: the module to query or module path
:type module: module | str
:returns: list of module names and boolean whether its a package
:rtype: list
:raises: TypeError
"""
if inspect.ismodule(module):
if hasattr(module, '__path__'):
p = module.__path__
else:
return []
elif isinstance(module, str):
p = module
else:
raise TypeError("Only Module or String accepted. %s given." % type(module))
logger.debug('Getting submodules of %s', p)
submodules = [(name, ispkg) for loader, name, ispkg in pkgutil.iter_modules(p)]
logger.debug('Found submodules of %s: %s', module, submodules)
return submodules
def get_submodules(app, module):
"""Get all submodules without packages for the given module/package
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param module: the module to query or module path
:type module: module | str
:returns: list of module names excluding packages
:rtype: list
:raises: TypeError
"""
submodules = _get_submodules(app, module)
return [name for name, ispkg in submodules if not ispkg]
def get_subpackages(app, module):
"""Get all subpackages for the given module/package
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param module: the module to query or module path
:type module: module | str
:returns: list of packages names
:rtype: list
:raises: TypeError
"""
submodules = _get_submodules(app, module)
return [name for name, ispkg in submodules if ispkg]
def get_context(app, package, module, fullname):
"""Return a dict for template rendering
Variables:
* :package: The top package
* :module: the module
* :fullname: package.module
* :subpkgs: packages beneath module
* :submods: modules beneath module
* :classes: public classes in module
* :allclasses: public and private classes in module
* :exceptions: public exceptions in module
* :allexceptions: public and private exceptions in module
* :functions: public functions in module
* :allfunctions: public and private functions in module
* :data: public data in module
* :alldata: public and private data in module
* :members: dir(module)
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param package: the parent package name
:type package: str
:param module: the module name
:type module: str
:param fullname: package.module
:type fullname: str
:returns: a dict with variables for template rendering
:rtype: :class:`dict`
:raises: None
"""
var = {'package': package,
'module': module,
'fullname': fullname}
logger.debug('Creating context for: package %s, module %s, fullname %s', package, module, fullname)
obj = import_name(app, fullname)
if not obj:
for k in ('subpkgs', 'submods', 'classes', 'allclasses',
'exceptions', 'allexceptions', 'functions', 'allfunctions',
'data', 'alldata', 'memebers'):
var[k] = []
return var
var['subpkgs'] = get_subpackages(app, obj)
var['submods'] = get_submodules(app, obj)
var['classes'], var['allclasses'] = get_members(app, obj, 'class')
var['exceptions'], var['allexceptions'] = get_members(app, obj, 'exception')
var['functions'], var['allfunctions'] = get_members(app, obj, 'function')
var['data'], var['alldata'] = get_members(app, obj, 'data')
var['members'] = get_members(app, obj, 'members')
logger.debug('Created context: %s', var)
return var
def create_package_file(app, env, root_package, sub_package, private,
dest, suffix, dryrun, force):
"""Build the text of the file and write the file.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param env: the jinja environment for the templates
:type env: :class:`jinja2.Environment`
:param root_package: the parent package
:type root_package: :class:`str`
:param sub_package: the package name without root
:type sub_package: :class:`str`
:param private: Include \"_private\" modules
:type private: :class:`bool`
:param dest: the output directory
:type dest: :class:`str`
:param suffix: the file extension
:type suffix: :class:`str`
:param dryrun: If True, do not create any files, just log the potential location.
:type dryrun: :class:`bool`
:param force: Overwrite existing files
:type force: :class:`bool`
:returns: None
:raises: None
"""
logger.debug('Create package file: rootpackage %s, sub_package %s', root_package, sub_package)
template_file = PACKAGE_TEMPLATE_NAME
template = env.get_template(template_file)
fn = makename(root_package, sub_package)
var = get_context(app, root_package, sub_package, fn)
var['ispkg'] = True
for submod in var['submods']:
if shall_skip(app, submod, private):
continue
create_module_file(app, env, fn, submod, dest, suffix, dryrun, force)
rendered = template.render(var)
write_file(app, fn, rendered, dest, suffix, dryrun, force)
def shall_skip(app, module, private):
"""Check if we want to skip this module.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param module: the module name
:type module: :class:`str`
:param private: True, if privates are allowed
:type private: :class:`bool`
"""
logger.debug('Testing if %s should be skipped.', module)
# skip if it has a "private" name and this is selected
if module != '__init__.py' and module.startswith('_') and \
not private:
logger.debug('Skip %s because its either private or __init__.', module)
return True
logger.debug('Do not skip %s', module)
return False
def recurse_tree(app, env, src, dest, excludes, followlinks, force, dryrun, private, suffix):
"""Look for every file in the directory tree and create the corresponding
ReST files.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param env: the jinja environment
:type env: :class:`jinja2.Environment`
:param src: the path to the python source files
:type src: :class:`str`
:param dest: the output directory
:type dest: :class:`str`
:param excludes: the paths to exclude
:type excludes: :class:`list`
:param followlinks: follow symbolic links
:type followlinks: :class:`bool`
:param force: overwrite existing files
:type force: :class:`bool`
:param dryrun: do not generate files
:type dryrun: :class:`bool`
:param private: include "_private" modules
:type private: :class:`bool`
:param suffix: the file extension
:type suffix: :class:`str`
"""
# check if the base directory is a package and get its name
if INITPY in os.listdir(src):
root_package = src.split(os.path.sep)[-1]
else:
# otherwise, the base is a directory with packages
root_package = None
toplevels = []
for root, subs, files in walk(src, followlinks=followlinks):
# document only Python module files (that aren't excluded)
py_files = sorted(f for f in files
if os.path.splitext(f)[1] in PY_SUFFIXES and # noqa: W504
not is_excluded(os.path.join(root, f), excludes))
is_pkg = INITPY in py_files
if is_pkg:
py_files.remove(INITPY)
py_files.insert(0, INITPY)
elif root != src:
# only accept non-package at toplevel
del subs[:]
continue
# remove hidden ('.') and private ('_') directories, as well as
# excluded dirs
if private:
exclude_prefixes = ('.',)
else:
exclude_prefixes = ('.', '_')
subs[:] = sorted(sub for sub in subs if not sub.startswith(exclude_prefixes) and not
is_excluded(os.path.join(root, sub), excludes))
if is_pkg:
# we are in a package with something to document
if subs or len(py_files) > 1 or not \
shall_skip(app, os.path.join(root, INITPY), private):
subpackage = root[len(src):].lstrip(os.path.sep).\
replace(os.path.sep, '.')
create_package_file(app, env, root_package, subpackage,
private, dest, suffix, dryrun, force)
toplevels.append(makename(root_package, subpackage))
else:
# if we are at the root level, we don't require it to be a package
assert root == src and root_package is None
for py_file in py_files:
if not shall_skip(app, os.path.join(src, py_file), private):
module = os.path.splitext(py_file)[0]
create_module_file(app, env, root_package, module, dest, suffix, dryrun, force)
toplevels.append(module)
return toplevels
def normalize_excludes(excludes):
"""Normalize the excluded directory list."""
return [os.path.normpath(os.path.abspath(exclude)) for exclude in excludes]
def is_excluded(root, excludes):
"""Check if the directory is in the exclude list.
Note: by having trailing slashes, we avoid common prefix issues, like
e.g. an exlude "foo" also accidentally excluding "foobar".
"""
root = os.path.normpath(root)
for exclude in excludes:
if root == exclude:
return True
return False
def generate(app, src, dest, exclude=[], followlinks=False,
force=False, dryrun=False, private=False, suffix='rst',
template_dirs=None):
"""Generage the rst files
Raises an :class:`OSError` if the source path is not a directory.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param src: path to python source files
:type src: :class:`str`
:param dest: output directory
:type dest: :class:`str`
:param exclude: list of paths to exclude
:type exclude: :class:`list`
:param followlinks: follow symbolic links
:type followlinks: :class:`bool`
:param force: overwrite existing files
:type force: :class:`bool`
:param dryrun: do not create any files
:type dryrun: :class:`bool`
:param private: include \"_private\" modules
:type private: :class:`bool`
:param suffix: file suffix
:type suffix: :class:`str`
:param template_dirs: directories to search for user templates
:type template_dirs: None | :class:`list`
:returns: None
:rtype: None
:raises: OSError
"""
suffix = suffix.strip('.')
if not os.path.isdir(src):
raise OSError("%s is not a directory" % src)
if not os.path.isdir(dest) and not dryrun:
os.makedirs(dest)
src = os.path.normpath(os.path.abspath(src))
exclude = normalize_excludes(exclude)
loader = make_loader(template_dirs)
env = make_environment(loader)
recurse_tree(app, env, src, dest, exclude, followlinks, force, dryrun, private, suffix)
def main(app):
"""Parse the config of the app and initiate the generation process
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:returns: None
:rtype: None
:raises: None
"""
c = app.config
src = c.jinjaapi_srcdir
if not src:
return
suffix = "rst"
out = c.jinjaapi_outputdir or app.env.srcdir
if c.jinjaapi_addsummarytemplate:
tpath = pkg_resources.resource_filename(__package__, AUTOSUMMARYTEMPLATE_DIR)
c.templates_path.append(tpath)
tpath = pkg_resources.resource_filename(__package__, TEMPLATE_DIR)
c.templates_path.append(tpath)
prepare_dir(app, out, not c.jinjaapi_nodelete)
generate(app, src, out,
exclude=c.jinjaapi_exclude_paths,
force=c.jinjaapi_force,
followlinks=c.jinjaapi_followlinks,
dryrun=c.jinjaapi_dryrun,
private=c.jinjaapi_includeprivate,
suffix=suffix,
template_dirs=c.templates_path)
|
storax/jinjaapidoc
|
src/jinjaapidoc/gendoc.py
|
create_package_file
|
python
|
def create_package_file(app, env, root_package, sub_package, private,
dest, suffix, dryrun, force):
logger.debug('Create package file: rootpackage %s, sub_package %s', root_package, sub_package)
template_file = PACKAGE_TEMPLATE_NAME
template = env.get_template(template_file)
fn = makename(root_package, sub_package)
var = get_context(app, root_package, sub_package, fn)
var['ispkg'] = True
for submod in var['submods']:
if shall_skip(app, submod, private):
continue
create_module_file(app, env, fn, submod, dest, suffix, dryrun, force)
rendered = template.render(var)
write_file(app, fn, rendered, dest, suffix, dryrun, force)
|
Build the text of the file and write the file.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param env: the jinja environment for the templates
:type env: :class:`jinja2.Environment`
:param root_package: the parent package
:type root_package: :class:`str`
:param sub_package: the package name without root
:type sub_package: :class:`str`
:param private: Include \"_private\" modules
:type private: :class:`bool`
:param dest: the output directory
:type dest: :class:`str`
:param suffix: the file extension
:type suffix: :class:`str`
:param dryrun: If True, do not create any files, just log the potential location.
:type dryrun: :class:`bool`
:param force: Overwrite existing files
:type force: :class:`bool`
:returns: None
:raises: None
|
train
|
https://github.com/storax/jinjaapidoc/blob/f1eeb6ab5bd1a96c4130306718c6423f37c76856/src/jinjaapidoc/gendoc.py#L365-L401
|
[
"def get_context(app, package, module, fullname):\n \"\"\"Return a dict for template rendering\n\n Variables:\n\n * :package: The top package\n * :module: the module\n * :fullname: package.module\n * :subpkgs: packages beneath module\n * :submods: modules beneath module\n * :classes: public classes in module\n * :allclasses: public and private classes in module\n * :exceptions: public exceptions in module\n * :allexceptions: public and private exceptions in module\n * :functions: public functions in module\n * :allfunctions: public and private functions in module\n * :data: public data in module\n * :alldata: public and private data in module\n * :members: dir(module)\n\n\n :param app: the sphinx app\n :type app: :class:`sphinx.application.Sphinx`\n :param package: the parent package name\n :type package: str\n :param module: the module name\n :type module: str\n :param fullname: package.module\n :type fullname: str\n :returns: a dict with variables for template rendering\n :rtype: :class:`dict`\n :raises: None\n \"\"\"\n var = {'package': package,\n 'module': module,\n 'fullname': fullname}\n logger.debug('Creating context for: package %s, module %s, fullname %s', package, module, fullname)\n obj = import_name(app, fullname)\n if not obj:\n for k in ('subpkgs', 'submods', 'classes', 'allclasses',\n 'exceptions', 'allexceptions', 'functions', 'allfunctions',\n 'data', 'alldata', 'memebers'):\n var[k] = []\n return var\n\n var['subpkgs'] = get_subpackages(app, obj)\n var['submods'] = get_submodules(app, obj)\n var['classes'], var['allclasses'] = get_members(app, obj, 'class')\n var['exceptions'], var['allexceptions'] = get_members(app, obj, 'exception')\n var['functions'], var['allfunctions'] = get_members(app, obj, 'function')\n var['data'], var['alldata'] = get_members(app, obj, 'data')\n var['members'] = get_members(app, obj, 'members')\n logger.debug('Created context: %s', var)\n return var\n",
"def write_file(app, name, text, dest, suffix, dryrun, force):\n \"\"\"Write the output file for module/package <name>.\n\n :param app: the sphinx app\n :type app: :class:`sphinx.application.Sphinx`\n :param name: the file name without file extension\n :type name: :class:`str`\n :param text: the content of the file\n :type text: :class:`str`\n :param dest: the output directory\n :type dest: :class:`str`\n :param suffix: the file extension\n :type suffix: :class:`str`\n :param dryrun: If True, do not create any files, just log the potential location.\n :type dryrun: :class:`bool`\n :param force: Overwrite existing files\n :type force: :class:`bool`\n :returns: None\n :raises: None\n \"\"\"\n fname = os.path.join(dest, '%s.%s' % (name, suffix))\n if dryrun:\n logger.info('Would create file %s.' % fname)\n return\n if not force and os.path.isfile(fname):\n logger.info('File %s already exists, skipping.' % fname)\n else:\n logger.info('Creating file %s.' % fname)\n f = open(fname, 'w')\n try:\n f.write(text)\n relpath = os.path.relpath(fname, start=app.env.srcdir)\n abspath = os.sep + relpath\n docpath = app.env.relfn2path(abspath)[0]\n docpath = docpath.rsplit(os.path.extsep, 1)[0]\n logger.debug('Adding document %s' % docpath)\n app.env.found_docs.add(docpath)\n finally:\n f.close()\n",
"def makename(package, module):\n \"\"\"Join package and module with a dot.\n\n Package or Module can be empty.\n\n :param package: the package name\n :type package: :class:`str`\n :param module: the module name\n :type module: :class:`str`\n :returns: the joined name\n :rtype: :class:`str`\n :raises: :class:`AssertionError`, if both package and module are empty\n \"\"\"\n # Both package and module can be None/empty.\n assert package or module, \"Specify either package or module\"\n if package:\n name = package\n if module:\n name += '.' + module\n else:\n name = module\n return name\n",
"def create_module_file(app, env, package, module, dest, suffix, dryrun, force):\n \"\"\"Build the text of the file and write the file.\n\n :param app: the sphinx app\n :type app: :class:`sphinx.application.Sphinx`\n :param env: the jinja environment for the templates\n :type env: :class:`jinja2.Environment`\n :param package: the package name\n :type package: :class:`str`\n :param module: the module name\n :type module: :class:`str`\n :param dest: the output directory\n :type dest: :class:`str`\n :param suffix: the file extension\n :type suffix: :class:`str`\n :param dryrun: If True, do not create any files, just log the potential location.\n :type dryrun: :class:`bool`\n :param force: Overwrite existing files\n :type force: :class:`bool`\n :returns: None\n :raises: None\n \"\"\"\n logger.debug('Create module file: package %s, module %s', package, module)\n template_file = MODULE_TEMPLATE_NAME\n template = env.get_template(template_file)\n fn = makename(package, module)\n var = get_context(app, package, module, fn)\n var['ispkg'] = False\n rendered = template.render(var)\n write_file(app, makename(package, module), rendered, dest, suffix, dryrun, force)\n",
"def shall_skip(app, module, private):\n \"\"\"Check if we want to skip this module.\n\n :param app: the sphinx app\n :type app: :class:`sphinx.application.Sphinx`\n :param module: the module name\n :type module: :class:`str`\n :param private: True, if privates are allowed\n :type private: :class:`bool`\n \"\"\"\n logger.debug('Testing if %s should be skipped.', module)\n # skip if it has a \"private\" name and this is selected\n if module != '__init__.py' and module.startswith('_') and \\\n not private:\n logger.debug('Skip %s because its either private or __init__.', module)\n return True\n logger.debug('Do not skip %s', module)\n return False\n"
] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""This is a modification of sphinx.apidoc by David.Zuber.
It uses jinja templates to render the rst files.
Parses a directory tree looking for Python modules and packages and creates
ReST files appropriately to create code documentation with Sphinx.
This is derived form the "sphinx-apidoc" script, which is:
Copyright 2007-2014 by the Sphinx team, see http://sphinx-doc.org/latest/authors.html.
"""
import os
import inspect
import pkgutil
import pkg_resources
import shutil
import jinja2
from sphinx.util.osutil import walk
from sphinx.util import logging
from sphinx.ext import autosummary
logger = logging.getLogger(__name__)
INITPY = '__init__.py'
PY_SUFFIXES = set(['.py', '.pyx'])
TEMPLATE_DIR = 'templates'
"""Built-in template dir for jinjaapi rendering"""
AUTOSUMMARYTEMPLATE_DIR = 'autosummarytemplates'
"""Templates for autosummary"""
MODULE_TEMPLATE_NAME = 'jinjaapi_module.rst'
"""Name of the template that is used for rendering modules."""
PACKAGE_TEMPLATE_NAME = 'jinjaapi_package.rst'
"""Name of the template that is used for rendering packages."""
def prepare_dir(app, directory, delete=False):
"""Create apidoc dir, delete contents if delete is True.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param directory: the apidoc directory. you can use relative paths here
:type directory: str
:param delete: if True, deletes the contents of apidoc. This acts like an override switch.
:type delete: bool
:returns: None
:rtype: None
:raises: None
"""
logger.info("Preparing output directories for jinjaapidoc.")
if os.path.exists(directory):
if delete:
logger.debug("Deleting dir %s", directory)
shutil.rmtree(directory)
logger.debug("Creating dir %s", directory)
os.mkdir(directory)
else:
logger.debug("Creating %s", directory)
os.mkdir(directory)
def make_loader(template_dirs):
"""Return a new :class:`jinja2.FileSystemLoader` that uses the template_dirs
:param template_dirs: directories to search for templates
:type template_dirs: None | :class:`list`
:returns: a new loader
:rtype: :class:`jinja2.FileSystemLoader`
:raises: None
"""
return jinja2.FileSystemLoader(searchpath=template_dirs)
def make_environment(loader):
"""Return a new :class:`jinja2.Environment` with the given loader
:param loader: a jinja2 loader
:type loader: :class:`jinja2.BaseLoader`
:returns: a new environment
:rtype: :class:`jinja2.Environment`
:raises: None
"""
return jinja2.Environment(loader=loader)
def makename(package, module):
"""Join package and module with a dot.
Package or Module can be empty.
:param package: the package name
:type package: :class:`str`
:param module: the module name
:type module: :class:`str`
:returns: the joined name
:rtype: :class:`str`
:raises: :class:`AssertionError`, if both package and module are empty
"""
# Both package and module can be None/empty.
assert package or module, "Specify either package or module"
if package:
name = package
if module:
name += '.' + module
else:
name = module
return name
def write_file(app, name, text, dest, suffix, dryrun, force):
"""Write the output file for module/package <name>.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param name: the file name without file extension
:type name: :class:`str`
:param text: the content of the file
:type text: :class:`str`
:param dest: the output directory
:type dest: :class:`str`
:param suffix: the file extension
:type suffix: :class:`str`
:param dryrun: If True, do not create any files, just log the potential location.
:type dryrun: :class:`bool`
:param force: Overwrite existing files
:type force: :class:`bool`
:returns: None
:raises: None
"""
fname = os.path.join(dest, '%s.%s' % (name, suffix))
if dryrun:
logger.info('Would create file %s.' % fname)
return
if not force and os.path.isfile(fname):
logger.info('File %s already exists, skipping.' % fname)
else:
logger.info('Creating file %s.' % fname)
f = open(fname, 'w')
try:
f.write(text)
relpath = os.path.relpath(fname, start=app.env.srcdir)
abspath = os.sep + relpath
docpath = app.env.relfn2path(abspath)[0]
docpath = docpath.rsplit(os.path.extsep, 1)[0]
logger.debug('Adding document %s' % docpath)
app.env.found_docs.add(docpath)
finally:
f.close()
def import_name(app, name):
"""Import the given name and return name, obj, parent, mod_name
:param name: name to import
:type name: str
:returns: the imported object or None
:rtype: object | None
:raises: None
"""
try:
logger.debug('Importing %r', name)
name, obj = autosummary.import_by_name(name)[:2]
logger.debug('Imported %s', obj)
return obj
except ImportError as e:
logger.warn("Jinjapidoc failed to import %r: %s", name, e)
def get_members(app, mod, typ, include_public=None):
"""Return the members of mod of the given type
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param mod: the module with members
:type mod: module
:param typ: the typ, ``'class'``, ``'function'``, ``'exception'``, ``'data'``, ``'members'``
:type typ: str
:param include_public: list of private members to include to publics
:type include_public: list | None
:returns: None
:rtype: None
:raises: None
"""
def include_here(x):
"""Return true if the member should be included in mod.
A member will be included if it is declared in this module or package.
If the `jinjaapidoc_include_from_all` option is `True` then the member
can also be included if it is listed in `__all__`.
:param x: The member
:type x: A class, exception, or function.
:returns: True if the member should be included in mod. False otherwise.
:rtype: bool
"""
return (x.__module__ == mod.__name__ or (include_from_all and x.__name__ in all_list))
all_list = getattr(mod, '__all__', [])
include_from_all = app.config.jinjaapi_include_from_all
include_public = include_public or []
tests = {'class': lambda x: inspect.isclass(x) and not issubclass(x, BaseException) and include_here(x),
'function': lambda x: inspect.isfunction(x) and include_here(x),
'exception': lambda x: inspect.isclass(x) and issubclass(x, BaseException) and include_here(x),
'data': lambda x: not inspect.ismodule(x) and not inspect.isclass(x) and not inspect.isfunction(x),
'members': lambda x: True}
items = []
for name in dir(mod):
i = getattr(mod, name)
inspect.ismodule(i)
if tests.get(typ, lambda x: False)(i):
items.append(name)
public = [x for x in items
if x in include_public or not x.startswith('_')]
logger.debug('Got members of %s of type %s: public %s and %s', mod, typ, public, items)
return public, items
def _get_submodules(app, module):
"""Get all submodules for the given module/package
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param module: the module to query or module path
:type module: module | str
:returns: list of module names and boolean whether its a package
:rtype: list
:raises: TypeError
"""
if inspect.ismodule(module):
if hasattr(module, '__path__'):
p = module.__path__
else:
return []
elif isinstance(module, str):
p = module
else:
raise TypeError("Only Module or String accepted. %s given." % type(module))
logger.debug('Getting submodules of %s', p)
submodules = [(name, ispkg) for loader, name, ispkg in pkgutil.iter_modules(p)]
logger.debug('Found submodules of %s: %s', module, submodules)
return submodules
def get_submodules(app, module):
"""Get all submodules without packages for the given module/package
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param module: the module to query or module path
:type module: module | str
:returns: list of module names excluding packages
:rtype: list
:raises: TypeError
"""
submodules = _get_submodules(app, module)
return [name for name, ispkg in submodules if not ispkg]
def get_subpackages(app, module):
"""Get all subpackages for the given module/package
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param module: the module to query or module path
:type module: module | str
:returns: list of packages names
:rtype: list
:raises: TypeError
"""
submodules = _get_submodules(app, module)
return [name for name, ispkg in submodules if ispkg]
def get_context(app, package, module, fullname):
"""Return a dict for template rendering
Variables:
* :package: The top package
* :module: the module
* :fullname: package.module
* :subpkgs: packages beneath module
* :submods: modules beneath module
* :classes: public classes in module
* :allclasses: public and private classes in module
* :exceptions: public exceptions in module
* :allexceptions: public and private exceptions in module
* :functions: public functions in module
* :allfunctions: public and private functions in module
* :data: public data in module
* :alldata: public and private data in module
* :members: dir(module)
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param package: the parent package name
:type package: str
:param module: the module name
:type module: str
:param fullname: package.module
:type fullname: str
:returns: a dict with variables for template rendering
:rtype: :class:`dict`
:raises: None
"""
var = {'package': package,
'module': module,
'fullname': fullname}
logger.debug('Creating context for: package %s, module %s, fullname %s', package, module, fullname)
obj = import_name(app, fullname)
if not obj:
for k in ('subpkgs', 'submods', 'classes', 'allclasses',
'exceptions', 'allexceptions', 'functions', 'allfunctions',
'data', 'alldata', 'memebers'):
var[k] = []
return var
var['subpkgs'] = get_subpackages(app, obj)
var['submods'] = get_submodules(app, obj)
var['classes'], var['allclasses'] = get_members(app, obj, 'class')
var['exceptions'], var['allexceptions'] = get_members(app, obj, 'exception')
var['functions'], var['allfunctions'] = get_members(app, obj, 'function')
var['data'], var['alldata'] = get_members(app, obj, 'data')
var['members'] = get_members(app, obj, 'members')
logger.debug('Created context: %s', var)
return var
def create_module_file(app, env, package, module, dest, suffix, dryrun, force):
"""Build the text of the file and write the file.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param env: the jinja environment for the templates
:type env: :class:`jinja2.Environment`
:param package: the package name
:type package: :class:`str`
:param module: the module name
:type module: :class:`str`
:param dest: the output directory
:type dest: :class:`str`
:param suffix: the file extension
:type suffix: :class:`str`
:param dryrun: If True, do not create any files, just log the potential location.
:type dryrun: :class:`bool`
:param force: Overwrite existing files
:type force: :class:`bool`
:returns: None
:raises: None
"""
logger.debug('Create module file: package %s, module %s', package, module)
template_file = MODULE_TEMPLATE_NAME
template = env.get_template(template_file)
fn = makename(package, module)
var = get_context(app, package, module, fn)
var['ispkg'] = False
rendered = template.render(var)
write_file(app, makename(package, module), rendered, dest, suffix, dryrun, force)
def shall_skip(app, module, private):
"""Check if we want to skip this module.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param module: the module name
:type module: :class:`str`
:param private: True, if privates are allowed
:type private: :class:`bool`
"""
logger.debug('Testing if %s should be skipped.', module)
# skip if it has a "private" name and this is selected
if module != '__init__.py' and module.startswith('_') and \
not private:
logger.debug('Skip %s because its either private or __init__.', module)
return True
logger.debug('Do not skip %s', module)
return False
def recurse_tree(app, env, src, dest, excludes, followlinks, force, dryrun, private, suffix):
"""Look for every file in the directory tree and create the corresponding
ReST files.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param env: the jinja environment
:type env: :class:`jinja2.Environment`
:param src: the path to the python source files
:type src: :class:`str`
:param dest: the output directory
:type dest: :class:`str`
:param excludes: the paths to exclude
:type excludes: :class:`list`
:param followlinks: follow symbolic links
:type followlinks: :class:`bool`
:param force: overwrite existing files
:type force: :class:`bool`
:param dryrun: do not generate files
:type dryrun: :class:`bool`
:param private: include "_private" modules
:type private: :class:`bool`
:param suffix: the file extension
:type suffix: :class:`str`
"""
# check if the base directory is a package and get its name
if INITPY in os.listdir(src):
root_package = src.split(os.path.sep)[-1]
else:
# otherwise, the base is a directory with packages
root_package = None
toplevels = []
for root, subs, files in walk(src, followlinks=followlinks):
# document only Python module files (that aren't excluded)
py_files = sorted(f for f in files
if os.path.splitext(f)[1] in PY_SUFFIXES and # noqa: W504
not is_excluded(os.path.join(root, f), excludes))
is_pkg = INITPY in py_files
if is_pkg:
py_files.remove(INITPY)
py_files.insert(0, INITPY)
elif root != src:
# only accept non-package at toplevel
del subs[:]
continue
# remove hidden ('.') and private ('_') directories, as well as
# excluded dirs
if private:
exclude_prefixes = ('.',)
else:
exclude_prefixes = ('.', '_')
subs[:] = sorted(sub for sub in subs if not sub.startswith(exclude_prefixes) and not
is_excluded(os.path.join(root, sub), excludes))
if is_pkg:
# we are in a package with something to document
if subs or len(py_files) > 1 or not \
shall_skip(app, os.path.join(root, INITPY), private):
subpackage = root[len(src):].lstrip(os.path.sep).\
replace(os.path.sep, '.')
create_package_file(app, env, root_package, subpackage,
private, dest, suffix, dryrun, force)
toplevels.append(makename(root_package, subpackage))
else:
# if we are at the root level, we don't require it to be a package
assert root == src and root_package is None
for py_file in py_files:
if not shall_skip(app, os.path.join(src, py_file), private):
module = os.path.splitext(py_file)[0]
create_module_file(app, env, root_package, module, dest, suffix, dryrun, force)
toplevels.append(module)
return toplevels
def normalize_excludes(excludes):
"""Normalize the excluded directory list."""
return [os.path.normpath(os.path.abspath(exclude)) for exclude in excludes]
def is_excluded(root, excludes):
"""Check if the directory is in the exclude list.
Note: by having trailing slashes, we avoid common prefix issues, like
e.g. an exlude "foo" also accidentally excluding "foobar".
"""
root = os.path.normpath(root)
for exclude in excludes:
if root == exclude:
return True
return False
def generate(app, src, dest, exclude=[], followlinks=False,
force=False, dryrun=False, private=False, suffix='rst',
template_dirs=None):
"""Generage the rst files
Raises an :class:`OSError` if the source path is not a directory.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param src: path to python source files
:type src: :class:`str`
:param dest: output directory
:type dest: :class:`str`
:param exclude: list of paths to exclude
:type exclude: :class:`list`
:param followlinks: follow symbolic links
:type followlinks: :class:`bool`
:param force: overwrite existing files
:type force: :class:`bool`
:param dryrun: do not create any files
:type dryrun: :class:`bool`
:param private: include \"_private\" modules
:type private: :class:`bool`
:param suffix: file suffix
:type suffix: :class:`str`
:param template_dirs: directories to search for user templates
:type template_dirs: None | :class:`list`
:returns: None
:rtype: None
:raises: OSError
"""
suffix = suffix.strip('.')
if not os.path.isdir(src):
raise OSError("%s is not a directory" % src)
if not os.path.isdir(dest) and not dryrun:
os.makedirs(dest)
src = os.path.normpath(os.path.abspath(src))
exclude = normalize_excludes(exclude)
loader = make_loader(template_dirs)
env = make_environment(loader)
recurse_tree(app, env, src, dest, exclude, followlinks, force, dryrun, private, suffix)
def main(app):
"""Parse the config of the app and initiate the generation process
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:returns: None
:rtype: None
:raises: None
"""
c = app.config
src = c.jinjaapi_srcdir
if not src:
return
suffix = "rst"
out = c.jinjaapi_outputdir or app.env.srcdir
if c.jinjaapi_addsummarytemplate:
tpath = pkg_resources.resource_filename(__package__, AUTOSUMMARYTEMPLATE_DIR)
c.templates_path.append(tpath)
tpath = pkg_resources.resource_filename(__package__, TEMPLATE_DIR)
c.templates_path.append(tpath)
prepare_dir(app, out, not c.jinjaapi_nodelete)
generate(app, src, out,
exclude=c.jinjaapi_exclude_paths,
force=c.jinjaapi_force,
followlinks=c.jinjaapi_followlinks,
dryrun=c.jinjaapi_dryrun,
private=c.jinjaapi_includeprivate,
suffix=suffix,
template_dirs=c.templates_path)
|
storax/jinjaapidoc
|
src/jinjaapidoc/gendoc.py
|
shall_skip
|
python
|
def shall_skip(app, module, private):
logger.debug('Testing if %s should be skipped.', module)
# skip if it has a "private" name and this is selected
if module != '__init__.py' and module.startswith('_') and \
not private:
logger.debug('Skip %s because its either private or __init__.', module)
return True
logger.debug('Do not skip %s', module)
return False
|
Check if we want to skip this module.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param module: the module name
:type module: :class:`str`
:param private: True, if privates are allowed
:type private: :class:`bool`
|
train
|
https://github.com/storax/jinjaapidoc/blob/f1eeb6ab5bd1a96c4130306718c6423f37c76856/src/jinjaapidoc/gendoc.py#L404-L421
| null |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""This is a modification of sphinx.apidoc by David.Zuber.
It uses jinja templates to render the rst files.
Parses a directory tree looking for Python modules and packages and creates
ReST files appropriately to create code documentation with Sphinx.
This is derived form the "sphinx-apidoc" script, which is:
Copyright 2007-2014 by the Sphinx team, see http://sphinx-doc.org/latest/authors.html.
"""
import os
import inspect
import pkgutil
import pkg_resources
import shutil
import jinja2
from sphinx.util.osutil import walk
from sphinx.util import logging
from sphinx.ext import autosummary
logger = logging.getLogger(__name__)
INITPY = '__init__.py'
PY_SUFFIXES = set(['.py', '.pyx'])
TEMPLATE_DIR = 'templates'
"""Built-in template dir for jinjaapi rendering"""
AUTOSUMMARYTEMPLATE_DIR = 'autosummarytemplates'
"""Templates for autosummary"""
MODULE_TEMPLATE_NAME = 'jinjaapi_module.rst'
"""Name of the template that is used for rendering modules."""
PACKAGE_TEMPLATE_NAME = 'jinjaapi_package.rst'
"""Name of the template that is used for rendering packages."""
def prepare_dir(app, directory, delete=False):
"""Create apidoc dir, delete contents if delete is True.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param directory: the apidoc directory. you can use relative paths here
:type directory: str
:param delete: if True, deletes the contents of apidoc. This acts like an override switch.
:type delete: bool
:returns: None
:rtype: None
:raises: None
"""
logger.info("Preparing output directories for jinjaapidoc.")
if os.path.exists(directory):
if delete:
logger.debug("Deleting dir %s", directory)
shutil.rmtree(directory)
logger.debug("Creating dir %s", directory)
os.mkdir(directory)
else:
logger.debug("Creating %s", directory)
os.mkdir(directory)
def make_loader(template_dirs):
"""Return a new :class:`jinja2.FileSystemLoader` that uses the template_dirs
:param template_dirs: directories to search for templates
:type template_dirs: None | :class:`list`
:returns: a new loader
:rtype: :class:`jinja2.FileSystemLoader`
:raises: None
"""
return jinja2.FileSystemLoader(searchpath=template_dirs)
def make_environment(loader):
"""Return a new :class:`jinja2.Environment` with the given loader
:param loader: a jinja2 loader
:type loader: :class:`jinja2.BaseLoader`
:returns: a new environment
:rtype: :class:`jinja2.Environment`
:raises: None
"""
return jinja2.Environment(loader=loader)
def makename(package, module):
"""Join package and module with a dot.
Package or Module can be empty.
:param package: the package name
:type package: :class:`str`
:param module: the module name
:type module: :class:`str`
:returns: the joined name
:rtype: :class:`str`
:raises: :class:`AssertionError`, if both package and module are empty
"""
# Both package and module can be None/empty.
assert package or module, "Specify either package or module"
if package:
name = package
if module:
name += '.' + module
else:
name = module
return name
def write_file(app, name, text, dest, suffix, dryrun, force):
"""Write the output file for module/package <name>.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param name: the file name without file extension
:type name: :class:`str`
:param text: the content of the file
:type text: :class:`str`
:param dest: the output directory
:type dest: :class:`str`
:param suffix: the file extension
:type suffix: :class:`str`
:param dryrun: If True, do not create any files, just log the potential location.
:type dryrun: :class:`bool`
:param force: Overwrite existing files
:type force: :class:`bool`
:returns: None
:raises: None
"""
fname = os.path.join(dest, '%s.%s' % (name, suffix))
if dryrun:
logger.info('Would create file %s.' % fname)
return
if not force and os.path.isfile(fname):
logger.info('File %s already exists, skipping.' % fname)
else:
logger.info('Creating file %s.' % fname)
f = open(fname, 'w')
try:
f.write(text)
relpath = os.path.relpath(fname, start=app.env.srcdir)
abspath = os.sep + relpath
docpath = app.env.relfn2path(abspath)[0]
docpath = docpath.rsplit(os.path.extsep, 1)[0]
logger.debug('Adding document %s' % docpath)
app.env.found_docs.add(docpath)
finally:
f.close()
def import_name(app, name):
"""Import the given name and return name, obj, parent, mod_name
:param name: name to import
:type name: str
:returns: the imported object or None
:rtype: object | None
:raises: None
"""
try:
logger.debug('Importing %r', name)
name, obj = autosummary.import_by_name(name)[:2]
logger.debug('Imported %s', obj)
return obj
except ImportError as e:
logger.warn("Jinjapidoc failed to import %r: %s", name, e)
def get_members(app, mod, typ, include_public=None):
"""Return the members of mod of the given type
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param mod: the module with members
:type mod: module
:param typ: the typ, ``'class'``, ``'function'``, ``'exception'``, ``'data'``, ``'members'``
:type typ: str
:param include_public: list of private members to include to publics
:type include_public: list | None
:returns: None
:rtype: None
:raises: None
"""
def include_here(x):
"""Return true if the member should be included in mod.
A member will be included if it is declared in this module or package.
If the `jinjaapidoc_include_from_all` option is `True` then the member
can also be included if it is listed in `__all__`.
:param x: The member
:type x: A class, exception, or function.
:returns: True if the member should be included in mod. False otherwise.
:rtype: bool
"""
return (x.__module__ == mod.__name__ or (include_from_all and x.__name__ in all_list))
all_list = getattr(mod, '__all__', [])
include_from_all = app.config.jinjaapi_include_from_all
include_public = include_public or []
tests = {'class': lambda x: inspect.isclass(x) and not issubclass(x, BaseException) and include_here(x),
'function': lambda x: inspect.isfunction(x) and include_here(x),
'exception': lambda x: inspect.isclass(x) and issubclass(x, BaseException) and include_here(x),
'data': lambda x: not inspect.ismodule(x) and not inspect.isclass(x) and not inspect.isfunction(x),
'members': lambda x: True}
items = []
for name in dir(mod):
i = getattr(mod, name)
inspect.ismodule(i)
if tests.get(typ, lambda x: False)(i):
items.append(name)
public = [x for x in items
if x in include_public or not x.startswith('_')]
logger.debug('Got members of %s of type %s: public %s and %s', mod, typ, public, items)
return public, items
def _get_submodules(app, module):
"""Get all submodules for the given module/package
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param module: the module to query or module path
:type module: module | str
:returns: list of module names and boolean whether its a package
:rtype: list
:raises: TypeError
"""
if inspect.ismodule(module):
if hasattr(module, '__path__'):
p = module.__path__
else:
return []
elif isinstance(module, str):
p = module
else:
raise TypeError("Only Module or String accepted. %s given." % type(module))
logger.debug('Getting submodules of %s', p)
submodules = [(name, ispkg) for loader, name, ispkg in pkgutil.iter_modules(p)]
logger.debug('Found submodules of %s: %s', module, submodules)
return submodules
def get_submodules(app, module):
"""Get all submodules without packages for the given module/package
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param module: the module to query or module path
:type module: module | str
:returns: list of module names excluding packages
:rtype: list
:raises: TypeError
"""
submodules = _get_submodules(app, module)
return [name for name, ispkg in submodules if not ispkg]
def get_subpackages(app, module):
"""Get all subpackages for the given module/package
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param module: the module to query or module path
:type module: module | str
:returns: list of packages names
:rtype: list
:raises: TypeError
"""
submodules = _get_submodules(app, module)
return [name for name, ispkg in submodules if ispkg]
def get_context(app, package, module, fullname):
"""Return a dict for template rendering
Variables:
* :package: The top package
* :module: the module
* :fullname: package.module
* :subpkgs: packages beneath module
* :submods: modules beneath module
* :classes: public classes in module
* :allclasses: public and private classes in module
* :exceptions: public exceptions in module
* :allexceptions: public and private exceptions in module
* :functions: public functions in module
* :allfunctions: public and private functions in module
* :data: public data in module
* :alldata: public and private data in module
* :members: dir(module)
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param package: the parent package name
:type package: str
:param module: the module name
:type module: str
:param fullname: package.module
:type fullname: str
:returns: a dict with variables for template rendering
:rtype: :class:`dict`
:raises: None
"""
var = {'package': package,
'module': module,
'fullname': fullname}
logger.debug('Creating context for: package %s, module %s, fullname %s', package, module, fullname)
obj = import_name(app, fullname)
if not obj:
for k in ('subpkgs', 'submods', 'classes', 'allclasses',
'exceptions', 'allexceptions', 'functions', 'allfunctions',
'data', 'alldata', 'memebers'):
var[k] = []
return var
var['subpkgs'] = get_subpackages(app, obj)
var['submods'] = get_submodules(app, obj)
var['classes'], var['allclasses'] = get_members(app, obj, 'class')
var['exceptions'], var['allexceptions'] = get_members(app, obj, 'exception')
var['functions'], var['allfunctions'] = get_members(app, obj, 'function')
var['data'], var['alldata'] = get_members(app, obj, 'data')
var['members'] = get_members(app, obj, 'members')
logger.debug('Created context: %s', var)
return var
def create_module_file(app, env, package, module, dest, suffix, dryrun, force):
"""Build the text of the file and write the file.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param env: the jinja environment for the templates
:type env: :class:`jinja2.Environment`
:param package: the package name
:type package: :class:`str`
:param module: the module name
:type module: :class:`str`
:param dest: the output directory
:type dest: :class:`str`
:param suffix: the file extension
:type suffix: :class:`str`
:param dryrun: If True, do not create any files, just log the potential location.
:type dryrun: :class:`bool`
:param force: Overwrite existing files
:type force: :class:`bool`
:returns: None
:raises: None
"""
logger.debug('Create module file: package %s, module %s', package, module)
template_file = MODULE_TEMPLATE_NAME
template = env.get_template(template_file)
fn = makename(package, module)
var = get_context(app, package, module, fn)
var['ispkg'] = False
rendered = template.render(var)
write_file(app, makename(package, module), rendered, dest, suffix, dryrun, force)
def create_package_file(app, env, root_package, sub_package, private,
dest, suffix, dryrun, force):
"""Build the text of the file and write the file.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param env: the jinja environment for the templates
:type env: :class:`jinja2.Environment`
:param root_package: the parent package
:type root_package: :class:`str`
:param sub_package: the package name without root
:type sub_package: :class:`str`
:param private: Include \"_private\" modules
:type private: :class:`bool`
:param dest: the output directory
:type dest: :class:`str`
:param suffix: the file extension
:type suffix: :class:`str`
:param dryrun: If True, do not create any files, just log the potential location.
:type dryrun: :class:`bool`
:param force: Overwrite existing files
:type force: :class:`bool`
:returns: None
:raises: None
"""
logger.debug('Create package file: rootpackage %s, sub_package %s', root_package, sub_package)
template_file = PACKAGE_TEMPLATE_NAME
template = env.get_template(template_file)
fn = makename(root_package, sub_package)
var = get_context(app, root_package, sub_package, fn)
var['ispkg'] = True
for submod in var['submods']:
if shall_skip(app, submod, private):
continue
create_module_file(app, env, fn, submod, dest, suffix, dryrun, force)
rendered = template.render(var)
write_file(app, fn, rendered, dest, suffix, dryrun, force)
def recurse_tree(app, env, src, dest, excludes, followlinks, force, dryrun, private, suffix):
"""Look for every file in the directory tree and create the corresponding
ReST files.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param env: the jinja environment
:type env: :class:`jinja2.Environment`
:param src: the path to the python source files
:type src: :class:`str`
:param dest: the output directory
:type dest: :class:`str`
:param excludes: the paths to exclude
:type excludes: :class:`list`
:param followlinks: follow symbolic links
:type followlinks: :class:`bool`
:param force: overwrite existing files
:type force: :class:`bool`
:param dryrun: do not generate files
:type dryrun: :class:`bool`
:param private: include "_private" modules
:type private: :class:`bool`
:param suffix: the file extension
:type suffix: :class:`str`
"""
# check if the base directory is a package and get its name
if INITPY in os.listdir(src):
root_package = src.split(os.path.sep)[-1]
else:
# otherwise, the base is a directory with packages
root_package = None
toplevels = []
for root, subs, files in walk(src, followlinks=followlinks):
# document only Python module files (that aren't excluded)
py_files = sorted(f for f in files
if os.path.splitext(f)[1] in PY_SUFFIXES and # noqa: W504
not is_excluded(os.path.join(root, f), excludes))
is_pkg = INITPY in py_files
if is_pkg:
py_files.remove(INITPY)
py_files.insert(0, INITPY)
elif root != src:
# only accept non-package at toplevel
del subs[:]
continue
# remove hidden ('.') and private ('_') directories, as well as
# excluded dirs
if private:
exclude_prefixes = ('.',)
else:
exclude_prefixes = ('.', '_')
subs[:] = sorted(sub for sub in subs if not sub.startswith(exclude_prefixes) and not
is_excluded(os.path.join(root, sub), excludes))
if is_pkg:
# we are in a package with something to document
if subs or len(py_files) > 1 or not \
shall_skip(app, os.path.join(root, INITPY), private):
subpackage = root[len(src):].lstrip(os.path.sep).\
replace(os.path.sep, '.')
create_package_file(app, env, root_package, subpackage,
private, dest, suffix, dryrun, force)
toplevels.append(makename(root_package, subpackage))
else:
# if we are at the root level, we don't require it to be a package
assert root == src and root_package is None
for py_file in py_files:
if not shall_skip(app, os.path.join(src, py_file), private):
module = os.path.splitext(py_file)[0]
create_module_file(app, env, root_package, module, dest, suffix, dryrun, force)
toplevels.append(module)
return toplevels
def normalize_excludes(excludes):
"""Normalize the excluded directory list."""
return [os.path.normpath(os.path.abspath(exclude)) for exclude in excludes]
def is_excluded(root, excludes):
"""Check if the directory is in the exclude list.
Note: by having trailing slashes, we avoid common prefix issues, like
e.g. an exlude "foo" also accidentally excluding "foobar".
"""
root = os.path.normpath(root)
for exclude in excludes:
if root == exclude:
return True
return False
def generate(app, src, dest, exclude=[], followlinks=False,
force=False, dryrun=False, private=False, suffix='rst',
template_dirs=None):
"""Generage the rst files
Raises an :class:`OSError` if the source path is not a directory.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param src: path to python source files
:type src: :class:`str`
:param dest: output directory
:type dest: :class:`str`
:param exclude: list of paths to exclude
:type exclude: :class:`list`
:param followlinks: follow symbolic links
:type followlinks: :class:`bool`
:param force: overwrite existing files
:type force: :class:`bool`
:param dryrun: do not create any files
:type dryrun: :class:`bool`
:param private: include \"_private\" modules
:type private: :class:`bool`
:param suffix: file suffix
:type suffix: :class:`str`
:param template_dirs: directories to search for user templates
:type template_dirs: None | :class:`list`
:returns: None
:rtype: None
:raises: OSError
"""
suffix = suffix.strip('.')
if not os.path.isdir(src):
raise OSError("%s is not a directory" % src)
if not os.path.isdir(dest) and not dryrun:
os.makedirs(dest)
src = os.path.normpath(os.path.abspath(src))
exclude = normalize_excludes(exclude)
loader = make_loader(template_dirs)
env = make_environment(loader)
recurse_tree(app, env, src, dest, exclude, followlinks, force, dryrun, private, suffix)
def main(app):
"""Parse the config of the app and initiate the generation process
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:returns: None
:rtype: None
:raises: None
"""
c = app.config
src = c.jinjaapi_srcdir
if not src:
return
suffix = "rst"
out = c.jinjaapi_outputdir or app.env.srcdir
if c.jinjaapi_addsummarytemplate:
tpath = pkg_resources.resource_filename(__package__, AUTOSUMMARYTEMPLATE_DIR)
c.templates_path.append(tpath)
tpath = pkg_resources.resource_filename(__package__, TEMPLATE_DIR)
c.templates_path.append(tpath)
prepare_dir(app, out, not c.jinjaapi_nodelete)
generate(app, src, out,
exclude=c.jinjaapi_exclude_paths,
force=c.jinjaapi_force,
followlinks=c.jinjaapi_followlinks,
dryrun=c.jinjaapi_dryrun,
private=c.jinjaapi_includeprivate,
suffix=suffix,
template_dirs=c.templates_path)
|
storax/jinjaapidoc
|
src/jinjaapidoc/gendoc.py
|
recurse_tree
|
python
|
def recurse_tree(app, env, src, dest, excludes, followlinks, force, dryrun, private, suffix):
# check if the base directory is a package and get its name
if INITPY in os.listdir(src):
root_package = src.split(os.path.sep)[-1]
else:
# otherwise, the base is a directory with packages
root_package = None
toplevels = []
for root, subs, files in walk(src, followlinks=followlinks):
# document only Python module files (that aren't excluded)
py_files = sorted(f for f in files
if os.path.splitext(f)[1] in PY_SUFFIXES and # noqa: W504
not is_excluded(os.path.join(root, f), excludes))
is_pkg = INITPY in py_files
if is_pkg:
py_files.remove(INITPY)
py_files.insert(0, INITPY)
elif root != src:
# only accept non-package at toplevel
del subs[:]
continue
# remove hidden ('.') and private ('_') directories, as well as
# excluded dirs
if private:
exclude_prefixes = ('.',)
else:
exclude_prefixes = ('.', '_')
subs[:] = sorted(sub for sub in subs if not sub.startswith(exclude_prefixes) and not
is_excluded(os.path.join(root, sub), excludes))
if is_pkg:
# we are in a package with something to document
if subs or len(py_files) > 1 or not \
shall_skip(app, os.path.join(root, INITPY), private):
subpackage = root[len(src):].lstrip(os.path.sep).\
replace(os.path.sep, '.')
create_package_file(app, env, root_package, subpackage,
private, dest, suffix, dryrun, force)
toplevels.append(makename(root_package, subpackage))
else:
# if we are at the root level, we don't require it to be a package
assert root == src and root_package is None
for py_file in py_files:
if not shall_skip(app, os.path.join(src, py_file), private):
module = os.path.splitext(py_file)[0]
create_module_file(app, env, root_package, module, dest, suffix, dryrun, force)
toplevels.append(module)
return toplevels
|
Look for every file in the directory tree and create the corresponding
ReST files.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param env: the jinja environment
:type env: :class:`jinja2.Environment`
:param src: the path to the python source files
:type src: :class:`str`
:param dest: the output directory
:type dest: :class:`str`
:param excludes: the paths to exclude
:type excludes: :class:`list`
:param followlinks: follow symbolic links
:type followlinks: :class:`bool`
:param force: overwrite existing files
:type force: :class:`bool`
:param dryrun: do not generate files
:type dryrun: :class:`bool`
:param private: include "_private" modules
:type private: :class:`bool`
:param suffix: the file extension
:type suffix: :class:`str`
|
train
|
https://github.com/storax/jinjaapidoc/blob/f1eeb6ab5bd1a96c4130306718c6423f37c76856/src/jinjaapidoc/gendoc.py#L424-L495
|
[
"def makename(package, module):\n \"\"\"Join package and module with a dot.\n\n Package or Module can be empty.\n\n :param package: the package name\n :type package: :class:`str`\n :param module: the module name\n :type module: :class:`str`\n :returns: the joined name\n :rtype: :class:`str`\n :raises: :class:`AssertionError`, if both package and module are empty\n \"\"\"\n # Both package and module can be None/empty.\n assert package or module, \"Specify either package or module\"\n if package:\n name = package\n if module:\n name += '.' + module\n else:\n name = module\n return name\n",
"def create_module_file(app, env, package, module, dest, suffix, dryrun, force):\n \"\"\"Build the text of the file and write the file.\n\n :param app: the sphinx app\n :type app: :class:`sphinx.application.Sphinx`\n :param env: the jinja environment for the templates\n :type env: :class:`jinja2.Environment`\n :param package: the package name\n :type package: :class:`str`\n :param module: the module name\n :type module: :class:`str`\n :param dest: the output directory\n :type dest: :class:`str`\n :param suffix: the file extension\n :type suffix: :class:`str`\n :param dryrun: If True, do not create any files, just log the potential location.\n :type dryrun: :class:`bool`\n :param force: Overwrite existing files\n :type force: :class:`bool`\n :returns: None\n :raises: None\n \"\"\"\n logger.debug('Create module file: package %s, module %s', package, module)\n template_file = MODULE_TEMPLATE_NAME\n template = env.get_template(template_file)\n fn = makename(package, module)\n var = get_context(app, package, module, fn)\n var['ispkg'] = False\n rendered = template.render(var)\n write_file(app, makename(package, module), rendered, dest, suffix, dryrun, force)\n",
"def create_package_file(app, env, root_package, sub_package, private,\n dest, suffix, dryrun, force):\n \"\"\"Build the text of the file and write the file.\n\n :param app: the sphinx app\n :type app: :class:`sphinx.application.Sphinx`\n :param env: the jinja environment for the templates\n :type env: :class:`jinja2.Environment`\n :param root_package: the parent package\n :type root_package: :class:`str`\n :param sub_package: the package name without root\n :type sub_package: :class:`str`\n :param private: Include \\\"_private\\\" modules\n :type private: :class:`bool`\n :param dest: the output directory\n :type dest: :class:`str`\n :param suffix: the file extension\n :type suffix: :class:`str`\n :param dryrun: If True, do not create any files, just log the potential location.\n :type dryrun: :class:`bool`\n :param force: Overwrite existing files\n :type force: :class:`bool`\n :returns: None\n :raises: None\n \"\"\"\n logger.debug('Create package file: rootpackage %s, sub_package %s', root_package, sub_package)\n template_file = PACKAGE_TEMPLATE_NAME\n template = env.get_template(template_file)\n fn = makename(root_package, sub_package)\n var = get_context(app, root_package, sub_package, fn)\n var['ispkg'] = True\n for submod in var['submods']:\n if shall_skip(app, submod, private):\n continue\n create_module_file(app, env, fn, submod, dest, suffix, dryrun, force)\n rendered = template.render(var)\n write_file(app, fn, rendered, dest, suffix, dryrun, force)\n",
"def shall_skip(app, module, private):\n \"\"\"Check if we want to skip this module.\n\n :param app: the sphinx app\n :type app: :class:`sphinx.application.Sphinx`\n :param module: the module name\n :type module: :class:`str`\n :param private: True, if privates are allowed\n :type private: :class:`bool`\n \"\"\"\n logger.debug('Testing if %s should be skipped.', module)\n # skip if it has a \"private\" name and this is selected\n if module != '__init__.py' and module.startswith('_') and \\\n not private:\n logger.debug('Skip %s because its either private or __init__.', module)\n return True\n logger.debug('Do not skip %s', module)\n return False\n"
] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""This is a modification of sphinx.apidoc by David.Zuber.
It uses jinja templates to render the rst files.
Parses a directory tree looking for Python modules and packages and creates
ReST files appropriately to create code documentation with Sphinx.
This is derived form the "sphinx-apidoc" script, which is:
Copyright 2007-2014 by the Sphinx team, see http://sphinx-doc.org/latest/authors.html.
"""
import os
import inspect
import pkgutil
import pkg_resources
import shutil
import jinja2
from sphinx.util.osutil import walk
from sphinx.util import logging
from sphinx.ext import autosummary
logger = logging.getLogger(__name__)
INITPY = '__init__.py'
PY_SUFFIXES = set(['.py', '.pyx'])
TEMPLATE_DIR = 'templates'
"""Built-in template dir for jinjaapi rendering"""
AUTOSUMMARYTEMPLATE_DIR = 'autosummarytemplates'
"""Templates for autosummary"""
MODULE_TEMPLATE_NAME = 'jinjaapi_module.rst'
"""Name of the template that is used for rendering modules."""
PACKAGE_TEMPLATE_NAME = 'jinjaapi_package.rst'
"""Name of the template that is used for rendering packages."""
def prepare_dir(app, directory, delete=False):
"""Create apidoc dir, delete contents if delete is True.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param directory: the apidoc directory. you can use relative paths here
:type directory: str
:param delete: if True, deletes the contents of apidoc. This acts like an override switch.
:type delete: bool
:returns: None
:rtype: None
:raises: None
"""
logger.info("Preparing output directories for jinjaapidoc.")
if os.path.exists(directory):
if delete:
logger.debug("Deleting dir %s", directory)
shutil.rmtree(directory)
logger.debug("Creating dir %s", directory)
os.mkdir(directory)
else:
logger.debug("Creating %s", directory)
os.mkdir(directory)
def make_loader(template_dirs):
"""Return a new :class:`jinja2.FileSystemLoader` that uses the template_dirs
:param template_dirs: directories to search for templates
:type template_dirs: None | :class:`list`
:returns: a new loader
:rtype: :class:`jinja2.FileSystemLoader`
:raises: None
"""
return jinja2.FileSystemLoader(searchpath=template_dirs)
def make_environment(loader):
"""Return a new :class:`jinja2.Environment` with the given loader
:param loader: a jinja2 loader
:type loader: :class:`jinja2.BaseLoader`
:returns: a new environment
:rtype: :class:`jinja2.Environment`
:raises: None
"""
return jinja2.Environment(loader=loader)
def makename(package, module):
"""Join package and module with a dot.
Package or Module can be empty.
:param package: the package name
:type package: :class:`str`
:param module: the module name
:type module: :class:`str`
:returns: the joined name
:rtype: :class:`str`
:raises: :class:`AssertionError`, if both package and module are empty
"""
# Both package and module can be None/empty.
assert package or module, "Specify either package or module"
if package:
name = package
if module:
name += '.' + module
else:
name = module
return name
def write_file(app, name, text, dest, suffix, dryrun, force):
"""Write the output file for module/package <name>.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param name: the file name without file extension
:type name: :class:`str`
:param text: the content of the file
:type text: :class:`str`
:param dest: the output directory
:type dest: :class:`str`
:param suffix: the file extension
:type suffix: :class:`str`
:param dryrun: If True, do not create any files, just log the potential location.
:type dryrun: :class:`bool`
:param force: Overwrite existing files
:type force: :class:`bool`
:returns: None
:raises: None
"""
fname = os.path.join(dest, '%s.%s' % (name, suffix))
if dryrun:
logger.info('Would create file %s.' % fname)
return
if not force and os.path.isfile(fname):
logger.info('File %s already exists, skipping.' % fname)
else:
logger.info('Creating file %s.' % fname)
f = open(fname, 'w')
try:
f.write(text)
relpath = os.path.relpath(fname, start=app.env.srcdir)
abspath = os.sep + relpath
docpath = app.env.relfn2path(abspath)[0]
docpath = docpath.rsplit(os.path.extsep, 1)[0]
logger.debug('Adding document %s' % docpath)
app.env.found_docs.add(docpath)
finally:
f.close()
def import_name(app, name):
"""Import the given name and return name, obj, parent, mod_name
:param name: name to import
:type name: str
:returns: the imported object or None
:rtype: object | None
:raises: None
"""
try:
logger.debug('Importing %r', name)
name, obj = autosummary.import_by_name(name)[:2]
logger.debug('Imported %s', obj)
return obj
except ImportError as e:
logger.warn("Jinjapidoc failed to import %r: %s", name, e)
def get_members(app, mod, typ, include_public=None):
"""Return the members of mod of the given type
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param mod: the module with members
:type mod: module
:param typ: the typ, ``'class'``, ``'function'``, ``'exception'``, ``'data'``, ``'members'``
:type typ: str
:param include_public: list of private members to include to publics
:type include_public: list | None
:returns: None
:rtype: None
:raises: None
"""
def include_here(x):
"""Return true if the member should be included in mod.
A member will be included if it is declared in this module or package.
If the `jinjaapidoc_include_from_all` option is `True` then the member
can also be included if it is listed in `__all__`.
:param x: The member
:type x: A class, exception, or function.
:returns: True if the member should be included in mod. False otherwise.
:rtype: bool
"""
return (x.__module__ == mod.__name__ or (include_from_all and x.__name__ in all_list))
all_list = getattr(mod, '__all__', [])
include_from_all = app.config.jinjaapi_include_from_all
include_public = include_public or []
tests = {'class': lambda x: inspect.isclass(x) and not issubclass(x, BaseException) and include_here(x),
'function': lambda x: inspect.isfunction(x) and include_here(x),
'exception': lambda x: inspect.isclass(x) and issubclass(x, BaseException) and include_here(x),
'data': lambda x: not inspect.ismodule(x) and not inspect.isclass(x) and not inspect.isfunction(x),
'members': lambda x: True}
items = []
for name in dir(mod):
i = getattr(mod, name)
inspect.ismodule(i)
if tests.get(typ, lambda x: False)(i):
items.append(name)
public = [x for x in items
if x in include_public or not x.startswith('_')]
logger.debug('Got members of %s of type %s: public %s and %s', mod, typ, public, items)
return public, items
def _get_submodules(app, module):
"""Get all submodules for the given module/package
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param module: the module to query or module path
:type module: module | str
:returns: list of module names and boolean whether its a package
:rtype: list
:raises: TypeError
"""
if inspect.ismodule(module):
if hasattr(module, '__path__'):
p = module.__path__
else:
return []
elif isinstance(module, str):
p = module
else:
raise TypeError("Only Module or String accepted. %s given." % type(module))
logger.debug('Getting submodules of %s', p)
submodules = [(name, ispkg) for loader, name, ispkg in pkgutil.iter_modules(p)]
logger.debug('Found submodules of %s: %s', module, submodules)
return submodules
def get_submodules(app, module):
"""Get all submodules without packages for the given module/package
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param module: the module to query or module path
:type module: module | str
:returns: list of module names excluding packages
:rtype: list
:raises: TypeError
"""
submodules = _get_submodules(app, module)
return [name for name, ispkg in submodules if not ispkg]
def get_subpackages(app, module):
"""Get all subpackages for the given module/package
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param module: the module to query or module path
:type module: module | str
:returns: list of packages names
:rtype: list
:raises: TypeError
"""
submodules = _get_submodules(app, module)
return [name for name, ispkg in submodules if ispkg]
def get_context(app, package, module, fullname):
"""Return a dict for template rendering
Variables:
* :package: The top package
* :module: the module
* :fullname: package.module
* :subpkgs: packages beneath module
* :submods: modules beneath module
* :classes: public classes in module
* :allclasses: public and private classes in module
* :exceptions: public exceptions in module
* :allexceptions: public and private exceptions in module
* :functions: public functions in module
* :allfunctions: public and private functions in module
* :data: public data in module
* :alldata: public and private data in module
* :members: dir(module)
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param package: the parent package name
:type package: str
:param module: the module name
:type module: str
:param fullname: package.module
:type fullname: str
:returns: a dict with variables for template rendering
:rtype: :class:`dict`
:raises: None
"""
var = {'package': package,
'module': module,
'fullname': fullname}
logger.debug('Creating context for: package %s, module %s, fullname %s', package, module, fullname)
obj = import_name(app, fullname)
if not obj:
for k in ('subpkgs', 'submods', 'classes', 'allclasses',
'exceptions', 'allexceptions', 'functions', 'allfunctions',
'data', 'alldata', 'memebers'):
var[k] = []
return var
var['subpkgs'] = get_subpackages(app, obj)
var['submods'] = get_submodules(app, obj)
var['classes'], var['allclasses'] = get_members(app, obj, 'class')
var['exceptions'], var['allexceptions'] = get_members(app, obj, 'exception')
var['functions'], var['allfunctions'] = get_members(app, obj, 'function')
var['data'], var['alldata'] = get_members(app, obj, 'data')
var['members'] = get_members(app, obj, 'members')
logger.debug('Created context: %s', var)
return var
def create_module_file(app, env, package, module, dest, suffix, dryrun, force):
"""Build the text of the file and write the file.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param env: the jinja environment for the templates
:type env: :class:`jinja2.Environment`
:param package: the package name
:type package: :class:`str`
:param module: the module name
:type module: :class:`str`
:param dest: the output directory
:type dest: :class:`str`
:param suffix: the file extension
:type suffix: :class:`str`
:param dryrun: If True, do not create any files, just log the potential location.
:type dryrun: :class:`bool`
:param force: Overwrite existing files
:type force: :class:`bool`
:returns: None
:raises: None
"""
logger.debug('Create module file: package %s, module %s', package, module)
template_file = MODULE_TEMPLATE_NAME
template = env.get_template(template_file)
fn = makename(package, module)
var = get_context(app, package, module, fn)
var['ispkg'] = False
rendered = template.render(var)
write_file(app, makename(package, module), rendered, dest, suffix, dryrun, force)
def create_package_file(app, env, root_package, sub_package, private,
dest, suffix, dryrun, force):
"""Build the text of the file and write the file.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param env: the jinja environment for the templates
:type env: :class:`jinja2.Environment`
:param root_package: the parent package
:type root_package: :class:`str`
:param sub_package: the package name without root
:type sub_package: :class:`str`
:param private: Include \"_private\" modules
:type private: :class:`bool`
:param dest: the output directory
:type dest: :class:`str`
:param suffix: the file extension
:type suffix: :class:`str`
:param dryrun: If True, do not create any files, just log the potential location.
:type dryrun: :class:`bool`
:param force: Overwrite existing files
:type force: :class:`bool`
:returns: None
:raises: None
"""
logger.debug('Create package file: rootpackage %s, sub_package %s', root_package, sub_package)
template_file = PACKAGE_TEMPLATE_NAME
template = env.get_template(template_file)
fn = makename(root_package, sub_package)
var = get_context(app, root_package, sub_package, fn)
var['ispkg'] = True
for submod in var['submods']:
if shall_skip(app, submod, private):
continue
create_module_file(app, env, fn, submod, dest, suffix, dryrun, force)
rendered = template.render(var)
write_file(app, fn, rendered, dest, suffix, dryrun, force)
def shall_skip(app, module, private):
"""Check if we want to skip this module.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param module: the module name
:type module: :class:`str`
:param private: True, if privates are allowed
:type private: :class:`bool`
"""
logger.debug('Testing if %s should be skipped.', module)
# skip if it has a "private" name and this is selected
if module != '__init__.py' and module.startswith('_') and \
not private:
logger.debug('Skip %s because its either private or __init__.', module)
return True
logger.debug('Do not skip %s', module)
return False
def normalize_excludes(excludes):
"""Normalize the excluded directory list."""
return [os.path.normpath(os.path.abspath(exclude)) for exclude in excludes]
def is_excluded(root, excludes):
"""Check if the directory is in the exclude list.
Note: by having trailing slashes, we avoid common prefix issues, like
e.g. an exlude "foo" also accidentally excluding "foobar".
"""
root = os.path.normpath(root)
for exclude in excludes:
if root == exclude:
return True
return False
def generate(app, src, dest, exclude=[], followlinks=False,
force=False, dryrun=False, private=False, suffix='rst',
template_dirs=None):
"""Generage the rst files
Raises an :class:`OSError` if the source path is not a directory.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param src: path to python source files
:type src: :class:`str`
:param dest: output directory
:type dest: :class:`str`
:param exclude: list of paths to exclude
:type exclude: :class:`list`
:param followlinks: follow symbolic links
:type followlinks: :class:`bool`
:param force: overwrite existing files
:type force: :class:`bool`
:param dryrun: do not create any files
:type dryrun: :class:`bool`
:param private: include \"_private\" modules
:type private: :class:`bool`
:param suffix: file suffix
:type suffix: :class:`str`
:param template_dirs: directories to search for user templates
:type template_dirs: None | :class:`list`
:returns: None
:rtype: None
:raises: OSError
"""
suffix = suffix.strip('.')
if not os.path.isdir(src):
raise OSError("%s is not a directory" % src)
if not os.path.isdir(dest) and not dryrun:
os.makedirs(dest)
src = os.path.normpath(os.path.abspath(src))
exclude = normalize_excludes(exclude)
loader = make_loader(template_dirs)
env = make_environment(loader)
recurse_tree(app, env, src, dest, exclude, followlinks, force, dryrun, private, suffix)
def main(app):
"""Parse the config of the app and initiate the generation process
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:returns: None
:rtype: None
:raises: None
"""
c = app.config
src = c.jinjaapi_srcdir
if not src:
return
suffix = "rst"
out = c.jinjaapi_outputdir or app.env.srcdir
if c.jinjaapi_addsummarytemplate:
tpath = pkg_resources.resource_filename(__package__, AUTOSUMMARYTEMPLATE_DIR)
c.templates_path.append(tpath)
tpath = pkg_resources.resource_filename(__package__, TEMPLATE_DIR)
c.templates_path.append(tpath)
prepare_dir(app, out, not c.jinjaapi_nodelete)
generate(app, src, out,
exclude=c.jinjaapi_exclude_paths,
force=c.jinjaapi_force,
followlinks=c.jinjaapi_followlinks,
dryrun=c.jinjaapi_dryrun,
private=c.jinjaapi_includeprivate,
suffix=suffix,
template_dirs=c.templates_path)
|
storax/jinjaapidoc
|
src/jinjaapidoc/gendoc.py
|
normalize_excludes
|
python
|
def normalize_excludes(excludes):
return [os.path.normpath(os.path.abspath(exclude)) for exclude in excludes]
|
Normalize the excluded directory list.
|
train
|
https://github.com/storax/jinjaapidoc/blob/f1eeb6ab5bd1a96c4130306718c6423f37c76856/src/jinjaapidoc/gendoc.py#L498-L500
| null |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""This is a modification of sphinx.apidoc by David.Zuber.
It uses jinja templates to render the rst files.
Parses a directory tree looking for Python modules and packages and creates
ReST files appropriately to create code documentation with Sphinx.
This is derived form the "sphinx-apidoc" script, which is:
Copyright 2007-2014 by the Sphinx team, see http://sphinx-doc.org/latest/authors.html.
"""
import os
import inspect
import pkgutil
import pkg_resources
import shutil
import jinja2
from sphinx.util.osutil import walk
from sphinx.util import logging
from sphinx.ext import autosummary
logger = logging.getLogger(__name__)
INITPY = '__init__.py'
PY_SUFFIXES = set(['.py', '.pyx'])
TEMPLATE_DIR = 'templates'
"""Built-in template dir for jinjaapi rendering"""
AUTOSUMMARYTEMPLATE_DIR = 'autosummarytemplates'
"""Templates for autosummary"""
MODULE_TEMPLATE_NAME = 'jinjaapi_module.rst'
"""Name of the template that is used for rendering modules."""
PACKAGE_TEMPLATE_NAME = 'jinjaapi_package.rst'
"""Name of the template that is used for rendering packages."""
def prepare_dir(app, directory, delete=False):
"""Create apidoc dir, delete contents if delete is True.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param directory: the apidoc directory. you can use relative paths here
:type directory: str
:param delete: if True, deletes the contents of apidoc. This acts like an override switch.
:type delete: bool
:returns: None
:rtype: None
:raises: None
"""
logger.info("Preparing output directories for jinjaapidoc.")
if os.path.exists(directory):
if delete:
logger.debug("Deleting dir %s", directory)
shutil.rmtree(directory)
logger.debug("Creating dir %s", directory)
os.mkdir(directory)
else:
logger.debug("Creating %s", directory)
os.mkdir(directory)
def make_loader(template_dirs):
"""Return a new :class:`jinja2.FileSystemLoader` that uses the template_dirs
:param template_dirs: directories to search for templates
:type template_dirs: None | :class:`list`
:returns: a new loader
:rtype: :class:`jinja2.FileSystemLoader`
:raises: None
"""
return jinja2.FileSystemLoader(searchpath=template_dirs)
def make_environment(loader):
"""Return a new :class:`jinja2.Environment` with the given loader
:param loader: a jinja2 loader
:type loader: :class:`jinja2.BaseLoader`
:returns: a new environment
:rtype: :class:`jinja2.Environment`
:raises: None
"""
return jinja2.Environment(loader=loader)
def makename(package, module):
"""Join package and module with a dot.
Package or Module can be empty.
:param package: the package name
:type package: :class:`str`
:param module: the module name
:type module: :class:`str`
:returns: the joined name
:rtype: :class:`str`
:raises: :class:`AssertionError`, if both package and module are empty
"""
# Both package and module can be None/empty.
assert package or module, "Specify either package or module"
if package:
name = package
if module:
name += '.' + module
else:
name = module
return name
def write_file(app, name, text, dest, suffix, dryrun, force):
"""Write the output file for module/package <name>.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param name: the file name without file extension
:type name: :class:`str`
:param text: the content of the file
:type text: :class:`str`
:param dest: the output directory
:type dest: :class:`str`
:param suffix: the file extension
:type suffix: :class:`str`
:param dryrun: If True, do not create any files, just log the potential location.
:type dryrun: :class:`bool`
:param force: Overwrite existing files
:type force: :class:`bool`
:returns: None
:raises: None
"""
fname = os.path.join(dest, '%s.%s' % (name, suffix))
if dryrun:
logger.info('Would create file %s.' % fname)
return
if not force and os.path.isfile(fname):
logger.info('File %s already exists, skipping.' % fname)
else:
logger.info('Creating file %s.' % fname)
f = open(fname, 'w')
try:
f.write(text)
relpath = os.path.relpath(fname, start=app.env.srcdir)
abspath = os.sep + relpath
docpath = app.env.relfn2path(abspath)[0]
docpath = docpath.rsplit(os.path.extsep, 1)[0]
logger.debug('Adding document %s' % docpath)
app.env.found_docs.add(docpath)
finally:
f.close()
def import_name(app, name):
"""Import the given name and return name, obj, parent, mod_name
:param name: name to import
:type name: str
:returns: the imported object or None
:rtype: object | None
:raises: None
"""
try:
logger.debug('Importing %r', name)
name, obj = autosummary.import_by_name(name)[:2]
logger.debug('Imported %s', obj)
return obj
except ImportError as e:
logger.warn("Jinjapidoc failed to import %r: %s", name, e)
def get_members(app, mod, typ, include_public=None):
"""Return the members of mod of the given type
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param mod: the module with members
:type mod: module
:param typ: the typ, ``'class'``, ``'function'``, ``'exception'``, ``'data'``, ``'members'``
:type typ: str
:param include_public: list of private members to include to publics
:type include_public: list | None
:returns: None
:rtype: None
:raises: None
"""
def include_here(x):
"""Return true if the member should be included in mod.
A member will be included if it is declared in this module or package.
If the `jinjaapidoc_include_from_all` option is `True` then the member
can also be included if it is listed in `__all__`.
:param x: The member
:type x: A class, exception, or function.
:returns: True if the member should be included in mod. False otherwise.
:rtype: bool
"""
return (x.__module__ == mod.__name__ or (include_from_all and x.__name__ in all_list))
all_list = getattr(mod, '__all__', [])
include_from_all = app.config.jinjaapi_include_from_all
include_public = include_public or []
tests = {'class': lambda x: inspect.isclass(x) and not issubclass(x, BaseException) and include_here(x),
'function': lambda x: inspect.isfunction(x) and include_here(x),
'exception': lambda x: inspect.isclass(x) and issubclass(x, BaseException) and include_here(x),
'data': lambda x: not inspect.ismodule(x) and not inspect.isclass(x) and not inspect.isfunction(x),
'members': lambda x: True}
items = []
for name in dir(mod):
i = getattr(mod, name)
inspect.ismodule(i)
if tests.get(typ, lambda x: False)(i):
items.append(name)
public = [x for x in items
if x in include_public or not x.startswith('_')]
logger.debug('Got members of %s of type %s: public %s and %s', mod, typ, public, items)
return public, items
def _get_submodules(app, module):
"""Get all submodules for the given module/package
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param module: the module to query or module path
:type module: module | str
:returns: list of module names and boolean whether its a package
:rtype: list
:raises: TypeError
"""
if inspect.ismodule(module):
if hasattr(module, '__path__'):
p = module.__path__
else:
return []
elif isinstance(module, str):
p = module
else:
raise TypeError("Only Module or String accepted. %s given." % type(module))
logger.debug('Getting submodules of %s', p)
submodules = [(name, ispkg) for loader, name, ispkg in pkgutil.iter_modules(p)]
logger.debug('Found submodules of %s: %s', module, submodules)
return submodules
def get_submodules(app, module):
"""Get all submodules without packages for the given module/package
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param module: the module to query or module path
:type module: module | str
:returns: list of module names excluding packages
:rtype: list
:raises: TypeError
"""
submodules = _get_submodules(app, module)
return [name for name, ispkg in submodules if not ispkg]
def get_subpackages(app, module):
"""Get all subpackages for the given module/package
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param module: the module to query or module path
:type module: module | str
:returns: list of packages names
:rtype: list
:raises: TypeError
"""
submodules = _get_submodules(app, module)
return [name for name, ispkg in submodules if ispkg]
def get_context(app, package, module, fullname):
"""Return a dict for template rendering
Variables:
* :package: The top package
* :module: the module
* :fullname: package.module
* :subpkgs: packages beneath module
* :submods: modules beneath module
* :classes: public classes in module
* :allclasses: public and private classes in module
* :exceptions: public exceptions in module
* :allexceptions: public and private exceptions in module
* :functions: public functions in module
* :allfunctions: public and private functions in module
* :data: public data in module
* :alldata: public and private data in module
* :members: dir(module)
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param package: the parent package name
:type package: str
:param module: the module name
:type module: str
:param fullname: package.module
:type fullname: str
:returns: a dict with variables for template rendering
:rtype: :class:`dict`
:raises: None
"""
var = {'package': package,
'module': module,
'fullname': fullname}
logger.debug('Creating context for: package %s, module %s, fullname %s', package, module, fullname)
obj = import_name(app, fullname)
if not obj:
for k in ('subpkgs', 'submods', 'classes', 'allclasses',
'exceptions', 'allexceptions', 'functions', 'allfunctions',
'data', 'alldata', 'memebers'):
var[k] = []
return var
var['subpkgs'] = get_subpackages(app, obj)
var['submods'] = get_submodules(app, obj)
var['classes'], var['allclasses'] = get_members(app, obj, 'class')
var['exceptions'], var['allexceptions'] = get_members(app, obj, 'exception')
var['functions'], var['allfunctions'] = get_members(app, obj, 'function')
var['data'], var['alldata'] = get_members(app, obj, 'data')
var['members'] = get_members(app, obj, 'members')
logger.debug('Created context: %s', var)
return var
def create_module_file(app, env, package, module, dest, suffix, dryrun, force):
"""Build the text of the file and write the file.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param env: the jinja environment for the templates
:type env: :class:`jinja2.Environment`
:param package: the package name
:type package: :class:`str`
:param module: the module name
:type module: :class:`str`
:param dest: the output directory
:type dest: :class:`str`
:param suffix: the file extension
:type suffix: :class:`str`
:param dryrun: If True, do not create any files, just log the potential location.
:type dryrun: :class:`bool`
:param force: Overwrite existing files
:type force: :class:`bool`
:returns: None
:raises: None
"""
logger.debug('Create module file: package %s, module %s', package, module)
template_file = MODULE_TEMPLATE_NAME
template = env.get_template(template_file)
fn = makename(package, module)
var = get_context(app, package, module, fn)
var['ispkg'] = False
rendered = template.render(var)
write_file(app, makename(package, module), rendered, dest, suffix, dryrun, force)
def create_package_file(app, env, root_package, sub_package, private,
dest, suffix, dryrun, force):
"""Build the text of the file and write the file.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param env: the jinja environment for the templates
:type env: :class:`jinja2.Environment`
:param root_package: the parent package
:type root_package: :class:`str`
:param sub_package: the package name without root
:type sub_package: :class:`str`
:param private: Include \"_private\" modules
:type private: :class:`bool`
:param dest: the output directory
:type dest: :class:`str`
:param suffix: the file extension
:type suffix: :class:`str`
:param dryrun: If True, do not create any files, just log the potential location.
:type dryrun: :class:`bool`
:param force: Overwrite existing files
:type force: :class:`bool`
:returns: None
:raises: None
"""
logger.debug('Create package file: rootpackage %s, sub_package %s', root_package, sub_package)
template_file = PACKAGE_TEMPLATE_NAME
template = env.get_template(template_file)
fn = makename(root_package, sub_package)
var = get_context(app, root_package, sub_package, fn)
var['ispkg'] = True
for submod in var['submods']:
if shall_skip(app, submod, private):
continue
create_module_file(app, env, fn, submod, dest, suffix, dryrun, force)
rendered = template.render(var)
write_file(app, fn, rendered, dest, suffix, dryrun, force)
def shall_skip(app, module, private):
"""Check if we want to skip this module.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param module: the module name
:type module: :class:`str`
:param private: True, if privates are allowed
:type private: :class:`bool`
"""
logger.debug('Testing if %s should be skipped.', module)
# skip if it has a "private" name and this is selected
if module != '__init__.py' and module.startswith('_') and \
not private:
logger.debug('Skip %s because its either private or __init__.', module)
return True
logger.debug('Do not skip %s', module)
return False
def recurse_tree(app, env, src, dest, excludes, followlinks, force, dryrun, private, suffix):
"""Look for every file in the directory tree and create the corresponding
ReST files.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param env: the jinja environment
:type env: :class:`jinja2.Environment`
:param src: the path to the python source files
:type src: :class:`str`
:param dest: the output directory
:type dest: :class:`str`
:param excludes: the paths to exclude
:type excludes: :class:`list`
:param followlinks: follow symbolic links
:type followlinks: :class:`bool`
:param force: overwrite existing files
:type force: :class:`bool`
:param dryrun: do not generate files
:type dryrun: :class:`bool`
:param private: include "_private" modules
:type private: :class:`bool`
:param suffix: the file extension
:type suffix: :class:`str`
"""
# check if the base directory is a package and get its name
if INITPY in os.listdir(src):
root_package = src.split(os.path.sep)[-1]
else:
# otherwise, the base is a directory with packages
root_package = None
toplevels = []
for root, subs, files in walk(src, followlinks=followlinks):
# document only Python module files (that aren't excluded)
py_files = sorted(f for f in files
if os.path.splitext(f)[1] in PY_SUFFIXES and # noqa: W504
not is_excluded(os.path.join(root, f), excludes))
is_pkg = INITPY in py_files
if is_pkg:
py_files.remove(INITPY)
py_files.insert(0, INITPY)
elif root != src:
# only accept non-package at toplevel
del subs[:]
continue
# remove hidden ('.') and private ('_') directories, as well as
# excluded dirs
if private:
exclude_prefixes = ('.',)
else:
exclude_prefixes = ('.', '_')
subs[:] = sorted(sub for sub in subs if not sub.startswith(exclude_prefixes) and not
is_excluded(os.path.join(root, sub), excludes))
if is_pkg:
# we are in a package with something to document
if subs or len(py_files) > 1 or not \
shall_skip(app, os.path.join(root, INITPY), private):
subpackage = root[len(src):].lstrip(os.path.sep).\
replace(os.path.sep, '.')
create_package_file(app, env, root_package, subpackage,
private, dest, suffix, dryrun, force)
toplevels.append(makename(root_package, subpackage))
else:
# if we are at the root level, we don't require it to be a package
assert root == src and root_package is None
for py_file in py_files:
if not shall_skip(app, os.path.join(src, py_file), private):
module = os.path.splitext(py_file)[0]
create_module_file(app, env, root_package, module, dest, suffix, dryrun, force)
toplevels.append(module)
return toplevels
def is_excluded(root, excludes):
"""Check if the directory is in the exclude list.
Note: by having trailing slashes, we avoid common prefix issues, like
e.g. an exlude "foo" also accidentally excluding "foobar".
"""
root = os.path.normpath(root)
for exclude in excludes:
if root == exclude:
return True
return False
def generate(app, src, dest, exclude=[], followlinks=False,
force=False, dryrun=False, private=False, suffix='rst',
template_dirs=None):
"""Generage the rst files
Raises an :class:`OSError` if the source path is not a directory.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param src: path to python source files
:type src: :class:`str`
:param dest: output directory
:type dest: :class:`str`
:param exclude: list of paths to exclude
:type exclude: :class:`list`
:param followlinks: follow symbolic links
:type followlinks: :class:`bool`
:param force: overwrite existing files
:type force: :class:`bool`
:param dryrun: do not create any files
:type dryrun: :class:`bool`
:param private: include \"_private\" modules
:type private: :class:`bool`
:param suffix: file suffix
:type suffix: :class:`str`
:param template_dirs: directories to search for user templates
:type template_dirs: None | :class:`list`
:returns: None
:rtype: None
:raises: OSError
"""
suffix = suffix.strip('.')
if not os.path.isdir(src):
raise OSError("%s is not a directory" % src)
if not os.path.isdir(dest) and not dryrun:
os.makedirs(dest)
src = os.path.normpath(os.path.abspath(src))
exclude = normalize_excludes(exclude)
loader = make_loader(template_dirs)
env = make_environment(loader)
recurse_tree(app, env, src, dest, exclude, followlinks, force, dryrun, private, suffix)
def main(app):
"""Parse the config of the app and initiate the generation process
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:returns: None
:rtype: None
:raises: None
"""
c = app.config
src = c.jinjaapi_srcdir
if not src:
return
suffix = "rst"
out = c.jinjaapi_outputdir or app.env.srcdir
if c.jinjaapi_addsummarytemplate:
tpath = pkg_resources.resource_filename(__package__, AUTOSUMMARYTEMPLATE_DIR)
c.templates_path.append(tpath)
tpath = pkg_resources.resource_filename(__package__, TEMPLATE_DIR)
c.templates_path.append(tpath)
prepare_dir(app, out, not c.jinjaapi_nodelete)
generate(app, src, out,
exclude=c.jinjaapi_exclude_paths,
force=c.jinjaapi_force,
followlinks=c.jinjaapi_followlinks,
dryrun=c.jinjaapi_dryrun,
private=c.jinjaapi_includeprivate,
suffix=suffix,
template_dirs=c.templates_path)
|
storax/jinjaapidoc
|
src/jinjaapidoc/gendoc.py
|
is_excluded
|
python
|
def is_excluded(root, excludes):
root = os.path.normpath(root)
for exclude in excludes:
if root == exclude:
return True
return False
|
Check if the directory is in the exclude list.
Note: by having trailing slashes, we avoid common prefix issues, like
e.g. an exlude "foo" also accidentally excluding "foobar".
|
train
|
https://github.com/storax/jinjaapidoc/blob/f1eeb6ab5bd1a96c4130306718c6423f37c76856/src/jinjaapidoc/gendoc.py#L503-L513
| null |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""This is a modification of sphinx.apidoc by David.Zuber.
It uses jinja templates to render the rst files.
Parses a directory tree looking for Python modules and packages and creates
ReST files appropriately to create code documentation with Sphinx.
This is derived form the "sphinx-apidoc" script, which is:
Copyright 2007-2014 by the Sphinx team, see http://sphinx-doc.org/latest/authors.html.
"""
import os
import inspect
import pkgutil
import pkg_resources
import shutil
import jinja2
from sphinx.util.osutil import walk
from sphinx.util import logging
from sphinx.ext import autosummary
logger = logging.getLogger(__name__)
INITPY = '__init__.py'
PY_SUFFIXES = set(['.py', '.pyx'])
TEMPLATE_DIR = 'templates'
"""Built-in template dir for jinjaapi rendering"""
AUTOSUMMARYTEMPLATE_DIR = 'autosummarytemplates'
"""Templates for autosummary"""
MODULE_TEMPLATE_NAME = 'jinjaapi_module.rst'
"""Name of the template that is used for rendering modules."""
PACKAGE_TEMPLATE_NAME = 'jinjaapi_package.rst'
"""Name of the template that is used for rendering packages."""
def prepare_dir(app, directory, delete=False):
"""Create apidoc dir, delete contents if delete is True.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param directory: the apidoc directory. you can use relative paths here
:type directory: str
:param delete: if True, deletes the contents of apidoc. This acts like an override switch.
:type delete: bool
:returns: None
:rtype: None
:raises: None
"""
logger.info("Preparing output directories for jinjaapidoc.")
if os.path.exists(directory):
if delete:
logger.debug("Deleting dir %s", directory)
shutil.rmtree(directory)
logger.debug("Creating dir %s", directory)
os.mkdir(directory)
else:
logger.debug("Creating %s", directory)
os.mkdir(directory)
def make_loader(template_dirs):
"""Return a new :class:`jinja2.FileSystemLoader` that uses the template_dirs
:param template_dirs: directories to search for templates
:type template_dirs: None | :class:`list`
:returns: a new loader
:rtype: :class:`jinja2.FileSystemLoader`
:raises: None
"""
return jinja2.FileSystemLoader(searchpath=template_dirs)
def make_environment(loader):
"""Return a new :class:`jinja2.Environment` with the given loader
:param loader: a jinja2 loader
:type loader: :class:`jinja2.BaseLoader`
:returns: a new environment
:rtype: :class:`jinja2.Environment`
:raises: None
"""
return jinja2.Environment(loader=loader)
def makename(package, module):
"""Join package and module with a dot.
Package or Module can be empty.
:param package: the package name
:type package: :class:`str`
:param module: the module name
:type module: :class:`str`
:returns: the joined name
:rtype: :class:`str`
:raises: :class:`AssertionError`, if both package and module are empty
"""
# Both package and module can be None/empty.
assert package or module, "Specify either package or module"
if package:
name = package
if module:
name += '.' + module
else:
name = module
return name
def write_file(app, name, text, dest, suffix, dryrun, force):
"""Write the output file for module/package <name>.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param name: the file name without file extension
:type name: :class:`str`
:param text: the content of the file
:type text: :class:`str`
:param dest: the output directory
:type dest: :class:`str`
:param suffix: the file extension
:type suffix: :class:`str`
:param dryrun: If True, do not create any files, just log the potential location.
:type dryrun: :class:`bool`
:param force: Overwrite existing files
:type force: :class:`bool`
:returns: None
:raises: None
"""
fname = os.path.join(dest, '%s.%s' % (name, suffix))
if dryrun:
logger.info('Would create file %s.' % fname)
return
if not force and os.path.isfile(fname):
logger.info('File %s already exists, skipping.' % fname)
else:
logger.info('Creating file %s.' % fname)
f = open(fname, 'w')
try:
f.write(text)
relpath = os.path.relpath(fname, start=app.env.srcdir)
abspath = os.sep + relpath
docpath = app.env.relfn2path(abspath)[0]
docpath = docpath.rsplit(os.path.extsep, 1)[0]
logger.debug('Adding document %s' % docpath)
app.env.found_docs.add(docpath)
finally:
f.close()
def import_name(app, name):
"""Import the given name and return name, obj, parent, mod_name
:param name: name to import
:type name: str
:returns: the imported object or None
:rtype: object | None
:raises: None
"""
try:
logger.debug('Importing %r', name)
name, obj = autosummary.import_by_name(name)[:2]
logger.debug('Imported %s', obj)
return obj
except ImportError as e:
logger.warn("Jinjapidoc failed to import %r: %s", name, e)
def get_members(app, mod, typ, include_public=None):
"""Return the members of mod of the given type
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param mod: the module with members
:type mod: module
:param typ: the typ, ``'class'``, ``'function'``, ``'exception'``, ``'data'``, ``'members'``
:type typ: str
:param include_public: list of private members to include to publics
:type include_public: list | None
:returns: None
:rtype: None
:raises: None
"""
def include_here(x):
"""Return true if the member should be included in mod.
A member will be included if it is declared in this module or package.
If the `jinjaapidoc_include_from_all` option is `True` then the member
can also be included if it is listed in `__all__`.
:param x: The member
:type x: A class, exception, or function.
:returns: True if the member should be included in mod. False otherwise.
:rtype: bool
"""
return (x.__module__ == mod.__name__ or (include_from_all and x.__name__ in all_list))
all_list = getattr(mod, '__all__', [])
include_from_all = app.config.jinjaapi_include_from_all
include_public = include_public or []
tests = {'class': lambda x: inspect.isclass(x) and not issubclass(x, BaseException) and include_here(x),
'function': lambda x: inspect.isfunction(x) and include_here(x),
'exception': lambda x: inspect.isclass(x) and issubclass(x, BaseException) and include_here(x),
'data': lambda x: not inspect.ismodule(x) and not inspect.isclass(x) and not inspect.isfunction(x),
'members': lambda x: True}
items = []
for name in dir(mod):
i = getattr(mod, name)
inspect.ismodule(i)
if tests.get(typ, lambda x: False)(i):
items.append(name)
public = [x for x in items
if x in include_public or not x.startswith('_')]
logger.debug('Got members of %s of type %s: public %s and %s', mod, typ, public, items)
return public, items
def _get_submodules(app, module):
"""Get all submodules for the given module/package
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param module: the module to query or module path
:type module: module | str
:returns: list of module names and boolean whether its a package
:rtype: list
:raises: TypeError
"""
if inspect.ismodule(module):
if hasattr(module, '__path__'):
p = module.__path__
else:
return []
elif isinstance(module, str):
p = module
else:
raise TypeError("Only Module or String accepted. %s given." % type(module))
logger.debug('Getting submodules of %s', p)
submodules = [(name, ispkg) for loader, name, ispkg in pkgutil.iter_modules(p)]
logger.debug('Found submodules of %s: %s', module, submodules)
return submodules
def get_submodules(app, module):
"""Get all submodules without packages for the given module/package
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param module: the module to query or module path
:type module: module | str
:returns: list of module names excluding packages
:rtype: list
:raises: TypeError
"""
submodules = _get_submodules(app, module)
return [name for name, ispkg in submodules if not ispkg]
def get_subpackages(app, module):
"""Get all subpackages for the given module/package
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param module: the module to query or module path
:type module: module | str
:returns: list of packages names
:rtype: list
:raises: TypeError
"""
submodules = _get_submodules(app, module)
return [name for name, ispkg in submodules if ispkg]
def get_context(app, package, module, fullname):
"""Return a dict for template rendering
Variables:
* :package: The top package
* :module: the module
* :fullname: package.module
* :subpkgs: packages beneath module
* :submods: modules beneath module
* :classes: public classes in module
* :allclasses: public and private classes in module
* :exceptions: public exceptions in module
* :allexceptions: public and private exceptions in module
* :functions: public functions in module
* :allfunctions: public and private functions in module
* :data: public data in module
* :alldata: public and private data in module
* :members: dir(module)
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param package: the parent package name
:type package: str
:param module: the module name
:type module: str
:param fullname: package.module
:type fullname: str
:returns: a dict with variables for template rendering
:rtype: :class:`dict`
:raises: None
"""
var = {'package': package,
'module': module,
'fullname': fullname}
logger.debug('Creating context for: package %s, module %s, fullname %s', package, module, fullname)
obj = import_name(app, fullname)
if not obj:
for k in ('subpkgs', 'submods', 'classes', 'allclasses',
'exceptions', 'allexceptions', 'functions', 'allfunctions',
'data', 'alldata', 'memebers'):
var[k] = []
return var
var['subpkgs'] = get_subpackages(app, obj)
var['submods'] = get_submodules(app, obj)
var['classes'], var['allclasses'] = get_members(app, obj, 'class')
var['exceptions'], var['allexceptions'] = get_members(app, obj, 'exception')
var['functions'], var['allfunctions'] = get_members(app, obj, 'function')
var['data'], var['alldata'] = get_members(app, obj, 'data')
var['members'] = get_members(app, obj, 'members')
logger.debug('Created context: %s', var)
return var
def create_module_file(app, env, package, module, dest, suffix, dryrun, force):
"""Build the text of the file and write the file.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param env: the jinja environment for the templates
:type env: :class:`jinja2.Environment`
:param package: the package name
:type package: :class:`str`
:param module: the module name
:type module: :class:`str`
:param dest: the output directory
:type dest: :class:`str`
:param suffix: the file extension
:type suffix: :class:`str`
:param dryrun: If True, do not create any files, just log the potential location.
:type dryrun: :class:`bool`
:param force: Overwrite existing files
:type force: :class:`bool`
:returns: None
:raises: None
"""
logger.debug('Create module file: package %s, module %s', package, module)
template_file = MODULE_TEMPLATE_NAME
template = env.get_template(template_file)
fn = makename(package, module)
var = get_context(app, package, module, fn)
var['ispkg'] = False
rendered = template.render(var)
write_file(app, makename(package, module), rendered, dest, suffix, dryrun, force)
def create_package_file(app, env, root_package, sub_package, private,
dest, suffix, dryrun, force):
"""Build the text of the file and write the file.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param env: the jinja environment for the templates
:type env: :class:`jinja2.Environment`
:param root_package: the parent package
:type root_package: :class:`str`
:param sub_package: the package name without root
:type sub_package: :class:`str`
:param private: Include \"_private\" modules
:type private: :class:`bool`
:param dest: the output directory
:type dest: :class:`str`
:param suffix: the file extension
:type suffix: :class:`str`
:param dryrun: If True, do not create any files, just log the potential location.
:type dryrun: :class:`bool`
:param force: Overwrite existing files
:type force: :class:`bool`
:returns: None
:raises: None
"""
logger.debug('Create package file: rootpackage %s, sub_package %s', root_package, sub_package)
template_file = PACKAGE_TEMPLATE_NAME
template = env.get_template(template_file)
fn = makename(root_package, sub_package)
var = get_context(app, root_package, sub_package, fn)
var['ispkg'] = True
for submod in var['submods']:
if shall_skip(app, submod, private):
continue
create_module_file(app, env, fn, submod, dest, suffix, dryrun, force)
rendered = template.render(var)
write_file(app, fn, rendered, dest, suffix, dryrun, force)
def shall_skip(app, module, private):
"""Check if we want to skip this module.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param module: the module name
:type module: :class:`str`
:param private: True, if privates are allowed
:type private: :class:`bool`
"""
logger.debug('Testing if %s should be skipped.', module)
# skip if it has a "private" name and this is selected
if module != '__init__.py' and module.startswith('_') and \
not private:
logger.debug('Skip %s because its either private or __init__.', module)
return True
logger.debug('Do not skip %s', module)
return False
def recurse_tree(app, env, src, dest, excludes, followlinks, force, dryrun, private, suffix):
"""Look for every file in the directory tree and create the corresponding
ReST files.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param env: the jinja environment
:type env: :class:`jinja2.Environment`
:param src: the path to the python source files
:type src: :class:`str`
:param dest: the output directory
:type dest: :class:`str`
:param excludes: the paths to exclude
:type excludes: :class:`list`
:param followlinks: follow symbolic links
:type followlinks: :class:`bool`
:param force: overwrite existing files
:type force: :class:`bool`
:param dryrun: do not generate files
:type dryrun: :class:`bool`
:param private: include "_private" modules
:type private: :class:`bool`
:param suffix: the file extension
:type suffix: :class:`str`
"""
# check if the base directory is a package and get its name
if INITPY in os.listdir(src):
root_package = src.split(os.path.sep)[-1]
else:
# otherwise, the base is a directory with packages
root_package = None
toplevels = []
for root, subs, files in walk(src, followlinks=followlinks):
# document only Python module files (that aren't excluded)
py_files = sorted(f for f in files
if os.path.splitext(f)[1] in PY_SUFFIXES and # noqa: W504
not is_excluded(os.path.join(root, f), excludes))
is_pkg = INITPY in py_files
if is_pkg:
py_files.remove(INITPY)
py_files.insert(0, INITPY)
elif root != src:
# only accept non-package at toplevel
del subs[:]
continue
# remove hidden ('.') and private ('_') directories, as well as
# excluded dirs
if private:
exclude_prefixes = ('.',)
else:
exclude_prefixes = ('.', '_')
subs[:] = sorted(sub for sub in subs if not sub.startswith(exclude_prefixes) and not
is_excluded(os.path.join(root, sub), excludes))
if is_pkg:
# we are in a package with something to document
if subs or len(py_files) > 1 or not \
shall_skip(app, os.path.join(root, INITPY), private):
subpackage = root[len(src):].lstrip(os.path.sep).\
replace(os.path.sep, '.')
create_package_file(app, env, root_package, subpackage,
private, dest, suffix, dryrun, force)
toplevels.append(makename(root_package, subpackage))
else:
# if we are at the root level, we don't require it to be a package
assert root == src and root_package is None
for py_file in py_files:
if not shall_skip(app, os.path.join(src, py_file), private):
module = os.path.splitext(py_file)[0]
create_module_file(app, env, root_package, module, dest, suffix, dryrun, force)
toplevels.append(module)
return toplevels
def normalize_excludes(excludes):
"""Normalize the excluded directory list."""
return [os.path.normpath(os.path.abspath(exclude)) for exclude in excludes]
def generate(app, src, dest, exclude=[], followlinks=False,
force=False, dryrun=False, private=False, suffix='rst',
template_dirs=None):
"""Generage the rst files
Raises an :class:`OSError` if the source path is not a directory.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param src: path to python source files
:type src: :class:`str`
:param dest: output directory
:type dest: :class:`str`
:param exclude: list of paths to exclude
:type exclude: :class:`list`
:param followlinks: follow symbolic links
:type followlinks: :class:`bool`
:param force: overwrite existing files
:type force: :class:`bool`
:param dryrun: do not create any files
:type dryrun: :class:`bool`
:param private: include \"_private\" modules
:type private: :class:`bool`
:param suffix: file suffix
:type suffix: :class:`str`
:param template_dirs: directories to search for user templates
:type template_dirs: None | :class:`list`
:returns: None
:rtype: None
:raises: OSError
"""
suffix = suffix.strip('.')
if not os.path.isdir(src):
raise OSError("%s is not a directory" % src)
if not os.path.isdir(dest) and not dryrun:
os.makedirs(dest)
src = os.path.normpath(os.path.abspath(src))
exclude = normalize_excludes(exclude)
loader = make_loader(template_dirs)
env = make_environment(loader)
recurse_tree(app, env, src, dest, exclude, followlinks, force, dryrun, private, suffix)
def main(app):
"""Parse the config of the app and initiate the generation process
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:returns: None
:rtype: None
:raises: None
"""
c = app.config
src = c.jinjaapi_srcdir
if not src:
return
suffix = "rst"
out = c.jinjaapi_outputdir or app.env.srcdir
if c.jinjaapi_addsummarytemplate:
tpath = pkg_resources.resource_filename(__package__, AUTOSUMMARYTEMPLATE_DIR)
c.templates_path.append(tpath)
tpath = pkg_resources.resource_filename(__package__, TEMPLATE_DIR)
c.templates_path.append(tpath)
prepare_dir(app, out, not c.jinjaapi_nodelete)
generate(app, src, out,
exclude=c.jinjaapi_exclude_paths,
force=c.jinjaapi_force,
followlinks=c.jinjaapi_followlinks,
dryrun=c.jinjaapi_dryrun,
private=c.jinjaapi_includeprivate,
suffix=suffix,
template_dirs=c.templates_path)
|
storax/jinjaapidoc
|
src/jinjaapidoc/gendoc.py
|
generate
|
python
|
def generate(app, src, dest, exclude=[], followlinks=False,
force=False, dryrun=False, private=False, suffix='rst',
template_dirs=None):
suffix = suffix.strip('.')
if not os.path.isdir(src):
raise OSError("%s is not a directory" % src)
if not os.path.isdir(dest) and not dryrun:
os.makedirs(dest)
src = os.path.normpath(os.path.abspath(src))
exclude = normalize_excludes(exclude)
loader = make_loader(template_dirs)
env = make_environment(loader)
recurse_tree(app, env, src, dest, exclude, followlinks, force, dryrun, private, suffix)
|
Generage the rst files
Raises an :class:`OSError` if the source path is not a directory.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param src: path to python source files
:type src: :class:`str`
:param dest: output directory
:type dest: :class:`str`
:param exclude: list of paths to exclude
:type exclude: :class:`list`
:param followlinks: follow symbolic links
:type followlinks: :class:`bool`
:param force: overwrite existing files
:type force: :class:`bool`
:param dryrun: do not create any files
:type dryrun: :class:`bool`
:param private: include \"_private\" modules
:type private: :class:`bool`
:param suffix: file suffix
:type suffix: :class:`str`
:param template_dirs: directories to search for user templates
:type template_dirs: None | :class:`list`
:returns: None
:rtype: None
:raises: OSError
|
train
|
https://github.com/storax/jinjaapidoc/blob/f1eeb6ab5bd1a96c4130306718c6423f37c76856/src/jinjaapidoc/gendoc.py#L516-L556
|
[
"def make_loader(template_dirs):\n \"\"\"Return a new :class:`jinja2.FileSystemLoader` that uses the template_dirs\n\n :param template_dirs: directories to search for templates\n :type template_dirs: None | :class:`list`\n :returns: a new loader\n :rtype: :class:`jinja2.FileSystemLoader`\n :raises: None\n \"\"\"\n return jinja2.FileSystemLoader(searchpath=template_dirs)\n",
"def make_environment(loader):\n \"\"\"Return a new :class:`jinja2.Environment` with the given loader\n\n :param loader: a jinja2 loader\n :type loader: :class:`jinja2.BaseLoader`\n :returns: a new environment\n :rtype: :class:`jinja2.Environment`\n :raises: None\n \"\"\"\n return jinja2.Environment(loader=loader)\n",
"def recurse_tree(app, env, src, dest, excludes, followlinks, force, dryrun, private, suffix):\n \"\"\"Look for every file in the directory tree and create the corresponding\n ReST files.\n\n :param app: the sphinx app\n :type app: :class:`sphinx.application.Sphinx`\n :param env: the jinja environment\n :type env: :class:`jinja2.Environment`\n :param src: the path to the python source files\n :type src: :class:`str`\n :param dest: the output directory\n :type dest: :class:`str`\n :param excludes: the paths to exclude\n :type excludes: :class:`list`\n :param followlinks: follow symbolic links\n :type followlinks: :class:`bool`\n :param force: overwrite existing files\n :type force: :class:`bool`\n :param dryrun: do not generate files\n :type dryrun: :class:`bool`\n :param private: include \"_private\" modules\n :type private: :class:`bool`\n :param suffix: the file extension\n :type suffix: :class:`str`\n \"\"\"\n # check if the base directory is a package and get its name\n if INITPY in os.listdir(src):\n root_package = src.split(os.path.sep)[-1]\n else:\n # otherwise, the base is a directory with packages\n root_package = None\n\n toplevels = []\n for root, subs, files in walk(src, followlinks=followlinks):\n # document only Python module files (that aren't excluded)\n py_files = sorted(f for f in files\n if os.path.splitext(f)[1] in PY_SUFFIXES and # noqa: W504\n not is_excluded(os.path.join(root, f), excludes))\n is_pkg = INITPY in py_files\n if is_pkg:\n py_files.remove(INITPY)\n py_files.insert(0, INITPY)\n elif root != src:\n # only accept non-package at toplevel\n del subs[:]\n continue\n # remove hidden ('.') and private ('_') directories, as well as\n # excluded dirs\n if private:\n exclude_prefixes = ('.',)\n else:\n exclude_prefixes = ('.', '_')\n subs[:] = sorted(sub for sub in subs if not sub.startswith(exclude_prefixes) and not\n is_excluded(os.path.join(root, sub), excludes))\n if is_pkg:\n # we are in a package with something to document\n if subs or len(py_files) > 1 or not \\\n shall_skip(app, os.path.join(root, INITPY), private):\n subpackage = root[len(src):].lstrip(os.path.sep).\\\n replace(os.path.sep, '.')\n create_package_file(app, env, root_package, subpackage,\n private, dest, suffix, dryrun, force)\n toplevels.append(makename(root_package, subpackage))\n else:\n # if we are at the root level, we don't require it to be a package\n assert root == src and root_package is None\n for py_file in py_files:\n if not shall_skip(app, os.path.join(src, py_file), private):\n module = os.path.splitext(py_file)[0]\n create_module_file(app, env, root_package, module, dest, suffix, dryrun, force)\n toplevels.append(module)\n return toplevels\n",
"def normalize_excludes(excludes):\n \"\"\"Normalize the excluded directory list.\"\"\"\n return [os.path.normpath(os.path.abspath(exclude)) for exclude in excludes]\n"
] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""This is a modification of sphinx.apidoc by David.Zuber.
It uses jinja templates to render the rst files.
Parses a directory tree looking for Python modules and packages and creates
ReST files appropriately to create code documentation with Sphinx.
This is derived form the "sphinx-apidoc" script, which is:
Copyright 2007-2014 by the Sphinx team, see http://sphinx-doc.org/latest/authors.html.
"""
import os
import inspect
import pkgutil
import pkg_resources
import shutil
import jinja2
from sphinx.util.osutil import walk
from sphinx.util import logging
from sphinx.ext import autosummary
logger = logging.getLogger(__name__)
INITPY = '__init__.py'
PY_SUFFIXES = set(['.py', '.pyx'])
TEMPLATE_DIR = 'templates'
"""Built-in template dir for jinjaapi rendering"""
AUTOSUMMARYTEMPLATE_DIR = 'autosummarytemplates'
"""Templates for autosummary"""
MODULE_TEMPLATE_NAME = 'jinjaapi_module.rst'
"""Name of the template that is used for rendering modules."""
PACKAGE_TEMPLATE_NAME = 'jinjaapi_package.rst'
"""Name of the template that is used for rendering packages."""
def prepare_dir(app, directory, delete=False):
"""Create apidoc dir, delete contents if delete is True.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param directory: the apidoc directory. you can use relative paths here
:type directory: str
:param delete: if True, deletes the contents of apidoc. This acts like an override switch.
:type delete: bool
:returns: None
:rtype: None
:raises: None
"""
logger.info("Preparing output directories for jinjaapidoc.")
if os.path.exists(directory):
if delete:
logger.debug("Deleting dir %s", directory)
shutil.rmtree(directory)
logger.debug("Creating dir %s", directory)
os.mkdir(directory)
else:
logger.debug("Creating %s", directory)
os.mkdir(directory)
def make_loader(template_dirs):
"""Return a new :class:`jinja2.FileSystemLoader` that uses the template_dirs
:param template_dirs: directories to search for templates
:type template_dirs: None | :class:`list`
:returns: a new loader
:rtype: :class:`jinja2.FileSystemLoader`
:raises: None
"""
return jinja2.FileSystemLoader(searchpath=template_dirs)
def make_environment(loader):
"""Return a new :class:`jinja2.Environment` with the given loader
:param loader: a jinja2 loader
:type loader: :class:`jinja2.BaseLoader`
:returns: a new environment
:rtype: :class:`jinja2.Environment`
:raises: None
"""
return jinja2.Environment(loader=loader)
def makename(package, module):
"""Join package and module with a dot.
Package or Module can be empty.
:param package: the package name
:type package: :class:`str`
:param module: the module name
:type module: :class:`str`
:returns: the joined name
:rtype: :class:`str`
:raises: :class:`AssertionError`, if both package and module are empty
"""
# Both package and module can be None/empty.
assert package or module, "Specify either package or module"
if package:
name = package
if module:
name += '.' + module
else:
name = module
return name
def write_file(app, name, text, dest, suffix, dryrun, force):
"""Write the output file for module/package <name>.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param name: the file name without file extension
:type name: :class:`str`
:param text: the content of the file
:type text: :class:`str`
:param dest: the output directory
:type dest: :class:`str`
:param suffix: the file extension
:type suffix: :class:`str`
:param dryrun: If True, do not create any files, just log the potential location.
:type dryrun: :class:`bool`
:param force: Overwrite existing files
:type force: :class:`bool`
:returns: None
:raises: None
"""
fname = os.path.join(dest, '%s.%s' % (name, suffix))
if dryrun:
logger.info('Would create file %s.' % fname)
return
if not force and os.path.isfile(fname):
logger.info('File %s already exists, skipping.' % fname)
else:
logger.info('Creating file %s.' % fname)
f = open(fname, 'w')
try:
f.write(text)
relpath = os.path.relpath(fname, start=app.env.srcdir)
abspath = os.sep + relpath
docpath = app.env.relfn2path(abspath)[0]
docpath = docpath.rsplit(os.path.extsep, 1)[0]
logger.debug('Adding document %s' % docpath)
app.env.found_docs.add(docpath)
finally:
f.close()
def import_name(app, name):
"""Import the given name and return name, obj, parent, mod_name
:param name: name to import
:type name: str
:returns: the imported object or None
:rtype: object | None
:raises: None
"""
try:
logger.debug('Importing %r', name)
name, obj = autosummary.import_by_name(name)[:2]
logger.debug('Imported %s', obj)
return obj
except ImportError as e:
logger.warn("Jinjapidoc failed to import %r: %s", name, e)
def get_members(app, mod, typ, include_public=None):
"""Return the members of mod of the given type
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param mod: the module with members
:type mod: module
:param typ: the typ, ``'class'``, ``'function'``, ``'exception'``, ``'data'``, ``'members'``
:type typ: str
:param include_public: list of private members to include to publics
:type include_public: list | None
:returns: None
:rtype: None
:raises: None
"""
def include_here(x):
"""Return true if the member should be included in mod.
A member will be included if it is declared in this module or package.
If the `jinjaapidoc_include_from_all` option is `True` then the member
can also be included if it is listed in `__all__`.
:param x: The member
:type x: A class, exception, or function.
:returns: True if the member should be included in mod. False otherwise.
:rtype: bool
"""
return (x.__module__ == mod.__name__ or (include_from_all and x.__name__ in all_list))
all_list = getattr(mod, '__all__', [])
include_from_all = app.config.jinjaapi_include_from_all
include_public = include_public or []
tests = {'class': lambda x: inspect.isclass(x) and not issubclass(x, BaseException) and include_here(x),
'function': lambda x: inspect.isfunction(x) and include_here(x),
'exception': lambda x: inspect.isclass(x) and issubclass(x, BaseException) and include_here(x),
'data': lambda x: not inspect.ismodule(x) and not inspect.isclass(x) and not inspect.isfunction(x),
'members': lambda x: True}
items = []
for name in dir(mod):
i = getattr(mod, name)
inspect.ismodule(i)
if tests.get(typ, lambda x: False)(i):
items.append(name)
public = [x for x in items
if x in include_public or not x.startswith('_')]
logger.debug('Got members of %s of type %s: public %s and %s', mod, typ, public, items)
return public, items
def _get_submodules(app, module):
"""Get all submodules for the given module/package
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param module: the module to query or module path
:type module: module | str
:returns: list of module names and boolean whether its a package
:rtype: list
:raises: TypeError
"""
if inspect.ismodule(module):
if hasattr(module, '__path__'):
p = module.__path__
else:
return []
elif isinstance(module, str):
p = module
else:
raise TypeError("Only Module or String accepted. %s given." % type(module))
logger.debug('Getting submodules of %s', p)
submodules = [(name, ispkg) for loader, name, ispkg in pkgutil.iter_modules(p)]
logger.debug('Found submodules of %s: %s', module, submodules)
return submodules
def get_submodules(app, module):
"""Get all submodules without packages for the given module/package
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param module: the module to query or module path
:type module: module | str
:returns: list of module names excluding packages
:rtype: list
:raises: TypeError
"""
submodules = _get_submodules(app, module)
return [name for name, ispkg in submodules if not ispkg]
def get_subpackages(app, module):
"""Get all subpackages for the given module/package
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param module: the module to query or module path
:type module: module | str
:returns: list of packages names
:rtype: list
:raises: TypeError
"""
submodules = _get_submodules(app, module)
return [name for name, ispkg in submodules if ispkg]
def get_context(app, package, module, fullname):
"""Return a dict for template rendering
Variables:
* :package: The top package
* :module: the module
* :fullname: package.module
* :subpkgs: packages beneath module
* :submods: modules beneath module
* :classes: public classes in module
* :allclasses: public and private classes in module
* :exceptions: public exceptions in module
* :allexceptions: public and private exceptions in module
* :functions: public functions in module
* :allfunctions: public and private functions in module
* :data: public data in module
* :alldata: public and private data in module
* :members: dir(module)
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param package: the parent package name
:type package: str
:param module: the module name
:type module: str
:param fullname: package.module
:type fullname: str
:returns: a dict with variables for template rendering
:rtype: :class:`dict`
:raises: None
"""
var = {'package': package,
'module': module,
'fullname': fullname}
logger.debug('Creating context for: package %s, module %s, fullname %s', package, module, fullname)
obj = import_name(app, fullname)
if not obj:
for k in ('subpkgs', 'submods', 'classes', 'allclasses',
'exceptions', 'allexceptions', 'functions', 'allfunctions',
'data', 'alldata', 'memebers'):
var[k] = []
return var
var['subpkgs'] = get_subpackages(app, obj)
var['submods'] = get_submodules(app, obj)
var['classes'], var['allclasses'] = get_members(app, obj, 'class')
var['exceptions'], var['allexceptions'] = get_members(app, obj, 'exception')
var['functions'], var['allfunctions'] = get_members(app, obj, 'function')
var['data'], var['alldata'] = get_members(app, obj, 'data')
var['members'] = get_members(app, obj, 'members')
logger.debug('Created context: %s', var)
return var
def create_module_file(app, env, package, module, dest, suffix, dryrun, force):
"""Build the text of the file and write the file.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param env: the jinja environment for the templates
:type env: :class:`jinja2.Environment`
:param package: the package name
:type package: :class:`str`
:param module: the module name
:type module: :class:`str`
:param dest: the output directory
:type dest: :class:`str`
:param suffix: the file extension
:type suffix: :class:`str`
:param dryrun: If True, do not create any files, just log the potential location.
:type dryrun: :class:`bool`
:param force: Overwrite existing files
:type force: :class:`bool`
:returns: None
:raises: None
"""
logger.debug('Create module file: package %s, module %s', package, module)
template_file = MODULE_TEMPLATE_NAME
template = env.get_template(template_file)
fn = makename(package, module)
var = get_context(app, package, module, fn)
var['ispkg'] = False
rendered = template.render(var)
write_file(app, makename(package, module), rendered, dest, suffix, dryrun, force)
def create_package_file(app, env, root_package, sub_package, private,
dest, suffix, dryrun, force):
"""Build the text of the file and write the file.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param env: the jinja environment for the templates
:type env: :class:`jinja2.Environment`
:param root_package: the parent package
:type root_package: :class:`str`
:param sub_package: the package name without root
:type sub_package: :class:`str`
:param private: Include \"_private\" modules
:type private: :class:`bool`
:param dest: the output directory
:type dest: :class:`str`
:param suffix: the file extension
:type suffix: :class:`str`
:param dryrun: If True, do not create any files, just log the potential location.
:type dryrun: :class:`bool`
:param force: Overwrite existing files
:type force: :class:`bool`
:returns: None
:raises: None
"""
logger.debug('Create package file: rootpackage %s, sub_package %s', root_package, sub_package)
template_file = PACKAGE_TEMPLATE_NAME
template = env.get_template(template_file)
fn = makename(root_package, sub_package)
var = get_context(app, root_package, sub_package, fn)
var['ispkg'] = True
for submod in var['submods']:
if shall_skip(app, submod, private):
continue
create_module_file(app, env, fn, submod, dest, suffix, dryrun, force)
rendered = template.render(var)
write_file(app, fn, rendered, dest, suffix, dryrun, force)
def shall_skip(app, module, private):
"""Check if we want to skip this module.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param module: the module name
:type module: :class:`str`
:param private: True, if privates are allowed
:type private: :class:`bool`
"""
logger.debug('Testing if %s should be skipped.', module)
# skip if it has a "private" name and this is selected
if module != '__init__.py' and module.startswith('_') and \
not private:
logger.debug('Skip %s because its either private or __init__.', module)
return True
logger.debug('Do not skip %s', module)
return False
def recurse_tree(app, env, src, dest, excludes, followlinks, force, dryrun, private, suffix):
"""Look for every file in the directory tree and create the corresponding
ReST files.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param env: the jinja environment
:type env: :class:`jinja2.Environment`
:param src: the path to the python source files
:type src: :class:`str`
:param dest: the output directory
:type dest: :class:`str`
:param excludes: the paths to exclude
:type excludes: :class:`list`
:param followlinks: follow symbolic links
:type followlinks: :class:`bool`
:param force: overwrite existing files
:type force: :class:`bool`
:param dryrun: do not generate files
:type dryrun: :class:`bool`
:param private: include "_private" modules
:type private: :class:`bool`
:param suffix: the file extension
:type suffix: :class:`str`
"""
# check if the base directory is a package and get its name
if INITPY in os.listdir(src):
root_package = src.split(os.path.sep)[-1]
else:
# otherwise, the base is a directory with packages
root_package = None
toplevels = []
for root, subs, files in walk(src, followlinks=followlinks):
# document only Python module files (that aren't excluded)
py_files = sorted(f for f in files
if os.path.splitext(f)[1] in PY_SUFFIXES and # noqa: W504
not is_excluded(os.path.join(root, f), excludes))
is_pkg = INITPY in py_files
if is_pkg:
py_files.remove(INITPY)
py_files.insert(0, INITPY)
elif root != src:
# only accept non-package at toplevel
del subs[:]
continue
# remove hidden ('.') and private ('_') directories, as well as
# excluded dirs
if private:
exclude_prefixes = ('.',)
else:
exclude_prefixes = ('.', '_')
subs[:] = sorted(sub for sub in subs if not sub.startswith(exclude_prefixes) and not
is_excluded(os.path.join(root, sub), excludes))
if is_pkg:
# we are in a package with something to document
if subs or len(py_files) > 1 or not \
shall_skip(app, os.path.join(root, INITPY), private):
subpackage = root[len(src):].lstrip(os.path.sep).\
replace(os.path.sep, '.')
create_package_file(app, env, root_package, subpackage,
private, dest, suffix, dryrun, force)
toplevels.append(makename(root_package, subpackage))
else:
# if we are at the root level, we don't require it to be a package
assert root == src and root_package is None
for py_file in py_files:
if not shall_skip(app, os.path.join(src, py_file), private):
module = os.path.splitext(py_file)[0]
create_module_file(app, env, root_package, module, dest, suffix, dryrun, force)
toplevels.append(module)
return toplevels
def normalize_excludes(excludes):
"""Normalize the excluded directory list."""
return [os.path.normpath(os.path.abspath(exclude)) for exclude in excludes]
def is_excluded(root, excludes):
"""Check if the directory is in the exclude list.
Note: by having trailing slashes, we avoid common prefix issues, like
e.g. an exlude "foo" also accidentally excluding "foobar".
"""
root = os.path.normpath(root)
for exclude in excludes:
if root == exclude:
return True
return False
def main(app):
"""Parse the config of the app and initiate the generation process
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:returns: None
:rtype: None
:raises: None
"""
c = app.config
src = c.jinjaapi_srcdir
if not src:
return
suffix = "rst"
out = c.jinjaapi_outputdir or app.env.srcdir
if c.jinjaapi_addsummarytemplate:
tpath = pkg_resources.resource_filename(__package__, AUTOSUMMARYTEMPLATE_DIR)
c.templates_path.append(tpath)
tpath = pkg_resources.resource_filename(__package__, TEMPLATE_DIR)
c.templates_path.append(tpath)
prepare_dir(app, out, not c.jinjaapi_nodelete)
generate(app, src, out,
exclude=c.jinjaapi_exclude_paths,
force=c.jinjaapi_force,
followlinks=c.jinjaapi_followlinks,
dryrun=c.jinjaapi_dryrun,
private=c.jinjaapi_includeprivate,
suffix=suffix,
template_dirs=c.templates_path)
|
storax/jinjaapidoc
|
src/jinjaapidoc/gendoc.py
|
main
|
python
|
def main(app):
c = app.config
src = c.jinjaapi_srcdir
if not src:
return
suffix = "rst"
out = c.jinjaapi_outputdir or app.env.srcdir
if c.jinjaapi_addsummarytemplate:
tpath = pkg_resources.resource_filename(__package__, AUTOSUMMARYTEMPLATE_DIR)
c.templates_path.append(tpath)
tpath = pkg_resources.resource_filename(__package__, TEMPLATE_DIR)
c.templates_path.append(tpath)
prepare_dir(app, out, not c.jinjaapi_nodelete)
generate(app, src, out,
exclude=c.jinjaapi_exclude_paths,
force=c.jinjaapi_force,
followlinks=c.jinjaapi_followlinks,
dryrun=c.jinjaapi_dryrun,
private=c.jinjaapi_includeprivate,
suffix=suffix,
template_dirs=c.templates_path)
|
Parse the config of the app and initiate the generation process
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:returns: None
:rtype: None
:raises: None
|
train
|
https://github.com/storax/jinjaapidoc/blob/f1eeb6ab5bd1a96c4130306718c6423f37c76856/src/jinjaapidoc/gendoc.py#L559-L593
|
[
"def prepare_dir(app, directory, delete=False):\n \"\"\"Create apidoc dir, delete contents if delete is True.\n\n :param app: the sphinx app\n :type app: :class:`sphinx.application.Sphinx`\n :param directory: the apidoc directory. you can use relative paths here\n :type directory: str\n :param delete: if True, deletes the contents of apidoc. This acts like an override switch.\n :type delete: bool\n :returns: None\n :rtype: None\n :raises: None\n \"\"\"\n logger.info(\"Preparing output directories for jinjaapidoc.\")\n if os.path.exists(directory):\n if delete:\n logger.debug(\"Deleting dir %s\", directory)\n shutil.rmtree(directory)\n logger.debug(\"Creating dir %s\", directory)\n os.mkdir(directory)\n else:\n logger.debug(\"Creating %s\", directory)\n os.mkdir(directory)\n",
"def generate(app, src, dest, exclude=[], followlinks=False,\n force=False, dryrun=False, private=False, suffix='rst',\n template_dirs=None):\n \"\"\"Generage the rst files\n\n Raises an :class:`OSError` if the source path is not a directory.\n\n :param app: the sphinx app\n :type app: :class:`sphinx.application.Sphinx`\n :param src: path to python source files\n :type src: :class:`str`\n :param dest: output directory\n :type dest: :class:`str`\n :param exclude: list of paths to exclude\n :type exclude: :class:`list`\n :param followlinks: follow symbolic links\n :type followlinks: :class:`bool`\n :param force: overwrite existing files\n :type force: :class:`bool`\n :param dryrun: do not create any files\n :type dryrun: :class:`bool`\n :param private: include \\\"_private\\\" modules\n :type private: :class:`bool`\n :param suffix: file suffix\n :type suffix: :class:`str`\n :param template_dirs: directories to search for user templates\n :type template_dirs: None | :class:`list`\n :returns: None\n :rtype: None\n :raises: OSError\n \"\"\"\n suffix = suffix.strip('.')\n if not os.path.isdir(src):\n raise OSError(\"%s is not a directory\" % src)\n if not os.path.isdir(dest) and not dryrun:\n os.makedirs(dest)\n src = os.path.normpath(os.path.abspath(src))\n exclude = normalize_excludes(exclude)\n loader = make_loader(template_dirs)\n env = make_environment(loader)\n recurse_tree(app, env, src, dest, exclude, followlinks, force, dryrun, private, suffix)\n"
] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""This is a modification of sphinx.apidoc by David.Zuber.
It uses jinja templates to render the rst files.
Parses a directory tree looking for Python modules and packages and creates
ReST files appropriately to create code documentation with Sphinx.
This is derived form the "sphinx-apidoc" script, which is:
Copyright 2007-2014 by the Sphinx team, see http://sphinx-doc.org/latest/authors.html.
"""
import os
import inspect
import pkgutil
import pkg_resources
import shutil
import jinja2
from sphinx.util.osutil import walk
from sphinx.util import logging
from sphinx.ext import autosummary
logger = logging.getLogger(__name__)
INITPY = '__init__.py'
PY_SUFFIXES = set(['.py', '.pyx'])
TEMPLATE_DIR = 'templates'
"""Built-in template dir for jinjaapi rendering"""
AUTOSUMMARYTEMPLATE_DIR = 'autosummarytemplates'
"""Templates for autosummary"""
MODULE_TEMPLATE_NAME = 'jinjaapi_module.rst'
"""Name of the template that is used for rendering modules."""
PACKAGE_TEMPLATE_NAME = 'jinjaapi_package.rst'
"""Name of the template that is used for rendering packages."""
def prepare_dir(app, directory, delete=False):
"""Create apidoc dir, delete contents if delete is True.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param directory: the apidoc directory. you can use relative paths here
:type directory: str
:param delete: if True, deletes the contents of apidoc. This acts like an override switch.
:type delete: bool
:returns: None
:rtype: None
:raises: None
"""
logger.info("Preparing output directories for jinjaapidoc.")
if os.path.exists(directory):
if delete:
logger.debug("Deleting dir %s", directory)
shutil.rmtree(directory)
logger.debug("Creating dir %s", directory)
os.mkdir(directory)
else:
logger.debug("Creating %s", directory)
os.mkdir(directory)
def make_loader(template_dirs):
"""Return a new :class:`jinja2.FileSystemLoader` that uses the template_dirs
:param template_dirs: directories to search for templates
:type template_dirs: None | :class:`list`
:returns: a new loader
:rtype: :class:`jinja2.FileSystemLoader`
:raises: None
"""
return jinja2.FileSystemLoader(searchpath=template_dirs)
def make_environment(loader):
"""Return a new :class:`jinja2.Environment` with the given loader
:param loader: a jinja2 loader
:type loader: :class:`jinja2.BaseLoader`
:returns: a new environment
:rtype: :class:`jinja2.Environment`
:raises: None
"""
return jinja2.Environment(loader=loader)
def makename(package, module):
"""Join package and module with a dot.
Package or Module can be empty.
:param package: the package name
:type package: :class:`str`
:param module: the module name
:type module: :class:`str`
:returns: the joined name
:rtype: :class:`str`
:raises: :class:`AssertionError`, if both package and module are empty
"""
# Both package and module can be None/empty.
assert package or module, "Specify either package or module"
if package:
name = package
if module:
name += '.' + module
else:
name = module
return name
def write_file(app, name, text, dest, suffix, dryrun, force):
"""Write the output file for module/package <name>.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param name: the file name without file extension
:type name: :class:`str`
:param text: the content of the file
:type text: :class:`str`
:param dest: the output directory
:type dest: :class:`str`
:param suffix: the file extension
:type suffix: :class:`str`
:param dryrun: If True, do not create any files, just log the potential location.
:type dryrun: :class:`bool`
:param force: Overwrite existing files
:type force: :class:`bool`
:returns: None
:raises: None
"""
fname = os.path.join(dest, '%s.%s' % (name, suffix))
if dryrun:
logger.info('Would create file %s.' % fname)
return
if not force and os.path.isfile(fname):
logger.info('File %s already exists, skipping.' % fname)
else:
logger.info('Creating file %s.' % fname)
f = open(fname, 'w')
try:
f.write(text)
relpath = os.path.relpath(fname, start=app.env.srcdir)
abspath = os.sep + relpath
docpath = app.env.relfn2path(abspath)[0]
docpath = docpath.rsplit(os.path.extsep, 1)[0]
logger.debug('Adding document %s' % docpath)
app.env.found_docs.add(docpath)
finally:
f.close()
def import_name(app, name):
"""Import the given name and return name, obj, parent, mod_name
:param name: name to import
:type name: str
:returns: the imported object or None
:rtype: object | None
:raises: None
"""
try:
logger.debug('Importing %r', name)
name, obj = autosummary.import_by_name(name)[:2]
logger.debug('Imported %s', obj)
return obj
except ImportError as e:
logger.warn("Jinjapidoc failed to import %r: %s", name, e)
def get_members(app, mod, typ, include_public=None):
"""Return the members of mod of the given type
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param mod: the module with members
:type mod: module
:param typ: the typ, ``'class'``, ``'function'``, ``'exception'``, ``'data'``, ``'members'``
:type typ: str
:param include_public: list of private members to include to publics
:type include_public: list | None
:returns: None
:rtype: None
:raises: None
"""
def include_here(x):
"""Return true if the member should be included in mod.
A member will be included if it is declared in this module or package.
If the `jinjaapidoc_include_from_all` option is `True` then the member
can also be included if it is listed in `__all__`.
:param x: The member
:type x: A class, exception, or function.
:returns: True if the member should be included in mod. False otherwise.
:rtype: bool
"""
return (x.__module__ == mod.__name__ or (include_from_all and x.__name__ in all_list))
all_list = getattr(mod, '__all__', [])
include_from_all = app.config.jinjaapi_include_from_all
include_public = include_public or []
tests = {'class': lambda x: inspect.isclass(x) and not issubclass(x, BaseException) and include_here(x),
'function': lambda x: inspect.isfunction(x) and include_here(x),
'exception': lambda x: inspect.isclass(x) and issubclass(x, BaseException) and include_here(x),
'data': lambda x: not inspect.ismodule(x) and not inspect.isclass(x) and not inspect.isfunction(x),
'members': lambda x: True}
items = []
for name in dir(mod):
i = getattr(mod, name)
inspect.ismodule(i)
if tests.get(typ, lambda x: False)(i):
items.append(name)
public = [x for x in items
if x in include_public or not x.startswith('_')]
logger.debug('Got members of %s of type %s: public %s and %s', mod, typ, public, items)
return public, items
def _get_submodules(app, module):
"""Get all submodules for the given module/package
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param module: the module to query or module path
:type module: module | str
:returns: list of module names and boolean whether its a package
:rtype: list
:raises: TypeError
"""
if inspect.ismodule(module):
if hasattr(module, '__path__'):
p = module.__path__
else:
return []
elif isinstance(module, str):
p = module
else:
raise TypeError("Only Module or String accepted. %s given." % type(module))
logger.debug('Getting submodules of %s', p)
submodules = [(name, ispkg) for loader, name, ispkg in pkgutil.iter_modules(p)]
logger.debug('Found submodules of %s: %s', module, submodules)
return submodules
def get_submodules(app, module):
"""Get all submodules without packages for the given module/package
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param module: the module to query or module path
:type module: module | str
:returns: list of module names excluding packages
:rtype: list
:raises: TypeError
"""
submodules = _get_submodules(app, module)
return [name for name, ispkg in submodules if not ispkg]
def get_subpackages(app, module):
"""Get all subpackages for the given module/package
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param module: the module to query or module path
:type module: module | str
:returns: list of packages names
:rtype: list
:raises: TypeError
"""
submodules = _get_submodules(app, module)
return [name for name, ispkg in submodules if ispkg]
def get_context(app, package, module, fullname):
"""Return a dict for template rendering
Variables:
* :package: The top package
* :module: the module
* :fullname: package.module
* :subpkgs: packages beneath module
* :submods: modules beneath module
* :classes: public classes in module
* :allclasses: public and private classes in module
* :exceptions: public exceptions in module
* :allexceptions: public and private exceptions in module
* :functions: public functions in module
* :allfunctions: public and private functions in module
* :data: public data in module
* :alldata: public and private data in module
* :members: dir(module)
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param package: the parent package name
:type package: str
:param module: the module name
:type module: str
:param fullname: package.module
:type fullname: str
:returns: a dict with variables for template rendering
:rtype: :class:`dict`
:raises: None
"""
var = {'package': package,
'module': module,
'fullname': fullname}
logger.debug('Creating context for: package %s, module %s, fullname %s', package, module, fullname)
obj = import_name(app, fullname)
if not obj:
for k in ('subpkgs', 'submods', 'classes', 'allclasses',
'exceptions', 'allexceptions', 'functions', 'allfunctions',
'data', 'alldata', 'memebers'):
var[k] = []
return var
var['subpkgs'] = get_subpackages(app, obj)
var['submods'] = get_submodules(app, obj)
var['classes'], var['allclasses'] = get_members(app, obj, 'class')
var['exceptions'], var['allexceptions'] = get_members(app, obj, 'exception')
var['functions'], var['allfunctions'] = get_members(app, obj, 'function')
var['data'], var['alldata'] = get_members(app, obj, 'data')
var['members'] = get_members(app, obj, 'members')
logger.debug('Created context: %s', var)
return var
def create_module_file(app, env, package, module, dest, suffix, dryrun, force):
"""Build the text of the file and write the file.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param env: the jinja environment for the templates
:type env: :class:`jinja2.Environment`
:param package: the package name
:type package: :class:`str`
:param module: the module name
:type module: :class:`str`
:param dest: the output directory
:type dest: :class:`str`
:param suffix: the file extension
:type suffix: :class:`str`
:param dryrun: If True, do not create any files, just log the potential location.
:type dryrun: :class:`bool`
:param force: Overwrite existing files
:type force: :class:`bool`
:returns: None
:raises: None
"""
logger.debug('Create module file: package %s, module %s', package, module)
template_file = MODULE_TEMPLATE_NAME
template = env.get_template(template_file)
fn = makename(package, module)
var = get_context(app, package, module, fn)
var['ispkg'] = False
rendered = template.render(var)
write_file(app, makename(package, module), rendered, dest, suffix, dryrun, force)
def create_package_file(app, env, root_package, sub_package, private,
dest, suffix, dryrun, force):
"""Build the text of the file and write the file.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param env: the jinja environment for the templates
:type env: :class:`jinja2.Environment`
:param root_package: the parent package
:type root_package: :class:`str`
:param sub_package: the package name without root
:type sub_package: :class:`str`
:param private: Include \"_private\" modules
:type private: :class:`bool`
:param dest: the output directory
:type dest: :class:`str`
:param suffix: the file extension
:type suffix: :class:`str`
:param dryrun: If True, do not create any files, just log the potential location.
:type dryrun: :class:`bool`
:param force: Overwrite existing files
:type force: :class:`bool`
:returns: None
:raises: None
"""
logger.debug('Create package file: rootpackage %s, sub_package %s', root_package, sub_package)
template_file = PACKAGE_TEMPLATE_NAME
template = env.get_template(template_file)
fn = makename(root_package, sub_package)
var = get_context(app, root_package, sub_package, fn)
var['ispkg'] = True
for submod in var['submods']:
if shall_skip(app, submod, private):
continue
create_module_file(app, env, fn, submod, dest, suffix, dryrun, force)
rendered = template.render(var)
write_file(app, fn, rendered, dest, suffix, dryrun, force)
def shall_skip(app, module, private):
"""Check if we want to skip this module.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param module: the module name
:type module: :class:`str`
:param private: True, if privates are allowed
:type private: :class:`bool`
"""
logger.debug('Testing if %s should be skipped.', module)
# skip if it has a "private" name and this is selected
if module != '__init__.py' and module.startswith('_') and \
not private:
logger.debug('Skip %s because its either private or __init__.', module)
return True
logger.debug('Do not skip %s', module)
return False
def recurse_tree(app, env, src, dest, excludes, followlinks, force, dryrun, private, suffix):
"""Look for every file in the directory tree and create the corresponding
ReST files.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param env: the jinja environment
:type env: :class:`jinja2.Environment`
:param src: the path to the python source files
:type src: :class:`str`
:param dest: the output directory
:type dest: :class:`str`
:param excludes: the paths to exclude
:type excludes: :class:`list`
:param followlinks: follow symbolic links
:type followlinks: :class:`bool`
:param force: overwrite existing files
:type force: :class:`bool`
:param dryrun: do not generate files
:type dryrun: :class:`bool`
:param private: include "_private" modules
:type private: :class:`bool`
:param suffix: the file extension
:type suffix: :class:`str`
"""
# check if the base directory is a package and get its name
if INITPY in os.listdir(src):
root_package = src.split(os.path.sep)[-1]
else:
# otherwise, the base is a directory with packages
root_package = None
toplevels = []
for root, subs, files in walk(src, followlinks=followlinks):
# document only Python module files (that aren't excluded)
py_files = sorted(f for f in files
if os.path.splitext(f)[1] in PY_SUFFIXES and # noqa: W504
not is_excluded(os.path.join(root, f), excludes))
is_pkg = INITPY in py_files
if is_pkg:
py_files.remove(INITPY)
py_files.insert(0, INITPY)
elif root != src:
# only accept non-package at toplevel
del subs[:]
continue
# remove hidden ('.') and private ('_') directories, as well as
# excluded dirs
if private:
exclude_prefixes = ('.',)
else:
exclude_prefixes = ('.', '_')
subs[:] = sorted(sub for sub in subs if not sub.startswith(exclude_prefixes) and not
is_excluded(os.path.join(root, sub), excludes))
if is_pkg:
# we are in a package with something to document
if subs or len(py_files) > 1 or not \
shall_skip(app, os.path.join(root, INITPY), private):
subpackage = root[len(src):].lstrip(os.path.sep).\
replace(os.path.sep, '.')
create_package_file(app, env, root_package, subpackage,
private, dest, suffix, dryrun, force)
toplevels.append(makename(root_package, subpackage))
else:
# if we are at the root level, we don't require it to be a package
assert root == src and root_package is None
for py_file in py_files:
if not shall_skip(app, os.path.join(src, py_file), private):
module = os.path.splitext(py_file)[0]
create_module_file(app, env, root_package, module, dest, suffix, dryrun, force)
toplevels.append(module)
return toplevels
def normalize_excludes(excludes):
"""Normalize the excluded directory list."""
return [os.path.normpath(os.path.abspath(exclude)) for exclude in excludes]
def is_excluded(root, excludes):
"""Check if the directory is in the exclude list.
Note: by having trailing slashes, we avoid common prefix issues, like
e.g. an exlude "foo" also accidentally excluding "foobar".
"""
root = os.path.normpath(root)
for exclude in excludes:
if root == exclude:
return True
return False
def generate(app, src, dest, exclude=[], followlinks=False,
force=False, dryrun=False, private=False, suffix='rst',
template_dirs=None):
"""Generage the rst files
Raises an :class:`OSError` if the source path is not a directory.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param src: path to python source files
:type src: :class:`str`
:param dest: output directory
:type dest: :class:`str`
:param exclude: list of paths to exclude
:type exclude: :class:`list`
:param followlinks: follow symbolic links
:type followlinks: :class:`bool`
:param force: overwrite existing files
:type force: :class:`bool`
:param dryrun: do not create any files
:type dryrun: :class:`bool`
:param private: include \"_private\" modules
:type private: :class:`bool`
:param suffix: file suffix
:type suffix: :class:`str`
:param template_dirs: directories to search for user templates
:type template_dirs: None | :class:`list`
:returns: None
:rtype: None
:raises: OSError
"""
suffix = suffix.strip('.')
if not os.path.isdir(src):
raise OSError("%s is not a directory" % src)
if not os.path.isdir(dest) and not dryrun:
os.makedirs(dest)
src = os.path.normpath(os.path.abspath(src))
exclude = normalize_excludes(exclude)
loader = make_loader(template_dirs)
env = make_environment(loader)
recurse_tree(app, env, src, dest, exclude, followlinks, force, dryrun, private, suffix)
|
storax/jinjaapidoc
|
src/jinjaapidoc/__init__.py
|
setup
|
python
|
def setup(app):
"""Setup the sphinx extension
This will setup autodoc and autosummary.
Add the :class:`ext.ModDocstringDocumenter`.
Add the config values.
Connect builder-inited event to :func:`gendoc.main`.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:returns: None
:rtype: None
:raises: None
"""
# Connect before autosummary
app.connect('builder-inited', gendoc.main)
app.setup_extension('sphinx.ext.autodoc')
app.setup_extension('sphinx.ext.autosummary')
app.add_autodocumenter(ext.ModDocstringDocumenter)
app.add_config_value('jinjaapi_outputdir', '', 'env')
app.add_config_value('jinjaapi_nodelete', True, 'env')
app.add_config_value('jinjaapi_srcdir', '', 'env')
app.add_config_value('jinjaapi_exclude_paths', [], 'env')
app.add_config_value('jinjaapi_force', True, 'env')
app.add_config_value('jinjaapi_followlinks', True, 'env')
app.add_config_value('jinjaapi_dryrun', False, 'env')
app.add_config_value('jinjaapi_includeprivate', True, 'env')
app.add_config_value('jinjaapi_addsummarytemplate', True, 'env')
app.add_config_value('jinjaapi_include_from_all', True, 'env')
return {'version': __version__, 'parallel_read_safe': True}
|
Setup the sphinx extension
This will setup autodoc and autosummary.
Add the :class:`ext.ModDocstringDocumenter`.
Add the config values.
Connect builder-inited event to :func:`gendoc.main`.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:returns: None
:rtype: None
:raises: None
|
train
|
https://github.com/storax/jinjaapidoc/blob/f1eeb6ab5bd1a96c4130306718c6423f37c76856/src/jinjaapidoc/__init__.py#L9-L42
| null |
import jinjaapidoc.ext as ext
import jinjaapidoc.gendoc as gendoc
__author__ = 'David Zuber'
__email__ = 'zuber.david@gmx.de'
__version__ = '0.5.0'
def setup(app):
"""Setup the sphinx extension
This will setup autodoc and autosummary.
Add the :class:`ext.ModDocstringDocumenter`.
Add the config values.
Connect builder-inited event to :func:`gendoc.main`.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:returns: None
:rtype: None
:raises: None
"""
# Connect before autosummary
app.connect('builder-inited', gendoc.main)
app.setup_extension('sphinx.ext.autodoc')
app.setup_extension('sphinx.ext.autosummary')
app.add_autodocumenter(ext.ModDocstringDocumenter)
app.add_config_value('jinjaapi_outputdir', '', 'env')
app.add_config_value('jinjaapi_nodelete', True, 'env')
app.add_config_value('jinjaapi_srcdir', '', 'env')
app.add_config_value('jinjaapi_exclude_paths', [], 'env')
app.add_config_value('jinjaapi_force', True, 'env')
app.add_config_value('jinjaapi_followlinks', True, 'env')
app.add_config_value('jinjaapi_dryrun', False, 'env')
app.add_config_value('jinjaapi_includeprivate', True, 'env')
app.add_config_value('jinjaapi_addsummarytemplate', True, 'env')
app.add_config_value('jinjaapi_include_from_all', True, 'env')
return {'version': __version__, 'parallel_read_safe': True}
|
storax/jinjaapidoc
|
src/jinjaapidoc/ext.py
|
ModDocstringDocumenter.add_directive_header
|
python
|
def add_directive_header(self, sig):
domain = getattr(self, 'domain', 'py')
directive = getattr(self, 'directivetype', "module")
name = self.format_name()
self.add_line(u'.. %s:%s:: %s%s' % (domain, directive, name, sig),
'<autodoc>')
if self.options.noindex:
self.add_line(u' :noindex:', '<autodoc>')
if self.objpath:
# Be explicit about the module, this is necessary since .. class::
# etc. don't support a prepended module name
self.add_line(u' :module: %s' % self.modname, '<autodoc>')
|
Add the directive header and options to the generated content.
|
train
|
https://github.com/storax/jinjaapidoc/blob/f1eeb6ab5bd1a96c4130306718c6423f37c76856/src/jinjaapidoc/ext.py#L13-L25
| null |
class ModDocstringDocumenter(autodoc.ModuleDocumenter):
"""A documenter for modules which only inserts the docstring of the module."""
objtype = "moddoconly"
# do not indent the content
content_indent = ""
# do not add a header to the docstring
def document_members(self, all_members=False):
pass
|
stephantul/reach
|
reach/reach.py
|
Reach.load
|
python
|
def load(pathtovector,
wordlist=(),
num_to_load=None,
truncate_embeddings=None,
unk_word=None,
sep=" "):
r"""
Read a file in word2vec .txt format.
The load function will raise a ValueError when trying to load items
which do not conform to line lengths.
Parameters
----------
pathtovector : string
The path to the vector file.
header : bool
Whether the vector file has a header of the type
(NUMBER OF ITEMS, SIZE OF VECTOR).
wordlist : iterable, optional, default ()
A list of words you want loaded from the vector file. If this is
None (default), all words will be loaded.
num_to_load : int, optional, default None
The number of items to load from the file. Because loading can take
some time, it is sometimes useful to onlyl load the first n items
from a vector file for quick inspection.
truncate_embeddings : int, optional, default None
If this value is not None, the vectors in the vector space will
be truncated to the number of dimensions indicated by this value.
unk_word : object
The object to treat as UNK in your vector space. If this is not
in your items dictionary after loading, we add it with a zero
vector.
Returns
-------
r : Reach
An initialized Reach instance.
"""
vectors, items = Reach._load(pathtovector,
wordlist,
num_to_load,
truncate_embeddings,
sep)
if unk_word is not None:
if unk_word not in set(items):
unk_vec = np.zeros((1, vectors.shape[1]))
vectors = np.concatenate([unk_vec, vectors], 0)
items = [unk_word] + items
unk_index = 0
else:
unk_index = items.index(unk_word)
else:
unk_index = None
return Reach(vectors,
items,
name=os.path.split(pathtovector)[-1],
unk_index=unk_index)
|
r"""
Read a file in word2vec .txt format.
The load function will raise a ValueError when trying to load items
which do not conform to line lengths.
Parameters
----------
pathtovector : string
The path to the vector file.
header : bool
Whether the vector file has a header of the type
(NUMBER OF ITEMS, SIZE OF VECTOR).
wordlist : iterable, optional, default ()
A list of words you want loaded from the vector file. If this is
None (default), all words will be loaded.
num_to_load : int, optional, default None
The number of items to load from the file. Because loading can take
some time, it is sometimes useful to onlyl load the first n items
from a vector file for quick inspection.
truncate_embeddings : int, optional, default None
If this value is not None, the vectors in the vector space will
be truncated to the number of dimensions indicated by this value.
unk_word : object
The object to treat as UNK in your vector space. If this is not
in your items dictionary after loading, we add it with a zero
vector.
Returns
-------
r : Reach
An initialized Reach instance.
|
train
|
https://github.com/stephantul/reach/blob/e5ed0cc895d17429e797c6d7dd57bce82ff00d5d/reach/reach.py#L74-L133
|
[
"def _load(pathtovector,\n wordlist,\n num_to_load=None,\n truncate_embeddings=None,\n sep=\" \"):\n \"\"\"Load a matrix and wordlist from a .vec file.\"\"\"\n vectors = []\n addedwords = set()\n words = []\n\n try:\n wordlist = set(wordlist)\n except ValueError:\n wordlist = set()\n\n logger.info(\"Loading {0}\".format(pathtovector))\n\n firstline = open(pathtovector).readline().strip()\n try:\n num, size = firstline.split(sep)\n num, size = int(num), int(size)\n logger.info(\"Vector space: {} by {}\".format(num, size))\n header = True\n except ValueError:\n size = len(firstline.split(sep)) - 1\n logger.info(\"Vector space: {} dim, # items unknown\".format(size))\n word, rest = firstline.split(sep, 1)\n # If the first line is correctly parseable, set header to False.\n header = False\n\n if truncate_embeddings is None or truncate_embeddings == 0:\n truncate_embeddings = size\n\n for idx, line in enumerate(open(pathtovector, encoding='utf-8')):\n\n if header and idx == 0:\n continue\n\n word, rest = line.rstrip(\" \\n\").split(sep, 1)\n\n if wordlist and word not in wordlist:\n continue\n\n if word in addedwords:\n raise ValueError(\"Duplicate: {} on line {} was in the \"\n \"vector space twice\".format(word, idx))\n\n if len(rest.split(sep)) != size:\n raise ValueError(\"Incorrect input at index {}, size \"\n \"is {}, expected \"\n \"{}\".format(idx+1,\n len(rest.split(sep)), size))\n\n words.append(word)\n addedwords.add(word)\n vectors.append(np.fromstring(rest, sep=sep)[:truncate_embeddings])\n\n if num_to_load is not None and len(addedwords) >= num_to_load:\n break\n\n vectors = np.array(vectors).astype(np.float32)\n\n logger.info(\"Loading finished\")\n if wordlist:\n diff = wordlist - addedwords\n if diff:\n logger.info(\"Not all items from your wordlist were in your \"\n \"vector space: {}.\".format(diff))\n\n return vectors, words\n"
] |
class Reach(object):
"""
Work with vector representations of items.
Supports functions for calculating fast batched similarity
between items or composite representations of items.
Parameters
----------
vectors : numpy array
The vector space.
items : list
A list of items. Length must be equal to the number of vectors, and
aligned with the vectors.
name : string, optional
A string giving the name of the current reach. Only useful if you
have multiple spaces and want to keep track of them.
Attributes
----------
items : dict
A mapping from items to ids.
indices : dict
A mapping from ids to items.
vectors : numpy array
The array representing the vector space.
norm_vectors : numpy array
A normalized version of the vector space.
unk_index : int
The integer index of your unknown glyph. This glyph will be inserted
into your BoW space whenever an unknown item is encountered.
size : int
The dimensionality of the vector space.
name : string
The name of the Reach instance.
"""
def __init__(self, vectors, items, name="", unk_index=None):
"""Initialize a Reach instance with an array and list of items."""
if len(items) != len(vectors):
raise ValueError("Your vector space and list of items are not "
"the same length: "
"{} != {}".format(len(vectors), len(items)))
if isinstance(items, dict) or isinstance(items, set):
raise ValueError("Your item list is a set or dict, and might not "
"retain order in the conversion to internal look"
"-ups. Please convert it to list and check the "
"order.")
self.items = {w: idx for idx, w in enumerate(items)}
self.indices = {v: k for k, v in self.items.items()}
self.vectors = np.asarray(vectors)
self.norm_vectors = self.normalize(self.vectors)
self.unk_index = unk_index
self.size = self.vectors.shape[1]
self.name = name
@staticmethod
@staticmethod
def _load(pathtovector,
wordlist,
num_to_load=None,
truncate_embeddings=None,
sep=" "):
"""Load a matrix and wordlist from a .vec file."""
vectors = []
addedwords = set()
words = []
try:
wordlist = set(wordlist)
except ValueError:
wordlist = set()
logger.info("Loading {0}".format(pathtovector))
firstline = open(pathtovector).readline().strip()
try:
num, size = firstline.split(sep)
num, size = int(num), int(size)
logger.info("Vector space: {} by {}".format(num, size))
header = True
except ValueError:
size = len(firstline.split(sep)) - 1
logger.info("Vector space: {} dim, # items unknown".format(size))
word, rest = firstline.split(sep, 1)
# If the first line is correctly parseable, set header to False.
header = False
if truncate_embeddings is None or truncate_embeddings == 0:
truncate_embeddings = size
for idx, line in enumerate(open(pathtovector, encoding='utf-8')):
if header and idx == 0:
continue
word, rest = line.rstrip(" \n").split(sep, 1)
if wordlist and word not in wordlist:
continue
if word in addedwords:
raise ValueError("Duplicate: {} on line {} was in the "
"vector space twice".format(word, idx))
if len(rest.split(sep)) != size:
raise ValueError("Incorrect input at index {}, size "
"is {}, expected "
"{}".format(idx+1,
len(rest.split(sep)), size))
words.append(word)
addedwords.add(word)
vectors.append(np.fromstring(rest, sep=sep)[:truncate_embeddings])
if num_to_load is not None and len(addedwords) >= num_to_load:
break
vectors = np.array(vectors).astype(np.float32)
logger.info("Loading finished")
if wordlist:
diff = wordlist - addedwords
if diff:
logger.info("Not all items from your wordlist were in your "
"vector space: {}.".format(diff))
return vectors, words
def __getitem__(self, item):
"""Get the vector for a single item."""
return self.vectors[self.items[item]]
def vectorize(self, tokens, remove_oov=False, norm=False):
"""
Vectorize a sentence by replacing all items with their vectors.
Parameters
----------
tokens : object or list of objects
The tokens to vectorize.
remove_oov : bool, optional, default False
Whether to remove OOV items. If False, OOV items are replaced by
the UNK glyph. If this is True, the returned sequence might
have a different length than the original sequence.
norm : bool, optional, default False
Whether to return the unit vectors, or the regular vectors.
Returns
-------
s : numpy array
An M * N matrix, where every item has been replaced by
its vector. OOV items are either removed, or replaced
by the value of the UNK glyph.
"""
if not tokens:
raise ValueError("You supplied an empty list.")
index = list(self.bow(tokens, remove_oov=remove_oov))
if not index:
raise ValueError("You supplied a list with only OOV tokens: {}, "
"which then got removed. Set remove_oov to False,"
" or filter your sentences to remove any in which"
" all items are OOV.")
if norm:
return np.stack([self.norm_vectors[x] for x in index])
else:
return np.stack([self.vectors[x] for x in index])
def bow(self, tokens, remove_oov=False):
"""
Create a bow representation of a list of tokens.
Parameters
----------
tokens : list.
The list of items to change into a bag of words representation.
remove_oov : bool.
Whether to remove OOV items from the input.
If this is True, the length of the returned BOW representation
might not be the length of the original representation.
Returns
-------
bow : generator
A BOW representation of the list of items.
"""
if remove_oov:
tokens = [x for x in tokens if x in self.items]
for t in tokens:
try:
yield self.items[t]
except KeyError:
if self.unk_index is None:
raise ValueError("You supplied OOV items but didn't "
"provide the index of the replacement "
"glyph. Either set remove_oov to True, "
"or set unk_index to the index of the "
"item which replaces any OOV items.")
yield self.unk_index
def transform(self, corpus, remove_oov=False, norm=False):
"""
Transform a corpus by repeated calls to vectorize, defined above.
Parameters
----------
corpus : A list of strings, list of list of strings.
Represents a corpus as a list of sentences, where sentences
can either be strings or lists of tokens.
remove_oov : bool, optional, default False
If True, removes OOV items from the input before vectorization.
Returns
-------
c : list
A list of numpy arrays, where each array represents the transformed
sentence in the original list. The list is guaranteed to be the
same length as the input list, but the arrays in the list may be
of different lengths, depending on whether remove_oov is True.
"""
return [self.vectorize(s, remove_oov=remove_oov, norm=norm)
for s in corpus]
def most_similar(self,
items,
num=10,
batch_size=100,
show_progressbar=False,
return_names=True):
"""
Return the num most similar items to a given list of items.
Parameters
----------
items : list of objects or a single object.
The items to get the most similar items to.
num : int, optional, default 10
The number of most similar items to retrieve.
batch_size : int, optional, default 100.
The batch size to use. 100 is a good default option. Increasing
the batch size may increase the speed.
show_progressbar : bool, optional, default False
Whether to show a progressbar.
return_names : bool, optional, default True
Whether to return the item names, or just the distances.
Returns
-------
sim : array
For each items in the input the num most similar items are returned
in the form of (NAME, DISTANCE) tuples. If return_names is false,
the returned list just contains distances.
"""
# This line allows users to input single items.
# We used to rely on string identities, but we now also allow
# anything hashable as keys.
# Might fail if a list of passed items is also in the vocabulary.
# but I can't think of cases when this would happen, and what
# user expectations are.
try:
if items in self.items:
items = [items]
except TypeError:
pass
x = np.stack([self.norm_vectors[self.items[x]] for x in items])
result = self._batch(x,
batch_size,
num+1,
show_progressbar,
return_names)
# list call consumes the generator.
return [x[1:] for x in result]
def threshold(self,
items,
threshold=.5,
batch_size=100,
show_progressbar=False,
return_names=True):
"""
Return all items whose similarity is higher than threshold.
Parameters
----------
items : list of objects or a single object.
The items to get the most similar items to.
threshold : float, optional, default .5
The radius within which to retrieve items.
batch_size : int, optional, default 100.
The batch size to use. 100 is a good default option. Increasing
the batch size may increase the speed.
show_progressbar : bool, optional, default False
Whether to show a progressbar.
return_names : bool, optional, default True
Whether to return the item names, or just the distances.
Returns
-------
sim : array
For each items in the input the num most similar items are returned
in the form of (NAME, DISTANCE) tuples. If return_names is false,
the returned list just contains distances.
"""
# This line allows users to input single items.
# We used to rely on string identities, but we now also allow
# anything hashable as keys.
# Might fail if a list of passed items is also in the vocabulary.
# but I can't think of cases when this would happen, and what
# user expectations are.
try:
if items in self.items:
items = [items]
except TypeError:
pass
x = np.stack([self.norm_vectors[self.items[x]] for x in items])
result = self._threshold_batch(x,
batch_size,
threshold,
show_progressbar,
return_names)
# list call consumes the generator.
return [x[1:] for x in result]
def nearest_neighbor(self,
vectors,
num=10,
batch_size=100,
show_progressbar=False,
return_names=True):
"""
Find the nearest neighbors to some arbitrary vector.
This function is meant to be used in composition operations. The
most_similar function can only handle items that are in vocab, and
looks up their vector through a dictionary. Compositions, e.g.
"King - man + woman" are necessarily not in the vocabulary.
Parameters
----------
vectors : list of arrays or numpy array
The vectors to find the nearest neighbors to.
num : int, optional, default 10
The number of most similar items to retrieve.
batch_size : int, optional, default 100.
The batch size to use. 100 is a good default option. Increasing
the batch size may increase speed.
show_progressbar : bool, optional, default False
Whether to show a progressbar.
return_names : bool, optional, default True
Whether to return the item names, or just the distances.
Returns
-------
sim : list of tuples.
For each item in the input the num most similar items are returned
in the form of (NAME, DISTANCE) tuples. If return_names is set to
false, only the distances are returned.
"""
vectors = np.array(vectors)
if np.ndim(vectors) == 1:
vectors = vectors[None, :]
result = []
result = self._batch(vectors,
batch_size,
num+1,
show_progressbar,
return_names)
return list(result)
def nearest_neighbor_threshold(self,
vectors,
threshold=.5,
batch_size=100,
show_progressbar=False,
return_names=True):
"""
Find the nearest neighbors to some arbitrary vector.
This function is meant to be used in composition operations. The
most_similar function can only handle items that are in vocab, and
looks up their vector through a dictionary. Compositions, e.g.
"King - man + woman" are necessarily not in the vocabulary.
Parameters
----------
vectors : list of arrays or numpy array
The vectors to find the nearest neighbors to.
threshold : float, optional, default .5
The threshold within to retrieve items.
batch_size : int, optional, default 100.
The batch size to use. 100 is a good default option. Increasing
the batch size may increase speed.
show_progressbar : bool, optional, default False
Whether to show a progressbar.
return_names : bool, optional, default True
Whether to return the item names, or just the distances.
Returns
-------
sim : list of tuples.
For each item in the input the num most similar items are returned
in the form of (NAME, DISTANCE) tuples. If return_names is set to
false, only the distances are returned.
"""
vectors = np.array(vectors)
if np.ndim(vectors) == 1:
vectors = vectors[None, :]
result = []
result = self._threshold_batch(vectors,
batch_size,
threshold,
show_progressbar,
return_names)
return list(result)
def _threshold_batch(self,
vectors,
batch_size,
threshold,
show_progressbar,
return_names):
"""Batched cosine distance."""
vectors = self.normalize(vectors)
# Single transpose, makes things faster.
reference_transposed = self.norm_vectors.T
for i in tqdm(range(0, len(vectors), batch_size),
disable=not show_progressbar):
distances = vectors[i: i+batch_size].dot(reference_transposed)
# For safety we clip
distances = np.clip(distances, a_min=.0, a_max=1.0)
for lidx, dists in enumerate(distances):
indices = np.flatnonzero(dists >= threshold)
sorted_indices = indices[np.argsort(-dists[indices])]
if return_names:
yield [(self.indices[d], dists[d])
for d in sorted_indices]
else:
yield list(dists[sorted_indices])
def _batch(self,
vectors,
batch_size,
num,
show_progressbar,
return_names):
"""Batched cosine distance."""
vectors = self.normalize(vectors)
# Single transpose, makes things faster.
reference_transposed = self.norm_vectors.T
for i in tqdm(range(0, len(vectors), batch_size),
disable=not show_progressbar):
distances = vectors[i: i+batch_size].dot(reference_transposed)
# For safety we clip
distances = np.clip(distances, a_min=.0, a_max=1.0)
if num == 1:
sorted_indices = np.argmax(distances, 1)[:, None]
else:
sorted_indices = np.argpartition(-distances, kth=num, axis=1)
sorted_indices = sorted_indices[:, :num]
for lidx, indices in enumerate(sorted_indices):
dists = distances[lidx, indices]
if return_names:
dindex = np.argsort(-dists)
yield [(self.indices[indices[d]], dists[d])
for d in dindex]
else:
yield list(-1 * np.sort(-dists))
@staticmethod
def normalize(vectors):
"""
Normalize a matrix of row vectors to unit length.
Contains a shortcut if there are no zero vectors in the matrix.
If there are zero vectors, we do some indexing tricks to avoid
dividing by 0.
Parameters
----------
vectors : np.array
The vectors to normalize.
Returns
-------
vectors : np.array
The input vectors, normalized to unit length.
"""
if np.ndim(vectors) == 1:
norm = np.linalg.norm(vectors)
if norm == 0:
return np.zeros_like(vectors)
return vectors / norm
norm = np.linalg.norm(vectors, axis=1)
if np.any(norm == 0):
nonzero = norm > 0
result = np.zeros_like(vectors)
n = norm[nonzero]
p = vectors[nonzero]
result[nonzero] = p / n[:, None]
return result
else:
return vectors / norm[:, None]
def vector_similarity(self, vector, items):
"""Compute the similarity between a vector and a set of items."""
vector = self.normalize(vector)
items_vec = np.stack([self.norm_vectors[self.items[x]] for x in items])
return vector.dot(items_vec.T)
def similarity(self, i1, i2):
"""
Compute the similarity between two sets of items.
Parameters
----------
i1 : object
The first set of items.
i2 : object
The second set of item.
Returns
-------
sim : array of floats
An array of similarity scores between 1 and 0.
"""
try:
if i1 in self.items:
i1 = [i1]
except TypeError:
pass
try:
if i2 in self.items:
i2 = [i2]
except TypeError:
pass
i1_vec = np.stack([self.norm_vectors[self.items[x]] for x in i1])
i2_vec = np.stack([self.norm_vectors[self.items[x]] for x in i2])
return i1_vec.dot(i2_vec.T)
def prune(self, wordlist):
"""
Prune the current reach instance by removing items.
Parameters
----------
wordlist : list of str
A list of words to keep. Note that this wordlist need not include
all words in the Reach instance. Any words which are in the
wordlist, but not in the reach instance are ignored.
"""
# Remove duplicates
wordlist = set(wordlist).intersection(set(self.items.keys()))
indices = [self.items[w] for w in wordlist if w in self.items]
if self.unk_index is not None and self.unk_index not in indices:
raise ValueError("Your unknown item is not in your list of items. "
"Set it to None before pruning, or pass your "
"unknown item.")
self.vectors = self.vectors[indices]
self.norm_vectors = self.norm_vectors[indices]
self.items = {w: idx for idx, w in enumerate(wordlist)}
self.indices = {v: k for k, v in self.items.items()}
if self.unk_index is not None:
self.unk_index = self.items[wordlist[self.unk_index]]
def save(self, path, write_header=True):
"""
Save the current vector space in word2vec format.
Parameters
----------
path : str
The path to save the vector file to.
write_header : bool, optional, default True
Whether to write a word2vec-style header as the first line of the
file
"""
with open(path, 'w') as f:
if write_header:
f.write(u"{0} {1}\n".format(str(self.vectors.shape[0]),
str(self.vectors.shape[1])))
for i in range(len(self.items)):
w = self.indices[i]
vec = self.vectors[i]
f.write(u"{0} {1}\n".format(w,
" ".join([str(x) for x in vec])))
def save_fast_format(self, filename):
"""
Save a reach instance in a fast format.
The reach fast format stores the words and vectors of a Reach instance
separately in a JSON and numpy format, respectively.
Parameters
----------
filename : str
The prefix to add to the saved filename. Note that this is not the
real filename under which these items are stored.
The words and unk_index are stored under "{filename}_words.json",
and the numpy matrix is saved under "{filename}_vectors.npy".
"""
items, _ = zip(*sorted(self.items.items(), key=lambda x: x[1]))
items = {"items": items,
"unk_index": self.unk_index,
"name": self.name}
json.dump(items, open("{}_items.json".format(filename), 'w'))
np.save(open("{}_vectors.npy".format(filename), 'wb'), self.vectors)
@staticmethod
def load_fast_format(filename):
"""
Load a reach instance in fast format.
As described above, the fast format stores the words and vectors of the
Reach instance separately, and is drastically faster than loading from
.txt files.
Parameters
----------
filename : str
The filename prefix from which to load. Note that this is not a
real filepath as such, but a shared prefix for both files.
In order for this to work, both {filename}_words.json and
{filename}_vectors.npy should be present.
"""
words, unk_index, name, vectors = Reach._load_fast(filename)
return Reach(vectors, words, unk_index=unk_index, name=name)
@staticmethod
def _load_fast(filename):
"""Sub for fast loader."""
it = json.load(open("{}_items.json".format(filename)))
words, unk_index, name = it["items"], it["unk_index"], it["name"]
vectors = np.load(open("{}_vectors.npy".format(filename), 'rb'))
return words, unk_index, name, vectors
|
stephantul/reach
|
reach/reach.py
|
Reach._load
|
python
|
def _load(pathtovector,
wordlist,
num_to_load=None,
truncate_embeddings=None,
sep=" "):
vectors = []
addedwords = set()
words = []
try:
wordlist = set(wordlist)
except ValueError:
wordlist = set()
logger.info("Loading {0}".format(pathtovector))
firstline = open(pathtovector).readline().strip()
try:
num, size = firstline.split(sep)
num, size = int(num), int(size)
logger.info("Vector space: {} by {}".format(num, size))
header = True
except ValueError:
size = len(firstline.split(sep)) - 1
logger.info("Vector space: {} dim, # items unknown".format(size))
word, rest = firstline.split(sep, 1)
# If the first line is correctly parseable, set header to False.
header = False
if truncate_embeddings is None or truncate_embeddings == 0:
truncate_embeddings = size
for idx, line in enumerate(open(pathtovector, encoding='utf-8')):
if header and idx == 0:
continue
word, rest = line.rstrip(" \n").split(sep, 1)
if wordlist and word not in wordlist:
continue
if word in addedwords:
raise ValueError("Duplicate: {} on line {} was in the "
"vector space twice".format(word, idx))
if len(rest.split(sep)) != size:
raise ValueError("Incorrect input at index {}, size "
"is {}, expected "
"{}".format(idx+1,
len(rest.split(sep)), size))
words.append(word)
addedwords.add(word)
vectors.append(np.fromstring(rest, sep=sep)[:truncate_embeddings])
if num_to_load is not None and len(addedwords) >= num_to_load:
break
vectors = np.array(vectors).astype(np.float32)
logger.info("Loading finished")
if wordlist:
diff = wordlist - addedwords
if diff:
logger.info("Not all items from your wordlist were in your "
"vector space: {}.".format(diff))
return vectors, words
|
Load a matrix and wordlist from a .vec file.
|
train
|
https://github.com/stephantul/reach/blob/e5ed0cc895d17429e797c6d7dd57bce82ff00d5d/reach/reach.py#L136-L205
| null |
class Reach(object):
"""
Work with vector representations of items.
Supports functions for calculating fast batched similarity
between items or composite representations of items.
Parameters
----------
vectors : numpy array
The vector space.
items : list
A list of items. Length must be equal to the number of vectors, and
aligned with the vectors.
name : string, optional
A string giving the name of the current reach. Only useful if you
have multiple spaces and want to keep track of them.
Attributes
----------
items : dict
A mapping from items to ids.
indices : dict
A mapping from ids to items.
vectors : numpy array
The array representing the vector space.
norm_vectors : numpy array
A normalized version of the vector space.
unk_index : int
The integer index of your unknown glyph. This glyph will be inserted
into your BoW space whenever an unknown item is encountered.
size : int
The dimensionality of the vector space.
name : string
The name of the Reach instance.
"""
def __init__(self, vectors, items, name="", unk_index=None):
"""Initialize a Reach instance with an array and list of items."""
if len(items) != len(vectors):
raise ValueError("Your vector space and list of items are not "
"the same length: "
"{} != {}".format(len(vectors), len(items)))
if isinstance(items, dict) or isinstance(items, set):
raise ValueError("Your item list is a set or dict, and might not "
"retain order in the conversion to internal look"
"-ups. Please convert it to list and check the "
"order.")
self.items = {w: idx for idx, w in enumerate(items)}
self.indices = {v: k for k, v in self.items.items()}
self.vectors = np.asarray(vectors)
self.norm_vectors = self.normalize(self.vectors)
self.unk_index = unk_index
self.size = self.vectors.shape[1]
self.name = name
@staticmethod
def load(pathtovector,
wordlist=(),
num_to_load=None,
truncate_embeddings=None,
unk_word=None,
sep=" "):
r"""
Read a file in word2vec .txt format.
The load function will raise a ValueError when trying to load items
which do not conform to line lengths.
Parameters
----------
pathtovector : string
The path to the vector file.
header : bool
Whether the vector file has a header of the type
(NUMBER OF ITEMS, SIZE OF VECTOR).
wordlist : iterable, optional, default ()
A list of words you want loaded from the vector file. If this is
None (default), all words will be loaded.
num_to_load : int, optional, default None
The number of items to load from the file. Because loading can take
some time, it is sometimes useful to onlyl load the first n items
from a vector file for quick inspection.
truncate_embeddings : int, optional, default None
If this value is not None, the vectors in the vector space will
be truncated to the number of dimensions indicated by this value.
unk_word : object
The object to treat as UNK in your vector space. If this is not
in your items dictionary after loading, we add it with a zero
vector.
Returns
-------
r : Reach
An initialized Reach instance.
"""
vectors, items = Reach._load(pathtovector,
wordlist,
num_to_load,
truncate_embeddings,
sep)
if unk_word is not None:
if unk_word not in set(items):
unk_vec = np.zeros((1, vectors.shape[1]))
vectors = np.concatenate([unk_vec, vectors], 0)
items = [unk_word] + items
unk_index = 0
else:
unk_index = items.index(unk_word)
else:
unk_index = None
return Reach(vectors,
items,
name=os.path.split(pathtovector)[-1],
unk_index=unk_index)
@staticmethod
def __getitem__(self, item):
"""Get the vector for a single item."""
return self.vectors[self.items[item]]
def vectorize(self, tokens, remove_oov=False, norm=False):
"""
Vectorize a sentence by replacing all items with their vectors.
Parameters
----------
tokens : object or list of objects
The tokens to vectorize.
remove_oov : bool, optional, default False
Whether to remove OOV items. If False, OOV items are replaced by
the UNK glyph. If this is True, the returned sequence might
have a different length than the original sequence.
norm : bool, optional, default False
Whether to return the unit vectors, or the regular vectors.
Returns
-------
s : numpy array
An M * N matrix, where every item has been replaced by
its vector. OOV items are either removed, or replaced
by the value of the UNK glyph.
"""
if not tokens:
raise ValueError("You supplied an empty list.")
index = list(self.bow(tokens, remove_oov=remove_oov))
if not index:
raise ValueError("You supplied a list with only OOV tokens: {}, "
"which then got removed. Set remove_oov to False,"
" or filter your sentences to remove any in which"
" all items are OOV.")
if norm:
return np.stack([self.norm_vectors[x] for x in index])
else:
return np.stack([self.vectors[x] for x in index])
def bow(self, tokens, remove_oov=False):
"""
Create a bow representation of a list of tokens.
Parameters
----------
tokens : list.
The list of items to change into a bag of words representation.
remove_oov : bool.
Whether to remove OOV items from the input.
If this is True, the length of the returned BOW representation
might not be the length of the original representation.
Returns
-------
bow : generator
A BOW representation of the list of items.
"""
if remove_oov:
tokens = [x for x in tokens if x in self.items]
for t in tokens:
try:
yield self.items[t]
except KeyError:
if self.unk_index is None:
raise ValueError("You supplied OOV items but didn't "
"provide the index of the replacement "
"glyph. Either set remove_oov to True, "
"or set unk_index to the index of the "
"item which replaces any OOV items.")
yield self.unk_index
def transform(self, corpus, remove_oov=False, norm=False):
"""
Transform a corpus by repeated calls to vectorize, defined above.
Parameters
----------
corpus : A list of strings, list of list of strings.
Represents a corpus as a list of sentences, where sentences
can either be strings or lists of tokens.
remove_oov : bool, optional, default False
If True, removes OOV items from the input before vectorization.
Returns
-------
c : list
A list of numpy arrays, where each array represents the transformed
sentence in the original list. The list is guaranteed to be the
same length as the input list, but the arrays in the list may be
of different lengths, depending on whether remove_oov is True.
"""
return [self.vectorize(s, remove_oov=remove_oov, norm=norm)
for s in corpus]
def most_similar(self,
items,
num=10,
batch_size=100,
show_progressbar=False,
return_names=True):
"""
Return the num most similar items to a given list of items.
Parameters
----------
items : list of objects or a single object.
The items to get the most similar items to.
num : int, optional, default 10
The number of most similar items to retrieve.
batch_size : int, optional, default 100.
The batch size to use. 100 is a good default option. Increasing
the batch size may increase the speed.
show_progressbar : bool, optional, default False
Whether to show a progressbar.
return_names : bool, optional, default True
Whether to return the item names, or just the distances.
Returns
-------
sim : array
For each items in the input the num most similar items are returned
in the form of (NAME, DISTANCE) tuples. If return_names is false,
the returned list just contains distances.
"""
# This line allows users to input single items.
# We used to rely on string identities, but we now also allow
# anything hashable as keys.
# Might fail if a list of passed items is also in the vocabulary.
# but I can't think of cases when this would happen, and what
# user expectations are.
try:
if items in self.items:
items = [items]
except TypeError:
pass
x = np.stack([self.norm_vectors[self.items[x]] for x in items])
result = self._batch(x,
batch_size,
num+1,
show_progressbar,
return_names)
# list call consumes the generator.
return [x[1:] for x in result]
def threshold(self,
items,
threshold=.5,
batch_size=100,
show_progressbar=False,
return_names=True):
"""
Return all items whose similarity is higher than threshold.
Parameters
----------
items : list of objects or a single object.
The items to get the most similar items to.
threshold : float, optional, default .5
The radius within which to retrieve items.
batch_size : int, optional, default 100.
The batch size to use. 100 is a good default option. Increasing
the batch size may increase the speed.
show_progressbar : bool, optional, default False
Whether to show a progressbar.
return_names : bool, optional, default True
Whether to return the item names, or just the distances.
Returns
-------
sim : array
For each items in the input the num most similar items are returned
in the form of (NAME, DISTANCE) tuples. If return_names is false,
the returned list just contains distances.
"""
# This line allows users to input single items.
# We used to rely on string identities, but we now also allow
# anything hashable as keys.
# Might fail if a list of passed items is also in the vocabulary.
# but I can't think of cases when this would happen, and what
# user expectations are.
try:
if items in self.items:
items = [items]
except TypeError:
pass
x = np.stack([self.norm_vectors[self.items[x]] for x in items])
result = self._threshold_batch(x,
batch_size,
threshold,
show_progressbar,
return_names)
# list call consumes the generator.
return [x[1:] for x in result]
def nearest_neighbor(self,
vectors,
num=10,
batch_size=100,
show_progressbar=False,
return_names=True):
"""
Find the nearest neighbors to some arbitrary vector.
This function is meant to be used in composition operations. The
most_similar function can only handle items that are in vocab, and
looks up their vector through a dictionary. Compositions, e.g.
"King - man + woman" are necessarily not in the vocabulary.
Parameters
----------
vectors : list of arrays or numpy array
The vectors to find the nearest neighbors to.
num : int, optional, default 10
The number of most similar items to retrieve.
batch_size : int, optional, default 100.
The batch size to use. 100 is a good default option. Increasing
the batch size may increase speed.
show_progressbar : bool, optional, default False
Whether to show a progressbar.
return_names : bool, optional, default True
Whether to return the item names, or just the distances.
Returns
-------
sim : list of tuples.
For each item in the input the num most similar items are returned
in the form of (NAME, DISTANCE) tuples. If return_names is set to
false, only the distances are returned.
"""
vectors = np.array(vectors)
if np.ndim(vectors) == 1:
vectors = vectors[None, :]
result = []
result = self._batch(vectors,
batch_size,
num+1,
show_progressbar,
return_names)
return list(result)
def nearest_neighbor_threshold(self,
vectors,
threshold=.5,
batch_size=100,
show_progressbar=False,
return_names=True):
"""
Find the nearest neighbors to some arbitrary vector.
This function is meant to be used in composition operations. The
most_similar function can only handle items that are in vocab, and
looks up their vector through a dictionary. Compositions, e.g.
"King - man + woman" are necessarily not in the vocabulary.
Parameters
----------
vectors : list of arrays or numpy array
The vectors to find the nearest neighbors to.
threshold : float, optional, default .5
The threshold within to retrieve items.
batch_size : int, optional, default 100.
The batch size to use. 100 is a good default option. Increasing
the batch size may increase speed.
show_progressbar : bool, optional, default False
Whether to show a progressbar.
return_names : bool, optional, default True
Whether to return the item names, or just the distances.
Returns
-------
sim : list of tuples.
For each item in the input the num most similar items are returned
in the form of (NAME, DISTANCE) tuples. If return_names is set to
false, only the distances are returned.
"""
vectors = np.array(vectors)
if np.ndim(vectors) == 1:
vectors = vectors[None, :]
result = []
result = self._threshold_batch(vectors,
batch_size,
threshold,
show_progressbar,
return_names)
return list(result)
def _threshold_batch(self,
vectors,
batch_size,
threshold,
show_progressbar,
return_names):
"""Batched cosine distance."""
vectors = self.normalize(vectors)
# Single transpose, makes things faster.
reference_transposed = self.norm_vectors.T
for i in tqdm(range(0, len(vectors), batch_size),
disable=not show_progressbar):
distances = vectors[i: i+batch_size].dot(reference_transposed)
# For safety we clip
distances = np.clip(distances, a_min=.0, a_max=1.0)
for lidx, dists in enumerate(distances):
indices = np.flatnonzero(dists >= threshold)
sorted_indices = indices[np.argsort(-dists[indices])]
if return_names:
yield [(self.indices[d], dists[d])
for d in sorted_indices]
else:
yield list(dists[sorted_indices])
def _batch(self,
vectors,
batch_size,
num,
show_progressbar,
return_names):
"""Batched cosine distance."""
vectors = self.normalize(vectors)
# Single transpose, makes things faster.
reference_transposed = self.norm_vectors.T
for i in tqdm(range(0, len(vectors), batch_size),
disable=not show_progressbar):
distances = vectors[i: i+batch_size].dot(reference_transposed)
# For safety we clip
distances = np.clip(distances, a_min=.0, a_max=1.0)
if num == 1:
sorted_indices = np.argmax(distances, 1)[:, None]
else:
sorted_indices = np.argpartition(-distances, kth=num, axis=1)
sorted_indices = sorted_indices[:, :num]
for lidx, indices in enumerate(sorted_indices):
dists = distances[lidx, indices]
if return_names:
dindex = np.argsort(-dists)
yield [(self.indices[indices[d]], dists[d])
for d in dindex]
else:
yield list(-1 * np.sort(-dists))
@staticmethod
def normalize(vectors):
"""
Normalize a matrix of row vectors to unit length.
Contains a shortcut if there are no zero vectors in the matrix.
If there are zero vectors, we do some indexing tricks to avoid
dividing by 0.
Parameters
----------
vectors : np.array
The vectors to normalize.
Returns
-------
vectors : np.array
The input vectors, normalized to unit length.
"""
if np.ndim(vectors) == 1:
norm = np.linalg.norm(vectors)
if norm == 0:
return np.zeros_like(vectors)
return vectors / norm
norm = np.linalg.norm(vectors, axis=1)
if np.any(norm == 0):
nonzero = norm > 0
result = np.zeros_like(vectors)
n = norm[nonzero]
p = vectors[nonzero]
result[nonzero] = p / n[:, None]
return result
else:
return vectors / norm[:, None]
def vector_similarity(self, vector, items):
"""Compute the similarity between a vector and a set of items."""
vector = self.normalize(vector)
items_vec = np.stack([self.norm_vectors[self.items[x]] for x in items])
return vector.dot(items_vec.T)
def similarity(self, i1, i2):
"""
Compute the similarity between two sets of items.
Parameters
----------
i1 : object
The first set of items.
i2 : object
The second set of item.
Returns
-------
sim : array of floats
An array of similarity scores between 1 and 0.
"""
try:
if i1 in self.items:
i1 = [i1]
except TypeError:
pass
try:
if i2 in self.items:
i2 = [i2]
except TypeError:
pass
i1_vec = np.stack([self.norm_vectors[self.items[x]] for x in i1])
i2_vec = np.stack([self.norm_vectors[self.items[x]] for x in i2])
return i1_vec.dot(i2_vec.T)
def prune(self, wordlist):
"""
Prune the current reach instance by removing items.
Parameters
----------
wordlist : list of str
A list of words to keep. Note that this wordlist need not include
all words in the Reach instance. Any words which are in the
wordlist, but not in the reach instance are ignored.
"""
# Remove duplicates
wordlist = set(wordlist).intersection(set(self.items.keys()))
indices = [self.items[w] for w in wordlist if w in self.items]
if self.unk_index is not None and self.unk_index not in indices:
raise ValueError("Your unknown item is not in your list of items. "
"Set it to None before pruning, or pass your "
"unknown item.")
self.vectors = self.vectors[indices]
self.norm_vectors = self.norm_vectors[indices]
self.items = {w: idx for idx, w in enumerate(wordlist)}
self.indices = {v: k for k, v in self.items.items()}
if self.unk_index is not None:
self.unk_index = self.items[wordlist[self.unk_index]]
def save(self, path, write_header=True):
"""
Save the current vector space in word2vec format.
Parameters
----------
path : str
The path to save the vector file to.
write_header : bool, optional, default True
Whether to write a word2vec-style header as the first line of the
file
"""
with open(path, 'w') as f:
if write_header:
f.write(u"{0} {1}\n".format(str(self.vectors.shape[0]),
str(self.vectors.shape[1])))
for i in range(len(self.items)):
w = self.indices[i]
vec = self.vectors[i]
f.write(u"{0} {1}\n".format(w,
" ".join([str(x) for x in vec])))
def save_fast_format(self, filename):
"""
Save a reach instance in a fast format.
The reach fast format stores the words and vectors of a Reach instance
separately in a JSON and numpy format, respectively.
Parameters
----------
filename : str
The prefix to add to the saved filename. Note that this is not the
real filename under which these items are stored.
The words and unk_index are stored under "{filename}_words.json",
and the numpy matrix is saved under "{filename}_vectors.npy".
"""
items, _ = zip(*sorted(self.items.items(), key=lambda x: x[1]))
items = {"items": items,
"unk_index": self.unk_index,
"name": self.name}
json.dump(items, open("{}_items.json".format(filename), 'w'))
np.save(open("{}_vectors.npy".format(filename), 'wb'), self.vectors)
@staticmethod
def load_fast_format(filename):
"""
Load a reach instance in fast format.
As described above, the fast format stores the words and vectors of the
Reach instance separately, and is drastically faster than loading from
.txt files.
Parameters
----------
filename : str
The filename prefix from which to load. Note that this is not a
real filepath as such, but a shared prefix for both files.
In order for this to work, both {filename}_words.json and
{filename}_vectors.npy should be present.
"""
words, unk_index, name, vectors = Reach._load_fast(filename)
return Reach(vectors, words, unk_index=unk_index, name=name)
@staticmethod
def _load_fast(filename):
"""Sub for fast loader."""
it = json.load(open("{}_items.json".format(filename)))
words, unk_index, name = it["items"], it["unk_index"], it["name"]
vectors = np.load(open("{}_vectors.npy".format(filename), 'rb'))
return words, unk_index, name, vectors
|
stephantul/reach
|
reach/reach.py
|
Reach.vectorize
|
python
|
def vectorize(self, tokens, remove_oov=False, norm=False):
if not tokens:
raise ValueError("You supplied an empty list.")
index = list(self.bow(tokens, remove_oov=remove_oov))
if not index:
raise ValueError("You supplied a list with only OOV tokens: {}, "
"which then got removed. Set remove_oov to False,"
" or filter your sentences to remove any in which"
" all items are OOV.")
if norm:
return np.stack([self.norm_vectors[x] for x in index])
else:
return np.stack([self.vectors[x] for x in index])
|
Vectorize a sentence by replacing all items with their vectors.
Parameters
----------
tokens : object or list of objects
The tokens to vectorize.
remove_oov : bool, optional, default False
Whether to remove OOV items. If False, OOV items are replaced by
the UNK glyph. If this is True, the returned sequence might
have a different length than the original sequence.
norm : bool, optional, default False
Whether to return the unit vectors, or the regular vectors.
Returns
-------
s : numpy array
An M * N matrix, where every item has been replaced by
its vector. OOV items are either removed, or replaced
by the value of the UNK glyph.
|
train
|
https://github.com/stephantul/reach/blob/e5ed0cc895d17429e797c6d7dd57bce82ff00d5d/reach/reach.py#L211-L245
|
[
"def bow(self, tokens, remove_oov=False):\n \"\"\"\n Create a bow representation of a list of tokens.\n\n Parameters\n ----------\n tokens : list.\n The list of items to change into a bag of words representation.\n remove_oov : bool.\n Whether to remove OOV items from the input.\n If this is True, the length of the returned BOW representation\n might not be the length of the original representation.\n\n Returns\n -------\n bow : generator\n A BOW representation of the list of items.\n\n \"\"\"\n if remove_oov:\n tokens = [x for x in tokens if x in self.items]\n\n for t in tokens:\n try:\n yield self.items[t]\n except KeyError:\n if self.unk_index is None:\n raise ValueError(\"You supplied OOV items but didn't \"\n \"provide the index of the replacement \"\n \"glyph. Either set remove_oov to True, \"\n \"or set unk_index to the index of the \"\n \"item which replaces any OOV items.\")\n yield self.unk_index\n"
] |
class Reach(object):
"""
Work with vector representations of items.
Supports functions for calculating fast batched similarity
between items or composite representations of items.
Parameters
----------
vectors : numpy array
The vector space.
items : list
A list of items. Length must be equal to the number of vectors, and
aligned with the vectors.
name : string, optional
A string giving the name of the current reach. Only useful if you
have multiple spaces and want to keep track of them.
Attributes
----------
items : dict
A mapping from items to ids.
indices : dict
A mapping from ids to items.
vectors : numpy array
The array representing the vector space.
norm_vectors : numpy array
A normalized version of the vector space.
unk_index : int
The integer index of your unknown glyph. This glyph will be inserted
into your BoW space whenever an unknown item is encountered.
size : int
The dimensionality of the vector space.
name : string
The name of the Reach instance.
"""
def __init__(self, vectors, items, name="", unk_index=None):
"""Initialize a Reach instance with an array and list of items."""
if len(items) != len(vectors):
raise ValueError("Your vector space and list of items are not "
"the same length: "
"{} != {}".format(len(vectors), len(items)))
if isinstance(items, dict) or isinstance(items, set):
raise ValueError("Your item list is a set or dict, and might not "
"retain order in the conversion to internal look"
"-ups. Please convert it to list and check the "
"order.")
self.items = {w: idx for idx, w in enumerate(items)}
self.indices = {v: k for k, v in self.items.items()}
self.vectors = np.asarray(vectors)
self.norm_vectors = self.normalize(self.vectors)
self.unk_index = unk_index
self.size = self.vectors.shape[1]
self.name = name
@staticmethod
def load(pathtovector,
wordlist=(),
num_to_load=None,
truncate_embeddings=None,
unk_word=None,
sep=" "):
r"""
Read a file in word2vec .txt format.
The load function will raise a ValueError when trying to load items
which do not conform to line lengths.
Parameters
----------
pathtovector : string
The path to the vector file.
header : bool
Whether the vector file has a header of the type
(NUMBER OF ITEMS, SIZE OF VECTOR).
wordlist : iterable, optional, default ()
A list of words you want loaded from the vector file. If this is
None (default), all words will be loaded.
num_to_load : int, optional, default None
The number of items to load from the file. Because loading can take
some time, it is sometimes useful to onlyl load the first n items
from a vector file for quick inspection.
truncate_embeddings : int, optional, default None
If this value is not None, the vectors in the vector space will
be truncated to the number of dimensions indicated by this value.
unk_word : object
The object to treat as UNK in your vector space. If this is not
in your items dictionary after loading, we add it with a zero
vector.
Returns
-------
r : Reach
An initialized Reach instance.
"""
vectors, items = Reach._load(pathtovector,
wordlist,
num_to_load,
truncate_embeddings,
sep)
if unk_word is not None:
if unk_word not in set(items):
unk_vec = np.zeros((1, vectors.shape[1]))
vectors = np.concatenate([unk_vec, vectors], 0)
items = [unk_word] + items
unk_index = 0
else:
unk_index = items.index(unk_word)
else:
unk_index = None
return Reach(vectors,
items,
name=os.path.split(pathtovector)[-1],
unk_index=unk_index)
@staticmethod
def _load(pathtovector,
wordlist,
num_to_load=None,
truncate_embeddings=None,
sep=" "):
"""Load a matrix and wordlist from a .vec file."""
vectors = []
addedwords = set()
words = []
try:
wordlist = set(wordlist)
except ValueError:
wordlist = set()
logger.info("Loading {0}".format(pathtovector))
firstline = open(pathtovector).readline().strip()
try:
num, size = firstline.split(sep)
num, size = int(num), int(size)
logger.info("Vector space: {} by {}".format(num, size))
header = True
except ValueError:
size = len(firstline.split(sep)) - 1
logger.info("Vector space: {} dim, # items unknown".format(size))
word, rest = firstline.split(sep, 1)
# If the first line is correctly parseable, set header to False.
header = False
if truncate_embeddings is None or truncate_embeddings == 0:
truncate_embeddings = size
for idx, line in enumerate(open(pathtovector, encoding='utf-8')):
if header and idx == 0:
continue
word, rest = line.rstrip(" \n").split(sep, 1)
if wordlist and word not in wordlist:
continue
if word in addedwords:
raise ValueError("Duplicate: {} on line {} was in the "
"vector space twice".format(word, idx))
if len(rest.split(sep)) != size:
raise ValueError("Incorrect input at index {}, size "
"is {}, expected "
"{}".format(idx+1,
len(rest.split(sep)), size))
words.append(word)
addedwords.add(word)
vectors.append(np.fromstring(rest, sep=sep)[:truncate_embeddings])
if num_to_load is not None and len(addedwords) >= num_to_load:
break
vectors = np.array(vectors).astype(np.float32)
logger.info("Loading finished")
if wordlist:
diff = wordlist - addedwords
if diff:
logger.info("Not all items from your wordlist were in your "
"vector space: {}.".format(diff))
return vectors, words
def __getitem__(self, item):
"""Get the vector for a single item."""
return self.vectors[self.items[item]]
def bow(self, tokens, remove_oov=False):
"""
Create a bow representation of a list of tokens.
Parameters
----------
tokens : list.
The list of items to change into a bag of words representation.
remove_oov : bool.
Whether to remove OOV items from the input.
If this is True, the length of the returned BOW representation
might not be the length of the original representation.
Returns
-------
bow : generator
A BOW representation of the list of items.
"""
if remove_oov:
tokens = [x for x in tokens if x in self.items]
for t in tokens:
try:
yield self.items[t]
except KeyError:
if self.unk_index is None:
raise ValueError("You supplied OOV items but didn't "
"provide the index of the replacement "
"glyph. Either set remove_oov to True, "
"or set unk_index to the index of the "
"item which replaces any OOV items.")
yield self.unk_index
def transform(self, corpus, remove_oov=False, norm=False):
"""
Transform a corpus by repeated calls to vectorize, defined above.
Parameters
----------
corpus : A list of strings, list of list of strings.
Represents a corpus as a list of sentences, where sentences
can either be strings or lists of tokens.
remove_oov : bool, optional, default False
If True, removes OOV items from the input before vectorization.
Returns
-------
c : list
A list of numpy arrays, where each array represents the transformed
sentence in the original list. The list is guaranteed to be the
same length as the input list, but the arrays in the list may be
of different lengths, depending on whether remove_oov is True.
"""
return [self.vectorize(s, remove_oov=remove_oov, norm=norm)
for s in corpus]
def most_similar(self,
items,
num=10,
batch_size=100,
show_progressbar=False,
return_names=True):
"""
Return the num most similar items to a given list of items.
Parameters
----------
items : list of objects or a single object.
The items to get the most similar items to.
num : int, optional, default 10
The number of most similar items to retrieve.
batch_size : int, optional, default 100.
The batch size to use. 100 is a good default option. Increasing
the batch size may increase the speed.
show_progressbar : bool, optional, default False
Whether to show a progressbar.
return_names : bool, optional, default True
Whether to return the item names, or just the distances.
Returns
-------
sim : array
For each items in the input the num most similar items are returned
in the form of (NAME, DISTANCE) tuples. If return_names is false,
the returned list just contains distances.
"""
# This line allows users to input single items.
# We used to rely on string identities, but we now also allow
# anything hashable as keys.
# Might fail if a list of passed items is also in the vocabulary.
# but I can't think of cases when this would happen, and what
# user expectations are.
try:
if items in self.items:
items = [items]
except TypeError:
pass
x = np.stack([self.norm_vectors[self.items[x]] for x in items])
result = self._batch(x,
batch_size,
num+1,
show_progressbar,
return_names)
# list call consumes the generator.
return [x[1:] for x in result]
def threshold(self,
items,
threshold=.5,
batch_size=100,
show_progressbar=False,
return_names=True):
"""
Return all items whose similarity is higher than threshold.
Parameters
----------
items : list of objects or a single object.
The items to get the most similar items to.
threshold : float, optional, default .5
The radius within which to retrieve items.
batch_size : int, optional, default 100.
The batch size to use. 100 is a good default option. Increasing
the batch size may increase the speed.
show_progressbar : bool, optional, default False
Whether to show a progressbar.
return_names : bool, optional, default True
Whether to return the item names, or just the distances.
Returns
-------
sim : array
For each items in the input the num most similar items are returned
in the form of (NAME, DISTANCE) tuples. If return_names is false,
the returned list just contains distances.
"""
# This line allows users to input single items.
# We used to rely on string identities, but we now also allow
# anything hashable as keys.
# Might fail if a list of passed items is also in the vocabulary.
# but I can't think of cases when this would happen, and what
# user expectations are.
try:
if items in self.items:
items = [items]
except TypeError:
pass
x = np.stack([self.norm_vectors[self.items[x]] for x in items])
result = self._threshold_batch(x,
batch_size,
threshold,
show_progressbar,
return_names)
# list call consumes the generator.
return [x[1:] for x in result]
def nearest_neighbor(self,
vectors,
num=10,
batch_size=100,
show_progressbar=False,
return_names=True):
"""
Find the nearest neighbors to some arbitrary vector.
This function is meant to be used in composition operations. The
most_similar function can only handle items that are in vocab, and
looks up their vector through a dictionary. Compositions, e.g.
"King - man + woman" are necessarily not in the vocabulary.
Parameters
----------
vectors : list of arrays or numpy array
The vectors to find the nearest neighbors to.
num : int, optional, default 10
The number of most similar items to retrieve.
batch_size : int, optional, default 100.
The batch size to use. 100 is a good default option. Increasing
the batch size may increase speed.
show_progressbar : bool, optional, default False
Whether to show a progressbar.
return_names : bool, optional, default True
Whether to return the item names, or just the distances.
Returns
-------
sim : list of tuples.
For each item in the input the num most similar items are returned
in the form of (NAME, DISTANCE) tuples. If return_names is set to
false, only the distances are returned.
"""
vectors = np.array(vectors)
if np.ndim(vectors) == 1:
vectors = vectors[None, :]
result = []
result = self._batch(vectors,
batch_size,
num+1,
show_progressbar,
return_names)
return list(result)
def nearest_neighbor_threshold(self,
vectors,
threshold=.5,
batch_size=100,
show_progressbar=False,
return_names=True):
"""
Find the nearest neighbors to some arbitrary vector.
This function is meant to be used in composition operations. The
most_similar function can only handle items that are in vocab, and
looks up their vector through a dictionary. Compositions, e.g.
"King - man + woman" are necessarily not in the vocabulary.
Parameters
----------
vectors : list of arrays or numpy array
The vectors to find the nearest neighbors to.
threshold : float, optional, default .5
The threshold within to retrieve items.
batch_size : int, optional, default 100.
The batch size to use. 100 is a good default option. Increasing
the batch size may increase speed.
show_progressbar : bool, optional, default False
Whether to show a progressbar.
return_names : bool, optional, default True
Whether to return the item names, or just the distances.
Returns
-------
sim : list of tuples.
For each item in the input the num most similar items are returned
in the form of (NAME, DISTANCE) tuples. If return_names is set to
false, only the distances are returned.
"""
vectors = np.array(vectors)
if np.ndim(vectors) == 1:
vectors = vectors[None, :]
result = []
result = self._threshold_batch(vectors,
batch_size,
threshold,
show_progressbar,
return_names)
return list(result)
def _threshold_batch(self,
vectors,
batch_size,
threshold,
show_progressbar,
return_names):
"""Batched cosine distance."""
vectors = self.normalize(vectors)
# Single transpose, makes things faster.
reference_transposed = self.norm_vectors.T
for i in tqdm(range(0, len(vectors), batch_size),
disable=not show_progressbar):
distances = vectors[i: i+batch_size].dot(reference_transposed)
# For safety we clip
distances = np.clip(distances, a_min=.0, a_max=1.0)
for lidx, dists in enumerate(distances):
indices = np.flatnonzero(dists >= threshold)
sorted_indices = indices[np.argsort(-dists[indices])]
if return_names:
yield [(self.indices[d], dists[d])
for d in sorted_indices]
else:
yield list(dists[sorted_indices])
def _batch(self,
vectors,
batch_size,
num,
show_progressbar,
return_names):
"""Batched cosine distance."""
vectors = self.normalize(vectors)
# Single transpose, makes things faster.
reference_transposed = self.norm_vectors.T
for i in tqdm(range(0, len(vectors), batch_size),
disable=not show_progressbar):
distances = vectors[i: i+batch_size].dot(reference_transposed)
# For safety we clip
distances = np.clip(distances, a_min=.0, a_max=1.0)
if num == 1:
sorted_indices = np.argmax(distances, 1)[:, None]
else:
sorted_indices = np.argpartition(-distances, kth=num, axis=1)
sorted_indices = sorted_indices[:, :num]
for lidx, indices in enumerate(sorted_indices):
dists = distances[lidx, indices]
if return_names:
dindex = np.argsort(-dists)
yield [(self.indices[indices[d]], dists[d])
for d in dindex]
else:
yield list(-1 * np.sort(-dists))
@staticmethod
def normalize(vectors):
"""
Normalize a matrix of row vectors to unit length.
Contains a shortcut if there are no zero vectors in the matrix.
If there are zero vectors, we do some indexing tricks to avoid
dividing by 0.
Parameters
----------
vectors : np.array
The vectors to normalize.
Returns
-------
vectors : np.array
The input vectors, normalized to unit length.
"""
if np.ndim(vectors) == 1:
norm = np.linalg.norm(vectors)
if norm == 0:
return np.zeros_like(vectors)
return vectors / norm
norm = np.linalg.norm(vectors, axis=1)
if np.any(norm == 0):
nonzero = norm > 0
result = np.zeros_like(vectors)
n = norm[nonzero]
p = vectors[nonzero]
result[nonzero] = p / n[:, None]
return result
else:
return vectors / norm[:, None]
def vector_similarity(self, vector, items):
"""Compute the similarity between a vector and a set of items."""
vector = self.normalize(vector)
items_vec = np.stack([self.norm_vectors[self.items[x]] for x in items])
return vector.dot(items_vec.T)
def similarity(self, i1, i2):
"""
Compute the similarity between two sets of items.
Parameters
----------
i1 : object
The first set of items.
i2 : object
The second set of item.
Returns
-------
sim : array of floats
An array of similarity scores between 1 and 0.
"""
try:
if i1 in self.items:
i1 = [i1]
except TypeError:
pass
try:
if i2 in self.items:
i2 = [i2]
except TypeError:
pass
i1_vec = np.stack([self.norm_vectors[self.items[x]] for x in i1])
i2_vec = np.stack([self.norm_vectors[self.items[x]] for x in i2])
return i1_vec.dot(i2_vec.T)
def prune(self, wordlist):
"""
Prune the current reach instance by removing items.
Parameters
----------
wordlist : list of str
A list of words to keep. Note that this wordlist need not include
all words in the Reach instance. Any words which are in the
wordlist, but not in the reach instance are ignored.
"""
# Remove duplicates
wordlist = set(wordlist).intersection(set(self.items.keys()))
indices = [self.items[w] for w in wordlist if w in self.items]
if self.unk_index is not None and self.unk_index not in indices:
raise ValueError("Your unknown item is not in your list of items. "
"Set it to None before pruning, or pass your "
"unknown item.")
self.vectors = self.vectors[indices]
self.norm_vectors = self.norm_vectors[indices]
self.items = {w: idx for idx, w in enumerate(wordlist)}
self.indices = {v: k for k, v in self.items.items()}
if self.unk_index is not None:
self.unk_index = self.items[wordlist[self.unk_index]]
def save(self, path, write_header=True):
"""
Save the current vector space in word2vec format.
Parameters
----------
path : str
The path to save the vector file to.
write_header : bool, optional, default True
Whether to write a word2vec-style header as the first line of the
file
"""
with open(path, 'w') as f:
if write_header:
f.write(u"{0} {1}\n".format(str(self.vectors.shape[0]),
str(self.vectors.shape[1])))
for i in range(len(self.items)):
w = self.indices[i]
vec = self.vectors[i]
f.write(u"{0} {1}\n".format(w,
" ".join([str(x) for x in vec])))
def save_fast_format(self, filename):
"""
Save a reach instance in a fast format.
The reach fast format stores the words and vectors of a Reach instance
separately in a JSON and numpy format, respectively.
Parameters
----------
filename : str
The prefix to add to the saved filename. Note that this is not the
real filename under which these items are stored.
The words and unk_index are stored under "{filename}_words.json",
and the numpy matrix is saved under "{filename}_vectors.npy".
"""
items, _ = zip(*sorted(self.items.items(), key=lambda x: x[1]))
items = {"items": items,
"unk_index": self.unk_index,
"name": self.name}
json.dump(items, open("{}_items.json".format(filename), 'w'))
np.save(open("{}_vectors.npy".format(filename), 'wb'), self.vectors)
@staticmethod
def load_fast_format(filename):
"""
Load a reach instance in fast format.
As described above, the fast format stores the words and vectors of the
Reach instance separately, and is drastically faster than loading from
.txt files.
Parameters
----------
filename : str
The filename prefix from which to load. Note that this is not a
real filepath as such, but a shared prefix for both files.
In order for this to work, both {filename}_words.json and
{filename}_vectors.npy should be present.
"""
words, unk_index, name, vectors = Reach._load_fast(filename)
return Reach(vectors, words, unk_index=unk_index, name=name)
@staticmethod
def _load_fast(filename):
"""Sub for fast loader."""
it = json.load(open("{}_items.json".format(filename)))
words, unk_index, name = it["items"], it["unk_index"], it["name"]
vectors = np.load(open("{}_vectors.npy".format(filename), 'rb'))
return words, unk_index, name, vectors
|
stephantul/reach
|
reach/reach.py
|
Reach.bow
|
python
|
def bow(self, tokens, remove_oov=False):
if remove_oov:
tokens = [x for x in tokens if x in self.items]
for t in tokens:
try:
yield self.items[t]
except KeyError:
if self.unk_index is None:
raise ValueError("You supplied OOV items but didn't "
"provide the index of the replacement "
"glyph. Either set remove_oov to True, "
"or set unk_index to the index of the "
"item which replaces any OOV items.")
yield self.unk_index
|
Create a bow representation of a list of tokens.
Parameters
----------
tokens : list.
The list of items to change into a bag of words representation.
remove_oov : bool.
Whether to remove OOV items from the input.
If this is True, the length of the returned BOW representation
might not be the length of the original representation.
Returns
-------
bow : generator
A BOW representation of the list of items.
|
train
|
https://github.com/stephantul/reach/blob/e5ed0cc895d17429e797c6d7dd57bce82ff00d5d/reach/reach.py#L247-L279
| null |
class Reach(object):
"""
Work with vector representations of items.
Supports functions for calculating fast batched similarity
between items or composite representations of items.
Parameters
----------
vectors : numpy array
The vector space.
items : list
A list of items. Length must be equal to the number of vectors, and
aligned with the vectors.
name : string, optional
A string giving the name of the current reach. Only useful if you
have multiple spaces and want to keep track of them.
Attributes
----------
items : dict
A mapping from items to ids.
indices : dict
A mapping from ids to items.
vectors : numpy array
The array representing the vector space.
norm_vectors : numpy array
A normalized version of the vector space.
unk_index : int
The integer index of your unknown glyph. This glyph will be inserted
into your BoW space whenever an unknown item is encountered.
size : int
The dimensionality of the vector space.
name : string
The name of the Reach instance.
"""
def __init__(self, vectors, items, name="", unk_index=None):
"""Initialize a Reach instance with an array and list of items."""
if len(items) != len(vectors):
raise ValueError("Your vector space and list of items are not "
"the same length: "
"{} != {}".format(len(vectors), len(items)))
if isinstance(items, dict) or isinstance(items, set):
raise ValueError("Your item list is a set or dict, and might not "
"retain order in the conversion to internal look"
"-ups. Please convert it to list and check the "
"order.")
self.items = {w: idx for idx, w in enumerate(items)}
self.indices = {v: k for k, v in self.items.items()}
self.vectors = np.asarray(vectors)
self.norm_vectors = self.normalize(self.vectors)
self.unk_index = unk_index
self.size = self.vectors.shape[1]
self.name = name
@staticmethod
def load(pathtovector,
wordlist=(),
num_to_load=None,
truncate_embeddings=None,
unk_word=None,
sep=" "):
r"""
Read a file in word2vec .txt format.
The load function will raise a ValueError when trying to load items
which do not conform to line lengths.
Parameters
----------
pathtovector : string
The path to the vector file.
header : bool
Whether the vector file has a header of the type
(NUMBER OF ITEMS, SIZE OF VECTOR).
wordlist : iterable, optional, default ()
A list of words you want loaded from the vector file. If this is
None (default), all words will be loaded.
num_to_load : int, optional, default None
The number of items to load from the file. Because loading can take
some time, it is sometimes useful to onlyl load the first n items
from a vector file for quick inspection.
truncate_embeddings : int, optional, default None
If this value is not None, the vectors in the vector space will
be truncated to the number of dimensions indicated by this value.
unk_word : object
The object to treat as UNK in your vector space. If this is not
in your items dictionary after loading, we add it with a zero
vector.
Returns
-------
r : Reach
An initialized Reach instance.
"""
vectors, items = Reach._load(pathtovector,
wordlist,
num_to_load,
truncate_embeddings,
sep)
if unk_word is not None:
if unk_word not in set(items):
unk_vec = np.zeros((1, vectors.shape[1]))
vectors = np.concatenate([unk_vec, vectors], 0)
items = [unk_word] + items
unk_index = 0
else:
unk_index = items.index(unk_word)
else:
unk_index = None
return Reach(vectors,
items,
name=os.path.split(pathtovector)[-1],
unk_index=unk_index)
@staticmethod
def _load(pathtovector,
wordlist,
num_to_load=None,
truncate_embeddings=None,
sep=" "):
"""Load a matrix and wordlist from a .vec file."""
vectors = []
addedwords = set()
words = []
try:
wordlist = set(wordlist)
except ValueError:
wordlist = set()
logger.info("Loading {0}".format(pathtovector))
firstline = open(pathtovector).readline().strip()
try:
num, size = firstline.split(sep)
num, size = int(num), int(size)
logger.info("Vector space: {} by {}".format(num, size))
header = True
except ValueError:
size = len(firstline.split(sep)) - 1
logger.info("Vector space: {} dim, # items unknown".format(size))
word, rest = firstline.split(sep, 1)
# If the first line is correctly parseable, set header to False.
header = False
if truncate_embeddings is None or truncate_embeddings == 0:
truncate_embeddings = size
for idx, line in enumerate(open(pathtovector, encoding='utf-8')):
if header and idx == 0:
continue
word, rest = line.rstrip(" \n").split(sep, 1)
if wordlist and word not in wordlist:
continue
if word in addedwords:
raise ValueError("Duplicate: {} on line {} was in the "
"vector space twice".format(word, idx))
if len(rest.split(sep)) != size:
raise ValueError("Incorrect input at index {}, size "
"is {}, expected "
"{}".format(idx+1,
len(rest.split(sep)), size))
words.append(word)
addedwords.add(word)
vectors.append(np.fromstring(rest, sep=sep)[:truncate_embeddings])
if num_to_load is not None and len(addedwords) >= num_to_load:
break
vectors = np.array(vectors).astype(np.float32)
logger.info("Loading finished")
if wordlist:
diff = wordlist - addedwords
if diff:
logger.info("Not all items from your wordlist were in your "
"vector space: {}.".format(diff))
return vectors, words
def __getitem__(self, item):
"""Get the vector for a single item."""
return self.vectors[self.items[item]]
def vectorize(self, tokens, remove_oov=False, norm=False):
"""
Vectorize a sentence by replacing all items with their vectors.
Parameters
----------
tokens : object or list of objects
The tokens to vectorize.
remove_oov : bool, optional, default False
Whether to remove OOV items. If False, OOV items are replaced by
the UNK glyph. If this is True, the returned sequence might
have a different length than the original sequence.
norm : bool, optional, default False
Whether to return the unit vectors, or the regular vectors.
Returns
-------
s : numpy array
An M * N matrix, where every item has been replaced by
its vector. OOV items are either removed, or replaced
by the value of the UNK glyph.
"""
if not tokens:
raise ValueError("You supplied an empty list.")
index = list(self.bow(tokens, remove_oov=remove_oov))
if not index:
raise ValueError("You supplied a list with only OOV tokens: {}, "
"which then got removed. Set remove_oov to False,"
" or filter your sentences to remove any in which"
" all items are OOV.")
if norm:
return np.stack([self.norm_vectors[x] for x in index])
else:
return np.stack([self.vectors[x] for x in index])
def transform(self, corpus, remove_oov=False, norm=False):
"""
Transform a corpus by repeated calls to vectorize, defined above.
Parameters
----------
corpus : A list of strings, list of list of strings.
Represents a corpus as a list of sentences, where sentences
can either be strings or lists of tokens.
remove_oov : bool, optional, default False
If True, removes OOV items from the input before vectorization.
Returns
-------
c : list
A list of numpy arrays, where each array represents the transformed
sentence in the original list. The list is guaranteed to be the
same length as the input list, but the arrays in the list may be
of different lengths, depending on whether remove_oov is True.
"""
return [self.vectorize(s, remove_oov=remove_oov, norm=norm)
for s in corpus]
def most_similar(self,
items,
num=10,
batch_size=100,
show_progressbar=False,
return_names=True):
"""
Return the num most similar items to a given list of items.
Parameters
----------
items : list of objects or a single object.
The items to get the most similar items to.
num : int, optional, default 10
The number of most similar items to retrieve.
batch_size : int, optional, default 100.
The batch size to use. 100 is a good default option. Increasing
the batch size may increase the speed.
show_progressbar : bool, optional, default False
Whether to show a progressbar.
return_names : bool, optional, default True
Whether to return the item names, or just the distances.
Returns
-------
sim : array
For each items in the input the num most similar items are returned
in the form of (NAME, DISTANCE) tuples. If return_names is false,
the returned list just contains distances.
"""
# This line allows users to input single items.
# We used to rely on string identities, but we now also allow
# anything hashable as keys.
# Might fail if a list of passed items is also in the vocabulary.
# but I can't think of cases when this would happen, and what
# user expectations are.
try:
if items in self.items:
items = [items]
except TypeError:
pass
x = np.stack([self.norm_vectors[self.items[x]] for x in items])
result = self._batch(x,
batch_size,
num+1,
show_progressbar,
return_names)
# list call consumes the generator.
return [x[1:] for x in result]
def threshold(self,
items,
threshold=.5,
batch_size=100,
show_progressbar=False,
return_names=True):
"""
Return all items whose similarity is higher than threshold.
Parameters
----------
items : list of objects or a single object.
The items to get the most similar items to.
threshold : float, optional, default .5
The radius within which to retrieve items.
batch_size : int, optional, default 100.
The batch size to use. 100 is a good default option. Increasing
the batch size may increase the speed.
show_progressbar : bool, optional, default False
Whether to show a progressbar.
return_names : bool, optional, default True
Whether to return the item names, or just the distances.
Returns
-------
sim : array
For each items in the input the num most similar items are returned
in the form of (NAME, DISTANCE) tuples. If return_names is false,
the returned list just contains distances.
"""
# This line allows users to input single items.
# We used to rely on string identities, but we now also allow
# anything hashable as keys.
# Might fail if a list of passed items is also in the vocabulary.
# but I can't think of cases when this would happen, and what
# user expectations are.
try:
if items in self.items:
items = [items]
except TypeError:
pass
x = np.stack([self.norm_vectors[self.items[x]] for x in items])
result = self._threshold_batch(x,
batch_size,
threshold,
show_progressbar,
return_names)
# list call consumes the generator.
return [x[1:] for x in result]
def nearest_neighbor(self,
vectors,
num=10,
batch_size=100,
show_progressbar=False,
return_names=True):
"""
Find the nearest neighbors to some arbitrary vector.
This function is meant to be used in composition operations. The
most_similar function can only handle items that are in vocab, and
looks up their vector through a dictionary. Compositions, e.g.
"King - man + woman" are necessarily not in the vocabulary.
Parameters
----------
vectors : list of arrays or numpy array
The vectors to find the nearest neighbors to.
num : int, optional, default 10
The number of most similar items to retrieve.
batch_size : int, optional, default 100.
The batch size to use. 100 is a good default option. Increasing
the batch size may increase speed.
show_progressbar : bool, optional, default False
Whether to show a progressbar.
return_names : bool, optional, default True
Whether to return the item names, or just the distances.
Returns
-------
sim : list of tuples.
For each item in the input the num most similar items are returned
in the form of (NAME, DISTANCE) tuples. If return_names is set to
false, only the distances are returned.
"""
vectors = np.array(vectors)
if np.ndim(vectors) == 1:
vectors = vectors[None, :]
result = []
result = self._batch(vectors,
batch_size,
num+1,
show_progressbar,
return_names)
return list(result)
def nearest_neighbor_threshold(self,
vectors,
threshold=.5,
batch_size=100,
show_progressbar=False,
return_names=True):
"""
Find the nearest neighbors to some arbitrary vector.
This function is meant to be used in composition operations. The
most_similar function can only handle items that are in vocab, and
looks up their vector through a dictionary. Compositions, e.g.
"King - man + woman" are necessarily not in the vocabulary.
Parameters
----------
vectors : list of arrays or numpy array
The vectors to find the nearest neighbors to.
threshold : float, optional, default .5
The threshold within to retrieve items.
batch_size : int, optional, default 100.
The batch size to use. 100 is a good default option. Increasing
the batch size may increase speed.
show_progressbar : bool, optional, default False
Whether to show a progressbar.
return_names : bool, optional, default True
Whether to return the item names, or just the distances.
Returns
-------
sim : list of tuples.
For each item in the input the num most similar items are returned
in the form of (NAME, DISTANCE) tuples. If return_names is set to
false, only the distances are returned.
"""
vectors = np.array(vectors)
if np.ndim(vectors) == 1:
vectors = vectors[None, :]
result = []
result = self._threshold_batch(vectors,
batch_size,
threshold,
show_progressbar,
return_names)
return list(result)
def _threshold_batch(self,
vectors,
batch_size,
threshold,
show_progressbar,
return_names):
"""Batched cosine distance."""
vectors = self.normalize(vectors)
# Single transpose, makes things faster.
reference_transposed = self.norm_vectors.T
for i in tqdm(range(0, len(vectors), batch_size),
disable=not show_progressbar):
distances = vectors[i: i+batch_size].dot(reference_transposed)
# For safety we clip
distances = np.clip(distances, a_min=.0, a_max=1.0)
for lidx, dists in enumerate(distances):
indices = np.flatnonzero(dists >= threshold)
sorted_indices = indices[np.argsort(-dists[indices])]
if return_names:
yield [(self.indices[d], dists[d])
for d in sorted_indices]
else:
yield list(dists[sorted_indices])
def _batch(self,
vectors,
batch_size,
num,
show_progressbar,
return_names):
"""Batched cosine distance."""
vectors = self.normalize(vectors)
# Single transpose, makes things faster.
reference_transposed = self.norm_vectors.T
for i in tqdm(range(0, len(vectors), batch_size),
disable=not show_progressbar):
distances = vectors[i: i+batch_size].dot(reference_transposed)
# For safety we clip
distances = np.clip(distances, a_min=.0, a_max=1.0)
if num == 1:
sorted_indices = np.argmax(distances, 1)[:, None]
else:
sorted_indices = np.argpartition(-distances, kth=num, axis=1)
sorted_indices = sorted_indices[:, :num]
for lidx, indices in enumerate(sorted_indices):
dists = distances[lidx, indices]
if return_names:
dindex = np.argsort(-dists)
yield [(self.indices[indices[d]], dists[d])
for d in dindex]
else:
yield list(-1 * np.sort(-dists))
@staticmethod
def normalize(vectors):
"""
Normalize a matrix of row vectors to unit length.
Contains a shortcut if there are no zero vectors in the matrix.
If there are zero vectors, we do some indexing tricks to avoid
dividing by 0.
Parameters
----------
vectors : np.array
The vectors to normalize.
Returns
-------
vectors : np.array
The input vectors, normalized to unit length.
"""
if np.ndim(vectors) == 1:
norm = np.linalg.norm(vectors)
if norm == 0:
return np.zeros_like(vectors)
return vectors / norm
norm = np.linalg.norm(vectors, axis=1)
if np.any(norm == 0):
nonzero = norm > 0
result = np.zeros_like(vectors)
n = norm[nonzero]
p = vectors[nonzero]
result[nonzero] = p / n[:, None]
return result
else:
return vectors / norm[:, None]
def vector_similarity(self, vector, items):
"""Compute the similarity between a vector and a set of items."""
vector = self.normalize(vector)
items_vec = np.stack([self.norm_vectors[self.items[x]] for x in items])
return vector.dot(items_vec.T)
def similarity(self, i1, i2):
"""
Compute the similarity between two sets of items.
Parameters
----------
i1 : object
The first set of items.
i2 : object
The second set of item.
Returns
-------
sim : array of floats
An array of similarity scores between 1 and 0.
"""
try:
if i1 in self.items:
i1 = [i1]
except TypeError:
pass
try:
if i2 in self.items:
i2 = [i2]
except TypeError:
pass
i1_vec = np.stack([self.norm_vectors[self.items[x]] for x in i1])
i2_vec = np.stack([self.norm_vectors[self.items[x]] for x in i2])
return i1_vec.dot(i2_vec.T)
def prune(self, wordlist):
"""
Prune the current reach instance by removing items.
Parameters
----------
wordlist : list of str
A list of words to keep. Note that this wordlist need not include
all words in the Reach instance. Any words which are in the
wordlist, but not in the reach instance are ignored.
"""
# Remove duplicates
wordlist = set(wordlist).intersection(set(self.items.keys()))
indices = [self.items[w] for w in wordlist if w in self.items]
if self.unk_index is not None and self.unk_index not in indices:
raise ValueError("Your unknown item is not in your list of items. "
"Set it to None before pruning, or pass your "
"unknown item.")
self.vectors = self.vectors[indices]
self.norm_vectors = self.norm_vectors[indices]
self.items = {w: idx for idx, w in enumerate(wordlist)}
self.indices = {v: k for k, v in self.items.items()}
if self.unk_index is not None:
self.unk_index = self.items[wordlist[self.unk_index]]
def save(self, path, write_header=True):
"""
Save the current vector space in word2vec format.
Parameters
----------
path : str
The path to save the vector file to.
write_header : bool, optional, default True
Whether to write a word2vec-style header as the first line of the
file
"""
with open(path, 'w') as f:
if write_header:
f.write(u"{0} {1}\n".format(str(self.vectors.shape[0]),
str(self.vectors.shape[1])))
for i in range(len(self.items)):
w = self.indices[i]
vec = self.vectors[i]
f.write(u"{0} {1}\n".format(w,
" ".join([str(x) for x in vec])))
def save_fast_format(self, filename):
"""
Save a reach instance in a fast format.
The reach fast format stores the words and vectors of a Reach instance
separately in a JSON and numpy format, respectively.
Parameters
----------
filename : str
The prefix to add to the saved filename. Note that this is not the
real filename under which these items are stored.
The words and unk_index are stored under "{filename}_words.json",
and the numpy matrix is saved under "{filename}_vectors.npy".
"""
items, _ = zip(*sorted(self.items.items(), key=lambda x: x[1]))
items = {"items": items,
"unk_index": self.unk_index,
"name": self.name}
json.dump(items, open("{}_items.json".format(filename), 'w'))
np.save(open("{}_vectors.npy".format(filename), 'wb'), self.vectors)
@staticmethod
def load_fast_format(filename):
"""
Load a reach instance in fast format.
As described above, the fast format stores the words and vectors of the
Reach instance separately, and is drastically faster than loading from
.txt files.
Parameters
----------
filename : str
The filename prefix from which to load. Note that this is not a
real filepath as such, but a shared prefix for both files.
In order for this to work, both {filename}_words.json and
{filename}_vectors.npy should be present.
"""
words, unk_index, name, vectors = Reach._load_fast(filename)
return Reach(vectors, words, unk_index=unk_index, name=name)
@staticmethod
def _load_fast(filename):
"""Sub for fast loader."""
it = json.load(open("{}_items.json".format(filename)))
words, unk_index, name = it["items"], it["unk_index"], it["name"]
vectors = np.load(open("{}_vectors.npy".format(filename), 'rb'))
return words, unk_index, name, vectors
|
stephantul/reach
|
reach/reach.py
|
Reach.transform
|
python
|
def transform(self, corpus, remove_oov=False, norm=False):
return [self.vectorize(s, remove_oov=remove_oov, norm=norm)
for s in corpus]
|
Transform a corpus by repeated calls to vectorize, defined above.
Parameters
----------
corpus : A list of strings, list of list of strings.
Represents a corpus as a list of sentences, where sentences
can either be strings or lists of tokens.
remove_oov : bool, optional, default False
If True, removes OOV items from the input before vectorization.
Returns
-------
c : list
A list of numpy arrays, where each array represents the transformed
sentence in the original list. The list is guaranteed to be the
same length as the input list, but the arrays in the list may be
of different lengths, depending on whether remove_oov is True.
|
train
|
https://github.com/stephantul/reach/blob/e5ed0cc895d17429e797c6d7dd57bce82ff00d5d/reach/reach.py#L281-L303
| null |
class Reach(object):
"""
Work with vector representations of items.
Supports functions for calculating fast batched similarity
between items or composite representations of items.
Parameters
----------
vectors : numpy array
The vector space.
items : list
A list of items. Length must be equal to the number of vectors, and
aligned with the vectors.
name : string, optional
A string giving the name of the current reach. Only useful if you
have multiple spaces and want to keep track of them.
Attributes
----------
items : dict
A mapping from items to ids.
indices : dict
A mapping from ids to items.
vectors : numpy array
The array representing the vector space.
norm_vectors : numpy array
A normalized version of the vector space.
unk_index : int
The integer index of your unknown glyph. This glyph will be inserted
into your BoW space whenever an unknown item is encountered.
size : int
The dimensionality of the vector space.
name : string
The name of the Reach instance.
"""
def __init__(self, vectors, items, name="", unk_index=None):
"""Initialize a Reach instance with an array and list of items."""
if len(items) != len(vectors):
raise ValueError("Your vector space and list of items are not "
"the same length: "
"{} != {}".format(len(vectors), len(items)))
if isinstance(items, dict) or isinstance(items, set):
raise ValueError("Your item list is a set or dict, and might not "
"retain order in the conversion to internal look"
"-ups. Please convert it to list and check the "
"order.")
self.items = {w: idx for idx, w in enumerate(items)}
self.indices = {v: k for k, v in self.items.items()}
self.vectors = np.asarray(vectors)
self.norm_vectors = self.normalize(self.vectors)
self.unk_index = unk_index
self.size = self.vectors.shape[1]
self.name = name
@staticmethod
def load(pathtovector,
wordlist=(),
num_to_load=None,
truncate_embeddings=None,
unk_word=None,
sep=" "):
r"""
Read a file in word2vec .txt format.
The load function will raise a ValueError when trying to load items
which do not conform to line lengths.
Parameters
----------
pathtovector : string
The path to the vector file.
header : bool
Whether the vector file has a header of the type
(NUMBER OF ITEMS, SIZE OF VECTOR).
wordlist : iterable, optional, default ()
A list of words you want loaded from the vector file. If this is
None (default), all words will be loaded.
num_to_load : int, optional, default None
The number of items to load from the file. Because loading can take
some time, it is sometimes useful to onlyl load the first n items
from a vector file for quick inspection.
truncate_embeddings : int, optional, default None
If this value is not None, the vectors in the vector space will
be truncated to the number of dimensions indicated by this value.
unk_word : object
The object to treat as UNK in your vector space. If this is not
in your items dictionary after loading, we add it with a zero
vector.
Returns
-------
r : Reach
An initialized Reach instance.
"""
vectors, items = Reach._load(pathtovector,
wordlist,
num_to_load,
truncate_embeddings,
sep)
if unk_word is not None:
if unk_word not in set(items):
unk_vec = np.zeros((1, vectors.shape[1]))
vectors = np.concatenate([unk_vec, vectors], 0)
items = [unk_word] + items
unk_index = 0
else:
unk_index = items.index(unk_word)
else:
unk_index = None
return Reach(vectors,
items,
name=os.path.split(pathtovector)[-1],
unk_index=unk_index)
@staticmethod
def _load(pathtovector,
wordlist,
num_to_load=None,
truncate_embeddings=None,
sep=" "):
"""Load a matrix and wordlist from a .vec file."""
vectors = []
addedwords = set()
words = []
try:
wordlist = set(wordlist)
except ValueError:
wordlist = set()
logger.info("Loading {0}".format(pathtovector))
firstline = open(pathtovector).readline().strip()
try:
num, size = firstline.split(sep)
num, size = int(num), int(size)
logger.info("Vector space: {} by {}".format(num, size))
header = True
except ValueError:
size = len(firstline.split(sep)) - 1
logger.info("Vector space: {} dim, # items unknown".format(size))
word, rest = firstline.split(sep, 1)
# If the first line is correctly parseable, set header to False.
header = False
if truncate_embeddings is None or truncate_embeddings == 0:
truncate_embeddings = size
for idx, line in enumerate(open(pathtovector, encoding='utf-8')):
if header and idx == 0:
continue
word, rest = line.rstrip(" \n").split(sep, 1)
if wordlist and word not in wordlist:
continue
if word in addedwords:
raise ValueError("Duplicate: {} on line {} was in the "
"vector space twice".format(word, idx))
if len(rest.split(sep)) != size:
raise ValueError("Incorrect input at index {}, size "
"is {}, expected "
"{}".format(idx+1,
len(rest.split(sep)), size))
words.append(word)
addedwords.add(word)
vectors.append(np.fromstring(rest, sep=sep)[:truncate_embeddings])
if num_to_load is not None and len(addedwords) >= num_to_load:
break
vectors = np.array(vectors).astype(np.float32)
logger.info("Loading finished")
if wordlist:
diff = wordlist - addedwords
if diff:
logger.info("Not all items from your wordlist were in your "
"vector space: {}.".format(diff))
return vectors, words
def __getitem__(self, item):
"""Get the vector for a single item."""
return self.vectors[self.items[item]]
def vectorize(self, tokens, remove_oov=False, norm=False):
"""
Vectorize a sentence by replacing all items with their vectors.
Parameters
----------
tokens : object or list of objects
The tokens to vectorize.
remove_oov : bool, optional, default False
Whether to remove OOV items. If False, OOV items are replaced by
the UNK glyph. If this is True, the returned sequence might
have a different length than the original sequence.
norm : bool, optional, default False
Whether to return the unit vectors, or the regular vectors.
Returns
-------
s : numpy array
An M * N matrix, where every item has been replaced by
its vector. OOV items are either removed, or replaced
by the value of the UNK glyph.
"""
if not tokens:
raise ValueError("You supplied an empty list.")
index = list(self.bow(tokens, remove_oov=remove_oov))
if not index:
raise ValueError("You supplied a list with only OOV tokens: {}, "
"which then got removed. Set remove_oov to False,"
" or filter your sentences to remove any in which"
" all items are OOV.")
if norm:
return np.stack([self.norm_vectors[x] for x in index])
else:
return np.stack([self.vectors[x] for x in index])
def bow(self, tokens, remove_oov=False):
"""
Create a bow representation of a list of tokens.
Parameters
----------
tokens : list.
The list of items to change into a bag of words representation.
remove_oov : bool.
Whether to remove OOV items from the input.
If this is True, the length of the returned BOW representation
might not be the length of the original representation.
Returns
-------
bow : generator
A BOW representation of the list of items.
"""
if remove_oov:
tokens = [x for x in tokens if x in self.items]
for t in tokens:
try:
yield self.items[t]
except KeyError:
if self.unk_index is None:
raise ValueError("You supplied OOV items but didn't "
"provide the index of the replacement "
"glyph. Either set remove_oov to True, "
"or set unk_index to the index of the "
"item which replaces any OOV items.")
yield self.unk_index
def most_similar(self,
items,
num=10,
batch_size=100,
show_progressbar=False,
return_names=True):
"""
Return the num most similar items to a given list of items.
Parameters
----------
items : list of objects or a single object.
The items to get the most similar items to.
num : int, optional, default 10
The number of most similar items to retrieve.
batch_size : int, optional, default 100.
The batch size to use. 100 is a good default option. Increasing
the batch size may increase the speed.
show_progressbar : bool, optional, default False
Whether to show a progressbar.
return_names : bool, optional, default True
Whether to return the item names, or just the distances.
Returns
-------
sim : array
For each items in the input the num most similar items are returned
in the form of (NAME, DISTANCE) tuples. If return_names is false,
the returned list just contains distances.
"""
# This line allows users to input single items.
# We used to rely on string identities, but we now also allow
# anything hashable as keys.
# Might fail if a list of passed items is also in the vocabulary.
# but I can't think of cases when this would happen, and what
# user expectations are.
try:
if items in self.items:
items = [items]
except TypeError:
pass
x = np.stack([self.norm_vectors[self.items[x]] for x in items])
result = self._batch(x,
batch_size,
num+1,
show_progressbar,
return_names)
# list call consumes the generator.
return [x[1:] for x in result]
def threshold(self,
items,
threshold=.5,
batch_size=100,
show_progressbar=False,
return_names=True):
"""
Return all items whose similarity is higher than threshold.
Parameters
----------
items : list of objects or a single object.
The items to get the most similar items to.
threshold : float, optional, default .5
The radius within which to retrieve items.
batch_size : int, optional, default 100.
The batch size to use. 100 is a good default option. Increasing
the batch size may increase the speed.
show_progressbar : bool, optional, default False
Whether to show a progressbar.
return_names : bool, optional, default True
Whether to return the item names, or just the distances.
Returns
-------
sim : array
For each items in the input the num most similar items are returned
in the form of (NAME, DISTANCE) tuples. If return_names is false,
the returned list just contains distances.
"""
# This line allows users to input single items.
# We used to rely on string identities, but we now also allow
# anything hashable as keys.
# Might fail if a list of passed items is also in the vocabulary.
# but I can't think of cases when this would happen, and what
# user expectations are.
try:
if items in self.items:
items = [items]
except TypeError:
pass
x = np.stack([self.norm_vectors[self.items[x]] for x in items])
result = self._threshold_batch(x,
batch_size,
threshold,
show_progressbar,
return_names)
# list call consumes the generator.
return [x[1:] for x in result]
def nearest_neighbor(self,
vectors,
num=10,
batch_size=100,
show_progressbar=False,
return_names=True):
"""
Find the nearest neighbors to some arbitrary vector.
This function is meant to be used in composition operations. The
most_similar function can only handle items that are in vocab, and
looks up their vector through a dictionary. Compositions, e.g.
"King - man + woman" are necessarily not in the vocabulary.
Parameters
----------
vectors : list of arrays or numpy array
The vectors to find the nearest neighbors to.
num : int, optional, default 10
The number of most similar items to retrieve.
batch_size : int, optional, default 100.
The batch size to use. 100 is a good default option. Increasing
the batch size may increase speed.
show_progressbar : bool, optional, default False
Whether to show a progressbar.
return_names : bool, optional, default True
Whether to return the item names, or just the distances.
Returns
-------
sim : list of tuples.
For each item in the input the num most similar items are returned
in the form of (NAME, DISTANCE) tuples. If return_names is set to
false, only the distances are returned.
"""
vectors = np.array(vectors)
if np.ndim(vectors) == 1:
vectors = vectors[None, :]
result = []
result = self._batch(vectors,
batch_size,
num+1,
show_progressbar,
return_names)
return list(result)
def nearest_neighbor_threshold(self,
vectors,
threshold=.5,
batch_size=100,
show_progressbar=False,
return_names=True):
"""
Find the nearest neighbors to some arbitrary vector.
This function is meant to be used in composition operations. The
most_similar function can only handle items that are in vocab, and
looks up their vector through a dictionary. Compositions, e.g.
"King - man + woman" are necessarily not in the vocabulary.
Parameters
----------
vectors : list of arrays or numpy array
The vectors to find the nearest neighbors to.
threshold : float, optional, default .5
The threshold within to retrieve items.
batch_size : int, optional, default 100.
The batch size to use. 100 is a good default option. Increasing
the batch size may increase speed.
show_progressbar : bool, optional, default False
Whether to show a progressbar.
return_names : bool, optional, default True
Whether to return the item names, or just the distances.
Returns
-------
sim : list of tuples.
For each item in the input the num most similar items are returned
in the form of (NAME, DISTANCE) tuples. If return_names is set to
false, only the distances are returned.
"""
vectors = np.array(vectors)
if np.ndim(vectors) == 1:
vectors = vectors[None, :]
result = []
result = self._threshold_batch(vectors,
batch_size,
threshold,
show_progressbar,
return_names)
return list(result)
def _threshold_batch(self,
vectors,
batch_size,
threshold,
show_progressbar,
return_names):
"""Batched cosine distance."""
vectors = self.normalize(vectors)
# Single transpose, makes things faster.
reference_transposed = self.norm_vectors.T
for i in tqdm(range(0, len(vectors), batch_size),
disable=not show_progressbar):
distances = vectors[i: i+batch_size].dot(reference_transposed)
# For safety we clip
distances = np.clip(distances, a_min=.0, a_max=1.0)
for lidx, dists in enumerate(distances):
indices = np.flatnonzero(dists >= threshold)
sorted_indices = indices[np.argsort(-dists[indices])]
if return_names:
yield [(self.indices[d], dists[d])
for d in sorted_indices]
else:
yield list(dists[sorted_indices])
def _batch(self,
vectors,
batch_size,
num,
show_progressbar,
return_names):
"""Batched cosine distance."""
vectors = self.normalize(vectors)
# Single transpose, makes things faster.
reference_transposed = self.norm_vectors.T
for i in tqdm(range(0, len(vectors), batch_size),
disable=not show_progressbar):
distances = vectors[i: i+batch_size].dot(reference_transposed)
# For safety we clip
distances = np.clip(distances, a_min=.0, a_max=1.0)
if num == 1:
sorted_indices = np.argmax(distances, 1)[:, None]
else:
sorted_indices = np.argpartition(-distances, kth=num, axis=1)
sorted_indices = sorted_indices[:, :num]
for lidx, indices in enumerate(sorted_indices):
dists = distances[lidx, indices]
if return_names:
dindex = np.argsort(-dists)
yield [(self.indices[indices[d]], dists[d])
for d in dindex]
else:
yield list(-1 * np.sort(-dists))
@staticmethod
def normalize(vectors):
"""
Normalize a matrix of row vectors to unit length.
Contains a shortcut if there are no zero vectors in the matrix.
If there are zero vectors, we do some indexing tricks to avoid
dividing by 0.
Parameters
----------
vectors : np.array
The vectors to normalize.
Returns
-------
vectors : np.array
The input vectors, normalized to unit length.
"""
if np.ndim(vectors) == 1:
norm = np.linalg.norm(vectors)
if norm == 0:
return np.zeros_like(vectors)
return vectors / norm
norm = np.linalg.norm(vectors, axis=1)
if np.any(norm == 0):
nonzero = norm > 0
result = np.zeros_like(vectors)
n = norm[nonzero]
p = vectors[nonzero]
result[nonzero] = p / n[:, None]
return result
else:
return vectors / norm[:, None]
def vector_similarity(self, vector, items):
"""Compute the similarity between a vector and a set of items."""
vector = self.normalize(vector)
items_vec = np.stack([self.norm_vectors[self.items[x]] for x in items])
return vector.dot(items_vec.T)
def similarity(self, i1, i2):
"""
Compute the similarity between two sets of items.
Parameters
----------
i1 : object
The first set of items.
i2 : object
The second set of item.
Returns
-------
sim : array of floats
An array of similarity scores between 1 and 0.
"""
try:
if i1 in self.items:
i1 = [i1]
except TypeError:
pass
try:
if i2 in self.items:
i2 = [i2]
except TypeError:
pass
i1_vec = np.stack([self.norm_vectors[self.items[x]] for x in i1])
i2_vec = np.stack([self.norm_vectors[self.items[x]] for x in i2])
return i1_vec.dot(i2_vec.T)
def prune(self, wordlist):
"""
Prune the current reach instance by removing items.
Parameters
----------
wordlist : list of str
A list of words to keep. Note that this wordlist need not include
all words in the Reach instance. Any words which are in the
wordlist, but not in the reach instance are ignored.
"""
# Remove duplicates
wordlist = set(wordlist).intersection(set(self.items.keys()))
indices = [self.items[w] for w in wordlist if w in self.items]
if self.unk_index is not None and self.unk_index not in indices:
raise ValueError("Your unknown item is not in your list of items. "
"Set it to None before pruning, or pass your "
"unknown item.")
self.vectors = self.vectors[indices]
self.norm_vectors = self.norm_vectors[indices]
self.items = {w: idx for idx, w in enumerate(wordlist)}
self.indices = {v: k for k, v in self.items.items()}
if self.unk_index is not None:
self.unk_index = self.items[wordlist[self.unk_index]]
def save(self, path, write_header=True):
"""
Save the current vector space in word2vec format.
Parameters
----------
path : str
The path to save the vector file to.
write_header : bool, optional, default True
Whether to write a word2vec-style header as the first line of the
file
"""
with open(path, 'w') as f:
if write_header:
f.write(u"{0} {1}\n".format(str(self.vectors.shape[0]),
str(self.vectors.shape[1])))
for i in range(len(self.items)):
w = self.indices[i]
vec = self.vectors[i]
f.write(u"{0} {1}\n".format(w,
" ".join([str(x) for x in vec])))
def save_fast_format(self, filename):
"""
Save a reach instance in a fast format.
The reach fast format stores the words and vectors of a Reach instance
separately in a JSON and numpy format, respectively.
Parameters
----------
filename : str
The prefix to add to the saved filename. Note that this is not the
real filename under which these items are stored.
The words and unk_index are stored under "{filename}_words.json",
and the numpy matrix is saved under "{filename}_vectors.npy".
"""
items, _ = zip(*sorted(self.items.items(), key=lambda x: x[1]))
items = {"items": items,
"unk_index": self.unk_index,
"name": self.name}
json.dump(items, open("{}_items.json".format(filename), 'w'))
np.save(open("{}_vectors.npy".format(filename), 'wb'), self.vectors)
@staticmethod
def load_fast_format(filename):
"""
Load a reach instance in fast format.
As described above, the fast format stores the words and vectors of the
Reach instance separately, and is drastically faster than loading from
.txt files.
Parameters
----------
filename : str
The filename prefix from which to load. Note that this is not a
real filepath as such, but a shared prefix for both files.
In order for this to work, both {filename}_words.json and
{filename}_vectors.npy should be present.
"""
words, unk_index, name, vectors = Reach._load_fast(filename)
return Reach(vectors, words, unk_index=unk_index, name=name)
@staticmethod
def _load_fast(filename):
"""Sub for fast loader."""
it = json.load(open("{}_items.json".format(filename)))
words, unk_index, name = it["items"], it["unk_index"], it["name"]
vectors = np.load(open("{}_vectors.npy".format(filename), 'rb'))
return words, unk_index, name, vectors
|
stephantul/reach
|
reach/reach.py
|
Reach.most_similar
|
python
|
def most_similar(self,
items,
num=10,
batch_size=100,
show_progressbar=False,
return_names=True):
# This line allows users to input single items.
# We used to rely on string identities, but we now also allow
# anything hashable as keys.
# Might fail if a list of passed items is also in the vocabulary.
# but I can't think of cases when this would happen, and what
# user expectations are.
try:
if items in self.items:
items = [items]
except TypeError:
pass
x = np.stack([self.norm_vectors[self.items[x]] for x in items])
result = self._batch(x,
batch_size,
num+1,
show_progressbar,
return_names)
# list call consumes the generator.
return [x[1:] for x in result]
|
Return the num most similar items to a given list of items.
Parameters
----------
items : list of objects or a single object.
The items to get the most similar items to.
num : int, optional, default 10
The number of most similar items to retrieve.
batch_size : int, optional, default 100.
The batch size to use. 100 is a good default option. Increasing
the batch size may increase the speed.
show_progressbar : bool, optional, default False
Whether to show a progressbar.
return_names : bool, optional, default True
Whether to return the item names, or just the distances.
Returns
-------
sim : array
For each items in the input the num most similar items are returned
in the form of (NAME, DISTANCE) tuples. If return_names is false,
the returned list just contains distances.
|
train
|
https://github.com/stephantul/reach/blob/e5ed0cc895d17429e797c6d7dd57bce82ff00d5d/reach/reach.py#L305-L356
|
[
"def _batch(self,\n vectors,\n batch_size,\n num,\n show_progressbar,\n return_names):\n \"\"\"Batched cosine distance.\"\"\"\n vectors = self.normalize(vectors)\n\n # Single transpose, makes things faster.\n reference_transposed = self.norm_vectors.T\n\n for i in tqdm(range(0, len(vectors), batch_size),\n disable=not show_progressbar):\n\n distances = vectors[i: i+batch_size].dot(reference_transposed)\n # For safety we clip\n distances = np.clip(distances, a_min=.0, a_max=1.0)\n if num == 1:\n sorted_indices = np.argmax(distances, 1)[:, None]\n else:\n sorted_indices = np.argpartition(-distances, kth=num, axis=1)\n sorted_indices = sorted_indices[:, :num]\n for lidx, indices in enumerate(sorted_indices):\n dists = distances[lidx, indices]\n if return_names:\n dindex = np.argsort(-dists)\n yield [(self.indices[indices[d]], dists[d])\n for d in dindex]\n else:\n yield list(-1 * np.sort(-dists))\n"
] |
class Reach(object):
"""
Work with vector representations of items.
Supports functions for calculating fast batched similarity
between items or composite representations of items.
Parameters
----------
vectors : numpy array
The vector space.
items : list
A list of items. Length must be equal to the number of vectors, and
aligned with the vectors.
name : string, optional
A string giving the name of the current reach. Only useful if you
have multiple spaces and want to keep track of them.
Attributes
----------
items : dict
A mapping from items to ids.
indices : dict
A mapping from ids to items.
vectors : numpy array
The array representing the vector space.
norm_vectors : numpy array
A normalized version of the vector space.
unk_index : int
The integer index of your unknown glyph. This glyph will be inserted
into your BoW space whenever an unknown item is encountered.
size : int
The dimensionality of the vector space.
name : string
The name of the Reach instance.
"""
def __init__(self, vectors, items, name="", unk_index=None):
"""Initialize a Reach instance with an array and list of items."""
if len(items) != len(vectors):
raise ValueError("Your vector space and list of items are not "
"the same length: "
"{} != {}".format(len(vectors), len(items)))
if isinstance(items, dict) or isinstance(items, set):
raise ValueError("Your item list is a set or dict, and might not "
"retain order in the conversion to internal look"
"-ups. Please convert it to list and check the "
"order.")
self.items = {w: idx for idx, w in enumerate(items)}
self.indices = {v: k for k, v in self.items.items()}
self.vectors = np.asarray(vectors)
self.norm_vectors = self.normalize(self.vectors)
self.unk_index = unk_index
self.size = self.vectors.shape[1]
self.name = name
@staticmethod
def load(pathtovector,
wordlist=(),
num_to_load=None,
truncate_embeddings=None,
unk_word=None,
sep=" "):
r"""
Read a file in word2vec .txt format.
The load function will raise a ValueError when trying to load items
which do not conform to line lengths.
Parameters
----------
pathtovector : string
The path to the vector file.
header : bool
Whether the vector file has a header of the type
(NUMBER OF ITEMS, SIZE OF VECTOR).
wordlist : iterable, optional, default ()
A list of words you want loaded from the vector file. If this is
None (default), all words will be loaded.
num_to_load : int, optional, default None
The number of items to load from the file. Because loading can take
some time, it is sometimes useful to onlyl load the first n items
from a vector file for quick inspection.
truncate_embeddings : int, optional, default None
If this value is not None, the vectors in the vector space will
be truncated to the number of dimensions indicated by this value.
unk_word : object
The object to treat as UNK in your vector space. If this is not
in your items dictionary after loading, we add it with a zero
vector.
Returns
-------
r : Reach
An initialized Reach instance.
"""
vectors, items = Reach._load(pathtovector,
wordlist,
num_to_load,
truncate_embeddings,
sep)
if unk_word is not None:
if unk_word not in set(items):
unk_vec = np.zeros((1, vectors.shape[1]))
vectors = np.concatenate([unk_vec, vectors], 0)
items = [unk_word] + items
unk_index = 0
else:
unk_index = items.index(unk_word)
else:
unk_index = None
return Reach(vectors,
items,
name=os.path.split(pathtovector)[-1],
unk_index=unk_index)
@staticmethod
def _load(pathtovector,
wordlist,
num_to_load=None,
truncate_embeddings=None,
sep=" "):
"""Load a matrix and wordlist from a .vec file."""
vectors = []
addedwords = set()
words = []
try:
wordlist = set(wordlist)
except ValueError:
wordlist = set()
logger.info("Loading {0}".format(pathtovector))
firstline = open(pathtovector).readline().strip()
try:
num, size = firstline.split(sep)
num, size = int(num), int(size)
logger.info("Vector space: {} by {}".format(num, size))
header = True
except ValueError:
size = len(firstline.split(sep)) - 1
logger.info("Vector space: {} dim, # items unknown".format(size))
word, rest = firstline.split(sep, 1)
# If the first line is correctly parseable, set header to False.
header = False
if truncate_embeddings is None or truncate_embeddings == 0:
truncate_embeddings = size
for idx, line in enumerate(open(pathtovector, encoding='utf-8')):
if header and idx == 0:
continue
word, rest = line.rstrip(" \n").split(sep, 1)
if wordlist and word not in wordlist:
continue
if word in addedwords:
raise ValueError("Duplicate: {} on line {} was in the "
"vector space twice".format(word, idx))
if len(rest.split(sep)) != size:
raise ValueError("Incorrect input at index {}, size "
"is {}, expected "
"{}".format(idx+1,
len(rest.split(sep)), size))
words.append(word)
addedwords.add(word)
vectors.append(np.fromstring(rest, sep=sep)[:truncate_embeddings])
if num_to_load is not None and len(addedwords) >= num_to_load:
break
vectors = np.array(vectors).astype(np.float32)
logger.info("Loading finished")
if wordlist:
diff = wordlist - addedwords
if diff:
logger.info("Not all items from your wordlist were in your "
"vector space: {}.".format(diff))
return vectors, words
def __getitem__(self, item):
"""Get the vector for a single item."""
return self.vectors[self.items[item]]
def vectorize(self, tokens, remove_oov=False, norm=False):
"""
Vectorize a sentence by replacing all items with their vectors.
Parameters
----------
tokens : object or list of objects
The tokens to vectorize.
remove_oov : bool, optional, default False
Whether to remove OOV items. If False, OOV items are replaced by
the UNK glyph. If this is True, the returned sequence might
have a different length than the original sequence.
norm : bool, optional, default False
Whether to return the unit vectors, or the regular vectors.
Returns
-------
s : numpy array
An M * N matrix, where every item has been replaced by
its vector. OOV items are either removed, or replaced
by the value of the UNK glyph.
"""
if not tokens:
raise ValueError("You supplied an empty list.")
index = list(self.bow(tokens, remove_oov=remove_oov))
if not index:
raise ValueError("You supplied a list with only OOV tokens: {}, "
"which then got removed. Set remove_oov to False,"
" or filter your sentences to remove any in which"
" all items are OOV.")
if norm:
return np.stack([self.norm_vectors[x] for x in index])
else:
return np.stack([self.vectors[x] for x in index])
def bow(self, tokens, remove_oov=False):
"""
Create a bow representation of a list of tokens.
Parameters
----------
tokens : list.
The list of items to change into a bag of words representation.
remove_oov : bool.
Whether to remove OOV items from the input.
If this is True, the length of the returned BOW representation
might not be the length of the original representation.
Returns
-------
bow : generator
A BOW representation of the list of items.
"""
if remove_oov:
tokens = [x for x in tokens if x in self.items]
for t in tokens:
try:
yield self.items[t]
except KeyError:
if self.unk_index is None:
raise ValueError("You supplied OOV items but didn't "
"provide the index of the replacement "
"glyph. Either set remove_oov to True, "
"or set unk_index to the index of the "
"item which replaces any OOV items.")
yield self.unk_index
def transform(self, corpus, remove_oov=False, norm=False):
"""
Transform a corpus by repeated calls to vectorize, defined above.
Parameters
----------
corpus : A list of strings, list of list of strings.
Represents a corpus as a list of sentences, where sentences
can either be strings or lists of tokens.
remove_oov : bool, optional, default False
If True, removes OOV items from the input before vectorization.
Returns
-------
c : list
A list of numpy arrays, where each array represents the transformed
sentence in the original list. The list is guaranteed to be the
same length as the input list, but the arrays in the list may be
of different lengths, depending on whether remove_oov is True.
"""
return [self.vectorize(s, remove_oov=remove_oov, norm=norm)
for s in corpus]
def threshold(self,
items,
threshold=.5,
batch_size=100,
show_progressbar=False,
return_names=True):
"""
Return all items whose similarity is higher than threshold.
Parameters
----------
items : list of objects or a single object.
The items to get the most similar items to.
threshold : float, optional, default .5
The radius within which to retrieve items.
batch_size : int, optional, default 100.
The batch size to use. 100 is a good default option. Increasing
the batch size may increase the speed.
show_progressbar : bool, optional, default False
Whether to show a progressbar.
return_names : bool, optional, default True
Whether to return the item names, or just the distances.
Returns
-------
sim : array
For each items in the input the num most similar items are returned
in the form of (NAME, DISTANCE) tuples. If return_names is false,
the returned list just contains distances.
"""
# This line allows users to input single items.
# We used to rely on string identities, but we now also allow
# anything hashable as keys.
# Might fail if a list of passed items is also in the vocabulary.
# but I can't think of cases when this would happen, and what
# user expectations are.
try:
if items in self.items:
items = [items]
except TypeError:
pass
x = np.stack([self.norm_vectors[self.items[x]] for x in items])
result = self._threshold_batch(x,
batch_size,
threshold,
show_progressbar,
return_names)
# list call consumes the generator.
return [x[1:] for x in result]
def nearest_neighbor(self,
vectors,
num=10,
batch_size=100,
show_progressbar=False,
return_names=True):
"""
Find the nearest neighbors to some arbitrary vector.
This function is meant to be used in composition operations. The
most_similar function can only handle items that are in vocab, and
looks up their vector through a dictionary. Compositions, e.g.
"King - man + woman" are necessarily not in the vocabulary.
Parameters
----------
vectors : list of arrays or numpy array
The vectors to find the nearest neighbors to.
num : int, optional, default 10
The number of most similar items to retrieve.
batch_size : int, optional, default 100.
The batch size to use. 100 is a good default option. Increasing
the batch size may increase speed.
show_progressbar : bool, optional, default False
Whether to show a progressbar.
return_names : bool, optional, default True
Whether to return the item names, or just the distances.
Returns
-------
sim : list of tuples.
For each item in the input the num most similar items are returned
in the form of (NAME, DISTANCE) tuples. If return_names is set to
false, only the distances are returned.
"""
vectors = np.array(vectors)
if np.ndim(vectors) == 1:
vectors = vectors[None, :]
result = []
result = self._batch(vectors,
batch_size,
num+1,
show_progressbar,
return_names)
return list(result)
def nearest_neighbor_threshold(self,
vectors,
threshold=.5,
batch_size=100,
show_progressbar=False,
return_names=True):
"""
Find the nearest neighbors to some arbitrary vector.
This function is meant to be used in composition operations. The
most_similar function can only handle items that are in vocab, and
looks up their vector through a dictionary. Compositions, e.g.
"King - man + woman" are necessarily not in the vocabulary.
Parameters
----------
vectors : list of arrays or numpy array
The vectors to find the nearest neighbors to.
threshold : float, optional, default .5
The threshold within to retrieve items.
batch_size : int, optional, default 100.
The batch size to use. 100 is a good default option. Increasing
the batch size may increase speed.
show_progressbar : bool, optional, default False
Whether to show a progressbar.
return_names : bool, optional, default True
Whether to return the item names, or just the distances.
Returns
-------
sim : list of tuples.
For each item in the input the num most similar items are returned
in the form of (NAME, DISTANCE) tuples. If return_names is set to
false, only the distances are returned.
"""
vectors = np.array(vectors)
if np.ndim(vectors) == 1:
vectors = vectors[None, :]
result = []
result = self._threshold_batch(vectors,
batch_size,
threshold,
show_progressbar,
return_names)
return list(result)
def _threshold_batch(self,
vectors,
batch_size,
threshold,
show_progressbar,
return_names):
"""Batched cosine distance."""
vectors = self.normalize(vectors)
# Single transpose, makes things faster.
reference_transposed = self.norm_vectors.T
for i in tqdm(range(0, len(vectors), batch_size),
disable=not show_progressbar):
distances = vectors[i: i+batch_size].dot(reference_transposed)
# For safety we clip
distances = np.clip(distances, a_min=.0, a_max=1.0)
for lidx, dists in enumerate(distances):
indices = np.flatnonzero(dists >= threshold)
sorted_indices = indices[np.argsort(-dists[indices])]
if return_names:
yield [(self.indices[d], dists[d])
for d in sorted_indices]
else:
yield list(dists[sorted_indices])
def _batch(self,
vectors,
batch_size,
num,
show_progressbar,
return_names):
"""Batched cosine distance."""
vectors = self.normalize(vectors)
# Single transpose, makes things faster.
reference_transposed = self.norm_vectors.T
for i in tqdm(range(0, len(vectors), batch_size),
disable=not show_progressbar):
distances = vectors[i: i+batch_size].dot(reference_transposed)
# For safety we clip
distances = np.clip(distances, a_min=.0, a_max=1.0)
if num == 1:
sorted_indices = np.argmax(distances, 1)[:, None]
else:
sorted_indices = np.argpartition(-distances, kth=num, axis=1)
sorted_indices = sorted_indices[:, :num]
for lidx, indices in enumerate(sorted_indices):
dists = distances[lidx, indices]
if return_names:
dindex = np.argsort(-dists)
yield [(self.indices[indices[d]], dists[d])
for d in dindex]
else:
yield list(-1 * np.sort(-dists))
@staticmethod
def normalize(vectors):
"""
Normalize a matrix of row vectors to unit length.
Contains a shortcut if there are no zero vectors in the matrix.
If there are zero vectors, we do some indexing tricks to avoid
dividing by 0.
Parameters
----------
vectors : np.array
The vectors to normalize.
Returns
-------
vectors : np.array
The input vectors, normalized to unit length.
"""
if np.ndim(vectors) == 1:
norm = np.linalg.norm(vectors)
if norm == 0:
return np.zeros_like(vectors)
return vectors / norm
norm = np.linalg.norm(vectors, axis=1)
if np.any(norm == 0):
nonzero = norm > 0
result = np.zeros_like(vectors)
n = norm[nonzero]
p = vectors[nonzero]
result[nonzero] = p / n[:, None]
return result
else:
return vectors / norm[:, None]
def vector_similarity(self, vector, items):
"""Compute the similarity between a vector and a set of items."""
vector = self.normalize(vector)
items_vec = np.stack([self.norm_vectors[self.items[x]] for x in items])
return vector.dot(items_vec.T)
def similarity(self, i1, i2):
"""
Compute the similarity between two sets of items.
Parameters
----------
i1 : object
The first set of items.
i2 : object
The second set of item.
Returns
-------
sim : array of floats
An array of similarity scores between 1 and 0.
"""
try:
if i1 in self.items:
i1 = [i1]
except TypeError:
pass
try:
if i2 in self.items:
i2 = [i2]
except TypeError:
pass
i1_vec = np.stack([self.norm_vectors[self.items[x]] for x in i1])
i2_vec = np.stack([self.norm_vectors[self.items[x]] for x in i2])
return i1_vec.dot(i2_vec.T)
def prune(self, wordlist):
"""
Prune the current reach instance by removing items.
Parameters
----------
wordlist : list of str
A list of words to keep. Note that this wordlist need not include
all words in the Reach instance. Any words which are in the
wordlist, but not in the reach instance are ignored.
"""
# Remove duplicates
wordlist = set(wordlist).intersection(set(self.items.keys()))
indices = [self.items[w] for w in wordlist if w in self.items]
if self.unk_index is not None and self.unk_index not in indices:
raise ValueError("Your unknown item is not in your list of items. "
"Set it to None before pruning, or pass your "
"unknown item.")
self.vectors = self.vectors[indices]
self.norm_vectors = self.norm_vectors[indices]
self.items = {w: idx for idx, w in enumerate(wordlist)}
self.indices = {v: k for k, v in self.items.items()}
if self.unk_index is not None:
self.unk_index = self.items[wordlist[self.unk_index]]
def save(self, path, write_header=True):
"""
Save the current vector space in word2vec format.
Parameters
----------
path : str
The path to save the vector file to.
write_header : bool, optional, default True
Whether to write a word2vec-style header as the first line of the
file
"""
with open(path, 'w') as f:
if write_header:
f.write(u"{0} {1}\n".format(str(self.vectors.shape[0]),
str(self.vectors.shape[1])))
for i in range(len(self.items)):
w = self.indices[i]
vec = self.vectors[i]
f.write(u"{0} {1}\n".format(w,
" ".join([str(x) for x in vec])))
def save_fast_format(self, filename):
"""
Save a reach instance in a fast format.
The reach fast format stores the words and vectors of a Reach instance
separately in a JSON and numpy format, respectively.
Parameters
----------
filename : str
The prefix to add to the saved filename. Note that this is not the
real filename under which these items are stored.
The words and unk_index are stored under "{filename}_words.json",
and the numpy matrix is saved under "{filename}_vectors.npy".
"""
items, _ = zip(*sorted(self.items.items(), key=lambda x: x[1]))
items = {"items": items,
"unk_index": self.unk_index,
"name": self.name}
json.dump(items, open("{}_items.json".format(filename), 'w'))
np.save(open("{}_vectors.npy".format(filename), 'wb'), self.vectors)
@staticmethod
def load_fast_format(filename):
"""
Load a reach instance in fast format.
As described above, the fast format stores the words and vectors of the
Reach instance separately, and is drastically faster than loading from
.txt files.
Parameters
----------
filename : str
The filename prefix from which to load. Note that this is not a
real filepath as such, but a shared prefix for both files.
In order for this to work, both {filename}_words.json and
{filename}_vectors.npy should be present.
"""
words, unk_index, name, vectors = Reach._load_fast(filename)
return Reach(vectors, words, unk_index=unk_index, name=name)
@staticmethod
def _load_fast(filename):
"""Sub for fast loader."""
it = json.load(open("{}_items.json".format(filename)))
words, unk_index, name = it["items"], it["unk_index"], it["name"]
vectors = np.load(open("{}_vectors.npy".format(filename), 'rb'))
return words, unk_index, name, vectors
|
stephantul/reach
|
reach/reach.py
|
Reach.threshold
|
python
|
def threshold(self,
items,
threshold=.5,
batch_size=100,
show_progressbar=False,
return_names=True):
# This line allows users to input single items.
# We used to rely on string identities, but we now also allow
# anything hashable as keys.
# Might fail if a list of passed items is also in the vocabulary.
# but I can't think of cases when this would happen, and what
# user expectations are.
try:
if items in self.items:
items = [items]
except TypeError:
pass
x = np.stack([self.norm_vectors[self.items[x]] for x in items])
result = self._threshold_batch(x,
batch_size,
threshold,
show_progressbar,
return_names)
# list call consumes the generator.
return [x[1:] for x in result]
|
Return all items whose similarity is higher than threshold.
Parameters
----------
items : list of objects or a single object.
The items to get the most similar items to.
threshold : float, optional, default .5
The radius within which to retrieve items.
batch_size : int, optional, default 100.
The batch size to use. 100 is a good default option. Increasing
the batch size may increase the speed.
show_progressbar : bool, optional, default False
Whether to show a progressbar.
return_names : bool, optional, default True
Whether to return the item names, or just the distances.
Returns
-------
sim : array
For each items in the input the num most similar items are returned
in the form of (NAME, DISTANCE) tuples. If return_names is false,
the returned list just contains distances.
|
train
|
https://github.com/stephantul/reach/blob/e5ed0cc895d17429e797c6d7dd57bce82ff00d5d/reach/reach.py#L358-L409
|
[
"def _threshold_batch(self,\n vectors,\n batch_size,\n threshold,\n show_progressbar,\n return_names):\n \"\"\"Batched cosine distance.\"\"\"\n vectors = self.normalize(vectors)\n\n # Single transpose, makes things faster.\n reference_transposed = self.norm_vectors.T\n\n for i in tqdm(range(0, len(vectors), batch_size),\n disable=not show_progressbar):\n\n distances = vectors[i: i+batch_size].dot(reference_transposed)\n # For safety we clip\n distances = np.clip(distances, a_min=.0, a_max=1.0)\n for lidx, dists in enumerate(distances):\n indices = np.flatnonzero(dists >= threshold)\n sorted_indices = indices[np.argsort(-dists[indices])]\n if return_names:\n yield [(self.indices[d], dists[d])\n for d in sorted_indices]\n else:\n yield list(dists[sorted_indices])\n"
] |
class Reach(object):
"""
Work with vector representations of items.
Supports functions for calculating fast batched similarity
between items or composite representations of items.
Parameters
----------
vectors : numpy array
The vector space.
items : list
A list of items. Length must be equal to the number of vectors, and
aligned with the vectors.
name : string, optional
A string giving the name of the current reach. Only useful if you
have multiple spaces and want to keep track of them.
Attributes
----------
items : dict
A mapping from items to ids.
indices : dict
A mapping from ids to items.
vectors : numpy array
The array representing the vector space.
norm_vectors : numpy array
A normalized version of the vector space.
unk_index : int
The integer index of your unknown glyph. This glyph will be inserted
into your BoW space whenever an unknown item is encountered.
size : int
The dimensionality of the vector space.
name : string
The name of the Reach instance.
"""
def __init__(self, vectors, items, name="", unk_index=None):
"""Initialize a Reach instance with an array and list of items."""
if len(items) != len(vectors):
raise ValueError("Your vector space and list of items are not "
"the same length: "
"{} != {}".format(len(vectors), len(items)))
if isinstance(items, dict) or isinstance(items, set):
raise ValueError("Your item list is a set or dict, and might not "
"retain order in the conversion to internal look"
"-ups. Please convert it to list and check the "
"order.")
self.items = {w: idx for idx, w in enumerate(items)}
self.indices = {v: k for k, v in self.items.items()}
self.vectors = np.asarray(vectors)
self.norm_vectors = self.normalize(self.vectors)
self.unk_index = unk_index
self.size = self.vectors.shape[1]
self.name = name
@staticmethod
def load(pathtovector,
wordlist=(),
num_to_load=None,
truncate_embeddings=None,
unk_word=None,
sep=" "):
r"""
Read a file in word2vec .txt format.
The load function will raise a ValueError when trying to load items
which do not conform to line lengths.
Parameters
----------
pathtovector : string
The path to the vector file.
header : bool
Whether the vector file has a header of the type
(NUMBER OF ITEMS, SIZE OF VECTOR).
wordlist : iterable, optional, default ()
A list of words you want loaded from the vector file. If this is
None (default), all words will be loaded.
num_to_load : int, optional, default None
The number of items to load from the file. Because loading can take
some time, it is sometimes useful to onlyl load the first n items
from a vector file for quick inspection.
truncate_embeddings : int, optional, default None
If this value is not None, the vectors in the vector space will
be truncated to the number of dimensions indicated by this value.
unk_word : object
The object to treat as UNK in your vector space. If this is not
in your items dictionary after loading, we add it with a zero
vector.
Returns
-------
r : Reach
An initialized Reach instance.
"""
vectors, items = Reach._load(pathtovector,
wordlist,
num_to_load,
truncate_embeddings,
sep)
if unk_word is not None:
if unk_word not in set(items):
unk_vec = np.zeros((1, vectors.shape[1]))
vectors = np.concatenate([unk_vec, vectors], 0)
items = [unk_word] + items
unk_index = 0
else:
unk_index = items.index(unk_word)
else:
unk_index = None
return Reach(vectors,
items,
name=os.path.split(pathtovector)[-1],
unk_index=unk_index)
@staticmethod
def _load(pathtovector,
wordlist,
num_to_load=None,
truncate_embeddings=None,
sep=" "):
"""Load a matrix and wordlist from a .vec file."""
vectors = []
addedwords = set()
words = []
try:
wordlist = set(wordlist)
except ValueError:
wordlist = set()
logger.info("Loading {0}".format(pathtovector))
firstline = open(pathtovector).readline().strip()
try:
num, size = firstline.split(sep)
num, size = int(num), int(size)
logger.info("Vector space: {} by {}".format(num, size))
header = True
except ValueError:
size = len(firstline.split(sep)) - 1
logger.info("Vector space: {} dim, # items unknown".format(size))
word, rest = firstline.split(sep, 1)
# If the first line is correctly parseable, set header to False.
header = False
if truncate_embeddings is None or truncate_embeddings == 0:
truncate_embeddings = size
for idx, line in enumerate(open(pathtovector, encoding='utf-8')):
if header and idx == 0:
continue
word, rest = line.rstrip(" \n").split(sep, 1)
if wordlist and word not in wordlist:
continue
if word in addedwords:
raise ValueError("Duplicate: {} on line {} was in the "
"vector space twice".format(word, idx))
if len(rest.split(sep)) != size:
raise ValueError("Incorrect input at index {}, size "
"is {}, expected "
"{}".format(idx+1,
len(rest.split(sep)), size))
words.append(word)
addedwords.add(word)
vectors.append(np.fromstring(rest, sep=sep)[:truncate_embeddings])
if num_to_load is not None and len(addedwords) >= num_to_load:
break
vectors = np.array(vectors).astype(np.float32)
logger.info("Loading finished")
if wordlist:
diff = wordlist - addedwords
if diff:
logger.info("Not all items from your wordlist were in your "
"vector space: {}.".format(diff))
return vectors, words
def __getitem__(self, item):
"""Get the vector for a single item."""
return self.vectors[self.items[item]]
def vectorize(self, tokens, remove_oov=False, norm=False):
"""
Vectorize a sentence by replacing all items with their vectors.
Parameters
----------
tokens : object or list of objects
The tokens to vectorize.
remove_oov : bool, optional, default False
Whether to remove OOV items. If False, OOV items are replaced by
the UNK glyph. If this is True, the returned sequence might
have a different length than the original sequence.
norm : bool, optional, default False
Whether to return the unit vectors, or the regular vectors.
Returns
-------
s : numpy array
An M * N matrix, where every item has been replaced by
its vector. OOV items are either removed, or replaced
by the value of the UNK glyph.
"""
if not tokens:
raise ValueError("You supplied an empty list.")
index = list(self.bow(tokens, remove_oov=remove_oov))
if not index:
raise ValueError("You supplied a list with only OOV tokens: {}, "
"which then got removed. Set remove_oov to False,"
" or filter your sentences to remove any in which"
" all items are OOV.")
if norm:
return np.stack([self.norm_vectors[x] for x in index])
else:
return np.stack([self.vectors[x] for x in index])
def bow(self, tokens, remove_oov=False):
"""
Create a bow representation of a list of tokens.
Parameters
----------
tokens : list.
The list of items to change into a bag of words representation.
remove_oov : bool.
Whether to remove OOV items from the input.
If this is True, the length of the returned BOW representation
might not be the length of the original representation.
Returns
-------
bow : generator
A BOW representation of the list of items.
"""
if remove_oov:
tokens = [x for x in tokens if x in self.items]
for t in tokens:
try:
yield self.items[t]
except KeyError:
if self.unk_index is None:
raise ValueError("You supplied OOV items but didn't "
"provide the index of the replacement "
"glyph. Either set remove_oov to True, "
"or set unk_index to the index of the "
"item which replaces any OOV items.")
yield self.unk_index
def transform(self, corpus, remove_oov=False, norm=False):
"""
Transform a corpus by repeated calls to vectorize, defined above.
Parameters
----------
corpus : A list of strings, list of list of strings.
Represents a corpus as a list of sentences, where sentences
can either be strings or lists of tokens.
remove_oov : bool, optional, default False
If True, removes OOV items from the input before vectorization.
Returns
-------
c : list
A list of numpy arrays, where each array represents the transformed
sentence in the original list. The list is guaranteed to be the
same length as the input list, but the arrays in the list may be
of different lengths, depending on whether remove_oov is True.
"""
return [self.vectorize(s, remove_oov=remove_oov, norm=norm)
for s in corpus]
def most_similar(self,
items,
num=10,
batch_size=100,
show_progressbar=False,
return_names=True):
"""
Return the num most similar items to a given list of items.
Parameters
----------
items : list of objects or a single object.
The items to get the most similar items to.
num : int, optional, default 10
The number of most similar items to retrieve.
batch_size : int, optional, default 100.
The batch size to use. 100 is a good default option. Increasing
the batch size may increase the speed.
show_progressbar : bool, optional, default False
Whether to show a progressbar.
return_names : bool, optional, default True
Whether to return the item names, or just the distances.
Returns
-------
sim : array
For each items in the input the num most similar items are returned
in the form of (NAME, DISTANCE) tuples. If return_names is false,
the returned list just contains distances.
"""
# This line allows users to input single items.
# We used to rely on string identities, but we now also allow
# anything hashable as keys.
# Might fail if a list of passed items is also in the vocabulary.
# but I can't think of cases when this would happen, and what
# user expectations are.
try:
if items in self.items:
items = [items]
except TypeError:
pass
x = np.stack([self.norm_vectors[self.items[x]] for x in items])
result = self._batch(x,
batch_size,
num+1,
show_progressbar,
return_names)
# list call consumes the generator.
return [x[1:] for x in result]
def nearest_neighbor(self,
vectors,
num=10,
batch_size=100,
show_progressbar=False,
return_names=True):
"""
Find the nearest neighbors to some arbitrary vector.
This function is meant to be used in composition operations. The
most_similar function can only handle items that are in vocab, and
looks up their vector through a dictionary. Compositions, e.g.
"King - man + woman" are necessarily not in the vocabulary.
Parameters
----------
vectors : list of arrays or numpy array
The vectors to find the nearest neighbors to.
num : int, optional, default 10
The number of most similar items to retrieve.
batch_size : int, optional, default 100.
The batch size to use. 100 is a good default option. Increasing
the batch size may increase speed.
show_progressbar : bool, optional, default False
Whether to show a progressbar.
return_names : bool, optional, default True
Whether to return the item names, or just the distances.
Returns
-------
sim : list of tuples.
For each item in the input the num most similar items are returned
in the form of (NAME, DISTANCE) tuples. If return_names is set to
false, only the distances are returned.
"""
vectors = np.array(vectors)
if np.ndim(vectors) == 1:
vectors = vectors[None, :]
result = []
result = self._batch(vectors,
batch_size,
num+1,
show_progressbar,
return_names)
return list(result)
def nearest_neighbor_threshold(self,
vectors,
threshold=.5,
batch_size=100,
show_progressbar=False,
return_names=True):
"""
Find the nearest neighbors to some arbitrary vector.
This function is meant to be used in composition operations. The
most_similar function can only handle items that are in vocab, and
looks up their vector through a dictionary. Compositions, e.g.
"King - man + woman" are necessarily not in the vocabulary.
Parameters
----------
vectors : list of arrays or numpy array
The vectors to find the nearest neighbors to.
threshold : float, optional, default .5
The threshold within to retrieve items.
batch_size : int, optional, default 100.
The batch size to use. 100 is a good default option. Increasing
the batch size may increase speed.
show_progressbar : bool, optional, default False
Whether to show a progressbar.
return_names : bool, optional, default True
Whether to return the item names, or just the distances.
Returns
-------
sim : list of tuples.
For each item in the input the num most similar items are returned
in the form of (NAME, DISTANCE) tuples. If return_names is set to
false, only the distances are returned.
"""
vectors = np.array(vectors)
if np.ndim(vectors) == 1:
vectors = vectors[None, :]
result = []
result = self._threshold_batch(vectors,
batch_size,
threshold,
show_progressbar,
return_names)
return list(result)
def _threshold_batch(self,
vectors,
batch_size,
threshold,
show_progressbar,
return_names):
"""Batched cosine distance."""
vectors = self.normalize(vectors)
# Single transpose, makes things faster.
reference_transposed = self.norm_vectors.T
for i in tqdm(range(0, len(vectors), batch_size),
disable=not show_progressbar):
distances = vectors[i: i+batch_size].dot(reference_transposed)
# For safety we clip
distances = np.clip(distances, a_min=.0, a_max=1.0)
for lidx, dists in enumerate(distances):
indices = np.flatnonzero(dists >= threshold)
sorted_indices = indices[np.argsort(-dists[indices])]
if return_names:
yield [(self.indices[d], dists[d])
for d in sorted_indices]
else:
yield list(dists[sorted_indices])
def _batch(self,
vectors,
batch_size,
num,
show_progressbar,
return_names):
"""Batched cosine distance."""
vectors = self.normalize(vectors)
# Single transpose, makes things faster.
reference_transposed = self.norm_vectors.T
for i in tqdm(range(0, len(vectors), batch_size),
disable=not show_progressbar):
distances = vectors[i: i+batch_size].dot(reference_transposed)
# For safety we clip
distances = np.clip(distances, a_min=.0, a_max=1.0)
if num == 1:
sorted_indices = np.argmax(distances, 1)[:, None]
else:
sorted_indices = np.argpartition(-distances, kth=num, axis=1)
sorted_indices = sorted_indices[:, :num]
for lidx, indices in enumerate(sorted_indices):
dists = distances[lidx, indices]
if return_names:
dindex = np.argsort(-dists)
yield [(self.indices[indices[d]], dists[d])
for d in dindex]
else:
yield list(-1 * np.sort(-dists))
@staticmethod
def normalize(vectors):
"""
Normalize a matrix of row vectors to unit length.
Contains a shortcut if there are no zero vectors in the matrix.
If there are zero vectors, we do some indexing tricks to avoid
dividing by 0.
Parameters
----------
vectors : np.array
The vectors to normalize.
Returns
-------
vectors : np.array
The input vectors, normalized to unit length.
"""
if np.ndim(vectors) == 1:
norm = np.linalg.norm(vectors)
if norm == 0:
return np.zeros_like(vectors)
return vectors / norm
norm = np.linalg.norm(vectors, axis=1)
if np.any(norm == 0):
nonzero = norm > 0
result = np.zeros_like(vectors)
n = norm[nonzero]
p = vectors[nonzero]
result[nonzero] = p / n[:, None]
return result
else:
return vectors / norm[:, None]
def vector_similarity(self, vector, items):
"""Compute the similarity between a vector and a set of items."""
vector = self.normalize(vector)
items_vec = np.stack([self.norm_vectors[self.items[x]] for x in items])
return vector.dot(items_vec.T)
def similarity(self, i1, i2):
"""
Compute the similarity between two sets of items.
Parameters
----------
i1 : object
The first set of items.
i2 : object
The second set of item.
Returns
-------
sim : array of floats
An array of similarity scores between 1 and 0.
"""
try:
if i1 in self.items:
i1 = [i1]
except TypeError:
pass
try:
if i2 in self.items:
i2 = [i2]
except TypeError:
pass
i1_vec = np.stack([self.norm_vectors[self.items[x]] for x in i1])
i2_vec = np.stack([self.norm_vectors[self.items[x]] for x in i2])
return i1_vec.dot(i2_vec.T)
def prune(self, wordlist):
"""
Prune the current reach instance by removing items.
Parameters
----------
wordlist : list of str
A list of words to keep. Note that this wordlist need not include
all words in the Reach instance. Any words which are in the
wordlist, but not in the reach instance are ignored.
"""
# Remove duplicates
wordlist = set(wordlist).intersection(set(self.items.keys()))
indices = [self.items[w] for w in wordlist if w in self.items]
if self.unk_index is not None and self.unk_index not in indices:
raise ValueError("Your unknown item is not in your list of items. "
"Set it to None before pruning, or pass your "
"unknown item.")
self.vectors = self.vectors[indices]
self.norm_vectors = self.norm_vectors[indices]
self.items = {w: idx for idx, w in enumerate(wordlist)}
self.indices = {v: k for k, v in self.items.items()}
if self.unk_index is not None:
self.unk_index = self.items[wordlist[self.unk_index]]
def save(self, path, write_header=True):
"""
Save the current vector space in word2vec format.
Parameters
----------
path : str
The path to save the vector file to.
write_header : bool, optional, default True
Whether to write a word2vec-style header as the first line of the
file
"""
with open(path, 'w') as f:
if write_header:
f.write(u"{0} {1}\n".format(str(self.vectors.shape[0]),
str(self.vectors.shape[1])))
for i in range(len(self.items)):
w = self.indices[i]
vec = self.vectors[i]
f.write(u"{0} {1}\n".format(w,
" ".join([str(x) for x in vec])))
def save_fast_format(self, filename):
"""
Save a reach instance in a fast format.
The reach fast format stores the words and vectors of a Reach instance
separately in a JSON and numpy format, respectively.
Parameters
----------
filename : str
The prefix to add to the saved filename. Note that this is not the
real filename under which these items are stored.
The words and unk_index are stored under "{filename}_words.json",
and the numpy matrix is saved under "{filename}_vectors.npy".
"""
items, _ = zip(*sorted(self.items.items(), key=lambda x: x[1]))
items = {"items": items,
"unk_index": self.unk_index,
"name": self.name}
json.dump(items, open("{}_items.json".format(filename), 'w'))
np.save(open("{}_vectors.npy".format(filename), 'wb'), self.vectors)
@staticmethod
def load_fast_format(filename):
"""
Load a reach instance in fast format.
As described above, the fast format stores the words and vectors of the
Reach instance separately, and is drastically faster than loading from
.txt files.
Parameters
----------
filename : str
The filename prefix from which to load. Note that this is not a
real filepath as such, but a shared prefix for both files.
In order for this to work, both {filename}_words.json and
{filename}_vectors.npy should be present.
"""
words, unk_index, name, vectors = Reach._load_fast(filename)
return Reach(vectors, words, unk_index=unk_index, name=name)
@staticmethod
def _load_fast(filename):
"""Sub for fast loader."""
it = json.load(open("{}_items.json".format(filename)))
words, unk_index, name = it["items"], it["unk_index"], it["name"]
vectors = np.load(open("{}_vectors.npy".format(filename), 'rb'))
return words, unk_index, name, vectors
|
stephantul/reach
|
reach/reach.py
|
Reach.nearest_neighbor
|
python
|
def nearest_neighbor(self,
vectors,
num=10,
batch_size=100,
show_progressbar=False,
return_names=True):
vectors = np.array(vectors)
if np.ndim(vectors) == 1:
vectors = vectors[None, :]
result = []
result = self._batch(vectors,
batch_size,
num+1,
show_progressbar,
return_names)
return list(result)
|
Find the nearest neighbors to some arbitrary vector.
This function is meant to be used in composition operations. The
most_similar function can only handle items that are in vocab, and
looks up their vector through a dictionary. Compositions, e.g.
"King - man + woman" are necessarily not in the vocabulary.
Parameters
----------
vectors : list of arrays or numpy array
The vectors to find the nearest neighbors to.
num : int, optional, default 10
The number of most similar items to retrieve.
batch_size : int, optional, default 100.
The batch size to use. 100 is a good default option. Increasing
the batch size may increase speed.
show_progressbar : bool, optional, default False
Whether to show a progressbar.
return_names : bool, optional, default True
Whether to return the item names, or just the distances.
Returns
-------
sim : list of tuples.
For each item in the input the num most similar items are returned
in the form of (NAME, DISTANCE) tuples. If return_names is set to
false, only the distances are returned.
|
train
|
https://github.com/stephantul/reach/blob/e5ed0cc895d17429e797c6d7dd57bce82ff00d5d/reach/reach.py#L411-L459
|
[
"def _batch(self,\n vectors,\n batch_size,\n num,\n show_progressbar,\n return_names):\n \"\"\"Batched cosine distance.\"\"\"\n vectors = self.normalize(vectors)\n\n # Single transpose, makes things faster.\n reference_transposed = self.norm_vectors.T\n\n for i in tqdm(range(0, len(vectors), batch_size),\n disable=not show_progressbar):\n\n distances = vectors[i: i+batch_size].dot(reference_transposed)\n # For safety we clip\n distances = np.clip(distances, a_min=.0, a_max=1.0)\n if num == 1:\n sorted_indices = np.argmax(distances, 1)[:, None]\n else:\n sorted_indices = np.argpartition(-distances, kth=num, axis=1)\n sorted_indices = sorted_indices[:, :num]\n for lidx, indices in enumerate(sorted_indices):\n dists = distances[lidx, indices]\n if return_names:\n dindex = np.argsort(-dists)\n yield [(self.indices[indices[d]], dists[d])\n for d in dindex]\n else:\n yield list(-1 * np.sort(-dists))\n"
] |
class Reach(object):
"""
Work with vector representations of items.
Supports functions for calculating fast batched similarity
between items or composite representations of items.
Parameters
----------
vectors : numpy array
The vector space.
items : list
A list of items. Length must be equal to the number of vectors, and
aligned with the vectors.
name : string, optional
A string giving the name of the current reach. Only useful if you
have multiple spaces and want to keep track of them.
Attributes
----------
items : dict
A mapping from items to ids.
indices : dict
A mapping from ids to items.
vectors : numpy array
The array representing the vector space.
norm_vectors : numpy array
A normalized version of the vector space.
unk_index : int
The integer index of your unknown glyph. This glyph will be inserted
into your BoW space whenever an unknown item is encountered.
size : int
The dimensionality of the vector space.
name : string
The name of the Reach instance.
"""
def __init__(self, vectors, items, name="", unk_index=None):
"""Initialize a Reach instance with an array and list of items."""
if len(items) != len(vectors):
raise ValueError("Your vector space and list of items are not "
"the same length: "
"{} != {}".format(len(vectors), len(items)))
if isinstance(items, dict) or isinstance(items, set):
raise ValueError("Your item list is a set or dict, and might not "
"retain order in the conversion to internal look"
"-ups. Please convert it to list and check the "
"order.")
self.items = {w: idx for idx, w in enumerate(items)}
self.indices = {v: k for k, v in self.items.items()}
self.vectors = np.asarray(vectors)
self.norm_vectors = self.normalize(self.vectors)
self.unk_index = unk_index
self.size = self.vectors.shape[1]
self.name = name
@staticmethod
def load(pathtovector,
wordlist=(),
num_to_load=None,
truncate_embeddings=None,
unk_word=None,
sep=" "):
r"""
Read a file in word2vec .txt format.
The load function will raise a ValueError when trying to load items
which do not conform to line lengths.
Parameters
----------
pathtovector : string
The path to the vector file.
header : bool
Whether the vector file has a header of the type
(NUMBER OF ITEMS, SIZE OF VECTOR).
wordlist : iterable, optional, default ()
A list of words you want loaded from the vector file. If this is
None (default), all words will be loaded.
num_to_load : int, optional, default None
The number of items to load from the file. Because loading can take
some time, it is sometimes useful to onlyl load the first n items
from a vector file for quick inspection.
truncate_embeddings : int, optional, default None
If this value is not None, the vectors in the vector space will
be truncated to the number of dimensions indicated by this value.
unk_word : object
The object to treat as UNK in your vector space. If this is not
in your items dictionary after loading, we add it with a zero
vector.
Returns
-------
r : Reach
An initialized Reach instance.
"""
vectors, items = Reach._load(pathtovector,
wordlist,
num_to_load,
truncate_embeddings,
sep)
if unk_word is not None:
if unk_word not in set(items):
unk_vec = np.zeros((1, vectors.shape[1]))
vectors = np.concatenate([unk_vec, vectors], 0)
items = [unk_word] + items
unk_index = 0
else:
unk_index = items.index(unk_word)
else:
unk_index = None
return Reach(vectors,
items,
name=os.path.split(pathtovector)[-1],
unk_index=unk_index)
@staticmethod
def _load(pathtovector,
wordlist,
num_to_load=None,
truncate_embeddings=None,
sep=" "):
"""Load a matrix and wordlist from a .vec file."""
vectors = []
addedwords = set()
words = []
try:
wordlist = set(wordlist)
except ValueError:
wordlist = set()
logger.info("Loading {0}".format(pathtovector))
firstline = open(pathtovector).readline().strip()
try:
num, size = firstline.split(sep)
num, size = int(num), int(size)
logger.info("Vector space: {} by {}".format(num, size))
header = True
except ValueError:
size = len(firstline.split(sep)) - 1
logger.info("Vector space: {} dim, # items unknown".format(size))
word, rest = firstline.split(sep, 1)
# If the first line is correctly parseable, set header to False.
header = False
if truncate_embeddings is None or truncate_embeddings == 0:
truncate_embeddings = size
for idx, line in enumerate(open(pathtovector, encoding='utf-8')):
if header and idx == 0:
continue
word, rest = line.rstrip(" \n").split(sep, 1)
if wordlist and word not in wordlist:
continue
if word in addedwords:
raise ValueError("Duplicate: {} on line {} was in the "
"vector space twice".format(word, idx))
if len(rest.split(sep)) != size:
raise ValueError("Incorrect input at index {}, size "
"is {}, expected "
"{}".format(idx+1,
len(rest.split(sep)), size))
words.append(word)
addedwords.add(word)
vectors.append(np.fromstring(rest, sep=sep)[:truncate_embeddings])
if num_to_load is not None and len(addedwords) >= num_to_load:
break
vectors = np.array(vectors).astype(np.float32)
logger.info("Loading finished")
if wordlist:
diff = wordlist - addedwords
if diff:
logger.info("Not all items from your wordlist were in your "
"vector space: {}.".format(diff))
return vectors, words
def __getitem__(self, item):
"""Get the vector for a single item."""
return self.vectors[self.items[item]]
def vectorize(self, tokens, remove_oov=False, norm=False):
"""
Vectorize a sentence by replacing all items with their vectors.
Parameters
----------
tokens : object or list of objects
The tokens to vectorize.
remove_oov : bool, optional, default False
Whether to remove OOV items. If False, OOV items are replaced by
the UNK glyph. If this is True, the returned sequence might
have a different length than the original sequence.
norm : bool, optional, default False
Whether to return the unit vectors, or the regular vectors.
Returns
-------
s : numpy array
An M * N matrix, where every item has been replaced by
its vector. OOV items are either removed, or replaced
by the value of the UNK glyph.
"""
if not tokens:
raise ValueError("You supplied an empty list.")
index = list(self.bow(tokens, remove_oov=remove_oov))
if not index:
raise ValueError("You supplied a list with only OOV tokens: {}, "
"which then got removed. Set remove_oov to False,"
" or filter your sentences to remove any in which"
" all items are OOV.")
if norm:
return np.stack([self.norm_vectors[x] for x in index])
else:
return np.stack([self.vectors[x] for x in index])
def bow(self, tokens, remove_oov=False):
"""
Create a bow representation of a list of tokens.
Parameters
----------
tokens : list.
The list of items to change into a bag of words representation.
remove_oov : bool.
Whether to remove OOV items from the input.
If this is True, the length of the returned BOW representation
might not be the length of the original representation.
Returns
-------
bow : generator
A BOW representation of the list of items.
"""
if remove_oov:
tokens = [x for x in tokens if x in self.items]
for t in tokens:
try:
yield self.items[t]
except KeyError:
if self.unk_index is None:
raise ValueError("You supplied OOV items but didn't "
"provide the index of the replacement "
"glyph. Either set remove_oov to True, "
"or set unk_index to the index of the "
"item which replaces any OOV items.")
yield self.unk_index
def transform(self, corpus, remove_oov=False, norm=False):
"""
Transform a corpus by repeated calls to vectorize, defined above.
Parameters
----------
corpus : A list of strings, list of list of strings.
Represents a corpus as a list of sentences, where sentences
can either be strings or lists of tokens.
remove_oov : bool, optional, default False
If True, removes OOV items from the input before vectorization.
Returns
-------
c : list
A list of numpy arrays, where each array represents the transformed
sentence in the original list. The list is guaranteed to be the
same length as the input list, but the arrays in the list may be
of different lengths, depending on whether remove_oov is True.
"""
return [self.vectorize(s, remove_oov=remove_oov, norm=norm)
for s in corpus]
def most_similar(self,
items,
num=10,
batch_size=100,
show_progressbar=False,
return_names=True):
"""
Return the num most similar items to a given list of items.
Parameters
----------
items : list of objects or a single object.
The items to get the most similar items to.
num : int, optional, default 10
The number of most similar items to retrieve.
batch_size : int, optional, default 100.
The batch size to use. 100 is a good default option. Increasing
the batch size may increase the speed.
show_progressbar : bool, optional, default False
Whether to show a progressbar.
return_names : bool, optional, default True
Whether to return the item names, or just the distances.
Returns
-------
sim : array
For each items in the input the num most similar items are returned
in the form of (NAME, DISTANCE) tuples. If return_names is false,
the returned list just contains distances.
"""
# This line allows users to input single items.
# We used to rely on string identities, but we now also allow
# anything hashable as keys.
# Might fail if a list of passed items is also in the vocabulary.
# but I can't think of cases when this would happen, and what
# user expectations are.
try:
if items in self.items:
items = [items]
except TypeError:
pass
x = np.stack([self.norm_vectors[self.items[x]] for x in items])
result = self._batch(x,
batch_size,
num+1,
show_progressbar,
return_names)
# list call consumes the generator.
return [x[1:] for x in result]
def threshold(self,
items,
threshold=.5,
batch_size=100,
show_progressbar=False,
return_names=True):
"""
Return all items whose similarity is higher than threshold.
Parameters
----------
items : list of objects or a single object.
The items to get the most similar items to.
threshold : float, optional, default .5
The radius within which to retrieve items.
batch_size : int, optional, default 100.
The batch size to use. 100 is a good default option. Increasing
the batch size may increase the speed.
show_progressbar : bool, optional, default False
Whether to show a progressbar.
return_names : bool, optional, default True
Whether to return the item names, or just the distances.
Returns
-------
sim : array
For each items in the input the num most similar items are returned
in the form of (NAME, DISTANCE) tuples. If return_names is false,
the returned list just contains distances.
"""
# This line allows users to input single items.
# We used to rely on string identities, but we now also allow
# anything hashable as keys.
# Might fail if a list of passed items is also in the vocabulary.
# but I can't think of cases when this would happen, and what
# user expectations are.
try:
if items in self.items:
items = [items]
except TypeError:
pass
x = np.stack([self.norm_vectors[self.items[x]] for x in items])
result = self._threshold_batch(x,
batch_size,
threshold,
show_progressbar,
return_names)
# list call consumes the generator.
return [x[1:] for x in result]
def nearest_neighbor_threshold(self,
vectors,
threshold=.5,
batch_size=100,
show_progressbar=False,
return_names=True):
"""
Find the nearest neighbors to some arbitrary vector.
This function is meant to be used in composition operations. The
most_similar function can only handle items that are in vocab, and
looks up their vector through a dictionary. Compositions, e.g.
"King - man + woman" are necessarily not in the vocabulary.
Parameters
----------
vectors : list of arrays or numpy array
The vectors to find the nearest neighbors to.
threshold : float, optional, default .5
The threshold within to retrieve items.
batch_size : int, optional, default 100.
The batch size to use. 100 is a good default option. Increasing
the batch size may increase speed.
show_progressbar : bool, optional, default False
Whether to show a progressbar.
return_names : bool, optional, default True
Whether to return the item names, or just the distances.
Returns
-------
sim : list of tuples.
For each item in the input the num most similar items are returned
in the form of (NAME, DISTANCE) tuples. If return_names is set to
false, only the distances are returned.
"""
vectors = np.array(vectors)
if np.ndim(vectors) == 1:
vectors = vectors[None, :]
result = []
result = self._threshold_batch(vectors,
batch_size,
threshold,
show_progressbar,
return_names)
return list(result)
def _threshold_batch(self,
vectors,
batch_size,
threshold,
show_progressbar,
return_names):
"""Batched cosine distance."""
vectors = self.normalize(vectors)
# Single transpose, makes things faster.
reference_transposed = self.norm_vectors.T
for i in tqdm(range(0, len(vectors), batch_size),
disable=not show_progressbar):
distances = vectors[i: i+batch_size].dot(reference_transposed)
# For safety we clip
distances = np.clip(distances, a_min=.0, a_max=1.0)
for lidx, dists in enumerate(distances):
indices = np.flatnonzero(dists >= threshold)
sorted_indices = indices[np.argsort(-dists[indices])]
if return_names:
yield [(self.indices[d], dists[d])
for d in sorted_indices]
else:
yield list(dists[sorted_indices])
def _batch(self,
vectors,
batch_size,
num,
show_progressbar,
return_names):
"""Batched cosine distance."""
vectors = self.normalize(vectors)
# Single transpose, makes things faster.
reference_transposed = self.norm_vectors.T
for i in tqdm(range(0, len(vectors), batch_size),
disable=not show_progressbar):
distances = vectors[i: i+batch_size].dot(reference_transposed)
# For safety we clip
distances = np.clip(distances, a_min=.0, a_max=1.0)
if num == 1:
sorted_indices = np.argmax(distances, 1)[:, None]
else:
sorted_indices = np.argpartition(-distances, kth=num, axis=1)
sorted_indices = sorted_indices[:, :num]
for lidx, indices in enumerate(sorted_indices):
dists = distances[lidx, indices]
if return_names:
dindex = np.argsort(-dists)
yield [(self.indices[indices[d]], dists[d])
for d in dindex]
else:
yield list(-1 * np.sort(-dists))
@staticmethod
def normalize(vectors):
"""
Normalize a matrix of row vectors to unit length.
Contains a shortcut if there are no zero vectors in the matrix.
If there are zero vectors, we do some indexing tricks to avoid
dividing by 0.
Parameters
----------
vectors : np.array
The vectors to normalize.
Returns
-------
vectors : np.array
The input vectors, normalized to unit length.
"""
if np.ndim(vectors) == 1:
norm = np.linalg.norm(vectors)
if norm == 0:
return np.zeros_like(vectors)
return vectors / norm
norm = np.linalg.norm(vectors, axis=1)
if np.any(norm == 0):
nonzero = norm > 0
result = np.zeros_like(vectors)
n = norm[nonzero]
p = vectors[nonzero]
result[nonzero] = p / n[:, None]
return result
else:
return vectors / norm[:, None]
def vector_similarity(self, vector, items):
"""Compute the similarity between a vector and a set of items."""
vector = self.normalize(vector)
items_vec = np.stack([self.norm_vectors[self.items[x]] for x in items])
return vector.dot(items_vec.T)
def similarity(self, i1, i2):
"""
Compute the similarity between two sets of items.
Parameters
----------
i1 : object
The first set of items.
i2 : object
The second set of item.
Returns
-------
sim : array of floats
An array of similarity scores between 1 and 0.
"""
try:
if i1 in self.items:
i1 = [i1]
except TypeError:
pass
try:
if i2 in self.items:
i2 = [i2]
except TypeError:
pass
i1_vec = np.stack([self.norm_vectors[self.items[x]] for x in i1])
i2_vec = np.stack([self.norm_vectors[self.items[x]] for x in i2])
return i1_vec.dot(i2_vec.T)
def prune(self, wordlist):
"""
Prune the current reach instance by removing items.
Parameters
----------
wordlist : list of str
A list of words to keep. Note that this wordlist need not include
all words in the Reach instance. Any words which are in the
wordlist, but not in the reach instance are ignored.
"""
# Remove duplicates
wordlist = set(wordlist).intersection(set(self.items.keys()))
indices = [self.items[w] for w in wordlist if w in self.items]
if self.unk_index is not None and self.unk_index not in indices:
raise ValueError("Your unknown item is not in your list of items. "
"Set it to None before pruning, or pass your "
"unknown item.")
self.vectors = self.vectors[indices]
self.norm_vectors = self.norm_vectors[indices]
self.items = {w: idx for idx, w in enumerate(wordlist)}
self.indices = {v: k for k, v in self.items.items()}
if self.unk_index is not None:
self.unk_index = self.items[wordlist[self.unk_index]]
def save(self, path, write_header=True):
"""
Save the current vector space in word2vec format.
Parameters
----------
path : str
The path to save the vector file to.
write_header : bool, optional, default True
Whether to write a word2vec-style header as the first line of the
file
"""
with open(path, 'w') as f:
if write_header:
f.write(u"{0} {1}\n".format(str(self.vectors.shape[0]),
str(self.vectors.shape[1])))
for i in range(len(self.items)):
w = self.indices[i]
vec = self.vectors[i]
f.write(u"{0} {1}\n".format(w,
" ".join([str(x) for x in vec])))
def save_fast_format(self, filename):
"""
Save a reach instance in a fast format.
The reach fast format stores the words and vectors of a Reach instance
separately in a JSON and numpy format, respectively.
Parameters
----------
filename : str
The prefix to add to the saved filename. Note that this is not the
real filename under which these items are stored.
The words and unk_index are stored under "{filename}_words.json",
and the numpy matrix is saved under "{filename}_vectors.npy".
"""
items, _ = zip(*sorted(self.items.items(), key=lambda x: x[1]))
items = {"items": items,
"unk_index": self.unk_index,
"name": self.name}
json.dump(items, open("{}_items.json".format(filename), 'w'))
np.save(open("{}_vectors.npy".format(filename), 'wb'), self.vectors)
@staticmethod
def load_fast_format(filename):
"""
Load a reach instance in fast format.
As described above, the fast format stores the words and vectors of the
Reach instance separately, and is drastically faster than loading from
.txt files.
Parameters
----------
filename : str
The filename prefix from which to load. Note that this is not a
real filepath as such, but a shared prefix for both files.
In order for this to work, both {filename}_words.json and
{filename}_vectors.npy should be present.
"""
words, unk_index, name, vectors = Reach._load_fast(filename)
return Reach(vectors, words, unk_index=unk_index, name=name)
@staticmethod
def _load_fast(filename):
"""Sub for fast loader."""
it = json.load(open("{}_items.json".format(filename)))
words, unk_index, name = it["items"], it["unk_index"], it["name"]
vectors = np.load(open("{}_vectors.npy".format(filename), 'rb'))
return words, unk_index, name, vectors
|
stephantul/reach
|
reach/reach.py
|
Reach.nearest_neighbor_threshold
|
python
|
def nearest_neighbor_threshold(self,
vectors,
threshold=.5,
batch_size=100,
show_progressbar=False,
return_names=True):
vectors = np.array(vectors)
if np.ndim(vectors) == 1:
vectors = vectors[None, :]
result = []
result = self._threshold_batch(vectors,
batch_size,
threshold,
show_progressbar,
return_names)
return list(result)
|
Find the nearest neighbors to some arbitrary vector.
This function is meant to be used in composition operations. The
most_similar function can only handle items that are in vocab, and
looks up their vector through a dictionary. Compositions, e.g.
"King - man + woman" are necessarily not in the vocabulary.
Parameters
----------
vectors : list of arrays or numpy array
The vectors to find the nearest neighbors to.
threshold : float, optional, default .5
The threshold within to retrieve items.
batch_size : int, optional, default 100.
The batch size to use. 100 is a good default option. Increasing
the batch size may increase speed.
show_progressbar : bool, optional, default False
Whether to show a progressbar.
return_names : bool, optional, default True
Whether to return the item names, or just the distances.
Returns
-------
sim : list of tuples.
For each item in the input the num most similar items are returned
in the form of (NAME, DISTANCE) tuples. If return_names is set to
false, only the distances are returned.
|
train
|
https://github.com/stephantul/reach/blob/e5ed0cc895d17429e797c6d7dd57bce82ff00d5d/reach/reach.py#L461-L509
|
[
"def _threshold_batch(self,\n vectors,\n batch_size,\n threshold,\n show_progressbar,\n return_names):\n \"\"\"Batched cosine distance.\"\"\"\n vectors = self.normalize(vectors)\n\n # Single transpose, makes things faster.\n reference_transposed = self.norm_vectors.T\n\n for i in tqdm(range(0, len(vectors), batch_size),\n disable=not show_progressbar):\n\n distances = vectors[i: i+batch_size].dot(reference_transposed)\n # For safety we clip\n distances = np.clip(distances, a_min=.0, a_max=1.0)\n for lidx, dists in enumerate(distances):\n indices = np.flatnonzero(dists >= threshold)\n sorted_indices = indices[np.argsort(-dists[indices])]\n if return_names:\n yield [(self.indices[d], dists[d])\n for d in sorted_indices]\n else:\n yield list(dists[sorted_indices])\n"
] |
class Reach(object):
"""
Work with vector representations of items.
Supports functions for calculating fast batched similarity
between items or composite representations of items.
Parameters
----------
vectors : numpy array
The vector space.
items : list
A list of items. Length must be equal to the number of vectors, and
aligned with the vectors.
name : string, optional
A string giving the name of the current reach. Only useful if you
have multiple spaces and want to keep track of them.
Attributes
----------
items : dict
A mapping from items to ids.
indices : dict
A mapping from ids to items.
vectors : numpy array
The array representing the vector space.
norm_vectors : numpy array
A normalized version of the vector space.
unk_index : int
The integer index of your unknown glyph. This glyph will be inserted
into your BoW space whenever an unknown item is encountered.
size : int
The dimensionality of the vector space.
name : string
The name of the Reach instance.
"""
def __init__(self, vectors, items, name="", unk_index=None):
"""Initialize a Reach instance with an array and list of items."""
if len(items) != len(vectors):
raise ValueError("Your vector space and list of items are not "
"the same length: "
"{} != {}".format(len(vectors), len(items)))
if isinstance(items, dict) or isinstance(items, set):
raise ValueError("Your item list is a set or dict, and might not "
"retain order in the conversion to internal look"
"-ups. Please convert it to list and check the "
"order.")
self.items = {w: idx for idx, w in enumerate(items)}
self.indices = {v: k for k, v in self.items.items()}
self.vectors = np.asarray(vectors)
self.norm_vectors = self.normalize(self.vectors)
self.unk_index = unk_index
self.size = self.vectors.shape[1]
self.name = name
@staticmethod
def load(pathtovector,
wordlist=(),
num_to_load=None,
truncate_embeddings=None,
unk_word=None,
sep=" "):
r"""
Read a file in word2vec .txt format.
The load function will raise a ValueError when trying to load items
which do not conform to line lengths.
Parameters
----------
pathtovector : string
The path to the vector file.
header : bool
Whether the vector file has a header of the type
(NUMBER OF ITEMS, SIZE OF VECTOR).
wordlist : iterable, optional, default ()
A list of words you want loaded from the vector file. If this is
None (default), all words will be loaded.
num_to_load : int, optional, default None
The number of items to load from the file. Because loading can take
some time, it is sometimes useful to onlyl load the first n items
from a vector file for quick inspection.
truncate_embeddings : int, optional, default None
If this value is not None, the vectors in the vector space will
be truncated to the number of dimensions indicated by this value.
unk_word : object
The object to treat as UNK in your vector space. If this is not
in your items dictionary after loading, we add it with a zero
vector.
Returns
-------
r : Reach
An initialized Reach instance.
"""
vectors, items = Reach._load(pathtovector,
wordlist,
num_to_load,
truncate_embeddings,
sep)
if unk_word is not None:
if unk_word not in set(items):
unk_vec = np.zeros((1, vectors.shape[1]))
vectors = np.concatenate([unk_vec, vectors], 0)
items = [unk_word] + items
unk_index = 0
else:
unk_index = items.index(unk_word)
else:
unk_index = None
return Reach(vectors,
items,
name=os.path.split(pathtovector)[-1],
unk_index=unk_index)
@staticmethod
def _load(pathtovector,
wordlist,
num_to_load=None,
truncate_embeddings=None,
sep=" "):
"""Load a matrix and wordlist from a .vec file."""
vectors = []
addedwords = set()
words = []
try:
wordlist = set(wordlist)
except ValueError:
wordlist = set()
logger.info("Loading {0}".format(pathtovector))
firstline = open(pathtovector).readline().strip()
try:
num, size = firstline.split(sep)
num, size = int(num), int(size)
logger.info("Vector space: {} by {}".format(num, size))
header = True
except ValueError:
size = len(firstline.split(sep)) - 1
logger.info("Vector space: {} dim, # items unknown".format(size))
word, rest = firstline.split(sep, 1)
# If the first line is correctly parseable, set header to False.
header = False
if truncate_embeddings is None or truncate_embeddings == 0:
truncate_embeddings = size
for idx, line in enumerate(open(pathtovector, encoding='utf-8')):
if header and idx == 0:
continue
word, rest = line.rstrip(" \n").split(sep, 1)
if wordlist and word not in wordlist:
continue
if word in addedwords:
raise ValueError("Duplicate: {} on line {} was in the "
"vector space twice".format(word, idx))
if len(rest.split(sep)) != size:
raise ValueError("Incorrect input at index {}, size "
"is {}, expected "
"{}".format(idx+1,
len(rest.split(sep)), size))
words.append(word)
addedwords.add(word)
vectors.append(np.fromstring(rest, sep=sep)[:truncate_embeddings])
if num_to_load is not None and len(addedwords) >= num_to_load:
break
vectors = np.array(vectors).astype(np.float32)
logger.info("Loading finished")
if wordlist:
diff = wordlist - addedwords
if diff:
logger.info("Not all items from your wordlist were in your "
"vector space: {}.".format(diff))
return vectors, words
def __getitem__(self, item):
"""Get the vector for a single item."""
return self.vectors[self.items[item]]
def vectorize(self, tokens, remove_oov=False, norm=False):
"""
Vectorize a sentence by replacing all items with their vectors.
Parameters
----------
tokens : object or list of objects
The tokens to vectorize.
remove_oov : bool, optional, default False
Whether to remove OOV items. If False, OOV items are replaced by
the UNK glyph. If this is True, the returned sequence might
have a different length than the original sequence.
norm : bool, optional, default False
Whether to return the unit vectors, or the regular vectors.
Returns
-------
s : numpy array
An M * N matrix, where every item has been replaced by
its vector. OOV items are either removed, or replaced
by the value of the UNK glyph.
"""
if not tokens:
raise ValueError("You supplied an empty list.")
index = list(self.bow(tokens, remove_oov=remove_oov))
if not index:
raise ValueError("You supplied a list with only OOV tokens: {}, "
"which then got removed. Set remove_oov to False,"
" or filter your sentences to remove any in which"
" all items are OOV.")
if norm:
return np.stack([self.norm_vectors[x] for x in index])
else:
return np.stack([self.vectors[x] for x in index])
def bow(self, tokens, remove_oov=False):
"""
Create a bow representation of a list of tokens.
Parameters
----------
tokens : list.
The list of items to change into a bag of words representation.
remove_oov : bool.
Whether to remove OOV items from the input.
If this is True, the length of the returned BOW representation
might not be the length of the original representation.
Returns
-------
bow : generator
A BOW representation of the list of items.
"""
if remove_oov:
tokens = [x for x in tokens if x in self.items]
for t in tokens:
try:
yield self.items[t]
except KeyError:
if self.unk_index is None:
raise ValueError("You supplied OOV items but didn't "
"provide the index of the replacement "
"glyph. Either set remove_oov to True, "
"or set unk_index to the index of the "
"item which replaces any OOV items.")
yield self.unk_index
def transform(self, corpus, remove_oov=False, norm=False):
"""
Transform a corpus by repeated calls to vectorize, defined above.
Parameters
----------
corpus : A list of strings, list of list of strings.
Represents a corpus as a list of sentences, where sentences
can either be strings or lists of tokens.
remove_oov : bool, optional, default False
If True, removes OOV items from the input before vectorization.
Returns
-------
c : list
A list of numpy arrays, where each array represents the transformed
sentence in the original list. The list is guaranteed to be the
same length as the input list, but the arrays in the list may be
of different lengths, depending on whether remove_oov is True.
"""
return [self.vectorize(s, remove_oov=remove_oov, norm=norm)
for s in corpus]
def most_similar(self,
items,
num=10,
batch_size=100,
show_progressbar=False,
return_names=True):
"""
Return the num most similar items to a given list of items.
Parameters
----------
items : list of objects or a single object.
The items to get the most similar items to.
num : int, optional, default 10
The number of most similar items to retrieve.
batch_size : int, optional, default 100.
The batch size to use. 100 is a good default option. Increasing
the batch size may increase the speed.
show_progressbar : bool, optional, default False
Whether to show a progressbar.
return_names : bool, optional, default True
Whether to return the item names, or just the distances.
Returns
-------
sim : array
For each items in the input the num most similar items are returned
in the form of (NAME, DISTANCE) tuples. If return_names is false,
the returned list just contains distances.
"""
# This line allows users to input single items.
# We used to rely on string identities, but we now also allow
# anything hashable as keys.
# Might fail if a list of passed items is also in the vocabulary.
# but I can't think of cases when this would happen, and what
# user expectations are.
try:
if items in self.items:
items = [items]
except TypeError:
pass
x = np.stack([self.norm_vectors[self.items[x]] for x in items])
result = self._batch(x,
batch_size,
num+1,
show_progressbar,
return_names)
# list call consumes the generator.
return [x[1:] for x in result]
def threshold(self,
items,
threshold=.5,
batch_size=100,
show_progressbar=False,
return_names=True):
"""
Return all items whose similarity is higher than threshold.
Parameters
----------
items : list of objects or a single object.
The items to get the most similar items to.
threshold : float, optional, default .5
The radius within which to retrieve items.
batch_size : int, optional, default 100.
The batch size to use. 100 is a good default option. Increasing
the batch size may increase the speed.
show_progressbar : bool, optional, default False
Whether to show a progressbar.
return_names : bool, optional, default True
Whether to return the item names, or just the distances.
Returns
-------
sim : array
For each items in the input the num most similar items are returned
in the form of (NAME, DISTANCE) tuples. If return_names is false,
the returned list just contains distances.
"""
# This line allows users to input single items.
# We used to rely on string identities, but we now also allow
# anything hashable as keys.
# Might fail if a list of passed items is also in the vocabulary.
# but I can't think of cases when this would happen, and what
# user expectations are.
try:
if items in self.items:
items = [items]
except TypeError:
pass
x = np.stack([self.norm_vectors[self.items[x]] for x in items])
result = self._threshold_batch(x,
batch_size,
threshold,
show_progressbar,
return_names)
# list call consumes the generator.
return [x[1:] for x in result]
def nearest_neighbor(self,
vectors,
num=10,
batch_size=100,
show_progressbar=False,
return_names=True):
"""
Find the nearest neighbors to some arbitrary vector.
This function is meant to be used in composition operations. The
most_similar function can only handle items that are in vocab, and
looks up their vector through a dictionary. Compositions, e.g.
"King - man + woman" are necessarily not in the vocabulary.
Parameters
----------
vectors : list of arrays or numpy array
The vectors to find the nearest neighbors to.
num : int, optional, default 10
The number of most similar items to retrieve.
batch_size : int, optional, default 100.
The batch size to use. 100 is a good default option. Increasing
the batch size may increase speed.
show_progressbar : bool, optional, default False
Whether to show a progressbar.
return_names : bool, optional, default True
Whether to return the item names, or just the distances.
Returns
-------
sim : list of tuples.
For each item in the input the num most similar items are returned
in the form of (NAME, DISTANCE) tuples. If return_names is set to
false, only the distances are returned.
"""
vectors = np.array(vectors)
if np.ndim(vectors) == 1:
vectors = vectors[None, :]
result = []
result = self._batch(vectors,
batch_size,
num+1,
show_progressbar,
return_names)
return list(result)
def _threshold_batch(self,
vectors,
batch_size,
threshold,
show_progressbar,
return_names):
"""Batched cosine distance."""
vectors = self.normalize(vectors)
# Single transpose, makes things faster.
reference_transposed = self.norm_vectors.T
for i in tqdm(range(0, len(vectors), batch_size),
disable=not show_progressbar):
distances = vectors[i: i+batch_size].dot(reference_transposed)
# For safety we clip
distances = np.clip(distances, a_min=.0, a_max=1.0)
for lidx, dists in enumerate(distances):
indices = np.flatnonzero(dists >= threshold)
sorted_indices = indices[np.argsort(-dists[indices])]
if return_names:
yield [(self.indices[d], dists[d])
for d in sorted_indices]
else:
yield list(dists[sorted_indices])
def _batch(self,
vectors,
batch_size,
num,
show_progressbar,
return_names):
"""Batched cosine distance."""
vectors = self.normalize(vectors)
# Single transpose, makes things faster.
reference_transposed = self.norm_vectors.T
for i in tqdm(range(0, len(vectors), batch_size),
disable=not show_progressbar):
distances = vectors[i: i+batch_size].dot(reference_transposed)
# For safety we clip
distances = np.clip(distances, a_min=.0, a_max=1.0)
if num == 1:
sorted_indices = np.argmax(distances, 1)[:, None]
else:
sorted_indices = np.argpartition(-distances, kth=num, axis=1)
sorted_indices = sorted_indices[:, :num]
for lidx, indices in enumerate(sorted_indices):
dists = distances[lidx, indices]
if return_names:
dindex = np.argsort(-dists)
yield [(self.indices[indices[d]], dists[d])
for d in dindex]
else:
yield list(-1 * np.sort(-dists))
@staticmethod
def normalize(vectors):
"""
Normalize a matrix of row vectors to unit length.
Contains a shortcut if there are no zero vectors in the matrix.
If there are zero vectors, we do some indexing tricks to avoid
dividing by 0.
Parameters
----------
vectors : np.array
The vectors to normalize.
Returns
-------
vectors : np.array
The input vectors, normalized to unit length.
"""
if np.ndim(vectors) == 1:
norm = np.linalg.norm(vectors)
if norm == 0:
return np.zeros_like(vectors)
return vectors / norm
norm = np.linalg.norm(vectors, axis=1)
if np.any(norm == 0):
nonzero = norm > 0
result = np.zeros_like(vectors)
n = norm[nonzero]
p = vectors[nonzero]
result[nonzero] = p / n[:, None]
return result
else:
return vectors / norm[:, None]
def vector_similarity(self, vector, items):
"""Compute the similarity between a vector and a set of items."""
vector = self.normalize(vector)
items_vec = np.stack([self.norm_vectors[self.items[x]] for x in items])
return vector.dot(items_vec.T)
def similarity(self, i1, i2):
"""
Compute the similarity between two sets of items.
Parameters
----------
i1 : object
The first set of items.
i2 : object
The second set of item.
Returns
-------
sim : array of floats
An array of similarity scores between 1 and 0.
"""
try:
if i1 in self.items:
i1 = [i1]
except TypeError:
pass
try:
if i2 in self.items:
i2 = [i2]
except TypeError:
pass
i1_vec = np.stack([self.norm_vectors[self.items[x]] for x in i1])
i2_vec = np.stack([self.norm_vectors[self.items[x]] for x in i2])
return i1_vec.dot(i2_vec.T)
def prune(self, wordlist):
"""
Prune the current reach instance by removing items.
Parameters
----------
wordlist : list of str
A list of words to keep. Note that this wordlist need not include
all words in the Reach instance. Any words which are in the
wordlist, but not in the reach instance are ignored.
"""
# Remove duplicates
wordlist = set(wordlist).intersection(set(self.items.keys()))
indices = [self.items[w] for w in wordlist if w in self.items]
if self.unk_index is not None and self.unk_index not in indices:
raise ValueError("Your unknown item is not in your list of items. "
"Set it to None before pruning, or pass your "
"unknown item.")
self.vectors = self.vectors[indices]
self.norm_vectors = self.norm_vectors[indices]
self.items = {w: idx for idx, w in enumerate(wordlist)}
self.indices = {v: k for k, v in self.items.items()}
if self.unk_index is not None:
self.unk_index = self.items[wordlist[self.unk_index]]
def save(self, path, write_header=True):
"""
Save the current vector space in word2vec format.
Parameters
----------
path : str
The path to save the vector file to.
write_header : bool, optional, default True
Whether to write a word2vec-style header as the first line of the
file
"""
with open(path, 'w') as f:
if write_header:
f.write(u"{0} {1}\n".format(str(self.vectors.shape[0]),
str(self.vectors.shape[1])))
for i in range(len(self.items)):
w = self.indices[i]
vec = self.vectors[i]
f.write(u"{0} {1}\n".format(w,
" ".join([str(x) for x in vec])))
def save_fast_format(self, filename):
"""
Save a reach instance in a fast format.
The reach fast format stores the words and vectors of a Reach instance
separately in a JSON and numpy format, respectively.
Parameters
----------
filename : str
The prefix to add to the saved filename. Note that this is not the
real filename under which these items are stored.
The words and unk_index are stored under "{filename}_words.json",
and the numpy matrix is saved under "{filename}_vectors.npy".
"""
items, _ = zip(*sorted(self.items.items(), key=lambda x: x[1]))
items = {"items": items,
"unk_index": self.unk_index,
"name": self.name}
json.dump(items, open("{}_items.json".format(filename), 'w'))
np.save(open("{}_vectors.npy".format(filename), 'wb'), self.vectors)
@staticmethod
def load_fast_format(filename):
"""
Load a reach instance in fast format.
As described above, the fast format stores the words and vectors of the
Reach instance separately, and is drastically faster than loading from
.txt files.
Parameters
----------
filename : str
The filename prefix from which to load. Note that this is not a
real filepath as such, but a shared prefix for both files.
In order for this to work, both {filename}_words.json and
{filename}_vectors.npy should be present.
"""
words, unk_index, name, vectors = Reach._load_fast(filename)
return Reach(vectors, words, unk_index=unk_index, name=name)
@staticmethod
def _load_fast(filename):
"""Sub for fast loader."""
it = json.load(open("{}_items.json".format(filename)))
words, unk_index, name = it["items"], it["unk_index"], it["name"]
vectors = np.load(open("{}_vectors.npy".format(filename), 'rb'))
return words, unk_index, name, vectors
|
stephantul/reach
|
reach/reach.py
|
Reach._threshold_batch
|
python
|
def _threshold_batch(self,
vectors,
batch_size,
threshold,
show_progressbar,
return_names):
vectors = self.normalize(vectors)
# Single transpose, makes things faster.
reference_transposed = self.norm_vectors.T
for i in tqdm(range(0, len(vectors), batch_size),
disable=not show_progressbar):
distances = vectors[i: i+batch_size].dot(reference_transposed)
# For safety we clip
distances = np.clip(distances, a_min=.0, a_max=1.0)
for lidx, dists in enumerate(distances):
indices = np.flatnonzero(dists >= threshold)
sorted_indices = indices[np.argsort(-dists[indices])]
if return_names:
yield [(self.indices[d], dists[d])
for d in sorted_indices]
else:
yield list(dists[sorted_indices])
|
Batched cosine distance.
|
train
|
https://github.com/stephantul/reach/blob/e5ed0cc895d17429e797c6d7dd57bce82ff00d5d/reach/reach.py#L511-L536
|
[
"def normalize(vectors):\n \"\"\"\n Normalize a matrix of row vectors to unit length.\n\n Contains a shortcut if there are no zero vectors in the matrix.\n If there are zero vectors, we do some indexing tricks to avoid\n dividing by 0.\n\n Parameters\n ----------\n vectors : np.array\n The vectors to normalize.\n\n Returns\n -------\n vectors : np.array\n The input vectors, normalized to unit length.\n\n \"\"\"\n if np.ndim(vectors) == 1:\n norm = np.linalg.norm(vectors)\n if norm == 0:\n return np.zeros_like(vectors)\n return vectors / norm\n\n norm = np.linalg.norm(vectors, axis=1)\n\n if np.any(norm == 0):\n\n nonzero = norm > 0\n\n result = np.zeros_like(vectors)\n\n n = norm[nonzero]\n p = vectors[nonzero]\n result[nonzero] = p / n[:, None]\n\n return result\n else:\n return vectors / norm[:, None]\n"
] |
class Reach(object):
"""
Work with vector representations of items.
Supports functions for calculating fast batched similarity
between items or composite representations of items.
Parameters
----------
vectors : numpy array
The vector space.
items : list
A list of items. Length must be equal to the number of vectors, and
aligned with the vectors.
name : string, optional
A string giving the name of the current reach. Only useful if you
have multiple spaces and want to keep track of them.
Attributes
----------
items : dict
A mapping from items to ids.
indices : dict
A mapping from ids to items.
vectors : numpy array
The array representing the vector space.
norm_vectors : numpy array
A normalized version of the vector space.
unk_index : int
The integer index of your unknown glyph. This glyph will be inserted
into your BoW space whenever an unknown item is encountered.
size : int
The dimensionality of the vector space.
name : string
The name of the Reach instance.
"""
def __init__(self, vectors, items, name="", unk_index=None):
"""Initialize a Reach instance with an array and list of items."""
if len(items) != len(vectors):
raise ValueError("Your vector space and list of items are not "
"the same length: "
"{} != {}".format(len(vectors), len(items)))
if isinstance(items, dict) or isinstance(items, set):
raise ValueError("Your item list is a set or dict, and might not "
"retain order in the conversion to internal look"
"-ups. Please convert it to list and check the "
"order.")
self.items = {w: idx for idx, w in enumerate(items)}
self.indices = {v: k for k, v in self.items.items()}
self.vectors = np.asarray(vectors)
self.norm_vectors = self.normalize(self.vectors)
self.unk_index = unk_index
self.size = self.vectors.shape[1]
self.name = name
@staticmethod
def load(pathtovector,
wordlist=(),
num_to_load=None,
truncate_embeddings=None,
unk_word=None,
sep=" "):
r"""
Read a file in word2vec .txt format.
The load function will raise a ValueError when trying to load items
which do not conform to line lengths.
Parameters
----------
pathtovector : string
The path to the vector file.
header : bool
Whether the vector file has a header of the type
(NUMBER OF ITEMS, SIZE OF VECTOR).
wordlist : iterable, optional, default ()
A list of words you want loaded from the vector file. If this is
None (default), all words will be loaded.
num_to_load : int, optional, default None
The number of items to load from the file. Because loading can take
some time, it is sometimes useful to onlyl load the first n items
from a vector file for quick inspection.
truncate_embeddings : int, optional, default None
If this value is not None, the vectors in the vector space will
be truncated to the number of dimensions indicated by this value.
unk_word : object
The object to treat as UNK in your vector space. If this is not
in your items dictionary after loading, we add it with a zero
vector.
Returns
-------
r : Reach
An initialized Reach instance.
"""
vectors, items = Reach._load(pathtovector,
wordlist,
num_to_load,
truncate_embeddings,
sep)
if unk_word is not None:
if unk_word not in set(items):
unk_vec = np.zeros((1, vectors.shape[1]))
vectors = np.concatenate([unk_vec, vectors], 0)
items = [unk_word] + items
unk_index = 0
else:
unk_index = items.index(unk_word)
else:
unk_index = None
return Reach(vectors,
items,
name=os.path.split(pathtovector)[-1],
unk_index=unk_index)
@staticmethod
def _load(pathtovector,
wordlist,
num_to_load=None,
truncate_embeddings=None,
sep=" "):
"""Load a matrix and wordlist from a .vec file."""
vectors = []
addedwords = set()
words = []
try:
wordlist = set(wordlist)
except ValueError:
wordlist = set()
logger.info("Loading {0}".format(pathtovector))
firstline = open(pathtovector).readline().strip()
try:
num, size = firstline.split(sep)
num, size = int(num), int(size)
logger.info("Vector space: {} by {}".format(num, size))
header = True
except ValueError:
size = len(firstline.split(sep)) - 1
logger.info("Vector space: {} dim, # items unknown".format(size))
word, rest = firstline.split(sep, 1)
# If the first line is correctly parseable, set header to False.
header = False
if truncate_embeddings is None or truncate_embeddings == 0:
truncate_embeddings = size
for idx, line in enumerate(open(pathtovector, encoding='utf-8')):
if header and idx == 0:
continue
word, rest = line.rstrip(" \n").split(sep, 1)
if wordlist and word not in wordlist:
continue
if word in addedwords:
raise ValueError("Duplicate: {} on line {} was in the "
"vector space twice".format(word, idx))
if len(rest.split(sep)) != size:
raise ValueError("Incorrect input at index {}, size "
"is {}, expected "
"{}".format(idx+1,
len(rest.split(sep)), size))
words.append(word)
addedwords.add(word)
vectors.append(np.fromstring(rest, sep=sep)[:truncate_embeddings])
if num_to_load is not None and len(addedwords) >= num_to_load:
break
vectors = np.array(vectors).astype(np.float32)
logger.info("Loading finished")
if wordlist:
diff = wordlist - addedwords
if diff:
logger.info("Not all items from your wordlist were in your "
"vector space: {}.".format(diff))
return vectors, words
def __getitem__(self, item):
"""Get the vector for a single item."""
return self.vectors[self.items[item]]
def vectorize(self, tokens, remove_oov=False, norm=False):
"""
Vectorize a sentence by replacing all items with their vectors.
Parameters
----------
tokens : object or list of objects
The tokens to vectorize.
remove_oov : bool, optional, default False
Whether to remove OOV items. If False, OOV items are replaced by
the UNK glyph. If this is True, the returned sequence might
have a different length than the original sequence.
norm : bool, optional, default False
Whether to return the unit vectors, or the regular vectors.
Returns
-------
s : numpy array
An M * N matrix, where every item has been replaced by
its vector. OOV items are either removed, or replaced
by the value of the UNK glyph.
"""
if not tokens:
raise ValueError("You supplied an empty list.")
index = list(self.bow(tokens, remove_oov=remove_oov))
if not index:
raise ValueError("You supplied a list with only OOV tokens: {}, "
"which then got removed. Set remove_oov to False,"
" or filter your sentences to remove any in which"
" all items are OOV.")
if norm:
return np.stack([self.norm_vectors[x] for x in index])
else:
return np.stack([self.vectors[x] for x in index])
def bow(self, tokens, remove_oov=False):
"""
Create a bow representation of a list of tokens.
Parameters
----------
tokens : list.
The list of items to change into a bag of words representation.
remove_oov : bool.
Whether to remove OOV items from the input.
If this is True, the length of the returned BOW representation
might not be the length of the original representation.
Returns
-------
bow : generator
A BOW representation of the list of items.
"""
if remove_oov:
tokens = [x for x in tokens if x in self.items]
for t in tokens:
try:
yield self.items[t]
except KeyError:
if self.unk_index is None:
raise ValueError("You supplied OOV items but didn't "
"provide the index of the replacement "
"glyph. Either set remove_oov to True, "
"or set unk_index to the index of the "
"item which replaces any OOV items.")
yield self.unk_index
def transform(self, corpus, remove_oov=False, norm=False):
"""
Transform a corpus by repeated calls to vectorize, defined above.
Parameters
----------
corpus : A list of strings, list of list of strings.
Represents a corpus as a list of sentences, where sentences
can either be strings or lists of tokens.
remove_oov : bool, optional, default False
If True, removes OOV items from the input before vectorization.
Returns
-------
c : list
A list of numpy arrays, where each array represents the transformed
sentence in the original list. The list is guaranteed to be the
same length as the input list, but the arrays in the list may be
of different lengths, depending on whether remove_oov is True.
"""
return [self.vectorize(s, remove_oov=remove_oov, norm=norm)
for s in corpus]
def most_similar(self,
items,
num=10,
batch_size=100,
show_progressbar=False,
return_names=True):
"""
Return the num most similar items to a given list of items.
Parameters
----------
items : list of objects or a single object.
The items to get the most similar items to.
num : int, optional, default 10
The number of most similar items to retrieve.
batch_size : int, optional, default 100.
The batch size to use. 100 is a good default option. Increasing
the batch size may increase the speed.
show_progressbar : bool, optional, default False
Whether to show a progressbar.
return_names : bool, optional, default True
Whether to return the item names, or just the distances.
Returns
-------
sim : array
For each items in the input the num most similar items are returned
in the form of (NAME, DISTANCE) tuples. If return_names is false,
the returned list just contains distances.
"""
# This line allows users to input single items.
# We used to rely on string identities, but we now also allow
# anything hashable as keys.
# Might fail if a list of passed items is also in the vocabulary.
# but I can't think of cases when this would happen, and what
# user expectations are.
try:
if items in self.items:
items = [items]
except TypeError:
pass
x = np.stack([self.norm_vectors[self.items[x]] for x in items])
result = self._batch(x,
batch_size,
num+1,
show_progressbar,
return_names)
# list call consumes the generator.
return [x[1:] for x in result]
def threshold(self,
items,
threshold=.5,
batch_size=100,
show_progressbar=False,
return_names=True):
"""
Return all items whose similarity is higher than threshold.
Parameters
----------
items : list of objects or a single object.
The items to get the most similar items to.
threshold : float, optional, default .5
The radius within which to retrieve items.
batch_size : int, optional, default 100.
The batch size to use. 100 is a good default option. Increasing
the batch size may increase the speed.
show_progressbar : bool, optional, default False
Whether to show a progressbar.
return_names : bool, optional, default True
Whether to return the item names, or just the distances.
Returns
-------
sim : array
For each items in the input the num most similar items are returned
in the form of (NAME, DISTANCE) tuples. If return_names is false,
the returned list just contains distances.
"""
# This line allows users to input single items.
# We used to rely on string identities, but we now also allow
# anything hashable as keys.
# Might fail if a list of passed items is also in the vocabulary.
# but I can't think of cases when this would happen, and what
# user expectations are.
try:
if items in self.items:
items = [items]
except TypeError:
pass
x = np.stack([self.norm_vectors[self.items[x]] for x in items])
result = self._threshold_batch(x,
batch_size,
threshold,
show_progressbar,
return_names)
# list call consumes the generator.
return [x[1:] for x in result]
def nearest_neighbor(self,
vectors,
num=10,
batch_size=100,
show_progressbar=False,
return_names=True):
"""
Find the nearest neighbors to some arbitrary vector.
This function is meant to be used in composition operations. The
most_similar function can only handle items that are in vocab, and
looks up their vector through a dictionary. Compositions, e.g.
"King - man + woman" are necessarily not in the vocabulary.
Parameters
----------
vectors : list of arrays or numpy array
The vectors to find the nearest neighbors to.
num : int, optional, default 10
The number of most similar items to retrieve.
batch_size : int, optional, default 100.
The batch size to use. 100 is a good default option. Increasing
the batch size may increase speed.
show_progressbar : bool, optional, default False
Whether to show a progressbar.
return_names : bool, optional, default True
Whether to return the item names, or just the distances.
Returns
-------
sim : list of tuples.
For each item in the input the num most similar items are returned
in the form of (NAME, DISTANCE) tuples. If return_names is set to
false, only the distances are returned.
"""
vectors = np.array(vectors)
if np.ndim(vectors) == 1:
vectors = vectors[None, :]
result = []
result = self._batch(vectors,
batch_size,
num+1,
show_progressbar,
return_names)
return list(result)
def nearest_neighbor_threshold(self,
vectors,
threshold=.5,
batch_size=100,
show_progressbar=False,
return_names=True):
"""
Find the nearest neighbors to some arbitrary vector.
This function is meant to be used in composition operations. The
most_similar function can only handle items that are in vocab, and
looks up their vector through a dictionary. Compositions, e.g.
"King - man + woman" are necessarily not in the vocabulary.
Parameters
----------
vectors : list of arrays or numpy array
The vectors to find the nearest neighbors to.
threshold : float, optional, default .5
The threshold within to retrieve items.
batch_size : int, optional, default 100.
The batch size to use. 100 is a good default option. Increasing
the batch size may increase speed.
show_progressbar : bool, optional, default False
Whether to show a progressbar.
return_names : bool, optional, default True
Whether to return the item names, or just the distances.
Returns
-------
sim : list of tuples.
For each item in the input the num most similar items are returned
in the form of (NAME, DISTANCE) tuples. If return_names is set to
false, only the distances are returned.
"""
vectors = np.array(vectors)
if np.ndim(vectors) == 1:
vectors = vectors[None, :]
result = []
result = self._threshold_batch(vectors,
batch_size,
threshold,
show_progressbar,
return_names)
return list(result)
def _batch(self,
vectors,
batch_size,
num,
show_progressbar,
return_names):
"""Batched cosine distance."""
vectors = self.normalize(vectors)
# Single transpose, makes things faster.
reference_transposed = self.norm_vectors.T
for i in tqdm(range(0, len(vectors), batch_size),
disable=not show_progressbar):
distances = vectors[i: i+batch_size].dot(reference_transposed)
# For safety we clip
distances = np.clip(distances, a_min=.0, a_max=1.0)
if num == 1:
sorted_indices = np.argmax(distances, 1)[:, None]
else:
sorted_indices = np.argpartition(-distances, kth=num, axis=1)
sorted_indices = sorted_indices[:, :num]
for lidx, indices in enumerate(sorted_indices):
dists = distances[lidx, indices]
if return_names:
dindex = np.argsort(-dists)
yield [(self.indices[indices[d]], dists[d])
for d in dindex]
else:
yield list(-1 * np.sort(-dists))
@staticmethod
def normalize(vectors):
"""
Normalize a matrix of row vectors to unit length.
Contains a shortcut if there are no zero vectors in the matrix.
If there are zero vectors, we do some indexing tricks to avoid
dividing by 0.
Parameters
----------
vectors : np.array
The vectors to normalize.
Returns
-------
vectors : np.array
The input vectors, normalized to unit length.
"""
if np.ndim(vectors) == 1:
norm = np.linalg.norm(vectors)
if norm == 0:
return np.zeros_like(vectors)
return vectors / norm
norm = np.linalg.norm(vectors, axis=1)
if np.any(norm == 0):
nonzero = norm > 0
result = np.zeros_like(vectors)
n = norm[nonzero]
p = vectors[nonzero]
result[nonzero] = p / n[:, None]
return result
else:
return vectors / norm[:, None]
def vector_similarity(self, vector, items):
"""Compute the similarity between a vector and a set of items."""
vector = self.normalize(vector)
items_vec = np.stack([self.norm_vectors[self.items[x]] for x in items])
return vector.dot(items_vec.T)
def similarity(self, i1, i2):
"""
Compute the similarity between two sets of items.
Parameters
----------
i1 : object
The first set of items.
i2 : object
The second set of item.
Returns
-------
sim : array of floats
An array of similarity scores between 1 and 0.
"""
try:
if i1 in self.items:
i1 = [i1]
except TypeError:
pass
try:
if i2 in self.items:
i2 = [i2]
except TypeError:
pass
i1_vec = np.stack([self.norm_vectors[self.items[x]] for x in i1])
i2_vec = np.stack([self.norm_vectors[self.items[x]] for x in i2])
return i1_vec.dot(i2_vec.T)
def prune(self, wordlist):
"""
Prune the current reach instance by removing items.
Parameters
----------
wordlist : list of str
A list of words to keep. Note that this wordlist need not include
all words in the Reach instance. Any words which are in the
wordlist, but not in the reach instance are ignored.
"""
# Remove duplicates
wordlist = set(wordlist).intersection(set(self.items.keys()))
indices = [self.items[w] for w in wordlist if w in self.items]
if self.unk_index is not None and self.unk_index not in indices:
raise ValueError("Your unknown item is not in your list of items. "
"Set it to None before pruning, or pass your "
"unknown item.")
self.vectors = self.vectors[indices]
self.norm_vectors = self.norm_vectors[indices]
self.items = {w: idx for idx, w in enumerate(wordlist)}
self.indices = {v: k for k, v in self.items.items()}
if self.unk_index is not None:
self.unk_index = self.items[wordlist[self.unk_index]]
def save(self, path, write_header=True):
"""
Save the current vector space in word2vec format.
Parameters
----------
path : str
The path to save the vector file to.
write_header : bool, optional, default True
Whether to write a word2vec-style header as the first line of the
file
"""
with open(path, 'w') as f:
if write_header:
f.write(u"{0} {1}\n".format(str(self.vectors.shape[0]),
str(self.vectors.shape[1])))
for i in range(len(self.items)):
w = self.indices[i]
vec = self.vectors[i]
f.write(u"{0} {1}\n".format(w,
" ".join([str(x) for x in vec])))
def save_fast_format(self, filename):
"""
Save a reach instance in a fast format.
The reach fast format stores the words and vectors of a Reach instance
separately in a JSON and numpy format, respectively.
Parameters
----------
filename : str
The prefix to add to the saved filename. Note that this is not the
real filename under which these items are stored.
The words and unk_index are stored under "{filename}_words.json",
and the numpy matrix is saved under "{filename}_vectors.npy".
"""
items, _ = zip(*sorted(self.items.items(), key=lambda x: x[1]))
items = {"items": items,
"unk_index": self.unk_index,
"name": self.name}
json.dump(items, open("{}_items.json".format(filename), 'w'))
np.save(open("{}_vectors.npy".format(filename), 'wb'), self.vectors)
@staticmethod
def load_fast_format(filename):
"""
Load a reach instance in fast format.
As described above, the fast format stores the words and vectors of the
Reach instance separately, and is drastically faster than loading from
.txt files.
Parameters
----------
filename : str
The filename prefix from which to load. Note that this is not a
real filepath as such, but a shared prefix for both files.
In order for this to work, both {filename}_words.json and
{filename}_vectors.npy should be present.
"""
words, unk_index, name, vectors = Reach._load_fast(filename)
return Reach(vectors, words, unk_index=unk_index, name=name)
@staticmethod
def _load_fast(filename):
"""Sub for fast loader."""
it = json.load(open("{}_items.json".format(filename)))
words, unk_index, name = it["items"], it["unk_index"], it["name"]
vectors = np.load(open("{}_vectors.npy".format(filename), 'rb'))
return words, unk_index, name, vectors
|
stephantul/reach
|
reach/reach.py
|
Reach._batch
|
python
|
def _batch(self,
vectors,
batch_size,
num,
show_progressbar,
return_names):
vectors = self.normalize(vectors)
# Single transpose, makes things faster.
reference_transposed = self.norm_vectors.T
for i in tqdm(range(0, len(vectors), batch_size),
disable=not show_progressbar):
distances = vectors[i: i+batch_size].dot(reference_transposed)
# For safety we clip
distances = np.clip(distances, a_min=.0, a_max=1.0)
if num == 1:
sorted_indices = np.argmax(distances, 1)[:, None]
else:
sorted_indices = np.argpartition(-distances, kth=num, axis=1)
sorted_indices = sorted_indices[:, :num]
for lidx, indices in enumerate(sorted_indices):
dists = distances[lidx, indices]
if return_names:
dindex = np.argsort(-dists)
yield [(self.indices[indices[d]], dists[d])
for d in dindex]
else:
yield list(-1 * np.sort(-dists))
|
Batched cosine distance.
|
train
|
https://github.com/stephantul/reach/blob/e5ed0cc895d17429e797c6d7dd57bce82ff00d5d/reach/reach.py#L538-L568
|
[
"def normalize(vectors):\n \"\"\"\n Normalize a matrix of row vectors to unit length.\n\n Contains a shortcut if there are no zero vectors in the matrix.\n If there are zero vectors, we do some indexing tricks to avoid\n dividing by 0.\n\n Parameters\n ----------\n vectors : np.array\n The vectors to normalize.\n\n Returns\n -------\n vectors : np.array\n The input vectors, normalized to unit length.\n\n \"\"\"\n if np.ndim(vectors) == 1:\n norm = np.linalg.norm(vectors)\n if norm == 0:\n return np.zeros_like(vectors)\n return vectors / norm\n\n norm = np.linalg.norm(vectors, axis=1)\n\n if np.any(norm == 0):\n\n nonzero = norm > 0\n\n result = np.zeros_like(vectors)\n\n n = norm[nonzero]\n p = vectors[nonzero]\n result[nonzero] = p / n[:, None]\n\n return result\n else:\n return vectors / norm[:, None]\n"
] |
class Reach(object):
"""
Work with vector representations of items.
Supports functions for calculating fast batched similarity
between items or composite representations of items.
Parameters
----------
vectors : numpy array
The vector space.
items : list
A list of items. Length must be equal to the number of vectors, and
aligned with the vectors.
name : string, optional
A string giving the name of the current reach. Only useful if you
have multiple spaces and want to keep track of them.
Attributes
----------
items : dict
A mapping from items to ids.
indices : dict
A mapping from ids to items.
vectors : numpy array
The array representing the vector space.
norm_vectors : numpy array
A normalized version of the vector space.
unk_index : int
The integer index of your unknown glyph. This glyph will be inserted
into your BoW space whenever an unknown item is encountered.
size : int
The dimensionality of the vector space.
name : string
The name of the Reach instance.
"""
def __init__(self, vectors, items, name="", unk_index=None):
"""Initialize a Reach instance with an array and list of items."""
if len(items) != len(vectors):
raise ValueError("Your vector space and list of items are not "
"the same length: "
"{} != {}".format(len(vectors), len(items)))
if isinstance(items, dict) or isinstance(items, set):
raise ValueError("Your item list is a set or dict, and might not "
"retain order in the conversion to internal look"
"-ups. Please convert it to list and check the "
"order.")
self.items = {w: idx for idx, w in enumerate(items)}
self.indices = {v: k for k, v in self.items.items()}
self.vectors = np.asarray(vectors)
self.norm_vectors = self.normalize(self.vectors)
self.unk_index = unk_index
self.size = self.vectors.shape[1]
self.name = name
@staticmethod
def load(pathtovector,
wordlist=(),
num_to_load=None,
truncate_embeddings=None,
unk_word=None,
sep=" "):
r"""
Read a file in word2vec .txt format.
The load function will raise a ValueError when trying to load items
which do not conform to line lengths.
Parameters
----------
pathtovector : string
The path to the vector file.
header : bool
Whether the vector file has a header of the type
(NUMBER OF ITEMS, SIZE OF VECTOR).
wordlist : iterable, optional, default ()
A list of words you want loaded from the vector file. If this is
None (default), all words will be loaded.
num_to_load : int, optional, default None
The number of items to load from the file. Because loading can take
some time, it is sometimes useful to onlyl load the first n items
from a vector file for quick inspection.
truncate_embeddings : int, optional, default None
If this value is not None, the vectors in the vector space will
be truncated to the number of dimensions indicated by this value.
unk_word : object
The object to treat as UNK in your vector space. If this is not
in your items dictionary after loading, we add it with a zero
vector.
Returns
-------
r : Reach
An initialized Reach instance.
"""
vectors, items = Reach._load(pathtovector,
wordlist,
num_to_load,
truncate_embeddings,
sep)
if unk_word is not None:
if unk_word not in set(items):
unk_vec = np.zeros((1, vectors.shape[1]))
vectors = np.concatenate([unk_vec, vectors], 0)
items = [unk_word] + items
unk_index = 0
else:
unk_index = items.index(unk_word)
else:
unk_index = None
return Reach(vectors,
items,
name=os.path.split(pathtovector)[-1],
unk_index=unk_index)
@staticmethod
def _load(pathtovector,
wordlist,
num_to_load=None,
truncate_embeddings=None,
sep=" "):
"""Load a matrix and wordlist from a .vec file."""
vectors = []
addedwords = set()
words = []
try:
wordlist = set(wordlist)
except ValueError:
wordlist = set()
logger.info("Loading {0}".format(pathtovector))
firstline = open(pathtovector).readline().strip()
try:
num, size = firstline.split(sep)
num, size = int(num), int(size)
logger.info("Vector space: {} by {}".format(num, size))
header = True
except ValueError:
size = len(firstline.split(sep)) - 1
logger.info("Vector space: {} dim, # items unknown".format(size))
word, rest = firstline.split(sep, 1)
# If the first line is correctly parseable, set header to False.
header = False
if truncate_embeddings is None or truncate_embeddings == 0:
truncate_embeddings = size
for idx, line in enumerate(open(pathtovector, encoding='utf-8')):
if header and idx == 0:
continue
word, rest = line.rstrip(" \n").split(sep, 1)
if wordlist and word not in wordlist:
continue
if word in addedwords:
raise ValueError("Duplicate: {} on line {} was in the "
"vector space twice".format(word, idx))
if len(rest.split(sep)) != size:
raise ValueError("Incorrect input at index {}, size "
"is {}, expected "
"{}".format(idx+1,
len(rest.split(sep)), size))
words.append(word)
addedwords.add(word)
vectors.append(np.fromstring(rest, sep=sep)[:truncate_embeddings])
if num_to_load is not None and len(addedwords) >= num_to_load:
break
vectors = np.array(vectors).astype(np.float32)
logger.info("Loading finished")
if wordlist:
diff = wordlist - addedwords
if diff:
logger.info("Not all items from your wordlist were in your "
"vector space: {}.".format(diff))
return vectors, words
def __getitem__(self, item):
"""Get the vector for a single item."""
return self.vectors[self.items[item]]
def vectorize(self, tokens, remove_oov=False, norm=False):
"""
Vectorize a sentence by replacing all items with their vectors.
Parameters
----------
tokens : object or list of objects
The tokens to vectorize.
remove_oov : bool, optional, default False
Whether to remove OOV items. If False, OOV items are replaced by
the UNK glyph. If this is True, the returned sequence might
have a different length than the original sequence.
norm : bool, optional, default False
Whether to return the unit vectors, or the regular vectors.
Returns
-------
s : numpy array
An M * N matrix, where every item has been replaced by
its vector. OOV items are either removed, or replaced
by the value of the UNK glyph.
"""
if not tokens:
raise ValueError("You supplied an empty list.")
index = list(self.bow(tokens, remove_oov=remove_oov))
if not index:
raise ValueError("You supplied a list with only OOV tokens: {}, "
"which then got removed. Set remove_oov to False,"
" or filter your sentences to remove any in which"
" all items are OOV.")
if norm:
return np.stack([self.norm_vectors[x] for x in index])
else:
return np.stack([self.vectors[x] for x in index])
def bow(self, tokens, remove_oov=False):
"""
Create a bow representation of a list of tokens.
Parameters
----------
tokens : list.
The list of items to change into a bag of words representation.
remove_oov : bool.
Whether to remove OOV items from the input.
If this is True, the length of the returned BOW representation
might not be the length of the original representation.
Returns
-------
bow : generator
A BOW representation of the list of items.
"""
if remove_oov:
tokens = [x for x in tokens if x in self.items]
for t in tokens:
try:
yield self.items[t]
except KeyError:
if self.unk_index is None:
raise ValueError("You supplied OOV items but didn't "
"provide the index of the replacement "
"glyph. Either set remove_oov to True, "
"or set unk_index to the index of the "
"item which replaces any OOV items.")
yield self.unk_index
def transform(self, corpus, remove_oov=False, norm=False):
"""
Transform a corpus by repeated calls to vectorize, defined above.
Parameters
----------
corpus : A list of strings, list of list of strings.
Represents a corpus as a list of sentences, where sentences
can either be strings or lists of tokens.
remove_oov : bool, optional, default False
If True, removes OOV items from the input before vectorization.
Returns
-------
c : list
A list of numpy arrays, where each array represents the transformed
sentence in the original list. The list is guaranteed to be the
same length as the input list, but the arrays in the list may be
of different lengths, depending on whether remove_oov is True.
"""
return [self.vectorize(s, remove_oov=remove_oov, norm=norm)
for s in corpus]
def most_similar(self,
items,
num=10,
batch_size=100,
show_progressbar=False,
return_names=True):
"""
Return the num most similar items to a given list of items.
Parameters
----------
items : list of objects or a single object.
The items to get the most similar items to.
num : int, optional, default 10
The number of most similar items to retrieve.
batch_size : int, optional, default 100.
The batch size to use. 100 is a good default option. Increasing
the batch size may increase the speed.
show_progressbar : bool, optional, default False
Whether to show a progressbar.
return_names : bool, optional, default True
Whether to return the item names, or just the distances.
Returns
-------
sim : array
For each items in the input the num most similar items are returned
in the form of (NAME, DISTANCE) tuples. If return_names is false,
the returned list just contains distances.
"""
# This line allows users to input single items.
# We used to rely on string identities, but we now also allow
# anything hashable as keys.
# Might fail if a list of passed items is also in the vocabulary.
# but I can't think of cases when this would happen, and what
# user expectations are.
try:
if items in self.items:
items = [items]
except TypeError:
pass
x = np.stack([self.norm_vectors[self.items[x]] for x in items])
result = self._batch(x,
batch_size,
num+1,
show_progressbar,
return_names)
# list call consumes the generator.
return [x[1:] for x in result]
def threshold(self,
items,
threshold=.5,
batch_size=100,
show_progressbar=False,
return_names=True):
"""
Return all items whose similarity is higher than threshold.
Parameters
----------
items : list of objects or a single object.
The items to get the most similar items to.
threshold : float, optional, default .5
The radius within which to retrieve items.
batch_size : int, optional, default 100.
The batch size to use. 100 is a good default option. Increasing
the batch size may increase the speed.
show_progressbar : bool, optional, default False
Whether to show a progressbar.
return_names : bool, optional, default True
Whether to return the item names, or just the distances.
Returns
-------
sim : array
For each items in the input the num most similar items are returned
in the form of (NAME, DISTANCE) tuples. If return_names is false,
the returned list just contains distances.
"""
# This line allows users to input single items.
# We used to rely on string identities, but we now also allow
# anything hashable as keys.
# Might fail if a list of passed items is also in the vocabulary.
# but I can't think of cases when this would happen, and what
# user expectations are.
try:
if items in self.items:
items = [items]
except TypeError:
pass
x = np.stack([self.norm_vectors[self.items[x]] for x in items])
result = self._threshold_batch(x,
batch_size,
threshold,
show_progressbar,
return_names)
# list call consumes the generator.
return [x[1:] for x in result]
def nearest_neighbor(self,
vectors,
num=10,
batch_size=100,
show_progressbar=False,
return_names=True):
"""
Find the nearest neighbors to some arbitrary vector.
This function is meant to be used in composition operations. The
most_similar function can only handle items that are in vocab, and
looks up their vector through a dictionary. Compositions, e.g.
"King - man + woman" are necessarily not in the vocabulary.
Parameters
----------
vectors : list of arrays or numpy array
The vectors to find the nearest neighbors to.
num : int, optional, default 10
The number of most similar items to retrieve.
batch_size : int, optional, default 100.
The batch size to use. 100 is a good default option. Increasing
the batch size may increase speed.
show_progressbar : bool, optional, default False
Whether to show a progressbar.
return_names : bool, optional, default True
Whether to return the item names, or just the distances.
Returns
-------
sim : list of tuples.
For each item in the input the num most similar items are returned
in the form of (NAME, DISTANCE) tuples. If return_names is set to
false, only the distances are returned.
"""
vectors = np.array(vectors)
if np.ndim(vectors) == 1:
vectors = vectors[None, :]
result = []
result = self._batch(vectors,
batch_size,
num+1,
show_progressbar,
return_names)
return list(result)
def nearest_neighbor_threshold(self,
vectors,
threshold=.5,
batch_size=100,
show_progressbar=False,
return_names=True):
"""
Find the nearest neighbors to some arbitrary vector.
This function is meant to be used in composition operations. The
most_similar function can only handle items that are in vocab, and
looks up their vector through a dictionary. Compositions, e.g.
"King - man + woman" are necessarily not in the vocabulary.
Parameters
----------
vectors : list of arrays or numpy array
The vectors to find the nearest neighbors to.
threshold : float, optional, default .5
The threshold within to retrieve items.
batch_size : int, optional, default 100.
The batch size to use. 100 is a good default option. Increasing
the batch size may increase speed.
show_progressbar : bool, optional, default False
Whether to show a progressbar.
return_names : bool, optional, default True
Whether to return the item names, or just the distances.
Returns
-------
sim : list of tuples.
For each item in the input the num most similar items are returned
in the form of (NAME, DISTANCE) tuples. If return_names is set to
false, only the distances are returned.
"""
vectors = np.array(vectors)
if np.ndim(vectors) == 1:
vectors = vectors[None, :]
result = []
result = self._threshold_batch(vectors,
batch_size,
threshold,
show_progressbar,
return_names)
return list(result)
def _threshold_batch(self,
vectors,
batch_size,
threshold,
show_progressbar,
return_names):
"""Batched cosine distance."""
vectors = self.normalize(vectors)
# Single transpose, makes things faster.
reference_transposed = self.norm_vectors.T
for i in tqdm(range(0, len(vectors), batch_size),
disable=not show_progressbar):
distances = vectors[i: i+batch_size].dot(reference_transposed)
# For safety we clip
distances = np.clip(distances, a_min=.0, a_max=1.0)
for lidx, dists in enumerate(distances):
indices = np.flatnonzero(dists >= threshold)
sorted_indices = indices[np.argsort(-dists[indices])]
if return_names:
yield [(self.indices[d], dists[d])
for d in sorted_indices]
else:
yield list(dists[sorted_indices])
@staticmethod
def normalize(vectors):
"""
Normalize a matrix of row vectors to unit length.
Contains a shortcut if there are no zero vectors in the matrix.
If there are zero vectors, we do some indexing tricks to avoid
dividing by 0.
Parameters
----------
vectors : np.array
The vectors to normalize.
Returns
-------
vectors : np.array
The input vectors, normalized to unit length.
"""
if np.ndim(vectors) == 1:
norm = np.linalg.norm(vectors)
if norm == 0:
return np.zeros_like(vectors)
return vectors / norm
norm = np.linalg.norm(vectors, axis=1)
if np.any(norm == 0):
nonzero = norm > 0
result = np.zeros_like(vectors)
n = norm[nonzero]
p = vectors[nonzero]
result[nonzero] = p / n[:, None]
return result
else:
return vectors / norm[:, None]
def vector_similarity(self, vector, items):
"""Compute the similarity between a vector and a set of items."""
vector = self.normalize(vector)
items_vec = np.stack([self.norm_vectors[self.items[x]] for x in items])
return vector.dot(items_vec.T)
def similarity(self, i1, i2):
"""
Compute the similarity between two sets of items.
Parameters
----------
i1 : object
The first set of items.
i2 : object
The second set of item.
Returns
-------
sim : array of floats
An array of similarity scores between 1 and 0.
"""
try:
if i1 in self.items:
i1 = [i1]
except TypeError:
pass
try:
if i2 in self.items:
i2 = [i2]
except TypeError:
pass
i1_vec = np.stack([self.norm_vectors[self.items[x]] for x in i1])
i2_vec = np.stack([self.norm_vectors[self.items[x]] for x in i2])
return i1_vec.dot(i2_vec.T)
def prune(self, wordlist):
"""
Prune the current reach instance by removing items.
Parameters
----------
wordlist : list of str
A list of words to keep. Note that this wordlist need not include
all words in the Reach instance. Any words which are in the
wordlist, but not in the reach instance are ignored.
"""
# Remove duplicates
wordlist = set(wordlist).intersection(set(self.items.keys()))
indices = [self.items[w] for w in wordlist if w in self.items]
if self.unk_index is not None and self.unk_index not in indices:
raise ValueError("Your unknown item is not in your list of items. "
"Set it to None before pruning, or pass your "
"unknown item.")
self.vectors = self.vectors[indices]
self.norm_vectors = self.norm_vectors[indices]
self.items = {w: idx for idx, w in enumerate(wordlist)}
self.indices = {v: k for k, v in self.items.items()}
if self.unk_index is not None:
self.unk_index = self.items[wordlist[self.unk_index]]
def save(self, path, write_header=True):
"""
Save the current vector space in word2vec format.
Parameters
----------
path : str
The path to save the vector file to.
write_header : bool, optional, default True
Whether to write a word2vec-style header as the first line of the
file
"""
with open(path, 'w') as f:
if write_header:
f.write(u"{0} {1}\n".format(str(self.vectors.shape[0]),
str(self.vectors.shape[1])))
for i in range(len(self.items)):
w = self.indices[i]
vec = self.vectors[i]
f.write(u"{0} {1}\n".format(w,
" ".join([str(x) for x in vec])))
def save_fast_format(self, filename):
"""
Save a reach instance in a fast format.
The reach fast format stores the words and vectors of a Reach instance
separately in a JSON and numpy format, respectively.
Parameters
----------
filename : str
The prefix to add to the saved filename. Note that this is not the
real filename under which these items are stored.
The words and unk_index are stored under "{filename}_words.json",
and the numpy matrix is saved under "{filename}_vectors.npy".
"""
items, _ = zip(*sorted(self.items.items(), key=lambda x: x[1]))
items = {"items": items,
"unk_index": self.unk_index,
"name": self.name}
json.dump(items, open("{}_items.json".format(filename), 'w'))
np.save(open("{}_vectors.npy".format(filename), 'wb'), self.vectors)
@staticmethod
def load_fast_format(filename):
"""
Load a reach instance in fast format.
As described above, the fast format stores the words and vectors of the
Reach instance separately, and is drastically faster than loading from
.txt files.
Parameters
----------
filename : str
The filename prefix from which to load. Note that this is not a
real filepath as such, but a shared prefix for both files.
In order for this to work, both {filename}_words.json and
{filename}_vectors.npy should be present.
"""
words, unk_index, name, vectors = Reach._load_fast(filename)
return Reach(vectors, words, unk_index=unk_index, name=name)
@staticmethod
def _load_fast(filename):
"""Sub for fast loader."""
it = json.load(open("{}_items.json".format(filename)))
words, unk_index, name = it["items"], it["unk_index"], it["name"]
vectors = np.load(open("{}_vectors.npy".format(filename), 'rb'))
return words, unk_index, name, vectors
|
stephantul/reach
|
reach/reach.py
|
Reach.normalize
|
python
|
def normalize(vectors):
if np.ndim(vectors) == 1:
norm = np.linalg.norm(vectors)
if norm == 0:
return np.zeros_like(vectors)
return vectors / norm
norm = np.linalg.norm(vectors, axis=1)
if np.any(norm == 0):
nonzero = norm > 0
result = np.zeros_like(vectors)
n = norm[nonzero]
p = vectors[nonzero]
result[nonzero] = p / n[:, None]
return result
else:
return vectors / norm[:, None]
|
Normalize a matrix of row vectors to unit length.
Contains a shortcut if there are no zero vectors in the matrix.
If there are zero vectors, we do some indexing tricks to avoid
dividing by 0.
Parameters
----------
vectors : np.array
The vectors to normalize.
Returns
-------
vectors : np.array
The input vectors, normalized to unit length.
|
train
|
https://github.com/stephantul/reach/blob/e5ed0cc895d17429e797c6d7dd57bce82ff00d5d/reach/reach.py#L571-L610
| null |
class Reach(object):
"""
Work with vector representations of items.
Supports functions for calculating fast batched similarity
between items or composite representations of items.
Parameters
----------
vectors : numpy array
The vector space.
items : list
A list of items. Length must be equal to the number of vectors, and
aligned with the vectors.
name : string, optional
A string giving the name of the current reach. Only useful if you
have multiple spaces and want to keep track of them.
Attributes
----------
items : dict
A mapping from items to ids.
indices : dict
A mapping from ids to items.
vectors : numpy array
The array representing the vector space.
norm_vectors : numpy array
A normalized version of the vector space.
unk_index : int
The integer index of your unknown glyph. This glyph will be inserted
into your BoW space whenever an unknown item is encountered.
size : int
The dimensionality of the vector space.
name : string
The name of the Reach instance.
"""
def __init__(self, vectors, items, name="", unk_index=None):
"""Initialize a Reach instance with an array and list of items."""
if len(items) != len(vectors):
raise ValueError("Your vector space and list of items are not "
"the same length: "
"{} != {}".format(len(vectors), len(items)))
if isinstance(items, dict) or isinstance(items, set):
raise ValueError("Your item list is a set or dict, and might not "
"retain order in the conversion to internal look"
"-ups. Please convert it to list and check the "
"order.")
self.items = {w: idx for idx, w in enumerate(items)}
self.indices = {v: k for k, v in self.items.items()}
self.vectors = np.asarray(vectors)
self.norm_vectors = self.normalize(self.vectors)
self.unk_index = unk_index
self.size = self.vectors.shape[1]
self.name = name
@staticmethod
def load(pathtovector,
wordlist=(),
num_to_load=None,
truncate_embeddings=None,
unk_word=None,
sep=" "):
r"""
Read a file in word2vec .txt format.
The load function will raise a ValueError when trying to load items
which do not conform to line lengths.
Parameters
----------
pathtovector : string
The path to the vector file.
header : bool
Whether the vector file has a header of the type
(NUMBER OF ITEMS, SIZE OF VECTOR).
wordlist : iterable, optional, default ()
A list of words you want loaded from the vector file. If this is
None (default), all words will be loaded.
num_to_load : int, optional, default None
The number of items to load from the file. Because loading can take
some time, it is sometimes useful to onlyl load the first n items
from a vector file for quick inspection.
truncate_embeddings : int, optional, default None
If this value is not None, the vectors in the vector space will
be truncated to the number of dimensions indicated by this value.
unk_word : object
The object to treat as UNK in your vector space. If this is not
in your items dictionary after loading, we add it with a zero
vector.
Returns
-------
r : Reach
An initialized Reach instance.
"""
vectors, items = Reach._load(pathtovector,
wordlist,
num_to_load,
truncate_embeddings,
sep)
if unk_word is not None:
if unk_word not in set(items):
unk_vec = np.zeros((1, vectors.shape[1]))
vectors = np.concatenate([unk_vec, vectors], 0)
items = [unk_word] + items
unk_index = 0
else:
unk_index = items.index(unk_word)
else:
unk_index = None
return Reach(vectors,
items,
name=os.path.split(pathtovector)[-1],
unk_index=unk_index)
@staticmethod
def _load(pathtovector,
wordlist,
num_to_load=None,
truncate_embeddings=None,
sep=" "):
"""Load a matrix and wordlist from a .vec file."""
vectors = []
addedwords = set()
words = []
try:
wordlist = set(wordlist)
except ValueError:
wordlist = set()
logger.info("Loading {0}".format(pathtovector))
firstline = open(pathtovector).readline().strip()
try:
num, size = firstline.split(sep)
num, size = int(num), int(size)
logger.info("Vector space: {} by {}".format(num, size))
header = True
except ValueError:
size = len(firstline.split(sep)) - 1
logger.info("Vector space: {} dim, # items unknown".format(size))
word, rest = firstline.split(sep, 1)
# If the first line is correctly parseable, set header to False.
header = False
if truncate_embeddings is None or truncate_embeddings == 0:
truncate_embeddings = size
for idx, line in enumerate(open(pathtovector, encoding='utf-8')):
if header and idx == 0:
continue
word, rest = line.rstrip(" \n").split(sep, 1)
if wordlist and word not in wordlist:
continue
if word in addedwords:
raise ValueError("Duplicate: {} on line {} was in the "
"vector space twice".format(word, idx))
if len(rest.split(sep)) != size:
raise ValueError("Incorrect input at index {}, size "
"is {}, expected "
"{}".format(idx+1,
len(rest.split(sep)), size))
words.append(word)
addedwords.add(word)
vectors.append(np.fromstring(rest, sep=sep)[:truncate_embeddings])
if num_to_load is not None and len(addedwords) >= num_to_load:
break
vectors = np.array(vectors).astype(np.float32)
logger.info("Loading finished")
if wordlist:
diff = wordlist - addedwords
if diff:
logger.info("Not all items from your wordlist were in your "
"vector space: {}.".format(diff))
return vectors, words
def __getitem__(self, item):
"""Get the vector for a single item."""
return self.vectors[self.items[item]]
def vectorize(self, tokens, remove_oov=False, norm=False):
"""
Vectorize a sentence by replacing all items with their vectors.
Parameters
----------
tokens : object or list of objects
The tokens to vectorize.
remove_oov : bool, optional, default False
Whether to remove OOV items. If False, OOV items are replaced by
the UNK glyph. If this is True, the returned sequence might
have a different length than the original sequence.
norm : bool, optional, default False
Whether to return the unit vectors, or the regular vectors.
Returns
-------
s : numpy array
An M * N matrix, where every item has been replaced by
its vector. OOV items are either removed, or replaced
by the value of the UNK glyph.
"""
if not tokens:
raise ValueError("You supplied an empty list.")
index = list(self.bow(tokens, remove_oov=remove_oov))
if not index:
raise ValueError("You supplied a list with only OOV tokens: {}, "
"which then got removed. Set remove_oov to False,"
" or filter your sentences to remove any in which"
" all items are OOV.")
if norm:
return np.stack([self.norm_vectors[x] for x in index])
else:
return np.stack([self.vectors[x] for x in index])
def bow(self, tokens, remove_oov=False):
"""
Create a bow representation of a list of tokens.
Parameters
----------
tokens : list.
The list of items to change into a bag of words representation.
remove_oov : bool.
Whether to remove OOV items from the input.
If this is True, the length of the returned BOW representation
might not be the length of the original representation.
Returns
-------
bow : generator
A BOW representation of the list of items.
"""
if remove_oov:
tokens = [x for x in tokens if x in self.items]
for t in tokens:
try:
yield self.items[t]
except KeyError:
if self.unk_index is None:
raise ValueError("You supplied OOV items but didn't "
"provide the index of the replacement "
"glyph. Either set remove_oov to True, "
"or set unk_index to the index of the "
"item which replaces any OOV items.")
yield self.unk_index
def transform(self, corpus, remove_oov=False, norm=False):
"""
Transform a corpus by repeated calls to vectorize, defined above.
Parameters
----------
corpus : A list of strings, list of list of strings.
Represents a corpus as a list of sentences, where sentences
can either be strings or lists of tokens.
remove_oov : bool, optional, default False
If True, removes OOV items from the input before vectorization.
Returns
-------
c : list
A list of numpy arrays, where each array represents the transformed
sentence in the original list. The list is guaranteed to be the
same length as the input list, but the arrays in the list may be
of different lengths, depending on whether remove_oov is True.
"""
return [self.vectorize(s, remove_oov=remove_oov, norm=norm)
for s in corpus]
def most_similar(self,
items,
num=10,
batch_size=100,
show_progressbar=False,
return_names=True):
"""
Return the num most similar items to a given list of items.
Parameters
----------
items : list of objects or a single object.
The items to get the most similar items to.
num : int, optional, default 10
The number of most similar items to retrieve.
batch_size : int, optional, default 100.
The batch size to use. 100 is a good default option. Increasing
the batch size may increase the speed.
show_progressbar : bool, optional, default False
Whether to show a progressbar.
return_names : bool, optional, default True
Whether to return the item names, or just the distances.
Returns
-------
sim : array
For each items in the input the num most similar items are returned
in the form of (NAME, DISTANCE) tuples. If return_names is false,
the returned list just contains distances.
"""
# This line allows users to input single items.
# We used to rely on string identities, but we now also allow
# anything hashable as keys.
# Might fail if a list of passed items is also in the vocabulary.
# but I can't think of cases when this would happen, and what
# user expectations are.
try:
if items in self.items:
items = [items]
except TypeError:
pass
x = np.stack([self.norm_vectors[self.items[x]] for x in items])
result = self._batch(x,
batch_size,
num+1,
show_progressbar,
return_names)
# list call consumes the generator.
return [x[1:] for x in result]
def threshold(self,
items,
threshold=.5,
batch_size=100,
show_progressbar=False,
return_names=True):
"""
Return all items whose similarity is higher than threshold.
Parameters
----------
items : list of objects or a single object.
The items to get the most similar items to.
threshold : float, optional, default .5
The radius within which to retrieve items.
batch_size : int, optional, default 100.
The batch size to use. 100 is a good default option. Increasing
the batch size may increase the speed.
show_progressbar : bool, optional, default False
Whether to show a progressbar.
return_names : bool, optional, default True
Whether to return the item names, or just the distances.
Returns
-------
sim : array
For each items in the input the num most similar items are returned
in the form of (NAME, DISTANCE) tuples. If return_names is false,
the returned list just contains distances.
"""
# This line allows users to input single items.
# We used to rely on string identities, but we now also allow
# anything hashable as keys.
# Might fail if a list of passed items is also in the vocabulary.
# but I can't think of cases when this would happen, and what
# user expectations are.
try:
if items in self.items:
items = [items]
except TypeError:
pass
x = np.stack([self.norm_vectors[self.items[x]] for x in items])
result = self._threshold_batch(x,
batch_size,
threshold,
show_progressbar,
return_names)
# list call consumes the generator.
return [x[1:] for x in result]
def nearest_neighbor(self,
vectors,
num=10,
batch_size=100,
show_progressbar=False,
return_names=True):
"""
Find the nearest neighbors to some arbitrary vector.
This function is meant to be used in composition operations. The
most_similar function can only handle items that are in vocab, and
looks up their vector through a dictionary. Compositions, e.g.
"King - man + woman" are necessarily not in the vocabulary.
Parameters
----------
vectors : list of arrays or numpy array
The vectors to find the nearest neighbors to.
num : int, optional, default 10
The number of most similar items to retrieve.
batch_size : int, optional, default 100.
The batch size to use. 100 is a good default option. Increasing
the batch size may increase speed.
show_progressbar : bool, optional, default False
Whether to show a progressbar.
return_names : bool, optional, default True
Whether to return the item names, or just the distances.
Returns
-------
sim : list of tuples.
For each item in the input the num most similar items are returned
in the form of (NAME, DISTANCE) tuples. If return_names is set to
false, only the distances are returned.
"""
vectors = np.array(vectors)
if np.ndim(vectors) == 1:
vectors = vectors[None, :]
result = []
result = self._batch(vectors,
batch_size,
num+1,
show_progressbar,
return_names)
return list(result)
def nearest_neighbor_threshold(self,
vectors,
threshold=.5,
batch_size=100,
show_progressbar=False,
return_names=True):
"""
Find the nearest neighbors to some arbitrary vector.
This function is meant to be used in composition operations. The
most_similar function can only handle items that are in vocab, and
looks up their vector through a dictionary. Compositions, e.g.
"King - man + woman" are necessarily not in the vocabulary.
Parameters
----------
vectors : list of arrays or numpy array
The vectors to find the nearest neighbors to.
threshold : float, optional, default .5
The threshold within to retrieve items.
batch_size : int, optional, default 100.
The batch size to use. 100 is a good default option. Increasing
the batch size may increase speed.
show_progressbar : bool, optional, default False
Whether to show a progressbar.
return_names : bool, optional, default True
Whether to return the item names, or just the distances.
Returns
-------
sim : list of tuples.
For each item in the input the num most similar items are returned
in the form of (NAME, DISTANCE) tuples. If return_names is set to
false, only the distances are returned.
"""
vectors = np.array(vectors)
if np.ndim(vectors) == 1:
vectors = vectors[None, :]
result = []
result = self._threshold_batch(vectors,
batch_size,
threshold,
show_progressbar,
return_names)
return list(result)
def _threshold_batch(self,
vectors,
batch_size,
threshold,
show_progressbar,
return_names):
"""Batched cosine distance."""
vectors = self.normalize(vectors)
# Single transpose, makes things faster.
reference_transposed = self.norm_vectors.T
for i in tqdm(range(0, len(vectors), batch_size),
disable=not show_progressbar):
distances = vectors[i: i+batch_size].dot(reference_transposed)
# For safety we clip
distances = np.clip(distances, a_min=.0, a_max=1.0)
for lidx, dists in enumerate(distances):
indices = np.flatnonzero(dists >= threshold)
sorted_indices = indices[np.argsort(-dists[indices])]
if return_names:
yield [(self.indices[d], dists[d])
for d in sorted_indices]
else:
yield list(dists[sorted_indices])
def _batch(self,
vectors,
batch_size,
num,
show_progressbar,
return_names):
"""Batched cosine distance."""
vectors = self.normalize(vectors)
# Single transpose, makes things faster.
reference_transposed = self.norm_vectors.T
for i in tqdm(range(0, len(vectors), batch_size),
disable=not show_progressbar):
distances = vectors[i: i+batch_size].dot(reference_transposed)
# For safety we clip
distances = np.clip(distances, a_min=.0, a_max=1.0)
if num == 1:
sorted_indices = np.argmax(distances, 1)[:, None]
else:
sorted_indices = np.argpartition(-distances, kth=num, axis=1)
sorted_indices = sorted_indices[:, :num]
for lidx, indices in enumerate(sorted_indices):
dists = distances[lidx, indices]
if return_names:
dindex = np.argsort(-dists)
yield [(self.indices[indices[d]], dists[d])
for d in dindex]
else:
yield list(-1 * np.sort(-dists))
@staticmethod
def vector_similarity(self, vector, items):
"""Compute the similarity between a vector and a set of items."""
vector = self.normalize(vector)
items_vec = np.stack([self.norm_vectors[self.items[x]] for x in items])
return vector.dot(items_vec.T)
def similarity(self, i1, i2):
"""
Compute the similarity between two sets of items.
Parameters
----------
i1 : object
The first set of items.
i2 : object
The second set of item.
Returns
-------
sim : array of floats
An array of similarity scores between 1 and 0.
"""
try:
if i1 in self.items:
i1 = [i1]
except TypeError:
pass
try:
if i2 in self.items:
i2 = [i2]
except TypeError:
pass
i1_vec = np.stack([self.norm_vectors[self.items[x]] for x in i1])
i2_vec = np.stack([self.norm_vectors[self.items[x]] for x in i2])
return i1_vec.dot(i2_vec.T)
def prune(self, wordlist):
"""
Prune the current reach instance by removing items.
Parameters
----------
wordlist : list of str
A list of words to keep. Note that this wordlist need not include
all words in the Reach instance. Any words which are in the
wordlist, but not in the reach instance are ignored.
"""
# Remove duplicates
wordlist = set(wordlist).intersection(set(self.items.keys()))
indices = [self.items[w] for w in wordlist if w in self.items]
if self.unk_index is not None and self.unk_index not in indices:
raise ValueError("Your unknown item is not in your list of items. "
"Set it to None before pruning, or pass your "
"unknown item.")
self.vectors = self.vectors[indices]
self.norm_vectors = self.norm_vectors[indices]
self.items = {w: idx for idx, w in enumerate(wordlist)}
self.indices = {v: k for k, v in self.items.items()}
if self.unk_index is not None:
self.unk_index = self.items[wordlist[self.unk_index]]
def save(self, path, write_header=True):
"""
Save the current vector space in word2vec format.
Parameters
----------
path : str
The path to save the vector file to.
write_header : bool, optional, default True
Whether to write a word2vec-style header as the first line of the
file
"""
with open(path, 'w') as f:
if write_header:
f.write(u"{0} {1}\n".format(str(self.vectors.shape[0]),
str(self.vectors.shape[1])))
for i in range(len(self.items)):
w = self.indices[i]
vec = self.vectors[i]
f.write(u"{0} {1}\n".format(w,
" ".join([str(x) for x in vec])))
def save_fast_format(self, filename):
"""
Save a reach instance in a fast format.
The reach fast format stores the words and vectors of a Reach instance
separately in a JSON and numpy format, respectively.
Parameters
----------
filename : str
The prefix to add to the saved filename. Note that this is not the
real filename under which these items are stored.
The words and unk_index are stored under "{filename}_words.json",
and the numpy matrix is saved under "{filename}_vectors.npy".
"""
items, _ = zip(*sorted(self.items.items(), key=lambda x: x[1]))
items = {"items": items,
"unk_index": self.unk_index,
"name": self.name}
json.dump(items, open("{}_items.json".format(filename), 'w'))
np.save(open("{}_vectors.npy".format(filename), 'wb'), self.vectors)
@staticmethod
def load_fast_format(filename):
"""
Load a reach instance in fast format.
As described above, the fast format stores the words and vectors of the
Reach instance separately, and is drastically faster than loading from
.txt files.
Parameters
----------
filename : str
The filename prefix from which to load. Note that this is not a
real filepath as such, but a shared prefix for both files.
In order for this to work, both {filename}_words.json and
{filename}_vectors.npy should be present.
"""
words, unk_index, name, vectors = Reach._load_fast(filename)
return Reach(vectors, words, unk_index=unk_index, name=name)
@staticmethod
def _load_fast(filename):
"""Sub for fast loader."""
it = json.load(open("{}_items.json".format(filename)))
words, unk_index, name = it["items"], it["unk_index"], it["name"]
vectors = np.load(open("{}_vectors.npy".format(filename), 'rb'))
return words, unk_index, name, vectors
|
stephantul/reach
|
reach/reach.py
|
Reach.vector_similarity
|
python
|
def vector_similarity(self, vector, items):
vector = self.normalize(vector)
items_vec = np.stack([self.norm_vectors[self.items[x]] for x in items])
return vector.dot(items_vec.T)
|
Compute the similarity between a vector and a set of items.
|
train
|
https://github.com/stephantul/reach/blob/e5ed0cc895d17429e797c6d7dd57bce82ff00d5d/reach/reach.py#L612-L616
|
[
"def normalize(vectors):\n \"\"\"\n Normalize a matrix of row vectors to unit length.\n\n Contains a shortcut if there are no zero vectors in the matrix.\n If there are zero vectors, we do some indexing tricks to avoid\n dividing by 0.\n\n Parameters\n ----------\n vectors : np.array\n The vectors to normalize.\n\n Returns\n -------\n vectors : np.array\n The input vectors, normalized to unit length.\n\n \"\"\"\n if np.ndim(vectors) == 1:\n norm = np.linalg.norm(vectors)\n if norm == 0:\n return np.zeros_like(vectors)\n return vectors / norm\n\n norm = np.linalg.norm(vectors, axis=1)\n\n if np.any(norm == 0):\n\n nonzero = norm > 0\n\n result = np.zeros_like(vectors)\n\n n = norm[nonzero]\n p = vectors[nonzero]\n result[nonzero] = p / n[:, None]\n\n return result\n else:\n return vectors / norm[:, None]\n"
] |
class Reach(object):
"""
Work with vector representations of items.
Supports functions for calculating fast batched similarity
between items or composite representations of items.
Parameters
----------
vectors : numpy array
The vector space.
items : list
A list of items. Length must be equal to the number of vectors, and
aligned with the vectors.
name : string, optional
A string giving the name of the current reach. Only useful if you
have multiple spaces and want to keep track of them.
Attributes
----------
items : dict
A mapping from items to ids.
indices : dict
A mapping from ids to items.
vectors : numpy array
The array representing the vector space.
norm_vectors : numpy array
A normalized version of the vector space.
unk_index : int
The integer index of your unknown glyph. This glyph will be inserted
into your BoW space whenever an unknown item is encountered.
size : int
The dimensionality of the vector space.
name : string
The name of the Reach instance.
"""
def __init__(self, vectors, items, name="", unk_index=None):
"""Initialize a Reach instance with an array and list of items."""
if len(items) != len(vectors):
raise ValueError("Your vector space and list of items are not "
"the same length: "
"{} != {}".format(len(vectors), len(items)))
if isinstance(items, dict) or isinstance(items, set):
raise ValueError("Your item list is a set or dict, and might not "
"retain order in the conversion to internal look"
"-ups. Please convert it to list and check the "
"order.")
self.items = {w: idx for idx, w in enumerate(items)}
self.indices = {v: k for k, v in self.items.items()}
self.vectors = np.asarray(vectors)
self.norm_vectors = self.normalize(self.vectors)
self.unk_index = unk_index
self.size = self.vectors.shape[1]
self.name = name
@staticmethod
def load(pathtovector,
wordlist=(),
num_to_load=None,
truncate_embeddings=None,
unk_word=None,
sep=" "):
r"""
Read a file in word2vec .txt format.
The load function will raise a ValueError when trying to load items
which do not conform to line lengths.
Parameters
----------
pathtovector : string
The path to the vector file.
header : bool
Whether the vector file has a header of the type
(NUMBER OF ITEMS, SIZE OF VECTOR).
wordlist : iterable, optional, default ()
A list of words you want loaded from the vector file. If this is
None (default), all words will be loaded.
num_to_load : int, optional, default None
The number of items to load from the file. Because loading can take
some time, it is sometimes useful to onlyl load the first n items
from a vector file for quick inspection.
truncate_embeddings : int, optional, default None
If this value is not None, the vectors in the vector space will
be truncated to the number of dimensions indicated by this value.
unk_word : object
The object to treat as UNK in your vector space. If this is not
in your items dictionary after loading, we add it with a zero
vector.
Returns
-------
r : Reach
An initialized Reach instance.
"""
vectors, items = Reach._load(pathtovector,
wordlist,
num_to_load,
truncate_embeddings,
sep)
if unk_word is not None:
if unk_word not in set(items):
unk_vec = np.zeros((1, vectors.shape[1]))
vectors = np.concatenate([unk_vec, vectors], 0)
items = [unk_word] + items
unk_index = 0
else:
unk_index = items.index(unk_word)
else:
unk_index = None
return Reach(vectors,
items,
name=os.path.split(pathtovector)[-1],
unk_index=unk_index)
@staticmethod
def _load(pathtovector,
wordlist,
num_to_load=None,
truncate_embeddings=None,
sep=" "):
"""Load a matrix and wordlist from a .vec file."""
vectors = []
addedwords = set()
words = []
try:
wordlist = set(wordlist)
except ValueError:
wordlist = set()
logger.info("Loading {0}".format(pathtovector))
firstline = open(pathtovector).readline().strip()
try:
num, size = firstline.split(sep)
num, size = int(num), int(size)
logger.info("Vector space: {} by {}".format(num, size))
header = True
except ValueError:
size = len(firstline.split(sep)) - 1
logger.info("Vector space: {} dim, # items unknown".format(size))
word, rest = firstline.split(sep, 1)
# If the first line is correctly parseable, set header to False.
header = False
if truncate_embeddings is None or truncate_embeddings == 0:
truncate_embeddings = size
for idx, line in enumerate(open(pathtovector, encoding='utf-8')):
if header and idx == 0:
continue
word, rest = line.rstrip(" \n").split(sep, 1)
if wordlist and word not in wordlist:
continue
if word in addedwords:
raise ValueError("Duplicate: {} on line {} was in the "
"vector space twice".format(word, idx))
if len(rest.split(sep)) != size:
raise ValueError("Incorrect input at index {}, size "
"is {}, expected "
"{}".format(idx+1,
len(rest.split(sep)), size))
words.append(word)
addedwords.add(word)
vectors.append(np.fromstring(rest, sep=sep)[:truncate_embeddings])
if num_to_load is not None and len(addedwords) >= num_to_load:
break
vectors = np.array(vectors).astype(np.float32)
logger.info("Loading finished")
if wordlist:
diff = wordlist - addedwords
if diff:
logger.info("Not all items from your wordlist were in your "
"vector space: {}.".format(diff))
return vectors, words
def __getitem__(self, item):
"""Get the vector for a single item."""
return self.vectors[self.items[item]]
def vectorize(self, tokens, remove_oov=False, norm=False):
"""
Vectorize a sentence by replacing all items with their vectors.
Parameters
----------
tokens : object or list of objects
The tokens to vectorize.
remove_oov : bool, optional, default False
Whether to remove OOV items. If False, OOV items are replaced by
the UNK glyph. If this is True, the returned sequence might
have a different length than the original sequence.
norm : bool, optional, default False
Whether to return the unit vectors, or the regular vectors.
Returns
-------
s : numpy array
An M * N matrix, where every item has been replaced by
its vector. OOV items are either removed, or replaced
by the value of the UNK glyph.
"""
if not tokens:
raise ValueError("You supplied an empty list.")
index = list(self.bow(tokens, remove_oov=remove_oov))
if not index:
raise ValueError("You supplied a list with only OOV tokens: {}, "
"which then got removed. Set remove_oov to False,"
" or filter your sentences to remove any in which"
" all items are OOV.")
if norm:
return np.stack([self.norm_vectors[x] for x in index])
else:
return np.stack([self.vectors[x] for x in index])
def bow(self, tokens, remove_oov=False):
"""
Create a bow representation of a list of tokens.
Parameters
----------
tokens : list.
The list of items to change into a bag of words representation.
remove_oov : bool.
Whether to remove OOV items from the input.
If this is True, the length of the returned BOW representation
might not be the length of the original representation.
Returns
-------
bow : generator
A BOW representation of the list of items.
"""
if remove_oov:
tokens = [x for x in tokens if x in self.items]
for t in tokens:
try:
yield self.items[t]
except KeyError:
if self.unk_index is None:
raise ValueError("You supplied OOV items but didn't "
"provide the index of the replacement "
"glyph. Either set remove_oov to True, "
"or set unk_index to the index of the "
"item which replaces any OOV items.")
yield self.unk_index
def transform(self, corpus, remove_oov=False, norm=False):
"""
Transform a corpus by repeated calls to vectorize, defined above.
Parameters
----------
corpus : A list of strings, list of list of strings.
Represents a corpus as a list of sentences, where sentences
can either be strings or lists of tokens.
remove_oov : bool, optional, default False
If True, removes OOV items from the input before vectorization.
Returns
-------
c : list
A list of numpy arrays, where each array represents the transformed
sentence in the original list. The list is guaranteed to be the
same length as the input list, but the arrays in the list may be
of different lengths, depending on whether remove_oov is True.
"""
return [self.vectorize(s, remove_oov=remove_oov, norm=norm)
for s in corpus]
def most_similar(self,
items,
num=10,
batch_size=100,
show_progressbar=False,
return_names=True):
"""
Return the num most similar items to a given list of items.
Parameters
----------
items : list of objects or a single object.
The items to get the most similar items to.
num : int, optional, default 10
The number of most similar items to retrieve.
batch_size : int, optional, default 100.
The batch size to use. 100 is a good default option. Increasing
the batch size may increase the speed.
show_progressbar : bool, optional, default False
Whether to show a progressbar.
return_names : bool, optional, default True
Whether to return the item names, or just the distances.
Returns
-------
sim : array
For each items in the input the num most similar items are returned
in the form of (NAME, DISTANCE) tuples. If return_names is false,
the returned list just contains distances.
"""
# This line allows users to input single items.
# We used to rely on string identities, but we now also allow
# anything hashable as keys.
# Might fail if a list of passed items is also in the vocabulary.
# but I can't think of cases when this would happen, and what
# user expectations are.
try:
if items in self.items:
items = [items]
except TypeError:
pass
x = np.stack([self.norm_vectors[self.items[x]] for x in items])
result = self._batch(x,
batch_size,
num+1,
show_progressbar,
return_names)
# list call consumes the generator.
return [x[1:] for x in result]
def threshold(self,
items,
threshold=.5,
batch_size=100,
show_progressbar=False,
return_names=True):
"""
Return all items whose similarity is higher than threshold.
Parameters
----------
items : list of objects or a single object.
The items to get the most similar items to.
threshold : float, optional, default .5
The radius within which to retrieve items.
batch_size : int, optional, default 100.
The batch size to use. 100 is a good default option. Increasing
the batch size may increase the speed.
show_progressbar : bool, optional, default False
Whether to show a progressbar.
return_names : bool, optional, default True
Whether to return the item names, or just the distances.
Returns
-------
sim : array
For each items in the input the num most similar items are returned
in the form of (NAME, DISTANCE) tuples. If return_names is false,
the returned list just contains distances.
"""
# This line allows users to input single items.
# We used to rely on string identities, but we now also allow
# anything hashable as keys.
# Might fail if a list of passed items is also in the vocabulary.
# but I can't think of cases when this would happen, and what
# user expectations are.
try:
if items in self.items:
items = [items]
except TypeError:
pass
x = np.stack([self.norm_vectors[self.items[x]] for x in items])
result = self._threshold_batch(x,
batch_size,
threshold,
show_progressbar,
return_names)
# list call consumes the generator.
return [x[1:] for x in result]
def nearest_neighbor(self,
vectors,
num=10,
batch_size=100,
show_progressbar=False,
return_names=True):
"""
Find the nearest neighbors to some arbitrary vector.
This function is meant to be used in composition operations. The
most_similar function can only handle items that are in vocab, and
looks up their vector through a dictionary. Compositions, e.g.
"King - man + woman" are necessarily not in the vocabulary.
Parameters
----------
vectors : list of arrays or numpy array
The vectors to find the nearest neighbors to.
num : int, optional, default 10
The number of most similar items to retrieve.
batch_size : int, optional, default 100.
The batch size to use. 100 is a good default option. Increasing
the batch size may increase speed.
show_progressbar : bool, optional, default False
Whether to show a progressbar.
return_names : bool, optional, default True
Whether to return the item names, or just the distances.
Returns
-------
sim : list of tuples.
For each item in the input the num most similar items are returned
in the form of (NAME, DISTANCE) tuples. If return_names is set to
false, only the distances are returned.
"""
vectors = np.array(vectors)
if np.ndim(vectors) == 1:
vectors = vectors[None, :]
result = []
result = self._batch(vectors,
batch_size,
num+1,
show_progressbar,
return_names)
return list(result)
def nearest_neighbor_threshold(self,
vectors,
threshold=.5,
batch_size=100,
show_progressbar=False,
return_names=True):
"""
Find the nearest neighbors to some arbitrary vector.
This function is meant to be used in composition operations. The
most_similar function can only handle items that are in vocab, and
looks up their vector through a dictionary. Compositions, e.g.
"King - man + woman" are necessarily not in the vocabulary.
Parameters
----------
vectors : list of arrays or numpy array
The vectors to find the nearest neighbors to.
threshold : float, optional, default .5
The threshold within to retrieve items.
batch_size : int, optional, default 100.
The batch size to use. 100 is a good default option. Increasing
the batch size may increase speed.
show_progressbar : bool, optional, default False
Whether to show a progressbar.
return_names : bool, optional, default True
Whether to return the item names, or just the distances.
Returns
-------
sim : list of tuples.
For each item in the input the num most similar items are returned
in the form of (NAME, DISTANCE) tuples. If return_names is set to
false, only the distances are returned.
"""
vectors = np.array(vectors)
if np.ndim(vectors) == 1:
vectors = vectors[None, :]
result = []
result = self._threshold_batch(vectors,
batch_size,
threshold,
show_progressbar,
return_names)
return list(result)
def _threshold_batch(self,
vectors,
batch_size,
threshold,
show_progressbar,
return_names):
"""Batched cosine distance."""
vectors = self.normalize(vectors)
# Single transpose, makes things faster.
reference_transposed = self.norm_vectors.T
for i in tqdm(range(0, len(vectors), batch_size),
disable=not show_progressbar):
distances = vectors[i: i+batch_size].dot(reference_transposed)
# For safety we clip
distances = np.clip(distances, a_min=.0, a_max=1.0)
for lidx, dists in enumerate(distances):
indices = np.flatnonzero(dists >= threshold)
sorted_indices = indices[np.argsort(-dists[indices])]
if return_names:
yield [(self.indices[d], dists[d])
for d in sorted_indices]
else:
yield list(dists[sorted_indices])
def _batch(self,
vectors,
batch_size,
num,
show_progressbar,
return_names):
"""Batched cosine distance."""
vectors = self.normalize(vectors)
# Single transpose, makes things faster.
reference_transposed = self.norm_vectors.T
for i in tqdm(range(0, len(vectors), batch_size),
disable=not show_progressbar):
distances = vectors[i: i+batch_size].dot(reference_transposed)
# For safety we clip
distances = np.clip(distances, a_min=.0, a_max=1.0)
if num == 1:
sorted_indices = np.argmax(distances, 1)[:, None]
else:
sorted_indices = np.argpartition(-distances, kth=num, axis=1)
sorted_indices = sorted_indices[:, :num]
for lidx, indices in enumerate(sorted_indices):
dists = distances[lidx, indices]
if return_names:
dindex = np.argsort(-dists)
yield [(self.indices[indices[d]], dists[d])
for d in dindex]
else:
yield list(-1 * np.sort(-dists))
@staticmethod
def normalize(vectors):
"""
Normalize a matrix of row vectors to unit length.
Contains a shortcut if there are no zero vectors in the matrix.
If there are zero vectors, we do some indexing tricks to avoid
dividing by 0.
Parameters
----------
vectors : np.array
The vectors to normalize.
Returns
-------
vectors : np.array
The input vectors, normalized to unit length.
"""
if np.ndim(vectors) == 1:
norm = np.linalg.norm(vectors)
if norm == 0:
return np.zeros_like(vectors)
return vectors / norm
norm = np.linalg.norm(vectors, axis=1)
if np.any(norm == 0):
nonzero = norm > 0
result = np.zeros_like(vectors)
n = norm[nonzero]
p = vectors[nonzero]
result[nonzero] = p / n[:, None]
return result
else:
return vectors / norm[:, None]
def similarity(self, i1, i2):
"""
Compute the similarity between two sets of items.
Parameters
----------
i1 : object
The first set of items.
i2 : object
The second set of item.
Returns
-------
sim : array of floats
An array of similarity scores between 1 and 0.
"""
try:
if i1 in self.items:
i1 = [i1]
except TypeError:
pass
try:
if i2 in self.items:
i2 = [i2]
except TypeError:
pass
i1_vec = np.stack([self.norm_vectors[self.items[x]] for x in i1])
i2_vec = np.stack([self.norm_vectors[self.items[x]] for x in i2])
return i1_vec.dot(i2_vec.T)
def prune(self, wordlist):
"""
Prune the current reach instance by removing items.
Parameters
----------
wordlist : list of str
A list of words to keep. Note that this wordlist need not include
all words in the Reach instance. Any words which are in the
wordlist, but not in the reach instance are ignored.
"""
# Remove duplicates
wordlist = set(wordlist).intersection(set(self.items.keys()))
indices = [self.items[w] for w in wordlist if w in self.items]
if self.unk_index is not None and self.unk_index not in indices:
raise ValueError("Your unknown item is not in your list of items. "
"Set it to None before pruning, or pass your "
"unknown item.")
self.vectors = self.vectors[indices]
self.norm_vectors = self.norm_vectors[indices]
self.items = {w: idx for idx, w in enumerate(wordlist)}
self.indices = {v: k for k, v in self.items.items()}
if self.unk_index is not None:
self.unk_index = self.items[wordlist[self.unk_index]]
def save(self, path, write_header=True):
"""
Save the current vector space in word2vec format.
Parameters
----------
path : str
The path to save the vector file to.
write_header : bool, optional, default True
Whether to write a word2vec-style header as the first line of the
file
"""
with open(path, 'w') as f:
if write_header:
f.write(u"{0} {1}\n".format(str(self.vectors.shape[0]),
str(self.vectors.shape[1])))
for i in range(len(self.items)):
w = self.indices[i]
vec = self.vectors[i]
f.write(u"{0} {1}\n".format(w,
" ".join([str(x) for x in vec])))
def save_fast_format(self, filename):
"""
Save a reach instance in a fast format.
The reach fast format stores the words and vectors of a Reach instance
separately in a JSON and numpy format, respectively.
Parameters
----------
filename : str
The prefix to add to the saved filename. Note that this is not the
real filename under which these items are stored.
The words and unk_index are stored under "{filename}_words.json",
and the numpy matrix is saved under "{filename}_vectors.npy".
"""
items, _ = zip(*sorted(self.items.items(), key=lambda x: x[1]))
items = {"items": items,
"unk_index": self.unk_index,
"name": self.name}
json.dump(items, open("{}_items.json".format(filename), 'w'))
np.save(open("{}_vectors.npy".format(filename), 'wb'), self.vectors)
@staticmethod
def load_fast_format(filename):
"""
Load a reach instance in fast format.
As described above, the fast format stores the words and vectors of the
Reach instance separately, and is drastically faster than loading from
.txt files.
Parameters
----------
filename : str
The filename prefix from which to load. Note that this is not a
real filepath as such, but a shared prefix for both files.
In order for this to work, both {filename}_words.json and
{filename}_vectors.npy should be present.
"""
words, unk_index, name, vectors = Reach._load_fast(filename)
return Reach(vectors, words, unk_index=unk_index, name=name)
@staticmethod
def _load_fast(filename):
"""Sub for fast loader."""
it = json.load(open("{}_items.json".format(filename)))
words, unk_index, name = it["items"], it["unk_index"], it["name"]
vectors = np.load(open("{}_vectors.npy".format(filename), 'rb'))
return words, unk_index, name, vectors
|
stephantul/reach
|
reach/reach.py
|
Reach.similarity
|
python
|
def similarity(self, i1, i2):
try:
if i1 in self.items:
i1 = [i1]
except TypeError:
pass
try:
if i2 in self.items:
i2 = [i2]
except TypeError:
pass
i1_vec = np.stack([self.norm_vectors[self.items[x]] for x in i1])
i2_vec = np.stack([self.norm_vectors[self.items[x]] for x in i2])
return i1_vec.dot(i2_vec.T)
|
Compute the similarity between two sets of items.
Parameters
----------
i1 : object
The first set of items.
i2 : object
The second set of item.
Returns
-------
sim : array of floats
An array of similarity scores between 1 and 0.
|
train
|
https://github.com/stephantul/reach/blob/e5ed0cc895d17429e797c6d7dd57bce82ff00d5d/reach/reach.py#L618-L647
| null |
class Reach(object):
"""
Work with vector representations of items.
Supports functions for calculating fast batched similarity
between items or composite representations of items.
Parameters
----------
vectors : numpy array
The vector space.
items : list
A list of items. Length must be equal to the number of vectors, and
aligned with the vectors.
name : string, optional
A string giving the name of the current reach. Only useful if you
have multiple spaces and want to keep track of them.
Attributes
----------
items : dict
A mapping from items to ids.
indices : dict
A mapping from ids to items.
vectors : numpy array
The array representing the vector space.
norm_vectors : numpy array
A normalized version of the vector space.
unk_index : int
The integer index of your unknown glyph. This glyph will be inserted
into your BoW space whenever an unknown item is encountered.
size : int
The dimensionality of the vector space.
name : string
The name of the Reach instance.
"""
def __init__(self, vectors, items, name="", unk_index=None):
"""Initialize a Reach instance with an array and list of items."""
if len(items) != len(vectors):
raise ValueError("Your vector space and list of items are not "
"the same length: "
"{} != {}".format(len(vectors), len(items)))
if isinstance(items, dict) or isinstance(items, set):
raise ValueError("Your item list is a set or dict, and might not "
"retain order in the conversion to internal look"
"-ups. Please convert it to list and check the "
"order.")
self.items = {w: idx for idx, w in enumerate(items)}
self.indices = {v: k for k, v in self.items.items()}
self.vectors = np.asarray(vectors)
self.norm_vectors = self.normalize(self.vectors)
self.unk_index = unk_index
self.size = self.vectors.shape[1]
self.name = name
@staticmethod
def load(pathtovector,
wordlist=(),
num_to_load=None,
truncate_embeddings=None,
unk_word=None,
sep=" "):
r"""
Read a file in word2vec .txt format.
The load function will raise a ValueError when trying to load items
which do not conform to line lengths.
Parameters
----------
pathtovector : string
The path to the vector file.
header : bool
Whether the vector file has a header of the type
(NUMBER OF ITEMS, SIZE OF VECTOR).
wordlist : iterable, optional, default ()
A list of words you want loaded from the vector file. If this is
None (default), all words will be loaded.
num_to_load : int, optional, default None
The number of items to load from the file. Because loading can take
some time, it is sometimes useful to onlyl load the first n items
from a vector file for quick inspection.
truncate_embeddings : int, optional, default None
If this value is not None, the vectors in the vector space will
be truncated to the number of dimensions indicated by this value.
unk_word : object
The object to treat as UNK in your vector space. If this is not
in your items dictionary after loading, we add it with a zero
vector.
Returns
-------
r : Reach
An initialized Reach instance.
"""
vectors, items = Reach._load(pathtovector,
wordlist,
num_to_load,
truncate_embeddings,
sep)
if unk_word is not None:
if unk_word not in set(items):
unk_vec = np.zeros((1, vectors.shape[1]))
vectors = np.concatenate([unk_vec, vectors], 0)
items = [unk_word] + items
unk_index = 0
else:
unk_index = items.index(unk_word)
else:
unk_index = None
return Reach(vectors,
items,
name=os.path.split(pathtovector)[-1],
unk_index=unk_index)
@staticmethod
def _load(pathtovector,
wordlist,
num_to_load=None,
truncate_embeddings=None,
sep=" "):
"""Load a matrix and wordlist from a .vec file."""
vectors = []
addedwords = set()
words = []
try:
wordlist = set(wordlist)
except ValueError:
wordlist = set()
logger.info("Loading {0}".format(pathtovector))
firstline = open(pathtovector).readline().strip()
try:
num, size = firstline.split(sep)
num, size = int(num), int(size)
logger.info("Vector space: {} by {}".format(num, size))
header = True
except ValueError:
size = len(firstline.split(sep)) - 1
logger.info("Vector space: {} dim, # items unknown".format(size))
word, rest = firstline.split(sep, 1)
# If the first line is correctly parseable, set header to False.
header = False
if truncate_embeddings is None or truncate_embeddings == 0:
truncate_embeddings = size
for idx, line in enumerate(open(pathtovector, encoding='utf-8')):
if header and idx == 0:
continue
word, rest = line.rstrip(" \n").split(sep, 1)
if wordlist and word not in wordlist:
continue
if word in addedwords:
raise ValueError("Duplicate: {} on line {} was in the "
"vector space twice".format(word, idx))
if len(rest.split(sep)) != size:
raise ValueError("Incorrect input at index {}, size "
"is {}, expected "
"{}".format(idx+1,
len(rest.split(sep)), size))
words.append(word)
addedwords.add(word)
vectors.append(np.fromstring(rest, sep=sep)[:truncate_embeddings])
if num_to_load is not None and len(addedwords) >= num_to_load:
break
vectors = np.array(vectors).astype(np.float32)
logger.info("Loading finished")
if wordlist:
diff = wordlist - addedwords
if diff:
logger.info("Not all items from your wordlist were in your "
"vector space: {}.".format(diff))
return vectors, words
def __getitem__(self, item):
"""Get the vector for a single item."""
return self.vectors[self.items[item]]
def vectorize(self, tokens, remove_oov=False, norm=False):
"""
Vectorize a sentence by replacing all items with their vectors.
Parameters
----------
tokens : object or list of objects
The tokens to vectorize.
remove_oov : bool, optional, default False
Whether to remove OOV items. If False, OOV items are replaced by
the UNK glyph. If this is True, the returned sequence might
have a different length than the original sequence.
norm : bool, optional, default False
Whether to return the unit vectors, or the regular vectors.
Returns
-------
s : numpy array
An M * N matrix, where every item has been replaced by
its vector. OOV items are either removed, or replaced
by the value of the UNK glyph.
"""
if not tokens:
raise ValueError("You supplied an empty list.")
index = list(self.bow(tokens, remove_oov=remove_oov))
if not index:
raise ValueError("You supplied a list with only OOV tokens: {}, "
"which then got removed. Set remove_oov to False,"
" or filter your sentences to remove any in which"
" all items are OOV.")
if norm:
return np.stack([self.norm_vectors[x] for x in index])
else:
return np.stack([self.vectors[x] for x in index])
def bow(self, tokens, remove_oov=False):
"""
Create a bow representation of a list of tokens.
Parameters
----------
tokens : list.
The list of items to change into a bag of words representation.
remove_oov : bool.
Whether to remove OOV items from the input.
If this is True, the length of the returned BOW representation
might not be the length of the original representation.
Returns
-------
bow : generator
A BOW representation of the list of items.
"""
if remove_oov:
tokens = [x for x in tokens if x in self.items]
for t in tokens:
try:
yield self.items[t]
except KeyError:
if self.unk_index is None:
raise ValueError("You supplied OOV items but didn't "
"provide the index of the replacement "
"glyph. Either set remove_oov to True, "
"or set unk_index to the index of the "
"item which replaces any OOV items.")
yield self.unk_index
def transform(self, corpus, remove_oov=False, norm=False):
"""
Transform a corpus by repeated calls to vectorize, defined above.
Parameters
----------
corpus : A list of strings, list of list of strings.
Represents a corpus as a list of sentences, where sentences
can either be strings or lists of tokens.
remove_oov : bool, optional, default False
If True, removes OOV items from the input before vectorization.
Returns
-------
c : list
A list of numpy arrays, where each array represents the transformed
sentence in the original list. The list is guaranteed to be the
same length as the input list, but the arrays in the list may be
of different lengths, depending on whether remove_oov is True.
"""
return [self.vectorize(s, remove_oov=remove_oov, norm=norm)
for s in corpus]
def most_similar(self,
items,
num=10,
batch_size=100,
show_progressbar=False,
return_names=True):
"""
Return the num most similar items to a given list of items.
Parameters
----------
items : list of objects or a single object.
The items to get the most similar items to.
num : int, optional, default 10
The number of most similar items to retrieve.
batch_size : int, optional, default 100.
The batch size to use. 100 is a good default option. Increasing
the batch size may increase the speed.
show_progressbar : bool, optional, default False
Whether to show a progressbar.
return_names : bool, optional, default True
Whether to return the item names, or just the distances.
Returns
-------
sim : array
For each items in the input the num most similar items are returned
in the form of (NAME, DISTANCE) tuples. If return_names is false,
the returned list just contains distances.
"""
# This line allows users to input single items.
# We used to rely on string identities, but we now also allow
# anything hashable as keys.
# Might fail if a list of passed items is also in the vocabulary.
# but I can't think of cases when this would happen, and what
# user expectations are.
try:
if items in self.items:
items = [items]
except TypeError:
pass
x = np.stack([self.norm_vectors[self.items[x]] for x in items])
result = self._batch(x,
batch_size,
num+1,
show_progressbar,
return_names)
# list call consumes the generator.
return [x[1:] for x in result]
def threshold(self,
items,
threshold=.5,
batch_size=100,
show_progressbar=False,
return_names=True):
"""
Return all items whose similarity is higher than threshold.
Parameters
----------
items : list of objects or a single object.
The items to get the most similar items to.
threshold : float, optional, default .5
The radius within which to retrieve items.
batch_size : int, optional, default 100.
The batch size to use. 100 is a good default option. Increasing
the batch size may increase the speed.
show_progressbar : bool, optional, default False
Whether to show a progressbar.
return_names : bool, optional, default True
Whether to return the item names, or just the distances.
Returns
-------
sim : array
For each items in the input the num most similar items are returned
in the form of (NAME, DISTANCE) tuples. If return_names is false,
the returned list just contains distances.
"""
# This line allows users to input single items.
# We used to rely on string identities, but we now also allow
# anything hashable as keys.
# Might fail if a list of passed items is also in the vocabulary.
# but I can't think of cases when this would happen, and what
# user expectations are.
try:
if items in self.items:
items = [items]
except TypeError:
pass
x = np.stack([self.norm_vectors[self.items[x]] for x in items])
result = self._threshold_batch(x,
batch_size,
threshold,
show_progressbar,
return_names)
# list call consumes the generator.
return [x[1:] for x in result]
def nearest_neighbor(self,
vectors,
num=10,
batch_size=100,
show_progressbar=False,
return_names=True):
"""
Find the nearest neighbors to some arbitrary vector.
This function is meant to be used in composition operations. The
most_similar function can only handle items that are in vocab, and
looks up their vector through a dictionary. Compositions, e.g.
"King - man + woman" are necessarily not in the vocabulary.
Parameters
----------
vectors : list of arrays or numpy array
The vectors to find the nearest neighbors to.
num : int, optional, default 10
The number of most similar items to retrieve.
batch_size : int, optional, default 100.
The batch size to use. 100 is a good default option. Increasing
the batch size may increase speed.
show_progressbar : bool, optional, default False
Whether to show a progressbar.
return_names : bool, optional, default True
Whether to return the item names, or just the distances.
Returns
-------
sim : list of tuples.
For each item in the input the num most similar items are returned
in the form of (NAME, DISTANCE) tuples. If return_names is set to
false, only the distances are returned.
"""
vectors = np.array(vectors)
if np.ndim(vectors) == 1:
vectors = vectors[None, :]
result = []
result = self._batch(vectors,
batch_size,
num+1,
show_progressbar,
return_names)
return list(result)
def nearest_neighbor_threshold(self,
vectors,
threshold=.5,
batch_size=100,
show_progressbar=False,
return_names=True):
"""
Find the nearest neighbors to some arbitrary vector.
This function is meant to be used in composition operations. The
most_similar function can only handle items that are in vocab, and
looks up their vector through a dictionary. Compositions, e.g.
"King - man + woman" are necessarily not in the vocabulary.
Parameters
----------
vectors : list of arrays or numpy array
The vectors to find the nearest neighbors to.
threshold : float, optional, default .5
The threshold within to retrieve items.
batch_size : int, optional, default 100.
The batch size to use. 100 is a good default option. Increasing
the batch size may increase speed.
show_progressbar : bool, optional, default False
Whether to show a progressbar.
return_names : bool, optional, default True
Whether to return the item names, or just the distances.
Returns
-------
sim : list of tuples.
For each item in the input the num most similar items are returned
in the form of (NAME, DISTANCE) tuples. If return_names is set to
false, only the distances are returned.
"""
vectors = np.array(vectors)
if np.ndim(vectors) == 1:
vectors = vectors[None, :]
result = []
result = self._threshold_batch(vectors,
batch_size,
threshold,
show_progressbar,
return_names)
return list(result)
def _threshold_batch(self,
vectors,
batch_size,
threshold,
show_progressbar,
return_names):
"""Batched cosine distance."""
vectors = self.normalize(vectors)
# Single transpose, makes things faster.
reference_transposed = self.norm_vectors.T
for i in tqdm(range(0, len(vectors), batch_size),
disable=not show_progressbar):
distances = vectors[i: i+batch_size].dot(reference_transposed)
# For safety we clip
distances = np.clip(distances, a_min=.0, a_max=1.0)
for lidx, dists in enumerate(distances):
indices = np.flatnonzero(dists >= threshold)
sorted_indices = indices[np.argsort(-dists[indices])]
if return_names:
yield [(self.indices[d], dists[d])
for d in sorted_indices]
else:
yield list(dists[sorted_indices])
def _batch(self,
vectors,
batch_size,
num,
show_progressbar,
return_names):
"""Batched cosine distance."""
vectors = self.normalize(vectors)
# Single transpose, makes things faster.
reference_transposed = self.norm_vectors.T
for i in tqdm(range(0, len(vectors), batch_size),
disable=not show_progressbar):
distances = vectors[i: i+batch_size].dot(reference_transposed)
# For safety we clip
distances = np.clip(distances, a_min=.0, a_max=1.0)
if num == 1:
sorted_indices = np.argmax(distances, 1)[:, None]
else:
sorted_indices = np.argpartition(-distances, kth=num, axis=1)
sorted_indices = sorted_indices[:, :num]
for lidx, indices in enumerate(sorted_indices):
dists = distances[lidx, indices]
if return_names:
dindex = np.argsort(-dists)
yield [(self.indices[indices[d]], dists[d])
for d in dindex]
else:
yield list(-1 * np.sort(-dists))
@staticmethod
def normalize(vectors):
"""
Normalize a matrix of row vectors to unit length.
Contains a shortcut if there are no zero vectors in the matrix.
If there are zero vectors, we do some indexing tricks to avoid
dividing by 0.
Parameters
----------
vectors : np.array
The vectors to normalize.
Returns
-------
vectors : np.array
The input vectors, normalized to unit length.
"""
if np.ndim(vectors) == 1:
norm = np.linalg.norm(vectors)
if norm == 0:
return np.zeros_like(vectors)
return vectors / norm
norm = np.linalg.norm(vectors, axis=1)
if np.any(norm == 0):
nonzero = norm > 0
result = np.zeros_like(vectors)
n = norm[nonzero]
p = vectors[nonzero]
result[nonzero] = p / n[:, None]
return result
else:
return vectors / norm[:, None]
def vector_similarity(self, vector, items):
"""Compute the similarity between a vector and a set of items."""
vector = self.normalize(vector)
items_vec = np.stack([self.norm_vectors[self.items[x]] for x in items])
return vector.dot(items_vec.T)
def prune(self, wordlist):
"""
Prune the current reach instance by removing items.
Parameters
----------
wordlist : list of str
A list of words to keep. Note that this wordlist need not include
all words in the Reach instance. Any words which are in the
wordlist, but not in the reach instance are ignored.
"""
# Remove duplicates
wordlist = set(wordlist).intersection(set(self.items.keys()))
indices = [self.items[w] for w in wordlist if w in self.items]
if self.unk_index is not None and self.unk_index not in indices:
raise ValueError("Your unknown item is not in your list of items. "
"Set it to None before pruning, or pass your "
"unknown item.")
self.vectors = self.vectors[indices]
self.norm_vectors = self.norm_vectors[indices]
self.items = {w: idx for idx, w in enumerate(wordlist)}
self.indices = {v: k for k, v in self.items.items()}
if self.unk_index is not None:
self.unk_index = self.items[wordlist[self.unk_index]]
def save(self, path, write_header=True):
"""
Save the current vector space in word2vec format.
Parameters
----------
path : str
The path to save the vector file to.
write_header : bool, optional, default True
Whether to write a word2vec-style header as the first line of the
file
"""
with open(path, 'w') as f:
if write_header:
f.write(u"{0} {1}\n".format(str(self.vectors.shape[0]),
str(self.vectors.shape[1])))
for i in range(len(self.items)):
w = self.indices[i]
vec = self.vectors[i]
f.write(u"{0} {1}\n".format(w,
" ".join([str(x) for x in vec])))
def save_fast_format(self, filename):
"""
Save a reach instance in a fast format.
The reach fast format stores the words and vectors of a Reach instance
separately in a JSON and numpy format, respectively.
Parameters
----------
filename : str
The prefix to add to the saved filename. Note that this is not the
real filename under which these items are stored.
The words and unk_index are stored under "{filename}_words.json",
and the numpy matrix is saved under "{filename}_vectors.npy".
"""
items, _ = zip(*sorted(self.items.items(), key=lambda x: x[1]))
items = {"items": items,
"unk_index": self.unk_index,
"name": self.name}
json.dump(items, open("{}_items.json".format(filename), 'w'))
np.save(open("{}_vectors.npy".format(filename), 'wb'), self.vectors)
@staticmethod
def load_fast_format(filename):
"""
Load a reach instance in fast format.
As described above, the fast format stores the words and vectors of the
Reach instance separately, and is drastically faster than loading from
.txt files.
Parameters
----------
filename : str
The filename prefix from which to load. Note that this is not a
real filepath as such, but a shared prefix for both files.
In order for this to work, both {filename}_words.json and
{filename}_vectors.npy should be present.
"""
words, unk_index, name, vectors = Reach._load_fast(filename)
return Reach(vectors, words, unk_index=unk_index, name=name)
@staticmethod
def _load_fast(filename):
"""Sub for fast loader."""
it = json.load(open("{}_items.json".format(filename)))
words, unk_index, name = it["items"], it["unk_index"], it["name"]
vectors = np.load(open("{}_vectors.npy".format(filename), 'rb'))
return words, unk_index, name, vectors
|
stephantul/reach
|
reach/reach.py
|
Reach.prune
|
python
|
def prune(self, wordlist):
# Remove duplicates
wordlist = set(wordlist).intersection(set(self.items.keys()))
indices = [self.items[w] for w in wordlist if w in self.items]
if self.unk_index is not None and self.unk_index not in indices:
raise ValueError("Your unknown item is not in your list of items. "
"Set it to None before pruning, or pass your "
"unknown item.")
self.vectors = self.vectors[indices]
self.norm_vectors = self.norm_vectors[indices]
self.items = {w: idx for idx, w in enumerate(wordlist)}
self.indices = {v: k for k, v in self.items.items()}
if self.unk_index is not None:
self.unk_index = self.items[wordlist[self.unk_index]]
|
Prune the current reach instance by removing items.
Parameters
----------
wordlist : list of str
A list of words to keep. Note that this wordlist need not include
all words in the Reach instance. Any words which are in the
wordlist, but not in the reach instance are ignored.
|
train
|
https://github.com/stephantul/reach/blob/e5ed0cc895d17429e797c6d7dd57bce82ff00d5d/reach/reach.py#L649-L673
| null |
class Reach(object):
"""
Work with vector representations of items.
Supports functions for calculating fast batched similarity
between items or composite representations of items.
Parameters
----------
vectors : numpy array
The vector space.
items : list
A list of items. Length must be equal to the number of vectors, and
aligned with the vectors.
name : string, optional
A string giving the name of the current reach. Only useful if you
have multiple spaces and want to keep track of them.
Attributes
----------
items : dict
A mapping from items to ids.
indices : dict
A mapping from ids to items.
vectors : numpy array
The array representing the vector space.
norm_vectors : numpy array
A normalized version of the vector space.
unk_index : int
The integer index of your unknown glyph. This glyph will be inserted
into your BoW space whenever an unknown item is encountered.
size : int
The dimensionality of the vector space.
name : string
The name of the Reach instance.
"""
def __init__(self, vectors, items, name="", unk_index=None):
"""Initialize a Reach instance with an array and list of items."""
if len(items) != len(vectors):
raise ValueError("Your vector space and list of items are not "
"the same length: "
"{} != {}".format(len(vectors), len(items)))
if isinstance(items, dict) or isinstance(items, set):
raise ValueError("Your item list is a set or dict, and might not "
"retain order in the conversion to internal look"
"-ups. Please convert it to list and check the "
"order.")
self.items = {w: idx for idx, w in enumerate(items)}
self.indices = {v: k for k, v in self.items.items()}
self.vectors = np.asarray(vectors)
self.norm_vectors = self.normalize(self.vectors)
self.unk_index = unk_index
self.size = self.vectors.shape[1]
self.name = name
@staticmethod
def load(pathtovector,
wordlist=(),
num_to_load=None,
truncate_embeddings=None,
unk_word=None,
sep=" "):
r"""
Read a file in word2vec .txt format.
The load function will raise a ValueError when trying to load items
which do not conform to line lengths.
Parameters
----------
pathtovector : string
The path to the vector file.
header : bool
Whether the vector file has a header of the type
(NUMBER OF ITEMS, SIZE OF VECTOR).
wordlist : iterable, optional, default ()
A list of words you want loaded from the vector file. If this is
None (default), all words will be loaded.
num_to_load : int, optional, default None
The number of items to load from the file. Because loading can take
some time, it is sometimes useful to onlyl load the first n items
from a vector file for quick inspection.
truncate_embeddings : int, optional, default None
If this value is not None, the vectors in the vector space will
be truncated to the number of dimensions indicated by this value.
unk_word : object
The object to treat as UNK in your vector space. If this is not
in your items dictionary after loading, we add it with a zero
vector.
Returns
-------
r : Reach
An initialized Reach instance.
"""
vectors, items = Reach._load(pathtovector,
wordlist,
num_to_load,
truncate_embeddings,
sep)
if unk_word is not None:
if unk_word not in set(items):
unk_vec = np.zeros((1, vectors.shape[1]))
vectors = np.concatenate([unk_vec, vectors], 0)
items = [unk_word] + items
unk_index = 0
else:
unk_index = items.index(unk_word)
else:
unk_index = None
return Reach(vectors,
items,
name=os.path.split(pathtovector)[-1],
unk_index=unk_index)
@staticmethod
def _load(pathtovector,
wordlist,
num_to_load=None,
truncate_embeddings=None,
sep=" "):
"""Load a matrix and wordlist from a .vec file."""
vectors = []
addedwords = set()
words = []
try:
wordlist = set(wordlist)
except ValueError:
wordlist = set()
logger.info("Loading {0}".format(pathtovector))
firstline = open(pathtovector).readline().strip()
try:
num, size = firstline.split(sep)
num, size = int(num), int(size)
logger.info("Vector space: {} by {}".format(num, size))
header = True
except ValueError:
size = len(firstline.split(sep)) - 1
logger.info("Vector space: {} dim, # items unknown".format(size))
word, rest = firstline.split(sep, 1)
# If the first line is correctly parseable, set header to False.
header = False
if truncate_embeddings is None or truncate_embeddings == 0:
truncate_embeddings = size
for idx, line in enumerate(open(pathtovector, encoding='utf-8')):
if header and idx == 0:
continue
word, rest = line.rstrip(" \n").split(sep, 1)
if wordlist and word not in wordlist:
continue
if word in addedwords:
raise ValueError("Duplicate: {} on line {} was in the "
"vector space twice".format(word, idx))
if len(rest.split(sep)) != size:
raise ValueError("Incorrect input at index {}, size "
"is {}, expected "
"{}".format(idx+1,
len(rest.split(sep)), size))
words.append(word)
addedwords.add(word)
vectors.append(np.fromstring(rest, sep=sep)[:truncate_embeddings])
if num_to_load is not None and len(addedwords) >= num_to_load:
break
vectors = np.array(vectors).astype(np.float32)
logger.info("Loading finished")
if wordlist:
diff = wordlist - addedwords
if diff:
logger.info("Not all items from your wordlist were in your "
"vector space: {}.".format(diff))
return vectors, words
def __getitem__(self, item):
"""Get the vector for a single item."""
return self.vectors[self.items[item]]
def vectorize(self, tokens, remove_oov=False, norm=False):
"""
Vectorize a sentence by replacing all items with their vectors.
Parameters
----------
tokens : object or list of objects
The tokens to vectorize.
remove_oov : bool, optional, default False
Whether to remove OOV items. If False, OOV items are replaced by
the UNK glyph. If this is True, the returned sequence might
have a different length than the original sequence.
norm : bool, optional, default False
Whether to return the unit vectors, or the regular vectors.
Returns
-------
s : numpy array
An M * N matrix, where every item has been replaced by
its vector. OOV items are either removed, or replaced
by the value of the UNK glyph.
"""
if not tokens:
raise ValueError("You supplied an empty list.")
index = list(self.bow(tokens, remove_oov=remove_oov))
if not index:
raise ValueError("You supplied a list with only OOV tokens: {}, "
"which then got removed. Set remove_oov to False,"
" or filter your sentences to remove any in which"
" all items are OOV.")
if norm:
return np.stack([self.norm_vectors[x] for x in index])
else:
return np.stack([self.vectors[x] for x in index])
def bow(self, tokens, remove_oov=False):
"""
Create a bow representation of a list of tokens.
Parameters
----------
tokens : list.
The list of items to change into a bag of words representation.
remove_oov : bool.
Whether to remove OOV items from the input.
If this is True, the length of the returned BOW representation
might not be the length of the original representation.
Returns
-------
bow : generator
A BOW representation of the list of items.
"""
if remove_oov:
tokens = [x for x in tokens if x in self.items]
for t in tokens:
try:
yield self.items[t]
except KeyError:
if self.unk_index is None:
raise ValueError("You supplied OOV items but didn't "
"provide the index of the replacement "
"glyph. Either set remove_oov to True, "
"or set unk_index to the index of the "
"item which replaces any OOV items.")
yield self.unk_index
def transform(self, corpus, remove_oov=False, norm=False):
"""
Transform a corpus by repeated calls to vectorize, defined above.
Parameters
----------
corpus : A list of strings, list of list of strings.
Represents a corpus as a list of sentences, where sentences
can either be strings or lists of tokens.
remove_oov : bool, optional, default False
If True, removes OOV items from the input before vectorization.
Returns
-------
c : list
A list of numpy arrays, where each array represents the transformed
sentence in the original list. The list is guaranteed to be the
same length as the input list, but the arrays in the list may be
of different lengths, depending on whether remove_oov is True.
"""
return [self.vectorize(s, remove_oov=remove_oov, norm=norm)
for s in corpus]
def most_similar(self,
items,
num=10,
batch_size=100,
show_progressbar=False,
return_names=True):
"""
Return the num most similar items to a given list of items.
Parameters
----------
items : list of objects or a single object.
The items to get the most similar items to.
num : int, optional, default 10
The number of most similar items to retrieve.
batch_size : int, optional, default 100.
The batch size to use. 100 is a good default option. Increasing
the batch size may increase the speed.
show_progressbar : bool, optional, default False
Whether to show a progressbar.
return_names : bool, optional, default True
Whether to return the item names, or just the distances.
Returns
-------
sim : array
For each items in the input the num most similar items are returned
in the form of (NAME, DISTANCE) tuples. If return_names is false,
the returned list just contains distances.
"""
# This line allows users to input single items.
# We used to rely on string identities, but we now also allow
# anything hashable as keys.
# Might fail if a list of passed items is also in the vocabulary.
# but I can't think of cases when this would happen, and what
# user expectations are.
try:
if items in self.items:
items = [items]
except TypeError:
pass
x = np.stack([self.norm_vectors[self.items[x]] for x in items])
result = self._batch(x,
batch_size,
num+1,
show_progressbar,
return_names)
# list call consumes the generator.
return [x[1:] for x in result]
def threshold(self,
items,
threshold=.5,
batch_size=100,
show_progressbar=False,
return_names=True):
"""
Return all items whose similarity is higher than threshold.
Parameters
----------
items : list of objects or a single object.
The items to get the most similar items to.
threshold : float, optional, default .5
The radius within which to retrieve items.
batch_size : int, optional, default 100.
The batch size to use. 100 is a good default option. Increasing
the batch size may increase the speed.
show_progressbar : bool, optional, default False
Whether to show a progressbar.
return_names : bool, optional, default True
Whether to return the item names, or just the distances.
Returns
-------
sim : array
For each items in the input the num most similar items are returned
in the form of (NAME, DISTANCE) tuples. If return_names is false,
the returned list just contains distances.
"""
# This line allows users to input single items.
# We used to rely on string identities, but we now also allow
# anything hashable as keys.
# Might fail if a list of passed items is also in the vocabulary.
# but I can't think of cases when this would happen, and what
# user expectations are.
try:
if items in self.items:
items = [items]
except TypeError:
pass
x = np.stack([self.norm_vectors[self.items[x]] for x in items])
result = self._threshold_batch(x,
batch_size,
threshold,
show_progressbar,
return_names)
# list call consumes the generator.
return [x[1:] for x in result]
def nearest_neighbor(self,
vectors,
num=10,
batch_size=100,
show_progressbar=False,
return_names=True):
"""
Find the nearest neighbors to some arbitrary vector.
This function is meant to be used in composition operations. The
most_similar function can only handle items that are in vocab, and
looks up their vector through a dictionary. Compositions, e.g.
"King - man + woman" are necessarily not in the vocabulary.
Parameters
----------
vectors : list of arrays or numpy array
The vectors to find the nearest neighbors to.
num : int, optional, default 10
The number of most similar items to retrieve.
batch_size : int, optional, default 100.
The batch size to use. 100 is a good default option. Increasing
the batch size may increase speed.
show_progressbar : bool, optional, default False
Whether to show a progressbar.
return_names : bool, optional, default True
Whether to return the item names, or just the distances.
Returns
-------
sim : list of tuples.
For each item in the input the num most similar items are returned
in the form of (NAME, DISTANCE) tuples. If return_names is set to
false, only the distances are returned.
"""
vectors = np.array(vectors)
if np.ndim(vectors) == 1:
vectors = vectors[None, :]
result = []
result = self._batch(vectors,
batch_size,
num+1,
show_progressbar,
return_names)
return list(result)
def nearest_neighbor_threshold(self,
vectors,
threshold=.5,
batch_size=100,
show_progressbar=False,
return_names=True):
"""
Find the nearest neighbors to some arbitrary vector.
This function is meant to be used in composition operations. The
most_similar function can only handle items that are in vocab, and
looks up their vector through a dictionary. Compositions, e.g.
"King - man + woman" are necessarily not in the vocabulary.
Parameters
----------
vectors : list of arrays or numpy array
The vectors to find the nearest neighbors to.
threshold : float, optional, default .5
The threshold within to retrieve items.
batch_size : int, optional, default 100.
The batch size to use. 100 is a good default option. Increasing
the batch size may increase speed.
show_progressbar : bool, optional, default False
Whether to show a progressbar.
return_names : bool, optional, default True
Whether to return the item names, or just the distances.
Returns
-------
sim : list of tuples.
For each item in the input the num most similar items are returned
in the form of (NAME, DISTANCE) tuples. If return_names is set to
false, only the distances are returned.
"""
vectors = np.array(vectors)
if np.ndim(vectors) == 1:
vectors = vectors[None, :]
result = []
result = self._threshold_batch(vectors,
batch_size,
threshold,
show_progressbar,
return_names)
return list(result)
def _threshold_batch(self,
vectors,
batch_size,
threshold,
show_progressbar,
return_names):
"""Batched cosine distance."""
vectors = self.normalize(vectors)
# Single transpose, makes things faster.
reference_transposed = self.norm_vectors.T
for i in tqdm(range(0, len(vectors), batch_size),
disable=not show_progressbar):
distances = vectors[i: i+batch_size].dot(reference_transposed)
# For safety we clip
distances = np.clip(distances, a_min=.0, a_max=1.0)
for lidx, dists in enumerate(distances):
indices = np.flatnonzero(dists >= threshold)
sorted_indices = indices[np.argsort(-dists[indices])]
if return_names:
yield [(self.indices[d], dists[d])
for d in sorted_indices]
else:
yield list(dists[sorted_indices])
def _batch(self,
vectors,
batch_size,
num,
show_progressbar,
return_names):
"""Batched cosine distance."""
vectors = self.normalize(vectors)
# Single transpose, makes things faster.
reference_transposed = self.norm_vectors.T
for i in tqdm(range(0, len(vectors), batch_size),
disable=not show_progressbar):
distances = vectors[i: i+batch_size].dot(reference_transposed)
# For safety we clip
distances = np.clip(distances, a_min=.0, a_max=1.0)
if num == 1:
sorted_indices = np.argmax(distances, 1)[:, None]
else:
sorted_indices = np.argpartition(-distances, kth=num, axis=1)
sorted_indices = sorted_indices[:, :num]
for lidx, indices in enumerate(sorted_indices):
dists = distances[lidx, indices]
if return_names:
dindex = np.argsort(-dists)
yield [(self.indices[indices[d]], dists[d])
for d in dindex]
else:
yield list(-1 * np.sort(-dists))
@staticmethod
def normalize(vectors):
"""
Normalize a matrix of row vectors to unit length.
Contains a shortcut if there are no zero vectors in the matrix.
If there are zero vectors, we do some indexing tricks to avoid
dividing by 0.
Parameters
----------
vectors : np.array
The vectors to normalize.
Returns
-------
vectors : np.array
The input vectors, normalized to unit length.
"""
if np.ndim(vectors) == 1:
norm = np.linalg.norm(vectors)
if norm == 0:
return np.zeros_like(vectors)
return vectors / norm
norm = np.linalg.norm(vectors, axis=1)
if np.any(norm == 0):
nonzero = norm > 0
result = np.zeros_like(vectors)
n = norm[nonzero]
p = vectors[nonzero]
result[nonzero] = p / n[:, None]
return result
else:
return vectors / norm[:, None]
def vector_similarity(self, vector, items):
"""Compute the similarity between a vector and a set of items."""
vector = self.normalize(vector)
items_vec = np.stack([self.norm_vectors[self.items[x]] for x in items])
return vector.dot(items_vec.T)
def similarity(self, i1, i2):
"""
Compute the similarity between two sets of items.
Parameters
----------
i1 : object
The first set of items.
i2 : object
The second set of item.
Returns
-------
sim : array of floats
An array of similarity scores between 1 and 0.
"""
try:
if i1 in self.items:
i1 = [i1]
except TypeError:
pass
try:
if i2 in self.items:
i2 = [i2]
except TypeError:
pass
i1_vec = np.stack([self.norm_vectors[self.items[x]] for x in i1])
i2_vec = np.stack([self.norm_vectors[self.items[x]] for x in i2])
return i1_vec.dot(i2_vec.T)
def save(self, path, write_header=True):
"""
Save the current vector space in word2vec format.
Parameters
----------
path : str
The path to save the vector file to.
write_header : bool, optional, default True
Whether to write a word2vec-style header as the first line of the
file
"""
with open(path, 'w') as f:
if write_header:
f.write(u"{0} {1}\n".format(str(self.vectors.shape[0]),
str(self.vectors.shape[1])))
for i in range(len(self.items)):
w = self.indices[i]
vec = self.vectors[i]
f.write(u"{0} {1}\n".format(w,
" ".join([str(x) for x in vec])))
def save_fast_format(self, filename):
"""
Save a reach instance in a fast format.
The reach fast format stores the words and vectors of a Reach instance
separately in a JSON and numpy format, respectively.
Parameters
----------
filename : str
The prefix to add to the saved filename. Note that this is not the
real filename under which these items are stored.
The words and unk_index are stored under "{filename}_words.json",
and the numpy matrix is saved under "{filename}_vectors.npy".
"""
items, _ = zip(*sorted(self.items.items(), key=lambda x: x[1]))
items = {"items": items,
"unk_index": self.unk_index,
"name": self.name}
json.dump(items, open("{}_items.json".format(filename), 'w'))
np.save(open("{}_vectors.npy".format(filename), 'wb'), self.vectors)
@staticmethod
def load_fast_format(filename):
"""
Load a reach instance in fast format.
As described above, the fast format stores the words and vectors of the
Reach instance separately, and is drastically faster than loading from
.txt files.
Parameters
----------
filename : str
The filename prefix from which to load. Note that this is not a
real filepath as such, but a shared prefix for both files.
In order for this to work, both {filename}_words.json and
{filename}_vectors.npy should be present.
"""
words, unk_index, name, vectors = Reach._load_fast(filename)
return Reach(vectors, words, unk_index=unk_index, name=name)
@staticmethod
def _load_fast(filename):
"""Sub for fast loader."""
it = json.load(open("{}_items.json".format(filename)))
words, unk_index, name = it["items"], it["unk_index"], it["name"]
vectors = np.load(open("{}_vectors.npy".format(filename), 'rb'))
return words, unk_index, name, vectors
|
stephantul/reach
|
reach/reach.py
|
Reach.save
|
python
|
def save(self, path, write_header=True):
with open(path, 'w') as f:
if write_header:
f.write(u"{0} {1}\n".format(str(self.vectors.shape[0]),
str(self.vectors.shape[1])))
for i in range(len(self.items)):
w = self.indices[i]
vec = self.vectors[i]
f.write(u"{0} {1}\n".format(w,
" ".join([str(x) for x in vec])))
|
Save the current vector space in word2vec format.
Parameters
----------
path : str
The path to save the vector file to.
write_header : bool, optional, default True
Whether to write a word2vec-style header as the first line of the
file
|
train
|
https://github.com/stephantul/reach/blob/e5ed0cc895d17429e797c6d7dd57bce82ff00d5d/reach/reach.py#L675-L700
| null |
class Reach(object):
"""
Work with vector representations of items.
Supports functions for calculating fast batched similarity
between items or composite representations of items.
Parameters
----------
vectors : numpy array
The vector space.
items : list
A list of items. Length must be equal to the number of vectors, and
aligned with the vectors.
name : string, optional
A string giving the name of the current reach. Only useful if you
have multiple spaces and want to keep track of them.
Attributes
----------
items : dict
A mapping from items to ids.
indices : dict
A mapping from ids to items.
vectors : numpy array
The array representing the vector space.
norm_vectors : numpy array
A normalized version of the vector space.
unk_index : int
The integer index of your unknown glyph. This glyph will be inserted
into your BoW space whenever an unknown item is encountered.
size : int
The dimensionality of the vector space.
name : string
The name of the Reach instance.
"""
def __init__(self, vectors, items, name="", unk_index=None):
"""Initialize a Reach instance with an array and list of items."""
if len(items) != len(vectors):
raise ValueError("Your vector space and list of items are not "
"the same length: "
"{} != {}".format(len(vectors), len(items)))
if isinstance(items, dict) or isinstance(items, set):
raise ValueError("Your item list is a set or dict, and might not "
"retain order in the conversion to internal look"
"-ups. Please convert it to list and check the "
"order.")
self.items = {w: idx for idx, w in enumerate(items)}
self.indices = {v: k for k, v in self.items.items()}
self.vectors = np.asarray(vectors)
self.norm_vectors = self.normalize(self.vectors)
self.unk_index = unk_index
self.size = self.vectors.shape[1]
self.name = name
@staticmethod
def load(pathtovector,
wordlist=(),
num_to_load=None,
truncate_embeddings=None,
unk_word=None,
sep=" "):
r"""
Read a file in word2vec .txt format.
The load function will raise a ValueError when trying to load items
which do not conform to line lengths.
Parameters
----------
pathtovector : string
The path to the vector file.
header : bool
Whether the vector file has a header of the type
(NUMBER OF ITEMS, SIZE OF VECTOR).
wordlist : iterable, optional, default ()
A list of words you want loaded from the vector file. If this is
None (default), all words will be loaded.
num_to_load : int, optional, default None
The number of items to load from the file. Because loading can take
some time, it is sometimes useful to onlyl load the first n items
from a vector file for quick inspection.
truncate_embeddings : int, optional, default None
If this value is not None, the vectors in the vector space will
be truncated to the number of dimensions indicated by this value.
unk_word : object
The object to treat as UNK in your vector space. If this is not
in your items dictionary after loading, we add it with a zero
vector.
Returns
-------
r : Reach
An initialized Reach instance.
"""
vectors, items = Reach._load(pathtovector,
wordlist,
num_to_load,
truncate_embeddings,
sep)
if unk_word is not None:
if unk_word not in set(items):
unk_vec = np.zeros((1, vectors.shape[1]))
vectors = np.concatenate([unk_vec, vectors], 0)
items = [unk_word] + items
unk_index = 0
else:
unk_index = items.index(unk_word)
else:
unk_index = None
return Reach(vectors,
items,
name=os.path.split(pathtovector)[-1],
unk_index=unk_index)
@staticmethod
def _load(pathtovector,
wordlist,
num_to_load=None,
truncate_embeddings=None,
sep=" "):
"""Load a matrix and wordlist from a .vec file."""
vectors = []
addedwords = set()
words = []
try:
wordlist = set(wordlist)
except ValueError:
wordlist = set()
logger.info("Loading {0}".format(pathtovector))
firstline = open(pathtovector).readline().strip()
try:
num, size = firstline.split(sep)
num, size = int(num), int(size)
logger.info("Vector space: {} by {}".format(num, size))
header = True
except ValueError:
size = len(firstline.split(sep)) - 1
logger.info("Vector space: {} dim, # items unknown".format(size))
word, rest = firstline.split(sep, 1)
# If the first line is correctly parseable, set header to False.
header = False
if truncate_embeddings is None or truncate_embeddings == 0:
truncate_embeddings = size
for idx, line in enumerate(open(pathtovector, encoding='utf-8')):
if header and idx == 0:
continue
word, rest = line.rstrip(" \n").split(sep, 1)
if wordlist and word not in wordlist:
continue
if word in addedwords:
raise ValueError("Duplicate: {} on line {} was in the "
"vector space twice".format(word, idx))
if len(rest.split(sep)) != size:
raise ValueError("Incorrect input at index {}, size "
"is {}, expected "
"{}".format(idx+1,
len(rest.split(sep)), size))
words.append(word)
addedwords.add(word)
vectors.append(np.fromstring(rest, sep=sep)[:truncate_embeddings])
if num_to_load is not None and len(addedwords) >= num_to_load:
break
vectors = np.array(vectors).astype(np.float32)
logger.info("Loading finished")
if wordlist:
diff = wordlist - addedwords
if diff:
logger.info("Not all items from your wordlist were in your "
"vector space: {}.".format(diff))
return vectors, words
def __getitem__(self, item):
"""Get the vector for a single item."""
return self.vectors[self.items[item]]
def vectorize(self, tokens, remove_oov=False, norm=False):
"""
Vectorize a sentence by replacing all items with their vectors.
Parameters
----------
tokens : object or list of objects
The tokens to vectorize.
remove_oov : bool, optional, default False
Whether to remove OOV items. If False, OOV items are replaced by
the UNK glyph. If this is True, the returned sequence might
have a different length than the original sequence.
norm : bool, optional, default False
Whether to return the unit vectors, or the regular vectors.
Returns
-------
s : numpy array
An M * N matrix, where every item has been replaced by
its vector. OOV items are either removed, or replaced
by the value of the UNK glyph.
"""
if not tokens:
raise ValueError("You supplied an empty list.")
index = list(self.bow(tokens, remove_oov=remove_oov))
if not index:
raise ValueError("You supplied a list with only OOV tokens: {}, "
"which then got removed. Set remove_oov to False,"
" or filter your sentences to remove any in which"
" all items are OOV.")
if norm:
return np.stack([self.norm_vectors[x] for x in index])
else:
return np.stack([self.vectors[x] for x in index])
def bow(self, tokens, remove_oov=False):
"""
Create a bow representation of a list of tokens.
Parameters
----------
tokens : list.
The list of items to change into a bag of words representation.
remove_oov : bool.
Whether to remove OOV items from the input.
If this is True, the length of the returned BOW representation
might not be the length of the original representation.
Returns
-------
bow : generator
A BOW representation of the list of items.
"""
if remove_oov:
tokens = [x for x in tokens if x in self.items]
for t in tokens:
try:
yield self.items[t]
except KeyError:
if self.unk_index is None:
raise ValueError("You supplied OOV items but didn't "
"provide the index of the replacement "
"glyph. Either set remove_oov to True, "
"or set unk_index to the index of the "
"item which replaces any OOV items.")
yield self.unk_index
def transform(self, corpus, remove_oov=False, norm=False):
"""
Transform a corpus by repeated calls to vectorize, defined above.
Parameters
----------
corpus : A list of strings, list of list of strings.
Represents a corpus as a list of sentences, where sentences
can either be strings or lists of tokens.
remove_oov : bool, optional, default False
If True, removes OOV items from the input before vectorization.
Returns
-------
c : list
A list of numpy arrays, where each array represents the transformed
sentence in the original list. The list is guaranteed to be the
same length as the input list, but the arrays in the list may be
of different lengths, depending on whether remove_oov is True.
"""
return [self.vectorize(s, remove_oov=remove_oov, norm=norm)
for s in corpus]
def most_similar(self,
items,
num=10,
batch_size=100,
show_progressbar=False,
return_names=True):
"""
Return the num most similar items to a given list of items.
Parameters
----------
items : list of objects or a single object.
The items to get the most similar items to.
num : int, optional, default 10
The number of most similar items to retrieve.
batch_size : int, optional, default 100.
The batch size to use. 100 is a good default option. Increasing
the batch size may increase the speed.
show_progressbar : bool, optional, default False
Whether to show a progressbar.
return_names : bool, optional, default True
Whether to return the item names, or just the distances.
Returns
-------
sim : array
For each items in the input the num most similar items are returned
in the form of (NAME, DISTANCE) tuples. If return_names is false,
the returned list just contains distances.
"""
# This line allows users to input single items.
# We used to rely on string identities, but we now also allow
# anything hashable as keys.
# Might fail if a list of passed items is also in the vocabulary.
# but I can't think of cases when this would happen, and what
# user expectations are.
try:
if items in self.items:
items = [items]
except TypeError:
pass
x = np.stack([self.norm_vectors[self.items[x]] for x in items])
result = self._batch(x,
batch_size,
num+1,
show_progressbar,
return_names)
# list call consumes the generator.
return [x[1:] for x in result]
def threshold(self,
items,
threshold=.5,
batch_size=100,
show_progressbar=False,
return_names=True):
"""
Return all items whose similarity is higher than threshold.
Parameters
----------
items : list of objects or a single object.
The items to get the most similar items to.
threshold : float, optional, default .5
The radius within which to retrieve items.
batch_size : int, optional, default 100.
The batch size to use. 100 is a good default option. Increasing
the batch size may increase the speed.
show_progressbar : bool, optional, default False
Whether to show a progressbar.
return_names : bool, optional, default True
Whether to return the item names, or just the distances.
Returns
-------
sim : array
For each items in the input the num most similar items are returned
in the form of (NAME, DISTANCE) tuples. If return_names is false,
the returned list just contains distances.
"""
# This line allows users to input single items.
# We used to rely on string identities, but we now also allow
# anything hashable as keys.
# Might fail if a list of passed items is also in the vocabulary.
# but I can't think of cases when this would happen, and what
# user expectations are.
try:
if items in self.items:
items = [items]
except TypeError:
pass
x = np.stack([self.norm_vectors[self.items[x]] for x in items])
result = self._threshold_batch(x,
batch_size,
threshold,
show_progressbar,
return_names)
# list call consumes the generator.
return [x[1:] for x in result]
def nearest_neighbor(self,
vectors,
num=10,
batch_size=100,
show_progressbar=False,
return_names=True):
"""
Find the nearest neighbors to some arbitrary vector.
This function is meant to be used in composition operations. The
most_similar function can only handle items that are in vocab, and
looks up their vector through a dictionary. Compositions, e.g.
"King - man + woman" are necessarily not in the vocabulary.
Parameters
----------
vectors : list of arrays or numpy array
The vectors to find the nearest neighbors to.
num : int, optional, default 10
The number of most similar items to retrieve.
batch_size : int, optional, default 100.
The batch size to use. 100 is a good default option. Increasing
the batch size may increase speed.
show_progressbar : bool, optional, default False
Whether to show a progressbar.
return_names : bool, optional, default True
Whether to return the item names, or just the distances.
Returns
-------
sim : list of tuples.
For each item in the input the num most similar items are returned
in the form of (NAME, DISTANCE) tuples. If return_names is set to
false, only the distances are returned.
"""
vectors = np.array(vectors)
if np.ndim(vectors) == 1:
vectors = vectors[None, :]
result = []
result = self._batch(vectors,
batch_size,
num+1,
show_progressbar,
return_names)
return list(result)
def nearest_neighbor_threshold(self,
vectors,
threshold=.5,
batch_size=100,
show_progressbar=False,
return_names=True):
"""
Find the nearest neighbors to some arbitrary vector.
This function is meant to be used in composition operations. The
most_similar function can only handle items that are in vocab, and
looks up their vector through a dictionary. Compositions, e.g.
"King - man + woman" are necessarily not in the vocabulary.
Parameters
----------
vectors : list of arrays or numpy array
The vectors to find the nearest neighbors to.
threshold : float, optional, default .5
The threshold within to retrieve items.
batch_size : int, optional, default 100.
The batch size to use. 100 is a good default option. Increasing
the batch size may increase speed.
show_progressbar : bool, optional, default False
Whether to show a progressbar.
return_names : bool, optional, default True
Whether to return the item names, or just the distances.
Returns
-------
sim : list of tuples.
For each item in the input the num most similar items are returned
in the form of (NAME, DISTANCE) tuples. If return_names is set to
false, only the distances are returned.
"""
vectors = np.array(vectors)
if np.ndim(vectors) == 1:
vectors = vectors[None, :]
result = []
result = self._threshold_batch(vectors,
batch_size,
threshold,
show_progressbar,
return_names)
return list(result)
def _threshold_batch(self,
vectors,
batch_size,
threshold,
show_progressbar,
return_names):
"""Batched cosine distance."""
vectors = self.normalize(vectors)
# Single transpose, makes things faster.
reference_transposed = self.norm_vectors.T
for i in tqdm(range(0, len(vectors), batch_size),
disable=not show_progressbar):
distances = vectors[i: i+batch_size].dot(reference_transposed)
# For safety we clip
distances = np.clip(distances, a_min=.0, a_max=1.0)
for lidx, dists in enumerate(distances):
indices = np.flatnonzero(dists >= threshold)
sorted_indices = indices[np.argsort(-dists[indices])]
if return_names:
yield [(self.indices[d], dists[d])
for d in sorted_indices]
else:
yield list(dists[sorted_indices])
def _batch(self,
vectors,
batch_size,
num,
show_progressbar,
return_names):
"""Batched cosine distance."""
vectors = self.normalize(vectors)
# Single transpose, makes things faster.
reference_transposed = self.norm_vectors.T
for i in tqdm(range(0, len(vectors), batch_size),
disable=not show_progressbar):
distances = vectors[i: i+batch_size].dot(reference_transposed)
# For safety we clip
distances = np.clip(distances, a_min=.0, a_max=1.0)
if num == 1:
sorted_indices = np.argmax(distances, 1)[:, None]
else:
sorted_indices = np.argpartition(-distances, kth=num, axis=1)
sorted_indices = sorted_indices[:, :num]
for lidx, indices in enumerate(sorted_indices):
dists = distances[lidx, indices]
if return_names:
dindex = np.argsort(-dists)
yield [(self.indices[indices[d]], dists[d])
for d in dindex]
else:
yield list(-1 * np.sort(-dists))
@staticmethod
def normalize(vectors):
"""
Normalize a matrix of row vectors to unit length.
Contains a shortcut if there are no zero vectors in the matrix.
If there are zero vectors, we do some indexing tricks to avoid
dividing by 0.
Parameters
----------
vectors : np.array
The vectors to normalize.
Returns
-------
vectors : np.array
The input vectors, normalized to unit length.
"""
if np.ndim(vectors) == 1:
norm = np.linalg.norm(vectors)
if norm == 0:
return np.zeros_like(vectors)
return vectors / norm
norm = np.linalg.norm(vectors, axis=1)
if np.any(norm == 0):
nonzero = norm > 0
result = np.zeros_like(vectors)
n = norm[nonzero]
p = vectors[nonzero]
result[nonzero] = p / n[:, None]
return result
else:
return vectors / norm[:, None]
def vector_similarity(self, vector, items):
"""Compute the similarity between a vector and a set of items."""
vector = self.normalize(vector)
items_vec = np.stack([self.norm_vectors[self.items[x]] for x in items])
return vector.dot(items_vec.T)
def similarity(self, i1, i2):
"""
Compute the similarity between two sets of items.
Parameters
----------
i1 : object
The first set of items.
i2 : object
The second set of item.
Returns
-------
sim : array of floats
An array of similarity scores between 1 and 0.
"""
try:
if i1 in self.items:
i1 = [i1]
except TypeError:
pass
try:
if i2 in self.items:
i2 = [i2]
except TypeError:
pass
i1_vec = np.stack([self.norm_vectors[self.items[x]] for x in i1])
i2_vec = np.stack([self.norm_vectors[self.items[x]] for x in i2])
return i1_vec.dot(i2_vec.T)
def prune(self, wordlist):
"""
Prune the current reach instance by removing items.
Parameters
----------
wordlist : list of str
A list of words to keep. Note that this wordlist need not include
all words in the Reach instance. Any words which are in the
wordlist, but not in the reach instance are ignored.
"""
# Remove duplicates
wordlist = set(wordlist).intersection(set(self.items.keys()))
indices = [self.items[w] for w in wordlist if w in self.items]
if self.unk_index is not None and self.unk_index not in indices:
raise ValueError("Your unknown item is not in your list of items. "
"Set it to None before pruning, or pass your "
"unknown item.")
self.vectors = self.vectors[indices]
self.norm_vectors = self.norm_vectors[indices]
self.items = {w: idx for idx, w in enumerate(wordlist)}
self.indices = {v: k for k, v in self.items.items()}
if self.unk_index is not None:
self.unk_index = self.items[wordlist[self.unk_index]]
def save_fast_format(self, filename):
"""
Save a reach instance in a fast format.
The reach fast format stores the words and vectors of a Reach instance
separately in a JSON and numpy format, respectively.
Parameters
----------
filename : str
The prefix to add to the saved filename. Note that this is not the
real filename under which these items are stored.
The words and unk_index are stored under "{filename}_words.json",
and the numpy matrix is saved under "{filename}_vectors.npy".
"""
items, _ = zip(*sorted(self.items.items(), key=lambda x: x[1]))
items = {"items": items,
"unk_index": self.unk_index,
"name": self.name}
json.dump(items, open("{}_items.json".format(filename), 'w'))
np.save(open("{}_vectors.npy".format(filename), 'wb'), self.vectors)
@staticmethod
def load_fast_format(filename):
"""
Load a reach instance in fast format.
As described above, the fast format stores the words and vectors of the
Reach instance separately, and is drastically faster than loading from
.txt files.
Parameters
----------
filename : str
The filename prefix from which to load. Note that this is not a
real filepath as such, but a shared prefix for both files.
In order for this to work, both {filename}_words.json and
{filename}_vectors.npy should be present.
"""
words, unk_index, name, vectors = Reach._load_fast(filename)
return Reach(vectors, words, unk_index=unk_index, name=name)
@staticmethod
def _load_fast(filename):
"""Sub for fast loader."""
it = json.load(open("{}_items.json".format(filename)))
words, unk_index, name = it["items"], it["unk_index"], it["name"]
vectors = np.load(open("{}_vectors.npy".format(filename), 'rb'))
return words, unk_index, name, vectors
|
stephantul/reach
|
reach/reach.py
|
Reach.save_fast_format
|
python
|
def save_fast_format(self, filename):
items, _ = zip(*sorted(self.items.items(), key=lambda x: x[1]))
items = {"items": items,
"unk_index": self.unk_index,
"name": self.name}
json.dump(items, open("{}_items.json".format(filename), 'w'))
np.save(open("{}_vectors.npy".format(filename), 'wb'), self.vectors)
|
Save a reach instance in a fast format.
The reach fast format stores the words and vectors of a Reach instance
separately in a JSON and numpy format, respectively.
Parameters
----------
filename : str
The prefix to add to the saved filename. Note that this is not the
real filename under which these items are stored.
The words and unk_index are stored under "{filename}_words.json",
and the numpy matrix is saved under "{filename}_vectors.npy".
|
train
|
https://github.com/stephantul/reach/blob/e5ed0cc895d17429e797c6d7dd57bce82ff00d5d/reach/reach.py#L702-L724
| null |
class Reach(object):
"""
Work with vector representations of items.
Supports functions for calculating fast batched similarity
between items or composite representations of items.
Parameters
----------
vectors : numpy array
The vector space.
items : list
A list of items. Length must be equal to the number of vectors, and
aligned with the vectors.
name : string, optional
A string giving the name of the current reach. Only useful if you
have multiple spaces and want to keep track of them.
Attributes
----------
items : dict
A mapping from items to ids.
indices : dict
A mapping from ids to items.
vectors : numpy array
The array representing the vector space.
norm_vectors : numpy array
A normalized version of the vector space.
unk_index : int
The integer index of your unknown glyph. This glyph will be inserted
into your BoW space whenever an unknown item is encountered.
size : int
The dimensionality of the vector space.
name : string
The name of the Reach instance.
"""
def __init__(self, vectors, items, name="", unk_index=None):
"""Initialize a Reach instance with an array and list of items."""
if len(items) != len(vectors):
raise ValueError("Your vector space and list of items are not "
"the same length: "
"{} != {}".format(len(vectors), len(items)))
if isinstance(items, dict) or isinstance(items, set):
raise ValueError("Your item list is a set or dict, and might not "
"retain order in the conversion to internal look"
"-ups. Please convert it to list and check the "
"order.")
self.items = {w: idx for idx, w in enumerate(items)}
self.indices = {v: k for k, v in self.items.items()}
self.vectors = np.asarray(vectors)
self.norm_vectors = self.normalize(self.vectors)
self.unk_index = unk_index
self.size = self.vectors.shape[1]
self.name = name
@staticmethod
def load(pathtovector,
wordlist=(),
num_to_load=None,
truncate_embeddings=None,
unk_word=None,
sep=" "):
r"""
Read a file in word2vec .txt format.
The load function will raise a ValueError when trying to load items
which do not conform to line lengths.
Parameters
----------
pathtovector : string
The path to the vector file.
header : bool
Whether the vector file has a header of the type
(NUMBER OF ITEMS, SIZE OF VECTOR).
wordlist : iterable, optional, default ()
A list of words you want loaded from the vector file. If this is
None (default), all words will be loaded.
num_to_load : int, optional, default None
The number of items to load from the file. Because loading can take
some time, it is sometimes useful to onlyl load the first n items
from a vector file for quick inspection.
truncate_embeddings : int, optional, default None
If this value is not None, the vectors in the vector space will
be truncated to the number of dimensions indicated by this value.
unk_word : object
The object to treat as UNK in your vector space. If this is not
in your items dictionary after loading, we add it with a zero
vector.
Returns
-------
r : Reach
An initialized Reach instance.
"""
vectors, items = Reach._load(pathtovector,
wordlist,
num_to_load,
truncate_embeddings,
sep)
if unk_word is not None:
if unk_word not in set(items):
unk_vec = np.zeros((1, vectors.shape[1]))
vectors = np.concatenate([unk_vec, vectors], 0)
items = [unk_word] + items
unk_index = 0
else:
unk_index = items.index(unk_word)
else:
unk_index = None
return Reach(vectors,
items,
name=os.path.split(pathtovector)[-1],
unk_index=unk_index)
@staticmethod
def _load(pathtovector,
wordlist,
num_to_load=None,
truncate_embeddings=None,
sep=" "):
"""Load a matrix and wordlist from a .vec file."""
vectors = []
addedwords = set()
words = []
try:
wordlist = set(wordlist)
except ValueError:
wordlist = set()
logger.info("Loading {0}".format(pathtovector))
firstline = open(pathtovector).readline().strip()
try:
num, size = firstline.split(sep)
num, size = int(num), int(size)
logger.info("Vector space: {} by {}".format(num, size))
header = True
except ValueError:
size = len(firstline.split(sep)) - 1
logger.info("Vector space: {} dim, # items unknown".format(size))
word, rest = firstline.split(sep, 1)
# If the first line is correctly parseable, set header to False.
header = False
if truncate_embeddings is None or truncate_embeddings == 0:
truncate_embeddings = size
for idx, line in enumerate(open(pathtovector, encoding='utf-8')):
if header and idx == 0:
continue
word, rest = line.rstrip(" \n").split(sep, 1)
if wordlist and word not in wordlist:
continue
if word in addedwords:
raise ValueError("Duplicate: {} on line {} was in the "
"vector space twice".format(word, idx))
if len(rest.split(sep)) != size:
raise ValueError("Incorrect input at index {}, size "
"is {}, expected "
"{}".format(idx+1,
len(rest.split(sep)), size))
words.append(word)
addedwords.add(word)
vectors.append(np.fromstring(rest, sep=sep)[:truncate_embeddings])
if num_to_load is not None and len(addedwords) >= num_to_load:
break
vectors = np.array(vectors).astype(np.float32)
logger.info("Loading finished")
if wordlist:
diff = wordlist - addedwords
if diff:
logger.info("Not all items from your wordlist were in your "
"vector space: {}.".format(diff))
return vectors, words
def __getitem__(self, item):
"""Get the vector for a single item."""
return self.vectors[self.items[item]]
def vectorize(self, tokens, remove_oov=False, norm=False):
"""
Vectorize a sentence by replacing all items with their vectors.
Parameters
----------
tokens : object or list of objects
The tokens to vectorize.
remove_oov : bool, optional, default False
Whether to remove OOV items. If False, OOV items are replaced by
the UNK glyph. If this is True, the returned sequence might
have a different length than the original sequence.
norm : bool, optional, default False
Whether to return the unit vectors, or the regular vectors.
Returns
-------
s : numpy array
An M * N matrix, where every item has been replaced by
its vector. OOV items are either removed, or replaced
by the value of the UNK glyph.
"""
if not tokens:
raise ValueError("You supplied an empty list.")
index = list(self.bow(tokens, remove_oov=remove_oov))
if not index:
raise ValueError("You supplied a list with only OOV tokens: {}, "
"which then got removed. Set remove_oov to False,"
" or filter your sentences to remove any in which"
" all items are OOV.")
if norm:
return np.stack([self.norm_vectors[x] for x in index])
else:
return np.stack([self.vectors[x] for x in index])
def bow(self, tokens, remove_oov=False):
"""
Create a bow representation of a list of tokens.
Parameters
----------
tokens : list.
The list of items to change into a bag of words representation.
remove_oov : bool.
Whether to remove OOV items from the input.
If this is True, the length of the returned BOW representation
might not be the length of the original representation.
Returns
-------
bow : generator
A BOW representation of the list of items.
"""
if remove_oov:
tokens = [x for x in tokens if x in self.items]
for t in tokens:
try:
yield self.items[t]
except KeyError:
if self.unk_index is None:
raise ValueError("You supplied OOV items but didn't "
"provide the index of the replacement "
"glyph. Either set remove_oov to True, "
"or set unk_index to the index of the "
"item which replaces any OOV items.")
yield self.unk_index
def transform(self, corpus, remove_oov=False, norm=False):
"""
Transform a corpus by repeated calls to vectorize, defined above.
Parameters
----------
corpus : A list of strings, list of list of strings.
Represents a corpus as a list of sentences, where sentences
can either be strings or lists of tokens.
remove_oov : bool, optional, default False
If True, removes OOV items from the input before vectorization.
Returns
-------
c : list
A list of numpy arrays, where each array represents the transformed
sentence in the original list. The list is guaranteed to be the
same length as the input list, but the arrays in the list may be
of different lengths, depending on whether remove_oov is True.
"""
return [self.vectorize(s, remove_oov=remove_oov, norm=norm)
for s in corpus]
def most_similar(self,
items,
num=10,
batch_size=100,
show_progressbar=False,
return_names=True):
"""
Return the num most similar items to a given list of items.
Parameters
----------
items : list of objects or a single object.
The items to get the most similar items to.
num : int, optional, default 10
The number of most similar items to retrieve.
batch_size : int, optional, default 100.
The batch size to use. 100 is a good default option. Increasing
the batch size may increase the speed.
show_progressbar : bool, optional, default False
Whether to show a progressbar.
return_names : bool, optional, default True
Whether to return the item names, or just the distances.
Returns
-------
sim : array
For each items in the input the num most similar items are returned
in the form of (NAME, DISTANCE) tuples. If return_names is false,
the returned list just contains distances.
"""
# This line allows users to input single items.
# We used to rely on string identities, but we now also allow
# anything hashable as keys.
# Might fail if a list of passed items is also in the vocabulary.
# but I can't think of cases when this would happen, and what
# user expectations are.
try:
if items in self.items:
items = [items]
except TypeError:
pass
x = np.stack([self.norm_vectors[self.items[x]] for x in items])
result = self._batch(x,
batch_size,
num+1,
show_progressbar,
return_names)
# list call consumes the generator.
return [x[1:] for x in result]
def threshold(self,
items,
threshold=.5,
batch_size=100,
show_progressbar=False,
return_names=True):
"""
Return all items whose similarity is higher than threshold.
Parameters
----------
items : list of objects or a single object.
The items to get the most similar items to.
threshold : float, optional, default .5
The radius within which to retrieve items.
batch_size : int, optional, default 100.
The batch size to use. 100 is a good default option. Increasing
the batch size may increase the speed.
show_progressbar : bool, optional, default False
Whether to show a progressbar.
return_names : bool, optional, default True
Whether to return the item names, or just the distances.
Returns
-------
sim : array
For each items in the input the num most similar items are returned
in the form of (NAME, DISTANCE) tuples. If return_names is false,
the returned list just contains distances.
"""
# This line allows users to input single items.
# We used to rely on string identities, but we now also allow
# anything hashable as keys.
# Might fail if a list of passed items is also in the vocabulary.
# but I can't think of cases when this would happen, and what
# user expectations are.
try:
if items in self.items:
items = [items]
except TypeError:
pass
x = np.stack([self.norm_vectors[self.items[x]] for x in items])
result = self._threshold_batch(x,
batch_size,
threshold,
show_progressbar,
return_names)
# list call consumes the generator.
return [x[1:] for x in result]
def nearest_neighbor(self,
vectors,
num=10,
batch_size=100,
show_progressbar=False,
return_names=True):
"""
Find the nearest neighbors to some arbitrary vector.
This function is meant to be used in composition operations. The
most_similar function can only handle items that are in vocab, and
looks up their vector through a dictionary. Compositions, e.g.
"King - man + woman" are necessarily not in the vocabulary.
Parameters
----------
vectors : list of arrays or numpy array
The vectors to find the nearest neighbors to.
num : int, optional, default 10
The number of most similar items to retrieve.
batch_size : int, optional, default 100.
The batch size to use. 100 is a good default option. Increasing
the batch size may increase speed.
show_progressbar : bool, optional, default False
Whether to show a progressbar.
return_names : bool, optional, default True
Whether to return the item names, or just the distances.
Returns
-------
sim : list of tuples.
For each item in the input the num most similar items are returned
in the form of (NAME, DISTANCE) tuples. If return_names is set to
false, only the distances are returned.
"""
vectors = np.array(vectors)
if np.ndim(vectors) == 1:
vectors = vectors[None, :]
result = []
result = self._batch(vectors,
batch_size,
num+1,
show_progressbar,
return_names)
return list(result)
def nearest_neighbor_threshold(self,
vectors,
threshold=.5,
batch_size=100,
show_progressbar=False,
return_names=True):
"""
Find the nearest neighbors to some arbitrary vector.
This function is meant to be used in composition operations. The
most_similar function can only handle items that are in vocab, and
looks up their vector through a dictionary. Compositions, e.g.
"King - man + woman" are necessarily not in the vocabulary.
Parameters
----------
vectors : list of arrays or numpy array
The vectors to find the nearest neighbors to.
threshold : float, optional, default .5
The threshold within to retrieve items.
batch_size : int, optional, default 100.
The batch size to use. 100 is a good default option. Increasing
the batch size may increase speed.
show_progressbar : bool, optional, default False
Whether to show a progressbar.
return_names : bool, optional, default True
Whether to return the item names, or just the distances.
Returns
-------
sim : list of tuples.
For each item in the input the num most similar items are returned
in the form of (NAME, DISTANCE) tuples. If return_names is set to
false, only the distances are returned.
"""
vectors = np.array(vectors)
if np.ndim(vectors) == 1:
vectors = vectors[None, :]
result = []
result = self._threshold_batch(vectors,
batch_size,
threshold,
show_progressbar,
return_names)
return list(result)
def _threshold_batch(self,
vectors,
batch_size,
threshold,
show_progressbar,
return_names):
"""Batched cosine distance."""
vectors = self.normalize(vectors)
# Single transpose, makes things faster.
reference_transposed = self.norm_vectors.T
for i in tqdm(range(0, len(vectors), batch_size),
disable=not show_progressbar):
distances = vectors[i: i+batch_size].dot(reference_transposed)
# For safety we clip
distances = np.clip(distances, a_min=.0, a_max=1.0)
for lidx, dists in enumerate(distances):
indices = np.flatnonzero(dists >= threshold)
sorted_indices = indices[np.argsort(-dists[indices])]
if return_names:
yield [(self.indices[d], dists[d])
for d in sorted_indices]
else:
yield list(dists[sorted_indices])
def _batch(self,
vectors,
batch_size,
num,
show_progressbar,
return_names):
"""Batched cosine distance."""
vectors = self.normalize(vectors)
# Single transpose, makes things faster.
reference_transposed = self.norm_vectors.T
for i in tqdm(range(0, len(vectors), batch_size),
disable=not show_progressbar):
distances = vectors[i: i+batch_size].dot(reference_transposed)
# For safety we clip
distances = np.clip(distances, a_min=.0, a_max=1.0)
if num == 1:
sorted_indices = np.argmax(distances, 1)[:, None]
else:
sorted_indices = np.argpartition(-distances, kth=num, axis=1)
sorted_indices = sorted_indices[:, :num]
for lidx, indices in enumerate(sorted_indices):
dists = distances[lidx, indices]
if return_names:
dindex = np.argsort(-dists)
yield [(self.indices[indices[d]], dists[d])
for d in dindex]
else:
yield list(-1 * np.sort(-dists))
@staticmethod
def normalize(vectors):
"""
Normalize a matrix of row vectors to unit length.
Contains a shortcut if there are no zero vectors in the matrix.
If there are zero vectors, we do some indexing tricks to avoid
dividing by 0.
Parameters
----------
vectors : np.array
The vectors to normalize.
Returns
-------
vectors : np.array
The input vectors, normalized to unit length.
"""
if np.ndim(vectors) == 1:
norm = np.linalg.norm(vectors)
if norm == 0:
return np.zeros_like(vectors)
return vectors / norm
norm = np.linalg.norm(vectors, axis=1)
if np.any(norm == 0):
nonzero = norm > 0
result = np.zeros_like(vectors)
n = norm[nonzero]
p = vectors[nonzero]
result[nonzero] = p / n[:, None]
return result
else:
return vectors / norm[:, None]
def vector_similarity(self, vector, items):
"""Compute the similarity between a vector and a set of items."""
vector = self.normalize(vector)
items_vec = np.stack([self.norm_vectors[self.items[x]] for x in items])
return vector.dot(items_vec.T)
def similarity(self, i1, i2):
"""
Compute the similarity between two sets of items.
Parameters
----------
i1 : object
The first set of items.
i2 : object
The second set of item.
Returns
-------
sim : array of floats
An array of similarity scores between 1 and 0.
"""
try:
if i1 in self.items:
i1 = [i1]
except TypeError:
pass
try:
if i2 in self.items:
i2 = [i2]
except TypeError:
pass
i1_vec = np.stack([self.norm_vectors[self.items[x]] for x in i1])
i2_vec = np.stack([self.norm_vectors[self.items[x]] for x in i2])
return i1_vec.dot(i2_vec.T)
def prune(self, wordlist):
"""
Prune the current reach instance by removing items.
Parameters
----------
wordlist : list of str
A list of words to keep. Note that this wordlist need not include
all words in the Reach instance. Any words which are in the
wordlist, but not in the reach instance are ignored.
"""
# Remove duplicates
wordlist = set(wordlist).intersection(set(self.items.keys()))
indices = [self.items[w] for w in wordlist if w in self.items]
if self.unk_index is not None and self.unk_index not in indices:
raise ValueError("Your unknown item is not in your list of items. "
"Set it to None before pruning, or pass your "
"unknown item.")
self.vectors = self.vectors[indices]
self.norm_vectors = self.norm_vectors[indices]
self.items = {w: idx for idx, w in enumerate(wordlist)}
self.indices = {v: k for k, v in self.items.items()}
if self.unk_index is not None:
self.unk_index = self.items[wordlist[self.unk_index]]
def save(self, path, write_header=True):
"""
Save the current vector space in word2vec format.
Parameters
----------
path : str
The path to save the vector file to.
write_header : bool, optional, default True
Whether to write a word2vec-style header as the first line of the
file
"""
with open(path, 'w') as f:
if write_header:
f.write(u"{0} {1}\n".format(str(self.vectors.shape[0]),
str(self.vectors.shape[1])))
for i in range(len(self.items)):
w = self.indices[i]
vec = self.vectors[i]
f.write(u"{0} {1}\n".format(w,
" ".join([str(x) for x in vec])))
@staticmethod
def load_fast_format(filename):
"""
Load a reach instance in fast format.
As described above, the fast format stores the words and vectors of the
Reach instance separately, and is drastically faster than loading from
.txt files.
Parameters
----------
filename : str
The filename prefix from which to load. Note that this is not a
real filepath as such, but a shared prefix for both files.
In order for this to work, both {filename}_words.json and
{filename}_vectors.npy should be present.
"""
words, unk_index, name, vectors = Reach._load_fast(filename)
return Reach(vectors, words, unk_index=unk_index, name=name)
@staticmethod
def _load_fast(filename):
"""Sub for fast loader."""
it = json.load(open("{}_items.json".format(filename)))
words, unk_index, name = it["items"], it["unk_index"], it["name"]
vectors = np.load(open("{}_vectors.npy".format(filename), 'rb'))
return words, unk_index, name, vectors
|
stephantul/reach
|
reach/reach.py
|
Reach.load_fast_format
|
python
|
def load_fast_format(filename):
words, unk_index, name, vectors = Reach._load_fast(filename)
return Reach(vectors, words, unk_index=unk_index, name=name)
|
Load a reach instance in fast format.
As described above, the fast format stores the words and vectors of the
Reach instance separately, and is drastically faster than loading from
.txt files.
Parameters
----------
filename : str
The filename prefix from which to load. Note that this is not a
real filepath as such, but a shared prefix for both files.
In order for this to work, both {filename}_words.json and
{filename}_vectors.npy should be present.
|
train
|
https://github.com/stephantul/reach/blob/e5ed0cc895d17429e797c6d7dd57bce82ff00d5d/reach/reach.py#L727-L745
|
[
"def _load_fast(filename):\n \"\"\"Sub for fast loader.\"\"\"\n it = json.load(open(\"{}_items.json\".format(filename)))\n words, unk_index, name = it[\"items\"], it[\"unk_index\"], it[\"name\"]\n vectors = np.load(open(\"{}_vectors.npy\".format(filename), 'rb'))\n return words, unk_index, name, vectors\n"
] |
class Reach(object):
"""
Work with vector representations of items.
Supports functions for calculating fast batched similarity
between items or composite representations of items.
Parameters
----------
vectors : numpy array
The vector space.
items : list
A list of items. Length must be equal to the number of vectors, and
aligned with the vectors.
name : string, optional
A string giving the name of the current reach. Only useful if you
have multiple spaces and want to keep track of them.
Attributes
----------
items : dict
A mapping from items to ids.
indices : dict
A mapping from ids to items.
vectors : numpy array
The array representing the vector space.
norm_vectors : numpy array
A normalized version of the vector space.
unk_index : int
The integer index of your unknown glyph. This glyph will be inserted
into your BoW space whenever an unknown item is encountered.
size : int
The dimensionality of the vector space.
name : string
The name of the Reach instance.
"""
def __init__(self, vectors, items, name="", unk_index=None):
"""Initialize a Reach instance with an array and list of items."""
if len(items) != len(vectors):
raise ValueError("Your vector space and list of items are not "
"the same length: "
"{} != {}".format(len(vectors), len(items)))
if isinstance(items, dict) or isinstance(items, set):
raise ValueError("Your item list is a set or dict, and might not "
"retain order in the conversion to internal look"
"-ups. Please convert it to list and check the "
"order.")
self.items = {w: idx for idx, w in enumerate(items)}
self.indices = {v: k for k, v in self.items.items()}
self.vectors = np.asarray(vectors)
self.norm_vectors = self.normalize(self.vectors)
self.unk_index = unk_index
self.size = self.vectors.shape[1]
self.name = name
@staticmethod
def load(pathtovector,
wordlist=(),
num_to_load=None,
truncate_embeddings=None,
unk_word=None,
sep=" "):
r"""
Read a file in word2vec .txt format.
The load function will raise a ValueError when trying to load items
which do not conform to line lengths.
Parameters
----------
pathtovector : string
The path to the vector file.
header : bool
Whether the vector file has a header of the type
(NUMBER OF ITEMS, SIZE OF VECTOR).
wordlist : iterable, optional, default ()
A list of words you want loaded from the vector file. If this is
None (default), all words will be loaded.
num_to_load : int, optional, default None
The number of items to load from the file. Because loading can take
some time, it is sometimes useful to onlyl load the first n items
from a vector file for quick inspection.
truncate_embeddings : int, optional, default None
If this value is not None, the vectors in the vector space will
be truncated to the number of dimensions indicated by this value.
unk_word : object
The object to treat as UNK in your vector space. If this is not
in your items dictionary after loading, we add it with a zero
vector.
Returns
-------
r : Reach
An initialized Reach instance.
"""
vectors, items = Reach._load(pathtovector,
wordlist,
num_to_load,
truncate_embeddings,
sep)
if unk_word is not None:
if unk_word not in set(items):
unk_vec = np.zeros((1, vectors.shape[1]))
vectors = np.concatenate([unk_vec, vectors], 0)
items = [unk_word] + items
unk_index = 0
else:
unk_index = items.index(unk_word)
else:
unk_index = None
return Reach(vectors,
items,
name=os.path.split(pathtovector)[-1],
unk_index=unk_index)
@staticmethod
def _load(pathtovector,
wordlist,
num_to_load=None,
truncate_embeddings=None,
sep=" "):
"""Load a matrix and wordlist from a .vec file."""
vectors = []
addedwords = set()
words = []
try:
wordlist = set(wordlist)
except ValueError:
wordlist = set()
logger.info("Loading {0}".format(pathtovector))
firstline = open(pathtovector).readline().strip()
try:
num, size = firstline.split(sep)
num, size = int(num), int(size)
logger.info("Vector space: {} by {}".format(num, size))
header = True
except ValueError:
size = len(firstline.split(sep)) - 1
logger.info("Vector space: {} dim, # items unknown".format(size))
word, rest = firstline.split(sep, 1)
# If the first line is correctly parseable, set header to False.
header = False
if truncate_embeddings is None or truncate_embeddings == 0:
truncate_embeddings = size
for idx, line in enumerate(open(pathtovector, encoding='utf-8')):
if header and idx == 0:
continue
word, rest = line.rstrip(" \n").split(sep, 1)
if wordlist and word not in wordlist:
continue
if word in addedwords:
raise ValueError("Duplicate: {} on line {} was in the "
"vector space twice".format(word, idx))
if len(rest.split(sep)) != size:
raise ValueError("Incorrect input at index {}, size "
"is {}, expected "
"{}".format(idx+1,
len(rest.split(sep)), size))
words.append(word)
addedwords.add(word)
vectors.append(np.fromstring(rest, sep=sep)[:truncate_embeddings])
if num_to_load is not None and len(addedwords) >= num_to_load:
break
vectors = np.array(vectors).astype(np.float32)
logger.info("Loading finished")
if wordlist:
diff = wordlist - addedwords
if diff:
logger.info("Not all items from your wordlist were in your "
"vector space: {}.".format(diff))
return vectors, words
def __getitem__(self, item):
"""Get the vector for a single item."""
return self.vectors[self.items[item]]
def vectorize(self, tokens, remove_oov=False, norm=False):
"""
Vectorize a sentence by replacing all items with their vectors.
Parameters
----------
tokens : object or list of objects
The tokens to vectorize.
remove_oov : bool, optional, default False
Whether to remove OOV items. If False, OOV items are replaced by
the UNK glyph. If this is True, the returned sequence might
have a different length than the original sequence.
norm : bool, optional, default False
Whether to return the unit vectors, or the regular vectors.
Returns
-------
s : numpy array
An M * N matrix, where every item has been replaced by
its vector. OOV items are either removed, or replaced
by the value of the UNK glyph.
"""
if not tokens:
raise ValueError("You supplied an empty list.")
index = list(self.bow(tokens, remove_oov=remove_oov))
if not index:
raise ValueError("You supplied a list with only OOV tokens: {}, "
"which then got removed. Set remove_oov to False,"
" or filter your sentences to remove any in which"
" all items are OOV.")
if norm:
return np.stack([self.norm_vectors[x] for x in index])
else:
return np.stack([self.vectors[x] for x in index])
def bow(self, tokens, remove_oov=False):
"""
Create a bow representation of a list of tokens.
Parameters
----------
tokens : list.
The list of items to change into a bag of words representation.
remove_oov : bool.
Whether to remove OOV items from the input.
If this is True, the length of the returned BOW representation
might not be the length of the original representation.
Returns
-------
bow : generator
A BOW representation of the list of items.
"""
if remove_oov:
tokens = [x for x in tokens if x in self.items]
for t in tokens:
try:
yield self.items[t]
except KeyError:
if self.unk_index is None:
raise ValueError("You supplied OOV items but didn't "
"provide the index of the replacement "
"glyph. Either set remove_oov to True, "
"or set unk_index to the index of the "
"item which replaces any OOV items.")
yield self.unk_index
def transform(self, corpus, remove_oov=False, norm=False):
"""
Transform a corpus by repeated calls to vectorize, defined above.
Parameters
----------
corpus : A list of strings, list of list of strings.
Represents a corpus as a list of sentences, where sentences
can either be strings or lists of tokens.
remove_oov : bool, optional, default False
If True, removes OOV items from the input before vectorization.
Returns
-------
c : list
A list of numpy arrays, where each array represents the transformed
sentence in the original list. The list is guaranteed to be the
same length as the input list, but the arrays in the list may be
of different lengths, depending on whether remove_oov is True.
"""
return [self.vectorize(s, remove_oov=remove_oov, norm=norm)
for s in corpus]
def most_similar(self,
items,
num=10,
batch_size=100,
show_progressbar=False,
return_names=True):
"""
Return the num most similar items to a given list of items.
Parameters
----------
items : list of objects or a single object.
The items to get the most similar items to.
num : int, optional, default 10
The number of most similar items to retrieve.
batch_size : int, optional, default 100.
The batch size to use. 100 is a good default option. Increasing
the batch size may increase the speed.
show_progressbar : bool, optional, default False
Whether to show a progressbar.
return_names : bool, optional, default True
Whether to return the item names, or just the distances.
Returns
-------
sim : array
For each items in the input the num most similar items are returned
in the form of (NAME, DISTANCE) tuples. If return_names is false,
the returned list just contains distances.
"""
# This line allows users to input single items.
# We used to rely on string identities, but we now also allow
# anything hashable as keys.
# Might fail if a list of passed items is also in the vocabulary.
# but I can't think of cases when this would happen, and what
# user expectations are.
try:
if items in self.items:
items = [items]
except TypeError:
pass
x = np.stack([self.norm_vectors[self.items[x]] for x in items])
result = self._batch(x,
batch_size,
num+1,
show_progressbar,
return_names)
# list call consumes the generator.
return [x[1:] for x in result]
def threshold(self,
items,
threshold=.5,
batch_size=100,
show_progressbar=False,
return_names=True):
"""
Return all items whose similarity is higher than threshold.
Parameters
----------
items : list of objects or a single object.
The items to get the most similar items to.
threshold : float, optional, default .5
The radius within which to retrieve items.
batch_size : int, optional, default 100.
The batch size to use. 100 is a good default option. Increasing
the batch size may increase the speed.
show_progressbar : bool, optional, default False
Whether to show a progressbar.
return_names : bool, optional, default True
Whether to return the item names, or just the distances.
Returns
-------
sim : array
For each items in the input the num most similar items are returned
in the form of (NAME, DISTANCE) tuples. If return_names is false,
the returned list just contains distances.
"""
# This line allows users to input single items.
# We used to rely on string identities, but we now also allow
# anything hashable as keys.
# Might fail if a list of passed items is also in the vocabulary.
# but I can't think of cases when this would happen, and what
# user expectations are.
try:
if items in self.items:
items = [items]
except TypeError:
pass
x = np.stack([self.norm_vectors[self.items[x]] for x in items])
result = self._threshold_batch(x,
batch_size,
threshold,
show_progressbar,
return_names)
# list call consumes the generator.
return [x[1:] for x in result]
def nearest_neighbor(self,
vectors,
num=10,
batch_size=100,
show_progressbar=False,
return_names=True):
"""
Find the nearest neighbors to some arbitrary vector.
This function is meant to be used in composition operations. The
most_similar function can only handle items that are in vocab, and
looks up their vector through a dictionary. Compositions, e.g.
"King - man + woman" are necessarily not in the vocabulary.
Parameters
----------
vectors : list of arrays or numpy array
The vectors to find the nearest neighbors to.
num : int, optional, default 10
The number of most similar items to retrieve.
batch_size : int, optional, default 100.
The batch size to use. 100 is a good default option. Increasing
the batch size may increase speed.
show_progressbar : bool, optional, default False
Whether to show a progressbar.
return_names : bool, optional, default True
Whether to return the item names, or just the distances.
Returns
-------
sim : list of tuples.
For each item in the input the num most similar items are returned
in the form of (NAME, DISTANCE) tuples. If return_names is set to
false, only the distances are returned.
"""
vectors = np.array(vectors)
if np.ndim(vectors) == 1:
vectors = vectors[None, :]
result = []
result = self._batch(vectors,
batch_size,
num+1,
show_progressbar,
return_names)
return list(result)
def nearest_neighbor_threshold(self,
vectors,
threshold=.5,
batch_size=100,
show_progressbar=False,
return_names=True):
"""
Find the nearest neighbors to some arbitrary vector.
This function is meant to be used in composition operations. The
most_similar function can only handle items that are in vocab, and
looks up their vector through a dictionary. Compositions, e.g.
"King - man + woman" are necessarily not in the vocabulary.
Parameters
----------
vectors : list of arrays or numpy array
The vectors to find the nearest neighbors to.
threshold : float, optional, default .5
The threshold within to retrieve items.
batch_size : int, optional, default 100.
The batch size to use. 100 is a good default option. Increasing
the batch size may increase speed.
show_progressbar : bool, optional, default False
Whether to show a progressbar.
return_names : bool, optional, default True
Whether to return the item names, or just the distances.
Returns
-------
sim : list of tuples.
For each item in the input the num most similar items are returned
in the form of (NAME, DISTANCE) tuples. If return_names is set to
false, only the distances are returned.
"""
vectors = np.array(vectors)
if np.ndim(vectors) == 1:
vectors = vectors[None, :]
result = []
result = self._threshold_batch(vectors,
batch_size,
threshold,
show_progressbar,
return_names)
return list(result)
def _threshold_batch(self,
vectors,
batch_size,
threshold,
show_progressbar,
return_names):
"""Batched cosine distance."""
vectors = self.normalize(vectors)
# Single transpose, makes things faster.
reference_transposed = self.norm_vectors.T
for i in tqdm(range(0, len(vectors), batch_size),
disable=not show_progressbar):
distances = vectors[i: i+batch_size].dot(reference_transposed)
# For safety we clip
distances = np.clip(distances, a_min=.0, a_max=1.0)
for lidx, dists in enumerate(distances):
indices = np.flatnonzero(dists >= threshold)
sorted_indices = indices[np.argsort(-dists[indices])]
if return_names:
yield [(self.indices[d], dists[d])
for d in sorted_indices]
else:
yield list(dists[sorted_indices])
def _batch(self,
vectors,
batch_size,
num,
show_progressbar,
return_names):
"""Batched cosine distance."""
vectors = self.normalize(vectors)
# Single transpose, makes things faster.
reference_transposed = self.norm_vectors.T
for i in tqdm(range(0, len(vectors), batch_size),
disable=not show_progressbar):
distances = vectors[i: i+batch_size].dot(reference_transposed)
# For safety we clip
distances = np.clip(distances, a_min=.0, a_max=1.0)
if num == 1:
sorted_indices = np.argmax(distances, 1)[:, None]
else:
sorted_indices = np.argpartition(-distances, kth=num, axis=1)
sorted_indices = sorted_indices[:, :num]
for lidx, indices in enumerate(sorted_indices):
dists = distances[lidx, indices]
if return_names:
dindex = np.argsort(-dists)
yield [(self.indices[indices[d]], dists[d])
for d in dindex]
else:
yield list(-1 * np.sort(-dists))
@staticmethod
def normalize(vectors):
"""
Normalize a matrix of row vectors to unit length.
Contains a shortcut if there are no zero vectors in the matrix.
If there are zero vectors, we do some indexing tricks to avoid
dividing by 0.
Parameters
----------
vectors : np.array
The vectors to normalize.
Returns
-------
vectors : np.array
The input vectors, normalized to unit length.
"""
if np.ndim(vectors) == 1:
norm = np.linalg.norm(vectors)
if norm == 0:
return np.zeros_like(vectors)
return vectors / norm
norm = np.linalg.norm(vectors, axis=1)
if np.any(norm == 0):
nonzero = norm > 0
result = np.zeros_like(vectors)
n = norm[nonzero]
p = vectors[nonzero]
result[nonzero] = p / n[:, None]
return result
else:
return vectors / norm[:, None]
def vector_similarity(self, vector, items):
"""Compute the similarity between a vector and a set of items."""
vector = self.normalize(vector)
items_vec = np.stack([self.norm_vectors[self.items[x]] for x in items])
return vector.dot(items_vec.T)
def similarity(self, i1, i2):
"""
Compute the similarity between two sets of items.
Parameters
----------
i1 : object
The first set of items.
i2 : object
The second set of item.
Returns
-------
sim : array of floats
An array of similarity scores between 1 and 0.
"""
try:
if i1 in self.items:
i1 = [i1]
except TypeError:
pass
try:
if i2 in self.items:
i2 = [i2]
except TypeError:
pass
i1_vec = np.stack([self.norm_vectors[self.items[x]] for x in i1])
i2_vec = np.stack([self.norm_vectors[self.items[x]] for x in i2])
return i1_vec.dot(i2_vec.T)
def prune(self, wordlist):
"""
Prune the current reach instance by removing items.
Parameters
----------
wordlist : list of str
A list of words to keep. Note that this wordlist need not include
all words in the Reach instance. Any words which are in the
wordlist, but not in the reach instance are ignored.
"""
# Remove duplicates
wordlist = set(wordlist).intersection(set(self.items.keys()))
indices = [self.items[w] for w in wordlist if w in self.items]
if self.unk_index is not None and self.unk_index not in indices:
raise ValueError("Your unknown item is not in your list of items. "
"Set it to None before pruning, or pass your "
"unknown item.")
self.vectors = self.vectors[indices]
self.norm_vectors = self.norm_vectors[indices]
self.items = {w: idx for idx, w in enumerate(wordlist)}
self.indices = {v: k for k, v in self.items.items()}
if self.unk_index is not None:
self.unk_index = self.items[wordlist[self.unk_index]]
def save(self, path, write_header=True):
"""
Save the current vector space in word2vec format.
Parameters
----------
path : str
The path to save the vector file to.
write_header : bool, optional, default True
Whether to write a word2vec-style header as the first line of the
file
"""
with open(path, 'w') as f:
if write_header:
f.write(u"{0} {1}\n".format(str(self.vectors.shape[0]),
str(self.vectors.shape[1])))
for i in range(len(self.items)):
w = self.indices[i]
vec = self.vectors[i]
f.write(u"{0} {1}\n".format(w,
" ".join([str(x) for x in vec])))
def save_fast_format(self, filename):
"""
Save a reach instance in a fast format.
The reach fast format stores the words and vectors of a Reach instance
separately in a JSON and numpy format, respectively.
Parameters
----------
filename : str
The prefix to add to the saved filename. Note that this is not the
real filename under which these items are stored.
The words and unk_index are stored under "{filename}_words.json",
and the numpy matrix is saved under "{filename}_vectors.npy".
"""
items, _ = zip(*sorted(self.items.items(), key=lambda x: x[1]))
items = {"items": items,
"unk_index": self.unk_index,
"name": self.name}
json.dump(items, open("{}_items.json".format(filename), 'w'))
np.save(open("{}_vectors.npy".format(filename), 'wb'), self.vectors)
@staticmethod
@staticmethod
def _load_fast(filename):
"""Sub for fast loader."""
it = json.load(open("{}_items.json".format(filename)))
words, unk_index, name = it["items"], it["unk_index"], it["name"]
vectors = np.load(open("{}_vectors.npy".format(filename), 'rb'))
return words, unk_index, name, vectors
|
stephantul/reach
|
reach/reach.py
|
Reach._load_fast
|
python
|
def _load_fast(filename):
it = json.load(open("{}_items.json".format(filename)))
words, unk_index, name = it["items"], it["unk_index"], it["name"]
vectors = np.load(open("{}_vectors.npy".format(filename), 'rb'))
return words, unk_index, name, vectors
|
Sub for fast loader.
|
train
|
https://github.com/stephantul/reach/blob/e5ed0cc895d17429e797c6d7dd57bce82ff00d5d/reach/reach.py#L748-L753
| null |
class Reach(object):
"""
Work with vector representations of items.
Supports functions for calculating fast batched similarity
between items or composite representations of items.
Parameters
----------
vectors : numpy array
The vector space.
items : list
A list of items. Length must be equal to the number of vectors, and
aligned with the vectors.
name : string, optional
A string giving the name of the current reach. Only useful if you
have multiple spaces and want to keep track of them.
Attributes
----------
items : dict
A mapping from items to ids.
indices : dict
A mapping from ids to items.
vectors : numpy array
The array representing the vector space.
norm_vectors : numpy array
A normalized version of the vector space.
unk_index : int
The integer index of your unknown glyph. This glyph will be inserted
into your BoW space whenever an unknown item is encountered.
size : int
The dimensionality of the vector space.
name : string
The name of the Reach instance.
"""
def __init__(self, vectors, items, name="", unk_index=None):
"""Initialize a Reach instance with an array and list of items."""
if len(items) != len(vectors):
raise ValueError("Your vector space and list of items are not "
"the same length: "
"{} != {}".format(len(vectors), len(items)))
if isinstance(items, dict) or isinstance(items, set):
raise ValueError("Your item list is a set or dict, and might not "
"retain order in the conversion to internal look"
"-ups. Please convert it to list and check the "
"order.")
self.items = {w: idx for idx, w in enumerate(items)}
self.indices = {v: k for k, v in self.items.items()}
self.vectors = np.asarray(vectors)
self.norm_vectors = self.normalize(self.vectors)
self.unk_index = unk_index
self.size = self.vectors.shape[1]
self.name = name
@staticmethod
def load(pathtovector,
wordlist=(),
num_to_load=None,
truncate_embeddings=None,
unk_word=None,
sep=" "):
r"""
Read a file in word2vec .txt format.
The load function will raise a ValueError when trying to load items
which do not conform to line lengths.
Parameters
----------
pathtovector : string
The path to the vector file.
header : bool
Whether the vector file has a header of the type
(NUMBER OF ITEMS, SIZE OF VECTOR).
wordlist : iterable, optional, default ()
A list of words you want loaded from the vector file. If this is
None (default), all words will be loaded.
num_to_load : int, optional, default None
The number of items to load from the file. Because loading can take
some time, it is sometimes useful to onlyl load the first n items
from a vector file for quick inspection.
truncate_embeddings : int, optional, default None
If this value is not None, the vectors in the vector space will
be truncated to the number of dimensions indicated by this value.
unk_word : object
The object to treat as UNK in your vector space. If this is not
in your items dictionary after loading, we add it with a zero
vector.
Returns
-------
r : Reach
An initialized Reach instance.
"""
vectors, items = Reach._load(pathtovector,
wordlist,
num_to_load,
truncate_embeddings,
sep)
if unk_word is not None:
if unk_word not in set(items):
unk_vec = np.zeros((1, vectors.shape[1]))
vectors = np.concatenate([unk_vec, vectors], 0)
items = [unk_word] + items
unk_index = 0
else:
unk_index = items.index(unk_word)
else:
unk_index = None
return Reach(vectors,
items,
name=os.path.split(pathtovector)[-1],
unk_index=unk_index)
@staticmethod
def _load(pathtovector,
wordlist,
num_to_load=None,
truncate_embeddings=None,
sep=" "):
"""Load a matrix and wordlist from a .vec file."""
vectors = []
addedwords = set()
words = []
try:
wordlist = set(wordlist)
except ValueError:
wordlist = set()
logger.info("Loading {0}".format(pathtovector))
firstline = open(pathtovector).readline().strip()
try:
num, size = firstline.split(sep)
num, size = int(num), int(size)
logger.info("Vector space: {} by {}".format(num, size))
header = True
except ValueError:
size = len(firstline.split(sep)) - 1
logger.info("Vector space: {} dim, # items unknown".format(size))
word, rest = firstline.split(sep, 1)
# If the first line is correctly parseable, set header to False.
header = False
if truncate_embeddings is None or truncate_embeddings == 0:
truncate_embeddings = size
for idx, line in enumerate(open(pathtovector, encoding='utf-8')):
if header and idx == 0:
continue
word, rest = line.rstrip(" \n").split(sep, 1)
if wordlist and word not in wordlist:
continue
if word in addedwords:
raise ValueError("Duplicate: {} on line {} was in the "
"vector space twice".format(word, idx))
if len(rest.split(sep)) != size:
raise ValueError("Incorrect input at index {}, size "
"is {}, expected "
"{}".format(idx+1,
len(rest.split(sep)), size))
words.append(word)
addedwords.add(word)
vectors.append(np.fromstring(rest, sep=sep)[:truncate_embeddings])
if num_to_load is not None and len(addedwords) >= num_to_load:
break
vectors = np.array(vectors).astype(np.float32)
logger.info("Loading finished")
if wordlist:
diff = wordlist - addedwords
if diff:
logger.info("Not all items from your wordlist were in your "
"vector space: {}.".format(diff))
return vectors, words
def __getitem__(self, item):
"""Get the vector for a single item."""
return self.vectors[self.items[item]]
def vectorize(self, tokens, remove_oov=False, norm=False):
"""
Vectorize a sentence by replacing all items with their vectors.
Parameters
----------
tokens : object or list of objects
The tokens to vectorize.
remove_oov : bool, optional, default False
Whether to remove OOV items. If False, OOV items are replaced by
the UNK glyph. If this is True, the returned sequence might
have a different length than the original sequence.
norm : bool, optional, default False
Whether to return the unit vectors, or the regular vectors.
Returns
-------
s : numpy array
An M * N matrix, where every item has been replaced by
its vector. OOV items are either removed, or replaced
by the value of the UNK glyph.
"""
if not tokens:
raise ValueError("You supplied an empty list.")
index = list(self.bow(tokens, remove_oov=remove_oov))
if not index:
raise ValueError("You supplied a list with only OOV tokens: {}, "
"which then got removed. Set remove_oov to False,"
" or filter your sentences to remove any in which"
" all items are OOV.")
if norm:
return np.stack([self.norm_vectors[x] for x in index])
else:
return np.stack([self.vectors[x] for x in index])
def bow(self, tokens, remove_oov=False):
"""
Create a bow representation of a list of tokens.
Parameters
----------
tokens : list.
The list of items to change into a bag of words representation.
remove_oov : bool.
Whether to remove OOV items from the input.
If this is True, the length of the returned BOW representation
might not be the length of the original representation.
Returns
-------
bow : generator
A BOW representation of the list of items.
"""
if remove_oov:
tokens = [x for x in tokens if x in self.items]
for t in tokens:
try:
yield self.items[t]
except KeyError:
if self.unk_index is None:
raise ValueError("You supplied OOV items but didn't "
"provide the index of the replacement "
"glyph. Either set remove_oov to True, "
"or set unk_index to the index of the "
"item which replaces any OOV items.")
yield self.unk_index
def transform(self, corpus, remove_oov=False, norm=False):
"""
Transform a corpus by repeated calls to vectorize, defined above.
Parameters
----------
corpus : A list of strings, list of list of strings.
Represents a corpus as a list of sentences, where sentences
can either be strings or lists of tokens.
remove_oov : bool, optional, default False
If True, removes OOV items from the input before vectorization.
Returns
-------
c : list
A list of numpy arrays, where each array represents the transformed
sentence in the original list. The list is guaranteed to be the
same length as the input list, but the arrays in the list may be
of different lengths, depending on whether remove_oov is True.
"""
return [self.vectorize(s, remove_oov=remove_oov, norm=norm)
for s in corpus]
def most_similar(self,
items,
num=10,
batch_size=100,
show_progressbar=False,
return_names=True):
"""
Return the num most similar items to a given list of items.
Parameters
----------
items : list of objects or a single object.
The items to get the most similar items to.
num : int, optional, default 10
The number of most similar items to retrieve.
batch_size : int, optional, default 100.
The batch size to use. 100 is a good default option. Increasing
the batch size may increase the speed.
show_progressbar : bool, optional, default False
Whether to show a progressbar.
return_names : bool, optional, default True
Whether to return the item names, or just the distances.
Returns
-------
sim : array
For each items in the input the num most similar items are returned
in the form of (NAME, DISTANCE) tuples. If return_names is false,
the returned list just contains distances.
"""
# This line allows users to input single items.
# We used to rely on string identities, but we now also allow
# anything hashable as keys.
# Might fail if a list of passed items is also in the vocabulary.
# but I can't think of cases when this would happen, and what
# user expectations are.
try:
if items in self.items:
items = [items]
except TypeError:
pass
x = np.stack([self.norm_vectors[self.items[x]] for x in items])
result = self._batch(x,
batch_size,
num+1,
show_progressbar,
return_names)
# list call consumes the generator.
return [x[1:] for x in result]
def threshold(self,
items,
threshold=.5,
batch_size=100,
show_progressbar=False,
return_names=True):
"""
Return all items whose similarity is higher than threshold.
Parameters
----------
items : list of objects or a single object.
The items to get the most similar items to.
threshold : float, optional, default .5
The radius within which to retrieve items.
batch_size : int, optional, default 100.
The batch size to use. 100 is a good default option. Increasing
the batch size may increase the speed.
show_progressbar : bool, optional, default False
Whether to show a progressbar.
return_names : bool, optional, default True
Whether to return the item names, or just the distances.
Returns
-------
sim : array
For each items in the input the num most similar items are returned
in the form of (NAME, DISTANCE) tuples. If return_names is false,
the returned list just contains distances.
"""
# This line allows users to input single items.
# We used to rely on string identities, but we now also allow
# anything hashable as keys.
# Might fail if a list of passed items is also in the vocabulary.
# but I can't think of cases when this would happen, and what
# user expectations are.
try:
if items in self.items:
items = [items]
except TypeError:
pass
x = np.stack([self.norm_vectors[self.items[x]] for x in items])
result = self._threshold_batch(x,
batch_size,
threshold,
show_progressbar,
return_names)
# list call consumes the generator.
return [x[1:] for x in result]
def nearest_neighbor(self,
vectors,
num=10,
batch_size=100,
show_progressbar=False,
return_names=True):
"""
Find the nearest neighbors to some arbitrary vector.
This function is meant to be used in composition operations. The
most_similar function can only handle items that are in vocab, and
looks up their vector through a dictionary. Compositions, e.g.
"King - man + woman" are necessarily not in the vocabulary.
Parameters
----------
vectors : list of arrays or numpy array
The vectors to find the nearest neighbors to.
num : int, optional, default 10
The number of most similar items to retrieve.
batch_size : int, optional, default 100.
The batch size to use. 100 is a good default option. Increasing
the batch size may increase speed.
show_progressbar : bool, optional, default False
Whether to show a progressbar.
return_names : bool, optional, default True
Whether to return the item names, or just the distances.
Returns
-------
sim : list of tuples.
For each item in the input the num most similar items are returned
in the form of (NAME, DISTANCE) tuples. If return_names is set to
false, only the distances are returned.
"""
vectors = np.array(vectors)
if np.ndim(vectors) == 1:
vectors = vectors[None, :]
result = []
result = self._batch(vectors,
batch_size,
num+1,
show_progressbar,
return_names)
return list(result)
def nearest_neighbor_threshold(self,
vectors,
threshold=.5,
batch_size=100,
show_progressbar=False,
return_names=True):
"""
Find the nearest neighbors to some arbitrary vector.
This function is meant to be used in composition operations. The
most_similar function can only handle items that are in vocab, and
looks up their vector through a dictionary. Compositions, e.g.
"King - man + woman" are necessarily not in the vocabulary.
Parameters
----------
vectors : list of arrays or numpy array
The vectors to find the nearest neighbors to.
threshold : float, optional, default .5
The threshold within to retrieve items.
batch_size : int, optional, default 100.
The batch size to use. 100 is a good default option. Increasing
the batch size may increase speed.
show_progressbar : bool, optional, default False
Whether to show a progressbar.
return_names : bool, optional, default True
Whether to return the item names, or just the distances.
Returns
-------
sim : list of tuples.
For each item in the input the num most similar items are returned
in the form of (NAME, DISTANCE) tuples. If return_names is set to
false, only the distances are returned.
"""
vectors = np.array(vectors)
if np.ndim(vectors) == 1:
vectors = vectors[None, :]
result = []
result = self._threshold_batch(vectors,
batch_size,
threshold,
show_progressbar,
return_names)
return list(result)
def _threshold_batch(self,
vectors,
batch_size,
threshold,
show_progressbar,
return_names):
"""Batched cosine distance."""
vectors = self.normalize(vectors)
# Single transpose, makes things faster.
reference_transposed = self.norm_vectors.T
for i in tqdm(range(0, len(vectors), batch_size),
disable=not show_progressbar):
distances = vectors[i: i+batch_size].dot(reference_transposed)
# For safety we clip
distances = np.clip(distances, a_min=.0, a_max=1.0)
for lidx, dists in enumerate(distances):
indices = np.flatnonzero(dists >= threshold)
sorted_indices = indices[np.argsort(-dists[indices])]
if return_names:
yield [(self.indices[d], dists[d])
for d in sorted_indices]
else:
yield list(dists[sorted_indices])
def _batch(self,
vectors,
batch_size,
num,
show_progressbar,
return_names):
"""Batched cosine distance."""
vectors = self.normalize(vectors)
# Single transpose, makes things faster.
reference_transposed = self.norm_vectors.T
for i in tqdm(range(0, len(vectors), batch_size),
disable=not show_progressbar):
distances = vectors[i: i+batch_size].dot(reference_transposed)
# For safety we clip
distances = np.clip(distances, a_min=.0, a_max=1.0)
if num == 1:
sorted_indices = np.argmax(distances, 1)[:, None]
else:
sorted_indices = np.argpartition(-distances, kth=num, axis=1)
sorted_indices = sorted_indices[:, :num]
for lidx, indices in enumerate(sorted_indices):
dists = distances[lidx, indices]
if return_names:
dindex = np.argsort(-dists)
yield [(self.indices[indices[d]], dists[d])
for d in dindex]
else:
yield list(-1 * np.sort(-dists))
@staticmethod
def normalize(vectors):
"""
Normalize a matrix of row vectors to unit length.
Contains a shortcut if there are no zero vectors in the matrix.
If there are zero vectors, we do some indexing tricks to avoid
dividing by 0.
Parameters
----------
vectors : np.array
The vectors to normalize.
Returns
-------
vectors : np.array
The input vectors, normalized to unit length.
"""
if np.ndim(vectors) == 1:
norm = np.linalg.norm(vectors)
if norm == 0:
return np.zeros_like(vectors)
return vectors / norm
norm = np.linalg.norm(vectors, axis=1)
if np.any(norm == 0):
nonzero = norm > 0
result = np.zeros_like(vectors)
n = norm[nonzero]
p = vectors[nonzero]
result[nonzero] = p / n[:, None]
return result
else:
return vectors / norm[:, None]
def vector_similarity(self, vector, items):
"""Compute the similarity between a vector and a set of items."""
vector = self.normalize(vector)
items_vec = np.stack([self.norm_vectors[self.items[x]] for x in items])
return vector.dot(items_vec.T)
def similarity(self, i1, i2):
"""
Compute the similarity between two sets of items.
Parameters
----------
i1 : object
The first set of items.
i2 : object
The second set of item.
Returns
-------
sim : array of floats
An array of similarity scores between 1 and 0.
"""
try:
if i1 in self.items:
i1 = [i1]
except TypeError:
pass
try:
if i2 in self.items:
i2 = [i2]
except TypeError:
pass
i1_vec = np.stack([self.norm_vectors[self.items[x]] for x in i1])
i2_vec = np.stack([self.norm_vectors[self.items[x]] for x in i2])
return i1_vec.dot(i2_vec.T)
def prune(self, wordlist):
"""
Prune the current reach instance by removing items.
Parameters
----------
wordlist : list of str
A list of words to keep. Note that this wordlist need not include
all words in the Reach instance. Any words which are in the
wordlist, but not in the reach instance are ignored.
"""
# Remove duplicates
wordlist = set(wordlist).intersection(set(self.items.keys()))
indices = [self.items[w] for w in wordlist if w in self.items]
if self.unk_index is not None and self.unk_index not in indices:
raise ValueError("Your unknown item is not in your list of items. "
"Set it to None before pruning, or pass your "
"unknown item.")
self.vectors = self.vectors[indices]
self.norm_vectors = self.norm_vectors[indices]
self.items = {w: idx for idx, w in enumerate(wordlist)}
self.indices = {v: k for k, v in self.items.items()}
if self.unk_index is not None:
self.unk_index = self.items[wordlist[self.unk_index]]
def save(self, path, write_header=True):
"""
Save the current vector space in word2vec format.
Parameters
----------
path : str
The path to save the vector file to.
write_header : bool, optional, default True
Whether to write a word2vec-style header as the first line of the
file
"""
with open(path, 'w') as f:
if write_header:
f.write(u"{0} {1}\n".format(str(self.vectors.shape[0]),
str(self.vectors.shape[1])))
for i in range(len(self.items)):
w = self.indices[i]
vec = self.vectors[i]
f.write(u"{0} {1}\n".format(w,
" ".join([str(x) for x in vec])))
def save_fast_format(self, filename):
"""
Save a reach instance in a fast format.
The reach fast format stores the words and vectors of a Reach instance
separately in a JSON and numpy format, respectively.
Parameters
----------
filename : str
The prefix to add to the saved filename. Note that this is not the
real filename under which these items are stored.
The words and unk_index are stored under "{filename}_words.json",
and the numpy matrix is saved under "{filename}_vectors.npy".
"""
items, _ = zip(*sorted(self.items.items(), key=lambda x: x[1]))
items = {"items": items,
"unk_index": self.unk_index,
"name": self.name}
json.dump(items, open("{}_items.json".format(filename), 'w'))
np.save(open("{}_vectors.npy".format(filename), 'wb'), self.vectors)
@staticmethod
def load_fast_format(filename):
"""
Load a reach instance in fast format.
As described above, the fast format stores the words and vectors of the
Reach instance separately, and is drastically faster than loading from
.txt files.
Parameters
----------
filename : str
The filename prefix from which to load. Note that this is not a
real filepath as such, but a shared prefix for both files.
In order for this to work, both {filename}_words.json and
{filename}_vectors.npy should be present.
"""
words, unk_index, name, vectors = Reach._load_fast(filename)
return Reach(vectors, words, unk_index=unk_index, name=name)
@staticmethod
|
niklasb/webkit-server
|
webkit_server.py
|
SelectionMixin.xpath
|
python
|
def xpath(self, xpath):
return [self.get_node_factory().create(node_id)
for node_id in self._get_xpath_ids(xpath).split(",")
if node_id]
|
Finds another node by XPath originating at the current node.
|
train
|
https://github.com/niklasb/webkit-server/blob/c9e3a8394b8c51000c35f8a56fb770580562b544/webkit_server.py#L21-L25
|
[
"def _get_xpath_ids(self, xpath):\n \"\"\" Implements a mechanism to get a list of node IDs for an relative XPath\n query. \"\"\"\n return self._invoke(\"findXpathWithin\", xpath)\n"
] |
class SelectionMixin(object):
""" Implements a generic XPath selection for a class providing
``_get_xpath_ids``, ``_get_css_ids`` and ``get_node_factory`` methods. """
def css(self, css):
""" Finds another node by a CSS selector relative to the current node. """
return [self.get_node_factory().create(node_id)
for node_id in self._get_css_ids(css).split(",")
if node_id]
|
niklasb/webkit-server
|
webkit_server.py
|
SelectionMixin.css
|
python
|
def css(self, css):
return [self.get_node_factory().create(node_id)
for node_id in self._get_css_ids(css).split(",")
if node_id]
|
Finds another node by a CSS selector relative to the current node.
|
train
|
https://github.com/niklasb/webkit-server/blob/c9e3a8394b8c51000c35f8a56fb770580562b544/webkit_server.py#L27-L31
| null |
class SelectionMixin(object):
""" Implements a generic XPath selection for a class providing
``_get_xpath_ids``, ``_get_css_ids`` and ``get_node_factory`` methods. """
def xpath(self, xpath):
""" Finds another node by XPath originating at the current node. """
return [self.get_node_factory().create(node_id)
for node_id in self._get_xpath_ids(xpath).split(",")
if node_id]
|
niklasb/webkit-server
|
webkit_server.py
|
Node.get_bool_attr
|
python
|
def get_bool_attr(self, name):
val = self.get_attr(name)
return val is not None and val.lower() in ("true", name)
|
Returns the value of a boolean HTML attribute like `checked` or `disabled`
|
train
|
https://github.com/niklasb/webkit-server/blob/c9e3a8394b8c51000c35f8a56fb770580562b544/webkit_server.py#L68-L72
|
[
"def get_attr(self, name):\n \"\"\" Returns the value of an attribute. \"\"\"\n return self._invoke(\"attribute\", name)\n"
] |
class Node(SelectionMixin):
""" Represents a DOM node in our Webkit session.
`client` is the associated client instance.
`node_id` is the internal ID that is used to identify the node when communicating
with the server. """
def __init__(self, client, node_id):
super(Node, self).__init__()
self.client = client
self.node_id = node_id
def text(self):
""" Returns the inner text (*not* HTML). """
return self._invoke("text")
def get_attr(self, name):
""" Returns the value of an attribute. """
return self._invoke("attribute", name)
def set_attr(self, name, value):
""" Sets the value of an attribute. """
self.exec_script("node.setAttribute(%s, %s)" % (repr(name), repr(value)))
def value(self):
""" Returns the node's value. """
if self.is_multi_select():
return [opt.value()
for opt in self.xpath(".//option")
if opt["selected"]]
else:
return self._invoke("value")
def set(self, value):
""" Sets the node content to the given value (e.g. for input fields). """
self._invoke("set", value)
def path(self):
""" Returns an XPath expression that uniquely identifies the current node. """
return self._invoke("path")
def submit(self):
""" Submits a form node, then waits for the page to completely load. """
self.eval_script("node.submit()")
def eval_script(self, js):
""" Evaluate arbitrary Javascript with the ``node`` variable bound to the
current node. """
return self.client.eval_script(self._build_script(js))
def exec_script(self, js):
""" Execute arbitrary Javascript with the ``node`` variable bound to
the current node. """
self.client.exec_script(self._build_script(js))
def _build_script(self, js):
return "var node = Capybara.nodes[%s]; %s;" % (self.node_id, js)
def select_option(self):
""" Selects an option node. """
self._invoke("selectOption")
def unselect_options(self):
""" Unselects an option node (only possible within a multi-select). """
if self.xpath("ancestor::select")[0].is_multi_select():
self._invoke("unselectOption")
else:
raise NodeError("Unselect not allowed.")
def click(self):
""" Alias for ``left_click``. """
self.left_click()
def left_click(self):
""" Left clicks the current node, then waits for the page
to fully load. """
self._invoke("leftClick")
def right_click(self):
""" Right clicks the current node, then waits for the page
to fully load. """
self._invoke("rightClick")
def double_click(self):
""" Double clicks the current node, then waits for the page
to fully load. """
self._invoke("doubleClick")
def hover(self):
""" Hovers over the current node, then waits for the page
to fully load. """
self._invoke("hover")
def focus(self):
""" Puts the focus onto the current node, then waits for the page
to fully load. """
self._invoke("focus")
def drag_to(self, element):
""" Drag the node to another one. """
self._invoke("dragTo", element.node_id)
def tag_name(self):
""" Returns the tag name of the current node. """
return self._invoke("tagName")
def is_visible(self):
""" Checks whether the current node is visible. """
return self._invoke("visible") == "true"
def is_attached(self):
""" Checks whether the current node is actually existing on the currently
active web page. """
return self._invoke("isAttached") == "true"
def is_selected(self):
""" is the ``selected`` attribute set for this node? """
return self.get_bool_attr("selected")
def is_checked(self):
""" is the ``checked`` attribute set for this node? """
return self.get_bool_attr("checked")
def is_disabled(self):
""" is the ``disabled`` attribute set for this node? """
return self.get_bool_attr("disabled")
def is_multi_select(self):
""" is this node a multi-select? """
return self.tag_name() == "select" and self.get_bool_attr("multiple")
def _get_xpath_ids(self, xpath):
""" Implements a mechanism to get a list of node IDs for an relative XPath
query. """
return self._invoke("findXpathWithin", xpath)
def _get_css_ids(self, css):
""" Implements a mechanism to get a list of node IDs for an relative CSS
query. """
return self._invoke("findCssWithin", css)
def get_node_factory(self):
""" Returns the associated node factory. """
return self.client.get_node_factory()
def __repr__(self):
return "<Node #%s>" % self.path()
def _invoke(self, cmd, *args):
return self.client.issue_node_cmd(cmd, "false", self.node_id, *args)
|
niklasb/webkit-server
|
webkit_server.py
|
Node.set_attr
|
python
|
def set_attr(self, name, value):
self.exec_script("node.setAttribute(%s, %s)" % (repr(name), repr(value)))
|
Sets the value of an attribute.
|
train
|
https://github.com/niklasb/webkit-server/blob/c9e3a8394b8c51000c35f8a56fb770580562b544/webkit_server.py#L78-L80
|
[
"def exec_script(self, js):\n \"\"\" Execute arbitrary Javascript with the ``node`` variable bound to\n the current node. \"\"\"\n self.client.exec_script(self._build_script(js))\n"
] |
class Node(SelectionMixin):
""" Represents a DOM node in our Webkit session.
`client` is the associated client instance.
`node_id` is the internal ID that is used to identify the node when communicating
with the server. """
def __init__(self, client, node_id):
super(Node, self).__init__()
self.client = client
self.node_id = node_id
def text(self):
""" Returns the inner text (*not* HTML). """
return self._invoke("text")
def get_bool_attr(self, name):
""" Returns the value of a boolean HTML attribute like `checked` or `disabled`
"""
val = self.get_attr(name)
return val is not None and val.lower() in ("true", name)
def get_attr(self, name):
""" Returns the value of an attribute. """
return self._invoke("attribute", name)
def value(self):
""" Returns the node's value. """
if self.is_multi_select():
return [opt.value()
for opt in self.xpath(".//option")
if opt["selected"]]
else:
return self._invoke("value")
def set(self, value):
""" Sets the node content to the given value (e.g. for input fields). """
self._invoke("set", value)
def path(self):
""" Returns an XPath expression that uniquely identifies the current node. """
return self._invoke("path")
def submit(self):
""" Submits a form node, then waits for the page to completely load. """
self.eval_script("node.submit()")
def eval_script(self, js):
""" Evaluate arbitrary Javascript with the ``node`` variable bound to the
current node. """
return self.client.eval_script(self._build_script(js))
def exec_script(self, js):
""" Execute arbitrary Javascript with the ``node`` variable bound to
the current node. """
self.client.exec_script(self._build_script(js))
def _build_script(self, js):
return "var node = Capybara.nodes[%s]; %s;" % (self.node_id, js)
def select_option(self):
""" Selects an option node. """
self._invoke("selectOption")
def unselect_options(self):
""" Unselects an option node (only possible within a multi-select). """
if self.xpath("ancestor::select")[0].is_multi_select():
self._invoke("unselectOption")
else:
raise NodeError("Unselect not allowed.")
def click(self):
""" Alias for ``left_click``. """
self.left_click()
def left_click(self):
""" Left clicks the current node, then waits for the page
to fully load. """
self._invoke("leftClick")
def right_click(self):
""" Right clicks the current node, then waits for the page
to fully load. """
self._invoke("rightClick")
def double_click(self):
""" Double clicks the current node, then waits for the page
to fully load. """
self._invoke("doubleClick")
def hover(self):
""" Hovers over the current node, then waits for the page
to fully load. """
self._invoke("hover")
def focus(self):
""" Puts the focus onto the current node, then waits for the page
to fully load. """
self._invoke("focus")
def drag_to(self, element):
""" Drag the node to another one. """
self._invoke("dragTo", element.node_id)
def tag_name(self):
""" Returns the tag name of the current node. """
return self._invoke("tagName")
def is_visible(self):
""" Checks whether the current node is visible. """
return self._invoke("visible") == "true"
def is_attached(self):
""" Checks whether the current node is actually existing on the currently
active web page. """
return self._invoke("isAttached") == "true"
def is_selected(self):
""" is the ``selected`` attribute set for this node? """
return self.get_bool_attr("selected")
def is_checked(self):
""" is the ``checked`` attribute set for this node? """
return self.get_bool_attr("checked")
def is_disabled(self):
""" is the ``disabled`` attribute set for this node? """
return self.get_bool_attr("disabled")
def is_multi_select(self):
""" is this node a multi-select? """
return self.tag_name() == "select" and self.get_bool_attr("multiple")
def _get_xpath_ids(self, xpath):
""" Implements a mechanism to get a list of node IDs for an relative XPath
query. """
return self._invoke("findXpathWithin", xpath)
def _get_css_ids(self, css):
""" Implements a mechanism to get a list of node IDs for an relative CSS
query. """
return self._invoke("findCssWithin", css)
def get_node_factory(self):
""" Returns the associated node factory. """
return self.client.get_node_factory()
def __repr__(self):
return "<Node #%s>" % self.path()
def _invoke(self, cmd, *args):
return self.client.issue_node_cmd(cmd, "false", self.node_id, *args)
|
niklasb/webkit-server
|
webkit_server.py
|
Node.value
|
python
|
def value(self):
if self.is_multi_select():
return [opt.value()
for opt in self.xpath(".//option")
if opt["selected"]]
else:
return self._invoke("value")
|
Returns the node's value.
|
train
|
https://github.com/niklasb/webkit-server/blob/c9e3a8394b8c51000c35f8a56fb770580562b544/webkit_server.py#L82-L89
|
[
"def is_multi_select(self):\n \"\"\" is this node a multi-select? \"\"\"\n return self.tag_name() == \"select\" and self.get_bool_attr(\"multiple\")\n"
] |
class Node(SelectionMixin):
""" Represents a DOM node in our Webkit session.
`client` is the associated client instance.
`node_id` is the internal ID that is used to identify the node when communicating
with the server. """
def __init__(self, client, node_id):
super(Node, self).__init__()
self.client = client
self.node_id = node_id
def text(self):
""" Returns the inner text (*not* HTML). """
return self._invoke("text")
def get_bool_attr(self, name):
""" Returns the value of a boolean HTML attribute like `checked` or `disabled`
"""
val = self.get_attr(name)
return val is not None and val.lower() in ("true", name)
def get_attr(self, name):
""" Returns the value of an attribute. """
return self._invoke("attribute", name)
def set_attr(self, name, value):
""" Sets the value of an attribute. """
self.exec_script("node.setAttribute(%s, %s)" % (repr(name), repr(value)))
def set(self, value):
""" Sets the node content to the given value (e.g. for input fields). """
self._invoke("set", value)
def path(self):
""" Returns an XPath expression that uniquely identifies the current node. """
return self._invoke("path")
def submit(self):
""" Submits a form node, then waits for the page to completely load. """
self.eval_script("node.submit()")
def eval_script(self, js):
""" Evaluate arbitrary Javascript with the ``node`` variable bound to the
current node. """
return self.client.eval_script(self._build_script(js))
def exec_script(self, js):
""" Execute arbitrary Javascript with the ``node`` variable bound to
the current node. """
self.client.exec_script(self._build_script(js))
def _build_script(self, js):
return "var node = Capybara.nodes[%s]; %s;" % (self.node_id, js)
def select_option(self):
""" Selects an option node. """
self._invoke("selectOption")
def unselect_options(self):
""" Unselects an option node (only possible within a multi-select). """
if self.xpath("ancestor::select")[0].is_multi_select():
self._invoke("unselectOption")
else:
raise NodeError("Unselect not allowed.")
def click(self):
""" Alias for ``left_click``. """
self.left_click()
def left_click(self):
""" Left clicks the current node, then waits for the page
to fully load. """
self._invoke("leftClick")
def right_click(self):
""" Right clicks the current node, then waits for the page
to fully load. """
self._invoke("rightClick")
def double_click(self):
""" Double clicks the current node, then waits for the page
to fully load. """
self._invoke("doubleClick")
def hover(self):
""" Hovers over the current node, then waits for the page
to fully load. """
self._invoke("hover")
def focus(self):
""" Puts the focus onto the current node, then waits for the page
to fully load. """
self._invoke("focus")
def drag_to(self, element):
""" Drag the node to another one. """
self._invoke("dragTo", element.node_id)
def tag_name(self):
""" Returns the tag name of the current node. """
return self._invoke("tagName")
def is_visible(self):
""" Checks whether the current node is visible. """
return self._invoke("visible") == "true"
def is_attached(self):
""" Checks whether the current node is actually existing on the currently
active web page. """
return self._invoke("isAttached") == "true"
def is_selected(self):
""" is the ``selected`` attribute set for this node? """
return self.get_bool_attr("selected")
def is_checked(self):
""" is the ``checked`` attribute set for this node? """
return self.get_bool_attr("checked")
def is_disabled(self):
""" is the ``disabled`` attribute set for this node? """
return self.get_bool_attr("disabled")
def is_multi_select(self):
""" is this node a multi-select? """
return self.tag_name() == "select" and self.get_bool_attr("multiple")
def _get_xpath_ids(self, xpath):
""" Implements a mechanism to get a list of node IDs for an relative XPath
query. """
return self._invoke("findXpathWithin", xpath)
def _get_css_ids(self, css):
""" Implements a mechanism to get a list of node IDs for an relative CSS
query. """
return self._invoke("findCssWithin", css)
def get_node_factory(self):
""" Returns the associated node factory. """
return self.client.get_node_factory()
def __repr__(self):
return "<Node #%s>" % self.path()
def _invoke(self, cmd, *args):
return self.client.issue_node_cmd(cmd, "false", self.node_id, *args)
|
niklasb/webkit-server
|
webkit_server.py
|
Client.set_header
|
python
|
def set_header(self, key, value):
self.conn.issue_command("Header", _normalize_header(key), value)
|
Sets a HTTP header for future requests.
|
train
|
https://github.com/niklasb/webkit-server/blob/c9e3a8394b8c51000c35f8a56fb770580562b544/webkit_server.py#L250-L252
|
[
"def _normalize_header(key):\n return \"-\".join(part[0].upper() + part[1:].lower() for part in key.split(\"-\"))\n"
] |
class Client(SelectionMixin):
""" Wrappers for the webkit_server commands.
If `connection` is not specified, a new instance of ``ServerConnection`` is
created.
`node_factory_class` can be set to a value different from the default, in which
case a new instance of the given class will be used to create nodes. The given
class must accept a client instance through its constructor and support a
``create`` method that takes a node ID as an argument and returns a node object.
"""
def __init__(self,
connection = None,
node_factory_class = NodeFactory):
super(Client, self).__init__()
self.conn = connection or ServerConnection()
self._node_factory = node_factory_class(self)
def visit(self, url):
""" Goes to a given URL. """
self.conn.issue_command("Visit", url)
def body(self):
""" Returns the current DOM as HTML. """
return self.conn.issue_command("Body")
def source(self):
""" Returns the source of the page as it was originally
served by the web server. """
return self.conn.issue_command("Source")
def url(self):
""" Returns the current location. """
return self.conn.issue_command("CurrentUrl")
def reset(self):
""" Resets the current web session. """
self.conn.issue_command("Reset")
def status_code(self):
""" Returns the numeric HTTP status of the last response. """
return int(self.conn.issue_command("Status"))
def headers(self):
""" Returns a list of the last HTTP response headers.
Header keys are normalized to capitalized form, as in `User-Agent`.
"""
headers = self.conn.issue_command("Headers")
res = []
for header in headers.split("\r"):
key, value = header.split(": ", 1)
for line in value.split("\n"):
res.append((_normalize_header(key), line))
return res
def eval_script(self, expr):
""" Evaluates a piece of Javascript in the context of the current page and
returns its value. """
ret = self.conn.issue_command("Evaluate", expr)
return json.loads("[%s]" % ret)[0]
def exec_script(self, script):
""" Executes a piece of Javascript in the context of the current page. """
self.conn.issue_command("Execute", script)
def render(self, path, width = 1024, height = 1024):
""" Renders the current page to a PNG file (viewport size in pixels). """
self.conn.issue_command("Render", path, width, height)
def set_viewport_size(self, width, height):
""" Sets the viewport size. """
self.conn.issue_command("ResizeWindow", width, height)
def set_cookie(self, cookie):
""" Sets a cookie for future requests (must be in correct cookie string
format). """
self.conn.issue_command("SetCookie", cookie)
def clear_cookies(self):
""" Deletes all cookies. """
self.conn.issue_command("ClearCookies")
def cookies(self):
""" Returns a list of all cookies in cookie string format. """
return [line.strip()
for line in self.conn.issue_command("GetCookies").split("\n")
if line.strip()]
def set_error_tolerant(self, tolerant=True):
""" DEPRECATED! This function is a no-op now.
Used to set or unset the error tolerance flag in the server. If this flag
as set, dropped requests or erroneous responses would not lead to an error. """
return
def set_attribute(self, attr, value = True):
""" Sets a custom attribute for our Webkit instance. Possible attributes are:
* ``auto_load_images``
* ``dns_prefetch_enabled``
* ``plugins_enabled``
* ``private_browsing_enabled``
* ``javascript_can_open_windows``
* ``javascript_can_access_clipboard``
* ``offline_storage_database_enabled``
* ``offline_web_application_cache_enabled``
* ``local_storage_enabled``
* ``local_storage_database_enabled``
* ``local_content_can_access_remote_urls``
* ``local_content_can_access_file_urls``
* ``accelerated_compositing_enabled``
* ``site_specific_quirks_enabled``
For all those options, ``value`` must be a boolean. You can find more
information about these options `in the QT docs
<http://developer.qt.nokia.com/doc/qt-4.8/qwebsettings.html#WebAttribute-enum>`_.
"""
value = "true" if value else "false"
self.conn.issue_command("SetAttribute",
self._normalize_attr(attr),
value)
def reset_attribute(self, attr):
""" Resets a custom attribute. """
self.conn.issue_command("SetAttribute",
self._normalize_attr(attr),
"reset")
def set_html(self, html, url = None):
""" Sets custom HTML in our Webkit session and allows to specify a fake URL.
Scripts and CSS is dynamically fetched as if the HTML had been loaded from
the given URL. """
if url:
self.conn.issue_command('SetHtml', html, url)
else:
self.conn.issue_command('SetHtml', html)
def set_proxy(self, host = "localhost",
port = 0,
user = "",
password = ""):
""" Sets a custom HTTP proxy to use for future requests. """
self.conn.issue_command("SetProxy", host, port, user, password)
def set_timeout(self, timeout):
""" Set timeout for every webkit-server command """
self.conn.issue_command("SetTimeout", timeout)
def get_timeout(self):
""" Return timeout for every webkit-server command """
return int(self.conn.issue_command("GetTimeout"))
def clear_proxy(self):
""" Resets custom HTTP proxy (use none in future requests). """
self.conn.issue_command("ClearProxy")
def issue_node_cmd(self, *args):
""" Issues a node-specific command. """
return self.conn.issue_command("Node", *args)
def get_node_factory(self):
""" Returns the associated node factory. """
return self._node_factory
def _get_xpath_ids(self, xpath):
""" Implements a mechanism to get a list of node IDs for an absolute XPath
query. """
return self.conn.issue_command("FindXpath", xpath)
def _get_css_ids(self, css):
""" Implements a mechanism to get a list of node IDs for an absolute CSS query
query. """
return self.conn.issue_command("FindCss", css)
def _normalize_attr(self, attr):
""" Transforms a name like ``auto_load_images`` into ``AutoLoadImages``
(allows Webkit option names to blend in with Python naming). """
return ''.join(x.capitalize() for x in attr.split("_"))
|
niklasb/webkit-server
|
webkit_server.py
|
Client.headers
|
python
|
def headers(self):
headers = self.conn.issue_command("Headers")
res = []
for header in headers.split("\r"):
key, value = header.split(": ", 1)
for line in value.split("\n"):
res.append((_normalize_header(key), line))
return res
|
Returns a list of the last HTTP response headers.
Header keys are normalized to capitalized form, as in `User-Agent`.
|
train
|
https://github.com/niklasb/webkit-server/blob/c9e3a8394b8c51000c35f8a56fb770580562b544/webkit_server.py#L262-L272
|
[
"def _normalize_header(key):\n return \"-\".join(part[0].upper() + part[1:].lower() for part in key.split(\"-\"))\n"
] |
class Client(SelectionMixin):
""" Wrappers for the webkit_server commands.
If `connection` is not specified, a new instance of ``ServerConnection`` is
created.
`node_factory_class` can be set to a value different from the default, in which
case a new instance of the given class will be used to create nodes. The given
class must accept a client instance through its constructor and support a
``create`` method that takes a node ID as an argument and returns a node object.
"""
def __init__(self,
connection = None,
node_factory_class = NodeFactory):
super(Client, self).__init__()
self.conn = connection or ServerConnection()
self._node_factory = node_factory_class(self)
def visit(self, url):
""" Goes to a given URL. """
self.conn.issue_command("Visit", url)
def body(self):
""" Returns the current DOM as HTML. """
return self.conn.issue_command("Body")
def source(self):
""" Returns the source of the page as it was originally
served by the web server. """
return self.conn.issue_command("Source")
def url(self):
""" Returns the current location. """
return self.conn.issue_command("CurrentUrl")
def set_header(self, key, value):
""" Sets a HTTP header for future requests. """
self.conn.issue_command("Header", _normalize_header(key), value)
def reset(self):
""" Resets the current web session. """
self.conn.issue_command("Reset")
def status_code(self):
""" Returns the numeric HTTP status of the last response. """
return int(self.conn.issue_command("Status"))
def eval_script(self, expr):
""" Evaluates a piece of Javascript in the context of the current page and
returns its value. """
ret = self.conn.issue_command("Evaluate", expr)
return json.loads("[%s]" % ret)[0]
def exec_script(self, script):
""" Executes a piece of Javascript in the context of the current page. """
self.conn.issue_command("Execute", script)
def render(self, path, width = 1024, height = 1024):
""" Renders the current page to a PNG file (viewport size in pixels). """
self.conn.issue_command("Render", path, width, height)
def set_viewport_size(self, width, height):
""" Sets the viewport size. """
self.conn.issue_command("ResizeWindow", width, height)
def set_cookie(self, cookie):
""" Sets a cookie for future requests (must be in correct cookie string
format). """
self.conn.issue_command("SetCookie", cookie)
def clear_cookies(self):
""" Deletes all cookies. """
self.conn.issue_command("ClearCookies")
def cookies(self):
""" Returns a list of all cookies in cookie string format. """
return [line.strip()
for line in self.conn.issue_command("GetCookies").split("\n")
if line.strip()]
def set_error_tolerant(self, tolerant=True):
""" DEPRECATED! This function is a no-op now.
Used to set or unset the error tolerance flag in the server. If this flag
as set, dropped requests or erroneous responses would not lead to an error. """
return
def set_attribute(self, attr, value = True):
""" Sets a custom attribute for our Webkit instance. Possible attributes are:
* ``auto_load_images``
* ``dns_prefetch_enabled``
* ``plugins_enabled``
* ``private_browsing_enabled``
* ``javascript_can_open_windows``
* ``javascript_can_access_clipboard``
* ``offline_storage_database_enabled``
* ``offline_web_application_cache_enabled``
* ``local_storage_enabled``
* ``local_storage_database_enabled``
* ``local_content_can_access_remote_urls``
* ``local_content_can_access_file_urls``
* ``accelerated_compositing_enabled``
* ``site_specific_quirks_enabled``
For all those options, ``value`` must be a boolean. You can find more
information about these options `in the QT docs
<http://developer.qt.nokia.com/doc/qt-4.8/qwebsettings.html#WebAttribute-enum>`_.
"""
value = "true" if value else "false"
self.conn.issue_command("SetAttribute",
self._normalize_attr(attr),
value)
def reset_attribute(self, attr):
""" Resets a custom attribute. """
self.conn.issue_command("SetAttribute",
self._normalize_attr(attr),
"reset")
def set_html(self, html, url = None):
""" Sets custom HTML in our Webkit session and allows to specify a fake URL.
Scripts and CSS is dynamically fetched as if the HTML had been loaded from
the given URL. """
if url:
self.conn.issue_command('SetHtml', html, url)
else:
self.conn.issue_command('SetHtml', html)
def set_proxy(self, host = "localhost",
port = 0,
user = "",
password = ""):
""" Sets a custom HTTP proxy to use for future requests. """
self.conn.issue_command("SetProxy", host, port, user, password)
def set_timeout(self, timeout):
""" Set timeout for every webkit-server command """
self.conn.issue_command("SetTimeout", timeout)
def get_timeout(self):
""" Return timeout for every webkit-server command """
return int(self.conn.issue_command("GetTimeout"))
def clear_proxy(self):
""" Resets custom HTTP proxy (use none in future requests). """
self.conn.issue_command("ClearProxy")
def issue_node_cmd(self, *args):
""" Issues a node-specific command. """
return self.conn.issue_command("Node", *args)
def get_node_factory(self):
""" Returns the associated node factory. """
return self._node_factory
def _get_xpath_ids(self, xpath):
""" Implements a mechanism to get a list of node IDs for an absolute XPath
query. """
return self.conn.issue_command("FindXpath", xpath)
def _get_css_ids(self, css):
""" Implements a mechanism to get a list of node IDs for an absolute CSS query
query. """
return self.conn.issue_command("FindCss", css)
def _normalize_attr(self, attr):
""" Transforms a name like ``auto_load_images`` into ``AutoLoadImages``
(allows Webkit option names to blend in with Python naming). """
return ''.join(x.capitalize() for x in attr.split("_"))
|
niklasb/webkit-server
|
webkit_server.py
|
Client.eval_script
|
python
|
def eval_script(self, expr):
ret = self.conn.issue_command("Evaluate", expr)
return json.loads("[%s]" % ret)[0]
|
Evaluates a piece of Javascript in the context of the current page and
returns its value.
|
train
|
https://github.com/niklasb/webkit-server/blob/c9e3a8394b8c51000c35f8a56fb770580562b544/webkit_server.py#L274-L278
| null |
class Client(SelectionMixin):
""" Wrappers for the webkit_server commands.
If `connection` is not specified, a new instance of ``ServerConnection`` is
created.
`node_factory_class` can be set to a value different from the default, in which
case a new instance of the given class will be used to create nodes. The given
class must accept a client instance through its constructor and support a
``create`` method that takes a node ID as an argument and returns a node object.
"""
def __init__(self,
connection = None,
node_factory_class = NodeFactory):
super(Client, self).__init__()
self.conn = connection or ServerConnection()
self._node_factory = node_factory_class(self)
def visit(self, url):
""" Goes to a given URL. """
self.conn.issue_command("Visit", url)
def body(self):
""" Returns the current DOM as HTML. """
return self.conn.issue_command("Body")
def source(self):
""" Returns the source of the page as it was originally
served by the web server. """
return self.conn.issue_command("Source")
def url(self):
""" Returns the current location. """
return self.conn.issue_command("CurrentUrl")
def set_header(self, key, value):
""" Sets a HTTP header for future requests. """
self.conn.issue_command("Header", _normalize_header(key), value)
def reset(self):
""" Resets the current web session. """
self.conn.issue_command("Reset")
def status_code(self):
""" Returns the numeric HTTP status of the last response. """
return int(self.conn.issue_command("Status"))
def headers(self):
""" Returns a list of the last HTTP response headers.
Header keys are normalized to capitalized form, as in `User-Agent`.
"""
headers = self.conn.issue_command("Headers")
res = []
for header in headers.split("\r"):
key, value = header.split(": ", 1)
for line in value.split("\n"):
res.append((_normalize_header(key), line))
return res
def exec_script(self, script):
""" Executes a piece of Javascript in the context of the current page. """
self.conn.issue_command("Execute", script)
def render(self, path, width = 1024, height = 1024):
""" Renders the current page to a PNG file (viewport size in pixels). """
self.conn.issue_command("Render", path, width, height)
def set_viewport_size(self, width, height):
""" Sets the viewport size. """
self.conn.issue_command("ResizeWindow", width, height)
def set_cookie(self, cookie):
""" Sets a cookie for future requests (must be in correct cookie string
format). """
self.conn.issue_command("SetCookie", cookie)
def clear_cookies(self):
""" Deletes all cookies. """
self.conn.issue_command("ClearCookies")
def cookies(self):
""" Returns a list of all cookies in cookie string format. """
return [line.strip()
for line in self.conn.issue_command("GetCookies").split("\n")
if line.strip()]
def set_error_tolerant(self, tolerant=True):
""" DEPRECATED! This function is a no-op now.
Used to set or unset the error tolerance flag in the server. If this flag
as set, dropped requests or erroneous responses would not lead to an error. """
return
def set_attribute(self, attr, value = True):
""" Sets a custom attribute for our Webkit instance. Possible attributes are:
* ``auto_load_images``
* ``dns_prefetch_enabled``
* ``plugins_enabled``
* ``private_browsing_enabled``
* ``javascript_can_open_windows``
* ``javascript_can_access_clipboard``
* ``offline_storage_database_enabled``
* ``offline_web_application_cache_enabled``
* ``local_storage_enabled``
* ``local_storage_database_enabled``
* ``local_content_can_access_remote_urls``
* ``local_content_can_access_file_urls``
* ``accelerated_compositing_enabled``
* ``site_specific_quirks_enabled``
For all those options, ``value`` must be a boolean. You can find more
information about these options `in the QT docs
<http://developer.qt.nokia.com/doc/qt-4.8/qwebsettings.html#WebAttribute-enum>`_.
"""
value = "true" if value else "false"
self.conn.issue_command("SetAttribute",
self._normalize_attr(attr),
value)
def reset_attribute(self, attr):
""" Resets a custom attribute. """
self.conn.issue_command("SetAttribute",
self._normalize_attr(attr),
"reset")
def set_html(self, html, url = None):
""" Sets custom HTML in our Webkit session and allows to specify a fake URL.
Scripts and CSS is dynamically fetched as if the HTML had been loaded from
the given URL. """
if url:
self.conn.issue_command('SetHtml', html, url)
else:
self.conn.issue_command('SetHtml', html)
def set_proxy(self, host = "localhost",
port = 0,
user = "",
password = ""):
""" Sets a custom HTTP proxy to use for future requests. """
self.conn.issue_command("SetProxy", host, port, user, password)
def set_timeout(self, timeout):
""" Set timeout for every webkit-server command """
self.conn.issue_command("SetTimeout", timeout)
def get_timeout(self):
""" Return timeout for every webkit-server command """
return int(self.conn.issue_command("GetTimeout"))
def clear_proxy(self):
""" Resets custom HTTP proxy (use none in future requests). """
self.conn.issue_command("ClearProxy")
def issue_node_cmd(self, *args):
""" Issues a node-specific command. """
return self.conn.issue_command("Node", *args)
def get_node_factory(self):
""" Returns the associated node factory. """
return self._node_factory
def _get_xpath_ids(self, xpath):
""" Implements a mechanism to get a list of node IDs for an absolute XPath
query. """
return self.conn.issue_command("FindXpath", xpath)
def _get_css_ids(self, css):
""" Implements a mechanism to get a list of node IDs for an absolute CSS query
query. """
return self.conn.issue_command("FindCss", css)
def _normalize_attr(self, attr):
""" Transforms a name like ``auto_load_images`` into ``AutoLoadImages``
(allows Webkit option names to blend in with Python naming). """
return ''.join(x.capitalize() for x in attr.split("_"))
|
niklasb/webkit-server
|
webkit_server.py
|
Client.render
|
python
|
def render(self, path, width = 1024, height = 1024):
self.conn.issue_command("Render", path, width, height)
|
Renders the current page to a PNG file (viewport size in pixels).
|
train
|
https://github.com/niklasb/webkit-server/blob/c9e3a8394b8c51000c35f8a56fb770580562b544/webkit_server.py#L284-L286
| null |
class Client(SelectionMixin):
""" Wrappers for the webkit_server commands.
If `connection` is not specified, a new instance of ``ServerConnection`` is
created.
`node_factory_class` can be set to a value different from the default, in which
case a new instance of the given class will be used to create nodes. The given
class must accept a client instance through its constructor and support a
``create`` method that takes a node ID as an argument and returns a node object.
"""
def __init__(self,
connection = None,
node_factory_class = NodeFactory):
super(Client, self).__init__()
self.conn = connection or ServerConnection()
self._node_factory = node_factory_class(self)
def visit(self, url):
""" Goes to a given URL. """
self.conn.issue_command("Visit", url)
def body(self):
""" Returns the current DOM as HTML. """
return self.conn.issue_command("Body")
def source(self):
""" Returns the source of the page as it was originally
served by the web server. """
return self.conn.issue_command("Source")
def url(self):
""" Returns the current location. """
return self.conn.issue_command("CurrentUrl")
def set_header(self, key, value):
""" Sets a HTTP header for future requests. """
self.conn.issue_command("Header", _normalize_header(key), value)
def reset(self):
""" Resets the current web session. """
self.conn.issue_command("Reset")
def status_code(self):
""" Returns the numeric HTTP status of the last response. """
return int(self.conn.issue_command("Status"))
def headers(self):
""" Returns a list of the last HTTP response headers.
Header keys are normalized to capitalized form, as in `User-Agent`.
"""
headers = self.conn.issue_command("Headers")
res = []
for header in headers.split("\r"):
key, value = header.split(": ", 1)
for line in value.split("\n"):
res.append((_normalize_header(key), line))
return res
def eval_script(self, expr):
""" Evaluates a piece of Javascript in the context of the current page and
returns its value. """
ret = self.conn.issue_command("Evaluate", expr)
return json.loads("[%s]" % ret)[0]
def exec_script(self, script):
""" Executes a piece of Javascript in the context of the current page. """
self.conn.issue_command("Execute", script)
def set_viewport_size(self, width, height):
""" Sets the viewport size. """
self.conn.issue_command("ResizeWindow", width, height)
def set_cookie(self, cookie):
""" Sets a cookie for future requests (must be in correct cookie string
format). """
self.conn.issue_command("SetCookie", cookie)
def clear_cookies(self):
""" Deletes all cookies. """
self.conn.issue_command("ClearCookies")
def cookies(self):
""" Returns a list of all cookies in cookie string format. """
return [line.strip()
for line in self.conn.issue_command("GetCookies").split("\n")
if line.strip()]
def set_error_tolerant(self, tolerant=True):
""" DEPRECATED! This function is a no-op now.
Used to set or unset the error tolerance flag in the server. If this flag
as set, dropped requests or erroneous responses would not lead to an error. """
return
def set_attribute(self, attr, value = True):
""" Sets a custom attribute for our Webkit instance. Possible attributes are:
* ``auto_load_images``
* ``dns_prefetch_enabled``
* ``plugins_enabled``
* ``private_browsing_enabled``
* ``javascript_can_open_windows``
* ``javascript_can_access_clipboard``
* ``offline_storage_database_enabled``
* ``offline_web_application_cache_enabled``
* ``local_storage_enabled``
* ``local_storage_database_enabled``
* ``local_content_can_access_remote_urls``
* ``local_content_can_access_file_urls``
* ``accelerated_compositing_enabled``
* ``site_specific_quirks_enabled``
For all those options, ``value`` must be a boolean. You can find more
information about these options `in the QT docs
<http://developer.qt.nokia.com/doc/qt-4.8/qwebsettings.html#WebAttribute-enum>`_.
"""
value = "true" if value else "false"
self.conn.issue_command("SetAttribute",
self._normalize_attr(attr),
value)
def reset_attribute(self, attr):
""" Resets a custom attribute. """
self.conn.issue_command("SetAttribute",
self._normalize_attr(attr),
"reset")
def set_html(self, html, url = None):
""" Sets custom HTML in our Webkit session and allows to specify a fake URL.
Scripts and CSS is dynamically fetched as if the HTML had been loaded from
the given URL. """
if url:
self.conn.issue_command('SetHtml', html, url)
else:
self.conn.issue_command('SetHtml', html)
def set_proxy(self, host = "localhost",
port = 0,
user = "",
password = ""):
""" Sets a custom HTTP proxy to use for future requests. """
self.conn.issue_command("SetProxy", host, port, user, password)
def set_timeout(self, timeout):
""" Set timeout for every webkit-server command """
self.conn.issue_command("SetTimeout", timeout)
def get_timeout(self):
""" Return timeout for every webkit-server command """
return int(self.conn.issue_command("GetTimeout"))
def clear_proxy(self):
""" Resets custom HTTP proxy (use none in future requests). """
self.conn.issue_command("ClearProxy")
def issue_node_cmd(self, *args):
""" Issues a node-specific command. """
return self.conn.issue_command("Node", *args)
def get_node_factory(self):
""" Returns the associated node factory. """
return self._node_factory
def _get_xpath_ids(self, xpath):
""" Implements a mechanism to get a list of node IDs for an absolute XPath
query. """
return self.conn.issue_command("FindXpath", xpath)
def _get_css_ids(self, css):
""" Implements a mechanism to get a list of node IDs for an absolute CSS query
query. """
return self.conn.issue_command("FindCss", css)
def _normalize_attr(self, attr):
""" Transforms a name like ``auto_load_images`` into ``AutoLoadImages``
(allows Webkit option names to blend in with Python naming). """
return ''.join(x.capitalize() for x in attr.split("_"))
|
niklasb/webkit-server
|
webkit_server.py
|
Client.cookies
|
python
|
def cookies(self):
return [line.strip()
for line in self.conn.issue_command("GetCookies").split("\n")
if line.strip()]
|
Returns a list of all cookies in cookie string format.
|
train
|
https://github.com/niklasb/webkit-server/blob/c9e3a8394b8c51000c35f8a56fb770580562b544/webkit_server.py#L301-L305
| null |
class Client(SelectionMixin):
""" Wrappers for the webkit_server commands.
If `connection` is not specified, a new instance of ``ServerConnection`` is
created.
`node_factory_class` can be set to a value different from the default, in which
case a new instance of the given class will be used to create nodes. The given
class must accept a client instance through its constructor and support a
``create`` method that takes a node ID as an argument and returns a node object.
"""
def __init__(self,
connection = None,
node_factory_class = NodeFactory):
super(Client, self).__init__()
self.conn = connection or ServerConnection()
self._node_factory = node_factory_class(self)
def visit(self, url):
""" Goes to a given URL. """
self.conn.issue_command("Visit", url)
def body(self):
""" Returns the current DOM as HTML. """
return self.conn.issue_command("Body")
def source(self):
""" Returns the source of the page as it was originally
served by the web server. """
return self.conn.issue_command("Source")
def url(self):
""" Returns the current location. """
return self.conn.issue_command("CurrentUrl")
def set_header(self, key, value):
""" Sets a HTTP header for future requests. """
self.conn.issue_command("Header", _normalize_header(key), value)
def reset(self):
""" Resets the current web session. """
self.conn.issue_command("Reset")
def status_code(self):
""" Returns the numeric HTTP status of the last response. """
return int(self.conn.issue_command("Status"))
def headers(self):
""" Returns a list of the last HTTP response headers.
Header keys are normalized to capitalized form, as in `User-Agent`.
"""
headers = self.conn.issue_command("Headers")
res = []
for header in headers.split("\r"):
key, value = header.split(": ", 1)
for line in value.split("\n"):
res.append((_normalize_header(key), line))
return res
def eval_script(self, expr):
""" Evaluates a piece of Javascript in the context of the current page and
returns its value. """
ret = self.conn.issue_command("Evaluate", expr)
return json.loads("[%s]" % ret)[0]
def exec_script(self, script):
""" Executes a piece of Javascript in the context of the current page. """
self.conn.issue_command("Execute", script)
def render(self, path, width = 1024, height = 1024):
""" Renders the current page to a PNG file (viewport size in pixels). """
self.conn.issue_command("Render", path, width, height)
def set_viewport_size(self, width, height):
""" Sets the viewport size. """
self.conn.issue_command("ResizeWindow", width, height)
def set_cookie(self, cookie):
""" Sets a cookie for future requests (must be in correct cookie string
format). """
self.conn.issue_command("SetCookie", cookie)
def clear_cookies(self):
""" Deletes all cookies. """
self.conn.issue_command("ClearCookies")
def set_error_tolerant(self, tolerant=True):
""" DEPRECATED! This function is a no-op now.
Used to set or unset the error tolerance flag in the server. If this flag
as set, dropped requests or erroneous responses would not lead to an error. """
return
def set_attribute(self, attr, value = True):
""" Sets a custom attribute for our Webkit instance. Possible attributes are:
* ``auto_load_images``
* ``dns_prefetch_enabled``
* ``plugins_enabled``
* ``private_browsing_enabled``
* ``javascript_can_open_windows``
* ``javascript_can_access_clipboard``
* ``offline_storage_database_enabled``
* ``offline_web_application_cache_enabled``
* ``local_storage_enabled``
* ``local_storage_database_enabled``
* ``local_content_can_access_remote_urls``
* ``local_content_can_access_file_urls``
* ``accelerated_compositing_enabled``
* ``site_specific_quirks_enabled``
For all those options, ``value`` must be a boolean. You can find more
information about these options `in the QT docs
<http://developer.qt.nokia.com/doc/qt-4.8/qwebsettings.html#WebAttribute-enum>`_.
"""
value = "true" if value else "false"
self.conn.issue_command("SetAttribute",
self._normalize_attr(attr),
value)
def reset_attribute(self, attr):
""" Resets a custom attribute. """
self.conn.issue_command("SetAttribute",
self._normalize_attr(attr),
"reset")
def set_html(self, html, url = None):
""" Sets custom HTML in our Webkit session and allows to specify a fake URL.
Scripts and CSS is dynamically fetched as if the HTML had been loaded from
the given URL. """
if url:
self.conn.issue_command('SetHtml', html, url)
else:
self.conn.issue_command('SetHtml', html)
def set_proxy(self, host = "localhost",
port = 0,
user = "",
password = ""):
""" Sets a custom HTTP proxy to use for future requests. """
self.conn.issue_command("SetProxy", host, port, user, password)
def set_timeout(self, timeout):
""" Set timeout for every webkit-server command """
self.conn.issue_command("SetTimeout", timeout)
def get_timeout(self):
""" Return timeout for every webkit-server command """
return int(self.conn.issue_command("GetTimeout"))
def clear_proxy(self):
""" Resets custom HTTP proxy (use none in future requests). """
self.conn.issue_command("ClearProxy")
def issue_node_cmd(self, *args):
""" Issues a node-specific command. """
return self.conn.issue_command("Node", *args)
def get_node_factory(self):
""" Returns the associated node factory. """
return self._node_factory
def _get_xpath_ids(self, xpath):
""" Implements a mechanism to get a list of node IDs for an absolute XPath
query. """
return self.conn.issue_command("FindXpath", xpath)
def _get_css_ids(self, css):
""" Implements a mechanism to get a list of node IDs for an absolute CSS query
query. """
return self.conn.issue_command("FindCss", css)
def _normalize_attr(self, attr):
""" Transforms a name like ``auto_load_images`` into ``AutoLoadImages``
(allows Webkit option names to blend in with Python naming). """
return ''.join(x.capitalize() for x in attr.split("_"))
|
niklasb/webkit-server
|
webkit_server.py
|
Client.set_attribute
|
python
|
def set_attribute(self, attr, value = True):
value = "true" if value else "false"
self.conn.issue_command("SetAttribute",
self._normalize_attr(attr),
value)
|
Sets a custom attribute for our Webkit instance. Possible attributes are:
* ``auto_load_images``
* ``dns_prefetch_enabled``
* ``plugins_enabled``
* ``private_browsing_enabled``
* ``javascript_can_open_windows``
* ``javascript_can_access_clipboard``
* ``offline_storage_database_enabled``
* ``offline_web_application_cache_enabled``
* ``local_storage_enabled``
* ``local_storage_database_enabled``
* ``local_content_can_access_remote_urls``
* ``local_content_can_access_file_urls``
* ``accelerated_compositing_enabled``
* ``site_specific_quirks_enabled``
For all those options, ``value`` must be a boolean. You can find more
information about these options `in the QT docs
<http://developer.qt.nokia.com/doc/qt-4.8/qwebsettings.html#WebAttribute-enum>`_.
|
train
|
https://github.com/niklasb/webkit-server/blob/c9e3a8394b8c51000c35f8a56fb770580562b544/webkit_server.py#L314-L339
|
[
"def _normalize_attr(self, attr):\n \"\"\" Transforms a name like ``auto_load_images`` into ``AutoLoadImages``\n (allows Webkit option names to blend in with Python naming). \"\"\"\n return ''.join(x.capitalize() for x in attr.split(\"_\"))\n"
] |
class Client(SelectionMixin):
""" Wrappers for the webkit_server commands.
If `connection` is not specified, a new instance of ``ServerConnection`` is
created.
`node_factory_class` can be set to a value different from the default, in which
case a new instance of the given class will be used to create nodes. The given
class must accept a client instance through its constructor and support a
``create`` method that takes a node ID as an argument and returns a node object.
"""
def __init__(self,
connection = None,
node_factory_class = NodeFactory):
super(Client, self).__init__()
self.conn = connection or ServerConnection()
self._node_factory = node_factory_class(self)
def visit(self, url):
""" Goes to a given URL. """
self.conn.issue_command("Visit", url)
def body(self):
""" Returns the current DOM as HTML. """
return self.conn.issue_command("Body")
def source(self):
""" Returns the source of the page as it was originally
served by the web server. """
return self.conn.issue_command("Source")
def url(self):
""" Returns the current location. """
return self.conn.issue_command("CurrentUrl")
def set_header(self, key, value):
""" Sets a HTTP header for future requests. """
self.conn.issue_command("Header", _normalize_header(key), value)
def reset(self):
""" Resets the current web session. """
self.conn.issue_command("Reset")
def status_code(self):
""" Returns the numeric HTTP status of the last response. """
return int(self.conn.issue_command("Status"))
def headers(self):
""" Returns a list of the last HTTP response headers.
Header keys are normalized to capitalized form, as in `User-Agent`.
"""
headers = self.conn.issue_command("Headers")
res = []
for header in headers.split("\r"):
key, value = header.split(": ", 1)
for line in value.split("\n"):
res.append((_normalize_header(key), line))
return res
def eval_script(self, expr):
""" Evaluates a piece of Javascript in the context of the current page and
returns its value. """
ret = self.conn.issue_command("Evaluate", expr)
return json.loads("[%s]" % ret)[0]
def exec_script(self, script):
""" Executes a piece of Javascript in the context of the current page. """
self.conn.issue_command("Execute", script)
def render(self, path, width = 1024, height = 1024):
""" Renders the current page to a PNG file (viewport size in pixels). """
self.conn.issue_command("Render", path, width, height)
def set_viewport_size(self, width, height):
""" Sets the viewport size. """
self.conn.issue_command("ResizeWindow", width, height)
def set_cookie(self, cookie):
""" Sets a cookie for future requests (must be in correct cookie string
format). """
self.conn.issue_command("SetCookie", cookie)
def clear_cookies(self):
""" Deletes all cookies. """
self.conn.issue_command("ClearCookies")
def cookies(self):
""" Returns a list of all cookies in cookie string format. """
return [line.strip()
for line in self.conn.issue_command("GetCookies").split("\n")
if line.strip()]
def set_error_tolerant(self, tolerant=True):
""" DEPRECATED! This function is a no-op now.
Used to set or unset the error tolerance flag in the server. If this flag
as set, dropped requests or erroneous responses would not lead to an error. """
return
def reset_attribute(self, attr):
""" Resets a custom attribute. """
self.conn.issue_command("SetAttribute",
self._normalize_attr(attr),
"reset")
def set_html(self, html, url = None):
""" Sets custom HTML in our Webkit session and allows to specify a fake URL.
Scripts and CSS is dynamically fetched as if the HTML had been loaded from
the given URL. """
if url:
self.conn.issue_command('SetHtml', html, url)
else:
self.conn.issue_command('SetHtml', html)
def set_proxy(self, host = "localhost",
port = 0,
user = "",
password = ""):
""" Sets a custom HTTP proxy to use for future requests. """
self.conn.issue_command("SetProxy", host, port, user, password)
def set_timeout(self, timeout):
""" Set timeout for every webkit-server command """
self.conn.issue_command("SetTimeout", timeout)
def get_timeout(self):
""" Return timeout for every webkit-server command """
return int(self.conn.issue_command("GetTimeout"))
def clear_proxy(self):
""" Resets custom HTTP proxy (use none in future requests). """
self.conn.issue_command("ClearProxy")
def issue_node_cmd(self, *args):
""" Issues a node-specific command. """
return self.conn.issue_command("Node", *args)
def get_node_factory(self):
""" Returns the associated node factory. """
return self._node_factory
def _get_xpath_ids(self, xpath):
""" Implements a mechanism to get a list of node IDs for an absolute XPath
query. """
return self.conn.issue_command("FindXpath", xpath)
def _get_css_ids(self, css):
""" Implements a mechanism to get a list of node IDs for an absolute CSS query
query. """
return self.conn.issue_command("FindCss", css)
def _normalize_attr(self, attr):
""" Transforms a name like ``auto_load_images`` into ``AutoLoadImages``
(allows Webkit option names to blend in with Python naming). """
return ''.join(x.capitalize() for x in attr.split("_"))
|
niklasb/webkit-server
|
webkit_server.py
|
Client.set_html
|
python
|
def set_html(self, html, url = None):
if url:
self.conn.issue_command('SetHtml', html, url)
else:
self.conn.issue_command('SetHtml', html)
|
Sets custom HTML in our Webkit session and allows to specify a fake URL.
Scripts and CSS is dynamically fetched as if the HTML had been loaded from
the given URL.
|
train
|
https://github.com/niklasb/webkit-server/blob/c9e3a8394b8c51000c35f8a56fb770580562b544/webkit_server.py#L347-L354
| null |
class Client(SelectionMixin):
""" Wrappers for the webkit_server commands.
If `connection` is not specified, a new instance of ``ServerConnection`` is
created.
`node_factory_class` can be set to a value different from the default, in which
case a new instance of the given class will be used to create nodes. The given
class must accept a client instance through its constructor and support a
``create`` method that takes a node ID as an argument and returns a node object.
"""
def __init__(self,
connection = None,
node_factory_class = NodeFactory):
super(Client, self).__init__()
self.conn = connection or ServerConnection()
self._node_factory = node_factory_class(self)
def visit(self, url):
""" Goes to a given URL. """
self.conn.issue_command("Visit", url)
def body(self):
""" Returns the current DOM as HTML. """
return self.conn.issue_command("Body")
def source(self):
""" Returns the source of the page as it was originally
served by the web server. """
return self.conn.issue_command("Source")
def url(self):
""" Returns the current location. """
return self.conn.issue_command("CurrentUrl")
def set_header(self, key, value):
""" Sets a HTTP header for future requests. """
self.conn.issue_command("Header", _normalize_header(key), value)
def reset(self):
""" Resets the current web session. """
self.conn.issue_command("Reset")
def status_code(self):
""" Returns the numeric HTTP status of the last response. """
return int(self.conn.issue_command("Status"))
def headers(self):
""" Returns a list of the last HTTP response headers.
Header keys are normalized to capitalized form, as in `User-Agent`.
"""
headers = self.conn.issue_command("Headers")
res = []
for header in headers.split("\r"):
key, value = header.split(": ", 1)
for line in value.split("\n"):
res.append((_normalize_header(key), line))
return res
def eval_script(self, expr):
""" Evaluates a piece of Javascript in the context of the current page and
returns its value. """
ret = self.conn.issue_command("Evaluate", expr)
return json.loads("[%s]" % ret)[0]
def exec_script(self, script):
""" Executes a piece of Javascript in the context of the current page. """
self.conn.issue_command("Execute", script)
def render(self, path, width = 1024, height = 1024):
""" Renders the current page to a PNG file (viewport size in pixels). """
self.conn.issue_command("Render", path, width, height)
def set_viewport_size(self, width, height):
""" Sets the viewport size. """
self.conn.issue_command("ResizeWindow", width, height)
def set_cookie(self, cookie):
""" Sets a cookie for future requests (must be in correct cookie string
format). """
self.conn.issue_command("SetCookie", cookie)
def clear_cookies(self):
""" Deletes all cookies. """
self.conn.issue_command("ClearCookies")
def cookies(self):
""" Returns a list of all cookies in cookie string format. """
return [line.strip()
for line in self.conn.issue_command("GetCookies").split("\n")
if line.strip()]
def set_error_tolerant(self, tolerant=True):
""" DEPRECATED! This function is a no-op now.
Used to set or unset the error tolerance flag in the server. If this flag
as set, dropped requests or erroneous responses would not lead to an error. """
return
def set_attribute(self, attr, value = True):
""" Sets a custom attribute for our Webkit instance. Possible attributes are:
* ``auto_load_images``
* ``dns_prefetch_enabled``
* ``plugins_enabled``
* ``private_browsing_enabled``
* ``javascript_can_open_windows``
* ``javascript_can_access_clipboard``
* ``offline_storage_database_enabled``
* ``offline_web_application_cache_enabled``
* ``local_storage_enabled``
* ``local_storage_database_enabled``
* ``local_content_can_access_remote_urls``
* ``local_content_can_access_file_urls``
* ``accelerated_compositing_enabled``
* ``site_specific_quirks_enabled``
For all those options, ``value`` must be a boolean. You can find more
information about these options `in the QT docs
<http://developer.qt.nokia.com/doc/qt-4.8/qwebsettings.html#WebAttribute-enum>`_.
"""
value = "true" if value else "false"
self.conn.issue_command("SetAttribute",
self._normalize_attr(attr),
value)
def reset_attribute(self, attr):
""" Resets a custom attribute. """
self.conn.issue_command("SetAttribute",
self._normalize_attr(attr),
"reset")
def set_proxy(self, host = "localhost",
port = 0,
user = "",
password = ""):
""" Sets a custom HTTP proxy to use for future requests. """
self.conn.issue_command("SetProxy", host, port, user, password)
def set_timeout(self, timeout):
""" Set timeout for every webkit-server command """
self.conn.issue_command("SetTimeout", timeout)
def get_timeout(self):
""" Return timeout for every webkit-server command """
return int(self.conn.issue_command("GetTimeout"))
def clear_proxy(self):
""" Resets custom HTTP proxy (use none in future requests). """
self.conn.issue_command("ClearProxy")
def issue_node_cmd(self, *args):
""" Issues a node-specific command. """
return self.conn.issue_command("Node", *args)
def get_node_factory(self):
""" Returns the associated node factory. """
return self._node_factory
def _get_xpath_ids(self, xpath):
""" Implements a mechanism to get a list of node IDs for an absolute XPath
query. """
return self.conn.issue_command("FindXpath", xpath)
def _get_css_ids(self, css):
""" Implements a mechanism to get a list of node IDs for an absolute CSS query
query. """
return self.conn.issue_command("FindCss", css)
def _normalize_attr(self, attr):
""" Transforms a name like ``auto_load_images`` into ``AutoLoadImages``
(allows Webkit option names to blend in with Python naming). """
return ''.join(x.capitalize() for x in attr.split("_"))
|
niklasb/webkit-server
|
webkit_server.py
|
Client.set_proxy
|
python
|
def set_proxy(self, host = "localhost",
port = 0,
user = "",
password = ""):
self.conn.issue_command("SetProxy", host, port, user, password)
|
Sets a custom HTTP proxy to use for future requests.
|
train
|
https://github.com/niklasb/webkit-server/blob/c9e3a8394b8c51000c35f8a56fb770580562b544/webkit_server.py#L356-L361
| null |
class Client(SelectionMixin):
""" Wrappers for the webkit_server commands.
If `connection` is not specified, a new instance of ``ServerConnection`` is
created.
`node_factory_class` can be set to a value different from the default, in which
case a new instance of the given class will be used to create nodes. The given
class must accept a client instance through its constructor and support a
``create`` method that takes a node ID as an argument and returns a node object.
"""
def __init__(self,
connection = None,
node_factory_class = NodeFactory):
super(Client, self).__init__()
self.conn = connection or ServerConnection()
self._node_factory = node_factory_class(self)
def visit(self, url):
""" Goes to a given URL. """
self.conn.issue_command("Visit", url)
def body(self):
""" Returns the current DOM as HTML. """
return self.conn.issue_command("Body")
def source(self):
""" Returns the source of the page as it was originally
served by the web server. """
return self.conn.issue_command("Source")
def url(self):
""" Returns the current location. """
return self.conn.issue_command("CurrentUrl")
def set_header(self, key, value):
""" Sets a HTTP header for future requests. """
self.conn.issue_command("Header", _normalize_header(key), value)
def reset(self):
""" Resets the current web session. """
self.conn.issue_command("Reset")
def status_code(self):
""" Returns the numeric HTTP status of the last response. """
return int(self.conn.issue_command("Status"))
def headers(self):
""" Returns a list of the last HTTP response headers.
Header keys are normalized to capitalized form, as in `User-Agent`.
"""
headers = self.conn.issue_command("Headers")
res = []
for header in headers.split("\r"):
key, value = header.split(": ", 1)
for line in value.split("\n"):
res.append((_normalize_header(key), line))
return res
def eval_script(self, expr):
""" Evaluates a piece of Javascript in the context of the current page and
returns its value. """
ret = self.conn.issue_command("Evaluate", expr)
return json.loads("[%s]" % ret)[0]
def exec_script(self, script):
""" Executes a piece of Javascript in the context of the current page. """
self.conn.issue_command("Execute", script)
def render(self, path, width = 1024, height = 1024):
""" Renders the current page to a PNG file (viewport size in pixels). """
self.conn.issue_command("Render", path, width, height)
def set_viewport_size(self, width, height):
""" Sets the viewport size. """
self.conn.issue_command("ResizeWindow", width, height)
def set_cookie(self, cookie):
""" Sets a cookie for future requests (must be in correct cookie string
format). """
self.conn.issue_command("SetCookie", cookie)
def clear_cookies(self):
""" Deletes all cookies. """
self.conn.issue_command("ClearCookies")
def cookies(self):
""" Returns a list of all cookies in cookie string format. """
return [line.strip()
for line in self.conn.issue_command("GetCookies").split("\n")
if line.strip()]
def set_error_tolerant(self, tolerant=True):
""" DEPRECATED! This function is a no-op now.
Used to set or unset the error tolerance flag in the server. If this flag
as set, dropped requests or erroneous responses would not lead to an error. """
return
def set_attribute(self, attr, value = True):
""" Sets a custom attribute for our Webkit instance. Possible attributes are:
* ``auto_load_images``
* ``dns_prefetch_enabled``
* ``plugins_enabled``
* ``private_browsing_enabled``
* ``javascript_can_open_windows``
* ``javascript_can_access_clipboard``
* ``offline_storage_database_enabled``
* ``offline_web_application_cache_enabled``
* ``local_storage_enabled``
* ``local_storage_database_enabled``
* ``local_content_can_access_remote_urls``
* ``local_content_can_access_file_urls``
* ``accelerated_compositing_enabled``
* ``site_specific_quirks_enabled``
For all those options, ``value`` must be a boolean. You can find more
information about these options `in the QT docs
<http://developer.qt.nokia.com/doc/qt-4.8/qwebsettings.html#WebAttribute-enum>`_.
"""
value = "true" if value else "false"
self.conn.issue_command("SetAttribute",
self._normalize_attr(attr),
value)
def reset_attribute(self, attr):
""" Resets a custom attribute. """
self.conn.issue_command("SetAttribute",
self._normalize_attr(attr),
"reset")
def set_html(self, html, url = None):
""" Sets custom HTML in our Webkit session and allows to specify a fake URL.
Scripts and CSS is dynamically fetched as if the HTML had been loaded from
the given URL. """
if url:
self.conn.issue_command('SetHtml', html, url)
else:
self.conn.issue_command('SetHtml', html)
def set_timeout(self, timeout):
""" Set timeout for every webkit-server command """
self.conn.issue_command("SetTimeout", timeout)
def get_timeout(self):
""" Return timeout for every webkit-server command """
return int(self.conn.issue_command("GetTimeout"))
def clear_proxy(self):
""" Resets custom HTTP proxy (use none in future requests). """
self.conn.issue_command("ClearProxy")
def issue_node_cmd(self, *args):
""" Issues a node-specific command. """
return self.conn.issue_command("Node", *args)
def get_node_factory(self):
""" Returns the associated node factory. """
return self._node_factory
def _get_xpath_ids(self, xpath):
""" Implements a mechanism to get a list of node IDs for an absolute XPath
query. """
return self.conn.issue_command("FindXpath", xpath)
def _get_css_ids(self, css):
""" Implements a mechanism to get a list of node IDs for an absolute CSS query
query. """
return self.conn.issue_command("FindCss", css)
def _normalize_attr(self, attr):
""" Transforms a name like ``auto_load_images`` into ``AutoLoadImages``
(allows Webkit option names to blend in with Python naming). """
return ''.join(x.capitalize() for x in attr.split("_"))
|
niklasb/webkit-server
|
webkit_server.py
|
Server.connect
|
python
|
def connect(self):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(("127.0.0.1", self._port))
return sock
|
Returns a new socket connection to this server.
|
train
|
https://github.com/niklasb/webkit-server/blob/c9e3a8394b8c51000c35f8a56fb770580562b544/webkit_server.py#L437-L441
| null |
class Server(object):
""" Manages a Webkit server process. If `binary` is given, the specified
``webkit_server`` binary is used instead of the included one. """
def __init__(self, binary = None):
binary = binary or SERVER_EXEC
self._server = subprocess.Popen([binary],
stdin = subprocess.PIPE,
stdout = subprocess.PIPE,
stderr = subprocess.PIPE)
output = self._server.stdout.readline()
try:
self._port = int(re.search(b"port: (\d+)", output).group(1))
except AttributeError:
err = self._server.stderr.read().decode("utf-8")
if "Could not connect to display" in err:
raise NoX11Error("Could not connect to X server. "
"Try calling dryscrape.start_xvfb() before creating a session.")
else:
raise WebkitServerError("webkit-server failed to start. Output:\n" + err)
# on program termination, kill the server instance
atexit.register(self.kill)
def kill(self):
""" Kill the process. """
self._server.kill()
self._server.communicate()
|
niklasb/webkit-server
|
webkit_server.py
|
SocketBuffer.read_line
|
python
|
def read_line(self):
while True:
newline_idx = self.buf.find(b"\n")
if newline_idx >= 0:
res = self.buf[:newline_idx]
self.buf = self.buf[newline_idx + 1:]
return res
chunk = self.f.recv(4096)
if not chunk:
raise EndOfStreamError()
self.buf += chunk
|
Consume one line from the stream.
|
train
|
https://github.com/niklasb/webkit-server/blob/c9e3a8394b8c51000c35f8a56fb770580562b544/webkit_server.py#L475-L486
| null |
class SocketBuffer(object):
""" A convenience class for buffered reads from a socket. """
def __init__(self, f):
""" `f` is expected to be an open socket. """
self.f = f
self.buf = b''
def read(self, n):
""" Consume `n` characters from the stream. """
while len(self.buf) < n:
chunk = self.f.recv(4096)
if not chunk:
raise EndOfStreamError()
self.buf += chunk
res, self.buf = self.buf[:n], self.buf[n:]
return res
|
niklasb/webkit-server
|
webkit_server.py
|
SocketBuffer.read
|
python
|
def read(self, n):
while len(self.buf) < n:
chunk = self.f.recv(4096)
if not chunk:
raise EndOfStreamError()
self.buf += chunk
res, self.buf = self.buf[:n], self.buf[n:]
return res
|
Consume `n` characters from the stream.
|
train
|
https://github.com/niklasb/webkit-server/blob/c9e3a8394b8c51000c35f8a56fb770580562b544/webkit_server.py#L488-L496
| null |
class SocketBuffer(object):
""" A convenience class for buffered reads from a socket. """
def __init__(self, f):
""" `f` is expected to be an open socket. """
self.f = f
self.buf = b''
def read_line(self):
""" Consume one line from the stream. """
while True:
newline_idx = self.buf.find(b"\n")
if newline_idx >= 0:
res = self.buf[:newline_idx]
self.buf = self.buf[newline_idx + 1:]
return res
chunk = self.f.recv(4096)
if not chunk:
raise EndOfStreamError()
self.buf += chunk
|
niklasb/webkit-server
|
webkit_server.py
|
ServerConnection.issue_command
|
python
|
def issue_command(self, cmd, *args):
self._writeline(cmd)
self._writeline(str(len(args)))
for arg in args:
arg = str(arg)
self._writeline(str(len(arg)))
self._sock.sendall(arg.encode("utf-8"))
return self._read_response()
|
Sends and receives a message to/from the server
|
train
|
https://github.com/niklasb/webkit-server/blob/c9e3a8394b8c51000c35f8a56fb770580562b544/webkit_server.py#L511-L520
|
[
"def _read_response(self):\n \"\"\" Reads a complete response packet from the server \"\"\"\n result = self.buf.read_line().decode(\"utf-8\")\n if not result:\n raise NoResponseError(\"No response received from server.\")\n\n msg = self._read_message()\n if result != \"ok\":\n raise InvalidResponseError(msg)\n\n return msg\n",
"def _writeline(self, line):\n \"\"\" Writes a line to the underlying socket. \"\"\"\n self._sock.sendall(line.encode(\"utf-8\") + b\"\\n\")\n"
] |
class ServerConnection(object):
""" A connection to a Webkit server.
`server` is a server instance or `None` if a singleton server should be connected
to (will be started if necessary). """
def __init__(self, server = None):
super(ServerConnection, self).__init__()
self._sock = (server or get_default_server()).connect()
self.buf = SocketBuffer(self._sock)
self.issue_command("IgnoreSslErrors")
def _read_response(self):
""" Reads a complete response packet from the server """
result = self.buf.read_line().decode("utf-8")
if not result:
raise NoResponseError("No response received from server.")
msg = self._read_message()
if result != "ok":
raise InvalidResponseError(msg)
return msg
def _read_message(self):
""" Reads a single size-annotated message from the server """
size = int(self.buf.read_line().decode("utf-8"))
return self.buf.read(size).decode("utf-8")
def _writeline(self, line):
""" Writes a line to the underlying socket. """
self._sock.sendall(line.encode("utf-8") + b"\n")
|
niklasb/webkit-server
|
webkit_server.py
|
ServerConnection._read_response
|
python
|
def _read_response(self):
result = self.buf.read_line().decode("utf-8")
if not result:
raise NoResponseError("No response received from server.")
msg = self._read_message()
if result != "ok":
raise InvalidResponseError(msg)
return msg
|
Reads a complete response packet from the server
|
train
|
https://github.com/niklasb/webkit-server/blob/c9e3a8394b8c51000c35f8a56fb770580562b544/webkit_server.py#L522-L532
|
[
"def _read_message(self):\n \"\"\" Reads a single size-annotated message from the server \"\"\"\n size = int(self.buf.read_line().decode(\"utf-8\"))\n return self.buf.read(size).decode(\"utf-8\")\n"
] |
class ServerConnection(object):
""" A connection to a Webkit server.
`server` is a server instance or `None` if a singleton server should be connected
to (will be started if necessary). """
def __init__(self, server = None):
super(ServerConnection, self).__init__()
self._sock = (server or get_default_server()).connect()
self.buf = SocketBuffer(self._sock)
self.issue_command("IgnoreSslErrors")
def issue_command(self, cmd, *args):
""" Sends and receives a message to/from the server """
self._writeline(cmd)
self._writeline(str(len(args)))
for arg in args:
arg = str(arg)
self._writeline(str(len(arg)))
self._sock.sendall(arg.encode("utf-8"))
return self._read_response()
def _read_message(self):
""" Reads a single size-annotated message from the server """
size = int(self.buf.read_line().decode("utf-8"))
return self.buf.read(size).decode("utf-8")
def _writeline(self, line):
""" Writes a line to the underlying socket. """
self._sock.sendall(line.encode("utf-8") + b"\n")
|
niklasb/webkit-server
|
webkit_server.py
|
ServerConnection._read_message
|
python
|
def _read_message(self):
size = int(self.buf.read_line().decode("utf-8"))
return self.buf.read(size).decode("utf-8")
|
Reads a single size-annotated message from the server
|
train
|
https://github.com/niklasb/webkit-server/blob/c9e3a8394b8c51000c35f8a56fb770580562b544/webkit_server.py#L534-L537
| null |
class ServerConnection(object):
""" A connection to a Webkit server.
`server` is a server instance or `None` if a singleton server should be connected
to (will be started if necessary). """
def __init__(self, server = None):
super(ServerConnection, self).__init__()
self._sock = (server or get_default_server()).connect()
self.buf = SocketBuffer(self._sock)
self.issue_command("IgnoreSslErrors")
def issue_command(self, cmd, *args):
""" Sends and receives a message to/from the server """
self._writeline(cmd)
self._writeline(str(len(args)))
for arg in args:
arg = str(arg)
self._writeline(str(len(arg)))
self._sock.sendall(arg.encode("utf-8"))
return self._read_response()
def _read_response(self):
""" Reads a complete response packet from the server """
result = self.buf.read_line().decode("utf-8")
if not result:
raise NoResponseError("No response received from server.")
msg = self._read_message()
if result != "ok":
raise InvalidResponseError(msg)
return msg
def _writeline(self, line):
""" Writes a line to the underlying socket. """
self._sock.sendall(line.encode("utf-8") + b"\n")
|
gtaylor/paypal-python
|
paypal/interface.py
|
PayPalInterface._encode_utf8
|
python
|
def _encode_utf8(self, **kwargs):
if is_py3:
# This is only valid for Python 2. In Python 3, unicode is
# everywhere (yay).
return kwargs
unencoded_pairs = kwargs
for i in unencoded_pairs.keys():
#noinspection PyUnresolvedReferences
if isinstance(unencoded_pairs[i], types.UnicodeType):
unencoded_pairs[i] = unencoded_pairs[i].encode('utf-8')
return unencoded_pairs
|
UTF8 encodes all of the NVP values.
|
train
|
https://github.com/gtaylor/paypal-python/blob/aa7a987ea9e9b7f37bcd8a8b54a440aad6c871b1/paypal/interface.py#L58-L72
| null |
class PayPalInterface(object):
__credentials = ['USER', 'PWD', 'SIGNATURE', 'SUBJECT']
"""
The end developers will do 95% of their work through this class. API
queries, configuration, etc, all go through here. See the __init__ method
for config related details.
"""
def __init__(self, config=None, **kwargs):
"""
Constructor, which passes all config directives to the config class
via kwargs. For example:
paypal = PayPalInterface(API_USERNAME='somevalue')
Optionally, you may pass a 'config' kwarg to provide your own
PayPalConfig object.
"""
if config:
# User provided their own PayPalConfig object.
self.config = config
else:
# Take the kwargs and stuff them in a new PayPalConfig object.
self.config = PayPalConfig(**kwargs)
def _check_required(self, requires, **kwargs):
"""
Checks kwargs for the values specified in 'requires', which is a tuple
of strings. These strings are the NVP names of the required values.
"""
for req in requires:
# PayPal api is never mixed-case.
if req.lower() not in kwargs and req.upper() not in kwargs:
raise PayPalError('missing required : %s' % req)
def _sanitize_locals(self, data):
"""
Remove the 'self' key in locals()
It's more explicit to do it in one function
"""
if 'self' in data:
data = data.copy()
del data['self']
return data
def _call(self, method, **kwargs):
"""
Wrapper method for executing all API commands over HTTP. This method is
further used to implement wrapper methods listed here:
https://www.x.com/docs/DOC-1374
``method`` must be a supported NVP method listed at the above address.
``kwargs`` the actual call parameters
"""
post_params = self._get_call_params(method, **kwargs)
payload = post_params['data']
api_endpoint = post_params['url']
# This shows all of the key/val pairs we're sending to PayPal.
if logger.isEnabledFor(logging.DEBUG):
logger.debug('PayPal NVP Query Key/Vals:\n%s' % pformat(payload))
http_response = requests.post(**post_params)
response = PayPalResponse(http_response.text, self.config)
logger.debug('PayPal NVP API Endpoint: %s' % api_endpoint)
if not response.success:
raise PayPalAPIResponseError(response)
return response
def _get_call_params(self, method, **kwargs):
"""
Returns the prepared call parameters. Mind, these will be keyword
arguments to ``requests.post``.
``method`` the NVP method
``kwargs`` the actual call parameters
"""
payload = {'METHOD': method,
'VERSION': self.config.API_VERSION}
certificate = None
if self.config.API_AUTHENTICATION_MODE == "3TOKEN":
payload['USER'] = self.config.API_USERNAME
payload['PWD'] = self.config.API_PASSWORD
payload['SIGNATURE'] = self.config.API_SIGNATURE
elif self.config.API_AUTHENTICATION_MODE == "CERTIFICATE":
payload['USER'] = self.config.API_USERNAME
payload['PWD'] = self.config.API_PASSWORD
certificate = (self.config.API_CERTIFICATE_FILENAME,
self.config.API_KEY_FILENAME)
elif self.config.API_AUTHENTICATION_MODE == "UNIPAY":
payload['SUBJECT'] = self.config.UNIPAY_SUBJECT
none_configs = [config for config, value in payload.items()
if value is None]
if none_configs:
raise PayPalConfigError(
"Config(s) %s cannot be None. Please, check this "
"interface's config." % none_configs)
# all keys in the payload must be uppercase
for key, value in kwargs.items():
payload[key.upper()] = value
return {'data': payload,
'cert': certificate,
'url': self.config.API_ENDPOINT,
'timeout': self.config.HTTP_TIMEOUT,
'verify': self.config.API_CA_CERTS}
def address_verify(self, email, street, zip):
"""Shortcut for the AddressVerify method.
``email``::
Email address of a PayPal member to verify.
Maximum string length: 255 single-byte characters
Input mask: ?@?.??
``street``::
First line of the billing or shipping postal address to verify.
To pass verification, the value of Street must match the first three
single-byte characters of a postal address on file for the PayPal member.
Maximum string length: 35 single-byte characters.
Alphanumeric plus - , . ‘ # \
Whitespace and case of input value are ignored.
``zip``::
Postal code to verify.
To pass verification, the value of Zip mustmatch the first five
single-byte characters of the postal code of the verified postal
address for the verified PayPal member.
Maximumstring length: 16 single-byte characters.
Whitespace and case of input value are ignored.
"""
args = self._sanitize_locals(locals())
return self._call('AddressVerify', **args)
def create_recurring_payments_profile(self, **kwargs):
"""Shortcut for the CreateRecurringPaymentsProfile method.
Currently, this method only supports the Direct Payment flavor.
It requires standard credit card information and a few additional
parameters related to the billing. e.g.:
profile_info = {
# Credit card information
'creditcardtype': 'Visa',
'acct': '4812177017895760',
'expdate': '102015',
'cvv2': '123',
'firstname': 'John',
'lastname': 'Doe',
'street': '1313 Mockingbird Lane',
'city': 'Beverly Hills',
'state': 'CA',
'zip': '90110',
'countrycode': 'US',
'currencycode': 'USD',
# Recurring payment information
'profilestartdate': '2010-10-25T0:0:0',
'billingperiod': 'Month',
'billingfrequency': '6',
'amt': '10.00',
'desc': '6 months of our product.'
}
response = create_recurring_payments_profile(**profile_info)
The above NVPs compose the bare-minimum request for creating a
profile. For the complete list of parameters, visit this URI:
https://www.x.com/docs/DOC-1168
"""
return self._call('CreateRecurringPaymentsProfile', **kwargs)
def do_authorization(self, transactionid, amt):
"""Shortcut for the DoAuthorization method.
Use the TRANSACTIONID from DoExpressCheckoutPayment for the
``transactionid``. The latest version of the API does not support the
creation of an Order from `DoDirectPayment`.
The `amt` should be the same as passed to `DoExpressCheckoutPayment`.
Flow for a payment involving a `DoAuthorization` call::
1. One or many calls to `SetExpressCheckout` with pertinent order
details, returns `TOKEN`
1. `DoExpressCheckoutPayment` with `TOKEN`, `PAYMENTACTION` set to
Order, `AMT` set to the amount of the transaction, returns
`TRANSACTIONID`
1. `DoAuthorization` with `TRANSACTIONID` and `AMT` set to the
amount of the transaction.
1. `DoCapture` with the `AUTHORIZATIONID` (the `TRANSACTIONID`
returned by `DoAuthorization`)
"""
args = self._sanitize_locals(locals())
return self._call('DoAuthorization', **args)
def do_capture(self, authorizationid, amt, completetype='Complete',
**kwargs):
"""Shortcut for the DoCapture method.
Use the TRANSACTIONID from DoAuthorization, DoDirectPayment or
DoExpressCheckoutPayment for the ``authorizationid``.
The `amt` should be the same as the authorized transaction.
"""
kwargs.update(self._sanitize_locals(locals()))
return self._call('DoCapture', **kwargs)
def do_direct_payment(self, paymentaction="Sale", **kwargs):
"""Shortcut for the DoDirectPayment method.
``paymentaction`` could be 'Authorization' or 'Sale'
To issue a Sale immediately::
charge = {
'amt': '10.00',
'creditcardtype': 'Visa',
'acct': '4812177017895760',
'expdate': '012010',
'cvv2': '962',
'firstname': 'John',
'lastname': 'Doe',
'street': '1 Main St',
'city': 'San Jose',
'state': 'CA',
'zip': '95131',
'countrycode': 'US',
'currencycode': 'USD',
}
direct_payment("Sale", **charge)
Or, since "Sale" is the default:
direct_payment(**charge)
To issue an Authorization, simply pass "Authorization" instead
of "Sale".
You may also explicitly set ``paymentaction`` as a keyword argument:
...
direct_payment(paymentaction="Sale", **charge)
"""
kwargs.update(self._sanitize_locals(locals()))
return self._call('DoDirectPayment', **kwargs)
def do_void(self, **kwargs):
"""Shortcut for the DoVoid method.
Use the TRANSACTIONID from DoAuthorization, DoDirectPayment or
DoExpressCheckoutPayment for the ``AUTHORIZATIONID``.
Required Kwargs
---------------
* AUTHORIZATIONID
"""
return self._call('DoVoid', **kwargs)
def get_express_checkout_details(self, **kwargs):
"""Shortcut for the GetExpressCheckoutDetails method.
Required Kwargs
---------------
* TOKEN
"""
return self._call('GetExpressCheckoutDetails', **kwargs)
def get_transaction_details(self, **kwargs):
"""Shortcut for the GetTransactionDetails method.
Use the TRANSACTIONID from DoAuthorization, DoDirectPayment or
DoExpressCheckoutPayment for the ``transactionid``.
Required Kwargs
---------------
* TRANSACTIONID
"""
return self._call('GetTransactionDetails', **kwargs)
def transaction_search(self, **kwargs):
"""Shortcut for the TransactionSearch method.
Returns a PayPalResponseList object, which merges the L_ syntax list
to a list of dictionaries with properly named keys.
Note that the API will limit returned transactions to 100.
Required Kwargs
---------------
* STARTDATE
Optional Kwargs
---------------
STATUS = one of ['Pending','Processing','Success','Denied','Reversed']
"""
plain = self._call('TransactionSearch', **kwargs)
return PayPalResponseList(plain.raw, self.config)
def set_express_checkout(self, **kwargs):
"""Start an Express checkout.
You'll want to use this in conjunction with
:meth:`generate_express_checkout_redirect_url` to create a payment,
then figure out where to redirect the user to for them to
authorize the payment on PayPal's website.
Required Kwargs
---------------
* PAYMENTREQUEST_0_AMT
* PAYMENTREQUEST_0_PAYMENTACTION
* RETURNURL
* CANCELURL
"""
return self._call('SetExpressCheckout', **kwargs)
def refund_transaction(self, transactionid=None, payerid=None, **kwargs):
"""Shortcut for RefundTransaction method.
Note new API supports passing a PayerID instead of a transaction id,
exactly one must be provided.
Optional:
INVOICEID
REFUNDTYPE
AMT
CURRENCYCODE
NOTE
RETRYUNTIL
REFUNDSOURCE
MERCHANTSTOREDETAILS
REFUNDADVICE
REFUNDITEMDETAILS
MSGSUBID
MERCHANSTOREDETAILS has two fields:
STOREID
TERMINALID
"""
# This line seems like a complete waste of time... kwargs should not
# be populated
if (transactionid is None) and (payerid is None):
raise PayPalError(
'RefundTransaction requires either a transactionid or '
'a payerid')
if (transactionid is not None) and (payerid is not None):
raise PayPalError(
'RefundTransaction requires only one of transactionid %s '
'and payerid %s' % (transactionid, payerid))
if transactionid is not None:
kwargs['TRANSACTIONID'] = transactionid
else:
kwargs['PAYERID'] = payerid
return self._call('RefundTransaction', **kwargs)
def do_express_checkout_payment(self, **kwargs):
"""Finishes an Express checkout.
TOKEN is the token that was returned earlier by
:meth:`set_express_checkout`. This identifies the transaction.
Required
--------
* TOKEN
* PAYMENTACTION
* PAYERID
* AMT
"""
return self._call('DoExpressCheckoutPayment', **kwargs)
def generate_express_checkout_redirect_url(self, token, useraction=None):
"""Returns the URL to redirect the user to for the Express checkout.
Express Checkouts must be verified by the customer by redirecting them
to the PayPal website. Use the token returned in the response from
:meth:`set_express_checkout` with this function to figure out where
to redirect the user to.
The button text on the PayPal page can be controlled via `useraction`.
The documented possible values are `commit` and `continue`. However,
any other value will only result in a warning.
:param str token: The unique token identifying this transaction.
:param str useraction: Control the button text on the PayPal page.
:rtype: str
:returns: The URL to redirect the user to for approval.
"""
url_vars = (self.config.PAYPAL_URL_BASE, token)
url = "%s?cmd=_express-checkout&token=%s" % url_vars
if useraction:
if not useraction.lower() in ('commit', 'continue'):
warnings.warn('useraction=%s is not documented' % useraction,
RuntimeWarning)
url += '&useraction=%s' % useraction
return url
def generate_cart_upload_redirect_url(self, **kwargs):
"""https://www.sandbox.paypal.com/webscr
?cmd=_cart
&upload=1
"""
required_vals = ('business', 'item_name_1', 'amount_1', 'quantity_1')
self._check_required(required_vals, **kwargs)
url = "%s?cmd=_cart&upload=1" % self.config.PAYPAL_URL_BASE
additional = self._encode_utf8(**kwargs)
additional = urlencode(additional)
return url + "&" + additional
def get_recurring_payments_profile_details(self, profileid):
"""Shortcut for the GetRecurringPaymentsProfile method.
This returns details for a recurring payment plan. The ``profileid`` is
a value included in the response retrieved by the function
``create_recurring_payments_profile``. The profile details include the
data provided when the profile was created as well as default values
for ignored fields and some pertinent stastics.
e.g.:
response = create_recurring_payments_profile(**profile_info)
profileid = response.PROFILEID
details = get_recurring_payments_profile(profileid)
The response from PayPal is somewhat self-explanatory, but for a
description of each field, visit the following URI:
https://www.x.com/docs/DOC-1194
"""
args = self._sanitize_locals(locals())
return self._call('GetRecurringPaymentsProfileDetails', **args)
def manage_recurring_payments_profile_status(self, profileid, action,
note=None):
"""Shortcut to the ManageRecurringPaymentsProfileStatus method.
``profileid`` is the same profile id used for getting profile details.
``action`` should be either 'Cancel', 'Suspend', or 'Reactivate'.
``note`` is optional and is visible to the user. It contains the
reason for the change in status.
"""
args = self._sanitize_locals(locals())
if not note:
del args['note']
return self._call('ManageRecurringPaymentsProfileStatus', **args)
def update_recurring_payments_profile(self, profileid, **kwargs):
"""Shortcut to the UpdateRecurringPaymentsProfile method.
``profileid`` is the same profile id used for getting profile details.
The keyed arguments are data in the payment profile which you wish to
change. The profileid does not change. Anything else will take the new
value. Most of, though not all of, the fields available are shared
with creating a profile, but for the complete list of parameters, you
can visit the following URI:
https://www.x.com/docs/DOC-1212
"""
kwargs.update(self._sanitize_locals(locals()))
return self._call('UpdateRecurringPaymentsProfile', **kwargs)
def bm_create_button(self, **kwargs):
"""Shortcut to the BMCreateButton method.
See the docs for details on arguments:
https://cms.paypal.com/mx/cgi-bin/?cmd=_render-content&content_ID=developer/e_howto_api_nvp_BMCreateButton
The L_BUTTONVARn fields are especially important, so make sure to
read those and act accordingly. See unit tests for some examples.
"""
kwargs.update(self._sanitize_locals(locals()))
return self._call('BMCreateButton', **kwargs)
|
gtaylor/paypal-python
|
paypal/interface.py
|
PayPalInterface._check_required
|
python
|
def _check_required(self, requires, **kwargs):
for req in requires:
# PayPal api is never mixed-case.
if req.lower() not in kwargs and req.upper() not in kwargs:
raise PayPalError('missing required : %s' % req)
|
Checks kwargs for the values specified in 'requires', which is a tuple
of strings. These strings are the NVP names of the required values.
|
train
|
https://github.com/gtaylor/paypal-python/blob/aa7a987ea9e9b7f37bcd8a8b54a440aad6c871b1/paypal/interface.py#L74-L82
| null |
class PayPalInterface(object):
__credentials = ['USER', 'PWD', 'SIGNATURE', 'SUBJECT']
"""
The end developers will do 95% of their work through this class. API
queries, configuration, etc, all go through here. See the __init__ method
for config related details.
"""
def __init__(self, config=None, **kwargs):
"""
Constructor, which passes all config directives to the config class
via kwargs. For example:
paypal = PayPalInterface(API_USERNAME='somevalue')
Optionally, you may pass a 'config' kwarg to provide your own
PayPalConfig object.
"""
if config:
# User provided their own PayPalConfig object.
self.config = config
else:
# Take the kwargs and stuff them in a new PayPalConfig object.
self.config = PayPalConfig(**kwargs)
def _encode_utf8(self, **kwargs):
"""
UTF8 encodes all of the NVP values.
"""
if is_py3:
# This is only valid for Python 2. In Python 3, unicode is
# everywhere (yay).
return kwargs
unencoded_pairs = kwargs
for i in unencoded_pairs.keys():
#noinspection PyUnresolvedReferences
if isinstance(unencoded_pairs[i], types.UnicodeType):
unencoded_pairs[i] = unencoded_pairs[i].encode('utf-8')
return unencoded_pairs
def _sanitize_locals(self, data):
"""
Remove the 'self' key in locals()
It's more explicit to do it in one function
"""
if 'self' in data:
data = data.copy()
del data['self']
return data
def _call(self, method, **kwargs):
"""
Wrapper method for executing all API commands over HTTP. This method is
further used to implement wrapper methods listed here:
https://www.x.com/docs/DOC-1374
``method`` must be a supported NVP method listed at the above address.
``kwargs`` the actual call parameters
"""
post_params = self._get_call_params(method, **kwargs)
payload = post_params['data']
api_endpoint = post_params['url']
# This shows all of the key/val pairs we're sending to PayPal.
if logger.isEnabledFor(logging.DEBUG):
logger.debug('PayPal NVP Query Key/Vals:\n%s' % pformat(payload))
http_response = requests.post(**post_params)
response = PayPalResponse(http_response.text, self.config)
logger.debug('PayPal NVP API Endpoint: %s' % api_endpoint)
if not response.success:
raise PayPalAPIResponseError(response)
return response
def _get_call_params(self, method, **kwargs):
"""
Returns the prepared call parameters. Mind, these will be keyword
arguments to ``requests.post``.
``method`` the NVP method
``kwargs`` the actual call parameters
"""
payload = {'METHOD': method,
'VERSION': self.config.API_VERSION}
certificate = None
if self.config.API_AUTHENTICATION_MODE == "3TOKEN":
payload['USER'] = self.config.API_USERNAME
payload['PWD'] = self.config.API_PASSWORD
payload['SIGNATURE'] = self.config.API_SIGNATURE
elif self.config.API_AUTHENTICATION_MODE == "CERTIFICATE":
payload['USER'] = self.config.API_USERNAME
payload['PWD'] = self.config.API_PASSWORD
certificate = (self.config.API_CERTIFICATE_FILENAME,
self.config.API_KEY_FILENAME)
elif self.config.API_AUTHENTICATION_MODE == "UNIPAY":
payload['SUBJECT'] = self.config.UNIPAY_SUBJECT
none_configs = [config for config, value in payload.items()
if value is None]
if none_configs:
raise PayPalConfigError(
"Config(s) %s cannot be None. Please, check this "
"interface's config." % none_configs)
# all keys in the payload must be uppercase
for key, value in kwargs.items():
payload[key.upper()] = value
return {'data': payload,
'cert': certificate,
'url': self.config.API_ENDPOINT,
'timeout': self.config.HTTP_TIMEOUT,
'verify': self.config.API_CA_CERTS}
def address_verify(self, email, street, zip):
"""Shortcut for the AddressVerify method.
``email``::
Email address of a PayPal member to verify.
Maximum string length: 255 single-byte characters
Input mask: ?@?.??
``street``::
First line of the billing or shipping postal address to verify.
To pass verification, the value of Street must match the first three
single-byte characters of a postal address on file for the PayPal member.
Maximum string length: 35 single-byte characters.
Alphanumeric plus - , . ‘ # \
Whitespace and case of input value are ignored.
``zip``::
Postal code to verify.
To pass verification, the value of Zip mustmatch the first five
single-byte characters of the postal code of the verified postal
address for the verified PayPal member.
Maximumstring length: 16 single-byte characters.
Whitespace and case of input value are ignored.
"""
args = self._sanitize_locals(locals())
return self._call('AddressVerify', **args)
def create_recurring_payments_profile(self, **kwargs):
"""Shortcut for the CreateRecurringPaymentsProfile method.
Currently, this method only supports the Direct Payment flavor.
It requires standard credit card information and a few additional
parameters related to the billing. e.g.:
profile_info = {
# Credit card information
'creditcardtype': 'Visa',
'acct': '4812177017895760',
'expdate': '102015',
'cvv2': '123',
'firstname': 'John',
'lastname': 'Doe',
'street': '1313 Mockingbird Lane',
'city': 'Beverly Hills',
'state': 'CA',
'zip': '90110',
'countrycode': 'US',
'currencycode': 'USD',
# Recurring payment information
'profilestartdate': '2010-10-25T0:0:0',
'billingperiod': 'Month',
'billingfrequency': '6',
'amt': '10.00',
'desc': '6 months of our product.'
}
response = create_recurring_payments_profile(**profile_info)
The above NVPs compose the bare-minimum request for creating a
profile. For the complete list of parameters, visit this URI:
https://www.x.com/docs/DOC-1168
"""
return self._call('CreateRecurringPaymentsProfile', **kwargs)
def do_authorization(self, transactionid, amt):
"""Shortcut for the DoAuthorization method.
Use the TRANSACTIONID from DoExpressCheckoutPayment for the
``transactionid``. The latest version of the API does not support the
creation of an Order from `DoDirectPayment`.
The `amt` should be the same as passed to `DoExpressCheckoutPayment`.
Flow for a payment involving a `DoAuthorization` call::
1. One or many calls to `SetExpressCheckout` with pertinent order
details, returns `TOKEN`
1. `DoExpressCheckoutPayment` with `TOKEN`, `PAYMENTACTION` set to
Order, `AMT` set to the amount of the transaction, returns
`TRANSACTIONID`
1. `DoAuthorization` with `TRANSACTIONID` and `AMT` set to the
amount of the transaction.
1. `DoCapture` with the `AUTHORIZATIONID` (the `TRANSACTIONID`
returned by `DoAuthorization`)
"""
args = self._sanitize_locals(locals())
return self._call('DoAuthorization', **args)
def do_capture(self, authorizationid, amt, completetype='Complete',
**kwargs):
"""Shortcut for the DoCapture method.
Use the TRANSACTIONID from DoAuthorization, DoDirectPayment or
DoExpressCheckoutPayment for the ``authorizationid``.
The `amt` should be the same as the authorized transaction.
"""
kwargs.update(self._sanitize_locals(locals()))
return self._call('DoCapture', **kwargs)
def do_direct_payment(self, paymentaction="Sale", **kwargs):
"""Shortcut for the DoDirectPayment method.
``paymentaction`` could be 'Authorization' or 'Sale'
To issue a Sale immediately::
charge = {
'amt': '10.00',
'creditcardtype': 'Visa',
'acct': '4812177017895760',
'expdate': '012010',
'cvv2': '962',
'firstname': 'John',
'lastname': 'Doe',
'street': '1 Main St',
'city': 'San Jose',
'state': 'CA',
'zip': '95131',
'countrycode': 'US',
'currencycode': 'USD',
}
direct_payment("Sale", **charge)
Or, since "Sale" is the default:
direct_payment(**charge)
To issue an Authorization, simply pass "Authorization" instead
of "Sale".
You may also explicitly set ``paymentaction`` as a keyword argument:
...
direct_payment(paymentaction="Sale", **charge)
"""
kwargs.update(self._sanitize_locals(locals()))
return self._call('DoDirectPayment', **kwargs)
def do_void(self, **kwargs):
"""Shortcut for the DoVoid method.
Use the TRANSACTIONID from DoAuthorization, DoDirectPayment or
DoExpressCheckoutPayment for the ``AUTHORIZATIONID``.
Required Kwargs
---------------
* AUTHORIZATIONID
"""
return self._call('DoVoid', **kwargs)
def get_express_checkout_details(self, **kwargs):
"""Shortcut for the GetExpressCheckoutDetails method.
Required Kwargs
---------------
* TOKEN
"""
return self._call('GetExpressCheckoutDetails', **kwargs)
def get_transaction_details(self, **kwargs):
"""Shortcut for the GetTransactionDetails method.
Use the TRANSACTIONID from DoAuthorization, DoDirectPayment or
DoExpressCheckoutPayment for the ``transactionid``.
Required Kwargs
---------------
* TRANSACTIONID
"""
return self._call('GetTransactionDetails', **kwargs)
def transaction_search(self, **kwargs):
"""Shortcut for the TransactionSearch method.
Returns a PayPalResponseList object, which merges the L_ syntax list
to a list of dictionaries with properly named keys.
Note that the API will limit returned transactions to 100.
Required Kwargs
---------------
* STARTDATE
Optional Kwargs
---------------
STATUS = one of ['Pending','Processing','Success','Denied','Reversed']
"""
plain = self._call('TransactionSearch', **kwargs)
return PayPalResponseList(plain.raw, self.config)
def set_express_checkout(self, **kwargs):
"""Start an Express checkout.
You'll want to use this in conjunction with
:meth:`generate_express_checkout_redirect_url` to create a payment,
then figure out where to redirect the user to for them to
authorize the payment on PayPal's website.
Required Kwargs
---------------
* PAYMENTREQUEST_0_AMT
* PAYMENTREQUEST_0_PAYMENTACTION
* RETURNURL
* CANCELURL
"""
return self._call('SetExpressCheckout', **kwargs)
def refund_transaction(self, transactionid=None, payerid=None, **kwargs):
"""Shortcut for RefundTransaction method.
Note new API supports passing a PayerID instead of a transaction id,
exactly one must be provided.
Optional:
INVOICEID
REFUNDTYPE
AMT
CURRENCYCODE
NOTE
RETRYUNTIL
REFUNDSOURCE
MERCHANTSTOREDETAILS
REFUNDADVICE
REFUNDITEMDETAILS
MSGSUBID
MERCHANSTOREDETAILS has two fields:
STOREID
TERMINALID
"""
# This line seems like a complete waste of time... kwargs should not
# be populated
if (transactionid is None) and (payerid is None):
raise PayPalError(
'RefundTransaction requires either a transactionid or '
'a payerid')
if (transactionid is not None) and (payerid is not None):
raise PayPalError(
'RefundTransaction requires only one of transactionid %s '
'and payerid %s' % (transactionid, payerid))
if transactionid is not None:
kwargs['TRANSACTIONID'] = transactionid
else:
kwargs['PAYERID'] = payerid
return self._call('RefundTransaction', **kwargs)
def do_express_checkout_payment(self, **kwargs):
"""Finishes an Express checkout.
TOKEN is the token that was returned earlier by
:meth:`set_express_checkout`. This identifies the transaction.
Required
--------
* TOKEN
* PAYMENTACTION
* PAYERID
* AMT
"""
return self._call('DoExpressCheckoutPayment', **kwargs)
def generate_express_checkout_redirect_url(self, token, useraction=None):
"""Returns the URL to redirect the user to for the Express checkout.
Express Checkouts must be verified by the customer by redirecting them
to the PayPal website. Use the token returned in the response from
:meth:`set_express_checkout` with this function to figure out where
to redirect the user to.
The button text on the PayPal page can be controlled via `useraction`.
The documented possible values are `commit` and `continue`. However,
any other value will only result in a warning.
:param str token: The unique token identifying this transaction.
:param str useraction: Control the button text on the PayPal page.
:rtype: str
:returns: The URL to redirect the user to for approval.
"""
url_vars = (self.config.PAYPAL_URL_BASE, token)
url = "%s?cmd=_express-checkout&token=%s" % url_vars
if useraction:
if not useraction.lower() in ('commit', 'continue'):
warnings.warn('useraction=%s is not documented' % useraction,
RuntimeWarning)
url += '&useraction=%s' % useraction
return url
def generate_cart_upload_redirect_url(self, **kwargs):
"""https://www.sandbox.paypal.com/webscr
?cmd=_cart
&upload=1
"""
required_vals = ('business', 'item_name_1', 'amount_1', 'quantity_1')
self._check_required(required_vals, **kwargs)
url = "%s?cmd=_cart&upload=1" % self.config.PAYPAL_URL_BASE
additional = self._encode_utf8(**kwargs)
additional = urlencode(additional)
return url + "&" + additional
def get_recurring_payments_profile_details(self, profileid):
"""Shortcut for the GetRecurringPaymentsProfile method.
This returns details for a recurring payment plan. The ``profileid`` is
a value included in the response retrieved by the function
``create_recurring_payments_profile``. The profile details include the
data provided when the profile was created as well as default values
for ignored fields and some pertinent stastics.
e.g.:
response = create_recurring_payments_profile(**profile_info)
profileid = response.PROFILEID
details = get_recurring_payments_profile(profileid)
The response from PayPal is somewhat self-explanatory, but for a
description of each field, visit the following URI:
https://www.x.com/docs/DOC-1194
"""
args = self._sanitize_locals(locals())
return self._call('GetRecurringPaymentsProfileDetails', **args)
def manage_recurring_payments_profile_status(self, profileid, action,
note=None):
"""Shortcut to the ManageRecurringPaymentsProfileStatus method.
``profileid`` is the same profile id used for getting profile details.
``action`` should be either 'Cancel', 'Suspend', or 'Reactivate'.
``note`` is optional and is visible to the user. It contains the
reason for the change in status.
"""
args = self._sanitize_locals(locals())
if not note:
del args['note']
return self._call('ManageRecurringPaymentsProfileStatus', **args)
def update_recurring_payments_profile(self, profileid, **kwargs):
"""Shortcut to the UpdateRecurringPaymentsProfile method.
``profileid`` is the same profile id used for getting profile details.
The keyed arguments are data in the payment profile which you wish to
change. The profileid does not change. Anything else will take the new
value. Most of, though not all of, the fields available are shared
with creating a profile, but for the complete list of parameters, you
can visit the following URI:
https://www.x.com/docs/DOC-1212
"""
kwargs.update(self._sanitize_locals(locals()))
return self._call('UpdateRecurringPaymentsProfile', **kwargs)
def bm_create_button(self, **kwargs):
"""Shortcut to the BMCreateButton method.
See the docs for details on arguments:
https://cms.paypal.com/mx/cgi-bin/?cmd=_render-content&content_ID=developer/e_howto_api_nvp_BMCreateButton
The L_BUTTONVARn fields are especially important, so make sure to
read those and act accordingly. See unit tests for some examples.
"""
kwargs.update(self._sanitize_locals(locals()))
return self._call('BMCreateButton', **kwargs)
|
gtaylor/paypal-python
|
paypal/interface.py
|
PayPalInterface._call
|
python
|
def _call(self, method, **kwargs):
post_params = self._get_call_params(method, **kwargs)
payload = post_params['data']
api_endpoint = post_params['url']
# This shows all of the key/val pairs we're sending to PayPal.
if logger.isEnabledFor(logging.DEBUG):
logger.debug('PayPal NVP Query Key/Vals:\n%s' % pformat(payload))
http_response = requests.post(**post_params)
response = PayPalResponse(http_response.text, self.config)
logger.debug('PayPal NVP API Endpoint: %s' % api_endpoint)
if not response.success:
raise PayPalAPIResponseError(response)
return response
|
Wrapper method for executing all API commands over HTTP. This method is
further used to implement wrapper methods listed here:
https://www.x.com/docs/DOC-1374
``method`` must be a supported NVP method listed at the above address.
``kwargs`` the actual call parameters
|
train
|
https://github.com/gtaylor/paypal-python/blob/aa7a987ea9e9b7f37bcd8a8b54a440aad6c871b1/paypal/interface.py#L95-L120
|
[
"def _get_call_params(self, method, **kwargs):\n \"\"\"\n Returns the prepared call parameters. Mind, these will be keyword\n arguments to ``requests.post``.\n\n ``method`` the NVP method\n ``kwargs`` the actual call parameters\n \"\"\"\n payload = {'METHOD': method,\n 'VERSION': self.config.API_VERSION}\n certificate = None\n\n if self.config.API_AUTHENTICATION_MODE == \"3TOKEN\":\n payload['USER'] = self.config.API_USERNAME\n payload['PWD'] = self.config.API_PASSWORD\n payload['SIGNATURE'] = self.config.API_SIGNATURE\n elif self.config.API_AUTHENTICATION_MODE == \"CERTIFICATE\":\n payload['USER'] = self.config.API_USERNAME\n payload['PWD'] = self.config.API_PASSWORD\n certificate = (self.config.API_CERTIFICATE_FILENAME,\n self.config.API_KEY_FILENAME)\n elif self.config.API_AUTHENTICATION_MODE == \"UNIPAY\":\n payload['SUBJECT'] = self.config.UNIPAY_SUBJECT\n\n none_configs = [config for config, value in payload.items()\n if value is None]\n if none_configs:\n raise PayPalConfigError(\n \"Config(s) %s cannot be None. Please, check this \"\n \"interface's config.\" % none_configs)\n\n # all keys in the payload must be uppercase\n for key, value in kwargs.items():\n payload[key.upper()] = value\n\n return {'data': payload,\n 'cert': certificate,\n 'url': self.config.API_ENDPOINT,\n 'timeout': self.config.HTTP_TIMEOUT,\n 'verify': self.config.API_CA_CERTS}\n"
] |
class PayPalInterface(object):
__credentials = ['USER', 'PWD', 'SIGNATURE', 'SUBJECT']
"""
The end developers will do 95% of their work through this class. API
queries, configuration, etc, all go through here. See the __init__ method
for config related details.
"""
def __init__(self, config=None, **kwargs):
"""
Constructor, which passes all config directives to the config class
via kwargs. For example:
paypal = PayPalInterface(API_USERNAME='somevalue')
Optionally, you may pass a 'config' kwarg to provide your own
PayPalConfig object.
"""
if config:
# User provided their own PayPalConfig object.
self.config = config
else:
# Take the kwargs and stuff them in a new PayPalConfig object.
self.config = PayPalConfig(**kwargs)
def _encode_utf8(self, **kwargs):
"""
UTF8 encodes all of the NVP values.
"""
if is_py3:
# This is only valid for Python 2. In Python 3, unicode is
# everywhere (yay).
return kwargs
unencoded_pairs = kwargs
for i in unencoded_pairs.keys():
#noinspection PyUnresolvedReferences
if isinstance(unencoded_pairs[i], types.UnicodeType):
unencoded_pairs[i] = unencoded_pairs[i].encode('utf-8')
return unencoded_pairs
def _check_required(self, requires, **kwargs):
"""
Checks kwargs for the values specified in 'requires', which is a tuple
of strings. These strings are the NVP names of the required values.
"""
for req in requires:
# PayPal api is never mixed-case.
if req.lower() not in kwargs and req.upper() not in kwargs:
raise PayPalError('missing required : %s' % req)
def _sanitize_locals(self, data):
"""
Remove the 'self' key in locals()
It's more explicit to do it in one function
"""
if 'self' in data:
data = data.copy()
del data['self']
return data
def _get_call_params(self, method, **kwargs):
"""
Returns the prepared call parameters. Mind, these will be keyword
arguments to ``requests.post``.
``method`` the NVP method
``kwargs`` the actual call parameters
"""
payload = {'METHOD': method,
'VERSION': self.config.API_VERSION}
certificate = None
if self.config.API_AUTHENTICATION_MODE == "3TOKEN":
payload['USER'] = self.config.API_USERNAME
payload['PWD'] = self.config.API_PASSWORD
payload['SIGNATURE'] = self.config.API_SIGNATURE
elif self.config.API_AUTHENTICATION_MODE == "CERTIFICATE":
payload['USER'] = self.config.API_USERNAME
payload['PWD'] = self.config.API_PASSWORD
certificate = (self.config.API_CERTIFICATE_FILENAME,
self.config.API_KEY_FILENAME)
elif self.config.API_AUTHENTICATION_MODE == "UNIPAY":
payload['SUBJECT'] = self.config.UNIPAY_SUBJECT
none_configs = [config for config, value in payload.items()
if value is None]
if none_configs:
raise PayPalConfigError(
"Config(s) %s cannot be None. Please, check this "
"interface's config." % none_configs)
# all keys in the payload must be uppercase
for key, value in kwargs.items():
payload[key.upper()] = value
return {'data': payload,
'cert': certificate,
'url': self.config.API_ENDPOINT,
'timeout': self.config.HTTP_TIMEOUT,
'verify': self.config.API_CA_CERTS}
def address_verify(self, email, street, zip):
"""Shortcut for the AddressVerify method.
``email``::
Email address of a PayPal member to verify.
Maximum string length: 255 single-byte characters
Input mask: ?@?.??
``street``::
First line of the billing or shipping postal address to verify.
To pass verification, the value of Street must match the first three
single-byte characters of a postal address on file for the PayPal member.
Maximum string length: 35 single-byte characters.
Alphanumeric plus - , . ‘ # \
Whitespace and case of input value are ignored.
``zip``::
Postal code to verify.
To pass verification, the value of Zip mustmatch the first five
single-byte characters of the postal code of the verified postal
address for the verified PayPal member.
Maximumstring length: 16 single-byte characters.
Whitespace and case of input value are ignored.
"""
args = self._sanitize_locals(locals())
return self._call('AddressVerify', **args)
def create_recurring_payments_profile(self, **kwargs):
"""Shortcut for the CreateRecurringPaymentsProfile method.
Currently, this method only supports the Direct Payment flavor.
It requires standard credit card information and a few additional
parameters related to the billing. e.g.:
profile_info = {
# Credit card information
'creditcardtype': 'Visa',
'acct': '4812177017895760',
'expdate': '102015',
'cvv2': '123',
'firstname': 'John',
'lastname': 'Doe',
'street': '1313 Mockingbird Lane',
'city': 'Beverly Hills',
'state': 'CA',
'zip': '90110',
'countrycode': 'US',
'currencycode': 'USD',
# Recurring payment information
'profilestartdate': '2010-10-25T0:0:0',
'billingperiod': 'Month',
'billingfrequency': '6',
'amt': '10.00',
'desc': '6 months of our product.'
}
response = create_recurring_payments_profile(**profile_info)
The above NVPs compose the bare-minimum request for creating a
profile. For the complete list of parameters, visit this URI:
https://www.x.com/docs/DOC-1168
"""
return self._call('CreateRecurringPaymentsProfile', **kwargs)
def do_authorization(self, transactionid, amt):
"""Shortcut for the DoAuthorization method.
Use the TRANSACTIONID from DoExpressCheckoutPayment for the
``transactionid``. The latest version of the API does not support the
creation of an Order from `DoDirectPayment`.
The `amt` should be the same as passed to `DoExpressCheckoutPayment`.
Flow for a payment involving a `DoAuthorization` call::
1. One or many calls to `SetExpressCheckout` with pertinent order
details, returns `TOKEN`
1. `DoExpressCheckoutPayment` with `TOKEN`, `PAYMENTACTION` set to
Order, `AMT` set to the amount of the transaction, returns
`TRANSACTIONID`
1. `DoAuthorization` with `TRANSACTIONID` and `AMT` set to the
amount of the transaction.
1. `DoCapture` with the `AUTHORIZATIONID` (the `TRANSACTIONID`
returned by `DoAuthorization`)
"""
args = self._sanitize_locals(locals())
return self._call('DoAuthorization', **args)
def do_capture(self, authorizationid, amt, completetype='Complete',
**kwargs):
"""Shortcut for the DoCapture method.
Use the TRANSACTIONID from DoAuthorization, DoDirectPayment or
DoExpressCheckoutPayment for the ``authorizationid``.
The `amt` should be the same as the authorized transaction.
"""
kwargs.update(self._sanitize_locals(locals()))
return self._call('DoCapture', **kwargs)
def do_direct_payment(self, paymentaction="Sale", **kwargs):
"""Shortcut for the DoDirectPayment method.
``paymentaction`` could be 'Authorization' or 'Sale'
To issue a Sale immediately::
charge = {
'amt': '10.00',
'creditcardtype': 'Visa',
'acct': '4812177017895760',
'expdate': '012010',
'cvv2': '962',
'firstname': 'John',
'lastname': 'Doe',
'street': '1 Main St',
'city': 'San Jose',
'state': 'CA',
'zip': '95131',
'countrycode': 'US',
'currencycode': 'USD',
}
direct_payment("Sale", **charge)
Or, since "Sale" is the default:
direct_payment(**charge)
To issue an Authorization, simply pass "Authorization" instead
of "Sale".
You may also explicitly set ``paymentaction`` as a keyword argument:
...
direct_payment(paymentaction="Sale", **charge)
"""
kwargs.update(self._sanitize_locals(locals()))
return self._call('DoDirectPayment', **kwargs)
def do_void(self, **kwargs):
"""Shortcut for the DoVoid method.
Use the TRANSACTIONID from DoAuthorization, DoDirectPayment or
DoExpressCheckoutPayment for the ``AUTHORIZATIONID``.
Required Kwargs
---------------
* AUTHORIZATIONID
"""
return self._call('DoVoid', **kwargs)
def get_express_checkout_details(self, **kwargs):
"""Shortcut for the GetExpressCheckoutDetails method.
Required Kwargs
---------------
* TOKEN
"""
return self._call('GetExpressCheckoutDetails', **kwargs)
def get_transaction_details(self, **kwargs):
"""Shortcut for the GetTransactionDetails method.
Use the TRANSACTIONID from DoAuthorization, DoDirectPayment or
DoExpressCheckoutPayment for the ``transactionid``.
Required Kwargs
---------------
* TRANSACTIONID
"""
return self._call('GetTransactionDetails', **kwargs)
def transaction_search(self, **kwargs):
"""Shortcut for the TransactionSearch method.
Returns a PayPalResponseList object, which merges the L_ syntax list
to a list of dictionaries with properly named keys.
Note that the API will limit returned transactions to 100.
Required Kwargs
---------------
* STARTDATE
Optional Kwargs
---------------
STATUS = one of ['Pending','Processing','Success','Denied','Reversed']
"""
plain = self._call('TransactionSearch', **kwargs)
return PayPalResponseList(plain.raw, self.config)
def set_express_checkout(self, **kwargs):
"""Start an Express checkout.
You'll want to use this in conjunction with
:meth:`generate_express_checkout_redirect_url` to create a payment,
then figure out where to redirect the user to for them to
authorize the payment on PayPal's website.
Required Kwargs
---------------
* PAYMENTREQUEST_0_AMT
* PAYMENTREQUEST_0_PAYMENTACTION
* RETURNURL
* CANCELURL
"""
return self._call('SetExpressCheckout', **kwargs)
def refund_transaction(self, transactionid=None, payerid=None, **kwargs):
"""Shortcut for RefundTransaction method.
Note new API supports passing a PayerID instead of a transaction id,
exactly one must be provided.
Optional:
INVOICEID
REFUNDTYPE
AMT
CURRENCYCODE
NOTE
RETRYUNTIL
REFUNDSOURCE
MERCHANTSTOREDETAILS
REFUNDADVICE
REFUNDITEMDETAILS
MSGSUBID
MERCHANSTOREDETAILS has two fields:
STOREID
TERMINALID
"""
# This line seems like a complete waste of time... kwargs should not
# be populated
if (transactionid is None) and (payerid is None):
raise PayPalError(
'RefundTransaction requires either a transactionid or '
'a payerid')
if (transactionid is not None) and (payerid is not None):
raise PayPalError(
'RefundTransaction requires only one of transactionid %s '
'and payerid %s' % (transactionid, payerid))
if transactionid is not None:
kwargs['TRANSACTIONID'] = transactionid
else:
kwargs['PAYERID'] = payerid
return self._call('RefundTransaction', **kwargs)
def do_express_checkout_payment(self, **kwargs):
"""Finishes an Express checkout.
TOKEN is the token that was returned earlier by
:meth:`set_express_checkout`. This identifies the transaction.
Required
--------
* TOKEN
* PAYMENTACTION
* PAYERID
* AMT
"""
return self._call('DoExpressCheckoutPayment', **kwargs)
def generate_express_checkout_redirect_url(self, token, useraction=None):
"""Returns the URL to redirect the user to for the Express checkout.
Express Checkouts must be verified by the customer by redirecting them
to the PayPal website. Use the token returned in the response from
:meth:`set_express_checkout` with this function to figure out where
to redirect the user to.
The button text on the PayPal page can be controlled via `useraction`.
The documented possible values are `commit` and `continue`. However,
any other value will only result in a warning.
:param str token: The unique token identifying this transaction.
:param str useraction: Control the button text on the PayPal page.
:rtype: str
:returns: The URL to redirect the user to for approval.
"""
url_vars = (self.config.PAYPAL_URL_BASE, token)
url = "%s?cmd=_express-checkout&token=%s" % url_vars
if useraction:
if not useraction.lower() in ('commit', 'continue'):
warnings.warn('useraction=%s is not documented' % useraction,
RuntimeWarning)
url += '&useraction=%s' % useraction
return url
def generate_cart_upload_redirect_url(self, **kwargs):
"""https://www.sandbox.paypal.com/webscr
?cmd=_cart
&upload=1
"""
required_vals = ('business', 'item_name_1', 'amount_1', 'quantity_1')
self._check_required(required_vals, **kwargs)
url = "%s?cmd=_cart&upload=1" % self.config.PAYPAL_URL_BASE
additional = self._encode_utf8(**kwargs)
additional = urlencode(additional)
return url + "&" + additional
def get_recurring_payments_profile_details(self, profileid):
"""Shortcut for the GetRecurringPaymentsProfile method.
This returns details for a recurring payment plan. The ``profileid`` is
a value included in the response retrieved by the function
``create_recurring_payments_profile``. The profile details include the
data provided when the profile was created as well as default values
for ignored fields and some pertinent stastics.
e.g.:
response = create_recurring_payments_profile(**profile_info)
profileid = response.PROFILEID
details = get_recurring_payments_profile(profileid)
The response from PayPal is somewhat self-explanatory, but for a
description of each field, visit the following URI:
https://www.x.com/docs/DOC-1194
"""
args = self._sanitize_locals(locals())
return self._call('GetRecurringPaymentsProfileDetails', **args)
def manage_recurring_payments_profile_status(self, profileid, action,
note=None):
"""Shortcut to the ManageRecurringPaymentsProfileStatus method.
``profileid`` is the same profile id used for getting profile details.
``action`` should be either 'Cancel', 'Suspend', or 'Reactivate'.
``note`` is optional and is visible to the user. It contains the
reason for the change in status.
"""
args = self._sanitize_locals(locals())
if not note:
del args['note']
return self._call('ManageRecurringPaymentsProfileStatus', **args)
def update_recurring_payments_profile(self, profileid, **kwargs):
"""Shortcut to the UpdateRecurringPaymentsProfile method.
``profileid`` is the same profile id used for getting profile details.
The keyed arguments are data in the payment profile which you wish to
change. The profileid does not change. Anything else will take the new
value. Most of, though not all of, the fields available are shared
with creating a profile, but for the complete list of parameters, you
can visit the following URI:
https://www.x.com/docs/DOC-1212
"""
kwargs.update(self._sanitize_locals(locals()))
return self._call('UpdateRecurringPaymentsProfile', **kwargs)
def bm_create_button(self, **kwargs):
"""Shortcut to the BMCreateButton method.
See the docs for details on arguments:
https://cms.paypal.com/mx/cgi-bin/?cmd=_render-content&content_ID=developer/e_howto_api_nvp_BMCreateButton
The L_BUTTONVARn fields are especially important, so make sure to
read those and act accordingly. See unit tests for some examples.
"""
kwargs.update(self._sanitize_locals(locals()))
return self._call('BMCreateButton', **kwargs)
|
gtaylor/paypal-python
|
paypal/interface.py
|
PayPalInterface._get_call_params
|
python
|
def _get_call_params(self, method, **kwargs):
payload = {'METHOD': method,
'VERSION': self.config.API_VERSION}
certificate = None
if self.config.API_AUTHENTICATION_MODE == "3TOKEN":
payload['USER'] = self.config.API_USERNAME
payload['PWD'] = self.config.API_PASSWORD
payload['SIGNATURE'] = self.config.API_SIGNATURE
elif self.config.API_AUTHENTICATION_MODE == "CERTIFICATE":
payload['USER'] = self.config.API_USERNAME
payload['PWD'] = self.config.API_PASSWORD
certificate = (self.config.API_CERTIFICATE_FILENAME,
self.config.API_KEY_FILENAME)
elif self.config.API_AUTHENTICATION_MODE == "UNIPAY":
payload['SUBJECT'] = self.config.UNIPAY_SUBJECT
none_configs = [config for config, value in payload.items()
if value is None]
if none_configs:
raise PayPalConfigError(
"Config(s) %s cannot be None. Please, check this "
"interface's config." % none_configs)
# all keys in the payload must be uppercase
for key, value in kwargs.items():
payload[key.upper()] = value
return {'data': payload,
'cert': certificate,
'url': self.config.API_ENDPOINT,
'timeout': self.config.HTTP_TIMEOUT,
'verify': self.config.API_CA_CERTS}
|
Returns the prepared call parameters. Mind, these will be keyword
arguments to ``requests.post``.
``method`` the NVP method
``kwargs`` the actual call parameters
|
train
|
https://github.com/gtaylor/paypal-python/blob/aa7a987ea9e9b7f37bcd8a8b54a440aad6c871b1/paypal/interface.py#L122-L161
| null |
class PayPalInterface(object):
__credentials = ['USER', 'PWD', 'SIGNATURE', 'SUBJECT']
"""
The end developers will do 95% of their work through this class. API
queries, configuration, etc, all go through here. See the __init__ method
for config related details.
"""
def __init__(self, config=None, **kwargs):
"""
Constructor, which passes all config directives to the config class
via kwargs. For example:
paypal = PayPalInterface(API_USERNAME='somevalue')
Optionally, you may pass a 'config' kwarg to provide your own
PayPalConfig object.
"""
if config:
# User provided their own PayPalConfig object.
self.config = config
else:
# Take the kwargs and stuff them in a new PayPalConfig object.
self.config = PayPalConfig(**kwargs)
def _encode_utf8(self, **kwargs):
"""
UTF8 encodes all of the NVP values.
"""
if is_py3:
# This is only valid for Python 2. In Python 3, unicode is
# everywhere (yay).
return kwargs
unencoded_pairs = kwargs
for i in unencoded_pairs.keys():
#noinspection PyUnresolvedReferences
if isinstance(unencoded_pairs[i], types.UnicodeType):
unencoded_pairs[i] = unencoded_pairs[i].encode('utf-8')
return unencoded_pairs
def _check_required(self, requires, **kwargs):
"""
Checks kwargs for the values specified in 'requires', which is a tuple
of strings. These strings are the NVP names of the required values.
"""
for req in requires:
# PayPal api is never mixed-case.
if req.lower() not in kwargs and req.upper() not in kwargs:
raise PayPalError('missing required : %s' % req)
def _sanitize_locals(self, data):
"""
Remove the 'self' key in locals()
It's more explicit to do it in one function
"""
if 'self' in data:
data = data.copy()
del data['self']
return data
def _call(self, method, **kwargs):
"""
Wrapper method for executing all API commands over HTTP. This method is
further used to implement wrapper methods listed here:
https://www.x.com/docs/DOC-1374
``method`` must be a supported NVP method listed at the above address.
``kwargs`` the actual call parameters
"""
post_params = self._get_call_params(method, **kwargs)
payload = post_params['data']
api_endpoint = post_params['url']
# This shows all of the key/val pairs we're sending to PayPal.
if logger.isEnabledFor(logging.DEBUG):
logger.debug('PayPal NVP Query Key/Vals:\n%s' % pformat(payload))
http_response = requests.post(**post_params)
response = PayPalResponse(http_response.text, self.config)
logger.debug('PayPal NVP API Endpoint: %s' % api_endpoint)
if not response.success:
raise PayPalAPIResponseError(response)
return response
def address_verify(self, email, street, zip):
"""Shortcut for the AddressVerify method.
``email``::
Email address of a PayPal member to verify.
Maximum string length: 255 single-byte characters
Input mask: ?@?.??
``street``::
First line of the billing or shipping postal address to verify.
To pass verification, the value of Street must match the first three
single-byte characters of a postal address on file for the PayPal member.
Maximum string length: 35 single-byte characters.
Alphanumeric plus - , . ‘ # \
Whitespace and case of input value are ignored.
``zip``::
Postal code to verify.
To pass verification, the value of Zip mustmatch the first five
single-byte characters of the postal code of the verified postal
address for the verified PayPal member.
Maximumstring length: 16 single-byte characters.
Whitespace and case of input value are ignored.
"""
args = self._sanitize_locals(locals())
return self._call('AddressVerify', **args)
def create_recurring_payments_profile(self, **kwargs):
"""Shortcut for the CreateRecurringPaymentsProfile method.
Currently, this method only supports the Direct Payment flavor.
It requires standard credit card information and a few additional
parameters related to the billing. e.g.:
profile_info = {
# Credit card information
'creditcardtype': 'Visa',
'acct': '4812177017895760',
'expdate': '102015',
'cvv2': '123',
'firstname': 'John',
'lastname': 'Doe',
'street': '1313 Mockingbird Lane',
'city': 'Beverly Hills',
'state': 'CA',
'zip': '90110',
'countrycode': 'US',
'currencycode': 'USD',
# Recurring payment information
'profilestartdate': '2010-10-25T0:0:0',
'billingperiod': 'Month',
'billingfrequency': '6',
'amt': '10.00',
'desc': '6 months of our product.'
}
response = create_recurring_payments_profile(**profile_info)
The above NVPs compose the bare-minimum request for creating a
profile. For the complete list of parameters, visit this URI:
https://www.x.com/docs/DOC-1168
"""
return self._call('CreateRecurringPaymentsProfile', **kwargs)
def do_authorization(self, transactionid, amt):
"""Shortcut for the DoAuthorization method.
Use the TRANSACTIONID from DoExpressCheckoutPayment for the
``transactionid``. The latest version of the API does not support the
creation of an Order from `DoDirectPayment`.
The `amt` should be the same as passed to `DoExpressCheckoutPayment`.
Flow for a payment involving a `DoAuthorization` call::
1. One or many calls to `SetExpressCheckout` with pertinent order
details, returns `TOKEN`
1. `DoExpressCheckoutPayment` with `TOKEN`, `PAYMENTACTION` set to
Order, `AMT` set to the amount of the transaction, returns
`TRANSACTIONID`
1. `DoAuthorization` with `TRANSACTIONID` and `AMT` set to the
amount of the transaction.
1. `DoCapture` with the `AUTHORIZATIONID` (the `TRANSACTIONID`
returned by `DoAuthorization`)
"""
args = self._sanitize_locals(locals())
return self._call('DoAuthorization', **args)
def do_capture(self, authorizationid, amt, completetype='Complete',
**kwargs):
"""Shortcut for the DoCapture method.
Use the TRANSACTIONID from DoAuthorization, DoDirectPayment or
DoExpressCheckoutPayment for the ``authorizationid``.
The `amt` should be the same as the authorized transaction.
"""
kwargs.update(self._sanitize_locals(locals()))
return self._call('DoCapture', **kwargs)
def do_direct_payment(self, paymentaction="Sale", **kwargs):
"""Shortcut for the DoDirectPayment method.
``paymentaction`` could be 'Authorization' or 'Sale'
To issue a Sale immediately::
charge = {
'amt': '10.00',
'creditcardtype': 'Visa',
'acct': '4812177017895760',
'expdate': '012010',
'cvv2': '962',
'firstname': 'John',
'lastname': 'Doe',
'street': '1 Main St',
'city': 'San Jose',
'state': 'CA',
'zip': '95131',
'countrycode': 'US',
'currencycode': 'USD',
}
direct_payment("Sale", **charge)
Or, since "Sale" is the default:
direct_payment(**charge)
To issue an Authorization, simply pass "Authorization" instead
of "Sale".
You may also explicitly set ``paymentaction`` as a keyword argument:
...
direct_payment(paymentaction="Sale", **charge)
"""
kwargs.update(self._sanitize_locals(locals()))
return self._call('DoDirectPayment', **kwargs)
def do_void(self, **kwargs):
"""Shortcut for the DoVoid method.
Use the TRANSACTIONID from DoAuthorization, DoDirectPayment or
DoExpressCheckoutPayment for the ``AUTHORIZATIONID``.
Required Kwargs
---------------
* AUTHORIZATIONID
"""
return self._call('DoVoid', **kwargs)
def get_express_checkout_details(self, **kwargs):
"""Shortcut for the GetExpressCheckoutDetails method.
Required Kwargs
---------------
* TOKEN
"""
return self._call('GetExpressCheckoutDetails', **kwargs)
def get_transaction_details(self, **kwargs):
"""Shortcut for the GetTransactionDetails method.
Use the TRANSACTIONID from DoAuthorization, DoDirectPayment or
DoExpressCheckoutPayment for the ``transactionid``.
Required Kwargs
---------------
* TRANSACTIONID
"""
return self._call('GetTransactionDetails', **kwargs)
def transaction_search(self, **kwargs):
"""Shortcut for the TransactionSearch method.
Returns a PayPalResponseList object, which merges the L_ syntax list
to a list of dictionaries with properly named keys.
Note that the API will limit returned transactions to 100.
Required Kwargs
---------------
* STARTDATE
Optional Kwargs
---------------
STATUS = one of ['Pending','Processing','Success','Denied','Reversed']
"""
plain = self._call('TransactionSearch', **kwargs)
return PayPalResponseList(plain.raw, self.config)
def set_express_checkout(self, **kwargs):
"""Start an Express checkout.
You'll want to use this in conjunction with
:meth:`generate_express_checkout_redirect_url` to create a payment,
then figure out where to redirect the user to for them to
authorize the payment on PayPal's website.
Required Kwargs
---------------
* PAYMENTREQUEST_0_AMT
* PAYMENTREQUEST_0_PAYMENTACTION
* RETURNURL
* CANCELURL
"""
return self._call('SetExpressCheckout', **kwargs)
def refund_transaction(self, transactionid=None, payerid=None, **kwargs):
"""Shortcut for RefundTransaction method.
Note new API supports passing a PayerID instead of a transaction id,
exactly one must be provided.
Optional:
INVOICEID
REFUNDTYPE
AMT
CURRENCYCODE
NOTE
RETRYUNTIL
REFUNDSOURCE
MERCHANTSTOREDETAILS
REFUNDADVICE
REFUNDITEMDETAILS
MSGSUBID
MERCHANSTOREDETAILS has two fields:
STOREID
TERMINALID
"""
# This line seems like a complete waste of time... kwargs should not
# be populated
if (transactionid is None) and (payerid is None):
raise PayPalError(
'RefundTransaction requires either a transactionid or '
'a payerid')
if (transactionid is not None) and (payerid is not None):
raise PayPalError(
'RefundTransaction requires only one of transactionid %s '
'and payerid %s' % (transactionid, payerid))
if transactionid is not None:
kwargs['TRANSACTIONID'] = transactionid
else:
kwargs['PAYERID'] = payerid
return self._call('RefundTransaction', **kwargs)
def do_express_checkout_payment(self, **kwargs):
"""Finishes an Express checkout.
TOKEN is the token that was returned earlier by
:meth:`set_express_checkout`. This identifies the transaction.
Required
--------
* TOKEN
* PAYMENTACTION
* PAYERID
* AMT
"""
return self._call('DoExpressCheckoutPayment', **kwargs)
def generate_express_checkout_redirect_url(self, token, useraction=None):
"""Returns the URL to redirect the user to for the Express checkout.
Express Checkouts must be verified by the customer by redirecting them
to the PayPal website. Use the token returned in the response from
:meth:`set_express_checkout` with this function to figure out where
to redirect the user to.
The button text on the PayPal page can be controlled via `useraction`.
The documented possible values are `commit` and `continue`. However,
any other value will only result in a warning.
:param str token: The unique token identifying this transaction.
:param str useraction: Control the button text on the PayPal page.
:rtype: str
:returns: The URL to redirect the user to for approval.
"""
url_vars = (self.config.PAYPAL_URL_BASE, token)
url = "%s?cmd=_express-checkout&token=%s" % url_vars
if useraction:
if not useraction.lower() in ('commit', 'continue'):
warnings.warn('useraction=%s is not documented' % useraction,
RuntimeWarning)
url += '&useraction=%s' % useraction
return url
def generate_cart_upload_redirect_url(self, **kwargs):
"""https://www.sandbox.paypal.com/webscr
?cmd=_cart
&upload=1
"""
required_vals = ('business', 'item_name_1', 'amount_1', 'quantity_1')
self._check_required(required_vals, **kwargs)
url = "%s?cmd=_cart&upload=1" % self.config.PAYPAL_URL_BASE
additional = self._encode_utf8(**kwargs)
additional = urlencode(additional)
return url + "&" + additional
def get_recurring_payments_profile_details(self, profileid):
"""Shortcut for the GetRecurringPaymentsProfile method.
This returns details for a recurring payment plan. The ``profileid`` is
a value included in the response retrieved by the function
``create_recurring_payments_profile``. The profile details include the
data provided when the profile was created as well as default values
for ignored fields and some pertinent stastics.
e.g.:
response = create_recurring_payments_profile(**profile_info)
profileid = response.PROFILEID
details = get_recurring_payments_profile(profileid)
The response from PayPal is somewhat self-explanatory, but for a
description of each field, visit the following URI:
https://www.x.com/docs/DOC-1194
"""
args = self._sanitize_locals(locals())
return self._call('GetRecurringPaymentsProfileDetails', **args)
def manage_recurring_payments_profile_status(self, profileid, action,
note=None):
"""Shortcut to the ManageRecurringPaymentsProfileStatus method.
``profileid`` is the same profile id used for getting profile details.
``action`` should be either 'Cancel', 'Suspend', or 'Reactivate'.
``note`` is optional and is visible to the user. It contains the
reason for the change in status.
"""
args = self._sanitize_locals(locals())
if not note:
del args['note']
return self._call('ManageRecurringPaymentsProfileStatus', **args)
def update_recurring_payments_profile(self, profileid, **kwargs):
"""Shortcut to the UpdateRecurringPaymentsProfile method.
``profileid`` is the same profile id used for getting profile details.
The keyed arguments are data in the payment profile which you wish to
change. The profileid does not change. Anything else will take the new
value. Most of, though not all of, the fields available are shared
with creating a profile, but for the complete list of parameters, you
can visit the following URI:
https://www.x.com/docs/DOC-1212
"""
kwargs.update(self._sanitize_locals(locals()))
return self._call('UpdateRecurringPaymentsProfile', **kwargs)
def bm_create_button(self, **kwargs):
"""Shortcut to the BMCreateButton method.
See the docs for details on arguments:
https://cms.paypal.com/mx/cgi-bin/?cmd=_render-content&content_ID=developer/e_howto_api_nvp_BMCreateButton
The L_BUTTONVARn fields are especially important, so make sure to
read those and act accordingly. See unit tests for some examples.
"""
kwargs.update(self._sanitize_locals(locals()))
return self._call('BMCreateButton', **kwargs)
|
gtaylor/paypal-python
|
paypal/interface.py
|
PayPalInterface.address_verify
|
python
|
def address_verify(self, email, street, zip):
args = self._sanitize_locals(locals())
return self._call('AddressVerify', **args)
|
Shortcut for the AddressVerify method.
``email``::
Email address of a PayPal member to verify.
Maximum string length: 255 single-byte characters
Input mask: ?@?.??
``street``::
First line of the billing or shipping postal address to verify.
To pass verification, the value of Street must match the first three
single-byte characters of a postal address on file for the PayPal member.
Maximum string length: 35 single-byte characters.
Alphanumeric plus - , . ‘ # \
Whitespace and case of input value are ignored.
``zip``::
Postal code to verify.
To pass verification, the value of Zip mustmatch the first five
single-byte characters of the postal code of the verified postal
address for the verified PayPal member.
Maximumstring length: 16 single-byte characters.
Whitespace and case of input value are ignored.
|
train
|
https://github.com/gtaylor/paypal-python/blob/aa7a987ea9e9b7f37bcd8a8b54a440aad6c871b1/paypal/interface.py#L163-L190
|
[
"def _sanitize_locals(self, data):\n \"\"\"\n Remove the 'self' key in locals()\n It's more explicit to do it in one function\n \"\"\"\n if 'self' in data:\n data = data.copy()\n del data['self']\n\n return data\n",
"def _call(self, method, **kwargs):\n \"\"\"\n Wrapper method for executing all API commands over HTTP. This method is\n further used to implement wrapper methods listed here:\n\n https://www.x.com/docs/DOC-1374\n\n ``method`` must be a supported NVP method listed at the above address.\n ``kwargs`` the actual call parameters\n \"\"\"\n post_params = self._get_call_params(method, **kwargs)\n payload = post_params['data']\n api_endpoint = post_params['url']\n\n # This shows all of the key/val pairs we're sending to PayPal.\n if logger.isEnabledFor(logging.DEBUG):\n logger.debug('PayPal NVP Query Key/Vals:\\n%s' % pformat(payload))\n\n http_response = requests.post(**post_params)\n response = PayPalResponse(http_response.text, self.config)\n logger.debug('PayPal NVP API Endpoint: %s' % api_endpoint)\n\n if not response.success:\n raise PayPalAPIResponseError(response)\n\n return response\n"
] |
class PayPalInterface(object):
__credentials = ['USER', 'PWD', 'SIGNATURE', 'SUBJECT']
"""
The end developers will do 95% of their work through this class. API
queries, configuration, etc, all go through here. See the __init__ method
for config related details.
"""
def __init__(self, config=None, **kwargs):
"""
Constructor, which passes all config directives to the config class
via kwargs. For example:
paypal = PayPalInterface(API_USERNAME='somevalue')
Optionally, you may pass a 'config' kwarg to provide your own
PayPalConfig object.
"""
if config:
# User provided their own PayPalConfig object.
self.config = config
else:
# Take the kwargs and stuff them in a new PayPalConfig object.
self.config = PayPalConfig(**kwargs)
def _encode_utf8(self, **kwargs):
"""
UTF8 encodes all of the NVP values.
"""
if is_py3:
# This is only valid for Python 2. In Python 3, unicode is
# everywhere (yay).
return kwargs
unencoded_pairs = kwargs
for i in unencoded_pairs.keys():
#noinspection PyUnresolvedReferences
if isinstance(unencoded_pairs[i], types.UnicodeType):
unencoded_pairs[i] = unencoded_pairs[i].encode('utf-8')
return unencoded_pairs
def _check_required(self, requires, **kwargs):
"""
Checks kwargs for the values specified in 'requires', which is a tuple
of strings. These strings are the NVP names of the required values.
"""
for req in requires:
# PayPal api is never mixed-case.
if req.lower() not in kwargs and req.upper() not in kwargs:
raise PayPalError('missing required : %s' % req)
def _sanitize_locals(self, data):
"""
Remove the 'self' key in locals()
It's more explicit to do it in one function
"""
if 'self' in data:
data = data.copy()
del data['self']
return data
def _call(self, method, **kwargs):
"""
Wrapper method for executing all API commands over HTTP. This method is
further used to implement wrapper methods listed here:
https://www.x.com/docs/DOC-1374
``method`` must be a supported NVP method listed at the above address.
``kwargs`` the actual call parameters
"""
post_params = self._get_call_params(method, **kwargs)
payload = post_params['data']
api_endpoint = post_params['url']
# This shows all of the key/val pairs we're sending to PayPal.
if logger.isEnabledFor(logging.DEBUG):
logger.debug('PayPal NVP Query Key/Vals:\n%s' % pformat(payload))
http_response = requests.post(**post_params)
response = PayPalResponse(http_response.text, self.config)
logger.debug('PayPal NVP API Endpoint: %s' % api_endpoint)
if not response.success:
raise PayPalAPIResponseError(response)
return response
def _get_call_params(self, method, **kwargs):
"""
Returns the prepared call parameters. Mind, these will be keyword
arguments to ``requests.post``.
``method`` the NVP method
``kwargs`` the actual call parameters
"""
payload = {'METHOD': method,
'VERSION': self.config.API_VERSION}
certificate = None
if self.config.API_AUTHENTICATION_MODE == "3TOKEN":
payload['USER'] = self.config.API_USERNAME
payload['PWD'] = self.config.API_PASSWORD
payload['SIGNATURE'] = self.config.API_SIGNATURE
elif self.config.API_AUTHENTICATION_MODE == "CERTIFICATE":
payload['USER'] = self.config.API_USERNAME
payload['PWD'] = self.config.API_PASSWORD
certificate = (self.config.API_CERTIFICATE_FILENAME,
self.config.API_KEY_FILENAME)
elif self.config.API_AUTHENTICATION_MODE == "UNIPAY":
payload['SUBJECT'] = self.config.UNIPAY_SUBJECT
none_configs = [config for config, value in payload.items()
if value is None]
if none_configs:
raise PayPalConfigError(
"Config(s) %s cannot be None. Please, check this "
"interface's config." % none_configs)
# all keys in the payload must be uppercase
for key, value in kwargs.items():
payload[key.upper()] = value
return {'data': payload,
'cert': certificate,
'url': self.config.API_ENDPOINT,
'timeout': self.config.HTTP_TIMEOUT,
'verify': self.config.API_CA_CERTS}
def create_recurring_payments_profile(self, **kwargs):
"""Shortcut for the CreateRecurringPaymentsProfile method.
Currently, this method only supports the Direct Payment flavor.
It requires standard credit card information and a few additional
parameters related to the billing. e.g.:
profile_info = {
# Credit card information
'creditcardtype': 'Visa',
'acct': '4812177017895760',
'expdate': '102015',
'cvv2': '123',
'firstname': 'John',
'lastname': 'Doe',
'street': '1313 Mockingbird Lane',
'city': 'Beverly Hills',
'state': 'CA',
'zip': '90110',
'countrycode': 'US',
'currencycode': 'USD',
# Recurring payment information
'profilestartdate': '2010-10-25T0:0:0',
'billingperiod': 'Month',
'billingfrequency': '6',
'amt': '10.00',
'desc': '6 months of our product.'
}
response = create_recurring_payments_profile(**profile_info)
The above NVPs compose the bare-minimum request for creating a
profile. For the complete list of parameters, visit this URI:
https://www.x.com/docs/DOC-1168
"""
return self._call('CreateRecurringPaymentsProfile', **kwargs)
def do_authorization(self, transactionid, amt):
"""Shortcut for the DoAuthorization method.
Use the TRANSACTIONID from DoExpressCheckoutPayment for the
``transactionid``. The latest version of the API does not support the
creation of an Order from `DoDirectPayment`.
The `amt` should be the same as passed to `DoExpressCheckoutPayment`.
Flow for a payment involving a `DoAuthorization` call::
1. One or many calls to `SetExpressCheckout` with pertinent order
details, returns `TOKEN`
1. `DoExpressCheckoutPayment` with `TOKEN`, `PAYMENTACTION` set to
Order, `AMT` set to the amount of the transaction, returns
`TRANSACTIONID`
1. `DoAuthorization` with `TRANSACTIONID` and `AMT` set to the
amount of the transaction.
1. `DoCapture` with the `AUTHORIZATIONID` (the `TRANSACTIONID`
returned by `DoAuthorization`)
"""
args = self._sanitize_locals(locals())
return self._call('DoAuthorization', **args)
def do_capture(self, authorizationid, amt, completetype='Complete',
**kwargs):
"""Shortcut for the DoCapture method.
Use the TRANSACTIONID from DoAuthorization, DoDirectPayment or
DoExpressCheckoutPayment for the ``authorizationid``.
The `amt` should be the same as the authorized transaction.
"""
kwargs.update(self._sanitize_locals(locals()))
return self._call('DoCapture', **kwargs)
def do_direct_payment(self, paymentaction="Sale", **kwargs):
"""Shortcut for the DoDirectPayment method.
``paymentaction`` could be 'Authorization' or 'Sale'
To issue a Sale immediately::
charge = {
'amt': '10.00',
'creditcardtype': 'Visa',
'acct': '4812177017895760',
'expdate': '012010',
'cvv2': '962',
'firstname': 'John',
'lastname': 'Doe',
'street': '1 Main St',
'city': 'San Jose',
'state': 'CA',
'zip': '95131',
'countrycode': 'US',
'currencycode': 'USD',
}
direct_payment("Sale", **charge)
Or, since "Sale" is the default:
direct_payment(**charge)
To issue an Authorization, simply pass "Authorization" instead
of "Sale".
You may also explicitly set ``paymentaction`` as a keyword argument:
...
direct_payment(paymentaction="Sale", **charge)
"""
kwargs.update(self._sanitize_locals(locals()))
return self._call('DoDirectPayment', **kwargs)
def do_void(self, **kwargs):
"""Shortcut for the DoVoid method.
Use the TRANSACTIONID from DoAuthorization, DoDirectPayment or
DoExpressCheckoutPayment for the ``AUTHORIZATIONID``.
Required Kwargs
---------------
* AUTHORIZATIONID
"""
return self._call('DoVoid', **kwargs)
def get_express_checkout_details(self, **kwargs):
"""Shortcut for the GetExpressCheckoutDetails method.
Required Kwargs
---------------
* TOKEN
"""
return self._call('GetExpressCheckoutDetails', **kwargs)
def get_transaction_details(self, **kwargs):
"""Shortcut for the GetTransactionDetails method.
Use the TRANSACTIONID from DoAuthorization, DoDirectPayment or
DoExpressCheckoutPayment for the ``transactionid``.
Required Kwargs
---------------
* TRANSACTIONID
"""
return self._call('GetTransactionDetails', **kwargs)
def transaction_search(self, **kwargs):
"""Shortcut for the TransactionSearch method.
Returns a PayPalResponseList object, which merges the L_ syntax list
to a list of dictionaries with properly named keys.
Note that the API will limit returned transactions to 100.
Required Kwargs
---------------
* STARTDATE
Optional Kwargs
---------------
STATUS = one of ['Pending','Processing','Success','Denied','Reversed']
"""
plain = self._call('TransactionSearch', **kwargs)
return PayPalResponseList(plain.raw, self.config)
def set_express_checkout(self, **kwargs):
"""Start an Express checkout.
You'll want to use this in conjunction with
:meth:`generate_express_checkout_redirect_url` to create a payment,
then figure out where to redirect the user to for them to
authorize the payment on PayPal's website.
Required Kwargs
---------------
* PAYMENTREQUEST_0_AMT
* PAYMENTREQUEST_0_PAYMENTACTION
* RETURNURL
* CANCELURL
"""
return self._call('SetExpressCheckout', **kwargs)
def refund_transaction(self, transactionid=None, payerid=None, **kwargs):
"""Shortcut for RefundTransaction method.
Note new API supports passing a PayerID instead of a transaction id,
exactly one must be provided.
Optional:
INVOICEID
REFUNDTYPE
AMT
CURRENCYCODE
NOTE
RETRYUNTIL
REFUNDSOURCE
MERCHANTSTOREDETAILS
REFUNDADVICE
REFUNDITEMDETAILS
MSGSUBID
MERCHANSTOREDETAILS has two fields:
STOREID
TERMINALID
"""
# This line seems like a complete waste of time... kwargs should not
# be populated
if (transactionid is None) and (payerid is None):
raise PayPalError(
'RefundTransaction requires either a transactionid or '
'a payerid')
if (transactionid is not None) and (payerid is not None):
raise PayPalError(
'RefundTransaction requires only one of transactionid %s '
'and payerid %s' % (transactionid, payerid))
if transactionid is not None:
kwargs['TRANSACTIONID'] = transactionid
else:
kwargs['PAYERID'] = payerid
return self._call('RefundTransaction', **kwargs)
def do_express_checkout_payment(self, **kwargs):
"""Finishes an Express checkout.
TOKEN is the token that was returned earlier by
:meth:`set_express_checkout`. This identifies the transaction.
Required
--------
* TOKEN
* PAYMENTACTION
* PAYERID
* AMT
"""
return self._call('DoExpressCheckoutPayment', **kwargs)
def generate_express_checkout_redirect_url(self, token, useraction=None):
"""Returns the URL to redirect the user to for the Express checkout.
Express Checkouts must be verified by the customer by redirecting them
to the PayPal website. Use the token returned in the response from
:meth:`set_express_checkout` with this function to figure out where
to redirect the user to.
The button text on the PayPal page can be controlled via `useraction`.
The documented possible values are `commit` and `continue`. However,
any other value will only result in a warning.
:param str token: The unique token identifying this transaction.
:param str useraction: Control the button text on the PayPal page.
:rtype: str
:returns: The URL to redirect the user to for approval.
"""
url_vars = (self.config.PAYPAL_URL_BASE, token)
url = "%s?cmd=_express-checkout&token=%s" % url_vars
if useraction:
if not useraction.lower() in ('commit', 'continue'):
warnings.warn('useraction=%s is not documented' % useraction,
RuntimeWarning)
url += '&useraction=%s' % useraction
return url
def generate_cart_upload_redirect_url(self, **kwargs):
"""https://www.sandbox.paypal.com/webscr
?cmd=_cart
&upload=1
"""
required_vals = ('business', 'item_name_1', 'amount_1', 'quantity_1')
self._check_required(required_vals, **kwargs)
url = "%s?cmd=_cart&upload=1" % self.config.PAYPAL_URL_BASE
additional = self._encode_utf8(**kwargs)
additional = urlencode(additional)
return url + "&" + additional
def get_recurring_payments_profile_details(self, profileid):
"""Shortcut for the GetRecurringPaymentsProfile method.
This returns details for a recurring payment plan. The ``profileid`` is
a value included in the response retrieved by the function
``create_recurring_payments_profile``. The profile details include the
data provided when the profile was created as well as default values
for ignored fields and some pertinent stastics.
e.g.:
response = create_recurring_payments_profile(**profile_info)
profileid = response.PROFILEID
details = get_recurring_payments_profile(profileid)
The response from PayPal is somewhat self-explanatory, but for a
description of each field, visit the following URI:
https://www.x.com/docs/DOC-1194
"""
args = self._sanitize_locals(locals())
return self._call('GetRecurringPaymentsProfileDetails', **args)
def manage_recurring_payments_profile_status(self, profileid, action,
note=None):
"""Shortcut to the ManageRecurringPaymentsProfileStatus method.
``profileid`` is the same profile id used for getting profile details.
``action`` should be either 'Cancel', 'Suspend', or 'Reactivate'.
``note`` is optional and is visible to the user. It contains the
reason for the change in status.
"""
args = self._sanitize_locals(locals())
if not note:
del args['note']
return self._call('ManageRecurringPaymentsProfileStatus', **args)
def update_recurring_payments_profile(self, profileid, **kwargs):
"""Shortcut to the UpdateRecurringPaymentsProfile method.
``profileid`` is the same profile id used for getting profile details.
The keyed arguments are data in the payment profile which you wish to
change. The profileid does not change. Anything else will take the new
value. Most of, though not all of, the fields available are shared
with creating a profile, but for the complete list of parameters, you
can visit the following URI:
https://www.x.com/docs/DOC-1212
"""
kwargs.update(self._sanitize_locals(locals()))
return self._call('UpdateRecurringPaymentsProfile', **kwargs)
def bm_create_button(self, **kwargs):
"""Shortcut to the BMCreateButton method.
See the docs for details on arguments:
https://cms.paypal.com/mx/cgi-bin/?cmd=_render-content&content_ID=developer/e_howto_api_nvp_BMCreateButton
The L_BUTTONVARn fields are especially important, so make sure to
read those and act accordingly. See unit tests for some examples.
"""
kwargs.update(self._sanitize_locals(locals()))
return self._call('BMCreateButton', **kwargs)
|
gtaylor/paypal-python
|
paypal/interface.py
|
PayPalInterface.do_authorization
|
python
|
def do_authorization(self, transactionid, amt):
args = self._sanitize_locals(locals())
return self._call('DoAuthorization', **args)
|
Shortcut for the DoAuthorization method.
Use the TRANSACTIONID from DoExpressCheckoutPayment for the
``transactionid``. The latest version of the API does not support the
creation of an Order from `DoDirectPayment`.
The `amt` should be the same as passed to `DoExpressCheckoutPayment`.
Flow for a payment involving a `DoAuthorization` call::
1. One or many calls to `SetExpressCheckout` with pertinent order
details, returns `TOKEN`
1. `DoExpressCheckoutPayment` with `TOKEN`, `PAYMENTACTION` set to
Order, `AMT` set to the amount of the transaction, returns
`TRANSACTIONID`
1. `DoAuthorization` with `TRANSACTIONID` and `AMT` set to the
amount of the transaction.
1. `DoCapture` with the `AUTHORIZATIONID` (the `TRANSACTIONID`
returned by `DoAuthorization`)
|
train
|
https://github.com/gtaylor/paypal-python/blob/aa7a987ea9e9b7f37bcd8a8b54a440aad6c871b1/paypal/interface.py#L228-L251
|
[
"def _sanitize_locals(self, data):\n \"\"\"\n Remove the 'self' key in locals()\n It's more explicit to do it in one function\n \"\"\"\n if 'self' in data:\n data = data.copy()\n del data['self']\n\n return data\n",
"def _call(self, method, **kwargs):\n \"\"\"\n Wrapper method for executing all API commands over HTTP. This method is\n further used to implement wrapper methods listed here:\n\n https://www.x.com/docs/DOC-1374\n\n ``method`` must be a supported NVP method listed at the above address.\n ``kwargs`` the actual call parameters\n \"\"\"\n post_params = self._get_call_params(method, **kwargs)\n payload = post_params['data']\n api_endpoint = post_params['url']\n\n # This shows all of the key/val pairs we're sending to PayPal.\n if logger.isEnabledFor(logging.DEBUG):\n logger.debug('PayPal NVP Query Key/Vals:\\n%s' % pformat(payload))\n\n http_response = requests.post(**post_params)\n response = PayPalResponse(http_response.text, self.config)\n logger.debug('PayPal NVP API Endpoint: %s' % api_endpoint)\n\n if not response.success:\n raise PayPalAPIResponseError(response)\n\n return response\n"
] |
class PayPalInterface(object):
__credentials = ['USER', 'PWD', 'SIGNATURE', 'SUBJECT']
"""
The end developers will do 95% of their work through this class. API
queries, configuration, etc, all go through here. See the __init__ method
for config related details.
"""
def __init__(self, config=None, **kwargs):
"""
Constructor, which passes all config directives to the config class
via kwargs. For example:
paypal = PayPalInterface(API_USERNAME='somevalue')
Optionally, you may pass a 'config' kwarg to provide your own
PayPalConfig object.
"""
if config:
# User provided their own PayPalConfig object.
self.config = config
else:
# Take the kwargs and stuff them in a new PayPalConfig object.
self.config = PayPalConfig(**kwargs)
def _encode_utf8(self, **kwargs):
"""
UTF8 encodes all of the NVP values.
"""
if is_py3:
# This is only valid for Python 2. In Python 3, unicode is
# everywhere (yay).
return kwargs
unencoded_pairs = kwargs
for i in unencoded_pairs.keys():
#noinspection PyUnresolvedReferences
if isinstance(unencoded_pairs[i], types.UnicodeType):
unencoded_pairs[i] = unencoded_pairs[i].encode('utf-8')
return unencoded_pairs
def _check_required(self, requires, **kwargs):
"""
Checks kwargs for the values specified in 'requires', which is a tuple
of strings. These strings are the NVP names of the required values.
"""
for req in requires:
# PayPal api is never mixed-case.
if req.lower() not in kwargs and req.upper() not in kwargs:
raise PayPalError('missing required : %s' % req)
def _sanitize_locals(self, data):
"""
Remove the 'self' key in locals()
It's more explicit to do it in one function
"""
if 'self' in data:
data = data.copy()
del data['self']
return data
def _call(self, method, **kwargs):
"""
Wrapper method for executing all API commands over HTTP. This method is
further used to implement wrapper methods listed here:
https://www.x.com/docs/DOC-1374
``method`` must be a supported NVP method listed at the above address.
``kwargs`` the actual call parameters
"""
post_params = self._get_call_params(method, **kwargs)
payload = post_params['data']
api_endpoint = post_params['url']
# This shows all of the key/val pairs we're sending to PayPal.
if logger.isEnabledFor(logging.DEBUG):
logger.debug('PayPal NVP Query Key/Vals:\n%s' % pformat(payload))
http_response = requests.post(**post_params)
response = PayPalResponse(http_response.text, self.config)
logger.debug('PayPal NVP API Endpoint: %s' % api_endpoint)
if not response.success:
raise PayPalAPIResponseError(response)
return response
def _get_call_params(self, method, **kwargs):
"""
Returns the prepared call parameters. Mind, these will be keyword
arguments to ``requests.post``.
``method`` the NVP method
``kwargs`` the actual call parameters
"""
payload = {'METHOD': method,
'VERSION': self.config.API_VERSION}
certificate = None
if self.config.API_AUTHENTICATION_MODE == "3TOKEN":
payload['USER'] = self.config.API_USERNAME
payload['PWD'] = self.config.API_PASSWORD
payload['SIGNATURE'] = self.config.API_SIGNATURE
elif self.config.API_AUTHENTICATION_MODE == "CERTIFICATE":
payload['USER'] = self.config.API_USERNAME
payload['PWD'] = self.config.API_PASSWORD
certificate = (self.config.API_CERTIFICATE_FILENAME,
self.config.API_KEY_FILENAME)
elif self.config.API_AUTHENTICATION_MODE == "UNIPAY":
payload['SUBJECT'] = self.config.UNIPAY_SUBJECT
none_configs = [config for config, value in payload.items()
if value is None]
if none_configs:
raise PayPalConfigError(
"Config(s) %s cannot be None. Please, check this "
"interface's config." % none_configs)
# all keys in the payload must be uppercase
for key, value in kwargs.items():
payload[key.upper()] = value
return {'data': payload,
'cert': certificate,
'url': self.config.API_ENDPOINT,
'timeout': self.config.HTTP_TIMEOUT,
'verify': self.config.API_CA_CERTS}
def address_verify(self, email, street, zip):
"""Shortcut for the AddressVerify method.
``email``::
Email address of a PayPal member to verify.
Maximum string length: 255 single-byte characters
Input mask: ?@?.??
``street``::
First line of the billing or shipping postal address to verify.
To pass verification, the value of Street must match the first three
single-byte characters of a postal address on file for the PayPal member.
Maximum string length: 35 single-byte characters.
Alphanumeric plus - , . ‘ # \
Whitespace and case of input value are ignored.
``zip``::
Postal code to verify.
To pass verification, the value of Zip mustmatch the first five
single-byte characters of the postal code of the verified postal
address for the verified PayPal member.
Maximumstring length: 16 single-byte characters.
Whitespace and case of input value are ignored.
"""
args = self._sanitize_locals(locals())
return self._call('AddressVerify', **args)
def create_recurring_payments_profile(self, **kwargs):
"""Shortcut for the CreateRecurringPaymentsProfile method.
Currently, this method only supports the Direct Payment flavor.
It requires standard credit card information and a few additional
parameters related to the billing. e.g.:
profile_info = {
# Credit card information
'creditcardtype': 'Visa',
'acct': '4812177017895760',
'expdate': '102015',
'cvv2': '123',
'firstname': 'John',
'lastname': 'Doe',
'street': '1313 Mockingbird Lane',
'city': 'Beverly Hills',
'state': 'CA',
'zip': '90110',
'countrycode': 'US',
'currencycode': 'USD',
# Recurring payment information
'profilestartdate': '2010-10-25T0:0:0',
'billingperiod': 'Month',
'billingfrequency': '6',
'amt': '10.00',
'desc': '6 months of our product.'
}
response = create_recurring_payments_profile(**profile_info)
The above NVPs compose the bare-minimum request for creating a
profile. For the complete list of parameters, visit this URI:
https://www.x.com/docs/DOC-1168
"""
return self._call('CreateRecurringPaymentsProfile', **kwargs)
def do_capture(self, authorizationid, amt, completetype='Complete',
**kwargs):
"""Shortcut for the DoCapture method.
Use the TRANSACTIONID from DoAuthorization, DoDirectPayment or
DoExpressCheckoutPayment for the ``authorizationid``.
The `amt` should be the same as the authorized transaction.
"""
kwargs.update(self._sanitize_locals(locals()))
return self._call('DoCapture', **kwargs)
def do_direct_payment(self, paymentaction="Sale", **kwargs):
"""Shortcut for the DoDirectPayment method.
``paymentaction`` could be 'Authorization' or 'Sale'
To issue a Sale immediately::
charge = {
'amt': '10.00',
'creditcardtype': 'Visa',
'acct': '4812177017895760',
'expdate': '012010',
'cvv2': '962',
'firstname': 'John',
'lastname': 'Doe',
'street': '1 Main St',
'city': 'San Jose',
'state': 'CA',
'zip': '95131',
'countrycode': 'US',
'currencycode': 'USD',
}
direct_payment("Sale", **charge)
Or, since "Sale" is the default:
direct_payment(**charge)
To issue an Authorization, simply pass "Authorization" instead
of "Sale".
You may also explicitly set ``paymentaction`` as a keyword argument:
...
direct_payment(paymentaction="Sale", **charge)
"""
kwargs.update(self._sanitize_locals(locals()))
return self._call('DoDirectPayment', **kwargs)
def do_void(self, **kwargs):
"""Shortcut for the DoVoid method.
Use the TRANSACTIONID from DoAuthorization, DoDirectPayment or
DoExpressCheckoutPayment for the ``AUTHORIZATIONID``.
Required Kwargs
---------------
* AUTHORIZATIONID
"""
return self._call('DoVoid', **kwargs)
def get_express_checkout_details(self, **kwargs):
"""Shortcut for the GetExpressCheckoutDetails method.
Required Kwargs
---------------
* TOKEN
"""
return self._call('GetExpressCheckoutDetails', **kwargs)
def get_transaction_details(self, **kwargs):
"""Shortcut for the GetTransactionDetails method.
Use the TRANSACTIONID from DoAuthorization, DoDirectPayment or
DoExpressCheckoutPayment for the ``transactionid``.
Required Kwargs
---------------
* TRANSACTIONID
"""
return self._call('GetTransactionDetails', **kwargs)
def transaction_search(self, **kwargs):
"""Shortcut for the TransactionSearch method.
Returns a PayPalResponseList object, which merges the L_ syntax list
to a list of dictionaries with properly named keys.
Note that the API will limit returned transactions to 100.
Required Kwargs
---------------
* STARTDATE
Optional Kwargs
---------------
STATUS = one of ['Pending','Processing','Success','Denied','Reversed']
"""
plain = self._call('TransactionSearch', **kwargs)
return PayPalResponseList(plain.raw, self.config)
def set_express_checkout(self, **kwargs):
"""Start an Express checkout.
You'll want to use this in conjunction with
:meth:`generate_express_checkout_redirect_url` to create a payment,
then figure out where to redirect the user to for them to
authorize the payment on PayPal's website.
Required Kwargs
---------------
* PAYMENTREQUEST_0_AMT
* PAYMENTREQUEST_0_PAYMENTACTION
* RETURNURL
* CANCELURL
"""
return self._call('SetExpressCheckout', **kwargs)
def refund_transaction(self, transactionid=None, payerid=None, **kwargs):
"""Shortcut for RefundTransaction method.
Note new API supports passing a PayerID instead of a transaction id,
exactly one must be provided.
Optional:
INVOICEID
REFUNDTYPE
AMT
CURRENCYCODE
NOTE
RETRYUNTIL
REFUNDSOURCE
MERCHANTSTOREDETAILS
REFUNDADVICE
REFUNDITEMDETAILS
MSGSUBID
MERCHANSTOREDETAILS has two fields:
STOREID
TERMINALID
"""
# This line seems like a complete waste of time... kwargs should not
# be populated
if (transactionid is None) and (payerid is None):
raise PayPalError(
'RefundTransaction requires either a transactionid or '
'a payerid')
if (transactionid is not None) and (payerid is not None):
raise PayPalError(
'RefundTransaction requires only one of transactionid %s '
'and payerid %s' % (transactionid, payerid))
if transactionid is not None:
kwargs['TRANSACTIONID'] = transactionid
else:
kwargs['PAYERID'] = payerid
return self._call('RefundTransaction', **kwargs)
def do_express_checkout_payment(self, **kwargs):
"""Finishes an Express checkout.
TOKEN is the token that was returned earlier by
:meth:`set_express_checkout`. This identifies the transaction.
Required
--------
* TOKEN
* PAYMENTACTION
* PAYERID
* AMT
"""
return self._call('DoExpressCheckoutPayment', **kwargs)
def generate_express_checkout_redirect_url(self, token, useraction=None):
"""Returns the URL to redirect the user to for the Express checkout.
Express Checkouts must be verified by the customer by redirecting them
to the PayPal website. Use the token returned in the response from
:meth:`set_express_checkout` with this function to figure out where
to redirect the user to.
The button text on the PayPal page can be controlled via `useraction`.
The documented possible values are `commit` and `continue`. However,
any other value will only result in a warning.
:param str token: The unique token identifying this transaction.
:param str useraction: Control the button text on the PayPal page.
:rtype: str
:returns: The URL to redirect the user to for approval.
"""
url_vars = (self.config.PAYPAL_URL_BASE, token)
url = "%s?cmd=_express-checkout&token=%s" % url_vars
if useraction:
if not useraction.lower() in ('commit', 'continue'):
warnings.warn('useraction=%s is not documented' % useraction,
RuntimeWarning)
url += '&useraction=%s' % useraction
return url
def generate_cart_upload_redirect_url(self, **kwargs):
"""https://www.sandbox.paypal.com/webscr
?cmd=_cart
&upload=1
"""
required_vals = ('business', 'item_name_1', 'amount_1', 'quantity_1')
self._check_required(required_vals, **kwargs)
url = "%s?cmd=_cart&upload=1" % self.config.PAYPAL_URL_BASE
additional = self._encode_utf8(**kwargs)
additional = urlencode(additional)
return url + "&" + additional
def get_recurring_payments_profile_details(self, profileid):
"""Shortcut for the GetRecurringPaymentsProfile method.
This returns details for a recurring payment plan. The ``profileid`` is
a value included in the response retrieved by the function
``create_recurring_payments_profile``. The profile details include the
data provided when the profile was created as well as default values
for ignored fields and some pertinent stastics.
e.g.:
response = create_recurring_payments_profile(**profile_info)
profileid = response.PROFILEID
details = get_recurring_payments_profile(profileid)
The response from PayPal is somewhat self-explanatory, but for a
description of each field, visit the following URI:
https://www.x.com/docs/DOC-1194
"""
args = self._sanitize_locals(locals())
return self._call('GetRecurringPaymentsProfileDetails', **args)
def manage_recurring_payments_profile_status(self, profileid, action,
note=None):
"""Shortcut to the ManageRecurringPaymentsProfileStatus method.
``profileid`` is the same profile id used for getting profile details.
``action`` should be either 'Cancel', 'Suspend', or 'Reactivate'.
``note`` is optional and is visible to the user. It contains the
reason for the change in status.
"""
args = self._sanitize_locals(locals())
if not note:
del args['note']
return self._call('ManageRecurringPaymentsProfileStatus', **args)
def update_recurring_payments_profile(self, profileid, **kwargs):
"""Shortcut to the UpdateRecurringPaymentsProfile method.
``profileid`` is the same profile id used for getting profile details.
The keyed arguments are data in the payment profile which you wish to
change. The profileid does not change. Anything else will take the new
value. Most of, though not all of, the fields available are shared
with creating a profile, but for the complete list of parameters, you
can visit the following URI:
https://www.x.com/docs/DOC-1212
"""
kwargs.update(self._sanitize_locals(locals()))
return self._call('UpdateRecurringPaymentsProfile', **kwargs)
def bm_create_button(self, **kwargs):
"""Shortcut to the BMCreateButton method.
See the docs for details on arguments:
https://cms.paypal.com/mx/cgi-bin/?cmd=_render-content&content_ID=developer/e_howto_api_nvp_BMCreateButton
The L_BUTTONVARn fields are especially important, so make sure to
read those and act accordingly. See unit tests for some examples.
"""
kwargs.update(self._sanitize_locals(locals()))
return self._call('BMCreateButton', **kwargs)
|
gtaylor/paypal-python
|
paypal/interface.py
|
PayPalInterface.do_capture
|
python
|
def do_capture(self, authorizationid, amt, completetype='Complete',
**kwargs):
kwargs.update(self._sanitize_locals(locals()))
return self._call('DoCapture', **kwargs)
|
Shortcut for the DoCapture method.
Use the TRANSACTIONID from DoAuthorization, DoDirectPayment or
DoExpressCheckoutPayment for the ``authorizationid``.
The `amt` should be the same as the authorized transaction.
|
train
|
https://github.com/gtaylor/paypal-python/blob/aa7a987ea9e9b7f37bcd8a8b54a440aad6c871b1/paypal/interface.py#L253-L263
|
[
"def _sanitize_locals(self, data):\n \"\"\"\n Remove the 'self' key in locals()\n It's more explicit to do it in one function\n \"\"\"\n if 'self' in data:\n data = data.copy()\n del data['self']\n\n return data\n",
"def _call(self, method, **kwargs):\n \"\"\"\n Wrapper method for executing all API commands over HTTP. This method is\n further used to implement wrapper methods listed here:\n\n https://www.x.com/docs/DOC-1374\n\n ``method`` must be a supported NVP method listed at the above address.\n ``kwargs`` the actual call parameters\n \"\"\"\n post_params = self._get_call_params(method, **kwargs)\n payload = post_params['data']\n api_endpoint = post_params['url']\n\n # This shows all of the key/val pairs we're sending to PayPal.\n if logger.isEnabledFor(logging.DEBUG):\n logger.debug('PayPal NVP Query Key/Vals:\\n%s' % pformat(payload))\n\n http_response = requests.post(**post_params)\n response = PayPalResponse(http_response.text, self.config)\n logger.debug('PayPal NVP API Endpoint: %s' % api_endpoint)\n\n if not response.success:\n raise PayPalAPIResponseError(response)\n\n return response\n"
] |
class PayPalInterface(object):
__credentials = ['USER', 'PWD', 'SIGNATURE', 'SUBJECT']
"""
The end developers will do 95% of their work through this class. API
queries, configuration, etc, all go through here. See the __init__ method
for config related details.
"""
def __init__(self, config=None, **kwargs):
"""
Constructor, which passes all config directives to the config class
via kwargs. For example:
paypal = PayPalInterface(API_USERNAME='somevalue')
Optionally, you may pass a 'config' kwarg to provide your own
PayPalConfig object.
"""
if config:
# User provided their own PayPalConfig object.
self.config = config
else:
# Take the kwargs and stuff them in a new PayPalConfig object.
self.config = PayPalConfig(**kwargs)
def _encode_utf8(self, **kwargs):
"""
UTF8 encodes all of the NVP values.
"""
if is_py3:
# This is only valid for Python 2. In Python 3, unicode is
# everywhere (yay).
return kwargs
unencoded_pairs = kwargs
for i in unencoded_pairs.keys():
#noinspection PyUnresolvedReferences
if isinstance(unencoded_pairs[i], types.UnicodeType):
unencoded_pairs[i] = unencoded_pairs[i].encode('utf-8')
return unencoded_pairs
def _check_required(self, requires, **kwargs):
"""
Checks kwargs for the values specified in 'requires', which is a tuple
of strings. These strings are the NVP names of the required values.
"""
for req in requires:
# PayPal api is never mixed-case.
if req.lower() not in kwargs and req.upper() not in kwargs:
raise PayPalError('missing required : %s' % req)
def _sanitize_locals(self, data):
"""
Remove the 'self' key in locals()
It's more explicit to do it in one function
"""
if 'self' in data:
data = data.copy()
del data['self']
return data
def _call(self, method, **kwargs):
"""
Wrapper method for executing all API commands over HTTP. This method is
further used to implement wrapper methods listed here:
https://www.x.com/docs/DOC-1374
``method`` must be a supported NVP method listed at the above address.
``kwargs`` the actual call parameters
"""
post_params = self._get_call_params(method, **kwargs)
payload = post_params['data']
api_endpoint = post_params['url']
# This shows all of the key/val pairs we're sending to PayPal.
if logger.isEnabledFor(logging.DEBUG):
logger.debug('PayPal NVP Query Key/Vals:\n%s' % pformat(payload))
http_response = requests.post(**post_params)
response = PayPalResponse(http_response.text, self.config)
logger.debug('PayPal NVP API Endpoint: %s' % api_endpoint)
if not response.success:
raise PayPalAPIResponseError(response)
return response
def _get_call_params(self, method, **kwargs):
"""
Returns the prepared call parameters. Mind, these will be keyword
arguments to ``requests.post``.
``method`` the NVP method
``kwargs`` the actual call parameters
"""
payload = {'METHOD': method,
'VERSION': self.config.API_VERSION}
certificate = None
if self.config.API_AUTHENTICATION_MODE == "3TOKEN":
payload['USER'] = self.config.API_USERNAME
payload['PWD'] = self.config.API_PASSWORD
payload['SIGNATURE'] = self.config.API_SIGNATURE
elif self.config.API_AUTHENTICATION_MODE == "CERTIFICATE":
payload['USER'] = self.config.API_USERNAME
payload['PWD'] = self.config.API_PASSWORD
certificate = (self.config.API_CERTIFICATE_FILENAME,
self.config.API_KEY_FILENAME)
elif self.config.API_AUTHENTICATION_MODE == "UNIPAY":
payload['SUBJECT'] = self.config.UNIPAY_SUBJECT
none_configs = [config for config, value in payload.items()
if value is None]
if none_configs:
raise PayPalConfigError(
"Config(s) %s cannot be None. Please, check this "
"interface's config." % none_configs)
# all keys in the payload must be uppercase
for key, value in kwargs.items():
payload[key.upper()] = value
return {'data': payload,
'cert': certificate,
'url': self.config.API_ENDPOINT,
'timeout': self.config.HTTP_TIMEOUT,
'verify': self.config.API_CA_CERTS}
def address_verify(self, email, street, zip):
"""Shortcut for the AddressVerify method.
``email``::
Email address of a PayPal member to verify.
Maximum string length: 255 single-byte characters
Input mask: ?@?.??
``street``::
First line of the billing or shipping postal address to verify.
To pass verification, the value of Street must match the first three
single-byte characters of a postal address on file for the PayPal member.
Maximum string length: 35 single-byte characters.
Alphanumeric plus - , . ‘ # \
Whitespace and case of input value are ignored.
``zip``::
Postal code to verify.
To pass verification, the value of Zip mustmatch the first five
single-byte characters of the postal code of the verified postal
address for the verified PayPal member.
Maximumstring length: 16 single-byte characters.
Whitespace and case of input value are ignored.
"""
args = self._sanitize_locals(locals())
return self._call('AddressVerify', **args)
def create_recurring_payments_profile(self, **kwargs):
"""Shortcut for the CreateRecurringPaymentsProfile method.
Currently, this method only supports the Direct Payment flavor.
It requires standard credit card information and a few additional
parameters related to the billing. e.g.:
profile_info = {
# Credit card information
'creditcardtype': 'Visa',
'acct': '4812177017895760',
'expdate': '102015',
'cvv2': '123',
'firstname': 'John',
'lastname': 'Doe',
'street': '1313 Mockingbird Lane',
'city': 'Beverly Hills',
'state': 'CA',
'zip': '90110',
'countrycode': 'US',
'currencycode': 'USD',
# Recurring payment information
'profilestartdate': '2010-10-25T0:0:0',
'billingperiod': 'Month',
'billingfrequency': '6',
'amt': '10.00',
'desc': '6 months of our product.'
}
response = create_recurring_payments_profile(**profile_info)
The above NVPs compose the bare-minimum request for creating a
profile. For the complete list of parameters, visit this URI:
https://www.x.com/docs/DOC-1168
"""
return self._call('CreateRecurringPaymentsProfile', **kwargs)
def do_authorization(self, transactionid, amt):
"""Shortcut for the DoAuthorization method.
Use the TRANSACTIONID from DoExpressCheckoutPayment for the
``transactionid``. The latest version of the API does not support the
creation of an Order from `DoDirectPayment`.
The `amt` should be the same as passed to `DoExpressCheckoutPayment`.
Flow for a payment involving a `DoAuthorization` call::
1. One or many calls to `SetExpressCheckout` with pertinent order
details, returns `TOKEN`
1. `DoExpressCheckoutPayment` with `TOKEN`, `PAYMENTACTION` set to
Order, `AMT` set to the amount of the transaction, returns
`TRANSACTIONID`
1. `DoAuthorization` with `TRANSACTIONID` and `AMT` set to the
amount of the transaction.
1. `DoCapture` with the `AUTHORIZATIONID` (the `TRANSACTIONID`
returned by `DoAuthorization`)
"""
args = self._sanitize_locals(locals())
return self._call('DoAuthorization', **args)
def do_direct_payment(self, paymentaction="Sale", **kwargs):
"""Shortcut for the DoDirectPayment method.
``paymentaction`` could be 'Authorization' or 'Sale'
To issue a Sale immediately::
charge = {
'amt': '10.00',
'creditcardtype': 'Visa',
'acct': '4812177017895760',
'expdate': '012010',
'cvv2': '962',
'firstname': 'John',
'lastname': 'Doe',
'street': '1 Main St',
'city': 'San Jose',
'state': 'CA',
'zip': '95131',
'countrycode': 'US',
'currencycode': 'USD',
}
direct_payment("Sale", **charge)
Or, since "Sale" is the default:
direct_payment(**charge)
To issue an Authorization, simply pass "Authorization" instead
of "Sale".
You may also explicitly set ``paymentaction`` as a keyword argument:
...
direct_payment(paymentaction="Sale", **charge)
"""
kwargs.update(self._sanitize_locals(locals()))
return self._call('DoDirectPayment', **kwargs)
def do_void(self, **kwargs):
"""Shortcut for the DoVoid method.
Use the TRANSACTIONID from DoAuthorization, DoDirectPayment or
DoExpressCheckoutPayment for the ``AUTHORIZATIONID``.
Required Kwargs
---------------
* AUTHORIZATIONID
"""
return self._call('DoVoid', **kwargs)
def get_express_checkout_details(self, **kwargs):
"""Shortcut for the GetExpressCheckoutDetails method.
Required Kwargs
---------------
* TOKEN
"""
return self._call('GetExpressCheckoutDetails', **kwargs)
def get_transaction_details(self, **kwargs):
"""Shortcut for the GetTransactionDetails method.
Use the TRANSACTIONID from DoAuthorization, DoDirectPayment or
DoExpressCheckoutPayment for the ``transactionid``.
Required Kwargs
---------------
* TRANSACTIONID
"""
return self._call('GetTransactionDetails', **kwargs)
def transaction_search(self, **kwargs):
"""Shortcut for the TransactionSearch method.
Returns a PayPalResponseList object, which merges the L_ syntax list
to a list of dictionaries with properly named keys.
Note that the API will limit returned transactions to 100.
Required Kwargs
---------------
* STARTDATE
Optional Kwargs
---------------
STATUS = one of ['Pending','Processing','Success','Denied','Reversed']
"""
plain = self._call('TransactionSearch', **kwargs)
return PayPalResponseList(plain.raw, self.config)
def set_express_checkout(self, **kwargs):
"""Start an Express checkout.
You'll want to use this in conjunction with
:meth:`generate_express_checkout_redirect_url` to create a payment,
then figure out where to redirect the user to for them to
authorize the payment on PayPal's website.
Required Kwargs
---------------
* PAYMENTREQUEST_0_AMT
* PAYMENTREQUEST_0_PAYMENTACTION
* RETURNURL
* CANCELURL
"""
return self._call('SetExpressCheckout', **kwargs)
def refund_transaction(self, transactionid=None, payerid=None, **kwargs):
"""Shortcut for RefundTransaction method.
Note new API supports passing a PayerID instead of a transaction id,
exactly one must be provided.
Optional:
INVOICEID
REFUNDTYPE
AMT
CURRENCYCODE
NOTE
RETRYUNTIL
REFUNDSOURCE
MERCHANTSTOREDETAILS
REFUNDADVICE
REFUNDITEMDETAILS
MSGSUBID
MERCHANSTOREDETAILS has two fields:
STOREID
TERMINALID
"""
# This line seems like a complete waste of time... kwargs should not
# be populated
if (transactionid is None) and (payerid is None):
raise PayPalError(
'RefundTransaction requires either a transactionid or '
'a payerid')
if (transactionid is not None) and (payerid is not None):
raise PayPalError(
'RefundTransaction requires only one of transactionid %s '
'and payerid %s' % (transactionid, payerid))
if transactionid is not None:
kwargs['TRANSACTIONID'] = transactionid
else:
kwargs['PAYERID'] = payerid
return self._call('RefundTransaction', **kwargs)
def do_express_checkout_payment(self, **kwargs):
"""Finishes an Express checkout.
TOKEN is the token that was returned earlier by
:meth:`set_express_checkout`. This identifies the transaction.
Required
--------
* TOKEN
* PAYMENTACTION
* PAYERID
* AMT
"""
return self._call('DoExpressCheckoutPayment', **kwargs)
def generate_express_checkout_redirect_url(self, token, useraction=None):
"""Returns the URL to redirect the user to for the Express checkout.
Express Checkouts must be verified by the customer by redirecting them
to the PayPal website. Use the token returned in the response from
:meth:`set_express_checkout` with this function to figure out where
to redirect the user to.
The button text on the PayPal page can be controlled via `useraction`.
The documented possible values are `commit` and `continue`. However,
any other value will only result in a warning.
:param str token: The unique token identifying this transaction.
:param str useraction: Control the button text on the PayPal page.
:rtype: str
:returns: The URL to redirect the user to for approval.
"""
url_vars = (self.config.PAYPAL_URL_BASE, token)
url = "%s?cmd=_express-checkout&token=%s" % url_vars
if useraction:
if not useraction.lower() in ('commit', 'continue'):
warnings.warn('useraction=%s is not documented' % useraction,
RuntimeWarning)
url += '&useraction=%s' % useraction
return url
def generate_cart_upload_redirect_url(self, **kwargs):
"""https://www.sandbox.paypal.com/webscr
?cmd=_cart
&upload=1
"""
required_vals = ('business', 'item_name_1', 'amount_1', 'quantity_1')
self._check_required(required_vals, **kwargs)
url = "%s?cmd=_cart&upload=1" % self.config.PAYPAL_URL_BASE
additional = self._encode_utf8(**kwargs)
additional = urlencode(additional)
return url + "&" + additional
def get_recurring_payments_profile_details(self, profileid):
"""Shortcut for the GetRecurringPaymentsProfile method.
This returns details for a recurring payment plan. The ``profileid`` is
a value included in the response retrieved by the function
``create_recurring_payments_profile``. The profile details include the
data provided when the profile was created as well as default values
for ignored fields and some pertinent stastics.
e.g.:
response = create_recurring_payments_profile(**profile_info)
profileid = response.PROFILEID
details = get_recurring_payments_profile(profileid)
The response from PayPal is somewhat self-explanatory, but for a
description of each field, visit the following URI:
https://www.x.com/docs/DOC-1194
"""
args = self._sanitize_locals(locals())
return self._call('GetRecurringPaymentsProfileDetails', **args)
def manage_recurring_payments_profile_status(self, profileid, action,
note=None):
"""Shortcut to the ManageRecurringPaymentsProfileStatus method.
``profileid`` is the same profile id used for getting profile details.
``action`` should be either 'Cancel', 'Suspend', or 'Reactivate'.
``note`` is optional and is visible to the user. It contains the
reason for the change in status.
"""
args = self._sanitize_locals(locals())
if not note:
del args['note']
return self._call('ManageRecurringPaymentsProfileStatus', **args)
def update_recurring_payments_profile(self, profileid, **kwargs):
"""Shortcut to the UpdateRecurringPaymentsProfile method.
``profileid`` is the same profile id used for getting profile details.
The keyed arguments are data in the payment profile which you wish to
change. The profileid does not change. Anything else will take the new
value. Most of, though not all of, the fields available are shared
with creating a profile, but for the complete list of parameters, you
can visit the following URI:
https://www.x.com/docs/DOC-1212
"""
kwargs.update(self._sanitize_locals(locals()))
return self._call('UpdateRecurringPaymentsProfile', **kwargs)
def bm_create_button(self, **kwargs):
"""Shortcut to the BMCreateButton method.
See the docs for details on arguments:
https://cms.paypal.com/mx/cgi-bin/?cmd=_render-content&content_ID=developer/e_howto_api_nvp_BMCreateButton
The L_BUTTONVARn fields are especially important, so make sure to
read those and act accordingly. See unit tests for some examples.
"""
kwargs.update(self._sanitize_locals(locals()))
return self._call('BMCreateButton', **kwargs)
|
gtaylor/paypal-python
|
paypal/interface.py
|
PayPalInterface.do_direct_payment
|
python
|
def do_direct_payment(self, paymentaction="Sale", **kwargs):
kwargs.update(self._sanitize_locals(locals()))
return self._call('DoDirectPayment', **kwargs)
|
Shortcut for the DoDirectPayment method.
``paymentaction`` could be 'Authorization' or 'Sale'
To issue a Sale immediately::
charge = {
'amt': '10.00',
'creditcardtype': 'Visa',
'acct': '4812177017895760',
'expdate': '012010',
'cvv2': '962',
'firstname': 'John',
'lastname': 'Doe',
'street': '1 Main St',
'city': 'San Jose',
'state': 'CA',
'zip': '95131',
'countrycode': 'US',
'currencycode': 'USD',
}
direct_payment("Sale", **charge)
Or, since "Sale" is the default:
direct_payment(**charge)
To issue an Authorization, simply pass "Authorization" instead
of "Sale".
You may also explicitly set ``paymentaction`` as a keyword argument:
...
direct_payment(paymentaction="Sale", **charge)
|
train
|
https://github.com/gtaylor/paypal-python/blob/aa7a987ea9e9b7f37bcd8a8b54a440aad6c871b1/paypal/interface.py#L265-L302
|
[
"def _sanitize_locals(self, data):\n \"\"\"\n Remove the 'self' key in locals()\n It's more explicit to do it in one function\n \"\"\"\n if 'self' in data:\n data = data.copy()\n del data['self']\n\n return data\n",
"def _call(self, method, **kwargs):\n \"\"\"\n Wrapper method for executing all API commands over HTTP. This method is\n further used to implement wrapper methods listed here:\n\n https://www.x.com/docs/DOC-1374\n\n ``method`` must be a supported NVP method listed at the above address.\n ``kwargs`` the actual call parameters\n \"\"\"\n post_params = self._get_call_params(method, **kwargs)\n payload = post_params['data']\n api_endpoint = post_params['url']\n\n # This shows all of the key/val pairs we're sending to PayPal.\n if logger.isEnabledFor(logging.DEBUG):\n logger.debug('PayPal NVP Query Key/Vals:\\n%s' % pformat(payload))\n\n http_response = requests.post(**post_params)\n response = PayPalResponse(http_response.text, self.config)\n logger.debug('PayPal NVP API Endpoint: %s' % api_endpoint)\n\n if not response.success:\n raise PayPalAPIResponseError(response)\n\n return response\n"
] |
class PayPalInterface(object):
__credentials = ['USER', 'PWD', 'SIGNATURE', 'SUBJECT']
"""
The end developers will do 95% of their work through this class. API
queries, configuration, etc, all go through here. See the __init__ method
for config related details.
"""
def __init__(self, config=None, **kwargs):
"""
Constructor, which passes all config directives to the config class
via kwargs. For example:
paypal = PayPalInterface(API_USERNAME='somevalue')
Optionally, you may pass a 'config' kwarg to provide your own
PayPalConfig object.
"""
if config:
# User provided their own PayPalConfig object.
self.config = config
else:
# Take the kwargs and stuff them in a new PayPalConfig object.
self.config = PayPalConfig(**kwargs)
def _encode_utf8(self, **kwargs):
"""
UTF8 encodes all of the NVP values.
"""
if is_py3:
# This is only valid for Python 2. In Python 3, unicode is
# everywhere (yay).
return kwargs
unencoded_pairs = kwargs
for i in unencoded_pairs.keys():
#noinspection PyUnresolvedReferences
if isinstance(unencoded_pairs[i], types.UnicodeType):
unencoded_pairs[i] = unencoded_pairs[i].encode('utf-8')
return unencoded_pairs
def _check_required(self, requires, **kwargs):
"""
Checks kwargs for the values specified in 'requires', which is a tuple
of strings. These strings are the NVP names of the required values.
"""
for req in requires:
# PayPal api is never mixed-case.
if req.lower() not in kwargs and req.upper() not in kwargs:
raise PayPalError('missing required : %s' % req)
def _sanitize_locals(self, data):
"""
Remove the 'self' key in locals()
It's more explicit to do it in one function
"""
if 'self' in data:
data = data.copy()
del data['self']
return data
def _call(self, method, **kwargs):
"""
Wrapper method for executing all API commands over HTTP. This method is
further used to implement wrapper methods listed here:
https://www.x.com/docs/DOC-1374
``method`` must be a supported NVP method listed at the above address.
``kwargs`` the actual call parameters
"""
post_params = self._get_call_params(method, **kwargs)
payload = post_params['data']
api_endpoint = post_params['url']
# This shows all of the key/val pairs we're sending to PayPal.
if logger.isEnabledFor(logging.DEBUG):
logger.debug('PayPal NVP Query Key/Vals:\n%s' % pformat(payload))
http_response = requests.post(**post_params)
response = PayPalResponse(http_response.text, self.config)
logger.debug('PayPal NVP API Endpoint: %s' % api_endpoint)
if not response.success:
raise PayPalAPIResponseError(response)
return response
def _get_call_params(self, method, **kwargs):
"""
Returns the prepared call parameters. Mind, these will be keyword
arguments to ``requests.post``.
``method`` the NVP method
``kwargs`` the actual call parameters
"""
payload = {'METHOD': method,
'VERSION': self.config.API_VERSION}
certificate = None
if self.config.API_AUTHENTICATION_MODE == "3TOKEN":
payload['USER'] = self.config.API_USERNAME
payload['PWD'] = self.config.API_PASSWORD
payload['SIGNATURE'] = self.config.API_SIGNATURE
elif self.config.API_AUTHENTICATION_MODE == "CERTIFICATE":
payload['USER'] = self.config.API_USERNAME
payload['PWD'] = self.config.API_PASSWORD
certificate = (self.config.API_CERTIFICATE_FILENAME,
self.config.API_KEY_FILENAME)
elif self.config.API_AUTHENTICATION_MODE == "UNIPAY":
payload['SUBJECT'] = self.config.UNIPAY_SUBJECT
none_configs = [config for config, value in payload.items()
if value is None]
if none_configs:
raise PayPalConfigError(
"Config(s) %s cannot be None. Please, check this "
"interface's config." % none_configs)
# all keys in the payload must be uppercase
for key, value in kwargs.items():
payload[key.upper()] = value
return {'data': payload,
'cert': certificate,
'url': self.config.API_ENDPOINT,
'timeout': self.config.HTTP_TIMEOUT,
'verify': self.config.API_CA_CERTS}
def address_verify(self, email, street, zip):
"""Shortcut for the AddressVerify method.
``email``::
Email address of a PayPal member to verify.
Maximum string length: 255 single-byte characters
Input mask: ?@?.??
``street``::
First line of the billing or shipping postal address to verify.
To pass verification, the value of Street must match the first three
single-byte characters of a postal address on file for the PayPal member.
Maximum string length: 35 single-byte characters.
Alphanumeric plus - , . ‘ # \
Whitespace and case of input value are ignored.
``zip``::
Postal code to verify.
To pass verification, the value of Zip mustmatch the first five
single-byte characters of the postal code of the verified postal
address for the verified PayPal member.
Maximumstring length: 16 single-byte characters.
Whitespace and case of input value are ignored.
"""
args = self._sanitize_locals(locals())
return self._call('AddressVerify', **args)
def create_recurring_payments_profile(self, **kwargs):
"""Shortcut for the CreateRecurringPaymentsProfile method.
Currently, this method only supports the Direct Payment flavor.
It requires standard credit card information and a few additional
parameters related to the billing. e.g.:
profile_info = {
# Credit card information
'creditcardtype': 'Visa',
'acct': '4812177017895760',
'expdate': '102015',
'cvv2': '123',
'firstname': 'John',
'lastname': 'Doe',
'street': '1313 Mockingbird Lane',
'city': 'Beverly Hills',
'state': 'CA',
'zip': '90110',
'countrycode': 'US',
'currencycode': 'USD',
# Recurring payment information
'profilestartdate': '2010-10-25T0:0:0',
'billingperiod': 'Month',
'billingfrequency': '6',
'amt': '10.00',
'desc': '6 months of our product.'
}
response = create_recurring_payments_profile(**profile_info)
The above NVPs compose the bare-minimum request for creating a
profile. For the complete list of parameters, visit this URI:
https://www.x.com/docs/DOC-1168
"""
return self._call('CreateRecurringPaymentsProfile', **kwargs)
def do_authorization(self, transactionid, amt):
"""Shortcut for the DoAuthorization method.
Use the TRANSACTIONID from DoExpressCheckoutPayment for the
``transactionid``. The latest version of the API does not support the
creation of an Order from `DoDirectPayment`.
The `amt` should be the same as passed to `DoExpressCheckoutPayment`.
Flow for a payment involving a `DoAuthorization` call::
1. One or many calls to `SetExpressCheckout` with pertinent order
details, returns `TOKEN`
1. `DoExpressCheckoutPayment` with `TOKEN`, `PAYMENTACTION` set to
Order, `AMT` set to the amount of the transaction, returns
`TRANSACTIONID`
1. `DoAuthorization` with `TRANSACTIONID` and `AMT` set to the
amount of the transaction.
1. `DoCapture` with the `AUTHORIZATIONID` (the `TRANSACTIONID`
returned by `DoAuthorization`)
"""
args = self._sanitize_locals(locals())
return self._call('DoAuthorization', **args)
def do_capture(self, authorizationid, amt, completetype='Complete',
**kwargs):
"""Shortcut for the DoCapture method.
Use the TRANSACTIONID from DoAuthorization, DoDirectPayment or
DoExpressCheckoutPayment for the ``authorizationid``.
The `amt` should be the same as the authorized transaction.
"""
kwargs.update(self._sanitize_locals(locals()))
return self._call('DoCapture', **kwargs)
def do_void(self, **kwargs):
"""Shortcut for the DoVoid method.
Use the TRANSACTIONID from DoAuthorization, DoDirectPayment or
DoExpressCheckoutPayment for the ``AUTHORIZATIONID``.
Required Kwargs
---------------
* AUTHORIZATIONID
"""
return self._call('DoVoid', **kwargs)
def get_express_checkout_details(self, **kwargs):
"""Shortcut for the GetExpressCheckoutDetails method.
Required Kwargs
---------------
* TOKEN
"""
return self._call('GetExpressCheckoutDetails', **kwargs)
def get_transaction_details(self, **kwargs):
"""Shortcut for the GetTransactionDetails method.
Use the TRANSACTIONID from DoAuthorization, DoDirectPayment or
DoExpressCheckoutPayment for the ``transactionid``.
Required Kwargs
---------------
* TRANSACTIONID
"""
return self._call('GetTransactionDetails', **kwargs)
def transaction_search(self, **kwargs):
"""Shortcut for the TransactionSearch method.
Returns a PayPalResponseList object, which merges the L_ syntax list
to a list of dictionaries with properly named keys.
Note that the API will limit returned transactions to 100.
Required Kwargs
---------------
* STARTDATE
Optional Kwargs
---------------
STATUS = one of ['Pending','Processing','Success','Denied','Reversed']
"""
plain = self._call('TransactionSearch', **kwargs)
return PayPalResponseList(plain.raw, self.config)
def set_express_checkout(self, **kwargs):
"""Start an Express checkout.
You'll want to use this in conjunction with
:meth:`generate_express_checkout_redirect_url` to create a payment,
then figure out where to redirect the user to for them to
authorize the payment on PayPal's website.
Required Kwargs
---------------
* PAYMENTREQUEST_0_AMT
* PAYMENTREQUEST_0_PAYMENTACTION
* RETURNURL
* CANCELURL
"""
return self._call('SetExpressCheckout', **kwargs)
def refund_transaction(self, transactionid=None, payerid=None, **kwargs):
"""Shortcut for RefundTransaction method.
Note new API supports passing a PayerID instead of a transaction id,
exactly one must be provided.
Optional:
INVOICEID
REFUNDTYPE
AMT
CURRENCYCODE
NOTE
RETRYUNTIL
REFUNDSOURCE
MERCHANTSTOREDETAILS
REFUNDADVICE
REFUNDITEMDETAILS
MSGSUBID
MERCHANSTOREDETAILS has two fields:
STOREID
TERMINALID
"""
# This line seems like a complete waste of time... kwargs should not
# be populated
if (transactionid is None) and (payerid is None):
raise PayPalError(
'RefundTransaction requires either a transactionid or '
'a payerid')
if (transactionid is not None) and (payerid is not None):
raise PayPalError(
'RefundTransaction requires only one of transactionid %s '
'and payerid %s' % (transactionid, payerid))
if transactionid is not None:
kwargs['TRANSACTIONID'] = transactionid
else:
kwargs['PAYERID'] = payerid
return self._call('RefundTransaction', **kwargs)
def do_express_checkout_payment(self, **kwargs):
"""Finishes an Express checkout.
TOKEN is the token that was returned earlier by
:meth:`set_express_checkout`. This identifies the transaction.
Required
--------
* TOKEN
* PAYMENTACTION
* PAYERID
* AMT
"""
return self._call('DoExpressCheckoutPayment', **kwargs)
def generate_express_checkout_redirect_url(self, token, useraction=None):
"""Returns the URL to redirect the user to for the Express checkout.
Express Checkouts must be verified by the customer by redirecting them
to the PayPal website. Use the token returned in the response from
:meth:`set_express_checkout` with this function to figure out where
to redirect the user to.
The button text on the PayPal page can be controlled via `useraction`.
The documented possible values are `commit` and `continue`. However,
any other value will only result in a warning.
:param str token: The unique token identifying this transaction.
:param str useraction: Control the button text on the PayPal page.
:rtype: str
:returns: The URL to redirect the user to for approval.
"""
url_vars = (self.config.PAYPAL_URL_BASE, token)
url = "%s?cmd=_express-checkout&token=%s" % url_vars
if useraction:
if not useraction.lower() in ('commit', 'continue'):
warnings.warn('useraction=%s is not documented' % useraction,
RuntimeWarning)
url += '&useraction=%s' % useraction
return url
def generate_cart_upload_redirect_url(self, **kwargs):
"""https://www.sandbox.paypal.com/webscr
?cmd=_cart
&upload=1
"""
required_vals = ('business', 'item_name_1', 'amount_1', 'quantity_1')
self._check_required(required_vals, **kwargs)
url = "%s?cmd=_cart&upload=1" % self.config.PAYPAL_URL_BASE
additional = self._encode_utf8(**kwargs)
additional = urlencode(additional)
return url + "&" + additional
def get_recurring_payments_profile_details(self, profileid):
"""Shortcut for the GetRecurringPaymentsProfile method.
This returns details for a recurring payment plan. The ``profileid`` is
a value included in the response retrieved by the function
``create_recurring_payments_profile``. The profile details include the
data provided when the profile was created as well as default values
for ignored fields and some pertinent stastics.
e.g.:
response = create_recurring_payments_profile(**profile_info)
profileid = response.PROFILEID
details = get_recurring_payments_profile(profileid)
The response from PayPal is somewhat self-explanatory, but for a
description of each field, visit the following URI:
https://www.x.com/docs/DOC-1194
"""
args = self._sanitize_locals(locals())
return self._call('GetRecurringPaymentsProfileDetails', **args)
def manage_recurring_payments_profile_status(self, profileid, action,
note=None):
"""Shortcut to the ManageRecurringPaymentsProfileStatus method.
``profileid`` is the same profile id used for getting profile details.
``action`` should be either 'Cancel', 'Suspend', or 'Reactivate'.
``note`` is optional and is visible to the user. It contains the
reason for the change in status.
"""
args = self._sanitize_locals(locals())
if not note:
del args['note']
return self._call('ManageRecurringPaymentsProfileStatus', **args)
def update_recurring_payments_profile(self, profileid, **kwargs):
"""Shortcut to the UpdateRecurringPaymentsProfile method.
``profileid`` is the same profile id used for getting profile details.
The keyed arguments are data in the payment profile which you wish to
change. The profileid does not change. Anything else will take the new
value. Most of, though not all of, the fields available are shared
with creating a profile, but for the complete list of parameters, you
can visit the following URI:
https://www.x.com/docs/DOC-1212
"""
kwargs.update(self._sanitize_locals(locals()))
return self._call('UpdateRecurringPaymentsProfile', **kwargs)
def bm_create_button(self, **kwargs):
"""Shortcut to the BMCreateButton method.
See the docs for details on arguments:
https://cms.paypal.com/mx/cgi-bin/?cmd=_render-content&content_ID=developer/e_howto_api_nvp_BMCreateButton
The L_BUTTONVARn fields are especially important, so make sure to
read those and act accordingly. See unit tests for some examples.
"""
kwargs.update(self._sanitize_locals(locals()))
return self._call('BMCreateButton', **kwargs)
|
gtaylor/paypal-python
|
paypal/interface.py
|
PayPalInterface.transaction_search
|
python
|
def transaction_search(self, **kwargs):
plain = self._call('TransactionSearch', **kwargs)
return PayPalResponseList(plain.raw, self.config)
|
Shortcut for the TransactionSearch method.
Returns a PayPalResponseList object, which merges the L_ syntax list
to a list of dictionaries with properly named keys.
Note that the API will limit returned transactions to 100.
Required Kwargs
---------------
* STARTDATE
Optional Kwargs
---------------
STATUS = one of ['Pending','Processing','Success','Denied','Reversed']
|
train
|
https://github.com/gtaylor/paypal-python/blob/aa7a987ea9e9b7f37bcd8a8b54a440aad6c871b1/paypal/interface.py#L338-L355
|
[
"def _call(self, method, **kwargs):\n \"\"\"\n Wrapper method for executing all API commands over HTTP. This method is\n further used to implement wrapper methods listed here:\n\n https://www.x.com/docs/DOC-1374\n\n ``method`` must be a supported NVP method listed at the above address.\n ``kwargs`` the actual call parameters\n \"\"\"\n post_params = self._get_call_params(method, **kwargs)\n payload = post_params['data']\n api_endpoint = post_params['url']\n\n # This shows all of the key/val pairs we're sending to PayPal.\n if logger.isEnabledFor(logging.DEBUG):\n logger.debug('PayPal NVP Query Key/Vals:\\n%s' % pformat(payload))\n\n http_response = requests.post(**post_params)\n response = PayPalResponse(http_response.text, self.config)\n logger.debug('PayPal NVP API Endpoint: %s' % api_endpoint)\n\n if not response.success:\n raise PayPalAPIResponseError(response)\n\n return response\n"
] |
class PayPalInterface(object):
__credentials = ['USER', 'PWD', 'SIGNATURE', 'SUBJECT']
"""
The end developers will do 95% of their work through this class. API
queries, configuration, etc, all go through here. See the __init__ method
for config related details.
"""
def __init__(self, config=None, **kwargs):
"""
Constructor, which passes all config directives to the config class
via kwargs. For example:
paypal = PayPalInterface(API_USERNAME='somevalue')
Optionally, you may pass a 'config' kwarg to provide your own
PayPalConfig object.
"""
if config:
# User provided their own PayPalConfig object.
self.config = config
else:
# Take the kwargs and stuff them in a new PayPalConfig object.
self.config = PayPalConfig(**kwargs)
def _encode_utf8(self, **kwargs):
"""
UTF8 encodes all of the NVP values.
"""
if is_py3:
# This is only valid for Python 2. In Python 3, unicode is
# everywhere (yay).
return kwargs
unencoded_pairs = kwargs
for i in unencoded_pairs.keys():
#noinspection PyUnresolvedReferences
if isinstance(unencoded_pairs[i], types.UnicodeType):
unencoded_pairs[i] = unencoded_pairs[i].encode('utf-8')
return unencoded_pairs
def _check_required(self, requires, **kwargs):
"""
Checks kwargs for the values specified in 'requires', which is a tuple
of strings. These strings are the NVP names of the required values.
"""
for req in requires:
# PayPal api is never mixed-case.
if req.lower() not in kwargs and req.upper() not in kwargs:
raise PayPalError('missing required : %s' % req)
def _sanitize_locals(self, data):
"""
Remove the 'self' key in locals()
It's more explicit to do it in one function
"""
if 'self' in data:
data = data.copy()
del data['self']
return data
def _call(self, method, **kwargs):
"""
Wrapper method for executing all API commands over HTTP. This method is
further used to implement wrapper methods listed here:
https://www.x.com/docs/DOC-1374
``method`` must be a supported NVP method listed at the above address.
``kwargs`` the actual call parameters
"""
post_params = self._get_call_params(method, **kwargs)
payload = post_params['data']
api_endpoint = post_params['url']
# This shows all of the key/val pairs we're sending to PayPal.
if logger.isEnabledFor(logging.DEBUG):
logger.debug('PayPal NVP Query Key/Vals:\n%s' % pformat(payload))
http_response = requests.post(**post_params)
response = PayPalResponse(http_response.text, self.config)
logger.debug('PayPal NVP API Endpoint: %s' % api_endpoint)
if not response.success:
raise PayPalAPIResponseError(response)
return response
def _get_call_params(self, method, **kwargs):
"""
Returns the prepared call parameters. Mind, these will be keyword
arguments to ``requests.post``.
``method`` the NVP method
``kwargs`` the actual call parameters
"""
payload = {'METHOD': method,
'VERSION': self.config.API_VERSION}
certificate = None
if self.config.API_AUTHENTICATION_MODE == "3TOKEN":
payload['USER'] = self.config.API_USERNAME
payload['PWD'] = self.config.API_PASSWORD
payload['SIGNATURE'] = self.config.API_SIGNATURE
elif self.config.API_AUTHENTICATION_MODE == "CERTIFICATE":
payload['USER'] = self.config.API_USERNAME
payload['PWD'] = self.config.API_PASSWORD
certificate = (self.config.API_CERTIFICATE_FILENAME,
self.config.API_KEY_FILENAME)
elif self.config.API_AUTHENTICATION_MODE == "UNIPAY":
payload['SUBJECT'] = self.config.UNIPAY_SUBJECT
none_configs = [config for config, value in payload.items()
if value is None]
if none_configs:
raise PayPalConfigError(
"Config(s) %s cannot be None. Please, check this "
"interface's config." % none_configs)
# all keys in the payload must be uppercase
for key, value in kwargs.items():
payload[key.upper()] = value
return {'data': payload,
'cert': certificate,
'url': self.config.API_ENDPOINT,
'timeout': self.config.HTTP_TIMEOUT,
'verify': self.config.API_CA_CERTS}
def address_verify(self, email, street, zip):
"""Shortcut for the AddressVerify method.
``email``::
Email address of a PayPal member to verify.
Maximum string length: 255 single-byte characters
Input mask: ?@?.??
``street``::
First line of the billing or shipping postal address to verify.
To pass verification, the value of Street must match the first three
single-byte characters of a postal address on file for the PayPal member.
Maximum string length: 35 single-byte characters.
Alphanumeric plus - , . ‘ # \
Whitespace and case of input value are ignored.
``zip``::
Postal code to verify.
To pass verification, the value of Zip mustmatch the first five
single-byte characters of the postal code of the verified postal
address for the verified PayPal member.
Maximumstring length: 16 single-byte characters.
Whitespace and case of input value are ignored.
"""
args = self._sanitize_locals(locals())
return self._call('AddressVerify', **args)
def create_recurring_payments_profile(self, **kwargs):
"""Shortcut for the CreateRecurringPaymentsProfile method.
Currently, this method only supports the Direct Payment flavor.
It requires standard credit card information and a few additional
parameters related to the billing. e.g.:
profile_info = {
# Credit card information
'creditcardtype': 'Visa',
'acct': '4812177017895760',
'expdate': '102015',
'cvv2': '123',
'firstname': 'John',
'lastname': 'Doe',
'street': '1313 Mockingbird Lane',
'city': 'Beverly Hills',
'state': 'CA',
'zip': '90110',
'countrycode': 'US',
'currencycode': 'USD',
# Recurring payment information
'profilestartdate': '2010-10-25T0:0:0',
'billingperiod': 'Month',
'billingfrequency': '6',
'amt': '10.00',
'desc': '6 months of our product.'
}
response = create_recurring_payments_profile(**profile_info)
The above NVPs compose the bare-minimum request for creating a
profile. For the complete list of parameters, visit this URI:
https://www.x.com/docs/DOC-1168
"""
return self._call('CreateRecurringPaymentsProfile', **kwargs)
def do_authorization(self, transactionid, amt):
"""Shortcut for the DoAuthorization method.
Use the TRANSACTIONID from DoExpressCheckoutPayment for the
``transactionid``. The latest version of the API does not support the
creation of an Order from `DoDirectPayment`.
The `amt` should be the same as passed to `DoExpressCheckoutPayment`.
Flow for a payment involving a `DoAuthorization` call::
1. One or many calls to `SetExpressCheckout` with pertinent order
details, returns `TOKEN`
1. `DoExpressCheckoutPayment` with `TOKEN`, `PAYMENTACTION` set to
Order, `AMT` set to the amount of the transaction, returns
`TRANSACTIONID`
1. `DoAuthorization` with `TRANSACTIONID` and `AMT` set to the
amount of the transaction.
1. `DoCapture` with the `AUTHORIZATIONID` (the `TRANSACTIONID`
returned by `DoAuthorization`)
"""
args = self._sanitize_locals(locals())
return self._call('DoAuthorization', **args)
def do_capture(self, authorizationid, amt, completetype='Complete',
**kwargs):
"""Shortcut for the DoCapture method.
Use the TRANSACTIONID from DoAuthorization, DoDirectPayment or
DoExpressCheckoutPayment for the ``authorizationid``.
The `amt` should be the same as the authorized transaction.
"""
kwargs.update(self._sanitize_locals(locals()))
return self._call('DoCapture', **kwargs)
def do_direct_payment(self, paymentaction="Sale", **kwargs):
"""Shortcut for the DoDirectPayment method.
``paymentaction`` could be 'Authorization' or 'Sale'
To issue a Sale immediately::
charge = {
'amt': '10.00',
'creditcardtype': 'Visa',
'acct': '4812177017895760',
'expdate': '012010',
'cvv2': '962',
'firstname': 'John',
'lastname': 'Doe',
'street': '1 Main St',
'city': 'San Jose',
'state': 'CA',
'zip': '95131',
'countrycode': 'US',
'currencycode': 'USD',
}
direct_payment("Sale", **charge)
Or, since "Sale" is the default:
direct_payment(**charge)
To issue an Authorization, simply pass "Authorization" instead
of "Sale".
You may also explicitly set ``paymentaction`` as a keyword argument:
...
direct_payment(paymentaction="Sale", **charge)
"""
kwargs.update(self._sanitize_locals(locals()))
return self._call('DoDirectPayment', **kwargs)
def do_void(self, **kwargs):
"""Shortcut for the DoVoid method.
Use the TRANSACTIONID from DoAuthorization, DoDirectPayment or
DoExpressCheckoutPayment for the ``AUTHORIZATIONID``.
Required Kwargs
---------------
* AUTHORIZATIONID
"""
return self._call('DoVoid', **kwargs)
def get_express_checkout_details(self, **kwargs):
"""Shortcut for the GetExpressCheckoutDetails method.
Required Kwargs
---------------
* TOKEN
"""
return self._call('GetExpressCheckoutDetails', **kwargs)
def get_transaction_details(self, **kwargs):
"""Shortcut for the GetTransactionDetails method.
Use the TRANSACTIONID from DoAuthorization, DoDirectPayment or
DoExpressCheckoutPayment for the ``transactionid``.
Required Kwargs
---------------
* TRANSACTIONID
"""
return self._call('GetTransactionDetails', **kwargs)
def set_express_checkout(self, **kwargs):
"""Start an Express checkout.
You'll want to use this in conjunction with
:meth:`generate_express_checkout_redirect_url` to create a payment,
then figure out where to redirect the user to for them to
authorize the payment on PayPal's website.
Required Kwargs
---------------
* PAYMENTREQUEST_0_AMT
* PAYMENTREQUEST_0_PAYMENTACTION
* RETURNURL
* CANCELURL
"""
return self._call('SetExpressCheckout', **kwargs)
def refund_transaction(self, transactionid=None, payerid=None, **kwargs):
"""Shortcut for RefundTransaction method.
Note new API supports passing a PayerID instead of a transaction id,
exactly one must be provided.
Optional:
INVOICEID
REFUNDTYPE
AMT
CURRENCYCODE
NOTE
RETRYUNTIL
REFUNDSOURCE
MERCHANTSTOREDETAILS
REFUNDADVICE
REFUNDITEMDETAILS
MSGSUBID
MERCHANSTOREDETAILS has two fields:
STOREID
TERMINALID
"""
# This line seems like a complete waste of time... kwargs should not
# be populated
if (transactionid is None) and (payerid is None):
raise PayPalError(
'RefundTransaction requires either a transactionid or '
'a payerid')
if (transactionid is not None) and (payerid is not None):
raise PayPalError(
'RefundTransaction requires only one of transactionid %s '
'and payerid %s' % (transactionid, payerid))
if transactionid is not None:
kwargs['TRANSACTIONID'] = transactionid
else:
kwargs['PAYERID'] = payerid
return self._call('RefundTransaction', **kwargs)
def do_express_checkout_payment(self, **kwargs):
"""Finishes an Express checkout.
TOKEN is the token that was returned earlier by
:meth:`set_express_checkout`. This identifies the transaction.
Required
--------
* TOKEN
* PAYMENTACTION
* PAYERID
* AMT
"""
return self._call('DoExpressCheckoutPayment', **kwargs)
def generate_express_checkout_redirect_url(self, token, useraction=None):
"""Returns the URL to redirect the user to for the Express checkout.
Express Checkouts must be verified by the customer by redirecting them
to the PayPal website. Use the token returned in the response from
:meth:`set_express_checkout` with this function to figure out where
to redirect the user to.
The button text on the PayPal page can be controlled via `useraction`.
The documented possible values are `commit` and `continue`. However,
any other value will only result in a warning.
:param str token: The unique token identifying this transaction.
:param str useraction: Control the button text on the PayPal page.
:rtype: str
:returns: The URL to redirect the user to for approval.
"""
url_vars = (self.config.PAYPAL_URL_BASE, token)
url = "%s?cmd=_express-checkout&token=%s" % url_vars
if useraction:
if not useraction.lower() in ('commit', 'continue'):
warnings.warn('useraction=%s is not documented' % useraction,
RuntimeWarning)
url += '&useraction=%s' % useraction
return url
def generate_cart_upload_redirect_url(self, **kwargs):
"""https://www.sandbox.paypal.com/webscr
?cmd=_cart
&upload=1
"""
required_vals = ('business', 'item_name_1', 'amount_1', 'quantity_1')
self._check_required(required_vals, **kwargs)
url = "%s?cmd=_cart&upload=1" % self.config.PAYPAL_URL_BASE
additional = self._encode_utf8(**kwargs)
additional = urlencode(additional)
return url + "&" + additional
def get_recurring_payments_profile_details(self, profileid):
"""Shortcut for the GetRecurringPaymentsProfile method.
This returns details for a recurring payment plan. The ``profileid`` is
a value included in the response retrieved by the function
``create_recurring_payments_profile``. The profile details include the
data provided when the profile was created as well as default values
for ignored fields and some pertinent stastics.
e.g.:
response = create_recurring_payments_profile(**profile_info)
profileid = response.PROFILEID
details = get_recurring_payments_profile(profileid)
The response from PayPal is somewhat self-explanatory, but for a
description of each field, visit the following URI:
https://www.x.com/docs/DOC-1194
"""
args = self._sanitize_locals(locals())
return self._call('GetRecurringPaymentsProfileDetails', **args)
def manage_recurring_payments_profile_status(self, profileid, action,
note=None):
"""Shortcut to the ManageRecurringPaymentsProfileStatus method.
``profileid`` is the same profile id used for getting profile details.
``action`` should be either 'Cancel', 'Suspend', or 'Reactivate'.
``note`` is optional and is visible to the user. It contains the
reason for the change in status.
"""
args = self._sanitize_locals(locals())
if not note:
del args['note']
return self._call('ManageRecurringPaymentsProfileStatus', **args)
def update_recurring_payments_profile(self, profileid, **kwargs):
"""Shortcut to the UpdateRecurringPaymentsProfile method.
``profileid`` is the same profile id used for getting profile details.
The keyed arguments are data in the payment profile which you wish to
change. The profileid does not change. Anything else will take the new
value. Most of, though not all of, the fields available are shared
with creating a profile, but for the complete list of parameters, you
can visit the following URI:
https://www.x.com/docs/DOC-1212
"""
kwargs.update(self._sanitize_locals(locals()))
return self._call('UpdateRecurringPaymentsProfile', **kwargs)
def bm_create_button(self, **kwargs):
"""Shortcut to the BMCreateButton method.
See the docs for details on arguments:
https://cms.paypal.com/mx/cgi-bin/?cmd=_render-content&content_ID=developer/e_howto_api_nvp_BMCreateButton
The L_BUTTONVARn fields are especially important, so make sure to
read those and act accordingly. See unit tests for some examples.
"""
kwargs.update(self._sanitize_locals(locals()))
return self._call('BMCreateButton', **kwargs)
|
gtaylor/paypal-python
|
paypal/interface.py
|
PayPalInterface.refund_transaction
|
python
|
def refund_transaction(self, transactionid=None, payerid=None, **kwargs):
# This line seems like a complete waste of time... kwargs should not
# be populated
if (transactionid is None) and (payerid is None):
raise PayPalError(
'RefundTransaction requires either a transactionid or '
'a payerid')
if (transactionid is not None) and (payerid is not None):
raise PayPalError(
'RefundTransaction requires only one of transactionid %s '
'and payerid %s' % (transactionid, payerid))
if transactionid is not None:
kwargs['TRANSACTIONID'] = transactionid
else:
kwargs['PAYERID'] = payerid
return self._call('RefundTransaction', **kwargs)
|
Shortcut for RefundTransaction method.
Note new API supports passing a PayerID instead of a transaction id,
exactly one must be provided.
Optional:
INVOICEID
REFUNDTYPE
AMT
CURRENCYCODE
NOTE
RETRYUNTIL
REFUNDSOURCE
MERCHANTSTOREDETAILS
REFUNDADVICE
REFUNDITEMDETAILS
MSGSUBID
MERCHANSTOREDETAILS has two fields:
STOREID
TERMINALID
|
train
|
https://github.com/gtaylor/paypal-python/blob/aa7a987ea9e9b7f37bcd8a8b54a440aad6c871b1/paypal/interface.py#L375-L412
|
[
"def _call(self, method, **kwargs):\n \"\"\"\n Wrapper method for executing all API commands over HTTP. This method is\n further used to implement wrapper methods listed here:\n\n https://www.x.com/docs/DOC-1374\n\n ``method`` must be a supported NVP method listed at the above address.\n ``kwargs`` the actual call parameters\n \"\"\"\n post_params = self._get_call_params(method, **kwargs)\n payload = post_params['data']\n api_endpoint = post_params['url']\n\n # This shows all of the key/val pairs we're sending to PayPal.\n if logger.isEnabledFor(logging.DEBUG):\n logger.debug('PayPal NVP Query Key/Vals:\\n%s' % pformat(payload))\n\n http_response = requests.post(**post_params)\n response = PayPalResponse(http_response.text, self.config)\n logger.debug('PayPal NVP API Endpoint: %s' % api_endpoint)\n\n if not response.success:\n raise PayPalAPIResponseError(response)\n\n return response\n"
] |
class PayPalInterface(object):
__credentials = ['USER', 'PWD', 'SIGNATURE', 'SUBJECT']
"""
The end developers will do 95% of their work through this class. API
queries, configuration, etc, all go through here. See the __init__ method
for config related details.
"""
def __init__(self, config=None, **kwargs):
"""
Constructor, which passes all config directives to the config class
via kwargs. For example:
paypal = PayPalInterface(API_USERNAME='somevalue')
Optionally, you may pass a 'config' kwarg to provide your own
PayPalConfig object.
"""
if config:
# User provided their own PayPalConfig object.
self.config = config
else:
# Take the kwargs and stuff them in a new PayPalConfig object.
self.config = PayPalConfig(**kwargs)
def _encode_utf8(self, **kwargs):
"""
UTF8 encodes all of the NVP values.
"""
if is_py3:
# This is only valid for Python 2. In Python 3, unicode is
# everywhere (yay).
return kwargs
unencoded_pairs = kwargs
for i in unencoded_pairs.keys():
#noinspection PyUnresolvedReferences
if isinstance(unencoded_pairs[i], types.UnicodeType):
unencoded_pairs[i] = unencoded_pairs[i].encode('utf-8')
return unencoded_pairs
def _check_required(self, requires, **kwargs):
"""
Checks kwargs for the values specified in 'requires', which is a tuple
of strings. These strings are the NVP names of the required values.
"""
for req in requires:
# PayPal api is never mixed-case.
if req.lower() not in kwargs and req.upper() not in kwargs:
raise PayPalError('missing required : %s' % req)
def _sanitize_locals(self, data):
"""
Remove the 'self' key in locals()
It's more explicit to do it in one function
"""
if 'self' in data:
data = data.copy()
del data['self']
return data
def _call(self, method, **kwargs):
"""
Wrapper method for executing all API commands over HTTP. This method is
further used to implement wrapper methods listed here:
https://www.x.com/docs/DOC-1374
``method`` must be a supported NVP method listed at the above address.
``kwargs`` the actual call parameters
"""
post_params = self._get_call_params(method, **kwargs)
payload = post_params['data']
api_endpoint = post_params['url']
# This shows all of the key/val pairs we're sending to PayPal.
if logger.isEnabledFor(logging.DEBUG):
logger.debug('PayPal NVP Query Key/Vals:\n%s' % pformat(payload))
http_response = requests.post(**post_params)
response = PayPalResponse(http_response.text, self.config)
logger.debug('PayPal NVP API Endpoint: %s' % api_endpoint)
if not response.success:
raise PayPalAPIResponseError(response)
return response
def _get_call_params(self, method, **kwargs):
"""
Returns the prepared call parameters. Mind, these will be keyword
arguments to ``requests.post``.
``method`` the NVP method
``kwargs`` the actual call parameters
"""
payload = {'METHOD': method,
'VERSION': self.config.API_VERSION}
certificate = None
if self.config.API_AUTHENTICATION_MODE == "3TOKEN":
payload['USER'] = self.config.API_USERNAME
payload['PWD'] = self.config.API_PASSWORD
payload['SIGNATURE'] = self.config.API_SIGNATURE
elif self.config.API_AUTHENTICATION_MODE == "CERTIFICATE":
payload['USER'] = self.config.API_USERNAME
payload['PWD'] = self.config.API_PASSWORD
certificate = (self.config.API_CERTIFICATE_FILENAME,
self.config.API_KEY_FILENAME)
elif self.config.API_AUTHENTICATION_MODE == "UNIPAY":
payload['SUBJECT'] = self.config.UNIPAY_SUBJECT
none_configs = [config for config, value in payload.items()
if value is None]
if none_configs:
raise PayPalConfigError(
"Config(s) %s cannot be None. Please, check this "
"interface's config." % none_configs)
# all keys in the payload must be uppercase
for key, value in kwargs.items():
payload[key.upper()] = value
return {'data': payload,
'cert': certificate,
'url': self.config.API_ENDPOINT,
'timeout': self.config.HTTP_TIMEOUT,
'verify': self.config.API_CA_CERTS}
def address_verify(self, email, street, zip):
"""Shortcut for the AddressVerify method.
``email``::
Email address of a PayPal member to verify.
Maximum string length: 255 single-byte characters
Input mask: ?@?.??
``street``::
First line of the billing or shipping postal address to verify.
To pass verification, the value of Street must match the first three
single-byte characters of a postal address on file for the PayPal member.
Maximum string length: 35 single-byte characters.
Alphanumeric plus - , . ‘ # \
Whitespace and case of input value are ignored.
``zip``::
Postal code to verify.
To pass verification, the value of Zip mustmatch the first five
single-byte characters of the postal code of the verified postal
address for the verified PayPal member.
Maximumstring length: 16 single-byte characters.
Whitespace and case of input value are ignored.
"""
args = self._sanitize_locals(locals())
return self._call('AddressVerify', **args)
def create_recurring_payments_profile(self, **kwargs):
"""Shortcut for the CreateRecurringPaymentsProfile method.
Currently, this method only supports the Direct Payment flavor.
It requires standard credit card information and a few additional
parameters related to the billing. e.g.:
profile_info = {
# Credit card information
'creditcardtype': 'Visa',
'acct': '4812177017895760',
'expdate': '102015',
'cvv2': '123',
'firstname': 'John',
'lastname': 'Doe',
'street': '1313 Mockingbird Lane',
'city': 'Beverly Hills',
'state': 'CA',
'zip': '90110',
'countrycode': 'US',
'currencycode': 'USD',
# Recurring payment information
'profilestartdate': '2010-10-25T0:0:0',
'billingperiod': 'Month',
'billingfrequency': '6',
'amt': '10.00',
'desc': '6 months of our product.'
}
response = create_recurring_payments_profile(**profile_info)
The above NVPs compose the bare-minimum request for creating a
profile. For the complete list of parameters, visit this URI:
https://www.x.com/docs/DOC-1168
"""
return self._call('CreateRecurringPaymentsProfile', **kwargs)
def do_authorization(self, transactionid, amt):
"""Shortcut for the DoAuthorization method.
Use the TRANSACTIONID from DoExpressCheckoutPayment for the
``transactionid``. The latest version of the API does not support the
creation of an Order from `DoDirectPayment`.
The `amt` should be the same as passed to `DoExpressCheckoutPayment`.
Flow for a payment involving a `DoAuthorization` call::
1. One or many calls to `SetExpressCheckout` with pertinent order
details, returns `TOKEN`
1. `DoExpressCheckoutPayment` with `TOKEN`, `PAYMENTACTION` set to
Order, `AMT` set to the amount of the transaction, returns
`TRANSACTIONID`
1. `DoAuthorization` with `TRANSACTIONID` and `AMT` set to the
amount of the transaction.
1. `DoCapture` with the `AUTHORIZATIONID` (the `TRANSACTIONID`
returned by `DoAuthorization`)
"""
args = self._sanitize_locals(locals())
return self._call('DoAuthorization', **args)
def do_capture(self, authorizationid, amt, completetype='Complete',
**kwargs):
"""Shortcut for the DoCapture method.
Use the TRANSACTIONID from DoAuthorization, DoDirectPayment or
DoExpressCheckoutPayment for the ``authorizationid``.
The `amt` should be the same as the authorized transaction.
"""
kwargs.update(self._sanitize_locals(locals()))
return self._call('DoCapture', **kwargs)
def do_direct_payment(self, paymentaction="Sale", **kwargs):
"""Shortcut for the DoDirectPayment method.
``paymentaction`` could be 'Authorization' or 'Sale'
To issue a Sale immediately::
charge = {
'amt': '10.00',
'creditcardtype': 'Visa',
'acct': '4812177017895760',
'expdate': '012010',
'cvv2': '962',
'firstname': 'John',
'lastname': 'Doe',
'street': '1 Main St',
'city': 'San Jose',
'state': 'CA',
'zip': '95131',
'countrycode': 'US',
'currencycode': 'USD',
}
direct_payment("Sale", **charge)
Or, since "Sale" is the default:
direct_payment(**charge)
To issue an Authorization, simply pass "Authorization" instead
of "Sale".
You may also explicitly set ``paymentaction`` as a keyword argument:
...
direct_payment(paymentaction="Sale", **charge)
"""
kwargs.update(self._sanitize_locals(locals()))
return self._call('DoDirectPayment', **kwargs)
def do_void(self, **kwargs):
"""Shortcut for the DoVoid method.
Use the TRANSACTIONID from DoAuthorization, DoDirectPayment or
DoExpressCheckoutPayment for the ``AUTHORIZATIONID``.
Required Kwargs
---------------
* AUTHORIZATIONID
"""
return self._call('DoVoid', **kwargs)
def get_express_checkout_details(self, **kwargs):
"""Shortcut for the GetExpressCheckoutDetails method.
Required Kwargs
---------------
* TOKEN
"""
return self._call('GetExpressCheckoutDetails', **kwargs)
def get_transaction_details(self, **kwargs):
"""Shortcut for the GetTransactionDetails method.
Use the TRANSACTIONID from DoAuthorization, DoDirectPayment or
DoExpressCheckoutPayment for the ``transactionid``.
Required Kwargs
---------------
* TRANSACTIONID
"""
return self._call('GetTransactionDetails', **kwargs)
def transaction_search(self, **kwargs):
"""Shortcut for the TransactionSearch method.
Returns a PayPalResponseList object, which merges the L_ syntax list
to a list of dictionaries with properly named keys.
Note that the API will limit returned transactions to 100.
Required Kwargs
---------------
* STARTDATE
Optional Kwargs
---------------
STATUS = one of ['Pending','Processing','Success','Denied','Reversed']
"""
plain = self._call('TransactionSearch', **kwargs)
return PayPalResponseList(plain.raw, self.config)
def set_express_checkout(self, **kwargs):
"""Start an Express checkout.
You'll want to use this in conjunction with
:meth:`generate_express_checkout_redirect_url` to create a payment,
then figure out where to redirect the user to for them to
authorize the payment on PayPal's website.
Required Kwargs
---------------
* PAYMENTREQUEST_0_AMT
* PAYMENTREQUEST_0_PAYMENTACTION
* RETURNURL
* CANCELURL
"""
return self._call('SetExpressCheckout', **kwargs)
def do_express_checkout_payment(self, **kwargs):
"""Finishes an Express checkout.
TOKEN is the token that was returned earlier by
:meth:`set_express_checkout`. This identifies the transaction.
Required
--------
* TOKEN
* PAYMENTACTION
* PAYERID
* AMT
"""
return self._call('DoExpressCheckoutPayment', **kwargs)
def generate_express_checkout_redirect_url(self, token, useraction=None):
"""Returns the URL to redirect the user to for the Express checkout.
Express Checkouts must be verified by the customer by redirecting them
to the PayPal website. Use the token returned in the response from
:meth:`set_express_checkout` with this function to figure out where
to redirect the user to.
The button text on the PayPal page can be controlled via `useraction`.
The documented possible values are `commit` and `continue`. However,
any other value will only result in a warning.
:param str token: The unique token identifying this transaction.
:param str useraction: Control the button text on the PayPal page.
:rtype: str
:returns: The URL to redirect the user to for approval.
"""
url_vars = (self.config.PAYPAL_URL_BASE, token)
url = "%s?cmd=_express-checkout&token=%s" % url_vars
if useraction:
if not useraction.lower() in ('commit', 'continue'):
warnings.warn('useraction=%s is not documented' % useraction,
RuntimeWarning)
url += '&useraction=%s' % useraction
return url
def generate_cart_upload_redirect_url(self, **kwargs):
"""https://www.sandbox.paypal.com/webscr
?cmd=_cart
&upload=1
"""
required_vals = ('business', 'item_name_1', 'amount_1', 'quantity_1')
self._check_required(required_vals, **kwargs)
url = "%s?cmd=_cart&upload=1" % self.config.PAYPAL_URL_BASE
additional = self._encode_utf8(**kwargs)
additional = urlencode(additional)
return url + "&" + additional
def get_recurring_payments_profile_details(self, profileid):
"""Shortcut for the GetRecurringPaymentsProfile method.
This returns details for a recurring payment plan. The ``profileid`` is
a value included in the response retrieved by the function
``create_recurring_payments_profile``. The profile details include the
data provided when the profile was created as well as default values
for ignored fields and some pertinent stastics.
e.g.:
response = create_recurring_payments_profile(**profile_info)
profileid = response.PROFILEID
details = get_recurring_payments_profile(profileid)
The response from PayPal is somewhat self-explanatory, but for a
description of each field, visit the following URI:
https://www.x.com/docs/DOC-1194
"""
args = self._sanitize_locals(locals())
return self._call('GetRecurringPaymentsProfileDetails', **args)
def manage_recurring_payments_profile_status(self, profileid, action,
note=None):
"""Shortcut to the ManageRecurringPaymentsProfileStatus method.
``profileid`` is the same profile id used for getting profile details.
``action`` should be either 'Cancel', 'Suspend', or 'Reactivate'.
``note`` is optional and is visible to the user. It contains the
reason for the change in status.
"""
args = self._sanitize_locals(locals())
if not note:
del args['note']
return self._call('ManageRecurringPaymentsProfileStatus', **args)
def update_recurring_payments_profile(self, profileid, **kwargs):
"""Shortcut to the UpdateRecurringPaymentsProfile method.
``profileid`` is the same profile id used for getting profile details.
The keyed arguments are data in the payment profile which you wish to
change. The profileid does not change. Anything else will take the new
value. Most of, though not all of, the fields available are shared
with creating a profile, but for the complete list of parameters, you
can visit the following URI:
https://www.x.com/docs/DOC-1212
"""
kwargs.update(self._sanitize_locals(locals()))
return self._call('UpdateRecurringPaymentsProfile', **kwargs)
def bm_create_button(self, **kwargs):
"""Shortcut to the BMCreateButton method.
See the docs for details on arguments:
https://cms.paypal.com/mx/cgi-bin/?cmd=_render-content&content_ID=developer/e_howto_api_nvp_BMCreateButton
The L_BUTTONVARn fields are especially important, so make sure to
read those and act accordingly. See unit tests for some examples.
"""
kwargs.update(self._sanitize_locals(locals()))
return self._call('BMCreateButton', **kwargs)
|
gtaylor/paypal-python
|
paypal/interface.py
|
PayPalInterface.generate_express_checkout_redirect_url
|
python
|
def generate_express_checkout_redirect_url(self, token, useraction=None):
url_vars = (self.config.PAYPAL_URL_BASE, token)
url = "%s?cmd=_express-checkout&token=%s" % url_vars
if useraction:
if not useraction.lower() in ('commit', 'continue'):
warnings.warn('useraction=%s is not documented' % useraction,
RuntimeWarning)
url += '&useraction=%s' % useraction
return url
|
Returns the URL to redirect the user to for the Express checkout.
Express Checkouts must be verified by the customer by redirecting them
to the PayPal website. Use the token returned in the response from
:meth:`set_express_checkout` with this function to figure out where
to redirect the user to.
The button text on the PayPal page can be controlled via `useraction`.
The documented possible values are `commit` and `continue`. However,
any other value will only result in a warning.
:param str token: The unique token identifying this transaction.
:param str useraction: Control the button text on the PayPal page.
:rtype: str
:returns: The URL to redirect the user to for approval.
|
train
|
https://github.com/gtaylor/paypal-python/blob/aa7a987ea9e9b7f37bcd8a8b54a440aad6c871b1/paypal/interface.py#L430-L454
| null |
class PayPalInterface(object):
__credentials = ['USER', 'PWD', 'SIGNATURE', 'SUBJECT']
"""
The end developers will do 95% of their work through this class. API
queries, configuration, etc, all go through here. See the __init__ method
for config related details.
"""
def __init__(self, config=None, **kwargs):
"""
Constructor, which passes all config directives to the config class
via kwargs. For example:
paypal = PayPalInterface(API_USERNAME='somevalue')
Optionally, you may pass a 'config' kwarg to provide your own
PayPalConfig object.
"""
if config:
# User provided their own PayPalConfig object.
self.config = config
else:
# Take the kwargs and stuff them in a new PayPalConfig object.
self.config = PayPalConfig(**kwargs)
def _encode_utf8(self, **kwargs):
"""
UTF8 encodes all of the NVP values.
"""
if is_py3:
# This is only valid for Python 2. In Python 3, unicode is
# everywhere (yay).
return kwargs
unencoded_pairs = kwargs
for i in unencoded_pairs.keys():
#noinspection PyUnresolvedReferences
if isinstance(unencoded_pairs[i], types.UnicodeType):
unencoded_pairs[i] = unencoded_pairs[i].encode('utf-8')
return unencoded_pairs
def _check_required(self, requires, **kwargs):
"""
Checks kwargs for the values specified in 'requires', which is a tuple
of strings. These strings are the NVP names of the required values.
"""
for req in requires:
# PayPal api is never mixed-case.
if req.lower() not in kwargs and req.upper() not in kwargs:
raise PayPalError('missing required : %s' % req)
def _sanitize_locals(self, data):
"""
Remove the 'self' key in locals()
It's more explicit to do it in one function
"""
if 'self' in data:
data = data.copy()
del data['self']
return data
def _call(self, method, **kwargs):
"""
Wrapper method for executing all API commands over HTTP. This method is
further used to implement wrapper methods listed here:
https://www.x.com/docs/DOC-1374
``method`` must be a supported NVP method listed at the above address.
``kwargs`` the actual call parameters
"""
post_params = self._get_call_params(method, **kwargs)
payload = post_params['data']
api_endpoint = post_params['url']
# This shows all of the key/val pairs we're sending to PayPal.
if logger.isEnabledFor(logging.DEBUG):
logger.debug('PayPal NVP Query Key/Vals:\n%s' % pformat(payload))
http_response = requests.post(**post_params)
response = PayPalResponse(http_response.text, self.config)
logger.debug('PayPal NVP API Endpoint: %s' % api_endpoint)
if not response.success:
raise PayPalAPIResponseError(response)
return response
def _get_call_params(self, method, **kwargs):
"""
Returns the prepared call parameters. Mind, these will be keyword
arguments to ``requests.post``.
``method`` the NVP method
``kwargs`` the actual call parameters
"""
payload = {'METHOD': method,
'VERSION': self.config.API_VERSION}
certificate = None
if self.config.API_AUTHENTICATION_MODE == "3TOKEN":
payload['USER'] = self.config.API_USERNAME
payload['PWD'] = self.config.API_PASSWORD
payload['SIGNATURE'] = self.config.API_SIGNATURE
elif self.config.API_AUTHENTICATION_MODE == "CERTIFICATE":
payload['USER'] = self.config.API_USERNAME
payload['PWD'] = self.config.API_PASSWORD
certificate = (self.config.API_CERTIFICATE_FILENAME,
self.config.API_KEY_FILENAME)
elif self.config.API_AUTHENTICATION_MODE == "UNIPAY":
payload['SUBJECT'] = self.config.UNIPAY_SUBJECT
none_configs = [config for config, value in payload.items()
if value is None]
if none_configs:
raise PayPalConfigError(
"Config(s) %s cannot be None. Please, check this "
"interface's config." % none_configs)
# all keys in the payload must be uppercase
for key, value in kwargs.items():
payload[key.upper()] = value
return {'data': payload,
'cert': certificate,
'url': self.config.API_ENDPOINT,
'timeout': self.config.HTTP_TIMEOUT,
'verify': self.config.API_CA_CERTS}
def address_verify(self, email, street, zip):
"""Shortcut for the AddressVerify method.
``email``::
Email address of a PayPal member to verify.
Maximum string length: 255 single-byte characters
Input mask: ?@?.??
``street``::
First line of the billing or shipping postal address to verify.
To pass verification, the value of Street must match the first three
single-byte characters of a postal address on file for the PayPal member.
Maximum string length: 35 single-byte characters.
Alphanumeric plus - , . ‘ # \
Whitespace and case of input value are ignored.
``zip``::
Postal code to verify.
To pass verification, the value of Zip mustmatch the first five
single-byte characters of the postal code of the verified postal
address for the verified PayPal member.
Maximumstring length: 16 single-byte characters.
Whitespace and case of input value are ignored.
"""
args = self._sanitize_locals(locals())
return self._call('AddressVerify', **args)
def create_recurring_payments_profile(self, **kwargs):
"""Shortcut for the CreateRecurringPaymentsProfile method.
Currently, this method only supports the Direct Payment flavor.
It requires standard credit card information and a few additional
parameters related to the billing. e.g.:
profile_info = {
# Credit card information
'creditcardtype': 'Visa',
'acct': '4812177017895760',
'expdate': '102015',
'cvv2': '123',
'firstname': 'John',
'lastname': 'Doe',
'street': '1313 Mockingbird Lane',
'city': 'Beverly Hills',
'state': 'CA',
'zip': '90110',
'countrycode': 'US',
'currencycode': 'USD',
# Recurring payment information
'profilestartdate': '2010-10-25T0:0:0',
'billingperiod': 'Month',
'billingfrequency': '6',
'amt': '10.00',
'desc': '6 months of our product.'
}
response = create_recurring_payments_profile(**profile_info)
The above NVPs compose the bare-minimum request for creating a
profile. For the complete list of parameters, visit this URI:
https://www.x.com/docs/DOC-1168
"""
return self._call('CreateRecurringPaymentsProfile', **kwargs)
def do_authorization(self, transactionid, amt):
"""Shortcut for the DoAuthorization method.
Use the TRANSACTIONID from DoExpressCheckoutPayment for the
``transactionid``. The latest version of the API does not support the
creation of an Order from `DoDirectPayment`.
The `amt` should be the same as passed to `DoExpressCheckoutPayment`.
Flow for a payment involving a `DoAuthorization` call::
1. One or many calls to `SetExpressCheckout` with pertinent order
details, returns `TOKEN`
1. `DoExpressCheckoutPayment` with `TOKEN`, `PAYMENTACTION` set to
Order, `AMT` set to the amount of the transaction, returns
`TRANSACTIONID`
1. `DoAuthorization` with `TRANSACTIONID` and `AMT` set to the
amount of the transaction.
1. `DoCapture` with the `AUTHORIZATIONID` (the `TRANSACTIONID`
returned by `DoAuthorization`)
"""
args = self._sanitize_locals(locals())
return self._call('DoAuthorization', **args)
def do_capture(self, authorizationid, amt, completetype='Complete',
**kwargs):
"""Shortcut for the DoCapture method.
Use the TRANSACTIONID from DoAuthorization, DoDirectPayment or
DoExpressCheckoutPayment for the ``authorizationid``.
The `amt` should be the same as the authorized transaction.
"""
kwargs.update(self._sanitize_locals(locals()))
return self._call('DoCapture', **kwargs)
def do_direct_payment(self, paymentaction="Sale", **kwargs):
"""Shortcut for the DoDirectPayment method.
``paymentaction`` could be 'Authorization' or 'Sale'
To issue a Sale immediately::
charge = {
'amt': '10.00',
'creditcardtype': 'Visa',
'acct': '4812177017895760',
'expdate': '012010',
'cvv2': '962',
'firstname': 'John',
'lastname': 'Doe',
'street': '1 Main St',
'city': 'San Jose',
'state': 'CA',
'zip': '95131',
'countrycode': 'US',
'currencycode': 'USD',
}
direct_payment("Sale", **charge)
Or, since "Sale" is the default:
direct_payment(**charge)
To issue an Authorization, simply pass "Authorization" instead
of "Sale".
You may also explicitly set ``paymentaction`` as a keyword argument:
...
direct_payment(paymentaction="Sale", **charge)
"""
kwargs.update(self._sanitize_locals(locals()))
return self._call('DoDirectPayment', **kwargs)
def do_void(self, **kwargs):
"""Shortcut for the DoVoid method.
Use the TRANSACTIONID from DoAuthorization, DoDirectPayment or
DoExpressCheckoutPayment for the ``AUTHORIZATIONID``.
Required Kwargs
---------------
* AUTHORIZATIONID
"""
return self._call('DoVoid', **kwargs)
def get_express_checkout_details(self, **kwargs):
"""Shortcut for the GetExpressCheckoutDetails method.
Required Kwargs
---------------
* TOKEN
"""
return self._call('GetExpressCheckoutDetails', **kwargs)
def get_transaction_details(self, **kwargs):
"""Shortcut for the GetTransactionDetails method.
Use the TRANSACTIONID from DoAuthorization, DoDirectPayment or
DoExpressCheckoutPayment for the ``transactionid``.
Required Kwargs
---------------
* TRANSACTIONID
"""
return self._call('GetTransactionDetails', **kwargs)
def transaction_search(self, **kwargs):
"""Shortcut for the TransactionSearch method.
Returns a PayPalResponseList object, which merges the L_ syntax list
to a list of dictionaries with properly named keys.
Note that the API will limit returned transactions to 100.
Required Kwargs
---------------
* STARTDATE
Optional Kwargs
---------------
STATUS = one of ['Pending','Processing','Success','Denied','Reversed']
"""
plain = self._call('TransactionSearch', **kwargs)
return PayPalResponseList(plain.raw, self.config)
def set_express_checkout(self, **kwargs):
"""Start an Express checkout.
You'll want to use this in conjunction with
:meth:`generate_express_checkout_redirect_url` to create a payment,
then figure out where to redirect the user to for them to
authorize the payment on PayPal's website.
Required Kwargs
---------------
* PAYMENTREQUEST_0_AMT
* PAYMENTREQUEST_0_PAYMENTACTION
* RETURNURL
* CANCELURL
"""
return self._call('SetExpressCheckout', **kwargs)
def refund_transaction(self, transactionid=None, payerid=None, **kwargs):
"""Shortcut for RefundTransaction method.
Note new API supports passing a PayerID instead of a transaction id,
exactly one must be provided.
Optional:
INVOICEID
REFUNDTYPE
AMT
CURRENCYCODE
NOTE
RETRYUNTIL
REFUNDSOURCE
MERCHANTSTOREDETAILS
REFUNDADVICE
REFUNDITEMDETAILS
MSGSUBID
MERCHANSTOREDETAILS has two fields:
STOREID
TERMINALID
"""
# This line seems like a complete waste of time... kwargs should not
# be populated
if (transactionid is None) and (payerid is None):
raise PayPalError(
'RefundTransaction requires either a transactionid or '
'a payerid')
if (transactionid is not None) and (payerid is not None):
raise PayPalError(
'RefundTransaction requires only one of transactionid %s '
'and payerid %s' % (transactionid, payerid))
if transactionid is not None:
kwargs['TRANSACTIONID'] = transactionid
else:
kwargs['PAYERID'] = payerid
return self._call('RefundTransaction', **kwargs)
def do_express_checkout_payment(self, **kwargs):
"""Finishes an Express checkout.
TOKEN is the token that was returned earlier by
:meth:`set_express_checkout`. This identifies the transaction.
Required
--------
* TOKEN
* PAYMENTACTION
* PAYERID
* AMT
"""
return self._call('DoExpressCheckoutPayment', **kwargs)
def generate_cart_upload_redirect_url(self, **kwargs):
"""https://www.sandbox.paypal.com/webscr
?cmd=_cart
&upload=1
"""
required_vals = ('business', 'item_name_1', 'amount_1', 'quantity_1')
self._check_required(required_vals, **kwargs)
url = "%s?cmd=_cart&upload=1" % self.config.PAYPAL_URL_BASE
additional = self._encode_utf8(**kwargs)
additional = urlencode(additional)
return url + "&" + additional
def get_recurring_payments_profile_details(self, profileid):
"""Shortcut for the GetRecurringPaymentsProfile method.
This returns details for a recurring payment plan. The ``profileid`` is
a value included in the response retrieved by the function
``create_recurring_payments_profile``. The profile details include the
data provided when the profile was created as well as default values
for ignored fields and some pertinent stastics.
e.g.:
response = create_recurring_payments_profile(**profile_info)
profileid = response.PROFILEID
details = get_recurring_payments_profile(profileid)
The response from PayPal is somewhat self-explanatory, but for a
description of each field, visit the following URI:
https://www.x.com/docs/DOC-1194
"""
args = self._sanitize_locals(locals())
return self._call('GetRecurringPaymentsProfileDetails', **args)
def manage_recurring_payments_profile_status(self, profileid, action,
note=None):
"""Shortcut to the ManageRecurringPaymentsProfileStatus method.
``profileid`` is the same profile id used for getting profile details.
``action`` should be either 'Cancel', 'Suspend', or 'Reactivate'.
``note`` is optional and is visible to the user. It contains the
reason for the change in status.
"""
args = self._sanitize_locals(locals())
if not note:
del args['note']
return self._call('ManageRecurringPaymentsProfileStatus', **args)
def update_recurring_payments_profile(self, profileid, **kwargs):
"""Shortcut to the UpdateRecurringPaymentsProfile method.
``profileid`` is the same profile id used for getting profile details.
The keyed arguments are data in the payment profile which you wish to
change. The profileid does not change. Anything else will take the new
value. Most of, though not all of, the fields available are shared
with creating a profile, but for the complete list of parameters, you
can visit the following URI:
https://www.x.com/docs/DOC-1212
"""
kwargs.update(self._sanitize_locals(locals()))
return self._call('UpdateRecurringPaymentsProfile', **kwargs)
def bm_create_button(self, **kwargs):
"""Shortcut to the BMCreateButton method.
See the docs for details on arguments:
https://cms.paypal.com/mx/cgi-bin/?cmd=_render-content&content_ID=developer/e_howto_api_nvp_BMCreateButton
The L_BUTTONVARn fields are especially important, so make sure to
read those and act accordingly. See unit tests for some examples.
"""
kwargs.update(self._sanitize_locals(locals()))
return self._call('BMCreateButton', **kwargs)
|
gtaylor/paypal-python
|
paypal/interface.py
|
PayPalInterface.generate_cart_upload_redirect_url
|
python
|
def generate_cart_upload_redirect_url(self, **kwargs):
required_vals = ('business', 'item_name_1', 'amount_1', 'quantity_1')
self._check_required(required_vals, **kwargs)
url = "%s?cmd=_cart&upload=1" % self.config.PAYPAL_URL_BASE
additional = self._encode_utf8(**kwargs)
additional = urlencode(additional)
return url + "&" + additional
|
https://www.sandbox.paypal.com/webscr
?cmd=_cart
&upload=1
|
train
|
https://github.com/gtaylor/paypal-python/blob/aa7a987ea9e9b7f37bcd8a8b54a440aad6c871b1/paypal/interface.py#L456-L466
|
[
"def _encode_utf8(self, **kwargs):\n \"\"\"\n UTF8 encodes all of the NVP values.\n \"\"\"\n if is_py3:\n # This is only valid for Python 2. In Python 3, unicode is\n # everywhere (yay).\n return kwargs\n\n unencoded_pairs = kwargs\n for i in unencoded_pairs.keys():\n #noinspection PyUnresolvedReferences\n if isinstance(unencoded_pairs[i], types.UnicodeType):\n unencoded_pairs[i] = unencoded_pairs[i].encode('utf-8')\n return unencoded_pairs\n",
"def _check_required(self, requires, **kwargs):\n \"\"\"\n Checks kwargs for the values specified in 'requires', which is a tuple\n of strings. These strings are the NVP names of the required values.\n \"\"\"\n for req in requires:\n # PayPal api is never mixed-case.\n if req.lower() not in kwargs and req.upper() not in kwargs:\n raise PayPalError('missing required : %s' % req)\n"
] |
class PayPalInterface(object):
__credentials = ['USER', 'PWD', 'SIGNATURE', 'SUBJECT']
"""
The end developers will do 95% of their work through this class. API
queries, configuration, etc, all go through here. See the __init__ method
for config related details.
"""
def __init__(self, config=None, **kwargs):
"""
Constructor, which passes all config directives to the config class
via kwargs. For example:
paypal = PayPalInterface(API_USERNAME='somevalue')
Optionally, you may pass a 'config' kwarg to provide your own
PayPalConfig object.
"""
if config:
# User provided their own PayPalConfig object.
self.config = config
else:
# Take the kwargs and stuff them in a new PayPalConfig object.
self.config = PayPalConfig(**kwargs)
def _encode_utf8(self, **kwargs):
"""
UTF8 encodes all of the NVP values.
"""
if is_py3:
# This is only valid for Python 2. In Python 3, unicode is
# everywhere (yay).
return kwargs
unencoded_pairs = kwargs
for i in unencoded_pairs.keys():
#noinspection PyUnresolvedReferences
if isinstance(unencoded_pairs[i], types.UnicodeType):
unencoded_pairs[i] = unencoded_pairs[i].encode('utf-8')
return unencoded_pairs
def _check_required(self, requires, **kwargs):
"""
Checks kwargs for the values specified in 'requires', which is a tuple
of strings. These strings are the NVP names of the required values.
"""
for req in requires:
# PayPal api is never mixed-case.
if req.lower() not in kwargs and req.upper() not in kwargs:
raise PayPalError('missing required : %s' % req)
def _sanitize_locals(self, data):
"""
Remove the 'self' key in locals()
It's more explicit to do it in one function
"""
if 'self' in data:
data = data.copy()
del data['self']
return data
def _call(self, method, **kwargs):
"""
Wrapper method for executing all API commands over HTTP. This method is
further used to implement wrapper methods listed here:
https://www.x.com/docs/DOC-1374
``method`` must be a supported NVP method listed at the above address.
``kwargs`` the actual call parameters
"""
post_params = self._get_call_params(method, **kwargs)
payload = post_params['data']
api_endpoint = post_params['url']
# This shows all of the key/val pairs we're sending to PayPal.
if logger.isEnabledFor(logging.DEBUG):
logger.debug('PayPal NVP Query Key/Vals:\n%s' % pformat(payload))
http_response = requests.post(**post_params)
response = PayPalResponse(http_response.text, self.config)
logger.debug('PayPal NVP API Endpoint: %s' % api_endpoint)
if not response.success:
raise PayPalAPIResponseError(response)
return response
def _get_call_params(self, method, **kwargs):
"""
Returns the prepared call parameters. Mind, these will be keyword
arguments to ``requests.post``.
``method`` the NVP method
``kwargs`` the actual call parameters
"""
payload = {'METHOD': method,
'VERSION': self.config.API_VERSION}
certificate = None
if self.config.API_AUTHENTICATION_MODE == "3TOKEN":
payload['USER'] = self.config.API_USERNAME
payload['PWD'] = self.config.API_PASSWORD
payload['SIGNATURE'] = self.config.API_SIGNATURE
elif self.config.API_AUTHENTICATION_MODE == "CERTIFICATE":
payload['USER'] = self.config.API_USERNAME
payload['PWD'] = self.config.API_PASSWORD
certificate = (self.config.API_CERTIFICATE_FILENAME,
self.config.API_KEY_FILENAME)
elif self.config.API_AUTHENTICATION_MODE == "UNIPAY":
payload['SUBJECT'] = self.config.UNIPAY_SUBJECT
none_configs = [config for config, value in payload.items()
if value is None]
if none_configs:
raise PayPalConfigError(
"Config(s) %s cannot be None. Please, check this "
"interface's config." % none_configs)
# all keys in the payload must be uppercase
for key, value in kwargs.items():
payload[key.upper()] = value
return {'data': payload,
'cert': certificate,
'url': self.config.API_ENDPOINT,
'timeout': self.config.HTTP_TIMEOUT,
'verify': self.config.API_CA_CERTS}
def address_verify(self, email, street, zip):
"""Shortcut for the AddressVerify method.
``email``::
Email address of a PayPal member to verify.
Maximum string length: 255 single-byte characters
Input mask: ?@?.??
``street``::
First line of the billing or shipping postal address to verify.
To pass verification, the value of Street must match the first three
single-byte characters of a postal address on file for the PayPal member.
Maximum string length: 35 single-byte characters.
Alphanumeric plus - , . ‘ # \
Whitespace and case of input value are ignored.
``zip``::
Postal code to verify.
To pass verification, the value of Zip mustmatch the first five
single-byte characters of the postal code of the verified postal
address for the verified PayPal member.
Maximumstring length: 16 single-byte characters.
Whitespace and case of input value are ignored.
"""
args = self._sanitize_locals(locals())
return self._call('AddressVerify', **args)
def create_recurring_payments_profile(self, **kwargs):
"""Shortcut for the CreateRecurringPaymentsProfile method.
Currently, this method only supports the Direct Payment flavor.
It requires standard credit card information and a few additional
parameters related to the billing. e.g.:
profile_info = {
# Credit card information
'creditcardtype': 'Visa',
'acct': '4812177017895760',
'expdate': '102015',
'cvv2': '123',
'firstname': 'John',
'lastname': 'Doe',
'street': '1313 Mockingbird Lane',
'city': 'Beverly Hills',
'state': 'CA',
'zip': '90110',
'countrycode': 'US',
'currencycode': 'USD',
# Recurring payment information
'profilestartdate': '2010-10-25T0:0:0',
'billingperiod': 'Month',
'billingfrequency': '6',
'amt': '10.00',
'desc': '6 months of our product.'
}
response = create_recurring_payments_profile(**profile_info)
The above NVPs compose the bare-minimum request for creating a
profile. For the complete list of parameters, visit this URI:
https://www.x.com/docs/DOC-1168
"""
return self._call('CreateRecurringPaymentsProfile', **kwargs)
def do_authorization(self, transactionid, amt):
"""Shortcut for the DoAuthorization method.
Use the TRANSACTIONID from DoExpressCheckoutPayment for the
``transactionid``. The latest version of the API does not support the
creation of an Order from `DoDirectPayment`.
The `amt` should be the same as passed to `DoExpressCheckoutPayment`.
Flow for a payment involving a `DoAuthorization` call::
1. One or many calls to `SetExpressCheckout` with pertinent order
details, returns `TOKEN`
1. `DoExpressCheckoutPayment` with `TOKEN`, `PAYMENTACTION` set to
Order, `AMT` set to the amount of the transaction, returns
`TRANSACTIONID`
1. `DoAuthorization` with `TRANSACTIONID` and `AMT` set to the
amount of the transaction.
1. `DoCapture` with the `AUTHORIZATIONID` (the `TRANSACTIONID`
returned by `DoAuthorization`)
"""
args = self._sanitize_locals(locals())
return self._call('DoAuthorization', **args)
def do_capture(self, authorizationid, amt, completetype='Complete',
**kwargs):
"""Shortcut for the DoCapture method.
Use the TRANSACTIONID from DoAuthorization, DoDirectPayment or
DoExpressCheckoutPayment for the ``authorizationid``.
The `amt` should be the same as the authorized transaction.
"""
kwargs.update(self._sanitize_locals(locals()))
return self._call('DoCapture', **kwargs)
def do_direct_payment(self, paymentaction="Sale", **kwargs):
"""Shortcut for the DoDirectPayment method.
``paymentaction`` could be 'Authorization' or 'Sale'
To issue a Sale immediately::
charge = {
'amt': '10.00',
'creditcardtype': 'Visa',
'acct': '4812177017895760',
'expdate': '012010',
'cvv2': '962',
'firstname': 'John',
'lastname': 'Doe',
'street': '1 Main St',
'city': 'San Jose',
'state': 'CA',
'zip': '95131',
'countrycode': 'US',
'currencycode': 'USD',
}
direct_payment("Sale", **charge)
Or, since "Sale" is the default:
direct_payment(**charge)
To issue an Authorization, simply pass "Authorization" instead
of "Sale".
You may also explicitly set ``paymentaction`` as a keyword argument:
...
direct_payment(paymentaction="Sale", **charge)
"""
kwargs.update(self._sanitize_locals(locals()))
return self._call('DoDirectPayment', **kwargs)
def do_void(self, **kwargs):
"""Shortcut for the DoVoid method.
Use the TRANSACTIONID from DoAuthorization, DoDirectPayment or
DoExpressCheckoutPayment for the ``AUTHORIZATIONID``.
Required Kwargs
---------------
* AUTHORIZATIONID
"""
return self._call('DoVoid', **kwargs)
def get_express_checkout_details(self, **kwargs):
"""Shortcut for the GetExpressCheckoutDetails method.
Required Kwargs
---------------
* TOKEN
"""
return self._call('GetExpressCheckoutDetails', **kwargs)
def get_transaction_details(self, **kwargs):
"""Shortcut for the GetTransactionDetails method.
Use the TRANSACTIONID from DoAuthorization, DoDirectPayment or
DoExpressCheckoutPayment for the ``transactionid``.
Required Kwargs
---------------
* TRANSACTIONID
"""
return self._call('GetTransactionDetails', **kwargs)
def transaction_search(self, **kwargs):
"""Shortcut for the TransactionSearch method.
Returns a PayPalResponseList object, which merges the L_ syntax list
to a list of dictionaries with properly named keys.
Note that the API will limit returned transactions to 100.
Required Kwargs
---------------
* STARTDATE
Optional Kwargs
---------------
STATUS = one of ['Pending','Processing','Success','Denied','Reversed']
"""
plain = self._call('TransactionSearch', **kwargs)
return PayPalResponseList(plain.raw, self.config)
def set_express_checkout(self, **kwargs):
"""Start an Express checkout.
You'll want to use this in conjunction with
:meth:`generate_express_checkout_redirect_url` to create a payment,
then figure out where to redirect the user to for them to
authorize the payment on PayPal's website.
Required Kwargs
---------------
* PAYMENTREQUEST_0_AMT
* PAYMENTREQUEST_0_PAYMENTACTION
* RETURNURL
* CANCELURL
"""
return self._call('SetExpressCheckout', **kwargs)
def refund_transaction(self, transactionid=None, payerid=None, **kwargs):
"""Shortcut for RefundTransaction method.
Note new API supports passing a PayerID instead of a transaction id,
exactly one must be provided.
Optional:
INVOICEID
REFUNDTYPE
AMT
CURRENCYCODE
NOTE
RETRYUNTIL
REFUNDSOURCE
MERCHANTSTOREDETAILS
REFUNDADVICE
REFUNDITEMDETAILS
MSGSUBID
MERCHANSTOREDETAILS has two fields:
STOREID
TERMINALID
"""
# This line seems like a complete waste of time... kwargs should not
# be populated
if (transactionid is None) and (payerid is None):
raise PayPalError(
'RefundTransaction requires either a transactionid or '
'a payerid')
if (transactionid is not None) and (payerid is not None):
raise PayPalError(
'RefundTransaction requires only one of transactionid %s '
'and payerid %s' % (transactionid, payerid))
if transactionid is not None:
kwargs['TRANSACTIONID'] = transactionid
else:
kwargs['PAYERID'] = payerid
return self._call('RefundTransaction', **kwargs)
def do_express_checkout_payment(self, **kwargs):
"""Finishes an Express checkout.
TOKEN is the token that was returned earlier by
:meth:`set_express_checkout`. This identifies the transaction.
Required
--------
* TOKEN
* PAYMENTACTION
* PAYERID
* AMT
"""
return self._call('DoExpressCheckoutPayment', **kwargs)
def generate_express_checkout_redirect_url(self, token, useraction=None):
"""Returns the URL to redirect the user to for the Express checkout.
Express Checkouts must be verified by the customer by redirecting them
to the PayPal website. Use the token returned in the response from
:meth:`set_express_checkout` with this function to figure out where
to redirect the user to.
The button text on the PayPal page can be controlled via `useraction`.
The documented possible values are `commit` and `continue`. However,
any other value will only result in a warning.
:param str token: The unique token identifying this transaction.
:param str useraction: Control the button text on the PayPal page.
:rtype: str
:returns: The URL to redirect the user to for approval.
"""
url_vars = (self.config.PAYPAL_URL_BASE, token)
url = "%s?cmd=_express-checkout&token=%s" % url_vars
if useraction:
if not useraction.lower() in ('commit', 'continue'):
warnings.warn('useraction=%s is not documented' % useraction,
RuntimeWarning)
url += '&useraction=%s' % useraction
return url
def get_recurring_payments_profile_details(self, profileid):
"""Shortcut for the GetRecurringPaymentsProfile method.
This returns details for a recurring payment plan. The ``profileid`` is
a value included in the response retrieved by the function
``create_recurring_payments_profile``. The profile details include the
data provided when the profile was created as well as default values
for ignored fields and some pertinent stastics.
e.g.:
response = create_recurring_payments_profile(**profile_info)
profileid = response.PROFILEID
details = get_recurring_payments_profile(profileid)
The response from PayPal is somewhat self-explanatory, but for a
description of each field, visit the following URI:
https://www.x.com/docs/DOC-1194
"""
args = self._sanitize_locals(locals())
return self._call('GetRecurringPaymentsProfileDetails', **args)
def manage_recurring_payments_profile_status(self, profileid, action,
note=None):
"""Shortcut to the ManageRecurringPaymentsProfileStatus method.
``profileid`` is the same profile id used for getting profile details.
``action`` should be either 'Cancel', 'Suspend', or 'Reactivate'.
``note`` is optional and is visible to the user. It contains the
reason for the change in status.
"""
args = self._sanitize_locals(locals())
if not note:
del args['note']
return self._call('ManageRecurringPaymentsProfileStatus', **args)
def update_recurring_payments_profile(self, profileid, **kwargs):
"""Shortcut to the UpdateRecurringPaymentsProfile method.
``profileid`` is the same profile id used for getting profile details.
The keyed arguments are data in the payment profile which you wish to
change. The profileid does not change. Anything else will take the new
value. Most of, though not all of, the fields available are shared
with creating a profile, but for the complete list of parameters, you
can visit the following URI:
https://www.x.com/docs/DOC-1212
"""
kwargs.update(self._sanitize_locals(locals()))
return self._call('UpdateRecurringPaymentsProfile', **kwargs)
def bm_create_button(self, **kwargs):
"""Shortcut to the BMCreateButton method.
See the docs for details on arguments:
https://cms.paypal.com/mx/cgi-bin/?cmd=_render-content&content_ID=developer/e_howto_api_nvp_BMCreateButton
The L_BUTTONVARn fields are especially important, so make sure to
read those and act accordingly. See unit tests for some examples.
"""
kwargs.update(self._sanitize_locals(locals()))
return self._call('BMCreateButton', **kwargs)
|
gtaylor/paypal-python
|
paypal/interface.py
|
PayPalInterface.get_recurring_payments_profile_details
|
python
|
def get_recurring_payments_profile_details(self, profileid):
args = self._sanitize_locals(locals())
return self._call('GetRecurringPaymentsProfileDetails', **args)
|
Shortcut for the GetRecurringPaymentsProfile method.
This returns details for a recurring payment plan. The ``profileid`` is
a value included in the response retrieved by the function
``create_recurring_payments_profile``. The profile details include the
data provided when the profile was created as well as default values
for ignored fields and some pertinent stastics.
e.g.:
response = create_recurring_payments_profile(**profile_info)
profileid = response.PROFILEID
details = get_recurring_payments_profile(profileid)
The response from PayPal is somewhat self-explanatory, but for a
description of each field, visit the following URI:
https://www.x.com/docs/DOC-1194
|
train
|
https://github.com/gtaylor/paypal-python/blob/aa7a987ea9e9b7f37bcd8a8b54a440aad6c871b1/paypal/interface.py#L468-L487
|
[
"def _sanitize_locals(self, data):\n \"\"\"\n Remove the 'self' key in locals()\n It's more explicit to do it in one function\n \"\"\"\n if 'self' in data:\n data = data.copy()\n del data['self']\n\n return data\n",
"def _call(self, method, **kwargs):\n \"\"\"\n Wrapper method for executing all API commands over HTTP. This method is\n further used to implement wrapper methods listed here:\n\n https://www.x.com/docs/DOC-1374\n\n ``method`` must be a supported NVP method listed at the above address.\n ``kwargs`` the actual call parameters\n \"\"\"\n post_params = self._get_call_params(method, **kwargs)\n payload = post_params['data']\n api_endpoint = post_params['url']\n\n # This shows all of the key/val pairs we're sending to PayPal.\n if logger.isEnabledFor(logging.DEBUG):\n logger.debug('PayPal NVP Query Key/Vals:\\n%s' % pformat(payload))\n\n http_response = requests.post(**post_params)\n response = PayPalResponse(http_response.text, self.config)\n logger.debug('PayPal NVP API Endpoint: %s' % api_endpoint)\n\n if not response.success:\n raise PayPalAPIResponseError(response)\n\n return response\n"
] |
class PayPalInterface(object):
__credentials = ['USER', 'PWD', 'SIGNATURE', 'SUBJECT']
"""
The end developers will do 95% of their work through this class. API
queries, configuration, etc, all go through here. See the __init__ method
for config related details.
"""
def __init__(self, config=None, **kwargs):
"""
Constructor, which passes all config directives to the config class
via kwargs. For example:
paypal = PayPalInterface(API_USERNAME='somevalue')
Optionally, you may pass a 'config' kwarg to provide your own
PayPalConfig object.
"""
if config:
# User provided their own PayPalConfig object.
self.config = config
else:
# Take the kwargs and stuff them in a new PayPalConfig object.
self.config = PayPalConfig(**kwargs)
def _encode_utf8(self, **kwargs):
"""
UTF8 encodes all of the NVP values.
"""
if is_py3:
# This is only valid for Python 2. In Python 3, unicode is
# everywhere (yay).
return kwargs
unencoded_pairs = kwargs
for i in unencoded_pairs.keys():
#noinspection PyUnresolvedReferences
if isinstance(unencoded_pairs[i], types.UnicodeType):
unencoded_pairs[i] = unencoded_pairs[i].encode('utf-8')
return unencoded_pairs
def _check_required(self, requires, **kwargs):
"""
Checks kwargs for the values specified in 'requires', which is a tuple
of strings. These strings are the NVP names of the required values.
"""
for req in requires:
# PayPal api is never mixed-case.
if req.lower() not in kwargs and req.upper() not in kwargs:
raise PayPalError('missing required : %s' % req)
def _sanitize_locals(self, data):
"""
Remove the 'self' key in locals()
It's more explicit to do it in one function
"""
if 'self' in data:
data = data.copy()
del data['self']
return data
def _call(self, method, **kwargs):
"""
Wrapper method for executing all API commands over HTTP. This method is
further used to implement wrapper methods listed here:
https://www.x.com/docs/DOC-1374
``method`` must be a supported NVP method listed at the above address.
``kwargs`` the actual call parameters
"""
post_params = self._get_call_params(method, **kwargs)
payload = post_params['data']
api_endpoint = post_params['url']
# This shows all of the key/val pairs we're sending to PayPal.
if logger.isEnabledFor(logging.DEBUG):
logger.debug('PayPal NVP Query Key/Vals:\n%s' % pformat(payload))
http_response = requests.post(**post_params)
response = PayPalResponse(http_response.text, self.config)
logger.debug('PayPal NVP API Endpoint: %s' % api_endpoint)
if not response.success:
raise PayPalAPIResponseError(response)
return response
def _get_call_params(self, method, **kwargs):
"""
Returns the prepared call parameters. Mind, these will be keyword
arguments to ``requests.post``.
``method`` the NVP method
``kwargs`` the actual call parameters
"""
payload = {'METHOD': method,
'VERSION': self.config.API_VERSION}
certificate = None
if self.config.API_AUTHENTICATION_MODE == "3TOKEN":
payload['USER'] = self.config.API_USERNAME
payload['PWD'] = self.config.API_PASSWORD
payload['SIGNATURE'] = self.config.API_SIGNATURE
elif self.config.API_AUTHENTICATION_MODE == "CERTIFICATE":
payload['USER'] = self.config.API_USERNAME
payload['PWD'] = self.config.API_PASSWORD
certificate = (self.config.API_CERTIFICATE_FILENAME,
self.config.API_KEY_FILENAME)
elif self.config.API_AUTHENTICATION_MODE == "UNIPAY":
payload['SUBJECT'] = self.config.UNIPAY_SUBJECT
none_configs = [config for config, value in payload.items()
if value is None]
if none_configs:
raise PayPalConfigError(
"Config(s) %s cannot be None. Please, check this "
"interface's config." % none_configs)
# all keys in the payload must be uppercase
for key, value in kwargs.items():
payload[key.upper()] = value
return {'data': payload,
'cert': certificate,
'url': self.config.API_ENDPOINT,
'timeout': self.config.HTTP_TIMEOUT,
'verify': self.config.API_CA_CERTS}
def address_verify(self, email, street, zip):
"""Shortcut for the AddressVerify method.
``email``::
Email address of a PayPal member to verify.
Maximum string length: 255 single-byte characters
Input mask: ?@?.??
``street``::
First line of the billing or shipping postal address to verify.
To pass verification, the value of Street must match the first three
single-byte characters of a postal address on file for the PayPal member.
Maximum string length: 35 single-byte characters.
Alphanumeric plus - , . ‘ # \
Whitespace and case of input value are ignored.
``zip``::
Postal code to verify.
To pass verification, the value of Zip mustmatch the first five
single-byte characters of the postal code of the verified postal
address for the verified PayPal member.
Maximumstring length: 16 single-byte characters.
Whitespace and case of input value are ignored.
"""
args = self._sanitize_locals(locals())
return self._call('AddressVerify', **args)
def create_recurring_payments_profile(self, **kwargs):
"""Shortcut for the CreateRecurringPaymentsProfile method.
Currently, this method only supports the Direct Payment flavor.
It requires standard credit card information and a few additional
parameters related to the billing. e.g.:
profile_info = {
# Credit card information
'creditcardtype': 'Visa',
'acct': '4812177017895760',
'expdate': '102015',
'cvv2': '123',
'firstname': 'John',
'lastname': 'Doe',
'street': '1313 Mockingbird Lane',
'city': 'Beverly Hills',
'state': 'CA',
'zip': '90110',
'countrycode': 'US',
'currencycode': 'USD',
# Recurring payment information
'profilestartdate': '2010-10-25T0:0:0',
'billingperiod': 'Month',
'billingfrequency': '6',
'amt': '10.00',
'desc': '6 months of our product.'
}
response = create_recurring_payments_profile(**profile_info)
The above NVPs compose the bare-minimum request for creating a
profile. For the complete list of parameters, visit this URI:
https://www.x.com/docs/DOC-1168
"""
return self._call('CreateRecurringPaymentsProfile', **kwargs)
def do_authorization(self, transactionid, amt):
"""Shortcut for the DoAuthorization method.
Use the TRANSACTIONID from DoExpressCheckoutPayment for the
``transactionid``. The latest version of the API does not support the
creation of an Order from `DoDirectPayment`.
The `amt` should be the same as passed to `DoExpressCheckoutPayment`.
Flow for a payment involving a `DoAuthorization` call::
1. One or many calls to `SetExpressCheckout` with pertinent order
details, returns `TOKEN`
1. `DoExpressCheckoutPayment` with `TOKEN`, `PAYMENTACTION` set to
Order, `AMT` set to the amount of the transaction, returns
`TRANSACTIONID`
1. `DoAuthorization` with `TRANSACTIONID` and `AMT` set to the
amount of the transaction.
1. `DoCapture` with the `AUTHORIZATIONID` (the `TRANSACTIONID`
returned by `DoAuthorization`)
"""
args = self._sanitize_locals(locals())
return self._call('DoAuthorization', **args)
def do_capture(self, authorizationid, amt, completetype='Complete',
**kwargs):
"""Shortcut for the DoCapture method.
Use the TRANSACTIONID from DoAuthorization, DoDirectPayment or
DoExpressCheckoutPayment for the ``authorizationid``.
The `amt` should be the same as the authorized transaction.
"""
kwargs.update(self._sanitize_locals(locals()))
return self._call('DoCapture', **kwargs)
def do_direct_payment(self, paymentaction="Sale", **kwargs):
"""Shortcut for the DoDirectPayment method.
``paymentaction`` could be 'Authorization' or 'Sale'
To issue a Sale immediately::
charge = {
'amt': '10.00',
'creditcardtype': 'Visa',
'acct': '4812177017895760',
'expdate': '012010',
'cvv2': '962',
'firstname': 'John',
'lastname': 'Doe',
'street': '1 Main St',
'city': 'San Jose',
'state': 'CA',
'zip': '95131',
'countrycode': 'US',
'currencycode': 'USD',
}
direct_payment("Sale", **charge)
Or, since "Sale" is the default:
direct_payment(**charge)
To issue an Authorization, simply pass "Authorization" instead
of "Sale".
You may also explicitly set ``paymentaction`` as a keyword argument:
...
direct_payment(paymentaction="Sale", **charge)
"""
kwargs.update(self._sanitize_locals(locals()))
return self._call('DoDirectPayment', **kwargs)
def do_void(self, **kwargs):
"""Shortcut for the DoVoid method.
Use the TRANSACTIONID from DoAuthorization, DoDirectPayment or
DoExpressCheckoutPayment for the ``AUTHORIZATIONID``.
Required Kwargs
---------------
* AUTHORIZATIONID
"""
return self._call('DoVoid', **kwargs)
def get_express_checkout_details(self, **kwargs):
"""Shortcut for the GetExpressCheckoutDetails method.
Required Kwargs
---------------
* TOKEN
"""
return self._call('GetExpressCheckoutDetails', **kwargs)
def get_transaction_details(self, **kwargs):
"""Shortcut for the GetTransactionDetails method.
Use the TRANSACTIONID from DoAuthorization, DoDirectPayment or
DoExpressCheckoutPayment for the ``transactionid``.
Required Kwargs
---------------
* TRANSACTIONID
"""
return self._call('GetTransactionDetails', **kwargs)
def transaction_search(self, **kwargs):
"""Shortcut for the TransactionSearch method.
Returns a PayPalResponseList object, which merges the L_ syntax list
to a list of dictionaries with properly named keys.
Note that the API will limit returned transactions to 100.
Required Kwargs
---------------
* STARTDATE
Optional Kwargs
---------------
STATUS = one of ['Pending','Processing','Success','Denied','Reversed']
"""
plain = self._call('TransactionSearch', **kwargs)
return PayPalResponseList(plain.raw, self.config)
def set_express_checkout(self, **kwargs):
"""Start an Express checkout.
You'll want to use this in conjunction with
:meth:`generate_express_checkout_redirect_url` to create a payment,
then figure out where to redirect the user to for them to
authorize the payment on PayPal's website.
Required Kwargs
---------------
* PAYMENTREQUEST_0_AMT
* PAYMENTREQUEST_0_PAYMENTACTION
* RETURNURL
* CANCELURL
"""
return self._call('SetExpressCheckout', **kwargs)
def refund_transaction(self, transactionid=None, payerid=None, **kwargs):
"""Shortcut for RefundTransaction method.
Note new API supports passing a PayerID instead of a transaction id,
exactly one must be provided.
Optional:
INVOICEID
REFUNDTYPE
AMT
CURRENCYCODE
NOTE
RETRYUNTIL
REFUNDSOURCE
MERCHANTSTOREDETAILS
REFUNDADVICE
REFUNDITEMDETAILS
MSGSUBID
MERCHANSTOREDETAILS has two fields:
STOREID
TERMINALID
"""
# This line seems like a complete waste of time... kwargs should not
# be populated
if (transactionid is None) and (payerid is None):
raise PayPalError(
'RefundTransaction requires either a transactionid or '
'a payerid')
if (transactionid is not None) and (payerid is not None):
raise PayPalError(
'RefundTransaction requires only one of transactionid %s '
'and payerid %s' % (transactionid, payerid))
if transactionid is not None:
kwargs['TRANSACTIONID'] = transactionid
else:
kwargs['PAYERID'] = payerid
return self._call('RefundTransaction', **kwargs)
def do_express_checkout_payment(self, **kwargs):
"""Finishes an Express checkout.
TOKEN is the token that was returned earlier by
:meth:`set_express_checkout`. This identifies the transaction.
Required
--------
* TOKEN
* PAYMENTACTION
* PAYERID
* AMT
"""
return self._call('DoExpressCheckoutPayment', **kwargs)
def generate_express_checkout_redirect_url(self, token, useraction=None):
"""Returns the URL to redirect the user to for the Express checkout.
Express Checkouts must be verified by the customer by redirecting them
to the PayPal website. Use the token returned in the response from
:meth:`set_express_checkout` with this function to figure out where
to redirect the user to.
The button text on the PayPal page can be controlled via `useraction`.
The documented possible values are `commit` and `continue`. However,
any other value will only result in a warning.
:param str token: The unique token identifying this transaction.
:param str useraction: Control the button text on the PayPal page.
:rtype: str
:returns: The URL to redirect the user to for approval.
"""
url_vars = (self.config.PAYPAL_URL_BASE, token)
url = "%s?cmd=_express-checkout&token=%s" % url_vars
if useraction:
if not useraction.lower() in ('commit', 'continue'):
warnings.warn('useraction=%s is not documented' % useraction,
RuntimeWarning)
url += '&useraction=%s' % useraction
return url
def generate_cart_upload_redirect_url(self, **kwargs):
"""https://www.sandbox.paypal.com/webscr
?cmd=_cart
&upload=1
"""
required_vals = ('business', 'item_name_1', 'amount_1', 'quantity_1')
self._check_required(required_vals, **kwargs)
url = "%s?cmd=_cart&upload=1" % self.config.PAYPAL_URL_BASE
additional = self._encode_utf8(**kwargs)
additional = urlencode(additional)
return url + "&" + additional
def manage_recurring_payments_profile_status(self, profileid, action,
note=None):
"""Shortcut to the ManageRecurringPaymentsProfileStatus method.
``profileid`` is the same profile id used for getting profile details.
``action`` should be either 'Cancel', 'Suspend', or 'Reactivate'.
``note`` is optional and is visible to the user. It contains the
reason for the change in status.
"""
args = self._sanitize_locals(locals())
if not note:
del args['note']
return self._call('ManageRecurringPaymentsProfileStatus', **args)
def update_recurring_payments_profile(self, profileid, **kwargs):
"""Shortcut to the UpdateRecurringPaymentsProfile method.
``profileid`` is the same profile id used for getting profile details.
The keyed arguments are data in the payment profile which you wish to
change. The profileid does not change. Anything else will take the new
value. Most of, though not all of, the fields available are shared
with creating a profile, but for the complete list of parameters, you
can visit the following URI:
https://www.x.com/docs/DOC-1212
"""
kwargs.update(self._sanitize_locals(locals()))
return self._call('UpdateRecurringPaymentsProfile', **kwargs)
def bm_create_button(self, **kwargs):
"""Shortcut to the BMCreateButton method.
See the docs for details on arguments:
https://cms.paypal.com/mx/cgi-bin/?cmd=_render-content&content_ID=developer/e_howto_api_nvp_BMCreateButton
The L_BUTTONVARn fields are especially important, so make sure to
read those and act accordingly. See unit tests for some examples.
"""
kwargs.update(self._sanitize_locals(locals()))
return self._call('BMCreateButton', **kwargs)
|
gtaylor/paypal-python
|
paypal/interface.py
|
PayPalInterface.manage_recurring_payments_profile_status
|
python
|
def manage_recurring_payments_profile_status(self, profileid, action,
note=None):
args = self._sanitize_locals(locals())
if not note:
del args['note']
return self._call('ManageRecurringPaymentsProfileStatus', **args)
|
Shortcut to the ManageRecurringPaymentsProfileStatus method.
``profileid`` is the same profile id used for getting profile details.
``action`` should be either 'Cancel', 'Suspend', or 'Reactivate'.
``note`` is optional and is visible to the user. It contains the
reason for the change in status.
|
train
|
https://github.com/gtaylor/paypal-python/blob/aa7a987ea9e9b7f37bcd8a8b54a440aad6c871b1/paypal/interface.py#L489-L501
|
[
"def _sanitize_locals(self, data):\n \"\"\"\n Remove the 'self' key in locals()\n It's more explicit to do it in one function\n \"\"\"\n if 'self' in data:\n data = data.copy()\n del data['self']\n\n return data\n",
"def _call(self, method, **kwargs):\n \"\"\"\n Wrapper method for executing all API commands over HTTP. This method is\n further used to implement wrapper methods listed here:\n\n https://www.x.com/docs/DOC-1374\n\n ``method`` must be a supported NVP method listed at the above address.\n ``kwargs`` the actual call parameters\n \"\"\"\n post_params = self._get_call_params(method, **kwargs)\n payload = post_params['data']\n api_endpoint = post_params['url']\n\n # This shows all of the key/val pairs we're sending to PayPal.\n if logger.isEnabledFor(logging.DEBUG):\n logger.debug('PayPal NVP Query Key/Vals:\\n%s' % pformat(payload))\n\n http_response = requests.post(**post_params)\n response = PayPalResponse(http_response.text, self.config)\n logger.debug('PayPal NVP API Endpoint: %s' % api_endpoint)\n\n if not response.success:\n raise PayPalAPIResponseError(response)\n\n return response\n"
] |
class PayPalInterface(object):
__credentials = ['USER', 'PWD', 'SIGNATURE', 'SUBJECT']
"""
The end developers will do 95% of their work through this class. API
queries, configuration, etc, all go through here. See the __init__ method
for config related details.
"""
def __init__(self, config=None, **kwargs):
"""
Constructor, which passes all config directives to the config class
via kwargs. For example:
paypal = PayPalInterface(API_USERNAME='somevalue')
Optionally, you may pass a 'config' kwarg to provide your own
PayPalConfig object.
"""
if config:
# User provided their own PayPalConfig object.
self.config = config
else:
# Take the kwargs and stuff them in a new PayPalConfig object.
self.config = PayPalConfig(**kwargs)
def _encode_utf8(self, **kwargs):
"""
UTF8 encodes all of the NVP values.
"""
if is_py3:
# This is only valid for Python 2. In Python 3, unicode is
# everywhere (yay).
return kwargs
unencoded_pairs = kwargs
for i in unencoded_pairs.keys():
#noinspection PyUnresolvedReferences
if isinstance(unencoded_pairs[i], types.UnicodeType):
unencoded_pairs[i] = unencoded_pairs[i].encode('utf-8')
return unencoded_pairs
def _check_required(self, requires, **kwargs):
"""
Checks kwargs for the values specified in 'requires', which is a tuple
of strings. These strings are the NVP names of the required values.
"""
for req in requires:
# PayPal api is never mixed-case.
if req.lower() not in kwargs and req.upper() not in kwargs:
raise PayPalError('missing required : %s' % req)
def _sanitize_locals(self, data):
"""
Remove the 'self' key in locals()
It's more explicit to do it in one function
"""
if 'self' in data:
data = data.copy()
del data['self']
return data
def _call(self, method, **kwargs):
"""
Wrapper method for executing all API commands over HTTP. This method is
further used to implement wrapper methods listed here:
https://www.x.com/docs/DOC-1374
``method`` must be a supported NVP method listed at the above address.
``kwargs`` the actual call parameters
"""
post_params = self._get_call_params(method, **kwargs)
payload = post_params['data']
api_endpoint = post_params['url']
# This shows all of the key/val pairs we're sending to PayPal.
if logger.isEnabledFor(logging.DEBUG):
logger.debug('PayPal NVP Query Key/Vals:\n%s' % pformat(payload))
http_response = requests.post(**post_params)
response = PayPalResponse(http_response.text, self.config)
logger.debug('PayPal NVP API Endpoint: %s' % api_endpoint)
if not response.success:
raise PayPalAPIResponseError(response)
return response
def _get_call_params(self, method, **kwargs):
"""
Returns the prepared call parameters. Mind, these will be keyword
arguments to ``requests.post``.
``method`` the NVP method
``kwargs`` the actual call parameters
"""
payload = {'METHOD': method,
'VERSION': self.config.API_VERSION}
certificate = None
if self.config.API_AUTHENTICATION_MODE == "3TOKEN":
payload['USER'] = self.config.API_USERNAME
payload['PWD'] = self.config.API_PASSWORD
payload['SIGNATURE'] = self.config.API_SIGNATURE
elif self.config.API_AUTHENTICATION_MODE == "CERTIFICATE":
payload['USER'] = self.config.API_USERNAME
payload['PWD'] = self.config.API_PASSWORD
certificate = (self.config.API_CERTIFICATE_FILENAME,
self.config.API_KEY_FILENAME)
elif self.config.API_AUTHENTICATION_MODE == "UNIPAY":
payload['SUBJECT'] = self.config.UNIPAY_SUBJECT
none_configs = [config for config, value in payload.items()
if value is None]
if none_configs:
raise PayPalConfigError(
"Config(s) %s cannot be None. Please, check this "
"interface's config." % none_configs)
# all keys in the payload must be uppercase
for key, value in kwargs.items():
payload[key.upper()] = value
return {'data': payload,
'cert': certificate,
'url': self.config.API_ENDPOINT,
'timeout': self.config.HTTP_TIMEOUT,
'verify': self.config.API_CA_CERTS}
def address_verify(self, email, street, zip):
"""Shortcut for the AddressVerify method.
``email``::
Email address of a PayPal member to verify.
Maximum string length: 255 single-byte characters
Input mask: ?@?.??
``street``::
First line of the billing or shipping postal address to verify.
To pass verification, the value of Street must match the first three
single-byte characters of a postal address on file for the PayPal member.
Maximum string length: 35 single-byte characters.
Alphanumeric plus - , . ‘ # \
Whitespace and case of input value are ignored.
``zip``::
Postal code to verify.
To pass verification, the value of Zip mustmatch the first five
single-byte characters of the postal code of the verified postal
address for the verified PayPal member.
Maximumstring length: 16 single-byte characters.
Whitespace and case of input value are ignored.
"""
args = self._sanitize_locals(locals())
return self._call('AddressVerify', **args)
def create_recurring_payments_profile(self, **kwargs):
"""Shortcut for the CreateRecurringPaymentsProfile method.
Currently, this method only supports the Direct Payment flavor.
It requires standard credit card information and a few additional
parameters related to the billing. e.g.:
profile_info = {
# Credit card information
'creditcardtype': 'Visa',
'acct': '4812177017895760',
'expdate': '102015',
'cvv2': '123',
'firstname': 'John',
'lastname': 'Doe',
'street': '1313 Mockingbird Lane',
'city': 'Beverly Hills',
'state': 'CA',
'zip': '90110',
'countrycode': 'US',
'currencycode': 'USD',
# Recurring payment information
'profilestartdate': '2010-10-25T0:0:0',
'billingperiod': 'Month',
'billingfrequency': '6',
'amt': '10.00',
'desc': '6 months of our product.'
}
response = create_recurring_payments_profile(**profile_info)
The above NVPs compose the bare-minimum request for creating a
profile. For the complete list of parameters, visit this URI:
https://www.x.com/docs/DOC-1168
"""
return self._call('CreateRecurringPaymentsProfile', **kwargs)
def do_authorization(self, transactionid, amt):
"""Shortcut for the DoAuthorization method.
Use the TRANSACTIONID from DoExpressCheckoutPayment for the
``transactionid``. The latest version of the API does not support the
creation of an Order from `DoDirectPayment`.
The `amt` should be the same as passed to `DoExpressCheckoutPayment`.
Flow for a payment involving a `DoAuthorization` call::
1. One or many calls to `SetExpressCheckout` with pertinent order
details, returns `TOKEN`
1. `DoExpressCheckoutPayment` with `TOKEN`, `PAYMENTACTION` set to
Order, `AMT` set to the amount of the transaction, returns
`TRANSACTIONID`
1. `DoAuthorization` with `TRANSACTIONID` and `AMT` set to the
amount of the transaction.
1. `DoCapture` with the `AUTHORIZATIONID` (the `TRANSACTIONID`
returned by `DoAuthorization`)
"""
args = self._sanitize_locals(locals())
return self._call('DoAuthorization', **args)
def do_capture(self, authorizationid, amt, completetype='Complete',
**kwargs):
"""Shortcut for the DoCapture method.
Use the TRANSACTIONID from DoAuthorization, DoDirectPayment or
DoExpressCheckoutPayment for the ``authorizationid``.
The `amt` should be the same as the authorized transaction.
"""
kwargs.update(self._sanitize_locals(locals()))
return self._call('DoCapture', **kwargs)
def do_direct_payment(self, paymentaction="Sale", **kwargs):
"""Shortcut for the DoDirectPayment method.
``paymentaction`` could be 'Authorization' or 'Sale'
To issue a Sale immediately::
charge = {
'amt': '10.00',
'creditcardtype': 'Visa',
'acct': '4812177017895760',
'expdate': '012010',
'cvv2': '962',
'firstname': 'John',
'lastname': 'Doe',
'street': '1 Main St',
'city': 'San Jose',
'state': 'CA',
'zip': '95131',
'countrycode': 'US',
'currencycode': 'USD',
}
direct_payment("Sale", **charge)
Or, since "Sale" is the default:
direct_payment(**charge)
To issue an Authorization, simply pass "Authorization" instead
of "Sale".
You may also explicitly set ``paymentaction`` as a keyword argument:
...
direct_payment(paymentaction="Sale", **charge)
"""
kwargs.update(self._sanitize_locals(locals()))
return self._call('DoDirectPayment', **kwargs)
def do_void(self, **kwargs):
"""Shortcut for the DoVoid method.
Use the TRANSACTIONID from DoAuthorization, DoDirectPayment or
DoExpressCheckoutPayment for the ``AUTHORIZATIONID``.
Required Kwargs
---------------
* AUTHORIZATIONID
"""
return self._call('DoVoid', **kwargs)
def get_express_checkout_details(self, **kwargs):
"""Shortcut for the GetExpressCheckoutDetails method.
Required Kwargs
---------------
* TOKEN
"""
return self._call('GetExpressCheckoutDetails', **kwargs)
def get_transaction_details(self, **kwargs):
"""Shortcut for the GetTransactionDetails method.
Use the TRANSACTIONID from DoAuthorization, DoDirectPayment or
DoExpressCheckoutPayment for the ``transactionid``.
Required Kwargs
---------------
* TRANSACTIONID
"""
return self._call('GetTransactionDetails', **kwargs)
def transaction_search(self, **kwargs):
"""Shortcut for the TransactionSearch method.
Returns a PayPalResponseList object, which merges the L_ syntax list
to a list of dictionaries with properly named keys.
Note that the API will limit returned transactions to 100.
Required Kwargs
---------------
* STARTDATE
Optional Kwargs
---------------
STATUS = one of ['Pending','Processing','Success','Denied','Reversed']
"""
plain = self._call('TransactionSearch', **kwargs)
return PayPalResponseList(plain.raw, self.config)
def set_express_checkout(self, **kwargs):
"""Start an Express checkout.
You'll want to use this in conjunction with
:meth:`generate_express_checkout_redirect_url` to create a payment,
then figure out where to redirect the user to for them to
authorize the payment on PayPal's website.
Required Kwargs
---------------
* PAYMENTREQUEST_0_AMT
* PAYMENTREQUEST_0_PAYMENTACTION
* RETURNURL
* CANCELURL
"""
return self._call('SetExpressCheckout', **kwargs)
def refund_transaction(self, transactionid=None, payerid=None, **kwargs):
"""Shortcut for RefundTransaction method.
Note new API supports passing a PayerID instead of a transaction id,
exactly one must be provided.
Optional:
INVOICEID
REFUNDTYPE
AMT
CURRENCYCODE
NOTE
RETRYUNTIL
REFUNDSOURCE
MERCHANTSTOREDETAILS
REFUNDADVICE
REFUNDITEMDETAILS
MSGSUBID
MERCHANSTOREDETAILS has two fields:
STOREID
TERMINALID
"""
# This line seems like a complete waste of time... kwargs should not
# be populated
if (transactionid is None) and (payerid is None):
raise PayPalError(
'RefundTransaction requires either a transactionid or '
'a payerid')
if (transactionid is not None) and (payerid is not None):
raise PayPalError(
'RefundTransaction requires only one of transactionid %s '
'and payerid %s' % (transactionid, payerid))
if transactionid is not None:
kwargs['TRANSACTIONID'] = transactionid
else:
kwargs['PAYERID'] = payerid
return self._call('RefundTransaction', **kwargs)
def do_express_checkout_payment(self, **kwargs):
"""Finishes an Express checkout.
TOKEN is the token that was returned earlier by
:meth:`set_express_checkout`. This identifies the transaction.
Required
--------
* TOKEN
* PAYMENTACTION
* PAYERID
* AMT
"""
return self._call('DoExpressCheckoutPayment', **kwargs)
def generate_express_checkout_redirect_url(self, token, useraction=None):
"""Returns the URL to redirect the user to for the Express checkout.
Express Checkouts must be verified by the customer by redirecting them
to the PayPal website. Use the token returned in the response from
:meth:`set_express_checkout` with this function to figure out where
to redirect the user to.
The button text on the PayPal page can be controlled via `useraction`.
The documented possible values are `commit` and `continue`. However,
any other value will only result in a warning.
:param str token: The unique token identifying this transaction.
:param str useraction: Control the button text on the PayPal page.
:rtype: str
:returns: The URL to redirect the user to for approval.
"""
url_vars = (self.config.PAYPAL_URL_BASE, token)
url = "%s?cmd=_express-checkout&token=%s" % url_vars
if useraction:
if not useraction.lower() in ('commit', 'continue'):
warnings.warn('useraction=%s is not documented' % useraction,
RuntimeWarning)
url += '&useraction=%s' % useraction
return url
def generate_cart_upload_redirect_url(self, **kwargs):
"""https://www.sandbox.paypal.com/webscr
?cmd=_cart
&upload=1
"""
required_vals = ('business', 'item_name_1', 'amount_1', 'quantity_1')
self._check_required(required_vals, **kwargs)
url = "%s?cmd=_cart&upload=1" % self.config.PAYPAL_URL_BASE
additional = self._encode_utf8(**kwargs)
additional = urlencode(additional)
return url + "&" + additional
def get_recurring_payments_profile_details(self, profileid):
"""Shortcut for the GetRecurringPaymentsProfile method.
This returns details for a recurring payment plan. The ``profileid`` is
a value included in the response retrieved by the function
``create_recurring_payments_profile``. The profile details include the
data provided when the profile was created as well as default values
for ignored fields and some pertinent stastics.
e.g.:
response = create_recurring_payments_profile(**profile_info)
profileid = response.PROFILEID
details = get_recurring_payments_profile(profileid)
The response from PayPal is somewhat self-explanatory, but for a
description of each field, visit the following URI:
https://www.x.com/docs/DOC-1194
"""
args = self._sanitize_locals(locals())
return self._call('GetRecurringPaymentsProfileDetails', **args)
def update_recurring_payments_profile(self, profileid, **kwargs):
"""Shortcut to the UpdateRecurringPaymentsProfile method.
``profileid`` is the same profile id used for getting profile details.
The keyed arguments are data in the payment profile which you wish to
change. The profileid does not change. Anything else will take the new
value. Most of, though not all of, the fields available are shared
with creating a profile, but for the complete list of parameters, you
can visit the following URI:
https://www.x.com/docs/DOC-1212
"""
kwargs.update(self._sanitize_locals(locals()))
return self._call('UpdateRecurringPaymentsProfile', **kwargs)
def bm_create_button(self, **kwargs):
"""Shortcut to the BMCreateButton method.
See the docs for details on arguments:
https://cms.paypal.com/mx/cgi-bin/?cmd=_render-content&content_ID=developer/e_howto_api_nvp_BMCreateButton
The L_BUTTONVARn fields are especially important, so make sure to
read those and act accordingly. See unit tests for some examples.
"""
kwargs.update(self._sanitize_locals(locals()))
return self._call('BMCreateButton', **kwargs)
|
gtaylor/paypal-python
|
paypal/interface.py
|
PayPalInterface.update_recurring_payments_profile
|
python
|
def update_recurring_payments_profile(self, profileid, **kwargs):
kwargs.update(self._sanitize_locals(locals()))
return self._call('UpdateRecurringPaymentsProfile', **kwargs)
|
Shortcut to the UpdateRecurringPaymentsProfile method.
``profileid`` is the same profile id used for getting profile details.
The keyed arguments are data in the payment profile which you wish to
change. The profileid does not change. Anything else will take the new
value. Most of, though not all of, the fields available are shared
with creating a profile, but for the complete list of parameters, you
can visit the following URI:
https://www.x.com/docs/DOC-1212
|
train
|
https://github.com/gtaylor/paypal-python/blob/aa7a987ea9e9b7f37bcd8a8b54a440aad6c871b1/paypal/interface.py#L503-L516
|
[
"def _sanitize_locals(self, data):\n \"\"\"\n Remove the 'self' key in locals()\n It's more explicit to do it in one function\n \"\"\"\n if 'self' in data:\n data = data.copy()\n del data['self']\n\n return data\n",
"def _call(self, method, **kwargs):\n \"\"\"\n Wrapper method for executing all API commands over HTTP. This method is\n further used to implement wrapper methods listed here:\n\n https://www.x.com/docs/DOC-1374\n\n ``method`` must be a supported NVP method listed at the above address.\n ``kwargs`` the actual call parameters\n \"\"\"\n post_params = self._get_call_params(method, **kwargs)\n payload = post_params['data']\n api_endpoint = post_params['url']\n\n # This shows all of the key/val pairs we're sending to PayPal.\n if logger.isEnabledFor(logging.DEBUG):\n logger.debug('PayPal NVP Query Key/Vals:\\n%s' % pformat(payload))\n\n http_response = requests.post(**post_params)\n response = PayPalResponse(http_response.text, self.config)\n logger.debug('PayPal NVP API Endpoint: %s' % api_endpoint)\n\n if not response.success:\n raise PayPalAPIResponseError(response)\n\n return response\n"
] |
class PayPalInterface(object):
__credentials = ['USER', 'PWD', 'SIGNATURE', 'SUBJECT']
"""
The end developers will do 95% of their work through this class. API
queries, configuration, etc, all go through here. See the __init__ method
for config related details.
"""
def __init__(self, config=None, **kwargs):
"""
Constructor, which passes all config directives to the config class
via kwargs. For example:
paypal = PayPalInterface(API_USERNAME='somevalue')
Optionally, you may pass a 'config' kwarg to provide your own
PayPalConfig object.
"""
if config:
# User provided their own PayPalConfig object.
self.config = config
else:
# Take the kwargs and stuff them in a new PayPalConfig object.
self.config = PayPalConfig(**kwargs)
def _encode_utf8(self, **kwargs):
"""
UTF8 encodes all of the NVP values.
"""
if is_py3:
# This is only valid for Python 2. In Python 3, unicode is
# everywhere (yay).
return kwargs
unencoded_pairs = kwargs
for i in unencoded_pairs.keys():
#noinspection PyUnresolvedReferences
if isinstance(unencoded_pairs[i], types.UnicodeType):
unencoded_pairs[i] = unencoded_pairs[i].encode('utf-8')
return unencoded_pairs
def _check_required(self, requires, **kwargs):
"""
Checks kwargs for the values specified in 'requires', which is a tuple
of strings. These strings are the NVP names of the required values.
"""
for req in requires:
# PayPal api is never mixed-case.
if req.lower() not in kwargs and req.upper() not in kwargs:
raise PayPalError('missing required : %s' % req)
def _sanitize_locals(self, data):
"""
Remove the 'self' key in locals()
It's more explicit to do it in one function
"""
if 'self' in data:
data = data.copy()
del data['self']
return data
def _call(self, method, **kwargs):
"""
Wrapper method for executing all API commands over HTTP. This method is
further used to implement wrapper methods listed here:
https://www.x.com/docs/DOC-1374
``method`` must be a supported NVP method listed at the above address.
``kwargs`` the actual call parameters
"""
post_params = self._get_call_params(method, **kwargs)
payload = post_params['data']
api_endpoint = post_params['url']
# This shows all of the key/val pairs we're sending to PayPal.
if logger.isEnabledFor(logging.DEBUG):
logger.debug('PayPal NVP Query Key/Vals:\n%s' % pformat(payload))
http_response = requests.post(**post_params)
response = PayPalResponse(http_response.text, self.config)
logger.debug('PayPal NVP API Endpoint: %s' % api_endpoint)
if not response.success:
raise PayPalAPIResponseError(response)
return response
def _get_call_params(self, method, **kwargs):
"""
Returns the prepared call parameters. Mind, these will be keyword
arguments to ``requests.post``.
``method`` the NVP method
``kwargs`` the actual call parameters
"""
payload = {'METHOD': method,
'VERSION': self.config.API_VERSION}
certificate = None
if self.config.API_AUTHENTICATION_MODE == "3TOKEN":
payload['USER'] = self.config.API_USERNAME
payload['PWD'] = self.config.API_PASSWORD
payload['SIGNATURE'] = self.config.API_SIGNATURE
elif self.config.API_AUTHENTICATION_MODE == "CERTIFICATE":
payload['USER'] = self.config.API_USERNAME
payload['PWD'] = self.config.API_PASSWORD
certificate = (self.config.API_CERTIFICATE_FILENAME,
self.config.API_KEY_FILENAME)
elif self.config.API_AUTHENTICATION_MODE == "UNIPAY":
payload['SUBJECT'] = self.config.UNIPAY_SUBJECT
none_configs = [config for config, value in payload.items()
if value is None]
if none_configs:
raise PayPalConfigError(
"Config(s) %s cannot be None. Please, check this "
"interface's config." % none_configs)
# all keys in the payload must be uppercase
for key, value in kwargs.items():
payload[key.upper()] = value
return {'data': payload,
'cert': certificate,
'url': self.config.API_ENDPOINT,
'timeout': self.config.HTTP_TIMEOUT,
'verify': self.config.API_CA_CERTS}
def address_verify(self, email, street, zip):
"""Shortcut for the AddressVerify method.
``email``::
Email address of a PayPal member to verify.
Maximum string length: 255 single-byte characters
Input mask: ?@?.??
``street``::
First line of the billing or shipping postal address to verify.
To pass verification, the value of Street must match the first three
single-byte characters of a postal address on file for the PayPal member.
Maximum string length: 35 single-byte characters.
Alphanumeric plus - , . ‘ # \
Whitespace and case of input value are ignored.
``zip``::
Postal code to verify.
To pass verification, the value of Zip mustmatch the first five
single-byte characters of the postal code of the verified postal
address for the verified PayPal member.
Maximumstring length: 16 single-byte characters.
Whitespace and case of input value are ignored.
"""
args = self._sanitize_locals(locals())
return self._call('AddressVerify', **args)
def create_recurring_payments_profile(self, **kwargs):
"""Shortcut for the CreateRecurringPaymentsProfile method.
Currently, this method only supports the Direct Payment flavor.
It requires standard credit card information and a few additional
parameters related to the billing. e.g.:
profile_info = {
# Credit card information
'creditcardtype': 'Visa',
'acct': '4812177017895760',
'expdate': '102015',
'cvv2': '123',
'firstname': 'John',
'lastname': 'Doe',
'street': '1313 Mockingbird Lane',
'city': 'Beverly Hills',
'state': 'CA',
'zip': '90110',
'countrycode': 'US',
'currencycode': 'USD',
# Recurring payment information
'profilestartdate': '2010-10-25T0:0:0',
'billingperiod': 'Month',
'billingfrequency': '6',
'amt': '10.00',
'desc': '6 months of our product.'
}
response = create_recurring_payments_profile(**profile_info)
The above NVPs compose the bare-minimum request for creating a
profile. For the complete list of parameters, visit this URI:
https://www.x.com/docs/DOC-1168
"""
return self._call('CreateRecurringPaymentsProfile', **kwargs)
def do_authorization(self, transactionid, amt):
"""Shortcut for the DoAuthorization method.
Use the TRANSACTIONID from DoExpressCheckoutPayment for the
``transactionid``. The latest version of the API does not support the
creation of an Order from `DoDirectPayment`.
The `amt` should be the same as passed to `DoExpressCheckoutPayment`.
Flow for a payment involving a `DoAuthorization` call::
1. One or many calls to `SetExpressCheckout` with pertinent order
details, returns `TOKEN`
1. `DoExpressCheckoutPayment` with `TOKEN`, `PAYMENTACTION` set to
Order, `AMT` set to the amount of the transaction, returns
`TRANSACTIONID`
1. `DoAuthorization` with `TRANSACTIONID` and `AMT` set to the
amount of the transaction.
1. `DoCapture` with the `AUTHORIZATIONID` (the `TRANSACTIONID`
returned by `DoAuthorization`)
"""
args = self._sanitize_locals(locals())
return self._call('DoAuthorization', **args)
def do_capture(self, authorizationid, amt, completetype='Complete',
**kwargs):
"""Shortcut for the DoCapture method.
Use the TRANSACTIONID from DoAuthorization, DoDirectPayment or
DoExpressCheckoutPayment for the ``authorizationid``.
The `amt` should be the same as the authorized transaction.
"""
kwargs.update(self._sanitize_locals(locals()))
return self._call('DoCapture', **kwargs)
def do_direct_payment(self, paymentaction="Sale", **kwargs):
"""Shortcut for the DoDirectPayment method.
``paymentaction`` could be 'Authorization' or 'Sale'
To issue a Sale immediately::
charge = {
'amt': '10.00',
'creditcardtype': 'Visa',
'acct': '4812177017895760',
'expdate': '012010',
'cvv2': '962',
'firstname': 'John',
'lastname': 'Doe',
'street': '1 Main St',
'city': 'San Jose',
'state': 'CA',
'zip': '95131',
'countrycode': 'US',
'currencycode': 'USD',
}
direct_payment("Sale", **charge)
Or, since "Sale" is the default:
direct_payment(**charge)
To issue an Authorization, simply pass "Authorization" instead
of "Sale".
You may also explicitly set ``paymentaction`` as a keyword argument:
...
direct_payment(paymentaction="Sale", **charge)
"""
kwargs.update(self._sanitize_locals(locals()))
return self._call('DoDirectPayment', **kwargs)
def do_void(self, **kwargs):
"""Shortcut for the DoVoid method.
Use the TRANSACTIONID from DoAuthorization, DoDirectPayment or
DoExpressCheckoutPayment for the ``AUTHORIZATIONID``.
Required Kwargs
---------------
* AUTHORIZATIONID
"""
return self._call('DoVoid', **kwargs)
def get_express_checkout_details(self, **kwargs):
"""Shortcut for the GetExpressCheckoutDetails method.
Required Kwargs
---------------
* TOKEN
"""
return self._call('GetExpressCheckoutDetails', **kwargs)
def get_transaction_details(self, **kwargs):
"""Shortcut for the GetTransactionDetails method.
Use the TRANSACTIONID from DoAuthorization, DoDirectPayment or
DoExpressCheckoutPayment for the ``transactionid``.
Required Kwargs
---------------
* TRANSACTIONID
"""
return self._call('GetTransactionDetails', **kwargs)
def transaction_search(self, **kwargs):
"""Shortcut for the TransactionSearch method.
Returns a PayPalResponseList object, which merges the L_ syntax list
to a list of dictionaries with properly named keys.
Note that the API will limit returned transactions to 100.
Required Kwargs
---------------
* STARTDATE
Optional Kwargs
---------------
STATUS = one of ['Pending','Processing','Success','Denied','Reversed']
"""
plain = self._call('TransactionSearch', **kwargs)
return PayPalResponseList(plain.raw, self.config)
def set_express_checkout(self, **kwargs):
"""Start an Express checkout.
You'll want to use this in conjunction with
:meth:`generate_express_checkout_redirect_url` to create a payment,
then figure out where to redirect the user to for them to
authorize the payment on PayPal's website.
Required Kwargs
---------------
* PAYMENTREQUEST_0_AMT
* PAYMENTREQUEST_0_PAYMENTACTION
* RETURNURL
* CANCELURL
"""
return self._call('SetExpressCheckout', **kwargs)
def refund_transaction(self, transactionid=None, payerid=None, **kwargs):
"""Shortcut for RefundTransaction method.
Note new API supports passing a PayerID instead of a transaction id,
exactly one must be provided.
Optional:
INVOICEID
REFUNDTYPE
AMT
CURRENCYCODE
NOTE
RETRYUNTIL
REFUNDSOURCE
MERCHANTSTOREDETAILS
REFUNDADVICE
REFUNDITEMDETAILS
MSGSUBID
MERCHANSTOREDETAILS has two fields:
STOREID
TERMINALID
"""
# This line seems like a complete waste of time... kwargs should not
# be populated
if (transactionid is None) and (payerid is None):
raise PayPalError(
'RefundTransaction requires either a transactionid or '
'a payerid')
if (transactionid is not None) and (payerid is not None):
raise PayPalError(
'RefundTransaction requires only one of transactionid %s '
'and payerid %s' % (transactionid, payerid))
if transactionid is not None:
kwargs['TRANSACTIONID'] = transactionid
else:
kwargs['PAYERID'] = payerid
return self._call('RefundTransaction', **kwargs)
def do_express_checkout_payment(self, **kwargs):
"""Finishes an Express checkout.
TOKEN is the token that was returned earlier by
:meth:`set_express_checkout`. This identifies the transaction.
Required
--------
* TOKEN
* PAYMENTACTION
* PAYERID
* AMT
"""
return self._call('DoExpressCheckoutPayment', **kwargs)
def generate_express_checkout_redirect_url(self, token, useraction=None):
"""Returns the URL to redirect the user to for the Express checkout.
Express Checkouts must be verified by the customer by redirecting them
to the PayPal website. Use the token returned in the response from
:meth:`set_express_checkout` with this function to figure out where
to redirect the user to.
The button text on the PayPal page can be controlled via `useraction`.
The documented possible values are `commit` and `continue`. However,
any other value will only result in a warning.
:param str token: The unique token identifying this transaction.
:param str useraction: Control the button text on the PayPal page.
:rtype: str
:returns: The URL to redirect the user to for approval.
"""
url_vars = (self.config.PAYPAL_URL_BASE, token)
url = "%s?cmd=_express-checkout&token=%s" % url_vars
if useraction:
if not useraction.lower() in ('commit', 'continue'):
warnings.warn('useraction=%s is not documented' % useraction,
RuntimeWarning)
url += '&useraction=%s' % useraction
return url
def generate_cart_upload_redirect_url(self, **kwargs):
"""https://www.sandbox.paypal.com/webscr
?cmd=_cart
&upload=1
"""
required_vals = ('business', 'item_name_1', 'amount_1', 'quantity_1')
self._check_required(required_vals, **kwargs)
url = "%s?cmd=_cart&upload=1" % self.config.PAYPAL_URL_BASE
additional = self._encode_utf8(**kwargs)
additional = urlencode(additional)
return url + "&" + additional
def get_recurring_payments_profile_details(self, profileid):
"""Shortcut for the GetRecurringPaymentsProfile method.
This returns details for a recurring payment plan. The ``profileid`` is
a value included in the response retrieved by the function
``create_recurring_payments_profile``. The profile details include the
data provided when the profile was created as well as default values
for ignored fields and some pertinent stastics.
e.g.:
response = create_recurring_payments_profile(**profile_info)
profileid = response.PROFILEID
details = get_recurring_payments_profile(profileid)
The response from PayPal is somewhat self-explanatory, but for a
description of each field, visit the following URI:
https://www.x.com/docs/DOC-1194
"""
args = self._sanitize_locals(locals())
return self._call('GetRecurringPaymentsProfileDetails', **args)
def manage_recurring_payments_profile_status(self, profileid, action,
note=None):
"""Shortcut to the ManageRecurringPaymentsProfileStatus method.
``profileid`` is the same profile id used for getting profile details.
``action`` should be either 'Cancel', 'Suspend', or 'Reactivate'.
``note`` is optional and is visible to the user. It contains the
reason for the change in status.
"""
args = self._sanitize_locals(locals())
if not note:
del args['note']
return self._call('ManageRecurringPaymentsProfileStatus', **args)
def bm_create_button(self, **kwargs):
"""Shortcut to the BMCreateButton method.
See the docs for details on arguments:
https://cms.paypal.com/mx/cgi-bin/?cmd=_render-content&content_ID=developer/e_howto_api_nvp_BMCreateButton
The L_BUTTONVARn fields are especially important, so make sure to
read those and act accordingly. See unit tests for some examples.
"""
kwargs.update(self._sanitize_locals(locals()))
return self._call('BMCreateButton', **kwargs)
|
gtaylor/paypal-python
|
paypal/interface.py
|
PayPalInterface.bm_create_button
|
python
|
def bm_create_button(self, **kwargs):
kwargs.update(self._sanitize_locals(locals()))
return self._call('BMCreateButton', **kwargs)
|
Shortcut to the BMCreateButton method.
See the docs for details on arguments:
https://cms.paypal.com/mx/cgi-bin/?cmd=_render-content&content_ID=developer/e_howto_api_nvp_BMCreateButton
The L_BUTTONVARn fields are especially important, so make sure to
read those and act accordingly. See unit tests for some examples.
|
train
|
https://github.com/gtaylor/paypal-python/blob/aa7a987ea9e9b7f37bcd8a8b54a440aad6c871b1/paypal/interface.py#L518-L528
|
[
"def _sanitize_locals(self, data):\n \"\"\"\n Remove the 'self' key in locals()\n It's more explicit to do it in one function\n \"\"\"\n if 'self' in data:\n data = data.copy()\n del data['self']\n\n return data\n",
"def _call(self, method, **kwargs):\n \"\"\"\n Wrapper method for executing all API commands over HTTP. This method is\n further used to implement wrapper methods listed here:\n\n https://www.x.com/docs/DOC-1374\n\n ``method`` must be a supported NVP method listed at the above address.\n ``kwargs`` the actual call parameters\n \"\"\"\n post_params = self._get_call_params(method, **kwargs)\n payload = post_params['data']\n api_endpoint = post_params['url']\n\n # This shows all of the key/val pairs we're sending to PayPal.\n if logger.isEnabledFor(logging.DEBUG):\n logger.debug('PayPal NVP Query Key/Vals:\\n%s' % pformat(payload))\n\n http_response = requests.post(**post_params)\n response = PayPalResponse(http_response.text, self.config)\n logger.debug('PayPal NVP API Endpoint: %s' % api_endpoint)\n\n if not response.success:\n raise PayPalAPIResponseError(response)\n\n return response\n"
] |
class PayPalInterface(object):
__credentials = ['USER', 'PWD', 'SIGNATURE', 'SUBJECT']
"""
The end developers will do 95% of their work through this class. API
queries, configuration, etc, all go through here. See the __init__ method
for config related details.
"""
def __init__(self, config=None, **kwargs):
"""
Constructor, which passes all config directives to the config class
via kwargs. For example:
paypal = PayPalInterface(API_USERNAME='somevalue')
Optionally, you may pass a 'config' kwarg to provide your own
PayPalConfig object.
"""
if config:
# User provided their own PayPalConfig object.
self.config = config
else:
# Take the kwargs and stuff them in a new PayPalConfig object.
self.config = PayPalConfig(**kwargs)
def _encode_utf8(self, **kwargs):
"""
UTF8 encodes all of the NVP values.
"""
if is_py3:
# This is only valid for Python 2. In Python 3, unicode is
# everywhere (yay).
return kwargs
unencoded_pairs = kwargs
for i in unencoded_pairs.keys():
#noinspection PyUnresolvedReferences
if isinstance(unencoded_pairs[i], types.UnicodeType):
unencoded_pairs[i] = unencoded_pairs[i].encode('utf-8')
return unencoded_pairs
def _check_required(self, requires, **kwargs):
"""
Checks kwargs for the values specified in 'requires', which is a tuple
of strings. These strings are the NVP names of the required values.
"""
for req in requires:
# PayPal api is never mixed-case.
if req.lower() not in kwargs and req.upper() not in kwargs:
raise PayPalError('missing required : %s' % req)
def _sanitize_locals(self, data):
"""
Remove the 'self' key in locals()
It's more explicit to do it in one function
"""
if 'self' in data:
data = data.copy()
del data['self']
return data
def _call(self, method, **kwargs):
"""
Wrapper method for executing all API commands over HTTP. This method is
further used to implement wrapper methods listed here:
https://www.x.com/docs/DOC-1374
``method`` must be a supported NVP method listed at the above address.
``kwargs`` the actual call parameters
"""
post_params = self._get_call_params(method, **kwargs)
payload = post_params['data']
api_endpoint = post_params['url']
# This shows all of the key/val pairs we're sending to PayPal.
if logger.isEnabledFor(logging.DEBUG):
logger.debug('PayPal NVP Query Key/Vals:\n%s' % pformat(payload))
http_response = requests.post(**post_params)
response = PayPalResponse(http_response.text, self.config)
logger.debug('PayPal NVP API Endpoint: %s' % api_endpoint)
if not response.success:
raise PayPalAPIResponseError(response)
return response
def _get_call_params(self, method, **kwargs):
"""
Returns the prepared call parameters. Mind, these will be keyword
arguments to ``requests.post``.
``method`` the NVP method
``kwargs`` the actual call parameters
"""
payload = {'METHOD': method,
'VERSION': self.config.API_VERSION}
certificate = None
if self.config.API_AUTHENTICATION_MODE == "3TOKEN":
payload['USER'] = self.config.API_USERNAME
payload['PWD'] = self.config.API_PASSWORD
payload['SIGNATURE'] = self.config.API_SIGNATURE
elif self.config.API_AUTHENTICATION_MODE == "CERTIFICATE":
payload['USER'] = self.config.API_USERNAME
payload['PWD'] = self.config.API_PASSWORD
certificate = (self.config.API_CERTIFICATE_FILENAME,
self.config.API_KEY_FILENAME)
elif self.config.API_AUTHENTICATION_MODE == "UNIPAY":
payload['SUBJECT'] = self.config.UNIPAY_SUBJECT
none_configs = [config for config, value in payload.items()
if value is None]
if none_configs:
raise PayPalConfigError(
"Config(s) %s cannot be None. Please, check this "
"interface's config." % none_configs)
# all keys in the payload must be uppercase
for key, value in kwargs.items():
payload[key.upper()] = value
return {'data': payload,
'cert': certificate,
'url': self.config.API_ENDPOINT,
'timeout': self.config.HTTP_TIMEOUT,
'verify': self.config.API_CA_CERTS}
def address_verify(self, email, street, zip):
"""Shortcut for the AddressVerify method.
``email``::
Email address of a PayPal member to verify.
Maximum string length: 255 single-byte characters
Input mask: ?@?.??
``street``::
First line of the billing or shipping postal address to verify.
To pass verification, the value of Street must match the first three
single-byte characters of a postal address on file for the PayPal member.
Maximum string length: 35 single-byte characters.
Alphanumeric plus - , . ‘ # \
Whitespace and case of input value are ignored.
``zip``::
Postal code to verify.
To pass verification, the value of Zip mustmatch the first five
single-byte characters of the postal code of the verified postal
address for the verified PayPal member.
Maximumstring length: 16 single-byte characters.
Whitespace and case of input value are ignored.
"""
args = self._sanitize_locals(locals())
return self._call('AddressVerify', **args)
def create_recurring_payments_profile(self, **kwargs):
"""Shortcut for the CreateRecurringPaymentsProfile method.
Currently, this method only supports the Direct Payment flavor.
It requires standard credit card information and a few additional
parameters related to the billing. e.g.:
profile_info = {
# Credit card information
'creditcardtype': 'Visa',
'acct': '4812177017895760',
'expdate': '102015',
'cvv2': '123',
'firstname': 'John',
'lastname': 'Doe',
'street': '1313 Mockingbird Lane',
'city': 'Beverly Hills',
'state': 'CA',
'zip': '90110',
'countrycode': 'US',
'currencycode': 'USD',
# Recurring payment information
'profilestartdate': '2010-10-25T0:0:0',
'billingperiod': 'Month',
'billingfrequency': '6',
'amt': '10.00',
'desc': '6 months of our product.'
}
response = create_recurring_payments_profile(**profile_info)
The above NVPs compose the bare-minimum request for creating a
profile. For the complete list of parameters, visit this URI:
https://www.x.com/docs/DOC-1168
"""
return self._call('CreateRecurringPaymentsProfile', **kwargs)
def do_authorization(self, transactionid, amt):
"""Shortcut for the DoAuthorization method.
Use the TRANSACTIONID from DoExpressCheckoutPayment for the
``transactionid``. The latest version of the API does not support the
creation of an Order from `DoDirectPayment`.
The `amt` should be the same as passed to `DoExpressCheckoutPayment`.
Flow for a payment involving a `DoAuthorization` call::
1. One or many calls to `SetExpressCheckout` with pertinent order
details, returns `TOKEN`
1. `DoExpressCheckoutPayment` with `TOKEN`, `PAYMENTACTION` set to
Order, `AMT` set to the amount of the transaction, returns
`TRANSACTIONID`
1. `DoAuthorization` with `TRANSACTIONID` and `AMT` set to the
amount of the transaction.
1. `DoCapture` with the `AUTHORIZATIONID` (the `TRANSACTIONID`
returned by `DoAuthorization`)
"""
args = self._sanitize_locals(locals())
return self._call('DoAuthorization', **args)
def do_capture(self, authorizationid, amt, completetype='Complete',
**kwargs):
"""Shortcut for the DoCapture method.
Use the TRANSACTIONID from DoAuthorization, DoDirectPayment or
DoExpressCheckoutPayment for the ``authorizationid``.
The `amt` should be the same as the authorized transaction.
"""
kwargs.update(self._sanitize_locals(locals()))
return self._call('DoCapture', **kwargs)
def do_direct_payment(self, paymentaction="Sale", **kwargs):
"""Shortcut for the DoDirectPayment method.
``paymentaction`` could be 'Authorization' or 'Sale'
To issue a Sale immediately::
charge = {
'amt': '10.00',
'creditcardtype': 'Visa',
'acct': '4812177017895760',
'expdate': '012010',
'cvv2': '962',
'firstname': 'John',
'lastname': 'Doe',
'street': '1 Main St',
'city': 'San Jose',
'state': 'CA',
'zip': '95131',
'countrycode': 'US',
'currencycode': 'USD',
}
direct_payment("Sale", **charge)
Or, since "Sale" is the default:
direct_payment(**charge)
To issue an Authorization, simply pass "Authorization" instead
of "Sale".
You may also explicitly set ``paymentaction`` as a keyword argument:
...
direct_payment(paymentaction="Sale", **charge)
"""
kwargs.update(self._sanitize_locals(locals()))
return self._call('DoDirectPayment', **kwargs)
def do_void(self, **kwargs):
"""Shortcut for the DoVoid method.
Use the TRANSACTIONID from DoAuthorization, DoDirectPayment or
DoExpressCheckoutPayment for the ``AUTHORIZATIONID``.
Required Kwargs
---------------
* AUTHORIZATIONID
"""
return self._call('DoVoid', **kwargs)
def get_express_checkout_details(self, **kwargs):
"""Shortcut for the GetExpressCheckoutDetails method.
Required Kwargs
---------------
* TOKEN
"""
return self._call('GetExpressCheckoutDetails', **kwargs)
def get_transaction_details(self, **kwargs):
"""Shortcut for the GetTransactionDetails method.
Use the TRANSACTIONID from DoAuthorization, DoDirectPayment or
DoExpressCheckoutPayment for the ``transactionid``.
Required Kwargs
---------------
* TRANSACTIONID
"""
return self._call('GetTransactionDetails', **kwargs)
def transaction_search(self, **kwargs):
"""Shortcut for the TransactionSearch method.
Returns a PayPalResponseList object, which merges the L_ syntax list
to a list of dictionaries with properly named keys.
Note that the API will limit returned transactions to 100.
Required Kwargs
---------------
* STARTDATE
Optional Kwargs
---------------
STATUS = one of ['Pending','Processing','Success','Denied','Reversed']
"""
plain = self._call('TransactionSearch', **kwargs)
return PayPalResponseList(plain.raw, self.config)
def set_express_checkout(self, **kwargs):
"""Start an Express checkout.
You'll want to use this in conjunction with
:meth:`generate_express_checkout_redirect_url` to create a payment,
then figure out where to redirect the user to for them to
authorize the payment on PayPal's website.
Required Kwargs
---------------
* PAYMENTREQUEST_0_AMT
* PAYMENTREQUEST_0_PAYMENTACTION
* RETURNURL
* CANCELURL
"""
return self._call('SetExpressCheckout', **kwargs)
def refund_transaction(self, transactionid=None, payerid=None, **kwargs):
"""Shortcut for RefundTransaction method.
Note new API supports passing a PayerID instead of a transaction id,
exactly one must be provided.
Optional:
INVOICEID
REFUNDTYPE
AMT
CURRENCYCODE
NOTE
RETRYUNTIL
REFUNDSOURCE
MERCHANTSTOREDETAILS
REFUNDADVICE
REFUNDITEMDETAILS
MSGSUBID
MERCHANSTOREDETAILS has two fields:
STOREID
TERMINALID
"""
# This line seems like a complete waste of time... kwargs should not
# be populated
if (transactionid is None) and (payerid is None):
raise PayPalError(
'RefundTransaction requires either a transactionid or '
'a payerid')
if (transactionid is not None) and (payerid is not None):
raise PayPalError(
'RefundTransaction requires only one of transactionid %s '
'and payerid %s' % (transactionid, payerid))
if transactionid is not None:
kwargs['TRANSACTIONID'] = transactionid
else:
kwargs['PAYERID'] = payerid
return self._call('RefundTransaction', **kwargs)
def do_express_checkout_payment(self, **kwargs):
"""Finishes an Express checkout.
TOKEN is the token that was returned earlier by
:meth:`set_express_checkout`. This identifies the transaction.
Required
--------
* TOKEN
* PAYMENTACTION
* PAYERID
* AMT
"""
return self._call('DoExpressCheckoutPayment', **kwargs)
def generate_express_checkout_redirect_url(self, token, useraction=None):
"""Returns the URL to redirect the user to for the Express checkout.
Express Checkouts must be verified by the customer by redirecting them
to the PayPal website. Use the token returned in the response from
:meth:`set_express_checkout` with this function to figure out where
to redirect the user to.
The button text on the PayPal page can be controlled via `useraction`.
The documented possible values are `commit` and `continue`. However,
any other value will only result in a warning.
:param str token: The unique token identifying this transaction.
:param str useraction: Control the button text on the PayPal page.
:rtype: str
:returns: The URL to redirect the user to for approval.
"""
url_vars = (self.config.PAYPAL_URL_BASE, token)
url = "%s?cmd=_express-checkout&token=%s" % url_vars
if useraction:
if not useraction.lower() in ('commit', 'continue'):
warnings.warn('useraction=%s is not documented' % useraction,
RuntimeWarning)
url += '&useraction=%s' % useraction
return url
def generate_cart_upload_redirect_url(self, **kwargs):
"""https://www.sandbox.paypal.com/webscr
?cmd=_cart
&upload=1
"""
required_vals = ('business', 'item_name_1', 'amount_1', 'quantity_1')
self._check_required(required_vals, **kwargs)
url = "%s?cmd=_cart&upload=1" % self.config.PAYPAL_URL_BASE
additional = self._encode_utf8(**kwargs)
additional = urlencode(additional)
return url + "&" + additional
def get_recurring_payments_profile_details(self, profileid):
"""Shortcut for the GetRecurringPaymentsProfile method.
This returns details for a recurring payment plan. The ``profileid`` is
a value included in the response retrieved by the function
``create_recurring_payments_profile``. The profile details include the
data provided when the profile was created as well as default values
for ignored fields and some pertinent stastics.
e.g.:
response = create_recurring_payments_profile(**profile_info)
profileid = response.PROFILEID
details = get_recurring_payments_profile(profileid)
The response from PayPal is somewhat self-explanatory, but for a
description of each field, visit the following URI:
https://www.x.com/docs/DOC-1194
"""
args = self._sanitize_locals(locals())
return self._call('GetRecurringPaymentsProfileDetails', **args)
def manage_recurring_payments_profile_status(self, profileid, action,
note=None):
"""Shortcut to the ManageRecurringPaymentsProfileStatus method.
``profileid`` is the same profile id used for getting profile details.
``action`` should be either 'Cancel', 'Suspend', or 'Reactivate'.
``note`` is optional and is visible to the user. It contains the
reason for the change in status.
"""
args = self._sanitize_locals(locals())
if not note:
del args['note']
return self._call('ManageRecurringPaymentsProfileStatus', **args)
def update_recurring_payments_profile(self, profileid, **kwargs):
"""Shortcut to the UpdateRecurringPaymentsProfile method.
``profileid`` is the same profile id used for getting profile details.
The keyed arguments are data in the payment profile which you wish to
change. The profileid does not change. Anything else will take the new
value. Most of, though not all of, the fields available are shared
with creating a profile, but for the complete list of parameters, you
can visit the following URI:
https://www.x.com/docs/DOC-1212
"""
kwargs.update(self._sanitize_locals(locals()))
return self._call('UpdateRecurringPaymentsProfile', **kwargs)
|
gtaylor/paypal-python
|
paypal/response.py
|
PayPalResponse.success
|
python
|
def success(self):
return self.ack.upper() in (self.config.ACK_SUCCESS,
self.config.ACK_SUCCESS_WITH_WARNING)
|
Checks for the presence of errors in the response. Returns ``True`` if
all is well, ``False`` otherwise.
:rtype: bool
:returns ``True`` if PayPal says our query was successful.
|
train
|
https://github.com/gtaylor/paypal-python/blob/aa7a987ea9e9b7f37bcd8a8b54a440aad6c871b1/paypal/response.py#L109-L118
| null |
class PayPalResponse(object):
"""
Parse and prepare the reponse from PayPal's API. Acts as somewhat of a
glorified dictionary for API responses.
NOTE: Don't access self.raw directly. Just do something like
PayPalResponse.someattr, going through PayPalResponse.__getattr__().
"""
def __init__(self, query_string, config):
"""
query_string is the response from the API, in NVP format. This is
parseable by urlparse.parse_qs(), which sticks it into the
:attr:`raw` dict for retrieval by the user.
:param str query_string: The raw response from the API server.
:param PayPalConfig config: The config object that was used to send
the query that caused this response.
"""
# A dict of NVP values. Don't access this directly, use
# PayPalResponse.attribname instead. See self.__getattr__().
self.raw = parse_qs(query_string)
self.config = config
logger.debug("PayPal NVP API Response:\n%s" % self.__str__())
def __str__(self):
"""
Returns a string representation of the PayPalResponse object, in
'pretty-print' format.
:rtype: str
:returns: A 'pretty' string representation of the response dict.
"""
return pformat(self.raw)
def __getattr__(self, key):
"""
Handles the retrieval of attributes that don't exist on the object
already. This is used to get API response values. Handles some
convenience stuff like discarding case and checking the cgi/urlparsed
response value dict (self.raw).
:param str key: The response attribute to get a value for.
:rtype: str
:returns: The requested value from the API server's response.
"""
# PayPal response names are always uppercase.
key = key.upper()
try:
value = self.raw[key]
if len(value) == 1:
# For some reason, PayPal returns lists for all of the values.
# I'm not positive as to why, so we'll just take the first
# of each one. Hasn't failed us so far.
return value[0]
return value
except KeyError:
# The requested value wasn't returned in the response.
raise AttributeError(self)
def __getitem__(self, key):
"""
Another (dict-style) means of accessing response data.
:param str key: The response key to get a value for.
:rtype: str
:returns: The requested value from the API server's response.
"""
# PayPal response names are always uppercase.
key = key.upper()
value = self.raw[key]
if len(value) == 1:
# For some reason, PayPal returns lists for all of the values.
# I'm not positive as to why, so we'll just take the first
# of each one. Hasn't failed us so far.
return value[0]
return value
def items(self):
items_list = []
for key in self.raw.keys():
items_list.append((key, self.__getitem__(key)))
return items_list
def iteritems(self):
for key in self.raw.keys():
yield (key, self.__getitem__(key))
success = property(success)
|
gtaylor/paypal-python
|
paypal/countries.py
|
is_valid_country_abbrev
|
python
|
def is_valid_country_abbrev(abbrev, case_sensitive=False):
if case_sensitive:
country_code = abbrev
else:
country_code = abbrev.upper()
for code, full_name in COUNTRY_TUPLES:
if country_code == code:
return True
return False
|
Given a country code abbreviation, check to see if it matches the
country table.
abbrev: (str) Country code to evaluate.
case_sensitive: (bool) When True, enforce case sensitivity.
Returns True if valid, False if not.
|
train
|
https://github.com/gtaylor/paypal-python/blob/aa7a987ea9e9b7f37bcd8a8b54a440aad6c871b1/paypal/countries.py#L254-L273
| null |
"""
Country Code List: ISO 3166-1993 (E)
http://xml.coverpages.org/country3166.html
A tuple of tuples of country codes and their full names. There are a few helper
functions provided if you'd rather not use the dict directly. Examples provided
in the test_countries.py unit tests.
"""
COUNTRY_TUPLES = (
('US', 'United States of America'),
('CA', 'Canada'),
('AD', 'Andorra'),
('AE', 'United Arab Emirates'),
('AF', 'Afghanistan'),
('AG', 'Antigua & Barbuda'),
('AI', 'Anguilla'),
('AL', 'Albania'),
('AM', 'Armenia'),
('AN', 'Netherlands Antilles'),
('AO', 'Angola'),
('AQ', 'Antarctica'),
('AR', 'Argentina'),
('AS', 'American Samoa'),
('AT', 'Austria'),
('AU', 'Australia'),
('AW', 'Aruba'),
('AZ', 'Azerbaijan'),
('BA', 'Bosnia and Herzegovina'),
('BB', 'Barbados'),
('BD', 'Bangladesh'),
('BE', 'Belgium'),
('BF', 'Burkina Faso'),
('BG', 'Bulgaria'),
('BH', 'Bahrain'),
('BI', 'Burundi'),
('BJ', 'Benin'),
('BM', 'Bermuda'),
('BN', 'Brunei Darussalam'),
('BO', 'Bolivia'),
('BR', 'Brazil'),
('BS', 'Bahama'),
('BT', 'Bhutan'),
('BV', 'Bouvet Island'),
('BW', 'Botswana'),
('BY', 'Belarus'),
('BZ', 'Belize'),
('CC', 'Cocos (Keeling) Islands'),
('CF', 'Central African Republic'),
('CG', 'Congo'),
('CH', 'Switzerland'),
('CI', 'Ivory Coast'),
('CK', 'Cook Iislands'),
('CL', 'Chile'),
('CM', 'Cameroon'),
('CN', 'China'),
('CO', 'Colombia'),
('CR', 'Costa Rica'),
('CU', 'Cuba'),
('CV', 'Cape Verde'),
('CX', 'Christmas Island'),
('CY', 'Cyprus'),
('CZ', 'Czech Republic'),
('DE', 'Germany'),
('DJ', 'Djibouti'),
('DK', 'Denmark'),
('DM', 'Dominica'),
('DO', 'Dominican Republic'),
('DZ', 'Algeria'),
('EC', 'Ecuador'),
('EE', 'Estonia'),
('EG', 'Egypt'),
('EH', 'Western Sahara'),
('ER', 'Eritrea'),
('ES', 'Spain'),
('ET', 'Ethiopia'),
('FI', 'Finland'),
('FJ', 'Fiji'),
('FK', 'Falkland Islands (Malvinas)'),
('FM', 'Micronesia'),
('FO', 'Faroe Islands'),
('FR', 'France'),
('FX', 'France, Metropolitan'),
('GA', 'Gabon'),
('GB', 'United Kingdom (Great Britain)'),
('GD', 'Grenada'),
('GE', 'Georgia'),
('GF', 'French Guiana'),
('GH', 'Ghana'),
('GI', 'Gibraltar'),
('GL', 'Greenland'),
('GM', 'Gambia'),
('GN', 'Guinea'),
('GP', 'Guadeloupe'),
('GQ', 'Equatorial Guinea'),
('GR', 'Greece'),
('GS', 'South Georgia and the South Sandwich Islands'),
('GT', 'Guatemala'),
('GU', 'Guam'),
('GW', 'Guinea-Bissau'),
('GY', 'Guyana'),
('HK', 'Hong Kong'),
('HM', 'Heard & McDonald Islands'),
('HN', 'Honduras'),
('HR', 'Croatia'),
('HT', 'Haiti'),
('HU', 'Hungary'),
('ID', 'Indonesia'),
('IE', 'Ireland'),
('IL', 'Israel'),
('IN', 'India'),
('IO', 'British Indian Ocean Territory'),
('IQ', 'Iraq'),
('IR', 'Islamic Republic of Iran'),
('IS', 'Iceland'),
('IT', 'Italy'),
('JM', 'Jamaica'),
('JO', 'Jordan'),
('JP', 'Japan'),
('KE', 'Kenya'),
('KG', 'Kyrgyzstan'),
('KH', 'Cambodia'),
('KI', 'Kiribati'),
('KM', 'Comoros'),
('KN', 'St. Kitts and Nevis'),
('KP', 'Korea, Democratic People\'s Republic of'),
('KR', 'Korea, Republic of'),
('KW', 'Kuwait'),
('KY', 'Cayman Islands'),
('KZ', 'Kazakhstan'),
('LA', 'Lao People\'s Democratic Republic'),
('LB', 'Lebanon'),
('LC', 'Saint Lucia'),
('LI', 'Liechtenstein'),
('LK', 'Sri Lanka'),
('LR', 'Liberia'),
('LS', 'Lesotho'),
('LT', 'Lithuania'),
('LU', 'Luxembourg'),
('LV', 'Latvia'),
('LY', 'Libyan Arab Jamahiriya'),
('MA', 'Morocco'),
('MC', 'Monaco'),
('MD', 'Moldova, Republic of'),
('MG', 'Madagascar'),
('MH', 'Marshall Islands'),
('ML', 'Mali'),
('MN', 'Mongolia'),
('MM', 'Myanmar'),
('MO', 'Macau'),
('MP', 'Northern Mariana Islands'),
('MQ', 'Martinique'),
('MR', 'Mauritania'),
('MS', 'Monserrat'),
('MT', 'Malta'),
('MU', 'Mauritius'),
('MV', 'Maldives'),
('MW', 'Malawi'),
('MX', 'Mexico'),
('MY', 'Malaysia'),
('MZ', 'Mozambique'),
('NA', 'Namibia'),
('NC', 'New Caledonia'),
('NE', 'Niger'),
('NF', 'Norfolk Island'),
('NG', 'Nigeria'),
('NI', 'Nicaragua'),
('NL', 'Netherlands'),
('NO', 'Norway'),
('NP', 'Nepal'),
('NR', 'Nauru'),
('NU', 'Niue'),
('NZ', 'New Zealand'),
('OM', 'Oman'),
('PA', 'Panama'),
('PE', 'Peru'),
('PF', 'French Polynesia'),
('PG', 'Papua New Guinea'),
('PH', 'Philippines'),
('PK', 'Pakistan'),
('PL', 'Poland'),
('PM', 'St. Pierre & Miquelon'),
('PN', 'Pitcairn'),
('PR', 'Puerto Rico'),
('PT', 'Portugal'),
('PW', 'Palau'),
('PY', 'Paraguay'),
('QA', 'Qatar'),
('RE', 'Reunion'),
('RO', 'Romania'),
('RU', 'Russian Federation'),
('RW', 'Rwanda'),
('SA', 'Saudi Arabia'),
('SB', 'Solomon Islands'),
('SC', 'Seychelles'),
('SD', 'Sudan'),
('SE', 'Sweden'),
('SG', 'Singapore'),
('SH', 'St. Helena'),
('SI', 'Slovenia'),
('SJ', 'Svalbard & Jan Mayen Islands'),
('SK', 'Slovakia'),
('SL', 'Sierra Leone'),
('SM', 'San Marino'),
('SN', 'Senegal'),
('SO', 'Somalia'),
('SR', 'Suriname'),
('ST', 'Sao Tome & Principe'),
('SV', 'El Salvador'),
('SY', 'Syrian Arab Republic'),
('SZ', 'Swaziland'),
('TC', 'Turks & Caicos Islands'),
('TD', 'Chad'),
('TF', 'French Southern Territories'),
('TG', 'Togo'),
('TH', 'Thailand'),
('TJ', 'Tajikistan'),
('TK', 'Tokelau'),
('TM', 'Turkmenistan'),
('TN', 'Tunisia'),
('TO', 'Tonga'),
('TP', 'East Timor'),
('TR', 'Turkey'),
('TT', 'Trinidad & Tobago'),
('TV', 'Tuvalu'),
('TW', 'Taiwan, Province of China'),
('TZ', 'Tanzania, United Republic of'),
('UA', 'Ukraine'),
('UG', 'Uganda'),
('UM', 'United States Minor Outlying Islands'),
('UY', 'Uruguay'),
('UZ', 'Uzbekistan'),
('VA', 'Vatican City State (Holy See)'),
('VC', 'St. Vincent & the Grenadines'),
('VE', 'Venezuela'),
('VG', 'British Virgin Islands'),
('VI', 'United States Virgin Islands'),
('VN', 'Viet Nam'),
('VU', 'Vanuatu'),
('WF', 'Wallis & Futuna Islands'),
('WS', 'Samoa'),
('YE', 'Yemen'),
('YT', 'Mayotte'),
('YU', 'Yugoslavia'),
('ZA', 'South Africa'),
('ZM', 'Zambia'),
('ZR', 'Zaire'),
('ZW', 'Zimbabwe'),
('ZZ', 'Unknown or unspecified country'),
)
def get_name_from_abbrev(abbrev, case_sensitive=False):
"""
Given a country code abbreviation, get the full name from the table.
abbrev: (str) Country code to retrieve the full name of.
case_sensitive: (bool) When True, enforce case sensitivity.
"""
if case_sensitive:
country_code = abbrev
else:
country_code = abbrev.upper()
for code, full_name in COUNTRY_TUPLES:
if country_code == code:
return full_name
raise KeyError('No country with that country code.')
|
gtaylor/paypal-python
|
paypal/countries.py
|
get_name_from_abbrev
|
python
|
def get_name_from_abbrev(abbrev, case_sensitive=False):
if case_sensitive:
country_code = abbrev
else:
country_code = abbrev.upper()
for code, full_name in COUNTRY_TUPLES:
if country_code == code:
return full_name
raise KeyError('No country with that country code.')
|
Given a country code abbreviation, get the full name from the table.
abbrev: (str) Country code to retrieve the full name of.
case_sensitive: (bool) When True, enforce case sensitivity.
|
train
|
https://github.com/gtaylor/paypal-python/blob/aa7a987ea9e9b7f37bcd8a8b54a440aad6c871b1/paypal/countries.py#L276-L292
| null |
"""
Country Code List: ISO 3166-1993 (E)
http://xml.coverpages.org/country3166.html
A tuple of tuples of country codes and their full names. There are a few helper
functions provided if you'd rather not use the dict directly. Examples provided
in the test_countries.py unit tests.
"""
COUNTRY_TUPLES = (
('US', 'United States of America'),
('CA', 'Canada'),
('AD', 'Andorra'),
('AE', 'United Arab Emirates'),
('AF', 'Afghanistan'),
('AG', 'Antigua & Barbuda'),
('AI', 'Anguilla'),
('AL', 'Albania'),
('AM', 'Armenia'),
('AN', 'Netherlands Antilles'),
('AO', 'Angola'),
('AQ', 'Antarctica'),
('AR', 'Argentina'),
('AS', 'American Samoa'),
('AT', 'Austria'),
('AU', 'Australia'),
('AW', 'Aruba'),
('AZ', 'Azerbaijan'),
('BA', 'Bosnia and Herzegovina'),
('BB', 'Barbados'),
('BD', 'Bangladesh'),
('BE', 'Belgium'),
('BF', 'Burkina Faso'),
('BG', 'Bulgaria'),
('BH', 'Bahrain'),
('BI', 'Burundi'),
('BJ', 'Benin'),
('BM', 'Bermuda'),
('BN', 'Brunei Darussalam'),
('BO', 'Bolivia'),
('BR', 'Brazil'),
('BS', 'Bahama'),
('BT', 'Bhutan'),
('BV', 'Bouvet Island'),
('BW', 'Botswana'),
('BY', 'Belarus'),
('BZ', 'Belize'),
('CC', 'Cocos (Keeling) Islands'),
('CF', 'Central African Republic'),
('CG', 'Congo'),
('CH', 'Switzerland'),
('CI', 'Ivory Coast'),
('CK', 'Cook Iislands'),
('CL', 'Chile'),
('CM', 'Cameroon'),
('CN', 'China'),
('CO', 'Colombia'),
('CR', 'Costa Rica'),
('CU', 'Cuba'),
('CV', 'Cape Verde'),
('CX', 'Christmas Island'),
('CY', 'Cyprus'),
('CZ', 'Czech Republic'),
('DE', 'Germany'),
('DJ', 'Djibouti'),
('DK', 'Denmark'),
('DM', 'Dominica'),
('DO', 'Dominican Republic'),
('DZ', 'Algeria'),
('EC', 'Ecuador'),
('EE', 'Estonia'),
('EG', 'Egypt'),
('EH', 'Western Sahara'),
('ER', 'Eritrea'),
('ES', 'Spain'),
('ET', 'Ethiopia'),
('FI', 'Finland'),
('FJ', 'Fiji'),
('FK', 'Falkland Islands (Malvinas)'),
('FM', 'Micronesia'),
('FO', 'Faroe Islands'),
('FR', 'France'),
('FX', 'France, Metropolitan'),
('GA', 'Gabon'),
('GB', 'United Kingdom (Great Britain)'),
('GD', 'Grenada'),
('GE', 'Georgia'),
('GF', 'French Guiana'),
('GH', 'Ghana'),
('GI', 'Gibraltar'),
('GL', 'Greenland'),
('GM', 'Gambia'),
('GN', 'Guinea'),
('GP', 'Guadeloupe'),
('GQ', 'Equatorial Guinea'),
('GR', 'Greece'),
('GS', 'South Georgia and the South Sandwich Islands'),
('GT', 'Guatemala'),
('GU', 'Guam'),
('GW', 'Guinea-Bissau'),
('GY', 'Guyana'),
('HK', 'Hong Kong'),
('HM', 'Heard & McDonald Islands'),
('HN', 'Honduras'),
('HR', 'Croatia'),
('HT', 'Haiti'),
('HU', 'Hungary'),
('ID', 'Indonesia'),
('IE', 'Ireland'),
('IL', 'Israel'),
('IN', 'India'),
('IO', 'British Indian Ocean Territory'),
('IQ', 'Iraq'),
('IR', 'Islamic Republic of Iran'),
('IS', 'Iceland'),
('IT', 'Italy'),
('JM', 'Jamaica'),
('JO', 'Jordan'),
('JP', 'Japan'),
('KE', 'Kenya'),
('KG', 'Kyrgyzstan'),
('KH', 'Cambodia'),
('KI', 'Kiribati'),
('KM', 'Comoros'),
('KN', 'St. Kitts and Nevis'),
('KP', 'Korea, Democratic People\'s Republic of'),
('KR', 'Korea, Republic of'),
('KW', 'Kuwait'),
('KY', 'Cayman Islands'),
('KZ', 'Kazakhstan'),
('LA', 'Lao People\'s Democratic Republic'),
('LB', 'Lebanon'),
('LC', 'Saint Lucia'),
('LI', 'Liechtenstein'),
('LK', 'Sri Lanka'),
('LR', 'Liberia'),
('LS', 'Lesotho'),
('LT', 'Lithuania'),
('LU', 'Luxembourg'),
('LV', 'Latvia'),
('LY', 'Libyan Arab Jamahiriya'),
('MA', 'Morocco'),
('MC', 'Monaco'),
('MD', 'Moldova, Republic of'),
('MG', 'Madagascar'),
('MH', 'Marshall Islands'),
('ML', 'Mali'),
('MN', 'Mongolia'),
('MM', 'Myanmar'),
('MO', 'Macau'),
('MP', 'Northern Mariana Islands'),
('MQ', 'Martinique'),
('MR', 'Mauritania'),
('MS', 'Monserrat'),
('MT', 'Malta'),
('MU', 'Mauritius'),
('MV', 'Maldives'),
('MW', 'Malawi'),
('MX', 'Mexico'),
('MY', 'Malaysia'),
('MZ', 'Mozambique'),
('NA', 'Namibia'),
('NC', 'New Caledonia'),
('NE', 'Niger'),
('NF', 'Norfolk Island'),
('NG', 'Nigeria'),
('NI', 'Nicaragua'),
('NL', 'Netherlands'),
('NO', 'Norway'),
('NP', 'Nepal'),
('NR', 'Nauru'),
('NU', 'Niue'),
('NZ', 'New Zealand'),
('OM', 'Oman'),
('PA', 'Panama'),
('PE', 'Peru'),
('PF', 'French Polynesia'),
('PG', 'Papua New Guinea'),
('PH', 'Philippines'),
('PK', 'Pakistan'),
('PL', 'Poland'),
('PM', 'St. Pierre & Miquelon'),
('PN', 'Pitcairn'),
('PR', 'Puerto Rico'),
('PT', 'Portugal'),
('PW', 'Palau'),
('PY', 'Paraguay'),
('QA', 'Qatar'),
('RE', 'Reunion'),
('RO', 'Romania'),
('RU', 'Russian Federation'),
('RW', 'Rwanda'),
('SA', 'Saudi Arabia'),
('SB', 'Solomon Islands'),
('SC', 'Seychelles'),
('SD', 'Sudan'),
('SE', 'Sweden'),
('SG', 'Singapore'),
('SH', 'St. Helena'),
('SI', 'Slovenia'),
('SJ', 'Svalbard & Jan Mayen Islands'),
('SK', 'Slovakia'),
('SL', 'Sierra Leone'),
('SM', 'San Marino'),
('SN', 'Senegal'),
('SO', 'Somalia'),
('SR', 'Suriname'),
('ST', 'Sao Tome & Principe'),
('SV', 'El Salvador'),
('SY', 'Syrian Arab Republic'),
('SZ', 'Swaziland'),
('TC', 'Turks & Caicos Islands'),
('TD', 'Chad'),
('TF', 'French Southern Territories'),
('TG', 'Togo'),
('TH', 'Thailand'),
('TJ', 'Tajikistan'),
('TK', 'Tokelau'),
('TM', 'Turkmenistan'),
('TN', 'Tunisia'),
('TO', 'Tonga'),
('TP', 'East Timor'),
('TR', 'Turkey'),
('TT', 'Trinidad & Tobago'),
('TV', 'Tuvalu'),
('TW', 'Taiwan, Province of China'),
('TZ', 'Tanzania, United Republic of'),
('UA', 'Ukraine'),
('UG', 'Uganda'),
('UM', 'United States Minor Outlying Islands'),
('UY', 'Uruguay'),
('UZ', 'Uzbekistan'),
('VA', 'Vatican City State (Holy See)'),
('VC', 'St. Vincent & the Grenadines'),
('VE', 'Venezuela'),
('VG', 'British Virgin Islands'),
('VI', 'United States Virgin Islands'),
('VN', 'Viet Nam'),
('VU', 'Vanuatu'),
('WF', 'Wallis & Futuna Islands'),
('WS', 'Samoa'),
('YE', 'Yemen'),
('YT', 'Mayotte'),
('YU', 'Yugoslavia'),
('ZA', 'South Africa'),
('ZM', 'Zambia'),
('ZR', 'Zaire'),
('ZW', 'Zimbabwe'),
('ZZ', 'Unknown or unspecified country'),
)
def is_valid_country_abbrev(abbrev, case_sensitive=False):
"""
Given a country code abbreviation, check to see if it matches the
country table.
abbrev: (str) Country code to evaluate.
case_sensitive: (bool) When True, enforce case sensitivity.
Returns True if valid, False if not.
"""
if case_sensitive:
country_code = abbrev
else:
country_code = abbrev.upper()
for code, full_name in COUNTRY_TUPLES:
if country_code == code:
return True
return False
|
erijo/tellcore-py
|
tellcore/library.py
|
Library.tdSensor
|
python
|
def tdSensor(self):
protocol = create_string_buffer(20)
model = create_string_buffer(20)
sid = c_int()
datatypes = c_int()
self._lib.tdSensor(protocol, sizeof(protocol), model, sizeof(model),
byref(sid), byref(datatypes))
return {'protocol': self._to_str(protocol),
'model': self._to_str(model),
'id': sid.value, 'datatypes': datatypes.value}
|
Get the next sensor while iterating.
:return: a dict with the keys: protocol, model, id, datatypes.
|
train
|
https://github.com/erijo/tellcore-py/blob/7a1eb53e12ef039a2350933e502633df7560f6a8/tellcore/library.py#L409-L423
|
[
"def _to_str(self, char_p):\n return char_p.value.decode(Library.STRING_ENCODING)\n"
] |
class Library(object):
"""Wrapper around the Telldus Core C API.
With the exception of tdInit, tdClose and tdReleaseString, all functions in
the C API (see `Telldus Core documentation
<http://developer.telldus.com/doxygen/group__core.html>`_) can be
called. The parameters are the same as in the C API documentation. The
return value are mostly the same as for the C API, except for functions
with multiple out parameters.
In addition, this class:
* automatically frees memory for strings returned from the C API,
* converts errors returned from functions into
(:class:`TelldusError`) exceptions,
* transparently converts between Python strings and C style strings.
"""
STRING_ENCODING = 'utf-8'
DECODE_STRINGS = True
class c_string_p(c_char_p):
def __init__(self, param):
c_char_p.__init__(self, param.encode(Library.STRING_ENCODING))
@classmethod
def from_param(cls, param):
if type(param) is str:
return cls(param)
try:
if type(param) is unicode:
return cls(param)
except NameError:
pass # The unicode type does not exist in python 3
return c_char_p.from_param(param)
# Must be a separate class (i.e. not part of Library), to avoid circular
# references when saving the wrapper callback function in a class with a
# destructor, as the destructor is not called in that case.
class CallbackWrapper(object):
def __init__(self, dispatcher):
self._callbacks = {}
self._lock = threading.Lock()
self._dispatcher = dispatcher
def get_callback_ids(self):
with self._lock:
return list(self._callbacks.keys())
def register_callback(self, registrator, functype, callback):
wrapper = functype(self._callback)
with self._lock:
cid = registrator(wrapper, None)
self._callbacks[cid] = (wrapper, callback)
return cid
def unregister_callback(self, cid):
with self._lock:
del self._callbacks[cid]
def _callback(self, *in_args):
args = []
# Convert all char* parameters (i.e. bytes) to proper python
# strings
for arg in in_args:
if type(arg) is bytes:
args.append(arg.decode(Library.STRING_ENCODING))
else:
args.append(arg)
# Get the real callback and the dispatcher
with self._lock:
try:
# args[-2] is callback id
(wrapper, callback) = self._callbacks[args[-2]]
except KeyError:
return
dispatcher = self._dispatcher
# Dispatch the callback, dropping the last parameter which is the
# context and always None.
try:
dispatcher.on_callback(callback, *args[:-1])
except:
pass
_lib = None
_refcount = 0
_functions = {
'tdInit': [None, []],
'tdClose': [None, []],
'tdReleaseString': [None, [c_void_p]],
'tdGetErrorString': [c_char_p, [c_int]],
'tdRegisterDeviceEvent':
[c_int, [DEVICE_EVENT_FUNC, c_void_p]],
'tdRegisterDeviceChangeEvent':
[c_int, [DEVICE_CHANGE_EVENT_FUNC, c_void_p]],
'tdRegisterRawDeviceEvent':
[c_int, [RAW_DEVICE_EVENT_FUNC, c_void_p]],
'tdRegisterSensorEvent':
[c_int, [SENSOR_EVENT_FUNC, c_void_p]],
'tdRegisterControllerEvent':
[c_int, [CONTROLLER_EVENT_FUNC, c_void_p]],
'tdUnregisterCallback': [c_int, [c_int]],
'tdTurnOn': [c_int, [c_int]],
'tdTurnOff': [c_int, [c_int]],
'tdBell': [c_int, [c_int]],
'tdDim': [c_int, [c_int, c_ubyte]],
'tdExecute': [c_int, [c_int]],
'tdUp': [c_int, [c_int]],
'tdDown': [c_int, [c_int]],
'tdStop': [c_int, [c_int]],
'tdLearn': [c_int, [c_int]],
'tdMethods': [c_int, [c_int, c_int]],
'tdLastSentCommand': [c_int, [c_int, c_int]],
'tdLastSentValue': [c_char_p, [c_int]],
'tdGetNumberOfDevices': [c_int, []],
'tdGetDeviceId': [c_int, [c_int]],
'tdGetDeviceType': [c_int, [c_int]],
'tdGetName': [c_char_p, [c_int]],
'tdSetName': [c_bool, [c_int, c_string_p]],
'tdGetProtocol': [c_char_p, [c_int]],
'tdSetProtocol': [c_bool, [c_int, c_string_p]],
'tdGetModel': [c_char_p, [c_int]],
'tdSetModel': [c_bool, [c_int, c_string_p]],
'tdGetDeviceParameter': [c_char_p, [c_int, c_string_p, c_string_p]],
'tdSetDeviceParameter': [c_bool, [c_int, c_string_p, c_string_p]],
'tdAddDevice': [c_int, []],
'tdRemoveDevice': [c_bool, [c_int]],
'tdSendRawCommand': [c_int, [c_string_p, c_int]],
'tdConnectTellStickController': [None, [c_int, c_int, c_string_p]],
'tdDisconnectTellStickController': [None, [c_int, c_int, c_string_p]],
'tdSensor': [c_int, [c_char_p, c_int, c_char_p, c_int,
POINTER(c_int), POINTER(c_int)]],
'tdSensorValue': [c_int, [c_string_p, c_string_p, c_int, c_int,
c_char_p, c_int, POINTER(c_int)]],
'tdController': [c_int, [POINTER(c_int), POINTER(c_int),
c_char_p, c_int, POINTER(c_int)]],
'tdControllerValue': [c_int, [c_int, c_string_p, c_char_p, c_int]],
'tdSetControllerValue': [c_int, [c_int, c_string_p, c_string_p]],
'tdRemoveController': [c_int, [c_int]],
}
def _to_str(self, char_p):
return char_p.value.decode(Library.STRING_ENCODING)
def _setup_functions(self, lib):
def check_int_result(result, func, args):
if result < 0:
raise TelldusError(result)
return result
def check_bool_result(result, func, args):
if not result:
raise TelldusError(const.TELLSTICK_ERROR_DEVICE_NOT_FOUND)
return result
def free_string(result, func, args):
string = cast(result, c_char_p).value
if string is not None:
lib.tdReleaseString(result)
if Library.DECODE_STRINGS:
string = string.decode(Library.STRING_ENCODING)
return string
for name, signature in Library._functions.items():
try:
func = getattr(lib, name)
func.restype = signature[0]
func.argtypes = signature[1]
if func.restype == c_int:
func.errcheck = check_int_result
elif func.restype == c_bool:
func.errcheck = check_bool_result
elif func.restype == c_char_p:
func.restype = c_void_p
func.errcheck = free_string
except AttributeError:
# Older version of the lib don't have all the functions
pass
def __init__(self, name=None, callback_dispatcher=None):
"""Load and initialize the Telldus core library.
The underlaying library is only initialized the first time this object
is created. Subsequent instances uses the same underlaying library
instance.
:param str name: If None than the platform specific name of the
Telldus library is used, but it can be e.g. an absolute path.
:param callback_dispatcher: If callbacks are to be used, this parameter
must refer to an instance of a class inheriting from
:class:`BaseCallbackDispatcher`.
"""
super(Library, self).__init__()
if not Library._lib:
assert Library._refcount == 0
if name is None:
name = LIBRARY_NAME
lib = DllLoader.LoadLibrary(name)
self._setup_functions(lib)
lib.tdInit()
Library._lib = lib
Library._refcount += 1
if callback_dispatcher is not None:
self._callback_wrapper = Library.CallbackWrapper(
callback_dispatcher)
else:
self._callback_wrapper = None
def __del__(self):
"""Close and unload the Telldus core library.
Any callback set up is removed.
The underlaying library is only closed and unloaded if this is the last
instance sharing the same underlaying library instance.
"""
# Using self.__class__.* instead of Library.* here to avoid a
# strange problem where Library could, in some runs, be None.
# Happens if the LoadLibrary call fails
if self.__class__._lib is None:
assert self.__class__._refcount == 0
return
assert self.__class__._refcount >= 1
self.__class__._refcount -= 1
if self._callback_wrapper is not None:
for cid in self._callback_wrapper.get_callback_ids():
try:
self.tdUnregisterCallback(cid)
except:
pass
if self.__class__._refcount != 0:
return
# telldus-core before v2.1.2 (where tdController was added) does not
# handle re-initialization after tdClose has been called (see Telldus
# ticket 188).
if hasattr(self.__class__._lib, "tdController"):
self.__class__._lib.tdClose()
self.__class__._lib = None
def __getattr__(self, name):
if name == 'callback_dispatcher':
return self._callback_wrapper._dispatcher
if name in Library._functions:
return getattr(self._lib, name)
raise AttributeError(name)
def tdInit(self):
raise NotImplementedError('should not be called explicitly')
def tdClose(self):
raise NotImplementedError('should not be called explicitly')
def tdReleaseString(self, string):
raise NotImplementedError('should not be called explicitly')
def tdRegisterDeviceEvent(self, callback):
assert(self._callback_wrapper is not None)
return self._callback_wrapper.register_callback(
self._lib.tdRegisterDeviceEvent, DEVICE_EVENT_FUNC, callback)
def tdRegisterDeviceChangeEvent(self, callback):
assert(self._callback_wrapper is not None)
return self._callback_wrapper.register_callback(
self._lib.tdRegisterDeviceChangeEvent, DEVICE_CHANGE_EVENT_FUNC,
callback)
def tdRegisterRawDeviceEvent(self, callback):
assert(self._callback_wrapper is not None)
return self._callback_wrapper.register_callback(
self._lib.tdRegisterRawDeviceEvent, RAW_DEVICE_EVENT_FUNC,
callback)
def tdRegisterSensorEvent(self, callback):
assert(self._callback_wrapper is not None)
return self._callback_wrapper.register_callback(
self._lib.tdRegisterSensorEvent, SENSOR_EVENT_FUNC, callback)
def tdRegisterControllerEvent(self, callback):
assert(self._callback_wrapper is not None)
return self._callback_wrapper.register_callback(
self._lib.tdRegisterControllerEvent, CONTROLLER_EVENT_FUNC,
callback)
def tdUnregisterCallback(self, cid):
assert(self._callback_wrapper is not None)
self._callback_wrapper.unregister_callback(cid)
self._lib.tdUnregisterCallback(cid)
def tdSensorValue(self, protocol, model, sid, datatype):
"""Get the sensor value for a given sensor.
:return: a dict with the keys: value, timestamp.
"""
value = create_string_buffer(20)
timestamp = c_int()
self._lib.tdSensorValue(protocol, model, sid, datatype,
value, sizeof(value), byref(timestamp))
return {'value': self._to_str(value), 'timestamp': timestamp.value}
def tdController(self):
"""Get the next controller while iterating.
:return: a dict with the keys: id, type, name, available.
"""
cid = c_int()
ctype = c_int()
name = create_string_buffer(255)
available = c_int()
self._lib.tdController(byref(cid), byref(ctype), name, sizeof(name),
byref(available))
return {'id': cid.value, 'type': ctype.value,
'name': self._to_str(name), 'available': available.value}
def tdControllerValue(self, cid, name):
value = create_string_buffer(255)
self._lib.tdControllerValue(cid, name, value, sizeof(value))
return self._to_str(value)
|
erijo/tellcore-py
|
tellcore/library.py
|
Library.tdSensorValue
|
python
|
def tdSensorValue(self, protocol, model, sid, datatype):
value = create_string_buffer(20)
timestamp = c_int()
self._lib.tdSensorValue(protocol, model, sid, datatype,
value, sizeof(value), byref(timestamp))
return {'value': self._to_str(value), 'timestamp': timestamp.value}
|
Get the sensor value for a given sensor.
:return: a dict with the keys: value, timestamp.
|
train
|
https://github.com/erijo/tellcore-py/blob/7a1eb53e12ef039a2350933e502633df7560f6a8/tellcore/library.py#L425-L435
|
[
"def _to_str(self, char_p):\n return char_p.value.decode(Library.STRING_ENCODING)\n"
] |
class Library(object):
"""Wrapper around the Telldus Core C API.
With the exception of tdInit, tdClose and tdReleaseString, all functions in
the C API (see `Telldus Core documentation
<http://developer.telldus.com/doxygen/group__core.html>`_) can be
called. The parameters are the same as in the C API documentation. The
return value are mostly the same as for the C API, except for functions
with multiple out parameters.
In addition, this class:
* automatically frees memory for strings returned from the C API,
* converts errors returned from functions into
(:class:`TelldusError`) exceptions,
* transparently converts between Python strings and C style strings.
"""
STRING_ENCODING = 'utf-8'
DECODE_STRINGS = True
class c_string_p(c_char_p):
def __init__(self, param):
c_char_p.__init__(self, param.encode(Library.STRING_ENCODING))
@classmethod
def from_param(cls, param):
if type(param) is str:
return cls(param)
try:
if type(param) is unicode:
return cls(param)
except NameError:
pass # The unicode type does not exist in python 3
return c_char_p.from_param(param)
# Must be a separate class (i.e. not part of Library), to avoid circular
# references when saving the wrapper callback function in a class with a
# destructor, as the destructor is not called in that case.
class CallbackWrapper(object):
def __init__(self, dispatcher):
self._callbacks = {}
self._lock = threading.Lock()
self._dispatcher = dispatcher
def get_callback_ids(self):
with self._lock:
return list(self._callbacks.keys())
def register_callback(self, registrator, functype, callback):
wrapper = functype(self._callback)
with self._lock:
cid = registrator(wrapper, None)
self._callbacks[cid] = (wrapper, callback)
return cid
def unregister_callback(self, cid):
with self._lock:
del self._callbacks[cid]
def _callback(self, *in_args):
args = []
# Convert all char* parameters (i.e. bytes) to proper python
# strings
for arg in in_args:
if type(arg) is bytes:
args.append(arg.decode(Library.STRING_ENCODING))
else:
args.append(arg)
# Get the real callback and the dispatcher
with self._lock:
try:
# args[-2] is callback id
(wrapper, callback) = self._callbacks[args[-2]]
except KeyError:
return
dispatcher = self._dispatcher
# Dispatch the callback, dropping the last parameter which is the
# context and always None.
try:
dispatcher.on_callback(callback, *args[:-1])
except:
pass
_lib = None
_refcount = 0
_functions = {
'tdInit': [None, []],
'tdClose': [None, []],
'tdReleaseString': [None, [c_void_p]],
'tdGetErrorString': [c_char_p, [c_int]],
'tdRegisterDeviceEvent':
[c_int, [DEVICE_EVENT_FUNC, c_void_p]],
'tdRegisterDeviceChangeEvent':
[c_int, [DEVICE_CHANGE_EVENT_FUNC, c_void_p]],
'tdRegisterRawDeviceEvent':
[c_int, [RAW_DEVICE_EVENT_FUNC, c_void_p]],
'tdRegisterSensorEvent':
[c_int, [SENSOR_EVENT_FUNC, c_void_p]],
'tdRegisterControllerEvent':
[c_int, [CONTROLLER_EVENT_FUNC, c_void_p]],
'tdUnregisterCallback': [c_int, [c_int]],
'tdTurnOn': [c_int, [c_int]],
'tdTurnOff': [c_int, [c_int]],
'tdBell': [c_int, [c_int]],
'tdDim': [c_int, [c_int, c_ubyte]],
'tdExecute': [c_int, [c_int]],
'tdUp': [c_int, [c_int]],
'tdDown': [c_int, [c_int]],
'tdStop': [c_int, [c_int]],
'tdLearn': [c_int, [c_int]],
'tdMethods': [c_int, [c_int, c_int]],
'tdLastSentCommand': [c_int, [c_int, c_int]],
'tdLastSentValue': [c_char_p, [c_int]],
'tdGetNumberOfDevices': [c_int, []],
'tdGetDeviceId': [c_int, [c_int]],
'tdGetDeviceType': [c_int, [c_int]],
'tdGetName': [c_char_p, [c_int]],
'tdSetName': [c_bool, [c_int, c_string_p]],
'tdGetProtocol': [c_char_p, [c_int]],
'tdSetProtocol': [c_bool, [c_int, c_string_p]],
'tdGetModel': [c_char_p, [c_int]],
'tdSetModel': [c_bool, [c_int, c_string_p]],
'tdGetDeviceParameter': [c_char_p, [c_int, c_string_p, c_string_p]],
'tdSetDeviceParameter': [c_bool, [c_int, c_string_p, c_string_p]],
'tdAddDevice': [c_int, []],
'tdRemoveDevice': [c_bool, [c_int]],
'tdSendRawCommand': [c_int, [c_string_p, c_int]],
'tdConnectTellStickController': [None, [c_int, c_int, c_string_p]],
'tdDisconnectTellStickController': [None, [c_int, c_int, c_string_p]],
'tdSensor': [c_int, [c_char_p, c_int, c_char_p, c_int,
POINTER(c_int), POINTER(c_int)]],
'tdSensorValue': [c_int, [c_string_p, c_string_p, c_int, c_int,
c_char_p, c_int, POINTER(c_int)]],
'tdController': [c_int, [POINTER(c_int), POINTER(c_int),
c_char_p, c_int, POINTER(c_int)]],
'tdControllerValue': [c_int, [c_int, c_string_p, c_char_p, c_int]],
'tdSetControllerValue': [c_int, [c_int, c_string_p, c_string_p]],
'tdRemoveController': [c_int, [c_int]],
}
def _to_str(self, char_p):
return char_p.value.decode(Library.STRING_ENCODING)
def _setup_functions(self, lib):
def check_int_result(result, func, args):
if result < 0:
raise TelldusError(result)
return result
def check_bool_result(result, func, args):
if not result:
raise TelldusError(const.TELLSTICK_ERROR_DEVICE_NOT_FOUND)
return result
def free_string(result, func, args):
string = cast(result, c_char_p).value
if string is not None:
lib.tdReleaseString(result)
if Library.DECODE_STRINGS:
string = string.decode(Library.STRING_ENCODING)
return string
for name, signature in Library._functions.items():
try:
func = getattr(lib, name)
func.restype = signature[0]
func.argtypes = signature[1]
if func.restype == c_int:
func.errcheck = check_int_result
elif func.restype == c_bool:
func.errcheck = check_bool_result
elif func.restype == c_char_p:
func.restype = c_void_p
func.errcheck = free_string
except AttributeError:
# Older version of the lib don't have all the functions
pass
def __init__(self, name=None, callback_dispatcher=None):
"""Load and initialize the Telldus core library.
The underlaying library is only initialized the first time this object
is created. Subsequent instances uses the same underlaying library
instance.
:param str name: If None than the platform specific name of the
Telldus library is used, but it can be e.g. an absolute path.
:param callback_dispatcher: If callbacks are to be used, this parameter
must refer to an instance of a class inheriting from
:class:`BaseCallbackDispatcher`.
"""
super(Library, self).__init__()
if not Library._lib:
assert Library._refcount == 0
if name is None:
name = LIBRARY_NAME
lib = DllLoader.LoadLibrary(name)
self._setup_functions(lib)
lib.tdInit()
Library._lib = lib
Library._refcount += 1
if callback_dispatcher is not None:
self._callback_wrapper = Library.CallbackWrapper(
callback_dispatcher)
else:
self._callback_wrapper = None
def __del__(self):
"""Close and unload the Telldus core library.
Any callback set up is removed.
The underlaying library is only closed and unloaded if this is the last
instance sharing the same underlaying library instance.
"""
# Using self.__class__.* instead of Library.* here to avoid a
# strange problem where Library could, in some runs, be None.
# Happens if the LoadLibrary call fails
if self.__class__._lib is None:
assert self.__class__._refcount == 0
return
assert self.__class__._refcount >= 1
self.__class__._refcount -= 1
if self._callback_wrapper is not None:
for cid in self._callback_wrapper.get_callback_ids():
try:
self.tdUnregisterCallback(cid)
except:
pass
if self.__class__._refcount != 0:
return
# telldus-core before v2.1.2 (where tdController was added) does not
# handle re-initialization after tdClose has been called (see Telldus
# ticket 188).
if hasattr(self.__class__._lib, "tdController"):
self.__class__._lib.tdClose()
self.__class__._lib = None
def __getattr__(self, name):
if name == 'callback_dispatcher':
return self._callback_wrapper._dispatcher
if name in Library._functions:
return getattr(self._lib, name)
raise AttributeError(name)
def tdInit(self):
raise NotImplementedError('should not be called explicitly')
def tdClose(self):
raise NotImplementedError('should not be called explicitly')
def tdReleaseString(self, string):
raise NotImplementedError('should not be called explicitly')
def tdRegisterDeviceEvent(self, callback):
assert(self._callback_wrapper is not None)
return self._callback_wrapper.register_callback(
self._lib.tdRegisterDeviceEvent, DEVICE_EVENT_FUNC, callback)
def tdRegisterDeviceChangeEvent(self, callback):
assert(self._callback_wrapper is not None)
return self._callback_wrapper.register_callback(
self._lib.tdRegisterDeviceChangeEvent, DEVICE_CHANGE_EVENT_FUNC,
callback)
def tdRegisterRawDeviceEvent(self, callback):
assert(self._callback_wrapper is not None)
return self._callback_wrapper.register_callback(
self._lib.tdRegisterRawDeviceEvent, RAW_DEVICE_EVENT_FUNC,
callback)
def tdRegisterSensorEvent(self, callback):
assert(self._callback_wrapper is not None)
return self._callback_wrapper.register_callback(
self._lib.tdRegisterSensorEvent, SENSOR_EVENT_FUNC, callback)
def tdRegisterControllerEvent(self, callback):
assert(self._callback_wrapper is not None)
return self._callback_wrapper.register_callback(
self._lib.tdRegisterControllerEvent, CONTROLLER_EVENT_FUNC,
callback)
def tdUnregisterCallback(self, cid):
assert(self._callback_wrapper is not None)
self._callback_wrapper.unregister_callback(cid)
self._lib.tdUnregisterCallback(cid)
def tdSensor(self):
"""Get the next sensor while iterating.
:return: a dict with the keys: protocol, model, id, datatypes.
"""
protocol = create_string_buffer(20)
model = create_string_buffer(20)
sid = c_int()
datatypes = c_int()
self._lib.tdSensor(protocol, sizeof(protocol), model, sizeof(model),
byref(sid), byref(datatypes))
return {'protocol': self._to_str(protocol),
'model': self._to_str(model),
'id': sid.value, 'datatypes': datatypes.value}
def tdController(self):
"""Get the next controller while iterating.
:return: a dict with the keys: id, type, name, available.
"""
cid = c_int()
ctype = c_int()
name = create_string_buffer(255)
available = c_int()
self._lib.tdController(byref(cid), byref(ctype), name, sizeof(name),
byref(available))
return {'id': cid.value, 'type': ctype.value,
'name': self._to_str(name), 'available': available.value}
def tdControllerValue(self, cid, name):
value = create_string_buffer(255)
self._lib.tdControllerValue(cid, name, value, sizeof(value))
return self._to_str(value)
|
erijo/tellcore-py
|
tellcore/library.py
|
Library.tdController
|
python
|
def tdController(self):
cid = c_int()
ctype = c_int()
name = create_string_buffer(255)
available = c_int()
self._lib.tdController(byref(cid), byref(ctype), name, sizeof(name),
byref(available))
return {'id': cid.value, 'type': ctype.value,
'name': self._to_str(name), 'available': available.value}
|
Get the next controller while iterating.
:return: a dict with the keys: id, type, name, available.
|
train
|
https://github.com/erijo/tellcore-py/blob/7a1eb53e12ef039a2350933e502633df7560f6a8/tellcore/library.py#L437-L450
|
[
"def _to_str(self, char_p):\n return char_p.value.decode(Library.STRING_ENCODING)\n"
] |
class Library(object):
"""Wrapper around the Telldus Core C API.
With the exception of tdInit, tdClose and tdReleaseString, all functions in
the C API (see `Telldus Core documentation
<http://developer.telldus.com/doxygen/group__core.html>`_) can be
called. The parameters are the same as in the C API documentation. The
return value are mostly the same as for the C API, except for functions
with multiple out parameters.
In addition, this class:
* automatically frees memory for strings returned from the C API,
* converts errors returned from functions into
(:class:`TelldusError`) exceptions,
* transparently converts between Python strings and C style strings.
"""
STRING_ENCODING = 'utf-8'
DECODE_STRINGS = True
class c_string_p(c_char_p):
def __init__(self, param):
c_char_p.__init__(self, param.encode(Library.STRING_ENCODING))
@classmethod
def from_param(cls, param):
if type(param) is str:
return cls(param)
try:
if type(param) is unicode:
return cls(param)
except NameError:
pass # The unicode type does not exist in python 3
return c_char_p.from_param(param)
# Must be a separate class (i.e. not part of Library), to avoid circular
# references when saving the wrapper callback function in a class with a
# destructor, as the destructor is not called in that case.
class CallbackWrapper(object):
def __init__(self, dispatcher):
self._callbacks = {}
self._lock = threading.Lock()
self._dispatcher = dispatcher
def get_callback_ids(self):
with self._lock:
return list(self._callbacks.keys())
def register_callback(self, registrator, functype, callback):
wrapper = functype(self._callback)
with self._lock:
cid = registrator(wrapper, None)
self._callbacks[cid] = (wrapper, callback)
return cid
def unregister_callback(self, cid):
with self._lock:
del self._callbacks[cid]
def _callback(self, *in_args):
args = []
# Convert all char* parameters (i.e. bytes) to proper python
# strings
for arg in in_args:
if type(arg) is bytes:
args.append(arg.decode(Library.STRING_ENCODING))
else:
args.append(arg)
# Get the real callback and the dispatcher
with self._lock:
try:
# args[-2] is callback id
(wrapper, callback) = self._callbacks[args[-2]]
except KeyError:
return
dispatcher = self._dispatcher
# Dispatch the callback, dropping the last parameter which is the
# context and always None.
try:
dispatcher.on_callback(callback, *args[:-1])
except:
pass
_lib = None
_refcount = 0
_functions = {
'tdInit': [None, []],
'tdClose': [None, []],
'tdReleaseString': [None, [c_void_p]],
'tdGetErrorString': [c_char_p, [c_int]],
'tdRegisterDeviceEvent':
[c_int, [DEVICE_EVENT_FUNC, c_void_p]],
'tdRegisterDeviceChangeEvent':
[c_int, [DEVICE_CHANGE_EVENT_FUNC, c_void_p]],
'tdRegisterRawDeviceEvent':
[c_int, [RAW_DEVICE_EVENT_FUNC, c_void_p]],
'tdRegisterSensorEvent':
[c_int, [SENSOR_EVENT_FUNC, c_void_p]],
'tdRegisterControllerEvent':
[c_int, [CONTROLLER_EVENT_FUNC, c_void_p]],
'tdUnregisterCallback': [c_int, [c_int]],
'tdTurnOn': [c_int, [c_int]],
'tdTurnOff': [c_int, [c_int]],
'tdBell': [c_int, [c_int]],
'tdDim': [c_int, [c_int, c_ubyte]],
'tdExecute': [c_int, [c_int]],
'tdUp': [c_int, [c_int]],
'tdDown': [c_int, [c_int]],
'tdStop': [c_int, [c_int]],
'tdLearn': [c_int, [c_int]],
'tdMethods': [c_int, [c_int, c_int]],
'tdLastSentCommand': [c_int, [c_int, c_int]],
'tdLastSentValue': [c_char_p, [c_int]],
'tdGetNumberOfDevices': [c_int, []],
'tdGetDeviceId': [c_int, [c_int]],
'tdGetDeviceType': [c_int, [c_int]],
'tdGetName': [c_char_p, [c_int]],
'tdSetName': [c_bool, [c_int, c_string_p]],
'tdGetProtocol': [c_char_p, [c_int]],
'tdSetProtocol': [c_bool, [c_int, c_string_p]],
'tdGetModel': [c_char_p, [c_int]],
'tdSetModel': [c_bool, [c_int, c_string_p]],
'tdGetDeviceParameter': [c_char_p, [c_int, c_string_p, c_string_p]],
'tdSetDeviceParameter': [c_bool, [c_int, c_string_p, c_string_p]],
'tdAddDevice': [c_int, []],
'tdRemoveDevice': [c_bool, [c_int]],
'tdSendRawCommand': [c_int, [c_string_p, c_int]],
'tdConnectTellStickController': [None, [c_int, c_int, c_string_p]],
'tdDisconnectTellStickController': [None, [c_int, c_int, c_string_p]],
'tdSensor': [c_int, [c_char_p, c_int, c_char_p, c_int,
POINTER(c_int), POINTER(c_int)]],
'tdSensorValue': [c_int, [c_string_p, c_string_p, c_int, c_int,
c_char_p, c_int, POINTER(c_int)]],
'tdController': [c_int, [POINTER(c_int), POINTER(c_int),
c_char_p, c_int, POINTER(c_int)]],
'tdControllerValue': [c_int, [c_int, c_string_p, c_char_p, c_int]],
'tdSetControllerValue': [c_int, [c_int, c_string_p, c_string_p]],
'tdRemoveController': [c_int, [c_int]],
}
def _to_str(self, char_p):
return char_p.value.decode(Library.STRING_ENCODING)
def _setup_functions(self, lib):
def check_int_result(result, func, args):
if result < 0:
raise TelldusError(result)
return result
def check_bool_result(result, func, args):
if not result:
raise TelldusError(const.TELLSTICK_ERROR_DEVICE_NOT_FOUND)
return result
def free_string(result, func, args):
string = cast(result, c_char_p).value
if string is not None:
lib.tdReleaseString(result)
if Library.DECODE_STRINGS:
string = string.decode(Library.STRING_ENCODING)
return string
for name, signature in Library._functions.items():
try:
func = getattr(lib, name)
func.restype = signature[0]
func.argtypes = signature[1]
if func.restype == c_int:
func.errcheck = check_int_result
elif func.restype == c_bool:
func.errcheck = check_bool_result
elif func.restype == c_char_p:
func.restype = c_void_p
func.errcheck = free_string
except AttributeError:
# Older version of the lib don't have all the functions
pass
def __init__(self, name=None, callback_dispatcher=None):
"""Load and initialize the Telldus core library.
The underlaying library is only initialized the first time this object
is created. Subsequent instances uses the same underlaying library
instance.
:param str name: If None than the platform specific name of the
Telldus library is used, but it can be e.g. an absolute path.
:param callback_dispatcher: If callbacks are to be used, this parameter
must refer to an instance of a class inheriting from
:class:`BaseCallbackDispatcher`.
"""
super(Library, self).__init__()
if not Library._lib:
assert Library._refcount == 0
if name is None:
name = LIBRARY_NAME
lib = DllLoader.LoadLibrary(name)
self._setup_functions(lib)
lib.tdInit()
Library._lib = lib
Library._refcount += 1
if callback_dispatcher is not None:
self._callback_wrapper = Library.CallbackWrapper(
callback_dispatcher)
else:
self._callback_wrapper = None
def __del__(self):
"""Close and unload the Telldus core library.
Any callback set up is removed.
The underlaying library is only closed and unloaded if this is the last
instance sharing the same underlaying library instance.
"""
# Using self.__class__.* instead of Library.* here to avoid a
# strange problem where Library could, in some runs, be None.
# Happens if the LoadLibrary call fails
if self.__class__._lib is None:
assert self.__class__._refcount == 0
return
assert self.__class__._refcount >= 1
self.__class__._refcount -= 1
if self._callback_wrapper is not None:
for cid in self._callback_wrapper.get_callback_ids():
try:
self.tdUnregisterCallback(cid)
except:
pass
if self.__class__._refcount != 0:
return
# telldus-core before v2.1.2 (where tdController was added) does not
# handle re-initialization after tdClose has been called (see Telldus
# ticket 188).
if hasattr(self.__class__._lib, "tdController"):
self.__class__._lib.tdClose()
self.__class__._lib = None
def __getattr__(self, name):
if name == 'callback_dispatcher':
return self._callback_wrapper._dispatcher
if name in Library._functions:
return getattr(self._lib, name)
raise AttributeError(name)
def tdInit(self):
raise NotImplementedError('should not be called explicitly')
def tdClose(self):
raise NotImplementedError('should not be called explicitly')
def tdReleaseString(self, string):
raise NotImplementedError('should not be called explicitly')
def tdRegisterDeviceEvent(self, callback):
assert(self._callback_wrapper is not None)
return self._callback_wrapper.register_callback(
self._lib.tdRegisterDeviceEvent, DEVICE_EVENT_FUNC, callback)
def tdRegisterDeviceChangeEvent(self, callback):
assert(self._callback_wrapper is not None)
return self._callback_wrapper.register_callback(
self._lib.tdRegisterDeviceChangeEvent, DEVICE_CHANGE_EVENT_FUNC,
callback)
def tdRegisterRawDeviceEvent(self, callback):
assert(self._callback_wrapper is not None)
return self._callback_wrapper.register_callback(
self._lib.tdRegisterRawDeviceEvent, RAW_DEVICE_EVENT_FUNC,
callback)
def tdRegisterSensorEvent(self, callback):
assert(self._callback_wrapper is not None)
return self._callback_wrapper.register_callback(
self._lib.tdRegisterSensorEvent, SENSOR_EVENT_FUNC, callback)
def tdRegisterControllerEvent(self, callback):
assert(self._callback_wrapper is not None)
return self._callback_wrapper.register_callback(
self._lib.tdRegisterControllerEvent, CONTROLLER_EVENT_FUNC,
callback)
def tdUnregisterCallback(self, cid):
assert(self._callback_wrapper is not None)
self._callback_wrapper.unregister_callback(cid)
self._lib.tdUnregisterCallback(cid)
def tdSensor(self):
"""Get the next sensor while iterating.
:return: a dict with the keys: protocol, model, id, datatypes.
"""
protocol = create_string_buffer(20)
model = create_string_buffer(20)
sid = c_int()
datatypes = c_int()
self._lib.tdSensor(protocol, sizeof(protocol), model, sizeof(model),
byref(sid), byref(datatypes))
return {'protocol': self._to_str(protocol),
'model': self._to_str(model),
'id': sid.value, 'datatypes': datatypes.value}
def tdSensorValue(self, protocol, model, sid, datatype):
"""Get the sensor value for a given sensor.
:return: a dict with the keys: value, timestamp.
"""
value = create_string_buffer(20)
timestamp = c_int()
self._lib.tdSensorValue(protocol, model, sid, datatype,
value, sizeof(value), byref(timestamp))
return {'value': self._to_str(value), 'timestamp': timestamp.value}
def tdControllerValue(self, cid, name):
value = create_string_buffer(255)
self._lib.tdControllerValue(cid, name, value, sizeof(value))
return self._to_str(value)
|
erijo/tellcore-py
|
tellcore/telldus.py
|
DeviceFactory
|
python
|
def DeviceFactory(id, lib=None):
lib = lib or Library()
if lib.tdGetDeviceType(id) == const.TELLSTICK_TYPE_GROUP:
return DeviceGroup(id, lib=lib)
return Device(id, lib=lib)
|
Create the correct device instance based on device type and return it.
:return: a :class:`Device` or :class:`DeviceGroup` instance.
|
train
|
https://github.com/erijo/tellcore-py/blob/7a1eb53e12ef039a2350933e502633df7560f6a8/tellcore/telldus.py#L266-L274
| null |
# Copyright (c) 2012-2014 Erik Johansson <erik@ejohansson.se>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
# USA
try:
import queue
except ImportError:
# Fall back on old (python 2) variant
import Queue as queue
import tellcore.constants as const
from tellcore.library import Library, TelldusError, BaseCallbackDispatcher
from datetime import datetime
class QueuedCallbackDispatcher(BaseCallbackDispatcher):
"""The default callback dispatcher used by :class:`TelldusCore`.
Queues callbacks that arrive from Telldus Core. Then calls them in the main
thread (or more precise: the thread calling :func:`process_callback`)
instead of the callback thread used by Telldus Core. This way the
application using :class:`TelldusCore` don't have to do any thread
synchronization. Only make sure :func:`process_pending_callbacks` is called
regularly.
"""
def __init__(self):
super(QueuedCallbackDispatcher, self).__init__()
self._queue = queue.Queue()
def on_callback(self, callback, *args):
self._queue.put((callback, args))
def process_callback(self, block=True):
"""Dispatch a single callback in the current thread.
:param boolean block: If True, blocks waiting for a callback to come.
:return: True if a callback was processed; otherwise False.
"""
try:
(callback, args) = self._queue.get(block=block)
try:
callback(*args)
finally:
self._queue.task_done()
except queue.Empty:
return False
return True
def process_pending_callbacks(self):
"""Dispatch all pending callbacks in the current thread."""
while self.process_callback(block=False):
pass
class AsyncioCallbackDispatcher(BaseCallbackDispatcher):
"""Dispatcher for use with the event loop available in Python 3.4+.
Callbacks will be dispatched on the thread running the event loop. The loop
argument should be a BaseEventLoop instance, e.g. the one returned from
asyncio.get_event_loop().
"""
def __init__(self, loop):
super(AsyncioCallbackDispatcher, self).__init__()
self._loop = loop
def on_callback(self, callback, *args):
self._loop.call_soon_threadsafe(callback, *args)
class TelldusCore(object):
"""The main class for tellcore-py.
Has methods for adding devices and for enumerating controllers, devices and
sensors. Also handles callbacks; both registration and making sure the
callbacks are processed in the main thread instead of the callback thread.
"""
def __init__(self, library_path=None, callback_dispatcher=None):
"""Create a new TelldusCore instance.
Only one instance should be used per program.
:param str library_path: Passed to the :class:`.library.Library`
constructor.
:param str callback_dispatcher: An instance implementing the
:class:`.library.BaseCallbackDispatcher` interface (
e.g. :class:`QueuedCallbackDispatcher` or
:class:`AsyncioCallbackDispatcher`) A callback dispatcher must be
provided if callbacks are to be used.
"""
super(TelldusCore, self).__init__()
self.lib = Library(library_path, callback_dispatcher)
def __getattr__(self, name):
if name == 'callback_dispatcher':
return self.lib.callback_dispatcher
raise AttributeError(name)
def register_device_event(self, callback):
"""Register a new device event callback handler.
See :ref:`event-example` for more information.
:return: the callback id
"""
return self.lib.tdRegisterDeviceEvent(callback)
def register_device_change_event(self, callback):
"""Register a new device change event callback handler.
See :ref:`event-example` for more information.
:return: the callback id
"""
return self.lib.tdRegisterDeviceChangeEvent(callback)
def register_raw_device_event(self, callback):
"""Register a new raw device event callback handler.
See :ref:`event-example` for more information.
:return: the callback id
"""
return self.lib.tdRegisterRawDeviceEvent(callback)
def register_sensor_event(self, callback):
"""Register a new sensor event callback handler.
See :ref:`event-example` for more information.
:return: the callback id
"""
return self.lib.tdRegisterSensorEvent(callback)
def register_controller_event(self, callback):
"""Register a new controller event callback handler.
See :ref:`event-example` for more information.
:return: the callback id
"""
return self.lib.tdRegisterControllerEvent(callback)
def unregister_callback(self, cid):
"""Unregister a callback handler.
:param int id: the callback id as returned from one of the
register_*_event methods.
"""
self.lib.tdUnregisterCallback(cid)
def devices(self):
"""Return all known devices.
:return: list of :class:`Device` or :class:`DeviceGroup` instances.
"""
devices = []
count = self.lib.tdGetNumberOfDevices()
for i in range(count):
device = DeviceFactory(self.lib.tdGetDeviceId(i), lib=self.lib)
devices.append(device)
return devices
def sensors(self):
"""Return all known sensors.
:return: list of :class:`Sensor` instances.
"""
sensors = []
try:
while True:
sensor = self.lib.tdSensor()
sensors.append(Sensor(lib=self.lib, **sensor))
except TelldusError as e:
if e.error != const.TELLSTICK_ERROR_DEVICE_NOT_FOUND:
raise
return sensors
def controllers(self):
"""Return all known controllers.
Requires Telldus core library version >= 2.1.2.
:return: list of :class:`Controller` instances.
"""
controllers = []
try:
while True:
controller = self.lib.tdController()
del controller["name"]
del controller["available"]
controllers.append(Controller(lib=self.lib, **controller))
except TelldusError as e:
if e.error != const.TELLSTICK_ERROR_NOT_FOUND:
raise
return controllers
def add_device(self, name, protocol, model=None, **parameters):
"""Add a new device.
:return: a :class:`Device` or :class:`DeviceGroup` instance.
"""
device = Device(self.lib.tdAddDevice(), lib=self.lib)
try:
device.name = name
device.protocol = protocol
if model:
device.model = model
for key, value in parameters.items():
device.set_parameter(key, value)
# Return correct type
return DeviceFactory(device.id, lib=self.lib)
except Exception:
import sys
exc_info = sys.exc_info()
try:
device.remove()
except:
pass
if "with_traceback" in dir(Exception):
raise exc_info[0].with_traceback(exc_info[1], exc_info[2])
else:
exec("raise exc_info[0], exc_info[1], exc_info[2]")
def add_group(self, name, devices):
"""Add a new device group.
:return: a :class:`DeviceGroup` instance.
"""
device = self.add_device(name, "group")
device.add_to_group(devices)
return device
def send_raw_command(self, command, reserved=0):
"""Send a raw command."""
return self.lib.tdSendRawCommand(command, reserved)
def connect_controller(self, vid, pid, serial):
"""Connect a controller."""
self.lib.tdConnectTellStickController(vid, pid, serial)
def disconnect_controller(self, vid, pid, serial):
"""Disconnect a controller."""
self.lib.tdDisconnectTellStickController(vid, pid, serial)
class Device(object):
"""A device that can be controlled by Telldus Core.
Can be instantiated directly if the id is known, but using
:func:`DeviceFactory` is recommended. Otherwise returned from
:func:`TelldusCore.add_device` or :func:`TelldusCore.devices`.
"""
PARAMETERS = ["devices", "house", "unit", "code", "system", "units",
"fade"]
def __init__(self, id, lib=None):
super(Device, self).__init__()
lib = lib or Library()
super(Device, self).__setattr__('id', id)
super(Device, self).__setattr__('lib', lib)
def remove(self):
"""Remove the device from Telldus Core."""
return self.lib.tdRemoveDevice(self.id)
def __getattr__(self, name):
if name == 'name':
func = self.lib.tdGetName
elif name == 'protocol':
func = self.lib.tdGetProtocol
elif name == 'model':
func = self.lib.tdGetModel
elif name == 'type':
func = self.lib.tdGetDeviceType
else:
raise AttributeError(name)
return func(self.id)
def __setattr__(self, name, value):
if name == 'name':
func = self.lib.tdSetName
elif name == 'protocol':
func = self.lib.tdSetProtocol
elif name == 'model':
func = self.lib.tdSetModel
else:
raise AttributeError(name)
func(self.id, value)
def parameters(self):
"""Get dict with all set parameters."""
parameters = {}
for name in self.PARAMETERS:
try:
parameters[name] = self.get_parameter(name)
except AttributeError:
pass
return parameters
def get_parameter(self, name):
"""Get a parameter."""
default_value = "$%!)(INVALID)(!%$"
value = self.lib.tdGetDeviceParameter(self.id, name, default_value)
if value == default_value:
raise AttributeError(name)
return value
def set_parameter(self, name, value):
"""Set a parameter."""
self.lib.tdSetDeviceParameter(self.id, name, str(value))
def turn_on(self):
"""Turn on the device."""
self.lib.tdTurnOn(self.id)
def turn_off(self):
"""Turn off the device."""
self.lib.tdTurnOff(self.id)
def bell(self):
"""Send "bell" command to the device."""
self.lib.tdBell(self.id)
def dim(self, level):
"""Dim the device.
:param int level: The level to dim to in the range [0, 255].
"""
self.lib.tdDim(self.id, level)
def execute(self):
"""Send "execute" command to the device."""
self.lib.tdExecute(self.id)
def up(self):
"""Send "up" command to the device."""
self.lib.tdUp(self.id)
def down(self):
"""Send "down" command to the device."""
self.lib.tdDown(self.id)
def stop(self):
"""Send "stop" command to the device."""
self.lib.tdStop(self.id)
def learn(self):
"""Send "learn" command to the device."""
self.lib.tdLearn(self.id)
def methods(self, methods_supported):
"""Query the device for supported methods."""
return self.lib.tdMethods(self.id, methods_supported)
def last_sent_command(self, methods_supported):
"""Get the last sent (or seen) command."""
return self.lib.tdLastSentCommand(self.id, methods_supported)
def last_sent_value(self):
"""Get the last sent (or seen) value."""
try:
return int(self.lib.tdLastSentValue(self.id))
except ValueError:
return None
class DeviceGroup(Device):
"""Extends :class:`Device` with methods for managing a group
E.g. when a group is turned on, all devices in that group are turned on.
"""
def add_to_group(self, devices):
"""Add device(s) to the group."""
ids = {d.id for d in self.devices_in_group()}
ids.update(self._device_ids(devices))
self._set_group(ids)
def remove_from_group(self, devices):
"""Remove device(s) from the group."""
ids = {d.id for d in self.devices_in_group()}
ids.difference_update(self._device_ids(devices))
self._set_group(ids)
def devices_in_group(self):
"""Fetch list of devices in group."""
try:
devices = self.get_parameter('devices')
except AttributeError:
return []
ctor = DeviceFactory
return [ctor(int(x), lib=self.lib) for x in devices.split(',') if x]
@staticmethod
def _device_ids(devices):
try:
iter(devices)
except TypeError:
devices = [devices]
ids = set()
for device in devices:
try:
ids.add(device.id)
except AttributeError:
# Assume device is id
ids.add(int(device))
return ids
def _set_group(self, ids):
self.set_parameter('devices', ','.join([str(x) for x in ids]))
class Sensor(object):
"""Represents a sensor.
Returned from :func:`TelldusCore.sensors`
"""
DATATYPES = {"temperature": const.TELLSTICK_TEMPERATURE,
"humidity": const.TELLSTICK_HUMIDITY,
"rainrate": const.TELLSTICK_RAINRATE,
"raintotal": const.TELLSTICK_RAINTOTAL,
"winddirection": const.TELLSTICK_WINDDIRECTION,
"windaverage": const.TELLSTICK_WINDAVERAGE,
"windgust": const.TELLSTICK_WINDGUST}
def __init__(self, protocol, model, id, datatypes, lib=None):
super(Sensor, self).__init__()
self.protocol = protocol
self.model = model
self.id = id
self.datatypes = datatypes
self.lib = lib or Library()
def has_value(self, datatype):
"""Return True if the sensor supports the given data type.
sensor.has_value(TELLSTICK_TEMPERATURE) is identical to calling
sensor.has_temperature().
"""
return (self.datatypes & datatype) != 0
def value(self, datatype):
"""Return the :class:`SensorValue` for the given data type.
sensor.value(TELLSTICK_TEMPERATURE) is identical to calling
sensor.temperature().
"""
value = self.lib.tdSensorValue(
self.protocol, self.model, self.id, datatype)
return SensorValue(datatype, value['value'], value['timestamp'])
def __getattr__(self, name):
typename = name.replace("has_", "", 1)
if typename in Sensor.DATATYPES:
datatype = Sensor.DATATYPES[typename]
if name == typename:
return lambda: self.value(datatype)
else:
return lambda: self.has_value(datatype)
raise AttributeError(name)
class SensorValue(object):
"""Represents a single sensor value.
Returned from :func:`Sensor.value`.
"""
def __init__(self, datatype, value, timestamp):
super(SensorValue, self).__init__()
self.datatype = datatype
self.value = value
self.timestamp = timestamp
def __getattr__(self, name):
if name == "datetime":
return datetime.fromtimestamp(self.timestamp)
raise AttributeError(name)
class Controller(object):
"""Represents a Telldus controller.
Returned from :func:`TelldusCore.controllers`
"""
def __init__(self, id, type, lib=None):
lib = lib or Library()
super(Controller, self).__init__()
super(Controller, self).__setattr__('id', id)
super(Controller, self).__setattr__('type', type)
super(Controller, self).__setattr__('lib', lib)
def __getattr__(self, name):
try:
return self.lib.tdControllerValue(self.id, name)
except TelldusError as e:
if e.error == const.TELLSTICK_ERROR_METHOD_NOT_SUPPORTED:
raise AttributeError(name)
raise
def __setattr__(self, name, value):
try:
self.lib.tdSetControllerValue(self.id, name, value)
except TelldusError as e:
if e.error == const.TELLSTICK_ERROR_SYNTAX:
raise AttributeError(name)
raise
|
erijo/tellcore-py
|
tellcore/telldus.py
|
QueuedCallbackDispatcher.process_callback
|
python
|
def process_callback(self, block=True):
try:
(callback, args) = self._queue.get(block=block)
try:
callback(*args)
finally:
self._queue.task_done()
except queue.Empty:
return False
return True
|
Dispatch a single callback in the current thread.
:param boolean block: If True, blocks waiting for a callback to come.
:return: True if a callback was processed; otherwise False.
|
train
|
https://github.com/erijo/tellcore-py/blob/7a1eb53e12ef039a2350933e502633df7560f6a8/tellcore/telldus.py#L48-L62
| null |
class QueuedCallbackDispatcher(BaseCallbackDispatcher):
"""The default callback dispatcher used by :class:`TelldusCore`.
Queues callbacks that arrive from Telldus Core. Then calls them in the main
thread (or more precise: the thread calling :func:`process_callback`)
instead of the callback thread used by Telldus Core. This way the
application using :class:`TelldusCore` don't have to do any thread
synchronization. Only make sure :func:`process_pending_callbacks` is called
regularly.
"""
def __init__(self):
super(QueuedCallbackDispatcher, self).__init__()
self._queue = queue.Queue()
def on_callback(self, callback, *args):
self._queue.put((callback, args))
def process_pending_callbacks(self):
"""Dispatch all pending callbacks in the current thread."""
while self.process_callback(block=False):
pass
|
erijo/tellcore-py
|
tellcore/telldus.py
|
TelldusCore.devices
|
python
|
def devices(self):
devices = []
count = self.lib.tdGetNumberOfDevices()
for i in range(count):
device = DeviceFactory(self.lib.tdGetDeviceId(i), lib=self.lib)
devices.append(device)
return devices
|
Return all known devices.
:return: list of :class:`Device` or :class:`DeviceGroup` instances.
|
train
|
https://github.com/erijo/tellcore-py/blob/7a1eb53e12ef039a2350933e502633df7560f6a8/tellcore/telldus.py#L169-L179
|
[
"def DeviceFactory(id, lib=None):\n \"\"\"Create the correct device instance based on device type and return it.\n\n :return: a :class:`Device` or :class:`DeviceGroup` instance.\n \"\"\"\n lib = lib or Library()\n if lib.tdGetDeviceType(id) == const.TELLSTICK_TYPE_GROUP:\n return DeviceGroup(id, lib=lib)\n return Device(id, lib=lib)\n"
] |
class TelldusCore(object):
"""The main class for tellcore-py.
Has methods for adding devices and for enumerating controllers, devices and
sensors. Also handles callbacks; both registration and making sure the
callbacks are processed in the main thread instead of the callback thread.
"""
def __init__(self, library_path=None, callback_dispatcher=None):
"""Create a new TelldusCore instance.
Only one instance should be used per program.
:param str library_path: Passed to the :class:`.library.Library`
constructor.
:param str callback_dispatcher: An instance implementing the
:class:`.library.BaseCallbackDispatcher` interface (
e.g. :class:`QueuedCallbackDispatcher` or
:class:`AsyncioCallbackDispatcher`) A callback dispatcher must be
provided if callbacks are to be used.
"""
super(TelldusCore, self).__init__()
self.lib = Library(library_path, callback_dispatcher)
def __getattr__(self, name):
if name == 'callback_dispatcher':
return self.lib.callback_dispatcher
raise AttributeError(name)
def register_device_event(self, callback):
"""Register a new device event callback handler.
See :ref:`event-example` for more information.
:return: the callback id
"""
return self.lib.tdRegisterDeviceEvent(callback)
def register_device_change_event(self, callback):
"""Register a new device change event callback handler.
See :ref:`event-example` for more information.
:return: the callback id
"""
return self.lib.tdRegisterDeviceChangeEvent(callback)
def register_raw_device_event(self, callback):
"""Register a new raw device event callback handler.
See :ref:`event-example` for more information.
:return: the callback id
"""
return self.lib.tdRegisterRawDeviceEvent(callback)
def register_sensor_event(self, callback):
"""Register a new sensor event callback handler.
See :ref:`event-example` for more information.
:return: the callback id
"""
return self.lib.tdRegisterSensorEvent(callback)
def register_controller_event(self, callback):
"""Register a new controller event callback handler.
See :ref:`event-example` for more information.
:return: the callback id
"""
return self.lib.tdRegisterControllerEvent(callback)
def unregister_callback(self, cid):
"""Unregister a callback handler.
:param int id: the callback id as returned from one of the
register_*_event methods.
"""
self.lib.tdUnregisterCallback(cid)
def sensors(self):
"""Return all known sensors.
:return: list of :class:`Sensor` instances.
"""
sensors = []
try:
while True:
sensor = self.lib.tdSensor()
sensors.append(Sensor(lib=self.lib, **sensor))
except TelldusError as e:
if e.error != const.TELLSTICK_ERROR_DEVICE_NOT_FOUND:
raise
return sensors
def controllers(self):
"""Return all known controllers.
Requires Telldus core library version >= 2.1.2.
:return: list of :class:`Controller` instances.
"""
controllers = []
try:
while True:
controller = self.lib.tdController()
del controller["name"]
del controller["available"]
controllers.append(Controller(lib=self.lib, **controller))
except TelldusError as e:
if e.error != const.TELLSTICK_ERROR_NOT_FOUND:
raise
return controllers
def add_device(self, name, protocol, model=None, **parameters):
"""Add a new device.
:return: a :class:`Device` or :class:`DeviceGroup` instance.
"""
device = Device(self.lib.tdAddDevice(), lib=self.lib)
try:
device.name = name
device.protocol = protocol
if model:
device.model = model
for key, value in parameters.items():
device.set_parameter(key, value)
# Return correct type
return DeviceFactory(device.id, lib=self.lib)
except Exception:
import sys
exc_info = sys.exc_info()
try:
device.remove()
except:
pass
if "with_traceback" in dir(Exception):
raise exc_info[0].with_traceback(exc_info[1], exc_info[2])
else:
exec("raise exc_info[0], exc_info[1], exc_info[2]")
def add_group(self, name, devices):
"""Add a new device group.
:return: a :class:`DeviceGroup` instance.
"""
device = self.add_device(name, "group")
device.add_to_group(devices)
return device
def send_raw_command(self, command, reserved=0):
"""Send a raw command."""
return self.lib.tdSendRawCommand(command, reserved)
def connect_controller(self, vid, pid, serial):
"""Connect a controller."""
self.lib.tdConnectTellStickController(vid, pid, serial)
def disconnect_controller(self, vid, pid, serial):
"""Disconnect a controller."""
self.lib.tdDisconnectTellStickController(vid, pid, serial)
|
erijo/tellcore-py
|
tellcore/telldus.py
|
TelldusCore.sensors
|
python
|
def sensors(self):
sensors = []
try:
while True:
sensor = self.lib.tdSensor()
sensors.append(Sensor(lib=self.lib, **sensor))
except TelldusError as e:
if e.error != const.TELLSTICK_ERROR_DEVICE_NOT_FOUND:
raise
return sensors
|
Return all known sensors.
:return: list of :class:`Sensor` instances.
|
train
|
https://github.com/erijo/tellcore-py/blob/7a1eb53e12ef039a2350933e502633df7560f6a8/tellcore/telldus.py#L181-L194
|
[
"def tdSensor(self):\n \"\"\"Get the next sensor while iterating.\n\n :return: a dict with the keys: protocol, model, id, datatypes.\n \"\"\"\n protocol = create_string_buffer(20)\n model = create_string_buffer(20)\n sid = c_int()\n datatypes = c_int()\n\n self._lib.tdSensor(protocol, sizeof(protocol), model, sizeof(model),\n byref(sid), byref(datatypes))\n return {'protocol': self._to_str(protocol),\n 'model': self._to_str(model),\n 'id': sid.value, 'datatypes': datatypes.value}\n"
] |
class TelldusCore(object):
"""The main class for tellcore-py.
Has methods for adding devices and for enumerating controllers, devices and
sensors. Also handles callbacks; both registration and making sure the
callbacks are processed in the main thread instead of the callback thread.
"""
def __init__(self, library_path=None, callback_dispatcher=None):
"""Create a new TelldusCore instance.
Only one instance should be used per program.
:param str library_path: Passed to the :class:`.library.Library`
constructor.
:param str callback_dispatcher: An instance implementing the
:class:`.library.BaseCallbackDispatcher` interface (
e.g. :class:`QueuedCallbackDispatcher` or
:class:`AsyncioCallbackDispatcher`) A callback dispatcher must be
provided if callbacks are to be used.
"""
super(TelldusCore, self).__init__()
self.lib = Library(library_path, callback_dispatcher)
def __getattr__(self, name):
if name == 'callback_dispatcher':
return self.lib.callback_dispatcher
raise AttributeError(name)
def register_device_event(self, callback):
"""Register a new device event callback handler.
See :ref:`event-example` for more information.
:return: the callback id
"""
return self.lib.tdRegisterDeviceEvent(callback)
def register_device_change_event(self, callback):
"""Register a new device change event callback handler.
See :ref:`event-example` for more information.
:return: the callback id
"""
return self.lib.tdRegisterDeviceChangeEvent(callback)
def register_raw_device_event(self, callback):
"""Register a new raw device event callback handler.
See :ref:`event-example` for more information.
:return: the callback id
"""
return self.lib.tdRegisterRawDeviceEvent(callback)
def register_sensor_event(self, callback):
"""Register a new sensor event callback handler.
See :ref:`event-example` for more information.
:return: the callback id
"""
return self.lib.tdRegisterSensorEvent(callback)
def register_controller_event(self, callback):
"""Register a new controller event callback handler.
See :ref:`event-example` for more information.
:return: the callback id
"""
return self.lib.tdRegisterControllerEvent(callback)
def unregister_callback(self, cid):
"""Unregister a callback handler.
:param int id: the callback id as returned from one of the
register_*_event methods.
"""
self.lib.tdUnregisterCallback(cid)
def devices(self):
"""Return all known devices.
:return: list of :class:`Device` or :class:`DeviceGroup` instances.
"""
devices = []
count = self.lib.tdGetNumberOfDevices()
for i in range(count):
device = DeviceFactory(self.lib.tdGetDeviceId(i), lib=self.lib)
devices.append(device)
return devices
def controllers(self):
"""Return all known controllers.
Requires Telldus core library version >= 2.1.2.
:return: list of :class:`Controller` instances.
"""
controllers = []
try:
while True:
controller = self.lib.tdController()
del controller["name"]
del controller["available"]
controllers.append(Controller(lib=self.lib, **controller))
except TelldusError as e:
if e.error != const.TELLSTICK_ERROR_NOT_FOUND:
raise
return controllers
def add_device(self, name, protocol, model=None, **parameters):
"""Add a new device.
:return: a :class:`Device` or :class:`DeviceGroup` instance.
"""
device = Device(self.lib.tdAddDevice(), lib=self.lib)
try:
device.name = name
device.protocol = protocol
if model:
device.model = model
for key, value in parameters.items():
device.set_parameter(key, value)
# Return correct type
return DeviceFactory(device.id, lib=self.lib)
except Exception:
import sys
exc_info = sys.exc_info()
try:
device.remove()
except:
pass
if "with_traceback" in dir(Exception):
raise exc_info[0].with_traceback(exc_info[1], exc_info[2])
else:
exec("raise exc_info[0], exc_info[1], exc_info[2]")
def add_group(self, name, devices):
"""Add a new device group.
:return: a :class:`DeviceGroup` instance.
"""
device = self.add_device(name, "group")
device.add_to_group(devices)
return device
def send_raw_command(self, command, reserved=0):
"""Send a raw command."""
return self.lib.tdSendRawCommand(command, reserved)
def connect_controller(self, vid, pid, serial):
"""Connect a controller."""
self.lib.tdConnectTellStickController(vid, pid, serial)
def disconnect_controller(self, vid, pid, serial):
"""Disconnect a controller."""
self.lib.tdDisconnectTellStickController(vid, pid, serial)
|
erijo/tellcore-py
|
tellcore/telldus.py
|
TelldusCore.controllers
|
python
|
def controllers(self):
controllers = []
try:
while True:
controller = self.lib.tdController()
del controller["name"]
del controller["available"]
controllers.append(Controller(lib=self.lib, **controller))
except TelldusError as e:
if e.error != const.TELLSTICK_ERROR_NOT_FOUND:
raise
return controllers
|
Return all known controllers.
Requires Telldus core library version >= 2.1.2.
:return: list of :class:`Controller` instances.
|
train
|
https://github.com/erijo/tellcore-py/blob/7a1eb53e12ef039a2350933e502633df7560f6a8/tellcore/telldus.py#L196-L213
|
[
"def tdController(self):\n \"\"\"Get the next controller while iterating.\n\n :return: a dict with the keys: id, type, name, available.\n \"\"\"\n cid = c_int()\n ctype = c_int()\n name = create_string_buffer(255)\n available = c_int()\n\n self._lib.tdController(byref(cid), byref(ctype), name, sizeof(name),\n byref(available))\n return {'id': cid.value, 'type': ctype.value,\n 'name': self._to_str(name), 'available': available.value}\n"
] |
class TelldusCore(object):
"""The main class for tellcore-py.
Has methods for adding devices and for enumerating controllers, devices and
sensors. Also handles callbacks; both registration and making sure the
callbacks are processed in the main thread instead of the callback thread.
"""
def __init__(self, library_path=None, callback_dispatcher=None):
"""Create a new TelldusCore instance.
Only one instance should be used per program.
:param str library_path: Passed to the :class:`.library.Library`
constructor.
:param str callback_dispatcher: An instance implementing the
:class:`.library.BaseCallbackDispatcher` interface (
e.g. :class:`QueuedCallbackDispatcher` or
:class:`AsyncioCallbackDispatcher`) A callback dispatcher must be
provided if callbacks are to be used.
"""
super(TelldusCore, self).__init__()
self.lib = Library(library_path, callback_dispatcher)
def __getattr__(self, name):
if name == 'callback_dispatcher':
return self.lib.callback_dispatcher
raise AttributeError(name)
def register_device_event(self, callback):
"""Register a new device event callback handler.
See :ref:`event-example` for more information.
:return: the callback id
"""
return self.lib.tdRegisterDeviceEvent(callback)
def register_device_change_event(self, callback):
"""Register a new device change event callback handler.
See :ref:`event-example` for more information.
:return: the callback id
"""
return self.lib.tdRegisterDeviceChangeEvent(callback)
def register_raw_device_event(self, callback):
"""Register a new raw device event callback handler.
See :ref:`event-example` for more information.
:return: the callback id
"""
return self.lib.tdRegisterRawDeviceEvent(callback)
def register_sensor_event(self, callback):
"""Register a new sensor event callback handler.
See :ref:`event-example` for more information.
:return: the callback id
"""
return self.lib.tdRegisterSensorEvent(callback)
def register_controller_event(self, callback):
"""Register a new controller event callback handler.
See :ref:`event-example` for more information.
:return: the callback id
"""
return self.lib.tdRegisterControllerEvent(callback)
def unregister_callback(self, cid):
"""Unregister a callback handler.
:param int id: the callback id as returned from one of the
register_*_event methods.
"""
self.lib.tdUnregisterCallback(cid)
def devices(self):
"""Return all known devices.
:return: list of :class:`Device` or :class:`DeviceGroup` instances.
"""
devices = []
count = self.lib.tdGetNumberOfDevices()
for i in range(count):
device = DeviceFactory(self.lib.tdGetDeviceId(i), lib=self.lib)
devices.append(device)
return devices
def sensors(self):
"""Return all known sensors.
:return: list of :class:`Sensor` instances.
"""
sensors = []
try:
while True:
sensor = self.lib.tdSensor()
sensors.append(Sensor(lib=self.lib, **sensor))
except TelldusError as e:
if e.error != const.TELLSTICK_ERROR_DEVICE_NOT_FOUND:
raise
return sensors
def add_device(self, name, protocol, model=None, **parameters):
"""Add a new device.
:return: a :class:`Device` or :class:`DeviceGroup` instance.
"""
device = Device(self.lib.tdAddDevice(), lib=self.lib)
try:
device.name = name
device.protocol = protocol
if model:
device.model = model
for key, value in parameters.items():
device.set_parameter(key, value)
# Return correct type
return DeviceFactory(device.id, lib=self.lib)
except Exception:
import sys
exc_info = sys.exc_info()
try:
device.remove()
except:
pass
if "with_traceback" in dir(Exception):
raise exc_info[0].with_traceback(exc_info[1], exc_info[2])
else:
exec("raise exc_info[0], exc_info[1], exc_info[2]")
def add_group(self, name, devices):
"""Add a new device group.
:return: a :class:`DeviceGroup` instance.
"""
device = self.add_device(name, "group")
device.add_to_group(devices)
return device
def send_raw_command(self, command, reserved=0):
"""Send a raw command."""
return self.lib.tdSendRawCommand(command, reserved)
def connect_controller(self, vid, pid, serial):
"""Connect a controller."""
self.lib.tdConnectTellStickController(vid, pid, serial)
def disconnect_controller(self, vid, pid, serial):
"""Disconnect a controller."""
self.lib.tdDisconnectTellStickController(vid, pid, serial)
|
erijo/tellcore-py
|
tellcore/telldus.py
|
TelldusCore.add_device
|
python
|
def add_device(self, name, protocol, model=None, **parameters):
device = Device(self.lib.tdAddDevice(), lib=self.lib)
try:
device.name = name
device.protocol = protocol
if model:
device.model = model
for key, value in parameters.items():
device.set_parameter(key, value)
# Return correct type
return DeviceFactory(device.id, lib=self.lib)
except Exception:
import sys
exc_info = sys.exc_info()
try:
device.remove()
except:
pass
if "with_traceback" in dir(Exception):
raise exc_info[0].with_traceback(exc_info[1], exc_info[2])
else:
exec("raise exc_info[0], exc_info[1], exc_info[2]")
|
Add a new device.
:return: a :class:`Device` or :class:`DeviceGroup` instance.
|
train
|
https://github.com/erijo/tellcore-py/blob/7a1eb53e12ef039a2350933e502633df7560f6a8/tellcore/telldus.py#L215-L242
|
[
"def DeviceFactory(id, lib=None):\n \"\"\"Create the correct device instance based on device type and return it.\n\n :return: a :class:`Device` or :class:`DeviceGroup` instance.\n \"\"\"\n lib = lib or Library()\n if lib.tdGetDeviceType(id) == const.TELLSTICK_TYPE_GROUP:\n return DeviceGroup(id, lib=lib)\n return Device(id, lib=lib)\n",
"def remove(self):\n \"\"\"Remove the device from Telldus Core.\"\"\"\n return self.lib.tdRemoveDevice(self.id)\n",
"def set_parameter(self, name, value):\n \"\"\"Set a parameter.\"\"\"\n self.lib.tdSetDeviceParameter(self.id, name, str(value))\n"
] |
class TelldusCore(object):
"""The main class for tellcore-py.
Has methods for adding devices and for enumerating controllers, devices and
sensors. Also handles callbacks; both registration and making sure the
callbacks are processed in the main thread instead of the callback thread.
"""
def __init__(self, library_path=None, callback_dispatcher=None):
"""Create a new TelldusCore instance.
Only one instance should be used per program.
:param str library_path: Passed to the :class:`.library.Library`
constructor.
:param str callback_dispatcher: An instance implementing the
:class:`.library.BaseCallbackDispatcher` interface (
e.g. :class:`QueuedCallbackDispatcher` or
:class:`AsyncioCallbackDispatcher`) A callback dispatcher must be
provided if callbacks are to be used.
"""
super(TelldusCore, self).__init__()
self.lib = Library(library_path, callback_dispatcher)
def __getattr__(self, name):
if name == 'callback_dispatcher':
return self.lib.callback_dispatcher
raise AttributeError(name)
def register_device_event(self, callback):
"""Register a new device event callback handler.
See :ref:`event-example` for more information.
:return: the callback id
"""
return self.lib.tdRegisterDeviceEvent(callback)
def register_device_change_event(self, callback):
"""Register a new device change event callback handler.
See :ref:`event-example` for more information.
:return: the callback id
"""
return self.lib.tdRegisterDeviceChangeEvent(callback)
def register_raw_device_event(self, callback):
"""Register a new raw device event callback handler.
See :ref:`event-example` for more information.
:return: the callback id
"""
return self.lib.tdRegisterRawDeviceEvent(callback)
def register_sensor_event(self, callback):
"""Register a new sensor event callback handler.
See :ref:`event-example` for more information.
:return: the callback id
"""
return self.lib.tdRegisterSensorEvent(callback)
def register_controller_event(self, callback):
"""Register a new controller event callback handler.
See :ref:`event-example` for more information.
:return: the callback id
"""
return self.lib.tdRegisterControllerEvent(callback)
def unregister_callback(self, cid):
"""Unregister a callback handler.
:param int id: the callback id as returned from one of the
register_*_event methods.
"""
self.lib.tdUnregisterCallback(cid)
def devices(self):
"""Return all known devices.
:return: list of :class:`Device` or :class:`DeviceGroup` instances.
"""
devices = []
count = self.lib.tdGetNumberOfDevices()
for i in range(count):
device = DeviceFactory(self.lib.tdGetDeviceId(i), lib=self.lib)
devices.append(device)
return devices
def sensors(self):
"""Return all known sensors.
:return: list of :class:`Sensor` instances.
"""
sensors = []
try:
while True:
sensor = self.lib.tdSensor()
sensors.append(Sensor(lib=self.lib, **sensor))
except TelldusError as e:
if e.error != const.TELLSTICK_ERROR_DEVICE_NOT_FOUND:
raise
return sensors
def controllers(self):
"""Return all known controllers.
Requires Telldus core library version >= 2.1.2.
:return: list of :class:`Controller` instances.
"""
controllers = []
try:
while True:
controller = self.lib.tdController()
del controller["name"]
del controller["available"]
controllers.append(Controller(lib=self.lib, **controller))
except TelldusError as e:
if e.error != const.TELLSTICK_ERROR_NOT_FOUND:
raise
return controllers
def add_group(self, name, devices):
"""Add a new device group.
:return: a :class:`DeviceGroup` instance.
"""
device = self.add_device(name, "group")
device.add_to_group(devices)
return device
def send_raw_command(self, command, reserved=0):
"""Send a raw command."""
return self.lib.tdSendRawCommand(command, reserved)
def connect_controller(self, vid, pid, serial):
"""Connect a controller."""
self.lib.tdConnectTellStickController(vid, pid, serial)
def disconnect_controller(self, vid, pid, serial):
"""Disconnect a controller."""
self.lib.tdDisconnectTellStickController(vid, pid, serial)
|
erijo/tellcore-py
|
tellcore/telldus.py
|
TelldusCore.add_group
|
python
|
def add_group(self, name, devices):
device = self.add_device(name, "group")
device.add_to_group(devices)
return device
|
Add a new device group.
:return: a :class:`DeviceGroup` instance.
|
train
|
https://github.com/erijo/tellcore-py/blob/7a1eb53e12ef039a2350933e502633df7560f6a8/tellcore/telldus.py#L244-L251
|
[
"def add_device(self, name, protocol, model=None, **parameters):\n \"\"\"Add a new device.\n\n :return: a :class:`Device` or :class:`DeviceGroup` instance.\n \"\"\"\n device = Device(self.lib.tdAddDevice(), lib=self.lib)\n try:\n device.name = name\n device.protocol = protocol\n if model:\n device.model = model\n for key, value in parameters.items():\n device.set_parameter(key, value)\n\n # Return correct type\n return DeviceFactory(device.id, lib=self.lib)\n except Exception:\n import sys\n exc_info = sys.exc_info()\n try:\n device.remove()\n except:\n pass\n\n if \"with_traceback\" in dir(Exception):\n raise exc_info[0].with_traceback(exc_info[1], exc_info[2])\n else:\n exec(\"raise exc_info[0], exc_info[1], exc_info[2]\")\n"
] |
class TelldusCore(object):
"""The main class for tellcore-py.
Has methods for adding devices and for enumerating controllers, devices and
sensors. Also handles callbacks; both registration and making sure the
callbacks are processed in the main thread instead of the callback thread.
"""
def __init__(self, library_path=None, callback_dispatcher=None):
"""Create a new TelldusCore instance.
Only one instance should be used per program.
:param str library_path: Passed to the :class:`.library.Library`
constructor.
:param str callback_dispatcher: An instance implementing the
:class:`.library.BaseCallbackDispatcher` interface (
e.g. :class:`QueuedCallbackDispatcher` or
:class:`AsyncioCallbackDispatcher`) A callback dispatcher must be
provided if callbacks are to be used.
"""
super(TelldusCore, self).__init__()
self.lib = Library(library_path, callback_dispatcher)
def __getattr__(self, name):
if name == 'callback_dispatcher':
return self.lib.callback_dispatcher
raise AttributeError(name)
def register_device_event(self, callback):
"""Register a new device event callback handler.
See :ref:`event-example` for more information.
:return: the callback id
"""
return self.lib.tdRegisterDeviceEvent(callback)
def register_device_change_event(self, callback):
"""Register a new device change event callback handler.
See :ref:`event-example` for more information.
:return: the callback id
"""
return self.lib.tdRegisterDeviceChangeEvent(callback)
def register_raw_device_event(self, callback):
"""Register a new raw device event callback handler.
See :ref:`event-example` for more information.
:return: the callback id
"""
return self.lib.tdRegisterRawDeviceEvent(callback)
def register_sensor_event(self, callback):
"""Register a new sensor event callback handler.
See :ref:`event-example` for more information.
:return: the callback id
"""
return self.lib.tdRegisterSensorEvent(callback)
def register_controller_event(self, callback):
"""Register a new controller event callback handler.
See :ref:`event-example` for more information.
:return: the callback id
"""
return self.lib.tdRegisterControllerEvent(callback)
def unregister_callback(self, cid):
"""Unregister a callback handler.
:param int id: the callback id as returned from one of the
register_*_event methods.
"""
self.lib.tdUnregisterCallback(cid)
def devices(self):
"""Return all known devices.
:return: list of :class:`Device` or :class:`DeviceGroup` instances.
"""
devices = []
count = self.lib.tdGetNumberOfDevices()
for i in range(count):
device = DeviceFactory(self.lib.tdGetDeviceId(i), lib=self.lib)
devices.append(device)
return devices
def sensors(self):
"""Return all known sensors.
:return: list of :class:`Sensor` instances.
"""
sensors = []
try:
while True:
sensor = self.lib.tdSensor()
sensors.append(Sensor(lib=self.lib, **sensor))
except TelldusError as e:
if e.error != const.TELLSTICK_ERROR_DEVICE_NOT_FOUND:
raise
return sensors
def controllers(self):
"""Return all known controllers.
Requires Telldus core library version >= 2.1.2.
:return: list of :class:`Controller` instances.
"""
controllers = []
try:
while True:
controller = self.lib.tdController()
del controller["name"]
del controller["available"]
controllers.append(Controller(lib=self.lib, **controller))
except TelldusError as e:
if e.error != const.TELLSTICK_ERROR_NOT_FOUND:
raise
return controllers
def add_device(self, name, protocol, model=None, **parameters):
"""Add a new device.
:return: a :class:`Device` or :class:`DeviceGroup` instance.
"""
device = Device(self.lib.tdAddDevice(), lib=self.lib)
try:
device.name = name
device.protocol = protocol
if model:
device.model = model
for key, value in parameters.items():
device.set_parameter(key, value)
# Return correct type
return DeviceFactory(device.id, lib=self.lib)
except Exception:
import sys
exc_info = sys.exc_info()
try:
device.remove()
except:
pass
if "with_traceback" in dir(Exception):
raise exc_info[0].with_traceback(exc_info[1], exc_info[2])
else:
exec("raise exc_info[0], exc_info[1], exc_info[2]")
def send_raw_command(self, command, reserved=0):
"""Send a raw command."""
return self.lib.tdSendRawCommand(command, reserved)
def connect_controller(self, vid, pid, serial):
"""Connect a controller."""
self.lib.tdConnectTellStickController(vid, pid, serial)
def disconnect_controller(self, vid, pid, serial):
"""Disconnect a controller."""
self.lib.tdDisconnectTellStickController(vid, pid, serial)
|
erijo/tellcore-py
|
tellcore/telldus.py
|
TelldusCore.connect_controller
|
python
|
def connect_controller(self, vid, pid, serial):
self.lib.tdConnectTellStickController(vid, pid, serial)
|
Connect a controller.
|
train
|
https://github.com/erijo/tellcore-py/blob/7a1eb53e12ef039a2350933e502633df7560f6a8/tellcore/telldus.py#L257-L259
| null |
class TelldusCore(object):
"""The main class for tellcore-py.
Has methods for adding devices and for enumerating controllers, devices and
sensors. Also handles callbacks; both registration and making sure the
callbacks are processed in the main thread instead of the callback thread.
"""
def __init__(self, library_path=None, callback_dispatcher=None):
"""Create a new TelldusCore instance.
Only one instance should be used per program.
:param str library_path: Passed to the :class:`.library.Library`
constructor.
:param str callback_dispatcher: An instance implementing the
:class:`.library.BaseCallbackDispatcher` interface (
e.g. :class:`QueuedCallbackDispatcher` or
:class:`AsyncioCallbackDispatcher`) A callback dispatcher must be
provided if callbacks are to be used.
"""
super(TelldusCore, self).__init__()
self.lib = Library(library_path, callback_dispatcher)
def __getattr__(self, name):
if name == 'callback_dispatcher':
return self.lib.callback_dispatcher
raise AttributeError(name)
def register_device_event(self, callback):
"""Register a new device event callback handler.
See :ref:`event-example` for more information.
:return: the callback id
"""
return self.lib.tdRegisterDeviceEvent(callback)
def register_device_change_event(self, callback):
"""Register a new device change event callback handler.
See :ref:`event-example` for more information.
:return: the callback id
"""
return self.lib.tdRegisterDeviceChangeEvent(callback)
def register_raw_device_event(self, callback):
"""Register a new raw device event callback handler.
See :ref:`event-example` for more information.
:return: the callback id
"""
return self.lib.tdRegisterRawDeviceEvent(callback)
def register_sensor_event(self, callback):
"""Register a new sensor event callback handler.
See :ref:`event-example` for more information.
:return: the callback id
"""
return self.lib.tdRegisterSensorEvent(callback)
def register_controller_event(self, callback):
"""Register a new controller event callback handler.
See :ref:`event-example` for more information.
:return: the callback id
"""
return self.lib.tdRegisterControllerEvent(callback)
def unregister_callback(self, cid):
"""Unregister a callback handler.
:param int id: the callback id as returned from one of the
register_*_event methods.
"""
self.lib.tdUnregisterCallback(cid)
def devices(self):
"""Return all known devices.
:return: list of :class:`Device` or :class:`DeviceGroup` instances.
"""
devices = []
count = self.lib.tdGetNumberOfDevices()
for i in range(count):
device = DeviceFactory(self.lib.tdGetDeviceId(i), lib=self.lib)
devices.append(device)
return devices
def sensors(self):
"""Return all known sensors.
:return: list of :class:`Sensor` instances.
"""
sensors = []
try:
while True:
sensor = self.lib.tdSensor()
sensors.append(Sensor(lib=self.lib, **sensor))
except TelldusError as e:
if e.error != const.TELLSTICK_ERROR_DEVICE_NOT_FOUND:
raise
return sensors
def controllers(self):
"""Return all known controllers.
Requires Telldus core library version >= 2.1.2.
:return: list of :class:`Controller` instances.
"""
controllers = []
try:
while True:
controller = self.lib.tdController()
del controller["name"]
del controller["available"]
controllers.append(Controller(lib=self.lib, **controller))
except TelldusError as e:
if e.error != const.TELLSTICK_ERROR_NOT_FOUND:
raise
return controllers
def add_device(self, name, protocol, model=None, **parameters):
"""Add a new device.
:return: a :class:`Device` or :class:`DeviceGroup` instance.
"""
device = Device(self.lib.tdAddDevice(), lib=self.lib)
try:
device.name = name
device.protocol = protocol
if model:
device.model = model
for key, value in parameters.items():
device.set_parameter(key, value)
# Return correct type
return DeviceFactory(device.id, lib=self.lib)
except Exception:
import sys
exc_info = sys.exc_info()
try:
device.remove()
except:
pass
if "with_traceback" in dir(Exception):
raise exc_info[0].with_traceback(exc_info[1], exc_info[2])
else:
exec("raise exc_info[0], exc_info[1], exc_info[2]")
def add_group(self, name, devices):
"""Add a new device group.
:return: a :class:`DeviceGroup` instance.
"""
device = self.add_device(name, "group")
device.add_to_group(devices)
return device
def send_raw_command(self, command, reserved=0):
"""Send a raw command."""
return self.lib.tdSendRawCommand(command, reserved)
def disconnect_controller(self, vid, pid, serial):
"""Disconnect a controller."""
self.lib.tdDisconnectTellStickController(vid, pid, serial)
|
erijo/tellcore-py
|
tellcore/telldus.py
|
TelldusCore.disconnect_controller
|
python
|
def disconnect_controller(self, vid, pid, serial):
self.lib.tdDisconnectTellStickController(vid, pid, serial)
|
Disconnect a controller.
|
train
|
https://github.com/erijo/tellcore-py/blob/7a1eb53e12ef039a2350933e502633df7560f6a8/tellcore/telldus.py#L261-L263
| null |
class TelldusCore(object):
"""The main class for tellcore-py.
Has methods for adding devices and for enumerating controllers, devices and
sensors. Also handles callbacks; both registration and making sure the
callbacks are processed in the main thread instead of the callback thread.
"""
def __init__(self, library_path=None, callback_dispatcher=None):
"""Create a new TelldusCore instance.
Only one instance should be used per program.
:param str library_path: Passed to the :class:`.library.Library`
constructor.
:param str callback_dispatcher: An instance implementing the
:class:`.library.BaseCallbackDispatcher` interface (
e.g. :class:`QueuedCallbackDispatcher` or
:class:`AsyncioCallbackDispatcher`) A callback dispatcher must be
provided if callbacks are to be used.
"""
super(TelldusCore, self).__init__()
self.lib = Library(library_path, callback_dispatcher)
def __getattr__(self, name):
if name == 'callback_dispatcher':
return self.lib.callback_dispatcher
raise AttributeError(name)
def register_device_event(self, callback):
"""Register a new device event callback handler.
See :ref:`event-example` for more information.
:return: the callback id
"""
return self.lib.tdRegisterDeviceEvent(callback)
def register_device_change_event(self, callback):
"""Register a new device change event callback handler.
See :ref:`event-example` for more information.
:return: the callback id
"""
return self.lib.tdRegisterDeviceChangeEvent(callback)
def register_raw_device_event(self, callback):
"""Register a new raw device event callback handler.
See :ref:`event-example` for more information.
:return: the callback id
"""
return self.lib.tdRegisterRawDeviceEvent(callback)
def register_sensor_event(self, callback):
"""Register a new sensor event callback handler.
See :ref:`event-example` for more information.
:return: the callback id
"""
return self.lib.tdRegisterSensorEvent(callback)
def register_controller_event(self, callback):
"""Register a new controller event callback handler.
See :ref:`event-example` for more information.
:return: the callback id
"""
return self.lib.tdRegisterControllerEvent(callback)
def unregister_callback(self, cid):
"""Unregister a callback handler.
:param int id: the callback id as returned from one of the
register_*_event methods.
"""
self.lib.tdUnregisterCallback(cid)
def devices(self):
"""Return all known devices.
:return: list of :class:`Device` or :class:`DeviceGroup` instances.
"""
devices = []
count = self.lib.tdGetNumberOfDevices()
for i in range(count):
device = DeviceFactory(self.lib.tdGetDeviceId(i), lib=self.lib)
devices.append(device)
return devices
def sensors(self):
"""Return all known sensors.
:return: list of :class:`Sensor` instances.
"""
sensors = []
try:
while True:
sensor = self.lib.tdSensor()
sensors.append(Sensor(lib=self.lib, **sensor))
except TelldusError as e:
if e.error != const.TELLSTICK_ERROR_DEVICE_NOT_FOUND:
raise
return sensors
def controllers(self):
"""Return all known controllers.
Requires Telldus core library version >= 2.1.2.
:return: list of :class:`Controller` instances.
"""
controllers = []
try:
while True:
controller = self.lib.tdController()
del controller["name"]
del controller["available"]
controllers.append(Controller(lib=self.lib, **controller))
except TelldusError as e:
if e.error != const.TELLSTICK_ERROR_NOT_FOUND:
raise
return controllers
def add_device(self, name, protocol, model=None, **parameters):
"""Add a new device.
:return: a :class:`Device` or :class:`DeviceGroup` instance.
"""
device = Device(self.lib.tdAddDevice(), lib=self.lib)
try:
device.name = name
device.protocol = protocol
if model:
device.model = model
for key, value in parameters.items():
device.set_parameter(key, value)
# Return correct type
return DeviceFactory(device.id, lib=self.lib)
except Exception:
import sys
exc_info = sys.exc_info()
try:
device.remove()
except:
pass
if "with_traceback" in dir(Exception):
raise exc_info[0].with_traceback(exc_info[1], exc_info[2])
else:
exec("raise exc_info[0], exc_info[1], exc_info[2]")
def add_group(self, name, devices):
"""Add a new device group.
:return: a :class:`DeviceGroup` instance.
"""
device = self.add_device(name, "group")
device.add_to_group(devices)
return device
def send_raw_command(self, command, reserved=0):
"""Send a raw command."""
return self.lib.tdSendRawCommand(command, reserved)
def connect_controller(self, vid, pid, serial):
"""Connect a controller."""
self.lib.tdConnectTellStickController(vid, pid, serial)
|
erijo/tellcore-py
|
tellcore/telldus.py
|
Device.parameters
|
python
|
def parameters(self):
parameters = {}
for name in self.PARAMETERS:
try:
parameters[name] = self.get_parameter(name)
except AttributeError:
pass
return parameters
|
Get dict with all set parameters.
|
train
|
https://github.com/erijo/tellcore-py/blob/7a1eb53e12ef039a2350933e502633df7560f6a8/tellcore/telldus.py#L323-L331
|
[
"def get_parameter(self, name):\n \"\"\"Get a parameter.\"\"\"\n default_value = \"$%!)(INVALID)(!%$\"\n value = self.lib.tdGetDeviceParameter(self.id, name, default_value)\n if value == default_value:\n raise AttributeError(name)\n return value\n"
] |
class Device(object):
"""A device that can be controlled by Telldus Core.
Can be instantiated directly if the id is known, but using
:func:`DeviceFactory` is recommended. Otherwise returned from
:func:`TelldusCore.add_device` or :func:`TelldusCore.devices`.
"""
PARAMETERS = ["devices", "house", "unit", "code", "system", "units",
"fade"]
def __init__(self, id, lib=None):
super(Device, self).__init__()
lib = lib or Library()
super(Device, self).__setattr__('id', id)
super(Device, self).__setattr__('lib', lib)
def remove(self):
"""Remove the device from Telldus Core."""
return self.lib.tdRemoveDevice(self.id)
def __getattr__(self, name):
if name == 'name':
func = self.lib.tdGetName
elif name == 'protocol':
func = self.lib.tdGetProtocol
elif name == 'model':
func = self.lib.tdGetModel
elif name == 'type':
func = self.lib.tdGetDeviceType
else:
raise AttributeError(name)
return func(self.id)
def __setattr__(self, name, value):
if name == 'name':
func = self.lib.tdSetName
elif name == 'protocol':
func = self.lib.tdSetProtocol
elif name == 'model':
func = self.lib.tdSetModel
else:
raise AttributeError(name)
func(self.id, value)
def get_parameter(self, name):
"""Get a parameter."""
default_value = "$%!)(INVALID)(!%$"
value = self.lib.tdGetDeviceParameter(self.id, name, default_value)
if value == default_value:
raise AttributeError(name)
return value
def set_parameter(self, name, value):
"""Set a parameter."""
self.lib.tdSetDeviceParameter(self.id, name, str(value))
def turn_on(self):
"""Turn on the device."""
self.lib.tdTurnOn(self.id)
def turn_off(self):
"""Turn off the device."""
self.lib.tdTurnOff(self.id)
def bell(self):
"""Send "bell" command to the device."""
self.lib.tdBell(self.id)
def dim(self, level):
"""Dim the device.
:param int level: The level to dim to in the range [0, 255].
"""
self.lib.tdDim(self.id, level)
def execute(self):
"""Send "execute" command to the device."""
self.lib.tdExecute(self.id)
def up(self):
"""Send "up" command to the device."""
self.lib.tdUp(self.id)
def down(self):
"""Send "down" command to the device."""
self.lib.tdDown(self.id)
def stop(self):
"""Send "stop" command to the device."""
self.lib.tdStop(self.id)
def learn(self):
"""Send "learn" command to the device."""
self.lib.tdLearn(self.id)
def methods(self, methods_supported):
"""Query the device for supported methods."""
return self.lib.tdMethods(self.id, methods_supported)
def last_sent_command(self, methods_supported):
"""Get the last sent (or seen) command."""
return self.lib.tdLastSentCommand(self.id, methods_supported)
def last_sent_value(self):
"""Get the last sent (or seen) value."""
try:
return int(self.lib.tdLastSentValue(self.id))
except ValueError:
return None
|
erijo/tellcore-py
|
tellcore/telldus.py
|
Device.get_parameter
|
python
|
def get_parameter(self, name):
default_value = "$%!)(INVALID)(!%$"
value = self.lib.tdGetDeviceParameter(self.id, name, default_value)
if value == default_value:
raise AttributeError(name)
return value
|
Get a parameter.
|
train
|
https://github.com/erijo/tellcore-py/blob/7a1eb53e12ef039a2350933e502633df7560f6a8/tellcore/telldus.py#L333-L339
| null |
class Device(object):
"""A device that can be controlled by Telldus Core.
Can be instantiated directly if the id is known, but using
:func:`DeviceFactory` is recommended. Otherwise returned from
:func:`TelldusCore.add_device` or :func:`TelldusCore.devices`.
"""
PARAMETERS = ["devices", "house", "unit", "code", "system", "units",
"fade"]
def __init__(self, id, lib=None):
super(Device, self).__init__()
lib = lib or Library()
super(Device, self).__setattr__('id', id)
super(Device, self).__setattr__('lib', lib)
def remove(self):
"""Remove the device from Telldus Core."""
return self.lib.tdRemoveDevice(self.id)
def __getattr__(self, name):
if name == 'name':
func = self.lib.tdGetName
elif name == 'protocol':
func = self.lib.tdGetProtocol
elif name == 'model':
func = self.lib.tdGetModel
elif name == 'type':
func = self.lib.tdGetDeviceType
else:
raise AttributeError(name)
return func(self.id)
def __setattr__(self, name, value):
if name == 'name':
func = self.lib.tdSetName
elif name == 'protocol':
func = self.lib.tdSetProtocol
elif name == 'model':
func = self.lib.tdSetModel
else:
raise AttributeError(name)
func(self.id, value)
def parameters(self):
"""Get dict with all set parameters."""
parameters = {}
for name in self.PARAMETERS:
try:
parameters[name] = self.get_parameter(name)
except AttributeError:
pass
return parameters
def set_parameter(self, name, value):
"""Set a parameter."""
self.lib.tdSetDeviceParameter(self.id, name, str(value))
def turn_on(self):
"""Turn on the device."""
self.lib.tdTurnOn(self.id)
def turn_off(self):
"""Turn off the device."""
self.lib.tdTurnOff(self.id)
def bell(self):
"""Send "bell" command to the device."""
self.lib.tdBell(self.id)
def dim(self, level):
"""Dim the device.
:param int level: The level to dim to in the range [0, 255].
"""
self.lib.tdDim(self.id, level)
def execute(self):
"""Send "execute" command to the device."""
self.lib.tdExecute(self.id)
def up(self):
"""Send "up" command to the device."""
self.lib.tdUp(self.id)
def down(self):
"""Send "down" command to the device."""
self.lib.tdDown(self.id)
def stop(self):
"""Send "stop" command to the device."""
self.lib.tdStop(self.id)
def learn(self):
"""Send "learn" command to the device."""
self.lib.tdLearn(self.id)
def methods(self, methods_supported):
"""Query the device for supported methods."""
return self.lib.tdMethods(self.id, methods_supported)
def last_sent_command(self, methods_supported):
"""Get the last sent (or seen) command."""
return self.lib.tdLastSentCommand(self.id, methods_supported)
def last_sent_value(self):
"""Get the last sent (or seen) value."""
try:
return int(self.lib.tdLastSentValue(self.id))
except ValueError:
return None
|
erijo/tellcore-py
|
tellcore/telldus.py
|
Device.set_parameter
|
python
|
def set_parameter(self, name, value):
self.lib.tdSetDeviceParameter(self.id, name, str(value))
|
Set a parameter.
|
train
|
https://github.com/erijo/tellcore-py/blob/7a1eb53e12ef039a2350933e502633df7560f6a8/tellcore/telldus.py#L341-L343
| null |
class Device(object):
"""A device that can be controlled by Telldus Core.
Can be instantiated directly if the id is known, but using
:func:`DeviceFactory` is recommended. Otherwise returned from
:func:`TelldusCore.add_device` or :func:`TelldusCore.devices`.
"""
PARAMETERS = ["devices", "house", "unit", "code", "system", "units",
"fade"]
def __init__(self, id, lib=None):
super(Device, self).__init__()
lib = lib or Library()
super(Device, self).__setattr__('id', id)
super(Device, self).__setattr__('lib', lib)
def remove(self):
"""Remove the device from Telldus Core."""
return self.lib.tdRemoveDevice(self.id)
def __getattr__(self, name):
if name == 'name':
func = self.lib.tdGetName
elif name == 'protocol':
func = self.lib.tdGetProtocol
elif name == 'model':
func = self.lib.tdGetModel
elif name == 'type':
func = self.lib.tdGetDeviceType
else:
raise AttributeError(name)
return func(self.id)
def __setattr__(self, name, value):
if name == 'name':
func = self.lib.tdSetName
elif name == 'protocol':
func = self.lib.tdSetProtocol
elif name == 'model':
func = self.lib.tdSetModel
else:
raise AttributeError(name)
func(self.id, value)
def parameters(self):
"""Get dict with all set parameters."""
parameters = {}
for name in self.PARAMETERS:
try:
parameters[name] = self.get_parameter(name)
except AttributeError:
pass
return parameters
def get_parameter(self, name):
"""Get a parameter."""
default_value = "$%!)(INVALID)(!%$"
value = self.lib.tdGetDeviceParameter(self.id, name, default_value)
if value == default_value:
raise AttributeError(name)
return value
def turn_on(self):
"""Turn on the device."""
self.lib.tdTurnOn(self.id)
def turn_off(self):
"""Turn off the device."""
self.lib.tdTurnOff(self.id)
def bell(self):
"""Send "bell" command to the device."""
self.lib.tdBell(self.id)
def dim(self, level):
"""Dim the device.
:param int level: The level to dim to in the range [0, 255].
"""
self.lib.tdDim(self.id, level)
def execute(self):
"""Send "execute" command to the device."""
self.lib.tdExecute(self.id)
def up(self):
"""Send "up" command to the device."""
self.lib.tdUp(self.id)
def down(self):
"""Send "down" command to the device."""
self.lib.tdDown(self.id)
def stop(self):
"""Send "stop" command to the device."""
self.lib.tdStop(self.id)
def learn(self):
"""Send "learn" command to the device."""
self.lib.tdLearn(self.id)
def methods(self, methods_supported):
"""Query the device for supported methods."""
return self.lib.tdMethods(self.id, methods_supported)
def last_sent_command(self, methods_supported):
"""Get the last sent (or seen) command."""
return self.lib.tdLastSentCommand(self.id, methods_supported)
def last_sent_value(self):
"""Get the last sent (or seen) value."""
try:
return int(self.lib.tdLastSentValue(self.id))
except ValueError:
return None
|
erijo/tellcore-py
|
tellcore/telldus.py
|
DeviceGroup.add_to_group
|
python
|
def add_to_group(self, devices):
ids = {d.id for d in self.devices_in_group()}
ids.update(self._device_ids(devices))
self._set_group(ids)
|
Add device(s) to the group.
|
train
|
https://github.com/erijo/tellcore-py/blob/7a1eb53e12ef039a2350933e502633df7560f6a8/tellcore/telldus.py#L406-L410
|
[
"def devices_in_group(self):\n \"\"\"Fetch list of devices in group.\"\"\"\n try:\n devices = self.get_parameter('devices')\n except AttributeError:\n return []\n\n ctor = DeviceFactory\n return [ctor(int(x), lib=self.lib) for x in devices.split(',') if x]\n",
"def _device_ids(devices):\n try:\n iter(devices)\n except TypeError:\n devices = [devices]\n\n ids = set()\n for device in devices:\n try:\n ids.add(device.id)\n except AttributeError:\n # Assume device is id\n ids.add(int(device))\n return ids\n",
"def _set_group(self, ids):\n self.set_parameter('devices', ','.join([str(x) for x in ids]))\n"
] |
class DeviceGroup(Device):
"""Extends :class:`Device` with methods for managing a group
E.g. when a group is turned on, all devices in that group are turned on.
"""
def remove_from_group(self, devices):
"""Remove device(s) from the group."""
ids = {d.id for d in self.devices_in_group()}
ids.difference_update(self._device_ids(devices))
self._set_group(ids)
def devices_in_group(self):
"""Fetch list of devices in group."""
try:
devices = self.get_parameter('devices')
except AttributeError:
return []
ctor = DeviceFactory
return [ctor(int(x), lib=self.lib) for x in devices.split(',') if x]
@staticmethod
def _device_ids(devices):
try:
iter(devices)
except TypeError:
devices = [devices]
ids = set()
for device in devices:
try:
ids.add(device.id)
except AttributeError:
# Assume device is id
ids.add(int(device))
return ids
def _set_group(self, ids):
self.set_parameter('devices', ','.join([str(x) for x in ids]))
|
erijo/tellcore-py
|
tellcore/telldus.py
|
DeviceGroup.remove_from_group
|
python
|
def remove_from_group(self, devices):
ids = {d.id for d in self.devices_in_group()}
ids.difference_update(self._device_ids(devices))
self._set_group(ids)
|
Remove device(s) from the group.
|
train
|
https://github.com/erijo/tellcore-py/blob/7a1eb53e12ef039a2350933e502633df7560f6a8/tellcore/telldus.py#L412-L416
|
[
"def devices_in_group(self):\n \"\"\"Fetch list of devices in group.\"\"\"\n try:\n devices = self.get_parameter('devices')\n except AttributeError:\n return []\n\n ctor = DeviceFactory\n return [ctor(int(x), lib=self.lib) for x in devices.split(',') if x]\n",
"def _device_ids(devices):\n try:\n iter(devices)\n except TypeError:\n devices = [devices]\n\n ids = set()\n for device in devices:\n try:\n ids.add(device.id)\n except AttributeError:\n # Assume device is id\n ids.add(int(device))\n return ids\n",
"def _set_group(self, ids):\n self.set_parameter('devices', ','.join([str(x) for x in ids]))\n"
] |
class DeviceGroup(Device):
"""Extends :class:`Device` with methods for managing a group
E.g. when a group is turned on, all devices in that group are turned on.
"""
def add_to_group(self, devices):
"""Add device(s) to the group."""
ids = {d.id for d in self.devices_in_group()}
ids.update(self._device_ids(devices))
self._set_group(ids)
def devices_in_group(self):
"""Fetch list of devices in group."""
try:
devices = self.get_parameter('devices')
except AttributeError:
return []
ctor = DeviceFactory
return [ctor(int(x), lib=self.lib) for x in devices.split(',') if x]
@staticmethod
def _device_ids(devices):
try:
iter(devices)
except TypeError:
devices = [devices]
ids = set()
for device in devices:
try:
ids.add(device.id)
except AttributeError:
# Assume device is id
ids.add(int(device))
return ids
def _set_group(self, ids):
self.set_parameter('devices', ','.join([str(x) for x in ids]))
|
erijo/tellcore-py
|
tellcore/telldus.py
|
DeviceGroup.devices_in_group
|
python
|
def devices_in_group(self):
try:
devices = self.get_parameter('devices')
except AttributeError:
return []
ctor = DeviceFactory
return [ctor(int(x), lib=self.lib) for x in devices.split(',') if x]
|
Fetch list of devices in group.
|
train
|
https://github.com/erijo/tellcore-py/blob/7a1eb53e12ef039a2350933e502633df7560f6a8/tellcore/telldus.py#L418-L426
|
[
"def get_parameter(self, name):\n \"\"\"Get a parameter.\"\"\"\n default_value = \"$%!)(INVALID)(!%$\"\n value = self.lib.tdGetDeviceParameter(self.id, name, default_value)\n if value == default_value:\n raise AttributeError(name)\n return value\n"
] |
class DeviceGroup(Device):
"""Extends :class:`Device` with methods for managing a group
E.g. when a group is turned on, all devices in that group are turned on.
"""
def add_to_group(self, devices):
"""Add device(s) to the group."""
ids = {d.id for d in self.devices_in_group()}
ids.update(self._device_ids(devices))
self._set_group(ids)
def remove_from_group(self, devices):
"""Remove device(s) from the group."""
ids = {d.id for d in self.devices_in_group()}
ids.difference_update(self._device_ids(devices))
self._set_group(ids)
@staticmethod
def _device_ids(devices):
try:
iter(devices)
except TypeError:
devices = [devices]
ids = set()
for device in devices:
try:
ids.add(device.id)
except AttributeError:
# Assume device is id
ids.add(int(device))
return ids
def _set_group(self, ids):
self.set_parameter('devices', ','.join([str(x) for x in ids]))
|
erijo/tellcore-py
|
tellcore/telldus.py
|
Sensor.value
|
python
|
def value(self, datatype):
value = self.lib.tdSensorValue(
self.protocol, self.model, self.id, datatype)
return SensorValue(datatype, value['value'], value['timestamp'])
|
Return the :class:`SensorValue` for the given data type.
sensor.value(TELLSTICK_TEMPERATURE) is identical to calling
sensor.temperature().
|
train
|
https://github.com/erijo/tellcore-py/blob/7a1eb53e12ef039a2350933e502633df7560f6a8/tellcore/telldus.py#L478-L486
| null |
class Sensor(object):
"""Represents a sensor.
Returned from :func:`TelldusCore.sensors`
"""
DATATYPES = {"temperature": const.TELLSTICK_TEMPERATURE,
"humidity": const.TELLSTICK_HUMIDITY,
"rainrate": const.TELLSTICK_RAINRATE,
"raintotal": const.TELLSTICK_RAINTOTAL,
"winddirection": const.TELLSTICK_WINDDIRECTION,
"windaverage": const.TELLSTICK_WINDAVERAGE,
"windgust": const.TELLSTICK_WINDGUST}
def __init__(self, protocol, model, id, datatypes, lib=None):
super(Sensor, self).__init__()
self.protocol = protocol
self.model = model
self.id = id
self.datatypes = datatypes
self.lib = lib or Library()
def has_value(self, datatype):
"""Return True if the sensor supports the given data type.
sensor.has_value(TELLSTICK_TEMPERATURE) is identical to calling
sensor.has_temperature().
"""
return (self.datatypes & datatype) != 0
def __getattr__(self, name):
typename = name.replace("has_", "", 1)
if typename in Sensor.DATATYPES:
datatype = Sensor.DATATYPES[typename]
if name == typename:
return lambda: self.value(datatype)
else:
return lambda: self.has_value(datatype)
raise AttributeError(name)
|
mozilla-services/python-dockerflow
|
src/dockerflow/version.py
|
get_version
|
python
|
def get_version(root):
version_json = os.path.join(root, 'version.json')
if os.path.exists(version_json):
with open(version_json, 'r') as version_json_file:
return json.load(version_json_file)
return None
|
Load and return the contents of version.json.
:param root: The root path that the ``version.json`` file will be opened
:type root: str
:returns: Content of ``version.json`` or None
:rtype: dict or None
|
train
|
https://github.com/mozilla-services/python-dockerflow/blob/43703c5e8934ba6901b0a1520d6da4ed6457208c/src/dockerflow/version.py#L10-L23
| null |
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, you can obtain one at http://mozilla.org/MPL/2.0/.
import json
import os
__all__ = ['get_version']
|
mozilla-services/python-dockerflow
|
src/dockerflow/django/views.py
|
version
|
python
|
def version(request):
version_json = import_string(version_callback)(settings.BASE_DIR)
if version_json is None:
return HttpResponseNotFound('version.json not found')
else:
return JsonResponse(version_json)
|
Returns the contents of version.json or a 404.
|
train
|
https://github.com/mozilla-services/python-dockerflow/blob/43703c5e8934ba6901b0a1520d6da4ed6457208c/src/dockerflow/django/views.py#L20-L28
| null |
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, you can obtain one at http://mozilla.org/MPL/2.0/.
from django.conf import settings
from django.core import checks
from django.http import HttpResponse, HttpResponseNotFound, JsonResponse
from django.utils.module_loading import import_string
from .checks import level_to_text
from .signals import heartbeat_failed, heartbeat_passed
version_callback = getattr(
settings,
'DOCKERFLOW_VERSION_CALLBACK',
'dockerflow.version.get_version',
)
def lbheartbeat(request):
"""
Let the load balancer know the application is running and available
must return 200 (not 204) for ELB
http://docs.aws.amazon.com/ElasticLoadBalancing/latest/DeveloperGuide/elb-healthchecks.html
"""
return HttpResponse()
def heartbeat(request):
"""
Runs all the Django checks and returns a JsonResponse with either
a status code of 200 or 500 depending on the results of the checks.
Any check that returns a warning or worse (error, critical) will
return a 500 response.
"""
all_checks = checks.registry.registry.get_checks(
include_deployment_checks=not settings.DEBUG,
)
details = {}
statuses = {}
level = 0
for check in all_checks:
detail = heartbeat_check_detail(check)
statuses[check.__name__] = detail['status']
level = max(level, detail['level'])
if detail['level'] > 0:
details[check.__name__] = detail
if level < checks.messages.WARNING:
status_code = 200
heartbeat_passed.send(sender=heartbeat, level=level)
else:
status_code = 500
heartbeat_failed.send(sender=heartbeat, level=level)
payload = {
'status': level_to_text(level),
'checks': statuses,
'details': details,
}
return JsonResponse(payload, status=status_code)
def heartbeat_check_detail(check):
errors = check(app_configs=None)
errors = list(filter(lambda e: e.id not in settings.SILENCED_SYSTEM_CHECKS, errors))
level = max([0] + [e.level for e in errors])
return {
'status': level_to_text(level),
'level': level,
'messages': {e.id: e.msg for e in errors},
}
|
mozilla-services/python-dockerflow
|
src/dockerflow/django/views.py
|
heartbeat
|
python
|
def heartbeat(request):
all_checks = checks.registry.registry.get_checks(
include_deployment_checks=not settings.DEBUG,
)
details = {}
statuses = {}
level = 0
for check in all_checks:
detail = heartbeat_check_detail(check)
statuses[check.__name__] = detail['status']
level = max(level, detail['level'])
if detail['level'] > 0:
details[check.__name__] = detail
if level < checks.messages.WARNING:
status_code = 200
heartbeat_passed.send(sender=heartbeat, level=level)
else:
status_code = 500
heartbeat_failed.send(sender=heartbeat, level=level)
payload = {
'status': level_to_text(level),
'checks': statuses,
'details': details,
}
return JsonResponse(payload, status=status_code)
|
Runs all the Django checks and returns a JsonResponse with either
a status code of 200 or 500 depending on the results of the checks.
Any check that returns a warning or worse (error, critical) will
return a 500 response.
|
train
|
https://github.com/mozilla-services/python-dockerflow/blob/43703c5e8934ba6901b0a1520d6da4ed6457208c/src/dockerflow/django/views.py#L40-L75
|
[
"def level_to_text(level):\n statuses = {\n 0: 'ok',\n checks.messages.DEBUG: 'debug',\n checks.messages.INFO: 'info',\n checks.messages.WARNING: 'warning',\n checks.messages.ERROR: 'error',\n checks.messages.CRITICAL: 'critical',\n }\n return statuses.get(level, 'unknown')\n",
"def heartbeat_check_detail(check):\n errors = check(app_configs=None)\n errors = list(filter(lambda e: e.id not in settings.SILENCED_SYSTEM_CHECKS, errors))\n level = max([0] + [e.level for e in errors])\n\n return {\n 'status': level_to_text(level),\n 'level': level,\n 'messages': {e.id: e.msg for e in errors},\n }\n"
] |
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, you can obtain one at http://mozilla.org/MPL/2.0/.
from django.conf import settings
from django.core import checks
from django.http import HttpResponse, HttpResponseNotFound, JsonResponse
from django.utils.module_loading import import_string
from .checks import level_to_text
from .signals import heartbeat_failed, heartbeat_passed
version_callback = getattr(
settings,
'DOCKERFLOW_VERSION_CALLBACK',
'dockerflow.version.get_version',
)
def version(request):
"""
Returns the contents of version.json or a 404.
"""
version_json = import_string(version_callback)(settings.BASE_DIR)
if version_json is None:
return HttpResponseNotFound('version.json not found')
else:
return JsonResponse(version_json)
def lbheartbeat(request):
"""
Let the load balancer know the application is running and available
must return 200 (not 204) for ELB
http://docs.aws.amazon.com/ElasticLoadBalancing/latest/DeveloperGuide/elb-healthchecks.html
"""
return HttpResponse()
def heartbeat_check_detail(check):
errors = check(app_configs=None)
errors = list(filter(lambda e: e.id not in settings.SILENCED_SYSTEM_CHECKS, errors))
level = max([0] + [e.level for e in errors])
return {
'status': level_to_text(level),
'level': level,
'messages': {e.id: e.msg for e in errors},
}
|
mozilla-services/python-dockerflow
|
src/dockerflow/django/checks.py
|
check_database_connected
|
python
|
def check_database_connected(app_configs, **kwargs):
errors = []
try:
connection.ensure_connection()
except OperationalError as e:
msg = 'Could not connect to database: {!s}'.format(e)
errors.append(checks.Error(msg,
id=health.ERROR_CANNOT_CONNECT_DATABASE))
except ImproperlyConfigured as e:
msg = 'Datbase misconfigured: "{!s}"'.format(e)
errors.append(checks.Error(msg,
id=health.ERROR_MISCONFIGURED_DATABASE))
else:
if not connection.is_usable():
errors.append(checks.Error('Database connection is not usable',
id=health.ERROR_UNUSABLE_DATABASE))
return errors
|
A Django check to see if connecting to the configured default
database backend succeeds.
|
train
|
https://github.com/mozilla-services/python-dockerflow/blob/43703c5e8934ba6901b0a1520d6da4ed6457208c/src/dockerflow/django/checks.py#L26-L48
| null |
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, you can obtain one at http://mozilla.org/MPL/2.0/.
from django.conf import settings
from django.core import checks
from django.core.exceptions import ImproperlyConfigured
from django.db import connection
from django.db.utils import OperationalError, ProgrammingError
from django.utils.module_loading import import_string
from .. import health
def level_to_text(level):
statuses = {
0: 'ok',
checks.messages.DEBUG: 'debug',
checks.messages.INFO: 'info',
checks.messages.WARNING: 'warning',
checks.messages.ERROR: 'error',
checks.messages.CRITICAL: 'critical',
}
return statuses.get(level, 'unknown')
def check_migrations_applied(app_configs, **kwargs):
"""
A Django check to see if all migrations have been applied correctly.
"""
from django.db.migrations.loader import MigrationLoader
errors = []
# Load migrations from disk/DB
try:
loader = MigrationLoader(connection, ignore_no_migrations=True)
except (ImproperlyConfigured, ProgrammingError, OperationalError):
msg = "Can't connect to database to check migrations"
return [checks.Info(msg, id=health.INFO_CANT_CHECK_MIGRATIONS)]
if app_configs:
app_labels = [app.label for app in app_configs]
else:
app_labels = loader.migrated_apps
for node, migration in loader.graph.nodes.items():
if migration.app_label not in app_labels:
continue
if node not in loader.applied_migrations:
msg = 'Unapplied migration {}'.format(migration)
# NB: This *must* be a Warning, not an Error, because Errors
# prevent migrations from being run.
errors.append(checks.Warning(msg,
id=health.WARNING_UNAPPLIED_MIGRATION))
return errors
def check_redis_connected(app_configs, **kwargs):
"""
A Django check to connect to the default redis connection
using ``django_redis.get_redis_connection`` and see if Redis
responds to a ``PING`` command.
"""
import redis
from django_redis import get_redis_connection
errors = []
try:
connection = get_redis_connection('default')
except redis.ConnectionError as e:
msg = 'Could not connect to redis: {!s}'.format(e)
errors.append(checks.Error(msg, id=health.ERROR_CANNOT_CONNECT_REDIS))
except NotImplementedError as e:
msg = 'Redis client not available: {!s}'.format(e)
errors.append(checks.Error(msg, id=health.ERROR_MISSING_REDIS_CLIENT))
except ImproperlyConfigured as e:
msg = 'Redis misconfigured: "{!s}"'.format(e)
errors.append(checks.Error(msg, id=health.ERROR_MISCONFIGURED_REDIS))
else:
result = connection.ping()
if not result:
msg = 'Redis ping failed'
errors.append(checks.Error(msg, id=health.ERROR_REDIS_PING_FAILED))
return errors
def register():
check_paths = getattr(settings, 'DOCKERFLOW_CHECKS', [
'dockerflow.django.checks.check_database_connected',
'dockerflow.django.checks.check_migrations_applied',
# 'dockerflow.django.checks.check_redis_connected',
])
for check_path in check_paths:
check = import_string(check_path)
checks.register(check)
|
mozilla-services/python-dockerflow
|
src/dockerflow/django/checks.py
|
check_migrations_applied
|
python
|
def check_migrations_applied(app_configs, **kwargs):
from django.db.migrations.loader import MigrationLoader
errors = []
# Load migrations from disk/DB
try:
loader = MigrationLoader(connection, ignore_no_migrations=True)
except (ImproperlyConfigured, ProgrammingError, OperationalError):
msg = "Can't connect to database to check migrations"
return [checks.Info(msg, id=health.INFO_CANT_CHECK_MIGRATIONS)]
if app_configs:
app_labels = [app.label for app in app_configs]
else:
app_labels = loader.migrated_apps
for node, migration in loader.graph.nodes.items():
if migration.app_label not in app_labels:
continue
if node not in loader.applied_migrations:
msg = 'Unapplied migration {}'.format(migration)
# NB: This *must* be a Warning, not an Error, because Errors
# prevent migrations from being run.
errors.append(checks.Warning(msg,
id=health.WARNING_UNAPPLIED_MIGRATION))
return errors
|
A Django check to see if all migrations have been applied correctly.
|
train
|
https://github.com/mozilla-services/python-dockerflow/blob/43703c5e8934ba6901b0a1520d6da4ed6457208c/src/dockerflow/django/checks.py#L51-L80
| null |
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, you can obtain one at http://mozilla.org/MPL/2.0/.
from django.conf import settings
from django.core import checks
from django.core.exceptions import ImproperlyConfigured
from django.db import connection
from django.db.utils import OperationalError, ProgrammingError
from django.utils.module_loading import import_string
from .. import health
def level_to_text(level):
statuses = {
0: 'ok',
checks.messages.DEBUG: 'debug',
checks.messages.INFO: 'info',
checks.messages.WARNING: 'warning',
checks.messages.ERROR: 'error',
checks.messages.CRITICAL: 'critical',
}
return statuses.get(level, 'unknown')
def check_database_connected(app_configs, **kwargs):
"""
A Django check to see if connecting to the configured default
database backend succeeds.
"""
errors = []
try:
connection.ensure_connection()
except OperationalError as e:
msg = 'Could not connect to database: {!s}'.format(e)
errors.append(checks.Error(msg,
id=health.ERROR_CANNOT_CONNECT_DATABASE))
except ImproperlyConfigured as e:
msg = 'Datbase misconfigured: "{!s}"'.format(e)
errors.append(checks.Error(msg,
id=health.ERROR_MISCONFIGURED_DATABASE))
else:
if not connection.is_usable():
errors.append(checks.Error('Database connection is not usable',
id=health.ERROR_UNUSABLE_DATABASE))
return errors
def check_redis_connected(app_configs, **kwargs):
"""
A Django check to connect to the default redis connection
using ``django_redis.get_redis_connection`` and see if Redis
responds to a ``PING`` command.
"""
import redis
from django_redis import get_redis_connection
errors = []
try:
connection = get_redis_connection('default')
except redis.ConnectionError as e:
msg = 'Could not connect to redis: {!s}'.format(e)
errors.append(checks.Error(msg, id=health.ERROR_CANNOT_CONNECT_REDIS))
except NotImplementedError as e:
msg = 'Redis client not available: {!s}'.format(e)
errors.append(checks.Error(msg, id=health.ERROR_MISSING_REDIS_CLIENT))
except ImproperlyConfigured as e:
msg = 'Redis misconfigured: "{!s}"'.format(e)
errors.append(checks.Error(msg, id=health.ERROR_MISCONFIGURED_REDIS))
else:
result = connection.ping()
if not result:
msg = 'Redis ping failed'
errors.append(checks.Error(msg, id=health.ERROR_REDIS_PING_FAILED))
return errors
def register():
check_paths = getattr(settings, 'DOCKERFLOW_CHECKS', [
'dockerflow.django.checks.check_database_connected',
'dockerflow.django.checks.check_migrations_applied',
# 'dockerflow.django.checks.check_redis_connected',
])
for check_path in check_paths:
check = import_string(check_path)
checks.register(check)
|
mozilla-services/python-dockerflow
|
src/dockerflow/django/checks.py
|
check_redis_connected
|
python
|
def check_redis_connected(app_configs, **kwargs):
import redis
from django_redis import get_redis_connection
errors = []
try:
connection = get_redis_connection('default')
except redis.ConnectionError as e:
msg = 'Could not connect to redis: {!s}'.format(e)
errors.append(checks.Error(msg, id=health.ERROR_CANNOT_CONNECT_REDIS))
except NotImplementedError as e:
msg = 'Redis client not available: {!s}'.format(e)
errors.append(checks.Error(msg, id=health.ERROR_MISSING_REDIS_CLIENT))
except ImproperlyConfigured as e:
msg = 'Redis misconfigured: "{!s}"'.format(e)
errors.append(checks.Error(msg, id=health.ERROR_MISCONFIGURED_REDIS))
else:
result = connection.ping()
if not result:
msg = 'Redis ping failed'
errors.append(checks.Error(msg, id=health.ERROR_REDIS_PING_FAILED))
return errors
|
A Django check to connect to the default redis connection
using ``django_redis.get_redis_connection`` and see if Redis
responds to a ``PING`` command.
|
train
|
https://github.com/mozilla-services/python-dockerflow/blob/43703c5e8934ba6901b0a1520d6da4ed6457208c/src/dockerflow/django/checks.py#L83-L109
| null |
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, you can obtain one at http://mozilla.org/MPL/2.0/.
from django.conf import settings
from django.core import checks
from django.core.exceptions import ImproperlyConfigured
from django.db import connection
from django.db.utils import OperationalError, ProgrammingError
from django.utils.module_loading import import_string
from .. import health
def level_to_text(level):
statuses = {
0: 'ok',
checks.messages.DEBUG: 'debug',
checks.messages.INFO: 'info',
checks.messages.WARNING: 'warning',
checks.messages.ERROR: 'error',
checks.messages.CRITICAL: 'critical',
}
return statuses.get(level, 'unknown')
def check_database_connected(app_configs, **kwargs):
"""
A Django check to see if connecting to the configured default
database backend succeeds.
"""
errors = []
try:
connection.ensure_connection()
except OperationalError as e:
msg = 'Could not connect to database: {!s}'.format(e)
errors.append(checks.Error(msg,
id=health.ERROR_CANNOT_CONNECT_DATABASE))
except ImproperlyConfigured as e:
msg = 'Datbase misconfigured: "{!s}"'.format(e)
errors.append(checks.Error(msg,
id=health.ERROR_MISCONFIGURED_DATABASE))
else:
if not connection.is_usable():
errors.append(checks.Error('Database connection is not usable',
id=health.ERROR_UNUSABLE_DATABASE))
return errors
def check_migrations_applied(app_configs, **kwargs):
"""
A Django check to see if all migrations have been applied correctly.
"""
from django.db.migrations.loader import MigrationLoader
errors = []
# Load migrations from disk/DB
try:
loader = MigrationLoader(connection, ignore_no_migrations=True)
except (ImproperlyConfigured, ProgrammingError, OperationalError):
msg = "Can't connect to database to check migrations"
return [checks.Info(msg, id=health.INFO_CANT_CHECK_MIGRATIONS)]
if app_configs:
app_labels = [app.label for app in app_configs]
else:
app_labels = loader.migrated_apps
for node, migration in loader.graph.nodes.items():
if migration.app_label not in app_labels:
continue
if node not in loader.applied_migrations:
msg = 'Unapplied migration {}'.format(migration)
# NB: This *must* be a Warning, not an Error, because Errors
# prevent migrations from being run.
errors.append(checks.Warning(msg,
id=health.WARNING_UNAPPLIED_MIGRATION))
return errors
def register():
check_paths = getattr(settings, 'DOCKERFLOW_CHECKS', [
'dockerflow.django.checks.check_database_connected',
'dockerflow.django.checks.check_migrations_applied',
# 'dockerflow.django.checks.check_redis_connected',
])
for check_path in check_paths:
check = import_string(check_path)
checks.register(check)
|
mozilla-services/python-dockerflow
|
src/dockerflow/flask/app.py
|
Dockerflow.init_check
|
python
|
def init_check(self, check, obj):
self.logger.info('Adding extension check %s' % check.__name__)
check = functools.wraps(check)(functools.partial(check, obj))
self.check(func=check)
|
Adds a given check callback with the provided object to the list
of checks. Useful for built-ins but also advanced custom checks.
|
train
|
https://github.com/mozilla-services/python-dockerflow/blob/43703c5e8934ba6901b0a1520d6da4ed6457208c/src/dockerflow/flask/app.py#L135-L142
|
[
"def check(self, func=None, name=None):\n \"\"\"\n A decorator to register a new Dockerflow check to be run\n when the /__heartbeat__ endpoint is called., e.g.::\n\n from dockerflow.flask import checks\n\n @dockerflow.check\n def storage_reachable():\n try:\n acme.storage.ping()\n except SlowConnectionException as exc:\n return [checks.Warning(exc.msg, id='acme.health.0002')]\n except StorageException as exc:\n return [checks.Error(exc.msg, id='acme.health.0001')]\n\n or using a custom name::\n\n @dockerflow.check(name='acme-storage-check)\n def storage_reachable():\n # ...\n\n \"\"\"\n if func is None:\n return functools.partial(self.check, name=name)\n\n if name is None:\n name = func.__name__\n\n self.logger.info('Registered Dockerflow check %s', name)\n\n @functools.wraps(func)\n def decorated_function(*args, **kwargs):\n self.logger.info('Called Dockerflow check %s', name)\n return func(*args, **kwargs)\n\n self.checks[name] = decorated_function\n return decorated_function\n"
] |
class Dockerflow(object):
"""
The Dockerflow Flask extension. Set it up like this:
.. code-block:: python
:caption: ``myproject.py``
from flask import Flask
from dockerflow.flask import Dockerflow
app = Flask(__name__)
dockerflow = Dockerflow(app)
Or if you use the Flask application factory pattern, in
an own module set up Dockerflow first:
.. code-block:: python
:caption: ``myproject/deployment.py``
from dockerflow.flask import Dockerflow
dockerflow = Dockerflow()
and then import and initialize it with the Flask application
object when you create the application:
.. code-block:: python
:caption: ``myproject/app.py``
def create_app(config_filename):
app = Flask(__name__)
app.config.from_pyfile(config_filename)
from myproject.deployment import dockerflow
dockerflow.init_app(app)
from myproject.views.admin import admin
from myproject.views.frontend import frontend
app.register_blueprint(admin)
app.register_blueprint(frontend)
return app
See the parameters for a more detailed list of optional features when
initializing the extension.
:param app: The Flask app that this Dockerflow extension should be
initialized with.
:type root: ~flask.Flask or None
:param db: A Flask-SQLAlchemy extension instance to be used by the
built-in Dockerflow check for the database connection.
:param redis: A Redis connection to be used by the built-in Dockerflow
check for the Redis connection.
:param migrate: A Flask-Migrate extension instance to be used by the
built-in Dockerflow check for Alembic migrations.
:param silenced_checks: Dockerflow check IDs to ignore when running
through the list of configured checks.
:type silenced_checks: list
:param version_path: The filesystem path where the ``version.json`` can
be found. Defaults to the parent directory of the
Flask app's root path.
"""
def __init__(self, app=None, db=None, redis=None, migrate=None,
silenced_checks=None, version_path=None, *args, **kwargs):
# The Flask blueprint to add the Dockerflow signal callbacks and views
self._blueprint = Blueprint('dockerflow', 'dockerflow.flask.app')
# The Dockerflow specific logger to be used by internals of this
# extension.
self.logger = logging.getLogger('dockerflow.flask')
self.logger.addHandler(logging.NullHandler())
self.logger.setLevel(logging.INFO)
# The request summary logger to be used by this extension
# without pre-configuration. See docs for how to set it up.
self.summary_logger = logging.getLogger('request.summary')
# An ordered dictionary for storing custom Dockerflow checks in.
self.checks = OrderedDict()
# A list of IDs of custom Dockerflow checks to ignore in case they
# show up.
self.silenced_checks = silenced_checks or []
# The path where to find the version JSON file. Defaults to the
# parent directory of the app root path.
self.version_path = version_path
self._version_callback = version.get_version
# Initialize the app if given.
if app:
self.init_app(app)
# Initialize the built-in checks.
if db:
self.init_check(checks.check_database_connected, db)
if redis:
self.init_check(checks.check_redis_connected, redis)
if migrate:
self.init_check(checks.check_migrations_applied, migrate)
def init_app(self, app):
"""
Initializes the extension with the given app, registers the
built-in views with an own blueprint and hooks up our signal
callbacks.
"""
# If no version path was provided in the init of the Dockerflow
# class we'll use the parent directory of the app root path.
if self.version_path is None:
self.version_path = os.path.dirname(app.root_path)
for view in (
('/__version__', 'version', self._version_view),
('/__heartbeat__', 'heartbeat', self._heartbeat_view),
('/__lbheartbeat__', 'lbheartbeat', self._lbheartbeat_view),
):
self._blueprint.add_url_rule(*view)
self._blueprint.before_app_request(self._before_request)
self._blueprint.after_app_request(self._after_request)
self._blueprint.app_errorhandler(HeartbeatFailure)(self._heartbeat_exception_handler)
app.register_blueprint(self._blueprint)
got_request_exception.connect(self._got_request_exception, sender=app)
if not hasattr(app, 'extensions'): # pragma: nocover
app.extensions = {}
app.extensions['dockerflow'] = self
def _heartbeat_exception_handler(self, error):
"""
An exception handler to act as a middleman to return
a heartbeat view response with a 500 error code.
"""
return error.get_response()
def _before_request(self):
"""
The before_request callback.
"""
g._request_id = str(uuid.uuid4())
g._start_timestamp = time.time()
def _after_request(self, response):
"""
The signal handler for the request_finished signal.
"""
if not getattr(g, '_has_exception', False):
extra = self.summary_extra()
self.summary_logger.info('', extra=extra)
return response
def _got_request_exception(self, sender, exception, **extra):
"""
The signal handler for the got_request_exception signal.
"""
extra = self.summary_extra()
extra['errno'] = 500
self.summary_logger.error(str(exception), extra=extra)
g._has_exception = True
def user_id(self):
"""
Return the ID of the current request's user
"""
# This needs flask-login to be installed
if not has_flask_login:
return
# and the actual login manager installed
if not hasattr(current_app, 'login_manager'):
return
# fail if no current_user was attached to the request context
try:
is_authenticated = current_user.is_authenticated
except AttributeError:
return
# because is_authenticated could be a callable, call it
if callable(is_authenticated):
is_authenticated = is_authenticated()
# and fail if the user isn't authenticated
if not is_authenticated:
return
# finally return the user id
return current_user.get_id()
def summary_extra(self):
"""
Build the extra data for the summary logger.
"""
out = {
'errno': 0,
'agent': request.headers.get('User-Agent', ''),
'lang': request.headers.get('Accept-Language', ''),
'method': request.method,
'path': request.path,
}
# set the uid value to the current user ID
user_id = self.user_id()
if user_id is None:
user_id = ''
out['uid'] = user_id
# the rid value to the current request ID
request_id = g.get('_request_id', None)
if request_id is not None:
out['rid'] = request_id
# and the t value to the time it took to render
start_timestamp = g.get('_start_timestamp', None)
if start_timestamp is not None:
# Duration of request, in milliseconds.
out['t'] = int(1000 * (time.time() - start_timestamp))
return out
def _version_view(self):
"""
View that returns the contents of version.json or a 404.
"""
version_json = self._version_callback(self.version_path)
if version_json is None:
return 'version.json not found', 404
else:
return jsonify(version_json)
def _lbheartbeat_view(self):
"""
Lets the load balancer know the application is running and available.
Must return 200 (not 204) for ELB
http://docs.aws.amazon.com/ElasticLoadBalancing/latest/DeveloperGuide/elb-healthchecks.html
"""
return '', 200
def _heartbeat_check_detail(self, check):
errors = list(filter(lambda e: e.id not in self.silenced_checks, check()))
level = max([0] + [e.level for e in errors])
return {
'status': checks.level_to_text(level),
'level': level,
'messages': {e.id: e.msg for e in errors},
}
def _heartbeat_view(self):
"""
Runs all the registered checks and returns a JSON response with either
a status code of 200 or 500 depending on the results of the checks.
Any check that returns a warning or worse (error, critical) will
return a 500 response.
"""
details = {}
statuses = {}
level = 0
for name, check in self.checks.items():
detail = self._heartbeat_check_detail(check)
statuses[name] = detail['status']
level = max(level, detail['level'])
if detail['level'] > 0:
details[name] = detail
payload = {
'status': checks.level_to_text(level),
'checks': statuses,
'details': details,
}
def render(status_code):
return make_response(jsonify(payload), status_code)
if level < checks.WARNING:
status_code = 200
heartbeat_passed.send(self, level=level)
return render(status_code)
else:
status_code = 500
heartbeat_failed.send(self, level=level)
raise HeartbeatFailure(response=render(status_code))
def version_callback(self, func):
"""
A decorator to optionally register a new Dockerflow version callback
and use that instead of the default of
:func:`dockerflow.version.get_version`.
The callback will be passed the value of the
``version_path`` parameter to the Dockerflow extension object,
which defaults to the parent directory of the Flask app's root path.
The callback should return a dictionary with the
version information as defined in the Dockerflow spec,
or None if no version information could be loaded.
E.g.::
app = Flask(__name__)
dockerflow = Dockerflow(app)
@dockerflow.version_callback
def my_version(root):
return json.loads(os.path.join(root, 'acme_version.json'))
"""
self._version_callback = func
def check(self, func=None, name=None):
"""
A decorator to register a new Dockerflow check to be run
when the /__heartbeat__ endpoint is called., e.g.::
from dockerflow.flask import checks
@dockerflow.check
def storage_reachable():
try:
acme.storage.ping()
except SlowConnectionException as exc:
return [checks.Warning(exc.msg, id='acme.health.0002')]
except StorageException as exc:
return [checks.Error(exc.msg, id='acme.health.0001')]
or using a custom name::
@dockerflow.check(name='acme-storage-check)
def storage_reachable():
# ...
"""
if func is None:
return functools.partial(self.check, name=name)
if name is None:
name = func.__name__
self.logger.info('Registered Dockerflow check %s', name)
@functools.wraps(func)
def decorated_function(*args, **kwargs):
self.logger.info('Called Dockerflow check %s', name)
return func(*args, **kwargs)
self.checks[name] = decorated_function
return decorated_function
|
mozilla-services/python-dockerflow
|
src/dockerflow/flask/app.py
|
Dockerflow.init_app
|
python
|
def init_app(self, app):
# If no version path was provided in the init of the Dockerflow
# class we'll use the parent directory of the app root path.
if self.version_path is None:
self.version_path = os.path.dirname(app.root_path)
for view in (
('/__version__', 'version', self._version_view),
('/__heartbeat__', 'heartbeat', self._heartbeat_view),
('/__lbheartbeat__', 'lbheartbeat', self._lbheartbeat_view),
):
self._blueprint.add_url_rule(*view)
self._blueprint.before_app_request(self._before_request)
self._blueprint.after_app_request(self._after_request)
self._blueprint.app_errorhandler(HeartbeatFailure)(self._heartbeat_exception_handler)
app.register_blueprint(self._blueprint)
got_request_exception.connect(self._got_request_exception, sender=app)
if not hasattr(app, 'extensions'): # pragma: nocover
app.extensions = {}
app.extensions['dockerflow'] = self
|
Initializes the extension with the given app, registers the
built-in views with an own blueprint and hooks up our signal
callbacks.
|
train
|
https://github.com/mozilla-services/python-dockerflow/blob/43703c5e8934ba6901b0a1520d6da4ed6457208c/src/dockerflow/flask/app.py#L144-L169
| null |
class Dockerflow(object):
"""
The Dockerflow Flask extension. Set it up like this:
.. code-block:: python
:caption: ``myproject.py``
from flask import Flask
from dockerflow.flask import Dockerflow
app = Flask(__name__)
dockerflow = Dockerflow(app)
Or if you use the Flask application factory pattern, in
an own module set up Dockerflow first:
.. code-block:: python
:caption: ``myproject/deployment.py``
from dockerflow.flask import Dockerflow
dockerflow = Dockerflow()
and then import and initialize it with the Flask application
object when you create the application:
.. code-block:: python
:caption: ``myproject/app.py``
def create_app(config_filename):
app = Flask(__name__)
app.config.from_pyfile(config_filename)
from myproject.deployment import dockerflow
dockerflow.init_app(app)
from myproject.views.admin import admin
from myproject.views.frontend import frontend
app.register_blueprint(admin)
app.register_blueprint(frontend)
return app
See the parameters for a more detailed list of optional features when
initializing the extension.
:param app: The Flask app that this Dockerflow extension should be
initialized with.
:type root: ~flask.Flask or None
:param db: A Flask-SQLAlchemy extension instance to be used by the
built-in Dockerflow check for the database connection.
:param redis: A Redis connection to be used by the built-in Dockerflow
check for the Redis connection.
:param migrate: A Flask-Migrate extension instance to be used by the
built-in Dockerflow check for Alembic migrations.
:param silenced_checks: Dockerflow check IDs to ignore when running
through the list of configured checks.
:type silenced_checks: list
:param version_path: The filesystem path where the ``version.json`` can
be found. Defaults to the parent directory of the
Flask app's root path.
"""
def __init__(self, app=None, db=None, redis=None, migrate=None,
silenced_checks=None, version_path=None, *args, **kwargs):
# The Flask blueprint to add the Dockerflow signal callbacks and views
self._blueprint = Blueprint('dockerflow', 'dockerflow.flask.app')
# The Dockerflow specific logger to be used by internals of this
# extension.
self.logger = logging.getLogger('dockerflow.flask')
self.logger.addHandler(logging.NullHandler())
self.logger.setLevel(logging.INFO)
# The request summary logger to be used by this extension
# without pre-configuration. See docs for how to set it up.
self.summary_logger = logging.getLogger('request.summary')
# An ordered dictionary for storing custom Dockerflow checks in.
self.checks = OrderedDict()
# A list of IDs of custom Dockerflow checks to ignore in case they
# show up.
self.silenced_checks = silenced_checks or []
# The path where to find the version JSON file. Defaults to the
# parent directory of the app root path.
self.version_path = version_path
self._version_callback = version.get_version
# Initialize the app if given.
if app:
self.init_app(app)
# Initialize the built-in checks.
if db:
self.init_check(checks.check_database_connected, db)
if redis:
self.init_check(checks.check_redis_connected, redis)
if migrate:
self.init_check(checks.check_migrations_applied, migrate)
def init_check(self, check, obj):
"""
Adds a given check callback with the provided object to the list
of checks. Useful for built-ins but also advanced custom checks.
"""
self.logger.info('Adding extension check %s' % check.__name__)
check = functools.wraps(check)(functools.partial(check, obj))
self.check(func=check)
def _heartbeat_exception_handler(self, error):
"""
An exception handler to act as a middleman to return
a heartbeat view response with a 500 error code.
"""
return error.get_response()
def _before_request(self):
"""
The before_request callback.
"""
g._request_id = str(uuid.uuid4())
g._start_timestamp = time.time()
def _after_request(self, response):
"""
The signal handler for the request_finished signal.
"""
if not getattr(g, '_has_exception', False):
extra = self.summary_extra()
self.summary_logger.info('', extra=extra)
return response
def _got_request_exception(self, sender, exception, **extra):
"""
The signal handler for the got_request_exception signal.
"""
extra = self.summary_extra()
extra['errno'] = 500
self.summary_logger.error(str(exception), extra=extra)
g._has_exception = True
def user_id(self):
"""
Return the ID of the current request's user
"""
# This needs flask-login to be installed
if not has_flask_login:
return
# and the actual login manager installed
if not hasattr(current_app, 'login_manager'):
return
# fail if no current_user was attached to the request context
try:
is_authenticated = current_user.is_authenticated
except AttributeError:
return
# because is_authenticated could be a callable, call it
if callable(is_authenticated):
is_authenticated = is_authenticated()
# and fail if the user isn't authenticated
if not is_authenticated:
return
# finally return the user id
return current_user.get_id()
def summary_extra(self):
"""
Build the extra data for the summary logger.
"""
out = {
'errno': 0,
'agent': request.headers.get('User-Agent', ''),
'lang': request.headers.get('Accept-Language', ''),
'method': request.method,
'path': request.path,
}
# set the uid value to the current user ID
user_id = self.user_id()
if user_id is None:
user_id = ''
out['uid'] = user_id
# the rid value to the current request ID
request_id = g.get('_request_id', None)
if request_id is not None:
out['rid'] = request_id
# and the t value to the time it took to render
start_timestamp = g.get('_start_timestamp', None)
if start_timestamp is not None:
# Duration of request, in milliseconds.
out['t'] = int(1000 * (time.time() - start_timestamp))
return out
def _version_view(self):
"""
View that returns the contents of version.json or a 404.
"""
version_json = self._version_callback(self.version_path)
if version_json is None:
return 'version.json not found', 404
else:
return jsonify(version_json)
def _lbheartbeat_view(self):
"""
Lets the load balancer know the application is running and available.
Must return 200 (not 204) for ELB
http://docs.aws.amazon.com/ElasticLoadBalancing/latest/DeveloperGuide/elb-healthchecks.html
"""
return '', 200
def _heartbeat_check_detail(self, check):
errors = list(filter(lambda e: e.id not in self.silenced_checks, check()))
level = max([0] + [e.level for e in errors])
return {
'status': checks.level_to_text(level),
'level': level,
'messages': {e.id: e.msg for e in errors},
}
def _heartbeat_view(self):
"""
Runs all the registered checks and returns a JSON response with either
a status code of 200 or 500 depending on the results of the checks.
Any check that returns a warning or worse (error, critical) will
return a 500 response.
"""
details = {}
statuses = {}
level = 0
for name, check in self.checks.items():
detail = self._heartbeat_check_detail(check)
statuses[name] = detail['status']
level = max(level, detail['level'])
if detail['level'] > 0:
details[name] = detail
payload = {
'status': checks.level_to_text(level),
'checks': statuses,
'details': details,
}
def render(status_code):
return make_response(jsonify(payload), status_code)
if level < checks.WARNING:
status_code = 200
heartbeat_passed.send(self, level=level)
return render(status_code)
else:
status_code = 500
heartbeat_failed.send(self, level=level)
raise HeartbeatFailure(response=render(status_code))
def version_callback(self, func):
"""
A decorator to optionally register a new Dockerflow version callback
and use that instead of the default of
:func:`dockerflow.version.get_version`.
The callback will be passed the value of the
``version_path`` parameter to the Dockerflow extension object,
which defaults to the parent directory of the Flask app's root path.
The callback should return a dictionary with the
version information as defined in the Dockerflow spec,
or None if no version information could be loaded.
E.g.::
app = Flask(__name__)
dockerflow = Dockerflow(app)
@dockerflow.version_callback
def my_version(root):
return json.loads(os.path.join(root, 'acme_version.json'))
"""
self._version_callback = func
def check(self, func=None, name=None):
"""
A decorator to register a new Dockerflow check to be run
when the /__heartbeat__ endpoint is called., e.g.::
from dockerflow.flask import checks
@dockerflow.check
def storage_reachable():
try:
acme.storage.ping()
except SlowConnectionException as exc:
return [checks.Warning(exc.msg, id='acme.health.0002')]
except StorageException as exc:
return [checks.Error(exc.msg, id='acme.health.0001')]
or using a custom name::
@dockerflow.check(name='acme-storage-check)
def storage_reachable():
# ...
"""
if func is None:
return functools.partial(self.check, name=name)
if name is None:
name = func.__name__
self.logger.info('Registered Dockerflow check %s', name)
@functools.wraps(func)
def decorated_function(*args, **kwargs):
self.logger.info('Called Dockerflow check %s', name)
return func(*args, **kwargs)
self.checks[name] = decorated_function
return decorated_function
|
mozilla-services/python-dockerflow
|
src/dockerflow/flask/app.py
|
Dockerflow._before_request
|
python
|
def _before_request(self):
g._request_id = str(uuid.uuid4())
g._start_timestamp = time.time()
|
The before_request callback.
|
train
|
https://github.com/mozilla-services/python-dockerflow/blob/43703c5e8934ba6901b0a1520d6da4ed6457208c/src/dockerflow/flask/app.py#L178-L183
| null |
class Dockerflow(object):
"""
The Dockerflow Flask extension. Set it up like this:
.. code-block:: python
:caption: ``myproject.py``
from flask import Flask
from dockerflow.flask import Dockerflow
app = Flask(__name__)
dockerflow = Dockerflow(app)
Or if you use the Flask application factory pattern, in
an own module set up Dockerflow first:
.. code-block:: python
:caption: ``myproject/deployment.py``
from dockerflow.flask import Dockerflow
dockerflow = Dockerflow()
and then import and initialize it with the Flask application
object when you create the application:
.. code-block:: python
:caption: ``myproject/app.py``
def create_app(config_filename):
app = Flask(__name__)
app.config.from_pyfile(config_filename)
from myproject.deployment import dockerflow
dockerflow.init_app(app)
from myproject.views.admin import admin
from myproject.views.frontend import frontend
app.register_blueprint(admin)
app.register_blueprint(frontend)
return app
See the parameters for a more detailed list of optional features when
initializing the extension.
:param app: The Flask app that this Dockerflow extension should be
initialized with.
:type root: ~flask.Flask or None
:param db: A Flask-SQLAlchemy extension instance to be used by the
built-in Dockerflow check for the database connection.
:param redis: A Redis connection to be used by the built-in Dockerflow
check for the Redis connection.
:param migrate: A Flask-Migrate extension instance to be used by the
built-in Dockerflow check for Alembic migrations.
:param silenced_checks: Dockerflow check IDs to ignore when running
through the list of configured checks.
:type silenced_checks: list
:param version_path: The filesystem path where the ``version.json`` can
be found. Defaults to the parent directory of the
Flask app's root path.
"""
def __init__(self, app=None, db=None, redis=None, migrate=None,
silenced_checks=None, version_path=None, *args, **kwargs):
# The Flask blueprint to add the Dockerflow signal callbacks and views
self._blueprint = Blueprint('dockerflow', 'dockerflow.flask.app')
# The Dockerflow specific logger to be used by internals of this
# extension.
self.logger = logging.getLogger('dockerflow.flask')
self.logger.addHandler(logging.NullHandler())
self.logger.setLevel(logging.INFO)
# The request summary logger to be used by this extension
# without pre-configuration. See docs for how to set it up.
self.summary_logger = logging.getLogger('request.summary')
# An ordered dictionary for storing custom Dockerflow checks in.
self.checks = OrderedDict()
# A list of IDs of custom Dockerflow checks to ignore in case they
# show up.
self.silenced_checks = silenced_checks or []
# The path where to find the version JSON file. Defaults to the
# parent directory of the app root path.
self.version_path = version_path
self._version_callback = version.get_version
# Initialize the app if given.
if app:
self.init_app(app)
# Initialize the built-in checks.
if db:
self.init_check(checks.check_database_connected, db)
if redis:
self.init_check(checks.check_redis_connected, redis)
if migrate:
self.init_check(checks.check_migrations_applied, migrate)
def init_check(self, check, obj):
"""
Adds a given check callback with the provided object to the list
of checks. Useful for built-ins but also advanced custom checks.
"""
self.logger.info('Adding extension check %s' % check.__name__)
check = functools.wraps(check)(functools.partial(check, obj))
self.check(func=check)
def init_app(self, app):
"""
Initializes the extension with the given app, registers the
built-in views with an own blueprint and hooks up our signal
callbacks.
"""
# If no version path was provided in the init of the Dockerflow
# class we'll use the parent directory of the app root path.
if self.version_path is None:
self.version_path = os.path.dirname(app.root_path)
for view in (
('/__version__', 'version', self._version_view),
('/__heartbeat__', 'heartbeat', self._heartbeat_view),
('/__lbheartbeat__', 'lbheartbeat', self._lbheartbeat_view),
):
self._blueprint.add_url_rule(*view)
self._blueprint.before_app_request(self._before_request)
self._blueprint.after_app_request(self._after_request)
self._blueprint.app_errorhandler(HeartbeatFailure)(self._heartbeat_exception_handler)
app.register_blueprint(self._blueprint)
got_request_exception.connect(self._got_request_exception, sender=app)
if not hasattr(app, 'extensions'): # pragma: nocover
app.extensions = {}
app.extensions['dockerflow'] = self
def _heartbeat_exception_handler(self, error):
"""
An exception handler to act as a middleman to return
a heartbeat view response with a 500 error code.
"""
return error.get_response()
def _after_request(self, response):
"""
The signal handler for the request_finished signal.
"""
if not getattr(g, '_has_exception', False):
extra = self.summary_extra()
self.summary_logger.info('', extra=extra)
return response
def _got_request_exception(self, sender, exception, **extra):
"""
The signal handler for the got_request_exception signal.
"""
extra = self.summary_extra()
extra['errno'] = 500
self.summary_logger.error(str(exception), extra=extra)
g._has_exception = True
def user_id(self):
"""
Return the ID of the current request's user
"""
# This needs flask-login to be installed
if not has_flask_login:
return
# and the actual login manager installed
if not hasattr(current_app, 'login_manager'):
return
# fail if no current_user was attached to the request context
try:
is_authenticated = current_user.is_authenticated
except AttributeError:
return
# because is_authenticated could be a callable, call it
if callable(is_authenticated):
is_authenticated = is_authenticated()
# and fail if the user isn't authenticated
if not is_authenticated:
return
# finally return the user id
return current_user.get_id()
def summary_extra(self):
"""
Build the extra data for the summary logger.
"""
out = {
'errno': 0,
'agent': request.headers.get('User-Agent', ''),
'lang': request.headers.get('Accept-Language', ''),
'method': request.method,
'path': request.path,
}
# set the uid value to the current user ID
user_id = self.user_id()
if user_id is None:
user_id = ''
out['uid'] = user_id
# the rid value to the current request ID
request_id = g.get('_request_id', None)
if request_id is not None:
out['rid'] = request_id
# and the t value to the time it took to render
start_timestamp = g.get('_start_timestamp', None)
if start_timestamp is not None:
# Duration of request, in milliseconds.
out['t'] = int(1000 * (time.time() - start_timestamp))
return out
def _version_view(self):
"""
View that returns the contents of version.json or a 404.
"""
version_json = self._version_callback(self.version_path)
if version_json is None:
return 'version.json not found', 404
else:
return jsonify(version_json)
def _lbheartbeat_view(self):
"""
Lets the load balancer know the application is running and available.
Must return 200 (not 204) for ELB
http://docs.aws.amazon.com/ElasticLoadBalancing/latest/DeveloperGuide/elb-healthchecks.html
"""
return '', 200
def _heartbeat_check_detail(self, check):
errors = list(filter(lambda e: e.id not in self.silenced_checks, check()))
level = max([0] + [e.level for e in errors])
return {
'status': checks.level_to_text(level),
'level': level,
'messages': {e.id: e.msg for e in errors},
}
def _heartbeat_view(self):
"""
Runs all the registered checks and returns a JSON response with either
a status code of 200 or 500 depending on the results of the checks.
Any check that returns a warning or worse (error, critical) will
return a 500 response.
"""
details = {}
statuses = {}
level = 0
for name, check in self.checks.items():
detail = self._heartbeat_check_detail(check)
statuses[name] = detail['status']
level = max(level, detail['level'])
if detail['level'] > 0:
details[name] = detail
payload = {
'status': checks.level_to_text(level),
'checks': statuses,
'details': details,
}
def render(status_code):
return make_response(jsonify(payload), status_code)
if level < checks.WARNING:
status_code = 200
heartbeat_passed.send(self, level=level)
return render(status_code)
else:
status_code = 500
heartbeat_failed.send(self, level=level)
raise HeartbeatFailure(response=render(status_code))
def version_callback(self, func):
"""
A decorator to optionally register a new Dockerflow version callback
and use that instead of the default of
:func:`dockerflow.version.get_version`.
The callback will be passed the value of the
``version_path`` parameter to the Dockerflow extension object,
which defaults to the parent directory of the Flask app's root path.
The callback should return a dictionary with the
version information as defined in the Dockerflow spec,
or None if no version information could be loaded.
E.g.::
app = Flask(__name__)
dockerflow = Dockerflow(app)
@dockerflow.version_callback
def my_version(root):
return json.loads(os.path.join(root, 'acme_version.json'))
"""
self._version_callback = func
def check(self, func=None, name=None):
"""
A decorator to register a new Dockerflow check to be run
when the /__heartbeat__ endpoint is called., e.g.::
from dockerflow.flask import checks
@dockerflow.check
def storage_reachable():
try:
acme.storage.ping()
except SlowConnectionException as exc:
return [checks.Warning(exc.msg, id='acme.health.0002')]
except StorageException as exc:
return [checks.Error(exc.msg, id='acme.health.0001')]
or using a custom name::
@dockerflow.check(name='acme-storage-check)
def storage_reachable():
# ...
"""
if func is None:
return functools.partial(self.check, name=name)
if name is None:
name = func.__name__
self.logger.info('Registered Dockerflow check %s', name)
@functools.wraps(func)
def decorated_function(*args, **kwargs):
self.logger.info('Called Dockerflow check %s', name)
return func(*args, **kwargs)
self.checks[name] = decorated_function
return decorated_function
|
mozilla-services/python-dockerflow
|
src/dockerflow/flask/app.py
|
Dockerflow._after_request
|
python
|
def _after_request(self, response):
if not getattr(g, '_has_exception', False):
extra = self.summary_extra()
self.summary_logger.info('', extra=extra)
return response
|
The signal handler for the request_finished signal.
|
train
|
https://github.com/mozilla-services/python-dockerflow/blob/43703c5e8934ba6901b0a1520d6da4ed6457208c/src/dockerflow/flask/app.py#L185-L192
| null |
class Dockerflow(object):
"""
The Dockerflow Flask extension. Set it up like this:
.. code-block:: python
:caption: ``myproject.py``
from flask import Flask
from dockerflow.flask import Dockerflow
app = Flask(__name__)
dockerflow = Dockerflow(app)
Or if you use the Flask application factory pattern, in
an own module set up Dockerflow first:
.. code-block:: python
:caption: ``myproject/deployment.py``
from dockerflow.flask import Dockerflow
dockerflow = Dockerflow()
and then import and initialize it with the Flask application
object when you create the application:
.. code-block:: python
:caption: ``myproject/app.py``
def create_app(config_filename):
app = Flask(__name__)
app.config.from_pyfile(config_filename)
from myproject.deployment import dockerflow
dockerflow.init_app(app)
from myproject.views.admin import admin
from myproject.views.frontend import frontend
app.register_blueprint(admin)
app.register_blueprint(frontend)
return app
See the parameters for a more detailed list of optional features when
initializing the extension.
:param app: The Flask app that this Dockerflow extension should be
initialized with.
:type root: ~flask.Flask or None
:param db: A Flask-SQLAlchemy extension instance to be used by the
built-in Dockerflow check for the database connection.
:param redis: A Redis connection to be used by the built-in Dockerflow
check for the Redis connection.
:param migrate: A Flask-Migrate extension instance to be used by the
built-in Dockerflow check for Alembic migrations.
:param silenced_checks: Dockerflow check IDs to ignore when running
through the list of configured checks.
:type silenced_checks: list
:param version_path: The filesystem path where the ``version.json`` can
be found. Defaults to the parent directory of the
Flask app's root path.
"""
def __init__(self, app=None, db=None, redis=None, migrate=None,
silenced_checks=None, version_path=None, *args, **kwargs):
# The Flask blueprint to add the Dockerflow signal callbacks and views
self._blueprint = Blueprint('dockerflow', 'dockerflow.flask.app')
# The Dockerflow specific logger to be used by internals of this
# extension.
self.logger = logging.getLogger('dockerflow.flask')
self.logger.addHandler(logging.NullHandler())
self.logger.setLevel(logging.INFO)
# The request summary logger to be used by this extension
# without pre-configuration. See docs for how to set it up.
self.summary_logger = logging.getLogger('request.summary')
# An ordered dictionary for storing custom Dockerflow checks in.
self.checks = OrderedDict()
# A list of IDs of custom Dockerflow checks to ignore in case they
# show up.
self.silenced_checks = silenced_checks or []
# The path where to find the version JSON file. Defaults to the
# parent directory of the app root path.
self.version_path = version_path
self._version_callback = version.get_version
# Initialize the app if given.
if app:
self.init_app(app)
# Initialize the built-in checks.
if db:
self.init_check(checks.check_database_connected, db)
if redis:
self.init_check(checks.check_redis_connected, redis)
if migrate:
self.init_check(checks.check_migrations_applied, migrate)
def init_check(self, check, obj):
"""
Adds a given check callback with the provided object to the list
of checks. Useful for built-ins but also advanced custom checks.
"""
self.logger.info('Adding extension check %s' % check.__name__)
check = functools.wraps(check)(functools.partial(check, obj))
self.check(func=check)
def init_app(self, app):
"""
Initializes the extension with the given app, registers the
built-in views with an own blueprint and hooks up our signal
callbacks.
"""
# If no version path was provided in the init of the Dockerflow
# class we'll use the parent directory of the app root path.
if self.version_path is None:
self.version_path = os.path.dirname(app.root_path)
for view in (
('/__version__', 'version', self._version_view),
('/__heartbeat__', 'heartbeat', self._heartbeat_view),
('/__lbheartbeat__', 'lbheartbeat', self._lbheartbeat_view),
):
self._blueprint.add_url_rule(*view)
self._blueprint.before_app_request(self._before_request)
self._blueprint.after_app_request(self._after_request)
self._blueprint.app_errorhandler(HeartbeatFailure)(self._heartbeat_exception_handler)
app.register_blueprint(self._blueprint)
got_request_exception.connect(self._got_request_exception, sender=app)
if not hasattr(app, 'extensions'): # pragma: nocover
app.extensions = {}
app.extensions['dockerflow'] = self
def _heartbeat_exception_handler(self, error):
"""
An exception handler to act as a middleman to return
a heartbeat view response with a 500 error code.
"""
return error.get_response()
def _before_request(self):
"""
The before_request callback.
"""
g._request_id = str(uuid.uuid4())
g._start_timestamp = time.time()
def _got_request_exception(self, sender, exception, **extra):
"""
The signal handler for the got_request_exception signal.
"""
extra = self.summary_extra()
extra['errno'] = 500
self.summary_logger.error(str(exception), extra=extra)
g._has_exception = True
def user_id(self):
"""
Return the ID of the current request's user
"""
# This needs flask-login to be installed
if not has_flask_login:
return
# and the actual login manager installed
if not hasattr(current_app, 'login_manager'):
return
# fail if no current_user was attached to the request context
try:
is_authenticated = current_user.is_authenticated
except AttributeError:
return
# because is_authenticated could be a callable, call it
if callable(is_authenticated):
is_authenticated = is_authenticated()
# and fail if the user isn't authenticated
if not is_authenticated:
return
# finally return the user id
return current_user.get_id()
def summary_extra(self):
"""
Build the extra data for the summary logger.
"""
out = {
'errno': 0,
'agent': request.headers.get('User-Agent', ''),
'lang': request.headers.get('Accept-Language', ''),
'method': request.method,
'path': request.path,
}
# set the uid value to the current user ID
user_id = self.user_id()
if user_id is None:
user_id = ''
out['uid'] = user_id
# the rid value to the current request ID
request_id = g.get('_request_id', None)
if request_id is not None:
out['rid'] = request_id
# and the t value to the time it took to render
start_timestamp = g.get('_start_timestamp', None)
if start_timestamp is not None:
# Duration of request, in milliseconds.
out['t'] = int(1000 * (time.time() - start_timestamp))
return out
def _version_view(self):
"""
View that returns the contents of version.json or a 404.
"""
version_json = self._version_callback(self.version_path)
if version_json is None:
return 'version.json not found', 404
else:
return jsonify(version_json)
def _lbheartbeat_view(self):
"""
Lets the load balancer know the application is running and available.
Must return 200 (not 204) for ELB
http://docs.aws.amazon.com/ElasticLoadBalancing/latest/DeveloperGuide/elb-healthchecks.html
"""
return '', 200
def _heartbeat_check_detail(self, check):
errors = list(filter(lambda e: e.id not in self.silenced_checks, check()))
level = max([0] + [e.level for e in errors])
return {
'status': checks.level_to_text(level),
'level': level,
'messages': {e.id: e.msg for e in errors},
}
def _heartbeat_view(self):
"""
Runs all the registered checks and returns a JSON response with either
a status code of 200 or 500 depending on the results of the checks.
Any check that returns a warning or worse (error, critical) will
return a 500 response.
"""
details = {}
statuses = {}
level = 0
for name, check in self.checks.items():
detail = self._heartbeat_check_detail(check)
statuses[name] = detail['status']
level = max(level, detail['level'])
if detail['level'] > 0:
details[name] = detail
payload = {
'status': checks.level_to_text(level),
'checks': statuses,
'details': details,
}
def render(status_code):
return make_response(jsonify(payload), status_code)
if level < checks.WARNING:
status_code = 200
heartbeat_passed.send(self, level=level)
return render(status_code)
else:
status_code = 500
heartbeat_failed.send(self, level=level)
raise HeartbeatFailure(response=render(status_code))
def version_callback(self, func):
"""
A decorator to optionally register a new Dockerflow version callback
and use that instead of the default of
:func:`dockerflow.version.get_version`.
The callback will be passed the value of the
``version_path`` parameter to the Dockerflow extension object,
which defaults to the parent directory of the Flask app's root path.
The callback should return a dictionary with the
version information as defined in the Dockerflow spec,
or None if no version information could be loaded.
E.g.::
app = Flask(__name__)
dockerflow = Dockerflow(app)
@dockerflow.version_callback
def my_version(root):
return json.loads(os.path.join(root, 'acme_version.json'))
"""
self._version_callback = func
def check(self, func=None, name=None):
"""
A decorator to register a new Dockerflow check to be run
when the /__heartbeat__ endpoint is called., e.g.::
from dockerflow.flask import checks
@dockerflow.check
def storage_reachable():
try:
acme.storage.ping()
except SlowConnectionException as exc:
return [checks.Warning(exc.msg, id='acme.health.0002')]
except StorageException as exc:
return [checks.Error(exc.msg, id='acme.health.0001')]
or using a custom name::
@dockerflow.check(name='acme-storage-check)
def storage_reachable():
# ...
"""
if func is None:
return functools.partial(self.check, name=name)
if name is None:
name = func.__name__
self.logger.info('Registered Dockerflow check %s', name)
@functools.wraps(func)
def decorated_function(*args, **kwargs):
self.logger.info('Called Dockerflow check %s', name)
return func(*args, **kwargs)
self.checks[name] = decorated_function
return decorated_function
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.