text
stringlengths
81
112k
Preprocess the input statement. def get_preprocessed_statement(self, input_statement): """ Preprocess the input statement. """ for preprocessor in self.chatbot.preprocessors: input_statement = preprocessor(input_statement) return input_statement
Create a file from the database that can be used to train other chat bots. def export_for_training(self, file_path='./export.json'): """ Create a file from the database that can be used to train other chat bots. """ import json export = {'conversations': self._ge...
Train the chat bot based on the provided list of statements that represents a single conversation. def train(self, conversation): """ Train the chat bot based on the provided list of statements that represents a single conversation. """ previous_statement_text = None ...
Check if the data file is already downloaded. def is_downloaded(self, file_path): """ Check if the data file is already downloaded. """ if os.path.exists(file_path): self.chatbot.logger.info('File is already downloaded') return True return False
Check if the data file is already extracted. def is_extracted(self, file_path): """ Check if the data file is already extracted. """ if os.path.isdir(file_path): self.chatbot.logger.info('File is already extracted') return True return False
Download a file from the given url. Show a progress indicator for the download status. Based on: http://stackoverflow.com/a/15645088/1547223 def download(self, url, show_status=True): """ Download a file from the given url. Show a progress indicator for the download status. ...
Extract a tar file at the specified file path. def extract(self, file_path): """ Extract a tar file at the specified file path. """ import tarfile print('Extracting {}'.format(file_path)) if not os.path.exists(self.extracted_data_directory): os.makedirs(sel...
Return the number of entries in the database. def count(self): """ Return the number of entries in the database. """ Statement = self.get_model('statement') session = self.Session() statement_count = session.query(Statement).count() session.close() retur...
Removes the statement that matches the input text. Removes any responses from statements where the response text matches the input text. def remove(self, statement_text): """ Removes the statement that matches the input text. Removes any responses from statements where the respo...
Returns a list of objects from the database. The kwargs parameter can contain any number of attributes. Only objects which contain all listed attributes and in which all values match for all listed attributes will be returned. def filter(self, **kwargs): """ Returns a li...
Creates a new statement matching the keyword arguments specified. Returns the created statement. def create(self, **kwargs): """ Creates a new statement matching the keyword arguments specified. Returns the created statement. """ Statement = self.get_model('statement') ...
Creates multiple statement entries. def create_many(self, statements): """ Creates multiple statement entries. """ Statement = self.get_model('statement') Tag = self.get_model('tag') session = self.Session() create_statements = [] create_tags = {} ...
Modifies an entry in the database. Creates an entry if one does not exist. def update(self, statement): """ Modifies an entry in the database. Creates an entry if one does not exist. """ Statement = self.get_model('statement') Tag = self.get_model('tag') ...
Returns a random statement from the database. def get_random(self): """ Returns a random statement from the database. """ import random Statement = self.get_model('statement') session = self.Session() count = self.count() if count < 1: raise...
Drop the database. def drop(self): """ Drop the database. """ Statement = self.get_model('statement') Tag = self.get_model('tag') session = self.Session() session.query(Statement).delete() session.query(Tag).delete() session.commit() se...
Populate the database with the tables. def create_database(self): """ Populate the database with the tables. """ from chatterbot.ext.sqlalchemy_app.models import Base Base.metadata.create_all(self.engine)
Return a response to the statement in the posted data. * The JSON data should contain a 'text' attribute. def post(self, request, *args, **kwargs): """ Return a response to the statement in the posted data. * The JSON data should contain a 'text' attribute. """ input_d...
Reads a dotted file path and returns the file path. def get_file_path(dotted_path, extension='json'): """ Reads a dotted file path and returns the file path. """ # If the operating system's file path seperator character is in the string if os.sep in dotted_path or '/' in dotted_path: # Assu...
Read and return the data from a corpus json file. def read_corpus(file_name): """ Read and return the data from a corpus json file. """ with io.open(file_name, encoding='utf-8') as data_file: return yaml.load(data_file)
Return a list of file paths to each data file in the specified corpus. def list_corpus_files(dotted_path): """ Return a list of file paths to each data file in the specified corpus. """ corpus_path = get_file_path(dotted_path, extension=CORPUS_EXTENSION) paths = [] if os.path.isdir(corpus_path...
Return the data contained within a specified corpus. def load_corpus(*data_file_paths): """ Return the data contained within a specified corpus. """ for file_path in data_file_paths: corpus = [] corpus_data = read_corpus(file_path) conversations = corpus_data.get('conversations...
Return a string of text containing part-of-speech, lemma pairs. def get_bigram_pair_string(self, text): """ Return a string of text containing part-of-speech, lemma pairs. """ bigram_pairs = [] if len(text) <= 2: text_without_punctuation = text.translate(self.punctu...
Returns a list of statements in the database that match the parameters specified. def filter(self, **kwargs): """ Returns a list of statements in the database that match the parameters specified. """ from django.db.models import Q Statement = self.get_model('sta...
Creates a new statement matching the keyword arguments specified. Returns the created statement. def create(self, **kwargs): """ Creates a new statement matching the keyword arguments specified. Returns the created statement. """ Statement = self.get_model('statement') ...
Creates multiple statement entries. def create_many(self, statements): """ Creates multiple statement entries. """ Statement = self.get_model('statement') Tag = self.get_model('tag') tag_cache = {} for statement in statements: statement_data = stat...
Update the provided statement. def update(self, statement): """ Update the provided statement. """ Statement = self.get_model('statement') Tag = self.get_model('tag') if hasattr(statement, 'id'): statement.save() else: statement = Stateme...
Returns a random statement from the database def get_random(self): """ Returns a random statement from the database """ Statement = self.get_model('statement') statement = Statement.objects.order_by('?').first() if statement is None: raise self.EmptyDatabas...
Removes the statement that matches the input text. Removes any responses from statements if the response text matches the input text. def remove(self, statement_text): """ Removes the statement that matches the input text. Removes any responses from statements if the response te...
Remove all data from the database. def drop(self): """ Remove all data from the database. """ Statement = self.get_model('statement') Tag = self.get_model('tag') Statement.objects.all().delete() Tag.objects.all().delete()
Remove any consecutive whitespace characters from the statement text. def clean_whitespace(statement): """ Remove any consecutive whitespace characters from the statement text. """ import re # Replace linebreaks and tabs with spaces statement.text = statement.text.replace('\n', ' ').replace('\...
Convert escaped html characters into unescaped html characters. For example: "&lt;b&gt;" becomes "<b>". def unescape_html(statement): """ Convert escaped html characters into unescaped html characters. For example: "&lt;b&gt;" becomes "<b>". """ import html statement.text = html.unescape(s...
Converts unicode characters to ASCII character equivalents. For example: "på fédéral" becomes "pa federal". def convert_to_ascii(statement): """ Converts unicode characters to ASCII character equivalents. For example: "på fédéral" becomes "pa federal". """ import unicodedata text = unicode...
Convert strings to numbers def convert_string_to_number(value): """ Convert strings to numbers """ if value is None: return 1 if isinstance(value, int): return value if value.isdigit(): return int(value) num_list = map(lambda s: NUMBERS[s], re.findall(numbers + '+', ...
Convert time to hour, minute def convert_time_to_hour_minute(hour, minute, convention): """ Convert time to hour, minute """ if hour is None: hour = 0 if minute is None: minute = 0 if convention is None: convention = 'am' hour = int(hour) minute = int(minute) ...
Extract date from quarter of a year def date_from_quarter(base_date, ordinal, year): """ Extract date from quarter of a year """ interval = 3 month_start = interval * (ordinal - 1) if month_start < 0: month_start = 9 month_end = month_start + interval if month_start == 0: ...
Converts relative day to time Ex: this tuesday, last tuesday def date_from_relative_day(base_date, time, dow): """ Converts relative day to time Ex: this tuesday, last tuesday """ # Reset date to start of the day base_date = datetime(base_date.year, base_date.month, base_date.day) time ...
Converts relative day to time Eg. this tuesday, last tuesday def date_from_relative_week_year(base_date, time, dow, ordinal=1): """ Converts relative day to time Eg. this tuesday, last tuesday """ # If there is an ordinal (next 3 weeks) => return a start and end range # Reset date to start ...
Convert Day adverbs to dates Tomorrow => Date Today => Date def date_from_adverb(base_date, name): """ Convert Day adverbs to dates Tomorrow => Date Today => Date """ # Reset date to start of the day adverb_date = datetime(base_date.year, base_date.month, base_date.day) if name ...
Find dates from duration Eg: 20 days from now Currently does not support strings like "20 days from last monday". def date_from_duration(base_date, number_as_string, unit, duration, base_time=None): """ Find dates from duration Eg: 20 days from now Currently does not support strings like "20 da...
Finds coming weekday def this_week_day(base_date, weekday): """ Finds coming weekday """ day_of_week = base_date.weekday() # If today is Tuesday and the query is `this monday` # We should output the next_week monday if day_of_week > weekday: return next_week_day(base_date, weekday) ...
Finds previous weekday def previous_week_day(base_date, weekday): """ Finds previous weekday """ day = base_date - timedelta(days=1) while day.weekday() != weekday: day = day - timedelta(days=1) return day
Finds next weekday def next_week_day(base_date, weekday): """ Finds next weekday """ day_of_week = base_date.weekday() end_of_this_week = base_date + timedelta(days=6 - day_of_week) day = end_of_this_week + timedelta(days=1) while day.weekday() != weekday: day = day + timedelta(days...
Extract datetime objects from a string of text. def datetime_parsing(text, base_date=datetime.now()): """ Extract datetime objects from a string of text. """ matches = [] found_array = [] # Find the position in the string for expression, function in regex: for match in expression.f...
Search for close matches to the input. Confidence scores for subsequent results will order of increasing value. :param input_statement: A statement. :type input_statement: chatterbot.conversation.Statement :param **additional_parameters: Additional parameters to be passed t...
Set window layout. def initialize(self): """ Set window layout. """ self.grid() self.respond = ttk.Button(self, text='Get Response', command=self.get_response) self.respond.grid(column=0, row=0, sticky='nesw', padx=3, pady=3) self.usr_input = ttk.Entry(self, st...
Get a response from the chatbot and display it. def get_response(self): """ Get a response from the chatbot and display it. """ user_input = self.usr_input.get() self.usr_input.delete(0, tk.END) response = self.chatbot.get_response(user_input) self.conversation...
Add a list of strings to the statement as tags. (Overrides the method from StatementMixin) def add_tags(self, *tags): """ Add a list of strings to the statement as tags. (Overrides the method from StatementMixin) """ for _tag in tags: self.tags.get_or_create(...
Display svelte components in iPython. Args: name: name of svelte component (must match component filename when built) path: path to compile svelte .js file or source svelte .html file. (If html file, we try to call svelte and build the file.) Returns: A function mapping data to a rendered svelte...
Save object as json on CNS. def save_json(object, handle, indent=2): """Save object as json on CNS.""" obj_json = json.dumps(object, indent=indent, cls=NumpyJSONEncoder) handle.write(obj_json)
Save dict of numpy array as npz file. def save_npz(object, handle): """Save dict of numpy array as npz file.""" # there is a bug where savez doesn't actually accept a file handle. log.warning("Saving npz files currently only works locally. :/") path = handle.name handle.close() if type(object) ...
Save numpy array as image file on CNS. def save_img(object, handle, **kwargs): """Save numpy array as image file on CNS.""" if isinstance(object, np.ndarray): normalized = _normalize_array(object) object = PIL.Image.fromarray(normalized) if isinstance(object, PIL.Image.Image): obj...
Save object to file on CNS. File format is inferred from path. Use save_img(), save_npy(), or save_json() if you need to force a particular format. Args: obj: object to save. path: CNS path. Raises: RuntimeError: If file extension not supported. def save(thing, url_or_handle, **kwa...
Create view frustum matrix. def frustum(left, right, bottom, top, znear, zfar): """Create view frustum matrix.""" assert right != left assert bottom != top assert znear != zfar M = np.zeros((4, 4), dtype=np.float32) M[0, 0] = +2.0 * znear / (right - left) M[2, 0] = (right + left) / (right - left) M[1,...
Compute L2 norms alogn specified axes. def anorm(x, axis=None, keepdims=False): """Compute L2 norms alogn specified axes.""" return np.sqrt((x*x).sum(axis=axis, keepdims=keepdims))
L2 Normalize along specified axes. def normalize(v, axis=None, eps=1e-10): """L2 Normalize along specified axes.""" return v / max(anorm(v, axis=axis, keepdims=True), eps)
Generate LookAt modelview matrix. def lookat(eye, target=[0, 0, 0], up=[0, 1, 0]): """Generate LookAt modelview matrix.""" eye = np.float32(eye) forward = normalize(target - eye) side = normalize(np.cross(forward, up)) up = np.cross(side, forward) M = np.eye(4, dtype=np.float32) R = M[:3, :3] R[:] = [s...
Sample random camera position. Sample origin directed camera position in given distance range from the origin. ModelView matrix is returned. def sample_view(min_dist, max_dist=None): '''Sample random camera position. Sample origin directed camera position in given distance range from the origin. ModelV...
Parse vertex indices in '/' separated form (like 'i/j/k', 'i//k' ...). def _parse_vertex_tuple(s): """Parse vertex indices in '/' separated form (like 'i/j/k', 'i//k' ...).""" vt = [0, 0, 0] for i, c in enumerate(s.split('/')): if c: vt[i] = int(c) return tuple(vt)
Unify lengths of each row of a. def _unify_rows(a): """Unify lengths of each row of a.""" lens = np.fromiter(map(len, a), np.int32) if not (lens[0] == lens).all(): out = np.zeros((len(a), lens.max()), np.float32) for i, row in enumerate(a): out[i, :lens[i]] = row else: out = np.float32(a) r...
Load 3d mesh form .obj' file. Args: fn: Input file name or file-like object. Returns: dictionary with the following keys (some of which may be missing): position: np.float32, (n, 3) array, vertex positions uv: np.float32, (n, 2) array, vertex uv coordinates normal: np.float32, (n, ...
Scale mesh to fit into -1..1 cube def normalize_mesh(mesh): '''Scale mesh to fit into -1..1 cube''' mesh = dict(mesh) pos = mesh['position'][:,:3].copy() pos -= (pos.max(0)+pos.min(0)) / 2.0 pos /= np.abs(pos).max() mesh['position'] = pos return mesh
Loads sampled activations, which requires network access. def activations(self): """Loads sampled activations, which requires network access.""" if self._activations is None: self._activations = _get_aligned_activations(self) return self._activations
Create input tensor. def create_input(self, t_input=None, forget_xy_shape=True): """Create input tensor.""" if t_input is None: t_input = tf.placeholder(tf.float32, self.image_shape) t_prep_input = t_input if len(t_prep_input.shape) == 3: t_prep_input = tf.expand_dims(t_prep_input, 0) i...
Import model GraphDef into the current graph. def import_graph(self, t_input=None, scope='import', forget_xy_shape=True): """Import model GraphDef into the current graph.""" graph = tf.get_default_graph() assert graph.unique_name(scope, False) == scope, ( 'Scope "%s" already exists. Provide explici...
Removes outliers and scales layout to between [0,1]. def normalize_layout(layout, min_percentile=1, max_percentile=99, relative_margin=0.1): """Removes outliers and scales layout to between [0,1].""" # compute percentiles mins = np.percentile(layout, min_percentile, axis=(0)) maxs = np.percentile(layo...
`activations` can be a list of ndarrays. In that case a list of layouts is returned. def aligned_umap(activations, umap_options={}, normalize=True, verbose=False): """`activations` can be a list of ndarrays. In that case a list of layouts is returned.""" umap_defaults = dict( n_components=2, n_neighbo...
Render each cell in the tile and stitch it into a single image def render_tile(cells, ti, tj, render, params, metadata, layout, summary): """ Render each cell in the tile and stitch it into a single image """ image_size = params["cell_size"] * params["n_tile"] tile = Image.new("RGB", (image_size, image_siz...
Call the user defined aggregation function on each cell and combine into a single json object def aggregate_tile(cells, ti, tj, aggregate, params, metadata, layout, summary): """ Call the user defined aggregation function on each cell and combine into a single json object """ tile = [] keys = cells.keys() ...
Create offscreen OpenGL context and make it current. Users are expected to directly use EGL API in case more advanced context management is required. Args: surface_size: (width, height), size of the offscreen rendering surface. def create_opengl_context(surface_size=(640, 480)): """Create offscreen OpenG...
Collapse `shape` outside the interval (`a`,`b`). This function collapses `shape` outside the interval (`a`,`b`) by multiplying the dimensions before `a` into a single dimension, and mutliplying the dimensions after `b` into a single dimension. Args: shape: a tensor shape a: integer, position in shape ...
Bilinear resizes a tensor t to have shape target_shape. This function bilinearly resizes a n-dimensional tensor by iteratively applying tf.image.resize_bilinear (which can only resize 2 dimensions). For bilinear interpolation, the order in which it is applied does not matter. Args: t: tensor to be resized...
Downloads 100k activations of the specified layer sampled from iterating over ImageNet. Activations of all layers where sampled at the same spatial positions for each image, allowing the calculation of correlations. def get_aligned_activations(layer): """Downloads 100k activations of the specified layer sa...
Computes the covariance matrix between the neurons of two layers. If only one layer is passed, computes the symmetric covariance matrix of that layer. def layer_covariance(layer1, layer2=None): """Computes the covariance matrix between the neurons of two layers. If only one layer is passed, computes the sy...
Push activations from one model to another using prerecorded correlations def push_activations(activations, from_layer, to_layer): """Push activations from one model to another using prerecorded correlations""" inverse_covariance_matrix = layer_inverse_covariance(from_layer) activations_decorrelated = np.d...
A paramaterization for interpolating between each pair of N objectives. Sometimes you want to interpolate between optimizing a bunch of objectives, in a paramaterization that encourages images to align. Args: n_objectives: number of objectives you want interpolate between n_interp_steps: number of inter...
Register a gradient function to a random string. In order to use a custom gradient in TensorFlow, it must be registered to a string. This is both a hassle, and -- because only one function can every be registered to a string -- annoying to iterate on in an interactive environemnt. This function registers a ...
Convenience wrapper for graph.gradient_override_map(). This functions provides two conveniences over normal tensorflow gradient overrides: it auomatically uses the default graph instead of you needing to find the graph, and it automatically Example: def _foo_grad_alt(op, grad): ... with gradient_ove...
Decorator for easily setting custom gradients for TensorFlow functions. * DO NOT use this function if you need to serialize your graph. * This function will cause the decorated function to run slower. Example: def _foo_grad(op, grad): ... @use_gradient(_foo_grad) def foo(x1, x2, x3): ... Args: ...
A naive, pixel-based image parameterization. Defaults to a random initialization, but can take a supplied init_val argument instead. Args: shape: shape of resulting image, [batch, width, height, channels]. sd: standard deviation of param initialization noise. init_val: an initial value to...
Computes 2D spectrum frequencies. def rfft2d_freqs(h, w): """Computes 2D spectrum frequencies.""" fy = np.fft.fftfreq(h)[:, None] # when we have an odd input dimension we need to keep one additional # frequency and later cut off 1 pixel if w % 2 == 1: fx = np.fft.fftfreq(w)[: w // 2 + 2] ...
An image paramaterization using 2D Fourier coefficients. def fft_image(shape, sd=None, decay_power=1): """An image paramaterization using 2D Fourier coefficients.""" sd = sd or 0.01 batch, h, w, ch = shape freqs = rfft2d_freqs(h, w) init_val_size = (2, ch) + freqs.shape images = [] for _ ...
Simple laplacian pyramid paramaterization of an image. For more flexibility, use a sum of lowres_tensor()s. Args: shape: shape of resulting image, [batch, width, height, channels]. n_levels: number of levels of laplacian pyarmid. sd: standard deviation of param initialization. Returns: ...
Build bilinear texture sampling graph. Coordinate transformation rules match OpenGL GL_REPEAT wrapping and GL_LINEAR interpolation modes. Args: texture: [tex_h, tex_w, channel_n] tensor. uv: [frame_h, frame_h, 2] tensor with per-pixel UV coordinates in range [0..1] Returns: [frame_h...
Multiply input by sqrt of emperical (ImageNet) color correlation matrix. If you interpret t's innermost dimension as describing colors in a decorrelated version of the color space (which is a very natural way to describe colors -- see discussion in Feature Visualization article) the way to map back to normal...
Transform inner dimension of t to valid rgb colors. In practice this consistes of two parts: (1) If requested, transform the colors from a decorrelated color space to RGB. (2) Constrain the color channels to be in [0,1], either using a sigmoid function or clipping. Args: t: input tensor, innerm...
Add Inception bottlenecks and their pre-Relu versions to the graph. def _populate_inception_bottlenecks(scope): """Add Inception bottlenecks and their pre-Relu versions to the graph.""" graph = tf.get_default_graph() for op in graph.get_operations(): if op.name.startswith(scope+'/') and 'Concat' in op.type: ...
Decorator for creating Objective factories. Changes f from the closure: (args) => () => TF Tensor into an Obejective factory: (args) => Objective while perserving function name, arg info, docs... for interactive python. def wrap_objective(f, *args, **kwds): """Decorator for creating Objective factories. C...
Visualize a single neuron of a single channel. Defaults to the center neuron. When width and height are even numbers, we choose the neuron in the bottom right of the center 2x2 neurons. Odd width & height: Even width & height: +---+---+---+ +---+---+---+---+ | | | | ...
Visualize a single channel def channel(layer, n_channel, batch=None): """Visualize a single channel""" if batch is None: return lambda T: tf.reduce_mean(T(layer)[..., n_channel]) else: return lambda T: tf.reduce_mean(T(layer)[batch, ..., n_channel])
Visualize a direction def direction(layer, vec, batch=None, cossim_pow=0): """Visualize a direction""" if batch is None: vec = vec[None, None, None] return lambda T: _dot_cossim(T(layer), vec) else: vec = vec[None, None] return lambda T: _dot_cossim(T(layer)[batch], vec)
Visualize a single (x, y) position along the given direction def direction_neuron(layer_name, vec, batch=None, x=None, y=None, cossim_pow=0): """Visualize a single (x, y) position along the given direction""" def inner(T): layer = T(layer_name) shape = tf.shape(layer) x_ = shape[1] // 2 if x is None el...
Visualize a direction (cossine similarity) def direction_cossim(layer, vec, batch=None): """Visualize a direction (cossine similarity)""" def inner(T): act_mags = tf.sqrt(tf.reduce_sum(T(layer)**2, -1, keepdims=True)) vec_mag = tf.sqrt(tf.reduce_sum(vec**2)) mags = act_mags * vec_mag if batch is No...
L1 norm of layer. Generally used as penalty. def L1(layer="input", constant=0, batch=None): """L1 norm of layer. Generally used as penalty.""" if batch is None: return lambda T: tf.reduce_sum(tf.abs(T(layer) - constant)) else: return lambda T: tf.reduce_sum(tf.abs(T(layer)[batch] - constant))
L2 norm of layer. Generally used as penalty. def L2(layer="input", constant=0, epsilon=1e-6, batch=None): """L2 norm of layer. Generally used as penalty.""" if batch is None: return lambda T: tf.sqrt(epsilon + tf.reduce_sum((T(layer) - constant) ** 2)) else: return lambda T: tf.sqrt(epsilon + tf.reduce_s...
Minimizing this objective is equivelant to blurring input each step. Optimizing (-k)*blur_input_each_step() is equivelant to: input <- (1-k)*input + k*blur(input) An operation that was used in early feature visualization work. See Nguyen, et al., 2015. def blur_input_each_step(): """Minimizing this obje...
Interpolate between layer1, n_channel1 and layer2, n_channel2. Optimize for a convex combination of layer1, n_channel1 and layer2, n_channel2, transitioning across the batch. Args: layer1: layer to optimize 100% at batch=0. n_channel1: neuron index to optimize 100% at batch=0. layer2: layer to optim...
Encourage the boundaries of an image to have less variation and of color C. Args: shp: shape of T("input") because this may not be known. w: width of boundary to penalize. Ignored if mask is set. mask: mask describing what area should be penalized. Returns: Objective. def penalize_boundary_comple...
Encourage neighboring images to be similar. When visualizing the interpolation between two objectives, it's often desireable to encourage analagous boejcts to be drawn in the same position, to make them more comparable. This term penalizes L2 distance between neighboring images, as evaluated at layer. In...
Encourage diversity between each batch element. A neural net feature often responds to multiple things, but naive feature visualization often only shows us one. If you optimize a batch of images, this objective will encourage them all to be different. In particular, it caculuates the correlation matrix of act...
Average L2 difference between optimized image and orig_img. This objective is usually mutliplied by a negative number and used as a penalty in making advarsarial counterexamples. def input_diff(orig_img): """Average L2 difference between optimized image and orig_img. This objective is usually mutliplied by a...