text
stringlengths 5
22M
| id
stringlengths 12
177
| metadata
dict | __index_level_0__
int64 0
1.37k
|
---|---|---|---|
bistring
========
The bistring library provides non-destructive versions of common string processing operations like normalization, case folding, and find/replace.
Each bistring remembers the original string, and how its substrings map to substrings of the modified version.
.. toctree::
:maxdepth: 2
:caption: Contents:
Introduction
FAQ
Python/index
JavaScript/index
Indices and tables
==================
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`
|
bistring/docs/index.rst/0
|
{
"file_path": "bistring/docs/index.rst",
"repo_id": "bistring",
"token_count": 146
}
| 433 |
import Alignment, { BiIndex } from "./alignment";
import BiString from "./bistring";
// https://unicode.org/reports/tr44/#GC_Values_Table
const CATEGORIES = [
"Lu", "Ll", "Lt", "Lm", "Lo",
"Mn", "Mc", "Me",
"Nd", "Nl", "No",
"Pc", "Pd", "Ps", "Pe", "Pi", "Pf", "Po",
"Sm", "Sc", "Sk", "So",
"Zs", "Zl", "Zp",
"Cc", "Cf", "Cs", "Co", "Cn",
];
// TODO: Babel doesn't polyfill this, and the source transformation doesn't catch it
// const CATEGORY_REGEXP = new RegExp(CATEGORIES.map(c => `(\\p{${c}})`).join("|"), "u");
const CATEGORY_REGEXP = /(\p{Lu})|(\p{Ll})|(\p{Lt})|(\p{Lm})|(\p{Lo})|(\p{Mn})|(\p{Mc})|(\p{Me})|(\p{Nd})|(\p{Nl})|(\p{No})|(\p{Pc})|(\p{Pd})|(\p{Ps})|(\p{Pe})|(\p{Pi})|(\p{Pf})|(\p{Po})|(\p{Sm})|(\p{Sc})|(\p{Sk})|(\p{So})|(\p{Zs})|(\p{Zl})|(\p{Zp})|(\p{Cc})|(\p{Cf})|(\p{Cs})|(\p{Co})|(\p{Cn})/u;
function category(cp: string): string {
const match = cp.match(CATEGORY_REGEXP)!;
const index = match.indexOf(cp, 1) - 1;
return CATEGORIES[index];
}
/**
* A single glyph in a string, augmented with some extra information.
*/
class AugmentedGlyph {
/** The original form of the glyph. */
readonly original: string;
/** The Unicode compatibility normalized form of the glyph. */
readonly normalized: string;
/** The uppercase form of the glyph. */
readonly upper: string;
/** The root code point of the grapheme cluster. */
readonly root: string;
/** The specific Unicode category of the glyph (Lu, Po, Zs, etc.). */
readonly category: string;
/** The top-level Unicode category of the glyph (L, P, Z, etc.). */
readonly topCategory: string;
constructor(original: string, normalized: string, upper: string) {
this.original = original;
this.normalized = normalized;
this.upper = upper;
this.root = String.fromCodePoint(upper.codePointAt(0)!);
this.category = category(this.root);
this.topCategory = this.category[0];
}
static costFn(a?: AugmentedGlyph, b?: AugmentedGlyph) {
if (!a || !b) {
// cost(insert) + cost(delete) (4 + 4) should be more than cost(substitute) (6)
return 4;
}
let result = 0;
result += +(a.original !== b.original);
result += +(a.normalized !== b.normalized);
result += +(a.upper !== b.upper);
result += +(a.root !== b.root);
result += +(a.category !== b.topCategory);
result += +(a.topCategory !== b.topCategory);
return result;
}
}
/**
* Not quite as good as UAX #29 grapheme clusters, but we're waiting on Intl.Segmenter.
*/
const GLYPH_REGEXP = /\P{M}\p{M}*|^\p{M}+/gu;
/**
* A string augmented with some extra information about each glyph.
*/
class AugmentedString {
/** The original string. */
readonly original: string;
/** The augmented glyphs of the string. */
readonly glyphs: readonly AugmentedGlyph[];
/** The alignment between the original string and the augmented glyphs. */
readonly alignment: Alignment;
constructor(original: string) {
const normalized = new BiString(original).normalize("NFKD");
const upper = new BiString(normalized.modified).toUpperCase();
const glyphs = [];
const alignment: BiIndex[] = [[0, 0]];
for (const match of upper.matchAll(GLYPH_REGEXP)) {
const [o, m] = alignment[alignment.length - 1];
const upperC = match[0];
const normBounds = upper.alignment.originalBounds(o, o + upperC.length);
const normC = upper.original.slice(...normBounds);
const origBounds = normalized.alignment.originalBounds(normBounds);
const origC = normalized.original.slice(...origBounds);
glyphs.push(new AugmentedGlyph(origC, normC, upperC));
alignment.push([o + normC.length, m + 1]);
}
this.original = original;
this.glyphs = glyphs;
this.alignment = normalized.alignment.compose(new Alignment(alignment));
}
}
/**
* Infer the alignment between two strings with a "smart" heuristic.
*
* We use Unicode normalization and case mapping to minimize differences that are due to case, accents, ligatures, etc.
*/
export default function heuristicInfer(original: string, modified: string): BiString {
const augOrig = new AugmentedString(original);
const augMod = new AugmentedString(modified);
let alignment = Alignment.infer(augOrig.glyphs, augMod.glyphs, AugmentedGlyph.costFn);
alignment = augOrig.alignment.compose(alignment);
alignment = alignment.compose(augMod.alignment.inverse());
return new BiString(original, modified, alignment);
}
|
bistring/js/src/infer.ts/0
|
{
"file_path": "bistring/js/src/infer.ts",
"repo_id": "bistring",
"token_count": 1903
}
| 434 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT license.
from __future__ import annotations
__all__ = ['bistr']
from itertools import islice
from typing import Any, Callable, Iterable, Iterator, List, Optional, Tuple, Union, overload, TYPE_CHECKING
import unicodedata
from ._alignment import Alignment
from ._typing import BiIndex, Bounds, Index, Regex, Replacement
Real = Union[int, float]
CostFn = Callable[[Optional[str], Optional[str]], Real]
class bistr:
"""
A bidirectionally transformed string.
"""
__slots__ = ('original', 'modified', 'alignment')
original: str
"""
The original string, before any modifications.
"""
modified: str
"""
The current value of the string, after all modifications.
"""
alignment: Alignment
"""
The sequence alignment between :attr:`original` and :attr:`modified`.
"""
def __new__(cls, original: String, modified: Optional[str] = None, alignment: Optional[Alignment] = None) -> bistr:
"""
A `bistr` can be constructed from only a single string, which will give it identical original and modified
strings and an identity alignment:
>>> s = bistr('test')
>>> s.original
'test'
>>> s.modified
'test'
>>> s.alignment
Alignment.identity(4)
You can also explicitly specify both the original and modified string. The inferred alignment will be as course
as possible:
>>> s = bistr('TEST', 'test')
>>> s.original
'TEST'
>>> s.modified
'test'
>>> s.alignment
Alignment([(0, 0), (4, 4)])
Finally, you can specify the alignment explicitly too, if you know it:
>>> s = bistr('TEST', 'test', Alignment.identity(4))
>>> s[1:3]
bistr('ES', 'es', Alignment.identity(2))
"""
if isinstance(original, bistr):
if modified is not None or alignment is not None:
raise ValueError('bistr copy constructor invoked with extra arguments')
return original
elif not isinstance(original, str):
raise TypeError(f'Expected a string, found {type(original)}')
if modified is None:
modified = original
if alignment is None:
alignment = Alignment.identity(len(original))
elif isinstance(modified, str):
if alignment is None:
alignment = Alignment([(0, 0), (len(original), len(modified))])
else:
raise TypeError(f'Expected a string, found {type(modified)}')
if not isinstance(alignment, Alignment):
raise TypeError(f'Expected an Alignment, found {type(alignment)}')
if alignment.original_bounds() != (0, len(original)):
raise ValueError('Alignment incompatible with original string')
elif alignment.modified_bounds() != (0, len(modified)):
raise ValueError('Alignment incompatible with modified string')
result: bistr = object.__new__(cls)
object.__setattr__(result, 'original', original)
object.__setattr__(result, 'modified', modified)
object.__setattr__(result, 'alignment', alignment)
return result
@classmethod
def infer(cls, original: str, modified: str, cost_fn: Optional[CostFn] = None) -> bistr:
"""
Create a `bistr`, automatically inferring an alignment between the `original` and `modified` strings.
This method can be useful if the modified string was produced by some method out of your control. If at all
possible, you should start with ``bistr(original)`` and perform non-destructive operations to get to the
modified string instead.
>>> s = bistr.infer('color', 'colour')
>>> print(s[0:3])
โฎ'col'โฎ
>>> print(s[3:5])
('o' โ 'ou')
>>> print(s[5:6])
โฎ'r'โฎ
`infer()` tries to be intelligent about certain aspects of Unicode, which enables it to guess good alignments
between strings that have been case-mapped, normalized, etc.:
>>> s = bistr.infer(
... '๐
๐ท๐ด ๐
๐
๐ธ๐ฒ๐บ, ๐ฑ๐
๐พ๐
๐ฝ ๐ฆ ๐น๐
๐ผ๐ฟ๐
๐พ๐
๐ด๐
๐
๐ท๐ด ๐ป๐ฐ๐
๐
๐ถ',
... 'the quick brown fox jumps over the lazy dog',
... )
>>> print(s[0:3])
('๐
๐ท๐ด' โ 'the')
>>> print(s[4:9])
('๐
๐
๐ธ๐ฒ๐บ' โ 'quick')
>>> print(s[10:15])
('๐ฑ๐
๐พ๐
๐ฝ' โ 'brown')
>>> print(s[16:19])
('๐ฆ' โ 'fox')
Warning: this operation has time complexity ``O(N*M)``, where `N` and `M` are the lengths of the original and
modified strings, and so should only be used for relatively short strings.
:param original:
The original string
:param modified:
The modified string.
:param cost_fn:
A function returning the cost of performing an edit (see :meth:`Alignment.infer`).
:returns:
A `bistr` with the inferred alignment.
"""
if cost_fn:
return cls(original, modified, Alignment.infer(original, modified, cost_fn))
else:
from ._infer import heuristic_infer
return heuristic_infer(original, modified)
def __str__(self) -> str:
if self.original == self.modified:
return f'โฎ{self.original!r}โฎ'
else:
return f'({self.original!r} โ {self.modified!r})'
def __repr__(self) -> str:
if self.original == self.modified and len(self.alignment) == len(self.original) + 1:
return f'bistr({self.original!r})'
elif len(self.alignment) == 2:
return f'bistr({self.original!r}, {self.modified!r})'
else:
return f'bistr({self.original!r}, {self.modified!r}, {self.alignment!r})'
def __len__(self) -> int:
return len(self.modified)
def __eq__(self, other: Any) -> bool:
if isinstance(other, bistr):
return (self.original, self.modified, self.alignment) == (other.original, other.modified, other.alignment)
else:
return NotImplemented
def __add__(self, other: Any) -> bistr:
if isinstance(other, bistr):
original = other.original
modified = other.modified
alignment = other.alignment
elif isinstance(other, str):
original = other
modified = other
alignment = Alignment.identity(len(other))
else:
return NotImplemented
alignment = alignment.shift(len(self.original), len(self.modified))
return bistr(self.original + original, self.modified + modified, self.alignment + alignment)
def __radd__(self, other: Any) -> bistr:
if isinstance(other, str):
length = len(other)
return bistr(
other + self.original,
other + self.modified,
Alignment.identity(length) + self.alignment.shift(length, length),
)
else:
return NotImplemented
def __iter__(self) -> Iterator[str]:
return iter(self.modified)
@overload
def __getitem__(self, index: int) -> str: ...
@overload
def __getitem__(self, index: slice) -> bistr: ...
def __getitem__(self, index: Index) -> String:
"""
Indexing a `bistr` returns the nth character of the modified string:
>>> s = bistr('TEST').lower()
>>> s[1]
'e'
Slicing a `bistr` extracts a substring, complete with the matching part
of the original string:
>>> s = bistr('TEST').lower()
>>> s[1:3]
bistr('ES', 'es', Alignment.identity(2))
"""
if isinstance(index, slice):
start, stop, stride = index.indices(len(self))
if stride != 1:
raise ValueError('Non-unit strides not supported')
alignment = self.alignment.slice_by_modified(start, stop)
modified = self.modified[start:stop]
original = self.original[alignment.original_slice()]
o0, m0 = alignment[0]
alignment = alignment.shift(-o0, -m0)
return bistr(original, modified, alignment)
else:
return self.modified[index]
def __setattr__(self, name: str, value: Any) -> None:
raise AttributeError('bistr is immutable')
def __delattr__(self, name: str) -> None:
raise AttributeError('bistr is immutable')
def inverse(self) -> bistr:
"""
:returns: The inverse of this string, swapping the original and modified strings.
>>> s = bistr('HELLO WORLD').lower()
>>> s
bistr('HELLO WORLD', 'hello world', Alignment.identity(11))
>>> s.inverse()
bistr('hello world', 'HELLO WORLD', Alignment.identity(11))
"""
return bistr(self.modified, self.original, self.alignment.inverse())
def chunks(self) -> Iterable[bistr]:
"""
:returns: All the chunks of associated text in this string.
"""
i, k = 0, 0
for j, l in self.alignment[1:]:
yield bistr(self.original[i:j], self.modified[k:l])
i, k = j, l
def count(self, sub: str, start: Optional[int] = None, end: Optional[int] = None) -> int:
"""
Like :meth:`str.count`, counts the occurrences of `sub` in the string.
"""
return self.modified.count(sub, start, end)
def find(self, sub: str, start: Optional[int] = None, end: Optional[int] = None) -> int:
"""
Like :meth:`str.find`, finds the position of `sub` in the string.
"""
return self.modified.find(sub, start, end)
def find_bounds(self, sub: str, start: Optional[int] = None, end: Optional[int] = None) -> Bounds:
"""
Like :meth:`find`, but returns both the start and end bounds for convenience.
:returns: The first `i, j` within `[start, end)` such that ``self[i:j] == sub``, or ``(-1, -1)`` if not found.
"""
i = self.find(sub, start, end)
if i >= 0:
return i, i + len(sub)
else:
return i, i
def rfind(self, sub: str, start: Optional[int] = None, end: Optional[int] = None) -> int:
"""
Like :meth:`str.rfind`, finds the position of `sub` in the string backwards.
"""
return self.modified.rfind(sub, start, end)
def rfind_bounds(self, sub: str, start: Optional[int] = None, end: Optional[int] = None) -> Bounds:
"""
Like :meth:`rfind`, but returns both the start and end bounds for convenience.
:returns: The last `i, j` within `[start, end)` such that ``self[i:j] == sub``, or ``(-1, -1)`` if not found.
"""
i = self.rfind(sub, start, end)
if i >= 0:
return i, i + len(sub)
else:
return i, i
def index(self, sub: str, start: Optional[int] = None, end: Optional[int] = None) -> int:
"""
Like :meth:`str.index`, finds the first position of `sub` in the string, otherwise raising a `ValueError`.
"""
return self.modified.index(sub, start, end)
def index_bounds(self, sub: str, start: Optional[int] = None, end: Optional[int] = None) -> Bounds:
"""
Like :meth:`index`, but returns both the start and end bounds for convenience. If the substring is not found, a
:class:`ValueError` is raised.
:returns: The first `i, j` within `[start, end)` such that ``self[i:j] == sub``.
:raises: :class:`ValueError` if the substring is not found.
"""
i = self.index(sub, start, end)
return i, i + len(sub)
def rindex(self, sub: str, start: Optional[int] = None, end: Optional[int] = None) -> int:
"""
Like :meth:`str.index`, finds the last position of `sub` in the string, otherwise raising a `ValueError`.
"""
return self.modified.rindex(sub, start, end)
def rindex_bounds(self, sub: str, start: Optional[int] = None, end: Optional[int] = None) -> Bounds:
"""
Like :meth:`rindex`, but returns both the start and end bounds for convenience. If the substring is not found, a
:class:`ValueError` is raised.
:returns: The last `i, j` within `[start, end)` such that ``self[i:j] == sub``.
:raises: :class:`ValueError` if the substring is not found.
"""
i = self.rindex(sub, start, end)
return i, i + len(sub)
def startswith(self, prefix: Union[str, Tuple[str, ...]], start: Optional[int] = None, end: Optional[int] = None) -> bool:
"""
Like :meth:`str.startswith`, checks if the string starts with the given `prefix`.
"""
return self.modified.startswith(prefix, start, end)
def endswith(self, suffix: Union[str, Tuple[str, ...]], start: Optional[int] = None, end: Optional[int] = None) -> bool:
"""
Like :meth:`str.endswith`, checks if the string starts with the given `suffix`.
"""
return self.modified.endswith(suffix, start, end)
def _append_alignment(self, alist: List[Bounds], alignment: Alignment) -> None:
do, dm = alist[-1]
alist.extend((o + do, m + dm) for o, m in alignment[1:])
def join(self, iterable: Iterable[String]) -> bistr:
"""
Like :meth:`str.join`, concatenates many (bi)strings together.
"""
original: List[str] = []
modified: List[str] = []
alignment: List[BiIndex] = [(0, 0)]
for element in iterable:
if original:
original.append(self.original)
modified.append(self.modified)
self._append_alignment(alignment, self.alignment)
bs = bistr(element)
original.append(bs.original)
modified.append(bs.modified)
self._append_alignment(alignment, bs.alignment)
return bistr("".join(original), "".join(modified), Alignment(alignment))
def _find_whitespace(self, start: int) -> Bounds:
for i in range(start, len(self)):
if self[i].isspace():
first = i
break
else:
return -1, -1
for i in range(first + 1, len(self)):
if not self[i].isspace():
last = i
break
else:
last = len(self)
return first, last
def split(self, sep: Optional[str] = None, maxsplit: int = -1) -> List[bistr]:
"""
Like :meth:`str.split`, splits this string on a separator.
"""
result = []
count = 0
start = 0
while start >= 0 and (count < maxsplit or maxsplit == -1):
if sep is None:
i, j = self._find_whitespace(start)
else:
i, j = self.find_bounds(sep, start)
if i < 0:
i = len(self)
if i > start or sep is not None:
result.append(self[start:i])
count += 1
start = j
if start >= 0:
result.append(self[start:])
return result
def partition(self, sep: str) -> Tuple[bistr, bistr, bistr]:
"""
Like :meth:`str.partition`, splits this string into three chunks on a separator.
"""
i, j = self.find_bounds(sep)
if i >= 0:
return self[:i], self[i:j], self[j:]
else:
return self, bistr(''), bistr('')
def rpartition(self, sep: str) -> Tuple[bistr, bistr, bistr]:
"""
Like :meth:`str.rpartition`, splits this string into three chunks on a separator, searching from the end.
"""
i, j = self.rfind_bounds(sep)
if i >= 0:
return self[:i], self[i:j], self[j:]
else:
return bistr(''), bistr(''), self
def center(self, width: int, fillchar: str = ' ') -> bistr:
"""
Like :meth:`str.center`, pads the start and end of the string to center it.
"""
if len(self) >= width:
return self
pad = width - len(self)
lpad = pad // 2
rpad = (pad + 1) // 2
return bistr('', fillchar * lpad) + self + bistr('', fillchar * rpad)
def ljust(self, width: int, fillchar: str = ' ') -> bistr:
"""
Like :meth:`str.ljust`, pads the end of the string to a fixed width.
"""
if len(self) >= width:
return self
pad = width - len(self)
return self + bistr('', fillchar * pad)
def rjust(self, width: int, fillchar: str = ' ') -> bistr:
"""
Like :meth:`str.rjust`, pads the start of the string to a fixed width.
"""
if len(self) >= width:
return self
pad = width - len(self)
return bistr('', fillchar * pad) + self
def _builder(self) -> BistrBuilder:
from ._builder import BistrBuilder
return BistrBuilder(self)
def casefold(self) -> bistr:
"""
Computes the case folded form of this string. Case folding is used for case-insensitive operations, and the
result may not be suitable for displaying to a user. For example:
>>> s = bistr('straรe').casefold()
>>> s.modified
'strasse'
>>> s[4:6]
bistr('ร', 'ss')
"""
from ._icu import casefold
return casefold(self)
def lower(self, locale: Optional[str] = None) -> bistr:
"""
Converts this string to lowercase. Unless you specify the `locale` parameter, the current system locale will be
used.
>>> bistr('HELLO WORLD').lower()
bistr('HELLO WORLD', 'hello world', Alignment.identity(11))
>>> bistr('I').lower('en_US')
bistr('I', 'i')
>>> bistr('I').lower('tr_TR')
bistr('I', 'ฤฑ')
"""
from ._icu import lower
return lower(self, locale)
def upper(self, locale: Optional[str] = None) -> bistr:
"""
Converts this string to uppercase. Unless you specify the `locale` parameter, the current system locale will be
used.
>>> bistr('hello world').upper()
bistr('hello world', 'HELLO WORLD', Alignment.identity(11))
>>> bistr('i').upper('en_US')
bistr('i', 'I')
>>> bistr('i').upper('tr_TR')
bistr('i', 'ฤฐ')
"""
from ._icu import upper
return upper(self, locale)
def title(self, locale: Optional[str] = None) -> bistr:
"""
Converts this string to title case. Unless you specify the `locale` parameter, the current system locale will
be used.
>>> bistr('hello world').title()
bistr('hello world', 'Hello World', Alignment.identity(11))
>>> bistr('istanbul').title('en_US')
bistr('istanbul', 'Istanbul', Alignment.identity(8))
>>> bistr('istanbul').title('tr_TR')
bistr('istanbul', 'ฤฐstanbul', Alignment.identity(8))
"""
from ._icu import title
return title(self, locale)
def capitalize(self, locale: Optional[str] = None) -> bistr:
"""
Capitalize the first character of this string, and lowercase the rest. Unless you specify the `locale`
parameter, the current system locale will be used.
>>> bistr('hello WORLD').capitalize()
bistr('hello WORLD', 'Hello world', Alignment.identity(11))
>>> bistr('แผดฮฃ').capitalize('el_GR')
bistr('แผดฮฃ', 'แผผฯ', Alignment.identity(2))
"""
# We have to be careful here to get context-sensitive letters like
# word-final sigma correct
builder = self._builder()
title = bistr(self.modified).title()
for chunk in islice(title.chunks(), 1):
builder.replace(len(chunk.original), chunk.modified)
lower = bistr(self.modified).lower()
for chunk in islice(lower.chunks(), 1, None):
builder.replace(len(chunk.original), chunk.modified)
return builder.build()
def swapcase(self, locale: Optional[str] = None) -> bistr:
"""
Swap the case of every letter in this string. Unless you specify the `locale` parameter, the current system
locale will be used.
>>> bistr('hello WORLD').swapcase()
bistr('hello WORLD', 'HELLO world', Alignment.identity(11))
Some Unicode characters, such as title-case ligatures and digraphs, don't have a case-swapped equivalent:
>>> bistr('วepรฒta').swapcase('hr_HR')
bistr('วepรฒta', 'วEPรTA', Alignment.identity(6))
In these cases, compatibilty normalization may help:
>>> s = bistr('วepรฒta')
>>> s = s.normalize('NFKC')
>>> s = s.swapcase('hr_HR')
>>> print(s)
('วepรฒta' โ 'lJEPรTA')
"""
builder = self._builder()
lower = bistr(self.modified).lower(locale)
upper = bistr(self.modified).upper(locale)
while not builder.is_complete:
i = builder.position
c = self[i]
cat = unicodedata.category(c)
if cat == 'Ll':
repl = upper
elif cat == 'Lu':
repl = lower
else:
builder.skip(1)
continue
chunk = repl[repl.alignment.modified_slice(i, i + 1)]
builder.append(chunk)
return builder.build()
def expandtabs(self, tabsize: int = 8) -> bistr:
"""
Like :meth:`str.expandtabs`, replaces tab (``\\t``) characters with spaces to align on multiples of `tabsize`.
"""
builder = self._builder()
col = 0
while not builder.is_complete:
c = builder.peek(1)
if c == '\t':
spaces = tabsize - (col % tabsize)
builder.replace(1, ' ' * spaces)
col += spaces
else:
builder.skip(1)
if c == '\n' or c == '\r':
col = 0
else:
col += 1
return builder.build()
def replace(self, old: str, new: str, count: Optional[int] = None) -> bistr:
"""
Like :meth:`str.replace`, replaces occurrences of `old` with `new`.
"""
builder = self._builder()
pos = 0
n = 0
while count is None or n < count:
index = self.modified.find(old, pos)
if index < 0:
break
builder.skip(index - pos)
builder.replace(len(old), new)
pos = index + len(old)
n += 1
builder.skip_rest()
return builder.build()
def sub(self, regex: Regex, repl: Replacement) -> bistr:
"""
Like :meth:`re.sub`, replaces all matches of `regex` with the replacement `repl`.
:param regex:
The regex to match. Can be a string pattern or a compiled regex.
:param repl:
The replacement to use. Can be a string, which is interpreted as in :meth:`re.Match.expand`, or a
`callable`, which will receive each match and return the replacement string.
"""
builder = self._builder()
builder.replace_all(regex, repl)
return builder.build()
def _should_strip(self, c: str, chars: Optional[str]) -> bool:
if chars is None:
return c.isspace()
else:
return c in chars
def strip(self, chars: Optional[str] = None) -> bistr:
"""
Like :meth:`str.strip`, removes leading and trailing characters (whitespace by default).
"""
length = len(self)
pre = 0
while pre < length and self._should_strip(self.modified[pre], chars):
pre += 1
post = length
while post > pre and self._should_strip(self.modified[post - 1], chars):
post -= 1
builder = self._builder()
builder.discard(pre)
builder.skip(post - pre)
builder.discard_rest()
return builder.build()
def lstrip(self, chars: Optional[str] = None) -> bistr:
"""
Like :meth:`str.lstrip`, removes leading characters (whitespace by default).
"""
length = len(self)
pre = 0
while pre < length and self._should_strip(self.modified[pre], chars):
pre += 1
builder = self._builder()
builder.discard(pre)
builder.skip_rest()
return builder.build()
def rstrip(self, chars: Optional[str] = None) -> bistr:
"""
Like :meth:`str.rstrip`, removes trailing characters (whitespace by default).
"""
length = len(self)
post = length
while post > 0 and self._should_strip(self.modified[post - 1], chars):
post -= 1
builder = self._builder()
builder.skip(post)
builder.discard_rest()
return builder.build()
def normalize(self, form: str) -> bistr:
"""
Like :meth:`unicodedata.normalize`, applies a Unicode `normalization form <https://unicode.org/reports/tr15/#Norm_Forms>`_.
The choices for `form` are:
- ``'NFC'``: Canonical Composition
- ``'NFKC'``: Compatibility Composition
- ``'NFD'``: Canonical Decomposition
- ``'NFKD'``: Compatibilty Decomposition
"""
from ._icu import normalize
return normalize(self, form)
String = Union[str, bistr]
if TYPE_CHECKING:
from ._builder import BistrBuilder
|
bistring/python/bistring/_bistr.py/0
|
{
"file_path": "bistring/python/bistring/_bistr.py",
"repo_id": "bistring",
"token_count": 11907
}
| 435 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT license.
from bistring import bistr, Token, Tokenization, Tokenizer
import pytest
def test_tokenization():
text = bistr(' The quick, brown fox jumps over the lazy dog ')
text = text.replace(',', '')
text = text.sub(r'^ +| +$', '')
tokens = Tokenization(text, [
Token.slice(text, 0, 3),
Token.slice(text, 4, 9),
Token.slice(text, 10, 15),
Token.slice(text, 16, 19),
Token.slice(text, 20, 25),
Token.slice(text, 26, 30),
Token.slice(text, 31, 34),
Token.slice(text, 35, 39),
Token.slice(text, 40, 43),
])
assert tokens.text == text
assert tokens.text_bounds(1, 3) == (4, 15)
assert tokens.original_bounds(1, 3) == (6, 18)
assert tokens.bounds_for_text(0, 13) == (0, 3)
assert tokens.bounds_for_original(0, 13) == (0, 2)
assert tokens.slice_by_text(34, 43).substring() == bistr('lazy dog')
assert tokens.slice_by_original(36, 48).substring() == bistr('the lazy dog')
assert tokens.snap_text_bounds(2, 13) == (0, 15)
assert tokens.snap_original_bounds(36, 47) == (34, 46)
def test_infer():
text = 'the quick, brown fox'
tokens = Tokenization.infer(text, ['the', 'quick', 'brown', 'fox'])
assert tokens.substring(1, 3) == bistr('quick, brown')
pytest.raises(ValueError, Tokenization.infer, text, ['the', 'quick', 'red', 'fox'])
def test_regex_tokenizer():
from bistring import RegexTokenizer
text = bistr(' ๐ฟ๐๐ ๐๐๐๐๐, ๐๐๐๐๐ ๐๐๐ ๐๐๐๐๐ ๐๐๐๐ ๐๐๐ ๐๐๐๐ ๐๐๐ ')
text = text.normalize('NFKD')
text = text.casefold()
tokenizer = RegexTokenizer(r'\w+')
assert isinstance(tokenizer, Tokenizer)
tokens = tokenizer.tokenize(text)
assert tokens.text == text
assert len(tokens) == 9
assert tokens.text_bounds(0, 2) == (1, 10)
assert tokens[0:2].substring() == text[1:10]
assert len(tokens.slice_by_text(5, 10)) == 1
assert len(tokens.slice_by_text(5, 11)) == 1
assert len(tokens.slice_by_text(3, 13)) == 3
def test_splitting_tokenizer():
from bistring import SplittingTokenizer
text = bistr(' ๐ฟ๐๐ ๐๐๐๐๐, ๐๐๐๐๐ ๐๐๐ ๐๐๐๐๐ ๐๐๐๐ ๐๐๐ ๐๐๐๐ ๐๐๐ ')
text = text.normalize('NFKD')
text = text.casefold()
tokenizer = SplittingTokenizer(r'\s+')
assert isinstance(tokenizer, Tokenizer)
tokens = tokenizer.tokenize(text)
assert tokens.text == text
assert len(tokens) == 9
assert tokens.text_bounds(0, 2) == (1, 11)
assert tokens[0:2].substring() == text[1:11]
assert len(tokens.slice_by_text(5, 10)) == 1
assert len(tokens.slice_by_text(5, 11)) == 1
assert len(tokens.slice_by_text(3, 13)) == 3
def test_character_tokenizer():
from bistring import CharacterTokenizer
text = bistr(' ๐ฟ๐๐ ๐๐๐๐๐, ๐๐๐๐๐ ๐๐๐ ๐๐๐๐๐ ๐๐๐๐ ๐๐๐ ๐๐๐๐ ๐๐๐ ')
tokenizer = CharacterTokenizer('en_US')
assert isinstance(tokenizer, Tokenizer)
tokens = tokenizer.tokenize(text)
assert tokens.text == text
assert all(token.text == text[i:i+1] for i, token in enumerate(tokens))
def test_word_tokenizer():
from bistring import WordTokenizer
text = bistr(' ๐ฟ๐๐ ๐๐๐๐๐, ๐๐๐๐๐ ๐๐๐ ๐๐๐๐๐ ๐๐๐๐ ๐๐๐ ๐๐๐๐ ๐๐๐ ')
tokenizer = WordTokenizer('en_US')
assert isinstance(tokenizer, Tokenizer)
tokens = tokenizer.tokenize(text)
assert tokens.text == text
assert len(tokens) == 9
assert tokens.text_bounds(0, 2) == (1, 10)
assert tokens[0:2].substring() == text[1:10]
assert len(tokens.slice_by_text(5, 10)) == 1
assert len(tokens.slice_by_text(5, 11)) == 1
assert len(tokens.slice_by_text(3, 13)) == 3
def test_sentence_tokenizer():
from bistring import SentenceTokenizer
text = bistr('The following sentence is true. The preceeding sentence, surprisingly, is false.')
tokenizer = SentenceTokenizer('en_US')
assert isinstance(tokenizer, Tokenizer)
tokens = tokenizer.tokenize(text)
assert tokens.text == text
assert len(tokens) == 2
assert tokens[0].text == text[:33]
assert tokens[1].text == text[33:]
|
bistring/python/tests/test_token.py/0
|
{
"file_path": "bistring/python/tests/test_token.py",
"repo_id": "bistring",
"token_count": 2020
}
| 436 |
{
"$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentParameters.json#",
"contentVersion": "1.0.0.0",
"parameters": {
"azureBotId": {
"value": ""
},
"azureBotSku": {
"value": "S1"
},
"azureBotRegion": {
"value": "global"
},
"botEndpoint": {
"value": ""
},
"appId": {
"value": ""
}
}
}
|
botbuilder-python/generators/app/templates/core/{{cookiecutter.bot_name}}/deploymentTemplates/deployUseExistResourceGroup/parameters-for-template-AzureBot-with-rg.json/0
|
{
"file_path": "botbuilder-python/generators/app/templates/core/{{cookiecutter.bot_name}}/deploymentTemplates/deployUseExistResourceGroup/parameters-for-template-AzureBot-with-rg.json",
"repo_id": "botbuilder-python",
"token_count": 276
}
| 437 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from .luis_helper import Intent, LuisHelper
from .dialog_helper import DialogHelper
__all__ = [
"DialogHelper",
"LuisHelper",
"Intent"
]
|
botbuilder-python/generators/app/templates/core/{{cookiecutter.bot_name}}/helpers/__init__.py/0
|
{
"file_path": "botbuilder-python/generators/app/templates/core/{{cookiecutter.bot_name}}/helpers/__init__.py",
"repo_id": "botbuilder-python",
"token_count": 81
}
| 438 |
{
"$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentParameters.json#",
"contentVersion": "1.0.0.0",
"parameters": {
"groupName": {
"value": ""
},
"groupLocation": {
"value": ""
},
"azureBotId": {
"value": ""
},
"azureBotSku": {
"value": "S1"
},
"azureBotRegion": {
"value": "global"
},
"botEndpoint": {
"value": ""
},
"appId": {
"value": ""
}
}
}
|
botbuilder-python/generators/app/templates/echo/{{cookiecutter.bot_name}}/deploymentTemplates/deployWithNewResourceGroup/parameters-for-template-AzureBot-new-rg.json/0
|
{
"file_path": "botbuilder-python/generators/app/templates/echo/{{cookiecutter.bot_name}}/deploymentTemplates/deployWithNewResourceGroup/parameters-for-template-AzureBot-new-rg.json",
"repo_id": "botbuilder-python",
"token_count": 352
}
| 439 |
{
"$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.0",
"parameters": {
"azureBotId": {
"type": "string",
"metadata": {
"description": "The globally unique and immutable bot ID."
}
},
"azureBotSku": {
"defaultValue": "S1",
"type": "string",
"metadata": {
"description": "The pricing tier of the Bot Service Registration. Allowed values are: F0, S1(default)."
}
},
"azureBotRegion": {
"type": "string",
"defaultValue": "global",
"metadata": {
"description": "Specifies the location of the new AzureBot. Allowed values are: global(default), westeurope."
}
},
"botEndpoint": {
"type": "string",
"metadata": {
"description": "Use to handle client messages, Such as https://<botappServiceName>.azurewebsites.net/api/messages."
}
},
"appId": {
"type": "string",
"metadata": {
"description": "Active Directory App ID or User-Assigned Managed Identity Client ID, set as MicrosoftAppId in the Web App's Application Settings."
}
}
},
"resources": [
{
"apiVersion": "2021-05-01-preview",
"type": "Microsoft.BotService/botServices",
"name": "[parameters('azureBotId')]",
"location": "[parameters('azureBotRegion')]",
"kind": "azurebot",
"sku": {
"name": "[parameters('azureBotSku')]"
},
"properties": {
"name": "[parameters('azureBotId')]",
"displayName": "[parameters('azureBotId')]",
"iconUrl": "https://docs.botframework.com/static/devportal/client/images/bot-framework-default.png",
"endpoint": "[parameters('botEndpoint')]",
"msaAppId": "[parameters('appId')]",
"luisAppIds": [],
"schemaTransformationVersion": "1.3",
"isCmekEnabled": false,
"isIsolated": false
}
}
]
}
|
botbuilder-python/generators/app/templates/empty/{{cookiecutter.bot_name}}/deploymentTemplates/deployUseExistResourceGroup/template-AzureBot-with-rg.json/0
|
{
"file_path": "botbuilder-python/generators/app/templates/empty/{{cookiecutter.bot_name}}/deploymentTemplates/deployUseExistResourceGroup/template-AzureBot-with-rg.json",
"repo_id": "botbuilder-python",
"token_count": 1188
}
| 440 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from typing import List
from botbuilder.adapters.slack.slack_message import SlackMessage
class SlackEvent:
"""
Wrapper class for an incoming slack event.
"""
def __init__(self, **kwargs):
self.client_msg_id = kwargs.get("client_msg_id")
self.type = kwargs.get("type")
self.subtype = kwargs.get("subtype")
self.text = kwargs.get("text")
self.ts = kwargs.get("ts") # pylint: disable=invalid-name
self.team = kwargs.get("team")
self.channel = kwargs.get("channel")
self.channel_id = kwargs.get("channel_id")
self.event_ts = kwargs.get("event_ts")
self.channel_type = kwargs.get("channel_type")
self.thread_ts = kwargs.get("thread_ts")
self.user = kwargs.get("user")
self.user_id = kwargs.get("user_id")
self.bot_id = kwargs.get("bot_id")
self.actions: List[str] = kwargs.get("actions")
self.item = kwargs.get("item")
self.item_channel = kwargs.get("item_channel")
self.files: [] = kwargs.get("files")
self.message = (
None if "message" not in kwargs else SlackMessage(**kwargs.get("message"))
)
|
botbuilder-python/libraries/botbuilder-adapters-slack/botbuilder/adapters/slack/slack_event.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-adapters-slack/botbuilder/adapters/slack/slack_event.py",
"repo_id": "botbuilder-python",
"token_count": 562
}
| 441 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import json
from typing import Dict, List, Tuple, Union
from botbuilder.core import (
BotAssert,
IntentScore,
Recognizer,
RecognizerResult,
TurnContext,
)
from botbuilder.schema import ActivityTypes
from . import LuisApplication, LuisPredictionOptions, LuisTelemetryConstants
from .luis_recognizer_v3 import LuisRecognizerV3
from .luis_recognizer_v2 import LuisRecognizerV2
from .luis_recognizer_options_v2 import LuisRecognizerOptionsV2
from .luis_recognizer_options_v3 import LuisRecognizerOptionsV3
class LuisRecognizer(Recognizer):
"""
A LUIS based implementation of :class:`botbuilder.core.Recognizer`.
"""
# The value type for a LUIS trace activity.
luis_trace_type: str = "https://www.luis.ai/schemas/trace"
# The context label for a LUIS trace activity.
luis_trace_label: str = "Luis Trace"
def __init__(
self,
application: Union[LuisApplication, str],
prediction_options: Union[
LuisRecognizerOptionsV2, LuisRecognizerOptionsV3, LuisPredictionOptions
] = None,
include_api_results: bool = False,
):
"""Initializes a new instance of the :class:`LuisRecognizer` class.
:param application: The LUIS application to use to recognize text.
:type application: :class:`LuisApplication`
:param prediction_options: The LUIS prediction options to use, defaults to None.
:type prediction_options: :class:`LuisPredictionOptions`, optional
:param include_api_results: True to include raw LUIS API response, defaults to False.
:type include_api_results: bool, optional
:raises: TypeError
"""
if isinstance(application, LuisApplication):
self._application = application
elif isinstance(application, str):
self._application = LuisApplication.from_application_endpoint(application)
else:
raise TypeError(
"LuisRecognizer.__init__(): application is not an instance of LuisApplication or str."
)
self._options = prediction_options or LuisPredictionOptions()
self._include_api_results = include_api_results or (
prediction_options.include_api_results
if isinstance(
prediction_options, (LuisRecognizerOptionsV3, LuisRecognizerOptionsV2)
)
else False
)
self.telemetry_client = self._options.telemetry_client
self.log_personal_information = self._options.log_personal_information
@staticmethod
def top_intent(
results: RecognizerResult, default_intent: str = "None", min_score: float = 0.0
) -> str:
"""Returns the name of the top scoring intent from a set of LUIS results.
:param results: Result set to be searched.
:type results: :class:`botbuilder.core.RecognizerResult`
:param default_intent: Intent name to return should a top intent be found, defaults to None.
:type default_intent: str, optional
:param min_score: Minimum score needed for an intent to be considered as a top intent. If all intents in the set
are below this threshold then the `defaultIntent` is returned, defaults to 0.0.
:type min_score: float, optional
:raises: TypeError
:return: The top scoring intent name.
:rtype: str
"""
if results is None:
raise TypeError("LuisRecognizer.top_intent(): results cannot be None.")
top_intent: str = None
top_score: float = -1.0
if results.intents:
for intent_name, intent_score in results.intents.items():
score = intent_score.score
if score > top_score and score >= min_score:
top_intent = intent_name
top_score = score
return top_intent or default_intent
async def recognize( # pylint: disable=arguments-differ
self,
turn_context: TurnContext,
telemetry_properties: Dict[str, str] = None,
telemetry_metrics: Dict[str, float] = None,
luis_prediction_options: LuisPredictionOptions = None,
) -> RecognizerResult:
"""Return results of the analysis (suggested actions and intents).
:param turn_context: Context object containing information for a single conversation turn with a user.
:type turn_context: :class:`botbuilder.core.TurnContext`
:param telemetry_properties: Additional properties to be logged to telemetry with the LuisResult event, defaults
to None.
:type telemetry_properties: :class:`typing.Dict[str, str]`, optional
:param telemetry_metrics: Additional metrics to be logged to telemetry with the LuisResult event, defaults to
None.
:type telemetry_metrics: :class:`typing.Dict[str, float]`, optional
:return: The LUIS results of the analysis of the current message text in the current turn's context activity.
:rtype: :class:`botbuilder.core.RecognizerResult`
"""
return await self._recognize_internal(
turn_context,
telemetry_properties,
telemetry_metrics,
luis_prediction_options,
)
def on_recognizer_result(
self,
recognizer_result: RecognizerResult,
turn_context: TurnContext,
telemetry_properties: Dict[str, str] = None,
telemetry_metrics: Dict[str, float] = None,
):
"""Invoked prior to a LuisResult being logged.
:param recognizer_result: The LuisResult for the call.
:type recognizer_result: :class:`botbuilder.core.RecognizerResult`
:param turn_context: Context object containing information for a single turn of conversation with a user.
:type turn_context: :class:`botbuilder.core.TurnContext`
:param telemetry_properties: Additional properties to be logged to telemetry with the LuisResult event, defaults
to None.
:type telemetry_properties: :class:`typing.Dict[str, str]`, optional
:param telemetry_metrics: Additional metrics to be logged to telemetry with the LuisResult event, defaults
to None.
:type telemetry_metrics: :class:`typing.Dict[str, float]`, optional
"""
properties = self.fill_luis_event_properties(
recognizer_result, turn_context, telemetry_properties
)
# Track the event
self.telemetry_client.track_event(
LuisTelemetryConstants.luis_result, properties, telemetry_metrics
)
@staticmethod
def _get_top_k_intent_score(
intent_names: List[str],
intents: Dict[str, IntentScore],
index: int, # pylint: disable=unused-argument
) -> Tuple[str, str]:
intent_name = ""
intent_score = "0.00"
if intent_names:
intent_name = intent_names[0]
if intents[intent_name] is not None:
intent_score = "{:.2f}".format(intents[intent_name].score)
return intent_name, intent_score
def fill_luis_event_properties(
self,
recognizer_result: RecognizerResult,
turn_context: TurnContext,
telemetry_properties: Dict[str, str] = None,
) -> Dict[str, str]:
"""Fills the event properties for LuisResult event for telemetry.
These properties are logged when the recognizer is called.
:param recognizer_result: Last activity sent from user.
:type recognizer_result: :class:`botbuilder.core.RecognizerResult`
:param turn_context: Context object containing information for a single turn of conversation with a user.
:type turn_context: :class:`botbuilder.core.TurnContext`
:param telemetry_properties: Additional properties to be logged to telemetry with the LuisResult event, defaults
to None.
:type telemetry_properties: :class:`typing.Dict[str, str]`, optional
:return: A dictionary sent as "Properties" to :func:`botbuilder.core.BotTelemetryClient.track_event` for the
BotMessageSend event.
:rtype: `typing.Dict[str, str]`
"""
intents = recognizer_result.intents
top_two_intents = (
sorted(intents.keys(), key=lambda k: intents[k].score, reverse=True)[:2]
if intents
else []
)
intent_name, intent_score = LuisRecognizer._get_top_k_intent_score(
top_two_intents, intents, index=0
)
intent2_name, intent2_score = LuisRecognizer._get_top_k_intent_score(
top_two_intents, intents, index=1
)
# Add the intent score and conversation id properties
properties: Dict[str, str] = {
LuisTelemetryConstants.application_id_property: self._application.application_id,
LuisTelemetryConstants.intent_property: intent_name,
LuisTelemetryConstants.intent_score_property: intent_score,
LuisTelemetryConstants.intent2_property: intent2_name,
LuisTelemetryConstants.intent_score2_property: intent2_score,
LuisTelemetryConstants.from_id_property: turn_context.activity.from_property.id,
}
sentiment = recognizer_result.properties.get("sentiment")
if sentiment is not None and isinstance(sentiment, Dict):
label = sentiment.get("label")
if label is not None:
properties[LuisTelemetryConstants.sentiment_label_property] = str(label)
score = sentiment.get("score")
if score is not None:
properties[LuisTelemetryConstants.sentiment_score_property] = str(score)
entities = None
if recognizer_result.entities is not None:
entities = json.dumps(recognizer_result.entities)
properties[LuisTelemetryConstants.entities_property] = entities
# Use the LogPersonalInformation flag to toggle logging PII data, text is a common example
if self.log_personal_information and turn_context.activity.text:
properties[
LuisTelemetryConstants.question_property
] = turn_context.activity.text
# Additional Properties can override "stock" properties.
if telemetry_properties is not None:
for key in telemetry_properties:
properties[key] = telemetry_properties[key]
return properties
async def _recognize_internal(
self,
turn_context: TurnContext,
telemetry_properties: Dict[str, str],
telemetry_metrics: Dict[str, float],
luis_prediction_options: Union[
LuisPredictionOptions, LuisRecognizerOptionsV2, LuisRecognizerOptionsV3
] = None,
) -> RecognizerResult:
BotAssert.context_not_none(turn_context)
if turn_context.activity.type != ActivityTypes.message:
return None
utterance: str = (
turn_context.activity.text if turn_context.activity is not None else None
)
recognizer_result: RecognizerResult = None
if luis_prediction_options:
options = luis_prediction_options
else:
options = self._options
if not utterance or utterance.isspace():
recognizer_result = RecognizerResult(
text=utterance, intents={"": IntentScore(score=1.0)}, entities={}
)
else:
luis_recognizer = self._build_recognizer(options)
recognizer_result = await luis_recognizer.recognizer_internal(turn_context)
# Log telemetry
self.on_recognizer_result(
recognizer_result, turn_context, telemetry_properties, telemetry_metrics
)
return recognizer_result
def _merge_options(
self,
user_defined_options: Union[
LuisRecognizerOptionsV3, LuisRecognizerOptionsV2, LuisPredictionOptions
],
) -> LuisPredictionOptions:
merged_options = LuisPredictionOptions()
merged_options.__dict__.update(user_defined_options.__dict__)
return merged_options
def _build_recognizer(
self,
luis_prediction_options: Union[
LuisRecognizerOptionsV3, LuisRecognizerOptionsV2, LuisPredictionOptions
],
):
if isinstance(luis_prediction_options, LuisRecognizerOptionsV3):
return LuisRecognizerV3(self._application, luis_prediction_options)
if isinstance(luis_prediction_options, LuisRecognizerOptionsV2):
return LuisRecognizerV3(self._application, luis_prediction_options)
recognizer_options = LuisRecognizerOptionsV2(
luis_prediction_options.bing_spell_check_subscription_key,
luis_prediction_options.include_all_intents,
luis_prediction_options.include_instance_data,
luis_prediction_options.log,
luis_prediction_options.spell_check,
luis_prediction_options.staging,
luis_prediction_options.timeout,
luis_prediction_options.timezone_offset,
self._include_api_results,
luis_prediction_options.telemetry_client,
luis_prediction_options.log_personal_information,
)
return LuisRecognizerV2(self._application, recognizer_options)
|
botbuilder-python/libraries/botbuilder-ai/botbuilder/ai/luis/luis_recognizer.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-ai/botbuilder/ai/luis/luis_recognizer.py",
"repo_id": "botbuilder-python",
"token_count": 5420
}
| 442 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from msrest.serialization import Model
class GenerateAnswerRequestBody(Model):
"""Question used as the payload body for QnA Maker's Generate Answer API."""
_attribute_map = {
"question": {"key": "question", "type": "str"},
"top": {"key": "top", "type": "int"},
"score_threshold": {"key": "scoreThreshold", "type": "float"},
"strict_filters": {"key": "strictFilters", "type": "[Metadata]"},
"context": {"key": "context", "type": "QnARequestContext"},
"qna_id": {"key": "qnaId", "type": "int"},
"is_test": {"key": "isTest", "type": "bool"},
"ranker_type": {"key": "rankerType", "type": "RankerTypes"},
"strict_filters_join_operator": {
"key": "strictFiltersCompoundOperationType",
"type": "str",
},
}
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.question = kwargs.get("question", None)
self.top = kwargs.get("top", None)
self.score_threshold = kwargs.get("score_threshold", None)
self.strict_filters = kwargs.get("strict_filters", None)
self.context = kwargs.get("context", None)
self.qna_id = kwargs.get("qna_id", None)
self.is_test = kwargs.get("is_test", None)
self.ranker_type = kwargs.get("ranker_type", None)
self.strict_filters_join_operator = kwargs.get(
"strict_filters_join_operator", None
)
|
botbuilder-python/libraries/botbuilder-ai/botbuilder/ai/qna/models/generate_answer_request_body.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-ai/botbuilder/ai/qna/models/generate_answer_request_body.py",
"repo_id": "botbuilder-python",
"token_count": 668
}
| 443 |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
from .active_learning_utils import ActiveLearningUtils
from .generate_answer_utils import GenerateAnswerUtils
from .http_request_utils import HttpRequestUtils
from .qna_telemetry_constants import QnATelemetryConstants
from .train_utils import TrainUtils
from .qna_card_builder import QnACardBuilder
__all__ = [
"ActiveLearningUtils",
"GenerateAnswerUtils",
"HttpRequestUtils",
"QnATelemetryConstants",
"TrainUtils",
"QnACardBuilder",
]
|
botbuilder-python/libraries/botbuilder-ai/botbuilder/ai/qna/utils/__init__.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-ai/botbuilder/ai/qna/utils/__init__.py",
"repo_id": "botbuilder-python",
"token_count": 210
}
| 444 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from typing import Dict
from botbuilder.ai.luis import LuisRecognizer, LuisTelemetryConstants
from botbuilder.core import RecognizerResult, TurnContext
class TelemetryOverrideRecognizer(LuisRecognizer):
def __init__(self, *args, **kwargs):
super(TelemetryOverrideRecognizer, self).__init__(*args, **kwargs)
def on_recognizer_result(
self,
recognizer_result: RecognizerResult,
turn_context: TurnContext,
telemetry_properties: Dict[str, str] = None,
telemetry_metrics: Dict[str, float] = None,
):
if "MyImportantProperty" not in telemetry_properties:
telemetry_properties["MyImportantProperty"] = "myImportantValue"
# Log event
self.telemetry_client.track_event(
LuisTelemetryConstants.luis_result, telemetry_properties, telemetry_metrics
)
# Create second event.
second_event_properties: Dict[str, str] = {
"MyImportantProperty2": "myImportantValue2"
}
self.telemetry_client.track_event("MySecondEvent", second_event_properties)
|
botbuilder-python/libraries/botbuilder-ai/tests/luis/telemetry_override_recognizer.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-ai/tests/luis/telemetry_override_recognizer.py",
"repo_id": "botbuilder-python",
"token_count": 449
}
| 445 |
{
"query": "Please deliver it to 98033 WA",
"topScoringIntent": {
"intent": "Delivery",
"score": 0.8785189
},
"intents": [
{
"intent": "Delivery",
"score": 0.8785189
}
],
"entities": [
{
"entity": "98033 wa",
"type": "Address",
"startIndex": 21,
"endIndex": 28,
"score": 0.864295959
},
{
"entity": "98033",
"type": "builtin.number",
"startIndex": 21,
"endIndex": 25,
"resolution": {
"value": "98033"
}
},
{
"entity": "wa",
"type": "State",
"startIndex": 27,
"endIndex": 28,
"score": 0.8981885
}
],
"compositeEntities": [
{
"parentType": "Address",
"value": "98033 wa",
"children": [
{
"type": "builtin.number",
"value": "98033"
},
{
"type": "State",
"value": "wa"
}
]
}
]
}
|
botbuilder-python/libraries/botbuilder-ai/tests/luis/test_data/MultipleIntents_CompositeEntityModel.json/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-ai/tests/luis/test_data/MultipleIntents_CompositeEntityModel.json",
"repo_id": "botbuilder-python",
"token_count": 799
}
| 446 |
{
"answers": [
{
"questions": [
"Where can I buy cleaning products?"
],
"answer": "Any DIY store",
"score": 100,
"id": 55,
"source": "Editorial",
"metadata": [],
"context": {
"isContextOnly": true,
"prompts": []
}
}
]
}
|
botbuilder-python/libraries/botbuilder-ai/tests/qna/test_data/AnswerWithHighScoreProvidedContext.json/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-ai/tests/qna/test_data/AnswerWithHighScoreProvidedContext.json",
"repo_id": "botbuilder-python",
"token_count": 197
}
| 447 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
# pylint: disable=protected-access
# pylint: disable=too-many-lines
import unittest
from os import path
from typing import List, Dict
from unittest.mock import patch
import json
import requests
from aiohttp import ClientSession
import aiounittest
from botbuilder.ai.qna import QnAMakerEndpoint, QnAMaker, QnAMakerOptions
from botbuilder.ai.qna.models import (
FeedbackRecord,
JoinOperator,
Metadata,
QueryResult,
QnARequestContext,
)
from botbuilder.ai.qna.utils import HttpRequestUtils, QnATelemetryConstants
from botbuilder.ai.qna.models import GenerateAnswerRequestBody
from botbuilder.core import BotAdapter, BotTelemetryClient, TurnContext
from botbuilder.core.adapters import TestAdapter
from botbuilder.schema import (
Activity,
ActivityTypes,
ChannelAccount,
ConversationAccount,
)
class TestContext(TurnContext):
__test__ = False
def __init__(self, request):
super().__init__(TestAdapter(), request)
self.sent: List[Activity] = list()
self.on_send_activities(self.capture_sent_activities)
async def capture_sent_activities(
self, context: TurnContext, activities, next
): # pylint: disable=unused-argument
self.sent += activities
context.responded = True
class QnaApplicationTest(aiounittest.AsyncTestCase):
# Note this is NOT a real QnA Maker application ID nor a real QnA Maker subscription-key
# theses are GUIDs edited to look right to the parsing and validation code.
_knowledge_base_id: str = "f028d9k3-7g9z-11d3-d300-2b8x98227q8w"
_endpoint_key: str = "1k997n7w-207z-36p3-j2u1-09tas20ci6011"
_host: str = "https://dummyqnahost.azurewebsites.net/qnamaker"
tests_endpoint = QnAMakerEndpoint(_knowledge_base_id, _endpoint_key, _host)
def test_qnamaker_construction(self):
# Arrange
endpoint = self.tests_endpoint
# Act
qna = QnAMaker(endpoint)
endpoint = qna._endpoint
# Assert
self.assertEqual(
"f028d9k3-7g9z-11d3-d300-2b8x98227q8w", endpoint.knowledge_base_id
)
self.assertEqual("1k997n7w-207z-36p3-j2u1-09tas20ci6011", endpoint.endpoint_key)
self.assertEqual(
"https://dummyqnahost.azurewebsites.net/qnamaker", endpoint.host
)
def test_endpoint_with_empty_kbid(self):
empty_kbid = ""
with self.assertRaises(TypeError):
QnAMakerEndpoint(empty_kbid, self._endpoint_key, self._host)
def test_endpoint_with_empty_endpoint_key(self):
empty_endpoint_key = ""
with self.assertRaises(TypeError):
QnAMakerEndpoint(self._knowledge_base_id, empty_endpoint_key, self._host)
def test_endpoint_with_emptyhost(self):
with self.assertRaises(TypeError):
QnAMakerEndpoint(self._knowledge_base_id, self._endpoint_key, "")
def test_qnamaker_with_none_endpoint(self):
with self.assertRaises(TypeError):
QnAMaker(None)
def test_set_default_options_with_no_options_arg(self):
qna_without_options = QnAMaker(self.tests_endpoint)
options = qna_without_options._generate_answer_helper.options
default_threshold = 0.3
default_top = 1
default_strict_filters = []
self.assertEqual(default_threshold, options.score_threshold)
self.assertEqual(default_top, options.top)
self.assertEqual(default_strict_filters, options.strict_filters)
def test_options_passed_to_ctor(self):
options = QnAMakerOptions(
score_threshold=0.8,
timeout=9000,
top=5,
strict_filters=[Metadata(**{"movie": "disney"})],
)
qna_with_options = QnAMaker(self.tests_endpoint, options)
actual_options = qna_with_options._generate_answer_helper.options
expected_threshold = 0.8
expected_timeout = 9000
expected_top = 5
expected_strict_filters = [Metadata(**{"movie": "disney"})]
self.assertEqual(expected_threshold, actual_options.score_threshold)
self.assertEqual(expected_timeout, actual_options.timeout)
self.assertEqual(expected_top, actual_options.top)
self.assertEqual(
expected_strict_filters[0].name, actual_options.strict_filters[0].name
)
self.assertEqual(
expected_strict_filters[0].value, actual_options.strict_filters[0].value
)
async def test_returns_answer(self):
# Arrange
question: str = "how do I clean the stove?"
response_path: str = "ReturnsAnswer.json"
# Act
result = await QnaApplicationTest._get_service_result(question, response_path)
first_answer = result[0]
# Assert
self.assertIsNotNone(result)
self.assertEqual(1, len(result))
self.assertEqual(
"BaseCamp: You can use a damp rag to clean around the Power Pack",
first_answer.answer,
)
async def test_active_learning_enabled_status(self):
# Arrange
question: str = "how do I clean the stove?"
response_path: str = "ReturnsAnswer.json"
# Act
result = await QnaApplicationTest._get_service_result_raw(
question, response_path
)
# Assert
self.assertIsNotNone(result)
self.assertEqual(1, len(result.answers))
self.assertFalse(result.active_learning_enabled)
async def test_returns_answer_with_strict_filters_with_or_operator(self):
# Arrange
question: str = "Where can you find"
response_path: str = "RetrunsAnswer_WithStrictFilter_Or_Operator.json"
response_json = QnaApplicationTest._get_json_for_file(response_path)
strict_filters = [
Metadata(name="species", value="human"),
Metadata(name="type", value="water"),
]
options = QnAMakerOptions(
top=5,
strict_filters=strict_filters,
strict_filters_join_operator=JoinOperator.OR,
)
qna = QnAMaker(endpoint=QnaApplicationTest.tests_endpoint)
context = QnaApplicationTest._get_context(question, TestAdapter())
# Act
with patch(
"aiohttp.ClientSession.post",
return_value=aiounittest.futurized(response_json),
) as mock_http_client:
result = await qna.get_answers_raw(context, options)
serialized_http_req_args = mock_http_client.call_args[1]["data"]
req_args = json.loads(serialized_http_req_args)
# Assert
self.assertIsNotNone(result)
self.assertEqual(3, len(result.answers))
self.assertEqual(
JoinOperator.OR, req_args["strictFiltersCompoundOperationType"]
)
req_args_strict_filters = req_args["strictFilters"]
first_filter = strict_filters[0]
self.assertEqual(first_filter.name, req_args_strict_filters[0]["name"])
self.assertEqual(first_filter.value, req_args_strict_filters[0]["value"])
second_filter = strict_filters[1]
self.assertEqual(second_filter.name, req_args_strict_filters[1]["name"])
self.assertEqual(second_filter.value, req_args_strict_filters[1]["value"])
async def test_returns_answer_with_strict_filters_with_and_operator(self):
# Arrange
question: str = "Where can you find"
response_path: str = "RetrunsAnswer_WithStrictFilter_And_Operator.json"
response_json = QnaApplicationTest._get_json_for_file(response_path)
strict_filters = [
Metadata(name="species", value="human"),
Metadata(name="type", value="water"),
]
options = QnAMakerOptions(
top=5,
strict_filters=strict_filters,
strict_filters_join_operator=JoinOperator.AND,
)
qna = QnAMaker(endpoint=QnaApplicationTest.tests_endpoint)
context = QnaApplicationTest._get_context(question, TestAdapter())
# Act
with patch(
"aiohttp.ClientSession.post",
return_value=aiounittest.futurized(response_json),
) as mock_http_client:
result = await qna.get_answers_raw(context, options)
serialized_http_req_args = mock_http_client.call_args[1]["data"]
req_args = json.loads(serialized_http_req_args)
# Assert
self.assertIsNotNone(result)
self.assertEqual(1, len(result.answers))
self.assertEqual(
JoinOperator.AND, req_args["strictFiltersCompoundOperationType"]
)
req_args_strict_filters = req_args["strictFilters"]
first_filter = strict_filters[0]
self.assertEqual(first_filter.name, req_args_strict_filters[0]["name"])
self.assertEqual(first_filter.value, req_args_strict_filters[0]["value"])
second_filter = strict_filters[1]
self.assertEqual(second_filter.name, req_args_strict_filters[1]["name"])
self.assertEqual(second_filter.value, req_args_strict_filters[1]["value"])
async def test_returns_answer_using_requests_module(self):
question: str = "how do I clean the stove?"
response_path: str = "ReturnsAnswer.json"
response_json = QnaApplicationTest._get_json_for_file(response_path)
qna = QnAMaker(endpoint=QnaApplicationTest.tests_endpoint, http_client=requests)
context = QnaApplicationTest._get_context(question, TestAdapter())
with patch("requests.post", return_value=response_json):
result = await qna.get_answers_raw(context)
answers = result.answers
self.assertIsNotNone(result)
self.assertEqual(1, len(answers))
self.assertEqual(
"BaseCamp: You can use a damp rag to clean around the Power Pack",
answers[0].answer,
)
async def test_returns_answer_using_options(self):
# Arrange
question: str = "up"
response_path: str = "AnswerWithOptions.json"
options = QnAMakerOptions(
score_threshold=0.8, top=5, strict_filters=[Metadata(**{"movie": "disney"})]
)
# Act
result = await QnaApplicationTest._get_service_result(
question, response_path, options=options
)
first_answer = result[0]
has_at_least_1_ans = True
first_metadata = first_answer.metadata[0]
# Assert
self.assertIsNotNone(result)
self.assertEqual(has_at_least_1_ans, len(result) >= 1)
self.assertTrue(first_answer.answer[0])
self.assertEqual("is a movie", first_answer.answer)
self.assertTrue(first_answer.score >= options.score_threshold)
self.assertEqual("movie", first_metadata.name)
self.assertEqual("disney", first_metadata.value)
async def test_trace_test(self):
activity = Activity(
type=ActivityTypes.message,
text="how do I clean the stove?",
conversation=ConversationAccount(),
recipient=ChannelAccount(),
from_property=ChannelAccount(),
)
response_json = QnaApplicationTest._get_json_for_file("ReturnsAnswer.json")
qna = QnAMaker(QnaApplicationTest.tests_endpoint)
context = TestContext(activity)
with patch(
"aiohttp.ClientSession.post",
return_value=aiounittest.futurized(response_json),
):
result = await qna.get_answers(context)
qna_trace_activities = list(
filter(
lambda act: act.type == "trace" and act.name == "QnAMaker",
context.sent,
)
)
trace_activity = qna_trace_activities[0]
self.assertEqual("trace", trace_activity.type)
self.assertEqual("QnAMaker", trace_activity.name)
self.assertEqual("QnAMaker Trace", trace_activity.label)
self.assertEqual(
"https://www.qnamaker.ai/schemas/trace", trace_activity.value_type
)
self.assertEqual(True, hasattr(trace_activity, "value"))
self.assertEqual(True, hasattr(trace_activity.value, "message"))
self.assertEqual(True, hasattr(trace_activity.value, "query_results"))
self.assertEqual(True, hasattr(trace_activity.value, "score_threshold"))
self.assertEqual(True, hasattr(trace_activity.value, "top"))
self.assertEqual(True, hasattr(trace_activity.value, "strict_filters"))
self.assertEqual(
self._knowledge_base_id, trace_activity.value.knowledge_base_id
)
return result
async def test_returns_answer_with_timeout(self):
question: str = "how do I clean the stove?"
options = QnAMakerOptions(timeout=999999)
qna = QnAMaker(QnaApplicationTest.tests_endpoint, options)
context = QnaApplicationTest._get_context(question, TestAdapter())
response_json = QnaApplicationTest._get_json_for_file("ReturnsAnswer.json")
with patch(
"aiohttp.ClientSession.post",
return_value=aiounittest.futurized(response_json),
):
result = await qna.get_answers(context, options)
self.assertIsNotNone(result)
self.assertEqual(
options.timeout, qna._generate_answer_helper.options.timeout
)
async def test_returns_answer_using_requests_module_with_no_timeout(self):
url = f"{QnaApplicationTest._host}/knowledgebases/{QnaApplicationTest._knowledge_base_id}/generateAnswer"
question = GenerateAnswerRequestBody(
question="how do I clean the stove?",
top=1,
score_threshold=0.3,
strict_filters=[],
context=None,
qna_id=None,
is_test=False,
ranker_type="Default",
)
response_path = "ReturnsAnswer.json"
response_json = QnaApplicationTest._get_json_for_file(response_path)
http_request_helper = HttpRequestUtils(requests)
with patch("requests.post", return_value=response_json):
result = await http_request_helper.execute_http_request(
url, question, QnaApplicationTest.tests_endpoint, timeout=None
)
answers = result["answers"]
self.assertIsNotNone(result)
self.assertEqual(1, len(answers))
self.assertEqual(
"BaseCamp: You can use a damp rag to clean around the Power Pack",
answers[0]["answer"],
)
async def test_telemetry_returns_answer(self):
# Arrange
question: str = "how do I clean the stove?"
response_json = QnaApplicationTest._get_json_for_file("ReturnsAnswer.json")
telemetry_client = unittest.mock.create_autospec(BotTelemetryClient)
log_personal_information = True
context = QnaApplicationTest._get_context(question, TestAdapter())
qna = QnAMaker(
QnaApplicationTest.tests_endpoint,
telemetry_client=telemetry_client,
log_personal_information=log_personal_information,
)
# Act
with patch(
"aiohttp.ClientSession.post",
return_value=aiounittest.futurized(response_json),
):
results = await qna.get_answers(context)
telemetry_args = telemetry_client.track_event.call_args_list[0][1]
telemetry_properties = telemetry_args["properties"]
telemetry_metrics = telemetry_args["measurements"]
number_of_args = len(telemetry_args)
first_answer = telemetry_args["properties"][
QnATelemetryConstants.answer_property
]
expected_answer = (
"BaseCamp: You can use a damp rag to clean around the Power Pack"
)
# Assert - Check Telemetry logged.
self.assertEqual(1, telemetry_client.track_event.call_count)
self.assertEqual(3, number_of_args)
self.assertEqual("QnaMessage", telemetry_args["name"])
self.assertTrue("answer" in telemetry_properties)
self.assertTrue("knowledgeBaseId" in telemetry_properties)
self.assertTrue("matchedQuestion" in telemetry_properties)
self.assertTrue("question" in telemetry_properties)
self.assertTrue("questionId" in telemetry_properties)
self.assertTrue("articleFound" in telemetry_properties)
self.assertEqual(expected_answer, first_answer)
self.assertTrue("score" in telemetry_metrics)
self.assertEqual(1, telemetry_metrics["score"])
# Assert - Validate we didn't break QnA functionality.
self.assertIsNotNone(results)
self.assertEqual(1, len(results))
self.assertEqual(expected_answer, results[0].answer)
self.assertEqual("Editorial", results[0].source)
async def test_telemetry_returns_answer_when_no_answer_found_in_kb(self):
# Arrange
question: str = "gibberish question"
response_json = QnaApplicationTest._get_json_for_file("NoAnswerFoundInKb.json")
telemetry_client = unittest.mock.create_autospec(BotTelemetryClient)
qna = QnAMaker(
QnaApplicationTest.tests_endpoint,
telemetry_client=telemetry_client,
log_personal_information=True,
)
context = QnaApplicationTest._get_context(question, TestAdapter())
# Act
with patch(
"aiohttp.ClientSession.post",
return_value=aiounittest.futurized(response_json),
):
results = await qna.get_answers(context)
telemetry_args = telemetry_client.track_event.call_args_list[0][1]
telemetry_properties = telemetry_args["properties"]
number_of_args = len(telemetry_args)
first_answer = telemetry_args["properties"][
QnATelemetryConstants.answer_property
]
expected_answer = "No Qna Answer matched"
expected_matched_question = "No Qna Question matched"
# Assert - Check Telemetry logged.
self.assertEqual(1, telemetry_client.track_event.call_count)
self.assertEqual(3, number_of_args)
self.assertEqual("QnaMessage", telemetry_args["name"])
self.assertTrue("answer" in telemetry_properties)
self.assertTrue("knowledgeBaseId" in telemetry_properties)
self.assertTrue("matchedQuestion" in telemetry_properties)
self.assertEqual(
expected_matched_question,
telemetry_properties[QnATelemetryConstants.matched_question_property],
)
self.assertTrue("question" in telemetry_properties)
self.assertTrue("questionId" in telemetry_properties)
self.assertTrue("articleFound" in telemetry_properties)
self.assertEqual(expected_answer, first_answer)
# Assert - Validate we didn't break QnA functionality.
self.assertIsNotNone(results)
self.assertEqual(0, len(results))
async def test_telemetry_pii(self):
# Arrange
question: str = "how do I clean the stove?"
response_json = QnaApplicationTest._get_json_for_file("ReturnsAnswer.json")
telemetry_client = unittest.mock.create_autospec(BotTelemetryClient)
log_personal_information = False
context = QnaApplicationTest._get_context(question, TestAdapter())
qna = QnAMaker(
QnaApplicationTest.tests_endpoint,
telemetry_client=telemetry_client,
log_personal_information=log_personal_information,
)
# Act
with patch(
"aiohttp.ClientSession.post",
return_value=aiounittest.futurized(response_json),
):
results = await qna.get_answers(context)
telemetry_args = telemetry_client.track_event.call_args_list[0][1]
telemetry_properties = telemetry_args["properties"]
telemetry_metrics = telemetry_args["measurements"]
number_of_args = len(telemetry_args)
first_answer = telemetry_args["properties"][
QnATelemetryConstants.answer_property
]
expected_answer = (
"BaseCamp: You can use a damp rag to clean around the Power Pack"
)
# Assert - Validate PII properties not logged.
self.assertEqual(1, telemetry_client.track_event.call_count)
self.assertEqual(3, number_of_args)
self.assertEqual("QnaMessage", telemetry_args["name"])
self.assertTrue("answer" in telemetry_properties)
self.assertTrue("knowledgeBaseId" in telemetry_properties)
self.assertTrue("matchedQuestion" in telemetry_properties)
self.assertTrue("question" not in telemetry_properties)
self.assertTrue("questionId" in telemetry_properties)
self.assertTrue("articleFound" in telemetry_properties)
self.assertEqual(expected_answer, first_answer)
self.assertTrue("score" in telemetry_metrics)
self.assertEqual(1, telemetry_metrics["score"])
# Assert - Validate we didn't break QnA functionality.
self.assertIsNotNone(results)
self.assertEqual(1, len(results))
self.assertEqual(expected_answer, results[0].answer)
self.assertEqual("Editorial", results[0].source)
async def test_telemetry_override(self):
# Arrange
question: str = "how do I clean the stove?"
response_json = QnaApplicationTest._get_json_for_file("ReturnsAnswer.json")
context = QnaApplicationTest._get_context(question, TestAdapter())
options = QnAMakerOptions(top=1)
telemetry_client = unittest.mock.create_autospec(BotTelemetryClient)
log_personal_information = False
# Act - Override the QnAMaker object to log custom stuff and honor params passed in.
telemetry_properties: Dict[str, str] = {"id": "MyId"}
qna = QnaApplicationTest.OverrideTelemetry(
QnaApplicationTest.tests_endpoint,
options,
None,
telemetry_client,
log_personal_information,
)
with patch(
"aiohttp.ClientSession.post",
return_value=aiounittest.futurized(response_json),
):
results = await qna.get_answers(context, options, telemetry_properties)
telemetry_args = telemetry_client.track_event.call_args_list
first_call_args = telemetry_args[0][0]
first_call_properties = first_call_args[1]
second_call_args = telemetry_args[1][0]
second_call_properties = second_call_args[1]
expected_answer = (
"BaseCamp: You can use a damp rag to clean around the Power Pack"
)
# Assert
self.assertEqual(2, telemetry_client.track_event.call_count)
self.assertEqual(2, len(first_call_args))
self.assertEqual("QnaMessage", first_call_args[0])
self.assertEqual(2, len(first_call_properties))
self.assertTrue("my_important_property" in first_call_properties)
self.assertEqual(
"my_important_value", first_call_properties["my_important_property"]
)
self.assertTrue("id" in first_call_properties)
self.assertEqual("MyId", first_call_properties["id"])
self.assertEqual("my_second_event", second_call_args[0])
self.assertTrue("my_important_property2" in second_call_properties)
self.assertEqual(
"my_important_value2", second_call_properties["my_important_property2"]
)
# Validate we didn't break QnA functionality.
self.assertIsNotNone(results)
self.assertEqual(1, len(results))
self.assertEqual(expected_answer, results[0].answer)
self.assertEqual("Editorial", results[0].source)
async def test_telemetry_additional_props_metrics(self):
# Arrange
question: str = "how do I clean the stove?"
response_json = QnaApplicationTest._get_json_for_file("ReturnsAnswer.json")
context = QnaApplicationTest._get_context(question, TestAdapter())
options = QnAMakerOptions(top=1)
telemetry_client = unittest.mock.create_autospec(BotTelemetryClient)
log_personal_information = False
# Act
with patch(
"aiohttp.ClientSession.post",
return_value=aiounittest.futurized(response_json),
):
qna = QnAMaker(
QnaApplicationTest.tests_endpoint,
options,
None,
telemetry_client,
log_personal_information,
)
telemetry_properties: Dict[str, str] = {
"my_important_property": "my_important_value"
}
telemetry_metrics: Dict[str, float] = {"my_important_metric": 3.14159}
results = await qna.get_answers(
context, None, telemetry_properties, telemetry_metrics
)
# Assert - Added properties were added.
telemetry_args = telemetry_client.track_event.call_args_list[0][1]
telemetry_properties = telemetry_args["properties"]
expected_answer = (
"BaseCamp: You can use a damp rag to clean around the Power Pack"
)
self.assertEqual(1, telemetry_client.track_event.call_count)
self.assertEqual(3, len(telemetry_args))
self.assertEqual("QnaMessage", telemetry_args["name"])
self.assertTrue("knowledgeBaseId" in telemetry_properties)
self.assertTrue("question" not in telemetry_properties)
self.assertTrue("matchedQuestion" in telemetry_properties)
self.assertTrue("questionId" in telemetry_properties)
self.assertTrue("answer" in telemetry_properties)
self.assertTrue(expected_answer, telemetry_properties["answer"])
self.assertTrue("my_important_property" in telemetry_properties)
self.assertEqual(
"my_important_value", telemetry_properties["my_important_property"]
)
tracked_metrics = telemetry_args["measurements"]
self.assertEqual(2, len(tracked_metrics))
self.assertTrue("score" in tracked_metrics)
self.assertTrue("my_important_metric" in tracked_metrics)
self.assertEqual(3.14159, tracked_metrics["my_important_metric"])
# Assert - Validate we didn't break QnA functionality.
self.assertIsNotNone(results)
self.assertEqual(1, len(results))
self.assertEqual(expected_answer, results[0].answer)
self.assertEqual("Editorial", results[0].source)
async def test_telemetry_additional_props_override(self):
question: str = "how do I clean the stove?"
response_json = QnaApplicationTest._get_json_for_file("ReturnsAnswer.json")
context = QnaApplicationTest._get_context(question, TestAdapter())
options = QnAMakerOptions(top=1)
telemetry_client = unittest.mock.create_autospec(BotTelemetryClient)
log_personal_information = False
# Act - Pass in properties during QnA invocation that override default properties
# NOTE: We are invoking this with PII turned OFF, and passing a PII property (originalQuestion).
qna = QnAMaker(
QnaApplicationTest.tests_endpoint,
options,
None,
telemetry_client,
log_personal_information,
)
telemetry_properties = {
"knowledge_base_id": "my_important_value",
"original_question": "my_important_value2",
}
telemetry_metrics = {"score": 3.14159}
with patch(
"aiohttp.ClientSession.post",
return_value=aiounittest.futurized(response_json),
):
results = await qna.get_answers(
context, None, telemetry_properties, telemetry_metrics
)
# Assert - Added properties were added.
tracked_args = telemetry_client.track_event.call_args_list[0][1]
tracked_properties = tracked_args["properties"]
expected_answer = (
"BaseCamp: You can use a damp rag to clean around the Power Pack"
)
tracked_metrics = tracked_args["measurements"]
self.assertEqual(1, telemetry_client.track_event.call_count)
self.assertEqual(3, len(tracked_args))
self.assertEqual("QnaMessage", tracked_args["name"])
self.assertTrue("knowledge_base_id" in tracked_properties)
self.assertEqual(
"my_important_value", tracked_properties["knowledge_base_id"]
)
self.assertTrue("original_question" in tracked_properties)
self.assertTrue("matchedQuestion" in tracked_properties)
self.assertEqual(
"my_important_value2", tracked_properties["original_question"]
)
self.assertTrue("question" not in tracked_properties)
self.assertTrue("questionId" in tracked_properties)
self.assertTrue("answer" in tracked_properties)
self.assertEqual(expected_answer, tracked_properties["answer"])
self.assertTrue("my_important_property" not in tracked_properties)
self.assertEqual(1, len(tracked_metrics))
self.assertTrue("score" in tracked_metrics)
self.assertEqual(3.14159, tracked_metrics["score"])
# Assert - Validate we didn't break QnA functionality.
self.assertIsNotNone(results)
self.assertEqual(1, len(results))
self.assertEqual(expected_answer, results[0].answer)
self.assertEqual("Editorial", results[0].source)
async def test_telemetry_fill_props_override(self):
# Arrange
question: str = "how do I clean the stove?"
response_json = QnaApplicationTest._get_json_for_file("ReturnsAnswer.json")
context: TurnContext = QnaApplicationTest._get_context(question, TestAdapter())
options = QnAMakerOptions(top=1)
telemetry_client = unittest.mock.create_autospec(BotTelemetryClient)
log_personal_information = False
# Act - Pass in properties during QnA invocation that override default properties
# In addition Override with derivation. This presents an interesting question of order of setting
# properties.
# If I want to override "originalQuestion" property:
# - Set in "Stock" schema
# - Set in derived QnAMaker class
# - Set in GetAnswersAsync
# Logically, the GetAnswersAync should win. But ultimately OnQnaResultsAsync decides since it is the last
# code to touch the properties before logging (since it actually logs the event).
qna = QnaApplicationTest.OverrideFillTelemetry(
QnaApplicationTest.tests_endpoint,
options,
None,
telemetry_client,
log_personal_information,
)
telemetry_properties: Dict[str, str] = {
"knowledgeBaseId": "my_important_value",
"matchedQuestion": "my_important_value2",
}
telemetry_metrics: Dict[str, float] = {"score": 3.14159}
with patch(
"aiohttp.ClientSession.post",
return_value=aiounittest.futurized(response_json),
):
results = await qna.get_answers(
context, None, telemetry_properties, telemetry_metrics
)
# Assert - Added properties were added.
first_call_args = telemetry_client.track_event.call_args_list[0][0]
first_properties = first_call_args[1]
expected_answer = (
"BaseCamp: You can use a damp rag to clean around the Power Pack"
)
first_metrics = first_call_args[2]
self.assertEqual(2, telemetry_client.track_event.call_count)
self.assertEqual(3, len(first_call_args))
self.assertEqual("QnaMessage", first_call_args[0])
self.assertEqual(6, len(first_properties))
self.assertTrue("knowledgeBaseId" in first_properties)
self.assertEqual("my_important_value", first_properties["knowledgeBaseId"])
self.assertTrue("matchedQuestion" in first_properties)
self.assertEqual("my_important_value2", first_properties["matchedQuestion"])
self.assertTrue("questionId" in first_properties)
self.assertTrue("answer" in first_properties)
self.assertEqual(expected_answer, first_properties["answer"])
self.assertTrue("articleFound" in first_properties)
self.assertTrue("my_important_property" in first_properties)
self.assertEqual(
"my_important_value", first_properties["my_important_property"]
)
self.assertEqual(1, len(first_metrics))
self.assertTrue("score" in first_metrics)
self.assertEqual(3.14159, first_metrics["score"])
# Assert - Validate we didn't break QnA functionality.
self.assertIsNotNone(results)
self.assertEqual(1, len(results))
self.assertEqual(expected_answer, results[0].answer)
self.assertEqual("Editorial", results[0].source)
async def test_call_train(self):
feedback_records = []
feedback1 = FeedbackRecord(
qna_id=1, user_id="test", user_question="How are you?"
)
feedback2 = FeedbackRecord(qna_id=2, user_id="test", user_question="What up??")
feedback_records.extend([feedback1, feedback2])
with patch.object(
QnAMaker, "call_train", return_value=None
) as mocked_call_train:
qna = QnAMaker(QnaApplicationTest.tests_endpoint)
qna.call_train(feedback_records)
mocked_call_train.assert_called_once_with(feedback_records)
async def test_should_filter_low_score_variation(self):
options = QnAMakerOptions(top=5)
qna = QnAMaker(QnaApplicationTest.tests_endpoint, options)
question: str = "Q11"
context = QnaApplicationTest._get_context(question, TestAdapter())
response_json = QnaApplicationTest._get_json_for_file("TopNAnswer.json")
with patch(
"aiohttp.ClientSession.post",
return_value=aiounittest.futurized(response_json),
):
results = await qna.get_answers(context)
self.assertEqual(4, len(results), "Should have received 4 answers.")
filtered_results = qna.get_low_score_variation(results)
self.assertEqual(
3,
len(filtered_results),
"Should have 3 filtered answers after low score variation.",
)
async def test_should_answer_with_is_test_true(self):
options = QnAMakerOptions(top=1, is_test=True)
qna = QnAMaker(QnaApplicationTest.tests_endpoint)
question: str = "Q11"
context = QnaApplicationTest._get_context(question, TestAdapter())
response_json = QnaApplicationTest._get_json_for_file(
"QnaMaker_IsTest_true.json"
)
with patch(
"aiohttp.ClientSession.post",
return_value=aiounittest.futurized(response_json),
):
results = await qna.get_answers(context, options=options)
self.assertEqual(0, len(results), "Should have received zero answer.")
async def test_should_answer_with_ranker_type_question_only(self):
options = QnAMakerOptions(top=1, ranker_type="QuestionOnly")
qna = QnAMaker(QnaApplicationTest.tests_endpoint)
question: str = "Q11"
context = QnaApplicationTest._get_context(question, TestAdapter())
response_json = QnaApplicationTest._get_json_for_file(
"QnaMaker_RankerType_QuestionOnly.json"
)
with patch(
"aiohttp.ClientSession.post",
return_value=aiounittest.futurized(response_json),
):
results = await qna.get_answers(context, options=options)
self.assertEqual(2, len(results), "Should have received two answers.")
async def test_should_answer_with_prompts(self):
options = QnAMakerOptions(top=2)
qna = QnAMaker(QnaApplicationTest.tests_endpoint, options)
question: str = "how do I clean the stove?"
turn_context = QnaApplicationTest._get_context(question, TestAdapter())
response_json = QnaApplicationTest._get_json_for_file("AnswerWithPrompts.json")
with patch(
"aiohttp.ClientSession.post",
return_value=aiounittest.futurized(response_json),
):
results = await qna.get_answers(turn_context, options)
self.assertEqual(1, len(results), "Should have received 1 answers.")
self.assertEqual(
1, len(results[0].context.prompts), "Should have received 1 prompt."
)
async def test_should_answer_with_high_score_provided_context(self):
qna = QnAMaker(QnaApplicationTest.tests_endpoint)
question: str = "where can I buy?"
context = QnARequestContext(
previous_qna_id=5, previous_user_query="how do I clean the stove?"
)
options = QnAMakerOptions(top=2, qna_id=55, context=context)
turn_context = QnaApplicationTest._get_context(question, TestAdapter())
response_json = QnaApplicationTest._get_json_for_file(
"AnswerWithHighScoreProvidedContext.json"
)
with patch(
"aiohttp.ClientSession.post",
return_value=aiounittest.futurized(response_json),
):
results = await qna.get_answers(turn_context, options)
self.assertEqual(1, len(results), "Should have received 1 answers.")
self.assertEqual(1, results[0].score, "Score should be high.")
async def test_should_answer_with_high_score_provided_qna_id(self):
qna = QnAMaker(QnaApplicationTest.tests_endpoint)
question: str = "where can I buy?"
options = QnAMakerOptions(top=2, qna_id=55)
turn_context = QnaApplicationTest._get_context(question, TestAdapter())
response_json = QnaApplicationTest._get_json_for_file(
"AnswerWithHighScoreProvidedContext.json"
)
with patch(
"aiohttp.ClientSession.post",
return_value=aiounittest.futurized(response_json),
):
results = await qna.get_answers(turn_context, options)
self.assertEqual(1, len(results), "Should have received 1 answers.")
self.assertEqual(1, results[0].score, "Score should be high.")
async def test_should_answer_with_low_score_without_provided_context(self):
qna = QnAMaker(QnaApplicationTest.tests_endpoint)
question: str = "where can I buy?"
options = QnAMakerOptions(top=2, context=None)
turn_context = QnaApplicationTest._get_context(question, TestAdapter())
response_json = QnaApplicationTest._get_json_for_file(
"AnswerWithLowScoreProvidedWithoutContext.json"
)
with patch(
"aiohttp.ClientSession.post",
return_value=aiounittest.futurized(response_json),
):
results = await qna.get_answers(turn_context, options)
self.assertEqual(
2, len(results), "Should have received more than one answers."
)
self.assertEqual(True, results[0].score < 1, "Score should be low.")
async def test_low_score_variation(self):
qna = QnAMaker(QnaApplicationTest.tests_endpoint)
options = QnAMakerOptions(top=5, context=None)
turn_context = QnaApplicationTest._get_context("Q11", TestAdapter())
response_json = QnaApplicationTest._get_json_for_file(
"QnaMaker_TopNAnswer.json"
)
# active learning enabled
with patch(
"aiohttp.ClientSession.post",
return_value=aiounittest.futurized(response_json),
):
results = await qna.get_answers(turn_context, options)
self.assertIsNotNone(results)
self.assertEqual(4, len(results), "should get four results")
filtered_results = qna.get_low_score_variation(results)
self.assertIsNotNone(filtered_results)
self.assertEqual(3, len(filtered_results), "should get three results")
# active learning disabled
turn_context = QnaApplicationTest._get_context("Q11", TestAdapter())
response_json = QnaApplicationTest._get_json_for_file(
"QnaMaker_TopNAnswer_DisableActiveLearning.json"
)
with patch(
"aiohttp.ClientSession.post",
return_value=aiounittest.futurized(response_json),
):
results = await qna.get_answers(turn_context, options)
self.assertIsNotNone(results)
self.assertEqual(4, len(results), "should get four results")
filtered_results = qna.get_low_score_variation(results)
self.assertIsNotNone(filtered_results)
self.assertEqual(3, len(filtered_results), "should get three results")
@classmethod
async def _get_service_result(
cls,
utterance: str,
response_file: str,
bot_adapter: BotAdapter = TestAdapter(),
options: QnAMakerOptions = None,
) -> [dict]:
response_json = QnaApplicationTest._get_json_for_file(response_file)
qna = QnAMaker(QnaApplicationTest.tests_endpoint)
context = QnaApplicationTest._get_context(utterance, bot_adapter)
with patch(
"aiohttp.ClientSession.post",
return_value=aiounittest.futurized(response_json),
):
result = await qna.get_answers(context, options)
return result
@classmethod
async def _get_service_result_raw(
cls,
utterance: str,
response_file: str,
bot_adapter: BotAdapter = TestAdapter(),
options: QnAMakerOptions = None,
) -> [dict]:
response_json = QnaApplicationTest._get_json_for_file(response_file)
qna = QnAMaker(QnaApplicationTest.tests_endpoint)
context = QnaApplicationTest._get_context(utterance, bot_adapter)
with patch(
"aiohttp.ClientSession.post",
return_value=aiounittest.futurized(response_json),
):
result = await qna.get_answers_raw(context, options)
return result
@classmethod
def _get_json_for_file(cls, response_file: str) -> object:
curr_dir = path.dirname(path.abspath(__file__))
response_path = path.join(curr_dir, "test_data", response_file)
with open(response_path, "r", encoding="utf-8-sig") as file:
response_str = file.read()
response_json = json.loads(response_str)
return response_json
@staticmethod
def _get_context(question: str, bot_adapter: BotAdapter) -> TurnContext:
test_adapter = bot_adapter or TestAdapter()
activity = Activity(
type=ActivityTypes.message,
text=question,
conversation=ConversationAccount(),
recipient=ChannelAccount(),
from_property=ChannelAccount(),
)
return TurnContext(test_adapter, activity)
class OverrideTelemetry(QnAMaker):
def __init__( # pylint: disable=useless-super-delegation
self,
endpoint: QnAMakerEndpoint,
options: QnAMakerOptions,
http_client: ClientSession,
telemetry_client: BotTelemetryClient,
log_personal_information: bool,
):
super().__init__(
endpoint,
options,
http_client,
telemetry_client,
log_personal_information,
)
async def on_qna_result( # pylint: disable=unused-argument
self,
query_results: [QueryResult],
turn_context: TurnContext,
telemetry_properties: Dict[str, str] = None,
telemetry_metrics: Dict[str, float] = None,
):
properties = telemetry_properties or {}
# get_answers overrides derived class
properties["my_important_property"] = "my_important_value"
# Log event
self.telemetry_client.track_event(
QnATelemetryConstants.qna_message_event, properties
)
# Create 2nd event.
second_event_properties = {"my_important_property2": "my_important_value2"}
self.telemetry_client.track_event(
"my_second_event", second_event_properties
)
class OverrideFillTelemetry(QnAMaker):
def __init__( # pylint: disable=useless-super-delegation
self,
endpoint: QnAMakerEndpoint,
options: QnAMakerOptions,
http_client: ClientSession,
telemetry_client: BotTelemetryClient,
log_personal_information: bool,
):
super().__init__(
endpoint,
options,
http_client,
telemetry_client,
log_personal_information,
)
async def on_qna_result(
self,
query_results: [QueryResult],
turn_context: TurnContext,
telemetry_properties: Dict[str, str] = None,
telemetry_metrics: Dict[str, float] = None,
):
event_data = await self.fill_qna_event(
query_results, turn_context, telemetry_properties, telemetry_metrics
)
# Add my property.
event_data.properties.update(
{"my_important_property": "my_important_value"}
)
# Log QnaMessage event.
self.telemetry_client.track_event(
QnATelemetryConstants.qna_message_event,
event_data.properties,
event_data.metrics,
)
# Create second event.
second_event_properties: Dict[str, str] = {
"my_important_property2": "my_important_value2"
}
self.telemetry_client.track_event("MySecondEvent", second_event_properties)
|
botbuilder-python/libraries/botbuilder-ai/tests/qna/test_qna.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-ai/tests/qna/test_qna.py",
"repo_id": "botbuilder-python",
"token_count": 21286
}
| 448 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
"""Telemetry processor for Flask."""
import sys
from ..processor.telemetry_processor import TelemetryProcessor
from .flask_telemetry_middleware import retrieve_flask_body
class FlaskTelemetryProcessor(TelemetryProcessor):
def can_process(self) -> bool:
return self.detect_flask()
def get_request_body(self) -> str:
if self.detect_flask():
return retrieve_flask_body()
return None
@staticmethod
def detect_flask() -> bool:
"""Detects if running in flask."""
return "flask" in sys.modules
|
botbuilder-python/libraries/botbuilder-applicationinsights/botbuilder/applicationinsights/flask/flask_telemetry_processor.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-applicationinsights/botbuilder/applicationinsights/flask/flask_telemetry_processor.py",
"repo_id": "botbuilder-python",
"token_count": 228
}
| 449 |
[bdist_wheel]
universal=0
|
botbuilder-python/libraries/botbuilder-azure/setup.cfg/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-azure/setup.cfg",
"repo_id": "botbuilder-python",
"token_count": 10
}
| 450 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from abc import ABC, abstractmethod
from typing import List, Callable, Awaitable
from botbuilder.schema import (
Activity,
ConversationReference,
ConversationParameters,
ResourceResponse,
)
from botframework.connector.auth import AppCredentials, ClaimsIdentity
from . import conversation_reference_extension
from .bot_assert import BotAssert
from .turn_context import TurnContext
from .middleware_set import MiddlewareSet
class BotAdapter(ABC):
BOT_IDENTITY_KEY = "BotIdentity"
BOT_OAUTH_SCOPE_KEY = "botbuilder.core.BotAdapter.OAuthScope"
BOT_CONNECTOR_CLIENT_KEY = "ConnectorClient"
BOT_CALLBACK_HANDLER_KEY = "BotCallbackHandler"
_INVOKE_RESPONSE_KEY = "BotFrameworkAdapter.InvokeResponse"
def __init__(
self, on_turn_error: Callable[[TurnContext, Exception], Awaitable] = None
):
self._middleware = MiddlewareSet()
self.on_turn_error = on_turn_error
@abstractmethod
async def send_activities(
self, context: TurnContext, activities: List[Activity]
) -> List[ResourceResponse]:
"""
Sends a set of activities to the user. An array of responses from the server will be returned.
:param context: The context object for the turn.
:type context: :class:`TurnContext`
:param activities: The activities to send.
:type activities: :class:`typing.List[Activity]`
:return:
"""
raise NotImplementedError()
@abstractmethod
async def update_activity(self, context: TurnContext, activity: Activity):
"""
Replaces an existing activity.
:param context: The context object for the turn.
:type context: :class:`TurnContext`
:param activity: New replacement activity.
:type activity: :class:`botbuilder.schema.Activity`
:return:
"""
raise NotImplementedError()
@abstractmethod
async def delete_activity(
self, context: TurnContext, reference: ConversationReference
):
"""
Deletes an existing activity.
:param context: The context object for the turn.
:type context: :class:`TurnContext`
:param reference: Conversation reference for the activity to delete.
:type reference: :class:`botbuilder.schema.ConversationReference`
:return:
"""
raise NotImplementedError()
def use(self, middleware):
"""
Registers a middleware handler with the adapter.
:param middleware: The middleware to register.
:return:
"""
self._middleware.use(middleware)
return self
async def continue_conversation(
self,
reference: ConversationReference,
callback: Callable,
bot_id: str = None, # pylint: disable=unused-argument
claims_identity: ClaimsIdentity = None, # pylint: disable=unused-argument
audience: str = None, # pylint: disable=unused-argument
):
"""
Sends a proactive message to a conversation. Call this method to proactively send a message to a conversation.
Most channels require a user to initiate a conversation with a bot before the bot can send activities
to the user.
:param bot_id: The application ID of the bot. This parameter is ignored in
single tenant the Adapters (Console, Test, etc) but is critical to the BotFrameworkAdapter
which is multi-tenant aware.
:param reference: A reference to the conversation to continue.
:type reference: :class:`botbuilder.schema.ConversationReference`
:param callback: The method to call for the resulting bot turn.
:type callback: :class:`typing.Callable`
:param claims_identity: A :class:`botframework.connector.auth.ClaimsIdentity` for the conversation.
:type claims_identity: :class:`botframework.connector.auth.ClaimsIdentity`
:param audience:A value signifying the recipient of the proactive message.
:type audience: str
"""
context = TurnContext(
self, conversation_reference_extension.get_continuation_activity(reference)
)
return await self.run_pipeline(context, callback)
async def create_conversation(
self,
reference: ConversationReference,
logic: Callable[[TurnContext], Awaitable] = None,
conversation_parameters: ConversationParameters = None,
channel_id: str = None,
service_url: str = None,
credentials: AppCredentials = None,
):
"""
Starts a new conversation with a user. Used to direct message to a member of a group.
:param reference: The conversation reference that contains the tenant
:type reference: :class:`botbuilder.schema.ConversationReference`
:param logic: The logic to use for the creation of the conversation
:type logic: :class:`typing.Callable`
:param conversation_parameters: The information to use to create the conversation
:type conversation_parameters:
:param channel_id: The ID for the channel.
:type channel_id: :class:`typing.str`
:param service_url: The channel's service URL endpoint.
:type service_url: :class:`typing.str`
:param credentials: The application credentials for the bot.
:type credentials: :class:`botframework.connector.auth.AppCredentials`
:raises: It raises a generic exception error.
:return: A task representing the work queued to execute.
.. remarks::
To start a conversation, your bot must know its account information and the user's
account information on that channel.
Most channels only support initiating a direct message (non-group) conversation.
The adapter attempts to create a new conversation on the channel, and
then sends a conversation update activity through its middleware pipeline
to the the callback method.
If the conversation is established with the specified users, the ID of the activity
will contain the ID of the new conversation.
"""
raise Exception("Not Implemented")
async def run_pipeline(
self, context: TurnContext, callback: Callable[[TurnContext], Awaitable] = None
):
"""
Called by the parent class to run the adapters middleware set and calls the passed in `callback()` handler at
the end of the chain.
:param context: The context object for the turn.
:type context: :class:`TurnContext`
:param callback: A callback method to run at the end of the pipeline.
:type callback: :class:`typing.Callable[[TurnContext], Awaitable]`
:return:
"""
BotAssert.context_not_none(context)
if context.activity is not None:
try:
return await self._middleware.receive_activity_with_status(
context, callback
)
except Exception as error:
if self.on_turn_error is not None:
await self.on_turn_error(context, error)
else:
raise error
else:
# callback to caller on proactive case
if callback is not None:
await callback(context)
|
botbuilder-python/libraries/botbuilder-core/botbuilder/core/bot_adapter.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-core/botbuilder/core/bot_adapter.py",
"repo_id": "botbuilder-python",
"token_count": 2779
}
| 451 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from typing import Dict
from botbuilder.schema import ConversationReference
class InspectionSessionsByStatus:
def __init__(
self,
opened_sessions: Dict[str, ConversationReference] = None,
attached_sessions: Dict[str, ConversationReference] = None,
):
self.opened_sessions: Dict[str, ConversationReference] = opened_sessions or {}
self.attached_sessions: Dict[str, ConversationReference] = (
attached_sessions or {}
)
DEFAULT_INSPECTION_SESSIONS_BY_STATUS = InspectionSessionsByStatus()
|
botbuilder-python/libraries/botbuilder-core/botbuilder/core/inspection/inspection_sessions_by_status.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-core/botbuilder/core/inspection/inspection_sessions_by_status.py",
"repo_id": "botbuilder-python",
"token_count": 227
}
| 452 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from abc import ABC
from typing import Dict, List
from botframework.connector.token_api.models import (
SignInUrlResponse,
TokenExchangeRequest,
TokenResponse,
)
from botframework.connector.auth import AppCredentials
from botbuilder.core.turn_context import TurnContext
from .user_token_provider import UserTokenProvider
class ExtendedUserTokenProvider(UserTokenProvider, ABC):
# pylint: disable=unused-argument
async def get_sign_in_resource(
self, turn_context: TurnContext, connection_name: str
) -> SignInUrlResponse:
"""
Get the raw signin link to be sent to the user for signin for a connection name.
:param turn_context: Context for the current turn of conversation with the user.
:param connection_name: Name of the auth connection to use.
:return: A task that represents the work queued to execute.
.. remarks:: If the task completes successfully, the result contains the raw signin link.
"""
return
async def get_sign_in_resource_from_user(
self,
turn_context: TurnContext,
connection_name: str,
user_id: str,
final_redirect: str = None,
) -> SignInUrlResponse:
"""
Get the raw signin link to be sent to the user for signin for a connection name.
:param turn_context: Context for the current turn of conversation with the user.
:param connection_name: Name of the auth connection to use.
:param user_id: The user id that will be associated with the token.
:param final_redirect: The final URL that the OAuth flow will redirect to.
:return: A task that represents the work queued to execute.
.. remarks:: If the task completes successfully, the result contains the raw signin link.
"""
return
async def get_sign_in_resource_from_user_and_credentials(
self,
turn_context: TurnContext,
oauth_app_credentials: AppCredentials,
connection_name: str,
user_id: str,
final_redirect: str = None,
) -> SignInUrlResponse:
"""
Get the raw signin link to be sent to the user for signin for a connection name.
:param turn_context: Context for the current turn of conversation with the user.
:param oauth_app_credentials: Credentials for OAuth.
:param connection_name: Name of the auth connection to use.
:param user_id: The user id that will be associated with the token.
:param final_redirect: The final URL that the OAuth flow will redirect to.
:return: A task that represents the work queued to execute.
.. remarks:: If the task completes successfully, the result contains the raw signin link.
"""
return
async def exchange_token(
self,
turn_context: TurnContext,
connection_name: str,
user_id: str,
exchange_request: TokenExchangeRequest,
) -> TokenResponse:
"""
Performs a token exchange operation such as for single sign-on.
:param turn_context: Context for the current turn of conversation with the user.
:param connection_name: Name of the auth connection to use.
:param user_id: The user id associated with the token..
:param exchange_request: The exchange request details, either a token to exchange or a uri to exchange.
:return: If the task completes, the exchanged token is returned.
"""
return
async def exchange_token_from_credentials(
self,
turn_context: TurnContext,
oauth_app_credentials: AppCredentials,
connection_name: str,
user_id: str,
exchange_request: TokenExchangeRequest,
) -> TokenResponse:
"""
Performs a token exchange operation such as for single sign-on.
:param turn_context: Context for the current turn of conversation with the user.
:param oauth_app_credentials: AppCredentials for OAuth.
:param connection_name: Name of the auth connection to use.
:param user_id: The user id associated with the token..
:param exchange_request: The exchange request details, either a token to exchange or a uri to exchange.
:return: If the task completes, the exchanged token is returned.
"""
return
async def get_user_token(
self,
context: TurnContext,
connection_name: str,
magic_code: str = None,
oauth_app_credentials: AppCredentials = None,
) -> TokenResponse:
"""
Retrieves the OAuth token for a user that is in a sign-in flow.
:param context:
:param connection_name:
:param magic_code:
:param oauth_app_credentials:
:return:
"""
raise NotImplementedError()
async def sign_out_user(
self,
context: TurnContext,
connection_name: str = None,
user_id: str = None,
oauth_app_credentials: AppCredentials = None,
):
"""
Signs the user out with the token server.
:param context:
:param connection_name:
:param user_id:
:param oauth_app_credentials:
:return:
"""
raise NotImplementedError()
async def get_oauth_sign_in_link(
self,
context: TurnContext,
connection_name: str,
final_redirect: str = None,
oauth_app_credentials: AppCredentials = None,
) -> str:
"""
Get the raw signin link to be sent to the user for signin for a connection name.
:param context:
:param connection_name:
:param final_redirect:
:param oauth_app_credentials:
:return:
"""
raise NotImplementedError()
async def get_aad_tokens(
self,
context: TurnContext,
connection_name: str,
resource_urls: List[str],
user_id: str = None,
oauth_app_credentials: AppCredentials = None,
) -> Dict[str, TokenResponse]:
"""
Retrieves Azure Active Directory tokens for particular resources on a configured connection.
:param context:
:param connection_name:
:param resource_urls:
:param user_id:
:param oauth_app_credentials:
:return:
"""
raise NotImplementedError()
|
botbuilder-python/libraries/botbuilder-core/botbuilder/core/oauth/extended_user_token_provider.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-core/botbuilder/core/oauth/extended_user_token_provider.py",
"repo_id": "botbuilder-python",
"token_count": 2525
}
| 453 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from abc import ABC
from typing import Union
from botbuilder.schema import ConversationReference
from .skill_conversation_id_factory_options import SkillConversationIdFactoryOptions
from .skill_conversation_reference import SkillConversationReference
class ConversationIdFactoryBase(ABC):
"""
Handles creating conversation ids for skill and should be subclassed.
.. remarks::
Derive from this class to handle creation of conversation ids, retrieval of
SkillConversationReferences and deletion.
"""
async def create_skill_conversation_id(
self,
options_or_conversation_reference: Union[
SkillConversationIdFactoryOptions, ConversationReference
],
) -> str:
"""
Using the options passed in, creates a conversation id and :class:`SkillConversationReference`,
storing them for future use.
:param options_or_conversation_reference: The options contain properties useful for generating a
:class:`SkillConversationReference` and conversation id.
:type options_or_conversation_reference:
:class:`Union[SkillConversationIdFactoryOptions, ConversationReference]`
:returns: A skill conversation id.
.. note::
:class:`SkillConversationIdFactoryOptions` is the preferred parameter type, while the
:class:`SkillConversationReference` type is provided for backwards compatability.
"""
raise NotImplementedError()
async def get_conversation_reference(
self, skill_conversation_id: str
) -> ConversationReference:
"""
[DEPRECATED] Method is deprecated, please use get_skill_conversation_reference() instead.
Retrieves a :class:`ConversationReference` using a conversation id passed in.
:param skill_conversation_id: The conversation id for which to retrieve the :class:`ConversationReference`.
:type skill_conversation_id: str
:returns: `ConversationReference` for the specified ID.
"""
raise NotImplementedError()
async def get_skill_conversation_reference(
self, skill_conversation_id: str
) -> SkillConversationReference:
"""
Retrieves a :class:`SkillConversationReference` using a conversation id passed in.
:param skill_conversation_id: The conversation id for which to retrieve the :class:`SkillConversationReference`.
:type skill_conversation_id: str
:returns: `SkillConversationReference` for the specified ID.
"""
raise NotImplementedError()
async def delete_conversation_reference(self, skill_conversation_id: str):
"""
Removes any reference to objects keyed on the conversation id passed in.
"""
raise NotImplementedError()
|
botbuilder-python/libraries/botbuilder-core/botbuilder/core/skills/conversation_id_factory.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-core/botbuilder/core/skills/conversation_id_factory.py",
"repo_id": "botbuilder-python",
"token_count": 998
}
| 454 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
# pylint: disable=too-many-lines
from http import HTTPStatus
from botbuilder.schema import ChannelAccount, ErrorResponseException, SignInConstants
from botbuilder.core import ActivityHandler, InvokeResponse
from botbuilder.core.activity_handler import _InvokeResponseException
from botbuilder.core.turn_context import TurnContext
from botbuilder.core.teams.teams_info import TeamsInfo
from botbuilder.schema.teams import (
AppBasedLinkQuery,
TeamInfo,
ChannelInfo,
FileConsentCardResponse,
MeetingStartEventDetails,
MeetingEndEventDetails,
TeamsChannelData,
TeamsChannelAccount,
MessagingExtensionAction,
MessagingExtensionQuery,
MessagingExtensionActionResponse,
MessagingExtensionResponse,
O365ConnectorCardActionQuery,
TaskModuleRequest,
TaskModuleResponse,
TabRequest,
TabSubmit,
)
from botframework.connector import Channels
from ..serializer_helper import deserializer_helper
class TeamsActivityHandler(ActivityHandler):
async def on_invoke_activity(self, turn_context: TurnContext) -> InvokeResponse:
"""
Invoked when an invoke activity is received from the connector.
Invoke activities can be used to communicate many different things.
:param turn_context: A context object for this turn.
:returns: An InvokeResponse that represents the work queued to execute.
.. remarks::
Invoke activities communicate programmatic commands from a client or channel to a bot.
The meaning of an invoke activity is defined by the "invoke_activity.name" property,
which is meaningful within the scope of a channel.
"""
try:
if (
not turn_context.activity.name
and turn_context.activity.channel_id == Channels.ms_teams
):
return await self.on_teams_card_action_invoke(turn_context)
if (
turn_context.activity.name
== SignInConstants.token_exchange_operation_name
):
await self.on_teams_signin_token_exchange(turn_context)
return self._create_invoke_response()
if turn_context.activity.name == "fileConsent/invoke":
return await self.on_teams_file_consent(
turn_context,
deserializer_helper(
FileConsentCardResponse, turn_context.activity.value
),
)
if turn_context.activity.name == "actionableMessage/executeAction":
await self.on_teams_o365_connector_card_action(
turn_context,
deserializer_helper(
O365ConnectorCardActionQuery, turn_context.activity.value
),
)
return self._create_invoke_response()
if turn_context.activity.name == "composeExtension/queryLink":
return self._create_invoke_response(
await self.on_teams_app_based_link_query(
turn_context,
deserializer_helper(
AppBasedLinkQuery, turn_context.activity.value
),
)
)
if turn_context.activity.name == "composeExtension/query":
return self._create_invoke_response(
await self.on_teams_messaging_extension_query(
turn_context,
deserializer_helper(
MessagingExtensionQuery, turn_context.activity.value
),
)
)
if turn_context.activity.name == "composeExtension/selectItem":
return self._create_invoke_response(
await self.on_teams_messaging_extension_select_item(
turn_context, turn_context.activity.value
)
)
if turn_context.activity.name == "composeExtension/submitAction":
return self._create_invoke_response(
await self.on_teams_messaging_extension_submit_action_dispatch(
turn_context,
deserializer_helper(
MessagingExtensionAction, turn_context.activity.value
),
)
)
if turn_context.activity.name == "composeExtension/fetchTask":
return self._create_invoke_response(
await self.on_teams_messaging_extension_fetch_task(
turn_context,
deserializer_helper(
MessagingExtensionAction,
turn_context.activity.value,
),
)
)
if turn_context.activity.name == "composeExtension/querySettingUrl":
return self._create_invoke_response(
await self.on_teams_messaging_extension_configuration_query_settings_url(
turn_context,
deserializer_helper(
MessagingExtensionQuery, turn_context.activity.value
),
)
)
if turn_context.activity.name == "composeExtension/setting":
await self.on_teams_messaging_extension_configuration_setting(
turn_context, turn_context.activity.value
)
return self._create_invoke_response()
if turn_context.activity.name == "composeExtension/onCardButtonClicked":
await self.on_teams_messaging_extension_card_button_clicked(
turn_context, turn_context.activity.value
)
return self._create_invoke_response()
if turn_context.activity.name == "task/fetch":
return self._create_invoke_response(
await self.on_teams_task_module_fetch(
turn_context,
deserializer_helper(
TaskModuleRequest, turn_context.activity.value
),
)
)
if turn_context.activity.name == "task/submit":
return self._create_invoke_response(
await self.on_teams_task_module_submit(
turn_context,
deserializer_helper(
TaskModuleRequest, turn_context.activity.value
),
)
)
if turn_context.activity.name == "tab/fetch":
return self._create_invoke_response(
await self.on_teams_tab_fetch(
turn_context,
deserializer_helper(TabRequest, turn_context.activity.value),
)
)
if turn_context.activity.name == "tab/submit":
return self._create_invoke_response(
await self.on_teams_tab_submit(
turn_context,
deserializer_helper(TabSubmit, turn_context.activity.value),
)
)
return await super().on_invoke_activity(turn_context)
except _InvokeResponseException as invoke_exception:
return invoke_exception.create_invoke_response()
async def on_sign_in_invoke(self, turn_context: TurnContext):
"""
Invoked when a signIn invoke activity is received from the connector.
:param turn_context: A context object for this turn.
:returns: A task that represents the work queued to execute.
"""
return await self.on_teams_signin_verify_state(turn_context)
async def on_teams_card_action_invoke(
self, turn_context: TurnContext
) -> InvokeResponse:
"""
Invoked when an card action invoke activity is received from the connector.
:param turn_context: A context object for this turn.
:returns: An InvokeResponse that represents the work queued to execute.
"""
raise _InvokeResponseException(status_code=HTTPStatus.NOT_IMPLEMENTED)
async def on_teams_signin_verify_state(self, turn_context: TurnContext):
"""
Invoked when a signIn verify state activity is received from the connector.
:param turn_context: A context object for this turn.
:returns: A task that represents the work queued to execute.
"""
raise _InvokeResponseException(status_code=HTTPStatus.NOT_IMPLEMENTED)
async def on_teams_signin_token_exchange(self, turn_context: TurnContext):
raise _InvokeResponseException(status_code=HTTPStatus.NOT_IMPLEMENTED)
async def on_teams_file_consent(
self,
turn_context: TurnContext,
file_consent_card_response: FileConsentCardResponse,
) -> InvokeResponse:
"""
Invoked when a file consent card activity is received from the connector.
:param turn_context: A context object for this turn.
:param file_consent_card_response: The response representing the value of the invoke
activity sent when the user acts on a file consent card.
:returns: An InvokeResponse depending on the action of the file consent card.
"""
if file_consent_card_response.action == "accept":
await self.on_teams_file_consent_accept(
turn_context, file_consent_card_response
)
return self._create_invoke_response()
if file_consent_card_response.action == "decline":
await self.on_teams_file_consent_decline(
turn_context, file_consent_card_response
)
return self._create_invoke_response()
raise _InvokeResponseException(
HTTPStatus.BAD_REQUEST,
f"{file_consent_card_response.action} is not a supported Action.",
)
async def on_teams_file_consent_accept( # pylint: disable=unused-argument
self,
turn_context: TurnContext,
file_consent_card_response: FileConsentCardResponse,
):
"""
Invoked when a file consent card is accepted by the user.
:param turn_context: A context object for this turn.
:param file_consent_card_response: The response representing the value of the invoke
activity sent when the user accepts a file consent card.
:returns: A task that represents the work queued to execute.
"""
raise _InvokeResponseException(status_code=HTTPStatus.NOT_IMPLEMENTED)
async def on_teams_file_consent_decline( # pylint: disable=unused-argument
self,
turn_context: TurnContext,
file_consent_card_response: FileConsentCardResponse,
):
"""
Invoked when a file consent card is declined by the user.
:param turn_context: A context object for this turn.
:param file_consent_card_response: The response representing the value of the invoke
activity sent when the user declines a file consent card.
:returns: A task that represents the work queued to execute.
"""
raise _InvokeResponseException(status_code=HTTPStatus.NOT_IMPLEMENTED)
async def on_teams_o365_connector_card_action( # pylint: disable=unused-argument
self, turn_context: TurnContext, query: O365ConnectorCardActionQuery
):
"""
Invoked when a O365 Connector Card Action activity is received from the connector.
:param turn_context: A context object for this turn.
:param query: The O365 connector card HttpPOST invoke query.
:returns: A task that represents the work queued to execute.
"""
raise _InvokeResponseException(status_code=HTTPStatus.NOT_IMPLEMENTED)
async def on_teams_app_based_link_query( # pylint: disable=unused-argument
self, turn_context: TurnContext, query: AppBasedLinkQuery
) -> MessagingExtensionResponse:
"""
Invoked when an app based link query activity is received from the connector.
:param turn_context: A context object for this turn.
:param query: The invoke request body type for app-based link query.
:returns: The Messaging Extension Response for the query.
"""
raise _InvokeResponseException(status_code=HTTPStatus.NOT_IMPLEMENTED)
async def on_teams_messaging_extension_query( # pylint: disable=unused-argument
self, turn_context: TurnContext, query: MessagingExtensionQuery
) -> MessagingExtensionResponse:
"""
Invoked when a Messaging Extension Query activity is received from the connector.
:param turn_context: A context object for this turn.
:param query: The query for the search command.
:returns: The Messaging Extension Response for the query.
"""
raise _InvokeResponseException(status_code=HTTPStatus.NOT_IMPLEMENTED)
async def on_teams_messaging_extension_select_item( # pylint: disable=unused-argument
self, turn_context: TurnContext, query
) -> MessagingExtensionResponse:
"""
Invoked when a messaging extension select item activity is received from the connector.
:param turn_context: A context object for this turn.
:param query: The object representing the query.
:returns: The Messaging Extension Response for the query.
"""
raise _InvokeResponseException(status_code=HTTPStatus.NOT_IMPLEMENTED)
async def on_teams_messaging_extension_submit_action_dispatch(
self, turn_context: TurnContext, action: MessagingExtensionAction
) -> MessagingExtensionActionResponse:
"""
Invoked when a messaging extension submit action dispatch activity is received from the connector.
:param turn_context: A context object for this turn.
:param action: The messaging extension action.
:returns: The Messaging Extension Action Response for the action.
"""
if not action.bot_message_preview_action:
return await self.on_teams_messaging_extension_submit_action(
turn_context, action
)
if action.bot_message_preview_action == "edit":
return await self.on_teams_messaging_extension_bot_message_preview_edit(
turn_context, action
)
if action.bot_message_preview_action == "send":
return await self.on_teams_messaging_extension_bot_message_preview_send(
turn_context, action
)
raise _InvokeResponseException(
status_code=HTTPStatus.BAD_REQUEST,
body=f"{action.bot_message_preview_action} is not a supported BotMessagePreviewAction",
)
async def on_teams_messaging_extension_bot_message_preview_edit( # pylint: disable=unused-argument
self, turn_context: TurnContext, action: MessagingExtensionAction
) -> MessagingExtensionActionResponse:
"""
Invoked when a messaging extension bot message preview edit activity is received from the connector.
:param turn_context: A context object for this turn.
:param action: The messaging extension action.
:returns: The Messaging Extension Action Response for the action.
"""
raise _InvokeResponseException(status_code=HTTPStatus.NOT_IMPLEMENTED)
async def on_teams_messaging_extension_bot_message_preview_send( # pylint: disable=unused-argument
self, turn_context: TurnContext, action: MessagingExtensionAction
) -> MessagingExtensionActionResponse:
"""
Invoked when a messaging extension bot message preview send activity is received from the connector.
:param turn_context: A context object for this turn.
:param action: The messaging extension action.
:returns: The Messaging Extension Action Response for the action.
"""
raise _InvokeResponseException(status_code=HTTPStatus.NOT_IMPLEMENTED)
async def on_teams_messaging_extension_submit_action( # pylint: disable=unused-argument
self, turn_context: TurnContext, action: MessagingExtensionAction
) -> MessagingExtensionActionResponse:
"""
Invoked when a messaging extension submit action activity is received from the connector.
:param turn_context: A context object for this turn.
:param action: The messaging extension action.
:returns: The Messaging Extension Action Response for the action.
"""
raise _InvokeResponseException(status_code=HTTPStatus.NOT_IMPLEMENTED)
async def on_teams_messaging_extension_fetch_task( # pylint: disable=unused-argument
self, turn_context: TurnContext, action: MessagingExtensionAction
) -> MessagingExtensionActionResponse:
"""
Invoked when a Messaging Extension Fetch activity is received from the connector.
:param turn_context: A context object for this turn.
:param action: The messaging extension action.
:returns: The Messaging Extension Action Response for the action.
"""
raise _InvokeResponseException(status_code=HTTPStatus.NOT_IMPLEMENTED)
async def on_teams_messaging_extension_configuration_query_settings_url( # pylint: disable=unused-argument
self, turn_context: TurnContext, query: MessagingExtensionQuery
) -> MessagingExtensionResponse:
"""
Invoked when a messaging extension configuration query setting url activity is received from the connector.
:param turn_context: A context object for this turn.
:param query: The Messaging extension query.
:returns: The Messaging Extension Response for the query.
"""
raise _InvokeResponseException(status_code=HTTPStatus.NOT_IMPLEMENTED)
async def on_teams_messaging_extension_configuration_setting( # pylint: disable=unused-argument
self, turn_context: TurnContext, settings
):
"""
Override this in a derived class to provide logic for when a configuration is set for a messaging extension.
:param turn_context: A context object for this turn.
:param settings: Object representing the configuration settings.
:returns: A task that represents the work queued to execute.
"""
raise _InvokeResponseException(status_code=HTTPStatus.NOT_IMPLEMENTED)
async def on_teams_messaging_extension_card_button_clicked( # pylint: disable=unused-argument
self, turn_context: TurnContext, card_data
):
"""
Override this in a derived class to provide logic for when a card button is clicked in a messaging extension.
:param turn_context: A context object for this turn.
:param card_data: Object representing the card data.
:returns: A task that represents the work queued to execute.
"""
raise _InvokeResponseException(status_code=HTTPStatus.NOT_IMPLEMENTED)
async def on_teams_task_module_fetch( # pylint: disable=unused-argument
self, turn_context: TurnContext, task_module_request: TaskModuleRequest
) -> TaskModuleResponse:
"""
Override this in a derived class to provide logic for when a task module is fetched.
:param turn_context: A context object for this turn.
:param task_module_request: The task module invoke request value payload.
:returns: A Task Module Response for the request.
"""
raise _InvokeResponseException(status_code=HTTPStatus.NOT_IMPLEMENTED)
async def on_teams_task_module_submit( # pylint: disable=unused-argument
self, turn_context: TurnContext, task_module_request: TaskModuleRequest
) -> TaskModuleResponse:
"""
Override this in a derived class to provide logic for when a task module is submitted.
:param turn_context: A context object for this turn.
:param task_module_request: The task module invoke request value payload.
:returns: A Task Module Response for the request.
"""
raise _InvokeResponseException(status_code=HTTPStatus.NOT_IMPLEMENTED)
async def on_teams_tab_fetch( # pylint: disable=unused-argument
self, turn_context: TurnContext, tab_request: TabRequest
):
"""
Override this in a derived class to provide logic for when a tab is fetched.
:param turn_context: A context object for this turn.
:param tab_request: The tab invoke request value payload.
:returns: A Tab Response for the request.
"""
raise _InvokeResponseException(status_code=HTTPStatus.NOT_IMPLEMENTED)
async def on_teams_tab_submit( # pylint: disable=unused-argument
self, turn_context: TurnContext, tab_submit: TabSubmit
):
"""
Override this in a derived class to provide logic for when a tab is submitted.
:param turn_context: A context object for this turn.
:param tab_submit: The tab submit invoke request value payload.
:returns: A Tab Response for the request.
"""
raise _InvokeResponseException(status_code=HTTPStatus.NOT_IMPLEMENTED)
async def on_conversation_update_activity(self, turn_context: TurnContext):
"""
Invoked when a conversation update activity is received from the channel.
Conversation update activities are useful when it comes to responding to users
being added to or removed from the channel.
For example, a bot could respond to a user being added by greeting the user.
:param turn_context: A context object for this turn.
:returns: A task that represents the work queued to execute.
.. remarks::
In a derived class, override this method to add logic that applies
to all conversation update activities.
"""
if turn_context.activity.channel_id == Channels.ms_teams:
channel_data = TeamsChannelData().deserialize(
turn_context.activity.channel_data
)
if turn_context.activity.members_added:
return await self.on_teams_members_added_dispatch(
turn_context.activity.members_added, channel_data.team, turn_context
)
if turn_context.activity.members_removed:
return await self.on_teams_members_removed_dispatch(
turn_context.activity.members_removed,
channel_data.team,
turn_context,
)
if channel_data:
if channel_data.event_type == "channelCreated":
return await self.on_teams_channel_created(
ChannelInfo().deserialize(channel_data.channel),
channel_data.team,
turn_context,
)
if channel_data.event_type == "channelDeleted":
return await self.on_teams_channel_deleted(
channel_data.channel, channel_data.team, turn_context
)
if channel_data.event_type == "channelRenamed":
return await self.on_teams_channel_renamed(
channel_data.channel, channel_data.team, turn_context
)
if channel_data.event_type == "teamArchived":
return await self.on_teams_team_archived(
channel_data.team, turn_context
)
if channel_data.event_type == "teamDeleted":
return await self.on_teams_team_deleted(
channel_data.team, turn_context
)
if channel_data.event_type == "teamHardDeleted":
return await self.on_teams_team_hard_deleted(
channel_data.team, turn_context
)
if channel_data.event_type == "channelRestored":
return await self.on_teams_channel_restored(
channel_data.channel, channel_data.team, turn_context
)
if channel_data.event_type == "teamRenamed":
return await self.on_teams_team_renamed(
channel_data.team, turn_context
)
if channel_data.event_type == "teamRestored":
return await self.on_teams_team_restored(
channel_data.team, turn_context
)
if channel_data.event_type == "teamUnarchived":
return await self.on_teams_team_unarchived(
channel_data.team, turn_context
)
return await super().on_conversation_update_activity(turn_context)
async def on_teams_channel_created( # pylint: disable=unused-argument
self, channel_info: ChannelInfo, team_info: TeamInfo, turn_context: TurnContext
):
"""
Invoked when a Channel Created event activity is received from the connector.
Channel Created correspond to the user creating a new channel.
:param channel_info: The channel info object which describes the channel.
:param team_info: The team info object representing the team.
:param turn_context: A context object for this turn.
:returns: A task that represents the work queued to execute.
"""
return
async def on_teams_team_archived( # pylint: disable=unused-argument
self, team_info: TeamInfo, turn_context: TurnContext
):
"""
Invoked when a Team Archived event activity is received from the connector.
Team Archived correspond to the user archiving a team.
:param team_info: The team info object representing the team.
:param turn_context: A context object for this turn.
:returns: A task that represents the work queued to execute.
"""
return
async def on_teams_team_deleted( # pylint: disable=unused-argument
self, team_info: TeamInfo, turn_context: TurnContext
):
"""
Invoked when a Team Deleted event activity is received from the connector.
Team Deleted corresponds to the user deleting a team.
:param team_info: The team info object representing the team.
:param turn_context: A context object for this turn.
:returns: A task that represents the work queued to execute.
"""
return
async def on_teams_team_hard_deleted( # pylint: disable=unused-argument
self, team_info: TeamInfo, turn_context: TurnContext
):
"""
Invoked when a Team Hard Deleted event activity is received from the connector.
Team Hard Deleted corresponds to the user hard deleting a team.
:param team_info: The team info object representing the team.
:param turn_context: A context object for this turn.
:returns: A task that represents the work queued to execute.
"""
return
async def on_teams_team_renamed( # pylint: disable=unused-argument
self, team_info: TeamInfo, turn_context: TurnContext
):
"""
Invoked when a Team Renamed event activity is received from the connector.
Team Renamed correspond to the user renaming an existing team.
:param team_info: The team info object representing the team.
:param turn_context: A context object for this turn.
:returns: A task that represents the work queued to execute.
"""
return await self.on_teams_team_renamed_activity(team_info, turn_context)
async def on_teams_team_renamed_activity( # pylint: disable=unused-argument
self, team_info: TeamInfo, turn_context: TurnContext
):
"""
DEPRECATED. Please use on_teams_team_renamed(). This method will remain in place throughout
v4 so as not to break existing bots.
Invoked when a Team Renamed event activity is received from the connector.
Team Renamed correspond to the user renaming an existing team.
:param team_info: The team info object representing the team.
:param turn_context: A context object for this turn.
:returns: A task that represents the work queued to execute.
"""
return
async def on_teams_team_restored( # pylint: disable=unused-argument
self, team_info: TeamInfo, turn_context: TurnContext
):
"""
Invoked when a Team Restored event activity is received from the connector.
Team Restored corresponds to the user restoring a team.
:param team_info: The team info object representing the team.
:param turn_context: A context object for this turn.
:returns: A task that represents the work queued to execute.
"""
return
async def on_teams_team_unarchived( # pylint: disable=unused-argument
self, team_info: TeamInfo, turn_context: TurnContext
):
"""
Invoked when a Team Unarchived event activity is received from the connector.
Team Unarchived correspond to the user unarchiving a team.
:param team_info: The team info object representing the team.
:param turn_context: A context object for this turn.
:returns: A task that represents the work queued to execute.
"""
return
async def on_teams_members_added_dispatch( # pylint: disable=unused-argument
self,
members_added: [ChannelAccount],
team_info: TeamInfo,
turn_context: TurnContext,
):
"""
Override this in a derived class to provide logic for when members other than the bot
join the channel, such as your bot's welcome logic.
It will get the associated members with the provided accounts.
:param members_added: A list of all the accounts added to the channel, as
described by the conversation update activity.
:param team_info: The team info object representing the team.
:param turn_context: A context object for this turn.
:returns: A task that represents the work queued to execute.
"""
team_members_added = []
for member in members_added:
is_bot = (
turn_context.activity.recipient is not None
and member.id == turn_context.activity.recipient.id
)
if member.additional_properties != {} or is_bot:
team_members_added.append(
deserializer_helper(TeamsChannelAccount, member)
)
else:
team_member = None
try:
team_member = await TeamsInfo.get_member(turn_context, member.id)
team_members_added.append(team_member)
except ErrorResponseException as ex:
if (
ex.error
and ex.error.error
and ex.error.error.code == "ConversationNotFound"
):
new_teams_channel_account = TeamsChannelAccount(
id=member.id,
name=member.name,
aad_object_id=member.aad_object_id,
role=member.role,
)
team_members_added.append(new_teams_channel_account)
else:
raise ex
return await self.on_teams_members_added(
team_members_added, team_info, turn_context
)
async def on_teams_members_added( # pylint: disable=unused-argument
self,
teams_members_added: [TeamsChannelAccount],
team_info: TeamInfo,
turn_context: TurnContext,
):
"""
Override this in a derived class to provide logic for when members other than the bot
join the channel, such as your bot's welcome logic.
:param teams_members_added: A list of all the members added to the channel, as
described by the conversation update activity.
:param team_info: The team info object representing the team.
:param turn_context: A context object for this turn.
:returns: A task that represents the work queued to execute.
"""
teams_members_added = [
ChannelAccount().deserialize(member.serialize())
for member in teams_members_added
]
return await self.on_members_added_activity(teams_members_added, turn_context)
async def on_teams_members_removed_dispatch( # pylint: disable=unused-argument
self,
members_removed: [ChannelAccount],
team_info: TeamInfo,
turn_context: TurnContext,
):
"""
Override this in a derived class to provide logic for when members other than the bot
leave the channel, such as your bot's good-bye logic.
It will get the associated members with the provided accounts.
:param members_removed: A list of all the accounts removed from the channel, as
described by the conversation update activity.
:param team_info: The team info object representing the team.
:param turn_context: A context object for this turn.
:returns: A task that represents the work queued to execute.
"""
teams_members_removed = []
for member in members_removed:
new_account_json = member.serialize()
if "additional_properties" in new_account_json:
del new_account_json["additional_properties"]
teams_members_removed.append(
TeamsChannelAccount().deserialize(new_account_json)
)
return await self.on_teams_members_removed(
teams_members_removed, team_info, turn_context
)
async def on_teams_members_removed( # pylint: disable=unused-argument
self,
teams_members_removed: [TeamsChannelAccount],
team_info: TeamInfo,
turn_context: TurnContext,
):
"""
Override this in a derived class to provide logic for when members other than the bot
leave the channel, such as your bot's good-bye logic.
:param teams_members_removed: A list of all the members removed from the channel, as
described by the conversation update activity.
:param team_info: The team info object representing the team.
:param turn_context: A context object for this turn.
:returns: A task that represents the work queued to execute.
"""
members_removed = [
ChannelAccount().deserialize(member.serialize())
for member in teams_members_removed
]
return await self.on_members_removed_activity(members_removed, turn_context)
async def on_teams_channel_deleted( # pylint: disable=unused-argument
self, channel_info: ChannelInfo, team_info: TeamInfo, turn_context: TurnContext
):
"""
Invoked when a Channel Deleted event activity is received from the connector.
Channel Deleted correspond to the user deleting an existing channel.
:param channel_info: The channel info object which describes the channel.
:param team_info: The team info object representing the team.
:param turn_context: A context object for this turn.
:returns: A task that represents the work queued to execute.
"""
return
async def on_teams_channel_renamed( # pylint: disable=unused-argument
self, channel_info: ChannelInfo, team_info: TeamInfo, turn_context: TurnContext
):
"""
Invoked when a Channel Renamed event activity is received from the connector.
Channel Renamed correspond to the user renaming an existing channel.
:param channel_info: The channel info object which describes the channel.
:param team_info: The team info object representing the team.
:param turn_context: A context object for this turn.
:returns: A task that represents the work queued to execute.
"""
return
async def on_teams_channel_restored( # pylint: disable=unused-argument
self, channel_info: ChannelInfo, team_info: TeamInfo, turn_context: TurnContext
):
"""
Invoked when a Channel Restored event activity is received from the connector.
Channel Restored correspond to the user restoring a previously deleted channel.
:param channel_info: The channel info object which describes the channel.
:param team_info: The team info object representing the team.
:param turn_context: A context object for this turn.
:returns: A task that represents the work queued to execute.
"""
return
async def on_event_activity(self, turn_context: TurnContext):
"""
Invoked when an event activity is received from the connector when the base behavior of
:meth:`on_turn()` is used.
:param turn_context: The context object for this turn
:type turn_context: :class:`botbuilder.core.TurnContext`
:returns: A task that represents the work queued to execute
.. remarks::
When the :meth:`on_turn()` method receives an event activity, it calls this method.
If the activity name is `tokens/response`, it calls :meth:`on_token_response_event()`;
otherwise, it calls :meth:`on_event()`.
In a derived class, override this method to add logic that applies to all event activities.
Add logic to apply before the specific event-handling logic before the call to this base class method.
Add logic to apply after the specific event-handling logic after the call to this base class method.
Event activities communicate programmatic information from a client or channel to a bot.
The meaning of an event activity is defined by the event activity name property, which is meaningful within
the scope of a channel.
"""
if turn_context.activity.channel_id == Channels.ms_teams:
if turn_context.activity.name == "application/vnd.microsoft.meetingStart":
return await self.on_teams_meeting_start_event(
turn_context.activity.value, turn_context
)
if turn_context.activity.name == "application/vnd.microsoft.meetingEnd":
return await self.on_teams_meeting_end_event(
turn_context.activity.value, turn_context
)
return await super().on_event_activity(turn_context)
async def on_teams_meeting_start_event(
self, meeting: MeetingStartEventDetails, turn_context: TurnContext
): # pylint: disable=unused-argument
"""
Override this in a derived class to provide logic for when a Teams meeting start event is received.
:param meeting: The details of the meeting.
:param turn_context: A context object for this turn.
:returns: A task that represents the work queued to execute.
"""
return
async def on_teams_meeting_end_event(
self, meeting: MeetingEndEventDetails, turn_context: TurnContext
): # pylint: disable=unused-argument
"""
Override this in a derived class to provide logic for when a Teams meeting end event is received.
:param meeting: The details of the meeting.
:param turn_context: A context object for this turn.
:returns: A task that represents the work queued to execute.
"""
return
|
botbuilder-python/libraries/botbuilder-core/botbuilder/core/teams/teams_activity_handler.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-core/botbuilder/core/teams/teams_activity_handler.py",
"repo_id": "botbuilder-python",
"token_count": 16572
}
| 455 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from uuid import uuid4 as uuid
from aiounittest import AsyncTestCase
from botbuilder.core import MemoryStorage
from botbuilder.schema import (
Activity,
ConversationAccount,
ConversationReference,
)
from botbuilder.core.skills import (
BotFrameworkSkill,
SkillConversationIdFactory,
SkillConversationIdFactoryOptions,
)
class SkillConversationIdFactoryForTest(AsyncTestCase):
SERVICE_URL = "http://testbot.com/api/messages"
SKILL_ID = "skill"
@classmethod
def setUpClass(cls):
cls._skill_conversation_id_factory = SkillConversationIdFactory(MemoryStorage())
cls._application_id = str(uuid())
cls._bot_id = str(uuid())
async def test_skill_conversation_id_factory_happy_path(self):
conversation_reference = self._build_conversation_reference()
# Create skill conversation
skill_conversation_id = (
await self._skill_conversation_id_factory.create_skill_conversation_id(
options=SkillConversationIdFactoryOptions(
activity=self._build_message_activity(conversation_reference),
bot_framework_skill=self._build_bot_framework_skill(),
from_bot_id=self._bot_id,
from_bot_oauth_scope=self._bot_id,
)
)
)
assert (
skill_conversation_id and skill_conversation_id.strip()
), "Expected a valid skill conversation ID to be created"
# Retrieve skill conversation
retrieved_conversation_reference = (
await self._skill_conversation_id_factory.get_skill_conversation_reference(
skill_conversation_id
)
)
# Delete
await self._skill_conversation_id_factory.delete_conversation_reference(
skill_conversation_id
)
# Retrieve again
deleted_conversation_reference = (
await self._skill_conversation_id_factory.get_skill_conversation_reference(
skill_conversation_id
)
)
self.assertIsNotNone(retrieved_conversation_reference)
self.assertIsNotNone(retrieved_conversation_reference.conversation_reference)
self.assertEqual(
conversation_reference,
retrieved_conversation_reference.conversation_reference,
)
self.assertIsNone(deleted_conversation_reference)
async def test_id_is_unique_each_time(self):
conversation_reference = self._build_conversation_reference()
# Create skill conversation
first_id = (
await self._skill_conversation_id_factory.create_skill_conversation_id(
options=SkillConversationIdFactoryOptions(
activity=self._build_message_activity(conversation_reference),
bot_framework_skill=self._build_bot_framework_skill(),
from_bot_id=self._bot_id,
from_bot_oauth_scope=self._bot_id,
)
)
)
second_id = (
await self._skill_conversation_id_factory.create_skill_conversation_id(
options=SkillConversationIdFactoryOptions(
activity=self._build_message_activity(conversation_reference),
bot_framework_skill=self._build_bot_framework_skill(),
from_bot_id=self._bot_id,
from_bot_oauth_scope=self._bot_id,
)
)
)
# Ensure that we get a different conversation_id each time we call create_skill_conversation_id
self.assertNotEqual(first_id, second_id)
def _build_conversation_reference(self) -> ConversationReference:
return ConversationReference(
conversation=ConversationAccount(id=str(uuid())),
service_url=self.SERVICE_URL,
)
def _build_message_activity(
self, conversation_reference: ConversationReference
) -> Activity:
if not conversation_reference:
raise TypeError(str(conversation_reference))
activity = Activity.create_message_activity()
activity.apply_conversation_reference(conversation_reference)
return activity
def _build_bot_framework_skill(self) -> BotFrameworkSkill:
return BotFrameworkSkill(
app_id=self._application_id,
id=self.SKILL_ID,
skill_endpoint=self.SERVICE_URL,
)
|
botbuilder-python/libraries/botbuilder-core/tests/skills/test_skill_conversation_id_factory.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-core/tests/skills/test_skill_conversation_id_factory.py",
"repo_id": "botbuilder-python",
"token_count": 2021
}
| 456 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import aiounittest
from botbuilder.core import TurnContext, MemoryStorage, ConversationState
from botbuilder.core.adapters import TestAdapter
from botbuilder.schema import Activity, ConversationAccount
RECEIVED_MESSAGE = Activity(
type="message",
text="received",
channel_id="test",
conversation=ConversationAccount(id="convo"),
)
MISSING_CHANNEL_ID = Activity(
type="message", text="received", conversation=ConversationAccount(id="convo")
)
MISSING_CONVERSATION = Activity(type="message", text="received", channel_id="test")
END_OF_CONVERSATION = Activity(
type="endOfConversation",
channel_id="test",
conversation=ConversationAccount(id="convo"),
)
class TestConversationState(aiounittest.AsyncTestCase):
storage = MemoryStorage()
adapter = TestAdapter()
context = TurnContext(adapter, RECEIVED_MESSAGE)
middleware = ConversationState(storage)
async def test_should_reject_with_error_if_channel_id_is_missing(self):
context = TurnContext(self.adapter, MISSING_CHANNEL_ID)
async def next_middleware():
assert False, "should not have called next_middleware"
try:
await self.middleware.on_process_request(context, next_middleware)
except AttributeError:
pass
except Exception as error:
raise error
else:
raise AssertionError(
"Should not have completed and not raised AttributeError."
)
async def test_should_reject_with_error_if_conversation_is_missing(self):
context = TurnContext(self.adapter, MISSING_CONVERSATION)
async def next_middleware():
assert False, "should not have called next_middleware"
try:
await self.middleware.on_process_request(context, next_middleware)
except AttributeError:
pass
except Exception as error:
raise error
else:
raise AssertionError(
"Should not have completed and not raised AttributeError."
)
|
botbuilder-python/libraries/botbuilder-core/tests/test_conversation_state.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-core/tests/test_conversation_state.py",
"repo_id": "botbuilder-python",
"token_count": 828
}
| 457 |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
from .about import __version__
from .component_dialog import ComponentDialog
from .dialog_container import DialogContainer
from .dialog_context import DialogContext
from .dialog_event import DialogEvent
from .dialog_events import DialogEvents
from .dialog_instance import DialogInstance
from .dialog_reason import DialogReason
from .dialog_set import DialogSet
from .dialog_state import DialogState
from .dialog_turn_result import DialogTurnResult
from .dialog_turn_status import DialogTurnStatus
from .dialog_manager import DialogManager
from .dialog_manager_result import DialogManagerResult
from .dialog import Dialog
from .dialogs_component_registration import DialogsComponentRegistration
from .persisted_state_keys import PersistedStateKeys
from .persisted_state import PersistedState
from .waterfall_dialog import WaterfallDialog
from .waterfall_step_context import WaterfallStepContext
from .dialog_extensions import DialogExtensions
from .prompts import *
from .choices import *
from .skills import *
from .object_path import ObjectPath
__all__ = [
"ComponentDialog",
"DialogContainer",
"DialogContext",
"DialogEvent",
"DialogEvents",
"DialogInstance",
"DialogReason",
"DialogSet",
"DialogState",
"DialogTurnResult",
"DialogTurnStatus",
"DialogManager",
"DialogManagerResult",
"Dialog",
"DialogsComponentRegistration",
"WaterfallDialog",
"WaterfallStepContext",
"ConfirmPrompt",
"DateTimePrompt",
"DateTimeResolution",
"NumberPrompt",
"OAuthPrompt",
"OAuthPromptSettings",
"PersistedStateKeys",
"PersistedState",
"PromptRecognizerResult",
"PromptValidatorContext",
"Prompt",
"PromptOptions",
"TextPrompt",
"DialogExtensions",
"ObjectPath",
"__version__",
]
|
botbuilder-python/libraries/botbuilder-dialogs/botbuilder/dialogs/__init__.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-dialogs/botbuilder/dialogs/__init__.py",
"repo_id": "botbuilder-python",
"token_count": 634
}
| 458 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
class SortedValue:
"""A value that can be sorted and still refer to its original position with a source array."""
def __init__(self, value: str, index: int):
"""
Parameters:
-----------
value: The value that will be sorted.
index: The values original position within its unsorted array.
"""
self.value = value
self.index = index
|
botbuilder-python/libraries/botbuilder-dialogs/botbuilder/dialogs/choices/sorted_value.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-dialogs/botbuilder/dialogs/choices/sorted_value.py",
"repo_id": "botbuilder-python",
"token_count": 172
}
| 459 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from .dialog_turn_status import DialogTurnStatus
class DialogTurnResult:
"""
Result returned to the caller of one of the various stack manipulation methods.
"""
def __init__(self, status: DialogTurnStatus, result: object = None):
"""
:param status: The current status of the stack.
:type status: :class:`botbuilder.dialogs.DialogTurnStatus`
:param result: The result returned by a dialog that was just ended.
:type result: object
"""
self._status = status
self._result = result
@property
def status(self):
"""
Gets or sets the current status of the stack.
:return self._status: The status of the stack.
:rtype self._status: :class:`DialogTurnStatus`
"""
return self._status
@property
def result(self):
"""
Final result returned by a dialog that just completed.
:return self._result: Final result returned by a dialog that just completed.
:rtype self._result: object
"""
return self._result
|
botbuilder-python/libraries/botbuilder-dialogs/botbuilder/dialogs/dialog_turn_result.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-dialogs/botbuilder/dialogs/dialog_turn_result.py",
"repo_id": "botbuilder-python",
"token_count": 430
}
| 460 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from .alias_path_resolver import AliasPathResolver
class PercentPathResolver(AliasPathResolver):
def __init__(self):
super().__init__(alias="%", prefix="class.")
|
botbuilder-python/libraries/botbuilder-dialogs/botbuilder/dialogs/memory/path_resolvers/percent_path_resolver.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-dialogs/botbuilder/dialogs/memory/path_resolvers/percent_path_resolver.py",
"repo_id": "botbuilder-python",
"token_count": 83
}
| 461 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
class PersistedStateKeys:
def __init__(self):
self.user_state: str = None
self.conversation_state: str = None
|
botbuilder-python/libraries/botbuilder-dialogs/botbuilder/dialogs/persisted_state_keys.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-dialogs/botbuilder/dialogs/persisted_state_keys.py",
"repo_id": "botbuilder-python",
"token_count": 76
}
| 462 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from typing import Dict
from botbuilder.core.turn_context import TurnContext
from .prompt_options import PromptOptions
from .prompt_recognizer_result import PromptRecognizerResult
class PromptValidatorContext:
def __init__(
self,
turn_context: TurnContext,
recognized: PromptRecognizerResult,
state: Dict[str, object],
options: PromptOptions,
):
"""Creates contextual information passed to a custom `PromptValidator`.
Parameters
----------
turn_context
The context for the current turn of conversation with the user.
recognized
Result returned from the prompts recognizer function.
state
A dictionary of values persisted for each conversational turn while the prompt is active.
options
Original set of options passed to the prompt by the calling dialog.
"""
self.context = turn_context
self.recognized = recognized
self.state = state
self.options = options
@property
def attempt_count(self) -> int:
"""
Gets the number of times the prompt has been executed.
"""
# pylint: disable=import-outside-toplevel
from botbuilder.dialogs.prompts import Prompt
return self.state.get(Prompt.ATTEMPT_COUNT_KEY, 0)
|
botbuilder-python/libraries/botbuilder-dialogs/botbuilder/dialogs/prompts/prompt_validator_context.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-dialogs/botbuilder/dialogs/prompts/prompt_validator_context.py",
"repo_id": "botbuilder-python",
"token_count": 529
}
| 463 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from typing import List
import aiounittest
from botbuilder.dialogs.choices import (
ChoiceRecognizers,
Find,
FindValuesOptions,
SortedValue,
)
def assert_result(result, start, end, text):
assert (
result.start == start
), f"Invalid ModelResult.start of '{result.start}' for '{text}' result."
assert (
result.end == end
), f"Invalid ModelResult.end of '{result.end}' for '{text}' result."
assert (
result.text == text
), f"Invalid ModelResult.text of '{result.text}' for '{text}' result."
def assert_value(result, value, index, score):
assert (
result.type_name == "value"
), f"Invalid ModelResult.type_name of '{result.type_name}' for '{value}' value."
assert result.resolution, f"Missing ModelResult.resolution for '{value}' value."
resolution = result.resolution
assert (
resolution.value == value
), f"Invalid resolution.value of '{resolution.value}' for '{value}' value."
assert (
resolution.index == index
), f"Invalid resolution.index of '{resolution.index}' for '{value}' value."
assert (
resolution.score == score
), f"Invalid resolution.score of '{resolution.score}' for '{value}' value."
def assert_choice(result, value, index, score, synonym=None):
assert (
result.type_name == "choice"
), f"Invalid ModelResult.type_name of '{result.type_name}' for '{value}' choice."
assert result.resolution, f"Missing ModelResult.resolution for '{value}' choice."
resolution = result.resolution
assert (
resolution.value == value
), f"Invalid resolution.value of '{resolution.value}' for '{value}' choice."
assert (
resolution.index == index
), f"Invalid resolution.index of '{resolution.index}' for '{value}' choice."
assert (
resolution.score == score
), f"Invalid resolution.score of '{resolution.score}' for '{value}' choice."
if synonym:
assert ( # pylint: disable=assert-on-tuple
resolution.synonym == synonym,
f"Invalid resolution.synonym of '{resolution.synonym}' for '{value}' choice.",
)
_color_choices: List[str] = ["red", "green", "blue"]
_overlapping_choices: List[str] = ["bread", "bread pudding", "pudding"]
_color_values: List[SortedValue] = [
SortedValue(value="red", index=0),
SortedValue(value="green", index=1),
SortedValue(value="blue", index=2),
]
_overlapping_values: List[SortedValue] = [
SortedValue(value="bread", index=0),
SortedValue(value="bread pudding", index=1),
SortedValue(value="pudding", index=2),
]
_similar_values: List[SortedValue] = [
SortedValue(value="option A", index=0),
SortedValue(value="option B", index=1),
SortedValue(value="option C", index=2),
]
class ChoiceRecognizersTest(aiounittest.AsyncTestCase):
# Find.find_values
def test_should_find_a_simple_value_in_a_single_word_utterance(self):
found = Find.find_values("red", _color_values)
assert len(found) == 1, f"Invalid token count of '{len(found)}' returned."
assert_result(found[0], 0, 2, "red")
assert_value(found[0], "red", 0, 1.0)
def test_should_find_a_simple_value_in_an_utterance(self):
found = Find.find_values("the red one please.", _color_values)
assert len(found) == 1, f"Invalid token count of '{len(found)}' returned."
assert_result(found[0], 4, 6, "red")
assert_value(found[0], "red", 0, 1.0)
def test_should_find_multiple_values_within_an_utterance(self):
found = Find.find_values("the red and blue ones please.", _color_values)
assert len(found) == 2, f"Invalid token count of '{len(found)}' returned."
assert_result(found[0], 4, 6, "red")
assert_value(found[0], "red", 0, 1.0)
assert_value(found[1], "blue", 2, 1.0)
def test_should_find_multiple_values_that_overlap(self):
found = Find.find_values(
"the bread pudding and bread please.", _overlapping_values
)
assert len(found) == 2, f"Invalid token count of '{len(found)}' returned."
assert_result(found[0], 4, 16, "bread pudding")
assert_value(found[0], "bread pudding", 1, 1.0)
assert_value(found[1], "bread", 0, 1.0)
def test_should_correctly_disambiguate_between_similar_values(self):
found = Find.find_values(
"option B", _similar_values, FindValuesOptions(allow_partial_matches=True)
)
assert len(found) == 1, f"Invalid token count of '{len(found)}' returned."
assert_value(found[0], "option B", 1, 1.0)
def test_should_find_a_single_choice_in_an_utterance(self):
found = Find.find_choices("the red one please.", _color_choices)
assert len(found) == 1, f"Invalid token count of '{len(found)}' returned."
assert_result(found[0], 4, 6, "red")
assert_choice(found[0], "red", 0, 1.0, "red")
def test_should_find_multiple_choices_within_an_utterance(self):
found = Find.find_choices("the red and blue ones please.", _color_choices)
assert len(found) == 2, f"Invalid token count of '{len(found)}' returned."
assert_result(found[0], 4, 6, "red")
assert_choice(found[0], "red", 0, 1.0)
assert_choice(found[1], "blue", 2, 1.0)
def test_should_find_multiple_choices_that_overlap(self):
found = Find.find_choices(
"the bread pudding and bread please.", _overlapping_choices
)
assert len(found) == 2, f"Invalid token count of '{len(found)}' returned."
assert_result(found[0], 4, 16, "bread pudding")
assert_choice(found[0], "bread pudding", 1, 1.0)
assert_choice(found[1], "bread", 0, 1.0)
def test_should_accept_null_utterance_in_find_choices(self):
found = Find.find_choices(None, _color_choices)
assert not found
# ChoiceRecognizers.recognize_choices
def test_should_find_a_choice_in_an_utterance_by_name(self):
found = ChoiceRecognizers.recognize_choices(
"the red one please.", _color_choices
)
assert len(found) == 1
assert_result(found[0], 4, 6, "red")
assert_choice(found[0], "red", 0, 1.0, "red")
def test_should_find_a_choice_in_an_utterance_by_ordinal_position(self):
found = ChoiceRecognizers.recognize_choices(
"the first one please.", _color_choices
)
assert len(found) == 1
assert_result(found[0], 4, 8, "first")
assert_choice(found[0], "red", 0, 1.0)
def test_should_find_multiple_choices_in_an_utterance_by_ordinal_position(self):
found = ChoiceRecognizers.recognize_choices(
"the first and third one please", _color_choices
)
assert len(found) == 2
assert_choice(found[0], "red", 0, 1.0)
assert_choice(found[1], "blue", 2, 1.0)
def test_should_find_a_choice_in_an_utterance_by_numerical_index_digit(self):
found = ChoiceRecognizers.recognize_choices("1", _color_choices)
assert len(found) == 1
assert_result(found[0], 0, 0, "1")
assert_choice(found[0], "red", 0, 1.0)
def test_should_find_a_choice_in_an_utterance_by_numerical_index_text(self):
found = ChoiceRecognizers.recognize_choices("one", _color_choices)
assert len(found) == 1
assert_result(found[0], 0, 2, "one")
assert_choice(found[0], "red", 0, 1.0)
def test_should_find_multiple_choices_in_an_utterance_by_numerical_index(self):
found = ChoiceRecognizers.recognize_choices("option one and 3.", _color_choices)
assert len(found) == 2
assert_choice(found[0], "red", 0, 1.0)
assert_choice(found[1], "blue", 2, 1.0)
def test_should_accept_null_utterance_in_recognize_choices(self):
found = ChoiceRecognizers.recognize_choices(None, _color_choices)
assert not found
|
botbuilder-python/libraries/botbuilder-dialogs/tests/choices/test_choice_recognizers.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-dialogs/tests/choices/test_choice_recognizers.py",
"repo_id": "botbuilder-python",
"token_count": 3283
}
| 464 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import uuid
from http import HTTPStatus
from typing import Callable, Union, List
from unittest.mock import Mock
import aiounittest
from botframework.connector.token_api.models import TokenExchangeResource
from botbuilder.core import (
ConversationState,
MemoryStorage,
InvokeResponse,
TurnContext,
MessageFactory,
)
from botbuilder.core.card_factory import ContentTypes
from botbuilder.core.skills import (
BotFrameworkSkill,
ConversationIdFactoryBase,
SkillConversationIdFactoryOptions,
SkillConversationReference,
BotFrameworkClient,
)
from botbuilder.schema import (
Activity,
ActivityTypes,
ConversationReference,
OAuthCard,
Attachment,
ConversationAccount,
ChannelAccount,
ExpectedReplies,
DeliveryModes,
)
from botbuilder.testing import DialogTestClient
from botbuilder.dialogs import (
SkillDialog,
SkillDialogOptions,
BeginSkillDialogOptions,
DialogTurnStatus,
)
class SimpleConversationIdFactory(
ConversationIdFactoryBase
): # pylint: disable=abstract-method
def __init__(self):
self.conversation_refs = {}
self.create_count = 0
async def create_skill_conversation_id(
self,
options_or_conversation_reference: Union[
SkillConversationIdFactoryOptions, ConversationReference
],
) -> str:
self.create_count += 1
key = (
options_or_conversation_reference.activity.conversation.id
+ options_or_conversation_reference.activity.service_url
)
if key not in self.conversation_refs:
self.conversation_refs[key] = SkillConversationReference(
conversation_reference=TurnContext.get_conversation_reference(
options_or_conversation_reference.activity
),
oauth_scope=options_or_conversation_reference.from_bot_oauth_scope,
)
return key
async def get_skill_conversation_reference(
self, skill_conversation_id: str
) -> SkillConversationReference:
return self.conversation_refs[skill_conversation_id]
async def delete_conversation_reference(self, skill_conversation_id: str):
self.conversation_refs.pop(skill_conversation_id, None)
return
class SkillDialogTests(aiounittest.AsyncTestCase):
async def test_constructor_validation_test(self):
# missing dialog_id
with self.assertRaises(TypeError):
SkillDialog(SkillDialogOptions(), None)
# missing dialog options
with self.assertRaises(TypeError):
SkillDialog(None, "dialog_id")
async def test_begin_dialog_options_validation(self):
dialog_options = SkillDialogOptions()
sut = SkillDialog(dialog_options, dialog_id="dialog_id")
# empty options should raise
client = DialogTestClient("test", sut)
with self.assertRaises(TypeError):
await client.send_activity("irrelevant")
# non DialogArgs should raise
client = DialogTestClient("test", sut, {})
with self.assertRaises(TypeError):
await client.send_activity("irrelevant")
# Activity in DialogArgs should be set
client = DialogTestClient("test", sut, BeginSkillDialogOptions(None))
with self.assertRaises(TypeError):
await client.send_activity("irrelevant")
async def test_begin_dialog_calls_skill_no_deliverymode(self):
return await self.begin_dialog_calls_skill(None)
async def test_begin_dialog_calls_skill_expect_replies(self):
return await self.begin_dialog_calls_skill(DeliveryModes.expect_replies)
async def begin_dialog_calls_skill(self, deliver_mode: str):
activity_sent = None
from_bot_id_sent = None
to_bot_id_sent = None
to_url_sent = None
async def capture(
from_bot_id: str,
to_bot_id: str,
to_url: str,
service_url: str, # pylint: disable=unused-argument
conversation_id: str, # pylint: disable=unused-argument
activity: Activity,
):
nonlocal from_bot_id_sent, to_bot_id_sent, to_url_sent, activity_sent
from_bot_id_sent = from_bot_id
to_bot_id_sent = to_bot_id
to_url_sent = to_url
activity_sent = activity
mock_skill_client = self._create_mock_skill_client(capture)
conversation_state = ConversationState(MemoryStorage())
dialog_options = SkillDialogTests.create_skill_dialog_options(
conversation_state, mock_skill_client
)
sut = SkillDialog(dialog_options, "dialog_id")
activity_to_send = MessageFactory.text(str(uuid.uuid4()))
activity_to_send.delivery_mode = deliver_mode
client = DialogTestClient(
"test",
sut,
BeginSkillDialogOptions(activity=activity_to_send),
conversation_state=conversation_state,
)
assert len(dialog_options.conversation_id_factory.conversation_refs) == 0
# Send something to the dialog to start it
await client.send_activity(MessageFactory.text("irrelevant"))
# Assert results and data sent to the SkillClient for fist turn
assert len(dialog_options.conversation_id_factory.conversation_refs) == 1
assert dialog_options.bot_id == from_bot_id_sent
assert dialog_options.skill.app_id == to_bot_id_sent
assert dialog_options.skill.skill_endpoint == to_url_sent
assert activity_to_send.text == activity_sent.text
assert DialogTurnStatus.Waiting == client.dialog_turn_result.status
# Send a second message to continue the dialog
await client.send_activity(MessageFactory.text("Second message"))
# Assert results for second turn
assert len(dialog_options.conversation_id_factory.conversation_refs) == 1
assert activity_sent.text == "Second message"
assert DialogTurnStatus.Waiting == client.dialog_turn_result.status
# Send EndOfConversation to the dialog
await client.send_activity(Activity(type=ActivityTypes.end_of_conversation))
# Assert we are done.
assert DialogTurnStatus.Complete == client.dialog_turn_result.status
async def test_should_handle_invoke_activities(self):
activity_sent = None
from_bot_id_sent = None
to_bot_id_sent = None
to_url_sent = None
async def capture(
from_bot_id: str,
to_bot_id: str,
to_url: str,
service_url: str, # pylint: disable=unused-argument
conversation_id: str, # pylint: disable=unused-argument
activity: Activity,
):
nonlocal from_bot_id_sent, to_bot_id_sent, to_url_sent, activity_sent
from_bot_id_sent = from_bot_id
to_bot_id_sent = to_bot_id
to_url_sent = to_url
activity_sent = activity
mock_skill_client = self._create_mock_skill_client(capture)
conversation_state = ConversationState(MemoryStorage())
dialog_options = SkillDialogTests.create_skill_dialog_options(
conversation_state, mock_skill_client
)
sut = SkillDialog(dialog_options, "dialog_id")
activity_to_send = Activity(
type=ActivityTypes.invoke,
name=str(uuid.uuid4()),
)
client = DialogTestClient(
"test",
sut,
BeginSkillDialogOptions(activity=activity_to_send),
conversation_state=conversation_state,
)
# Send something to the dialog to start it
await client.send_activity(MessageFactory.text("irrelevant"))
# Assert results and data sent to the SkillClient for fist turn
assert dialog_options.bot_id == from_bot_id_sent
assert dialog_options.skill.app_id == to_bot_id_sent
assert dialog_options.skill.skill_endpoint == to_url_sent
assert activity_to_send.text == activity_sent.text
assert DialogTurnStatus.Waiting == client.dialog_turn_result.status
# Send a second message to continue the dialog
await client.send_activity(MessageFactory.text("Second message"))
# Assert results for second turn
assert activity_sent.text == "Second message"
assert DialogTurnStatus.Waiting == client.dialog_turn_result.status
# Send EndOfConversation to the dialog
await client.send_activity(Activity(type=ActivityTypes.end_of_conversation))
# Assert we are done.
assert DialogTurnStatus.Complete == client.dialog_turn_result.status
async def test_cancel_dialog_sends_eoc(self):
activity_sent = None
async def capture(
from_bot_id: str, # pylint: disable=unused-argument
to_bot_id: str, # pylint: disable=unused-argument
to_url: str, # pylint: disable=unused-argument
service_url: str, # pylint: disable=unused-argument
conversation_id: str, # pylint: disable=unused-argument
activity: Activity,
):
nonlocal activity_sent
activity_sent = activity
mock_skill_client = self._create_mock_skill_client(capture)
conversation_state = ConversationState(MemoryStorage())
dialog_options = SkillDialogTests.create_skill_dialog_options(
conversation_state, mock_skill_client
)
sut = SkillDialog(dialog_options, "dialog_id")
activity_to_send = MessageFactory.text(str(uuid.uuid4()))
client = DialogTestClient(
"test",
sut,
BeginSkillDialogOptions(activity=activity_to_send),
conversation_state=conversation_state,
)
# Send something to the dialog to start it
await client.send_activity(MessageFactory.text("irrelevant"))
# Cancel the dialog so it sends an EoC to the skill
await client.dialog_context.cancel_all_dialogs()
assert activity_sent
assert activity_sent.type == ActivityTypes.end_of_conversation
async def test_should_throw_on_post_failure(self):
# This mock client will fail
mock_skill_client = self._create_mock_skill_client(None, 500)
conversation_state = ConversationState(MemoryStorage())
dialog_options = SkillDialogTests.create_skill_dialog_options(
conversation_state, mock_skill_client
)
sut = SkillDialog(dialog_options, "dialog_id")
activity_to_send = MessageFactory.text(str(uuid.uuid4()))
client = DialogTestClient(
"test",
sut,
BeginSkillDialogOptions(activity=activity_to_send),
conversation_state=conversation_state,
)
# A send should raise an exception
with self.assertRaises(Exception):
await client.send_activity("irrelevant")
async def test_should_intercept_oauth_cards_for_sso(self):
connection_name = "connectionName"
first_response = ExpectedReplies(
activities=[
SkillDialogTests.create_oauth_card_attachment_activity("https://test")
]
)
sequence = 0
async def post_return():
nonlocal sequence
if sequence == 0:
result = InvokeResponse(body=first_response, status=HTTPStatus.OK)
else:
result = InvokeResponse(status=HTTPStatus.OK)
sequence += 1
return result
mock_skill_client = self._create_mock_skill_client(None, post_return)
conversation_state = ConversationState(MemoryStorage())
dialog_options = SkillDialogTests.create_skill_dialog_options(
conversation_state, mock_skill_client, connection_name
)
sut = SkillDialog(dialog_options, dialog_id="dialog")
activity_to_send = SkillDialogTests.create_send_activity()
client = DialogTestClient(
"test",
sut,
BeginSkillDialogOptions(
activity=activity_to_send,
),
conversation_state=conversation_state,
)
client.test_adapter.add_exchangeable_token(
connection_name, "test", "User1", "https://test", "https://test1"
)
final_activity = await client.send_activity(MessageFactory.text("irrelevant"))
self.assertIsNone(final_activity)
async def test_should_not_intercept_oauth_cards_for_empty_connection_name(self):
connection_name = "connectionName"
first_response = ExpectedReplies(
activities=[
SkillDialogTests.create_oauth_card_attachment_activity("https://test")
]
)
sequence = 0
async def post_return():
nonlocal sequence
if sequence == 0:
result = InvokeResponse(body=first_response, status=HTTPStatus.OK)
else:
result = InvokeResponse(status=HTTPStatus.OK)
sequence += 1
return result
mock_skill_client = self._create_mock_skill_client(None, post_return)
conversation_state = ConversationState(MemoryStorage())
dialog_options = SkillDialogTests.create_skill_dialog_options(
conversation_state, mock_skill_client
)
sut = SkillDialog(dialog_options, dialog_id="dialog")
activity_to_send = SkillDialogTests.create_send_activity()
client = DialogTestClient(
"test",
sut,
BeginSkillDialogOptions(
activity=activity_to_send,
),
conversation_state=conversation_state,
)
client.test_adapter.add_exchangeable_token(
connection_name, "test", "User1", "https://test", "https://test1"
)
final_activity = await client.send_activity(MessageFactory.text("irrelevant"))
self.assertIsNotNone(final_activity)
self.assertEqual(len(final_activity.attachments), 1)
async def test_should_not_intercept_oauth_cards_for_empty_token(self):
first_response = ExpectedReplies(
activities=[
SkillDialogTests.create_oauth_card_attachment_activity("https://test")
]
)
sequence = 0
async def post_return():
nonlocal sequence
if sequence == 0:
result = InvokeResponse(body=first_response, status=HTTPStatus.OK)
else:
result = InvokeResponse(status=HTTPStatus.OK)
sequence += 1
return result
mock_skill_client = self._create_mock_skill_client(None, post_return)
conversation_state = ConversationState(MemoryStorage())
dialog_options = SkillDialogTests.create_skill_dialog_options(
conversation_state, mock_skill_client
)
sut = SkillDialog(dialog_options, dialog_id="dialog")
activity_to_send = SkillDialogTests.create_send_activity()
client = DialogTestClient(
"test",
sut,
BeginSkillDialogOptions(
activity=activity_to_send,
),
conversation_state=conversation_state,
)
# Don't add exchangeable token to test adapter
final_activity = await client.send_activity(MessageFactory.text("irrelevant"))
self.assertIsNotNone(final_activity)
self.assertEqual(len(final_activity.attachments), 1)
async def test_should_not_intercept_oauth_cards_for_token_exception(self):
connection_name = "connectionName"
first_response = ExpectedReplies(
activities=[
SkillDialogTests.create_oauth_card_attachment_activity("https://test")
]
)
sequence = 0
async def post_return():
nonlocal sequence
if sequence == 0:
result = InvokeResponse(body=first_response, status=HTTPStatus.OK)
else:
result = InvokeResponse(status=HTTPStatus.OK)
sequence += 1
return result
mock_skill_client = self._create_mock_skill_client(None, post_return)
conversation_state = ConversationState(MemoryStorage())
dialog_options = SkillDialogTests.create_skill_dialog_options(
conversation_state, mock_skill_client, connection_name
)
sut = SkillDialog(dialog_options, dialog_id="dialog")
activity_to_send = SkillDialogTests.create_send_activity()
initial_dialog_options = BeginSkillDialogOptions(
activity=activity_to_send,
)
client = DialogTestClient(
"test",
sut,
initial_dialog_options,
conversation_state=conversation_state,
)
client.test_adapter.throw_on_exchange_request(
connection_name, "test", "User1", "https://test"
)
final_activity = await client.send_activity(MessageFactory.text("irrelevant"))
self.assertIsNotNone(final_activity)
self.assertEqual(len(final_activity.attachments), 1)
async def test_should_not_intercept_oauth_cards_for_bad_request(self):
connection_name = "connectionName"
first_response = ExpectedReplies(
activities=[
SkillDialogTests.create_oauth_card_attachment_activity("https://test")
]
)
sequence = 0
async def post_return():
nonlocal sequence
if sequence == 0:
result = InvokeResponse(body=first_response, status=HTTPStatus.OK)
else:
result = InvokeResponse(status=HTTPStatus.CONFLICT)
sequence += 1
return result
mock_skill_client = self._create_mock_skill_client(None, post_return)
conversation_state = ConversationState(MemoryStorage())
dialog_options = SkillDialogTests.create_skill_dialog_options(
conversation_state, mock_skill_client, connection_name
)
sut = SkillDialog(dialog_options, dialog_id="dialog")
activity_to_send = SkillDialogTests.create_send_activity()
client = DialogTestClient(
"test",
sut,
BeginSkillDialogOptions(
activity=activity_to_send,
),
conversation_state=conversation_state,
)
client.test_adapter.add_exchangeable_token(
connection_name, "test", "User1", "https://test", "https://test1"
)
final_activity = await client.send_activity(MessageFactory.text("irrelevant"))
self.assertIsNotNone(final_activity)
self.assertEqual(len(final_activity.attachments), 1)
async def test_end_of_conversation_from_expect_replies_calls_delete_conversation_reference(
self,
):
activity_sent: Activity = None
# Callback to capture the parameters sent to the skill
async def capture_action(
from_bot_id: str, # pylint: disable=unused-argument
to_bot_id: str, # pylint: disable=unused-argument
to_uri: str, # pylint: disable=unused-argument
service_url: str, # pylint: disable=unused-argument
conversation_id: str, # pylint: disable=unused-argument
activity: Activity,
):
# Capture values sent to the skill so we can assert the right parameters were used.
nonlocal activity_sent
activity_sent = activity
eoc = Activity.create_end_of_conversation_activity()
expected_replies = list([eoc])
# Create a mock skill client to intercept calls and capture what is sent.
mock_skill_client = self._create_mock_skill_client(
capture_action, expected_replies=expected_replies
)
# Use Memory for conversation state
conversation_state = ConversationState(MemoryStorage())
dialog_options = self.create_skill_dialog_options(
conversation_state, mock_skill_client
)
# Create the SkillDialogInstance and the activity to send.
sut = SkillDialog(dialog_options, dialog_id="dialog")
activity_to_send = Activity.create_message_activity()
activity_to_send.delivery_mode = DeliveryModes.expect_replies
activity_to_send.text = str(uuid.uuid4())
client = DialogTestClient(
"test",
sut,
BeginSkillDialogOptions(activity_to_send),
conversation_state=conversation_state,
)
# Send something to the dialog to start it
await client.send_activity("hello")
simple_id_factory: SimpleConversationIdFactory = (
dialog_options.conversation_id_factory
)
self.assertEqual(0, len(simple_id_factory.conversation_refs))
self.assertEqual(1, simple_id_factory.create_count)
@staticmethod
def create_skill_dialog_options(
conversation_state: ConversationState,
skill_client: BotFrameworkClient,
connection_name: str = None,
):
return SkillDialogOptions(
bot_id=str(uuid.uuid4()),
skill_host_endpoint="http://test.contoso.com/skill/messages",
conversation_id_factory=SimpleConversationIdFactory(),
conversation_state=conversation_state,
skill_client=skill_client,
skill=BotFrameworkSkill(
app_id=str(uuid.uuid4()),
skill_endpoint="http://testskill.contoso.com/api/messages",
),
connection_name=connection_name,
)
@staticmethod
def create_send_activity() -> Activity:
return Activity(
type=ActivityTypes.message,
delivery_mode=DeliveryModes.expect_replies,
text=str(uuid.uuid4()),
)
@staticmethod
def create_oauth_card_attachment_activity(uri: str) -> Activity:
oauth_card = OAuthCard(token_exchange_resource=TokenExchangeResource(uri=uri))
attachment = Attachment(
content_type=ContentTypes.oauth_card,
content=oauth_card,
)
attachment_activity = MessageFactory.attachment(attachment)
attachment_activity.conversation = ConversationAccount(id=str(uuid.uuid4()))
attachment_activity.from_property = ChannelAccount(id="blah", name="name")
return attachment_activity
def _create_mock_skill_client(
self,
callback: Callable,
return_status: Union[Callable, int] = 200,
expected_replies: List[Activity] = None,
) -> BotFrameworkClient:
mock_client = Mock()
activity_list = ExpectedReplies(
activities=expected_replies or [MessageFactory.text("dummy activity")]
)
async def mock_post_activity(
from_bot_id: str,
to_bot_id: str,
to_url: str,
service_url: str,
conversation_id: str,
activity: Activity,
):
nonlocal callback, return_status
if callback:
await callback(
from_bot_id,
to_bot_id,
to_url,
service_url,
conversation_id,
activity,
)
if isinstance(return_status, Callable):
return await return_status()
return InvokeResponse(status=return_status, body=activity_list)
mock_client.post_activity.side_effect = mock_post_activity
return mock_client
|
botbuilder-python/libraries/botbuilder-dialogs/tests/test_skill_dialog.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-dialogs/tests/test_skill_dialog.py",
"repo_id": "botbuilder-python",
"token_count": 10360
}
| 465 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from .aiohttp_web_socket import AiohttpWebSocket
__all__ = [
"AiohttpWebSocket",
]
|
botbuilder-python/libraries/botbuilder-integration-aiohttp/botbuilder/integration/aiohttp/streaming/__init__.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-integration-aiohttp/botbuilder/integration/aiohttp/streaming/__init__.py",
"repo_id": "botbuilder-python",
"token_count": 58
}
| 466 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from .dialog_test_client import DialogTestClient
from .dialog_test_logger import DialogTestLogger
from .storage_base_tests import StorageBaseTests
__all__ = ["DialogTestClient", "DialogTestLogger", "StorageBaseTests"]
|
botbuilder-python/libraries/botbuilder-testing/botbuilder/testing/__init__.py/0
|
{
"file_path": "botbuilder-python/libraries/botbuilder-testing/botbuilder/testing/__init__.py",
"repo_id": "botbuilder-python",
"token_count": 88
}
| 467 |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
from typing import Optional, Type
from msrest.universal_http.async_abc import AsyncHTTPSender as AsyncHttpDriver
from msrest.pipeline.aiohttp import AsyncHTTPSender
from msrest.async_client import AsyncPipeline
from msrest import Serializer, Deserializer
from .operations_async import AttachmentsOperations
from .operations_async import ConversationsOperations
from .. import models
from ..bot_framework_sdk_client_async import (
BotFrameworkSDKClientAsync,
BotFrameworkConnectorConfiguration,
)
class ConnectorClient(BotFrameworkSDKClientAsync):
"""The Bot Connector REST API allows your bot to send and receive messages to channels configured in the
[Bot Framework Developer Portal](https://dev.botframework.com). The Connector service uses industry-standard REST
and JSON over HTTPS.
Client libraries for this REST API are available. See below for a list.
Many bots will use both the Bot Connector REST API and the associated [Bot State REST API](/en-us/restapi/state).
The Bot State REST API allows a bot to store and retrieve state associated with users and conversations.
Authentication for both the Bot Connector and Bot State REST APIs is accomplished with JWT Bearer tokens, and is
described in detail in the [Connector Authentication](/en-us/restapi/authentication) document.
# Client Libraries for the Bot Connector REST API
* [Bot Builder for C#](/en-us/csharp/builder/sdkreference/)
* [Bot Builder for Node.js](/en-us/node/builder/overview/)
* Generate your own from the
[Connector API Swagger file](https://raw.githubusercontent.com/Microsoft/BotBuilder/master/CSharp/Library/
Microsoft.Bot.Connector.Shared/Swagger/ConnectorAPI.json)
ยฉ 2016 Microsoft
:ivar config: Configuration for client.
:vartype config: ConnectorClientConfiguration
:ivar attachments: Attachments operations
:vartype attachments: botframework.connector.aio.operations_async.AttachmentsOperations
:ivar conversations: Conversations operations
:vartype conversations: botframework.connector.aio.operations_async.ConversationsOperations
:param credentials: Subscription credentials which uniquely identify
client subscription.
:type credentials: None
:param str base_url: Service URL
"""
def __init__(
self,
credentials,
base_url=None,
*,
pipeline_type: Optional[Type[AsyncPipeline]] = None,
sender: Optional[AsyncHTTPSender] = None,
driver: Optional[AsyncHttpDriver] = None,
custom_configuration: Optional[BotFrameworkConnectorConfiguration] = None,
):
if custom_configuration:
self.config = custom_configuration
else:
self.config = BotFrameworkConnectorConfiguration(
credentials,
base_url,
pipeline_type=pipeline_type,
sender=sender,
driver=driver,
)
super(ConnectorClient, self).__init__(self.config)
client_models = {
k: v for k, v in models.__dict__.items() if isinstance(v, type)
}
self.api_version = "v3"
self._serialize = Serializer(client_models)
self._deserialize = Deserializer(client_models)
self.attachments = AttachmentsOperations(
self._client, self.config, self._serialize, self._deserialize
)
self.conversations = ConversationsOperations(
self._client, self.config, self._serialize, self._deserialize
)
|
botbuilder-python/libraries/botframework-connector/botframework/connector/aio/_connector_client_async.py/0
|
{
"file_path": "botbuilder-python/libraries/botframework-connector/botframework/connector/aio/_connector_client_async.py",
"repo_id": "botbuilder-python",
"token_count": 1288
}
| 468 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from .claims_identity import ClaimsIdentity
from .connector_factory import ConnectorFactory
class AuthenticateRequestResult:
def __init__(self) -> None:
# A value for the Audience.
self.audience: str = None
# A value for the ClaimsIdentity.
self.claims_identity: ClaimsIdentity = None
# A value for the caller id.
self.caller_id: str = None
# A value for the ConnectorFactory.
self.connector_factory: ConnectorFactory = None
|
botbuilder-python/libraries/botframework-connector/botframework/connector/auth/authenticate_request_result.py/0
|
{
"file_path": "botbuilder-python/libraries/botframework-connector/botframework/connector/auth/authenticate_request_result.py",
"repo_id": "botbuilder-python",
"token_count": 210
}
| 469 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import json
from datetime import datetime, timedelta
from typing import List
import requests
from jwt.algorithms import RSAAlgorithm
import jwt
from .claims_identity import ClaimsIdentity
from .verify_options import VerifyOptions
from .endorsements_validator import EndorsementsValidator
class JwtTokenExtractor:
metadataCache = {}
def __init__(
self,
validation_params: VerifyOptions,
metadata_url: str,
allowed_algorithms: list,
):
self.validation_parameters = validation_params
self.validation_parameters.algorithms = allowed_algorithms
self.open_id_metadata = JwtTokenExtractor.get_open_id_metadata(metadata_url)
@staticmethod
def get_open_id_metadata(metadata_url: str):
metadata = JwtTokenExtractor.metadataCache.get(metadata_url, None)
if metadata is None:
metadata = _OpenIdMetadata(metadata_url)
JwtTokenExtractor.metadataCache.setdefault(metadata_url, metadata)
return metadata
async def get_identity_from_auth_header(
self, auth_header: str, channel_id: str, required_endorsements: List[str] = None
) -> ClaimsIdentity:
if not auth_header:
return None
parts = auth_header.split(" ")
if len(parts) == 2:
return await self.get_identity(
parts[0], parts[1], channel_id, required_endorsements
)
return None
async def get_identity(
self,
schema: str,
parameter: str,
channel_id: str,
required_endorsements: List[str] = None,
) -> ClaimsIdentity:
# No header in correct scheme or no token
if schema != "Bearer" or not parameter:
return None
# Issuer isn't allowed? No need to check signature
if not self._has_allowed_issuer(parameter):
return None
try:
return await self._validate_token(
parameter, channel_id, required_endorsements
)
except Exception as error:
raise error
def _has_allowed_issuer(self, jwt_token: str) -> bool:
decoded = jwt.decode(jwt_token, options={"verify_signature": False})
issuer = decoded.get("iss", None)
if issuer in self.validation_parameters.issuer:
return True
return issuer == self.validation_parameters.issuer
async def _validate_token(
self, jwt_token: str, channel_id: str, required_endorsements: List[str] = None
) -> ClaimsIdentity:
required_endorsements = required_endorsements or []
headers = jwt.get_unverified_header(jwt_token)
# Update the signing tokens from the last refresh
key_id = headers.get("kid", None)
metadata = await self.open_id_metadata.get(key_id)
if key_id and metadata.endorsements:
# Verify that channelId is included in endorsements
if not EndorsementsValidator.validate(channel_id, metadata.endorsements):
raise Exception("Could not validate endorsement key")
# Verify that additional endorsements are satisfied.
# If no additional endorsements are expected, the requirement is satisfied as well
for endorsement in required_endorsements:
if not EndorsementsValidator.validate(
endorsement, metadata.endorsements
):
raise Exception("Could not validate endorsement key")
if headers.get("alg", None) not in self.validation_parameters.algorithms:
raise Exception("Token signing algorithm not in allowed list")
options = {
"verify_aud": False,
"verify_exp": not self.validation_parameters.ignore_expiration,
}
decoded_payload = jwt.decode(
jwt_token,
metadata.public_key,
leeway=self.validation_parameters.clock_tolerance,
options=options,
algorithms=["RS256"],
)
claims = ClaimsIdentity(decoded_payload, True)
return claims
class _OpenIdMetadata:
def __init__(self, url):
self.url = url
self.keys = []
self.last_updated = datetime.min
async def get(self, key_id: str):
# If keys are more than 1 day old, refresh them
if self.last_updated < (datetime.now() - timedelta(days=1)):
await self._refresh()
key = self._find(key_id)
if not key and self.last_updated < (datetime.now() - timedelta(hours=1)):
# Refresh the cache if a key is not found (max once per hour)
await self._refresh()
key = self._find(key_id)
return key
async def _refresh(self):
response = requests.get(self.url)
response.raise_for_status()
keys_url = response.json()["jwks_uri"]
response_keys = requests.get(keys_url)
response_keys.raise_for_status()
self.last_updated = datetime.now()
self.keys = response_keys.json()["keys"]
def _find(self, key_id: str):
if not self.keys:
return None
key = [x for x in self.keys if x["kid"] == key_id][0]
public_key = RSAAlgorithm.from_jwk(json.dumps(key))
endorsements = key.get("endorsements", [])
return _OpenIdConfig(public_key, endorsements)
class _OpenIdConfig:
def __init__(self, public_key, endorsements):
self.public_key = public_key
self.endorsements = endorsements
|
botbuilder-python/libraries/botframework-connector/botframework/connector/auth/jwt_token_extractor.py/0
|
{
"file_path": "botbuilder-python/libraries/botframework-connector/botframework/connector/auth/jwt_token_extractor.py",
"repo_id": "botbuilder-python",
"token_count": 2357
}
| 470 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from typing import Any, Dict
class HttpRequest:
def __init__(
self,
*,
request_uri: str = None,
content: Any = None,
headers: Dict[str, str] = None
) -> None:
self.request_uri = request_uri
self.content = content
self.headers = headers
|
botbuilder-python/libraries/botframework-connector/botframework/connector/http_request.py/0
|
{
"file_path": "botbuilder-python/libraries/botframework-connector/botframework/connector/http_request.py",
"repo_id": "botbuilder-python",
"token_count": 166
}
| 471 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from msrest.authentication import BasicTokenAuthentication, Authentication
class MicrosoftTokenAuthenticationStub(Authentication):
def __init__(self, access_token):
self.access_token = access_token
def signed_session(self, session=None):
basic_authentication = BasicTokenAuthentication(
{"access_token": self.access_token}
)
return session or basic_authentication.signed_session()
|
botbuilder-python/libraries/botframework-connector/tests/authentication_stub.py/0
|
{
"file_path": "botbuilder-python/libraries/botframework-connector/tests/authentication_stub.py",
"repo_id": "botbuilder-python",
"token_count": 166
}
| 472 |
interactions:
- request:
body: '{"type": "message", "channelId": "slack", "from": {"id": "B21UTEF8S:T03CWQ0QB"},
"recipient": {"id": "U19KH8EHJ:T03CWQ0QB"}, "textFormat": "markdown", "attachmentLayout":
"list", "text": "Test Activity"}'
headers:
Accept: [application/json]
Accept-Encoding: ['gzip, deflate']
Connection: [keep-alive]
Content-Length: ['203']
Content-Type: [application/json; charset=utf-8]
User-Agent: [python/3.6.2 (Windows-10-10.0.16299-SP0) requests/2.18.1 msrest/0.4.23
azure-botframework-connector/3.0]
method: POST
uri: https://slack.botframework.com/v3/conversations/B21UTEF8S%3AT03CWQ0QB%3AD2369CT7C/activities
response:
body: {string: "{\r\n \"id\": \"1514570168.000161\"\r\n}"}
headers:
cache-control: [no-cache]
content-length: ['33']
content-type: [application/json; charset=utf-8]
date: ['Fri, 29 Dec 2017 17:56:08 GMT']
expires: ['-1']
pragma: [no-cache]
request-context: ['appId=cid-v1:6814484e-c0d5-40ea-9dba-74ff29ca4f62']
server: [Microsoft-IIS/10.0]
strict-transport-security: [max-age=31536000]
vary: [Accept-Encoding]
x-powered-by: [ASP.NET]
status: {code: 200, message: OK}
- request:
body: null
headers:
Accept: [application/json]
Accept-Encoding: ['gzip, deflate']
Connection: [keep-alive]
Content-Type: [application/json; charset=utf-8]
User-Agent: [python/3.6.2 (Windows-10-10.0.16299-SP0) requests/2.18.1 msrest/0.4.23
azure-botframework-connector/3.0]
method: GET
uri: https://slack.botframework.com/v3/conversations/INVALID_ID/activities/1514570168.000161/members
response:
body: {string: "{\r\n \"error\": {\r\n \"code\": \"ServiceError\",\r\n \
\ \"message\": \"Invalid ConversationId: INVALID_ID\"\r\n }\r\n}"}
headers:
cache-control: [no-cache]
content-length: ['105']
content-type: [application/json; charset=utf-8]
date: ['Fri, 29 Dec 2017 17:56:09 GMT']
expires: ['-1']
pragma: [no-cache]
request-context: ['appId=cid-v1:6814484e-c0d5-40ea-9dba-74ff29ca4f62']
server: [Microsoft-IIS/10.0]
strict-transport-security: [max-age=31536000]
x-powered-by: [ASP.NET]
status: {code: 400, message: Bad Request}
version: 1
|
botbuilder-python/libraries/botframework-connector/tests/recordings/test_conversations_get_activity_members_invalid_conversation_id_fails.yaml/0
|
{
"file_path": "botbuilder-python/libraries/botframework-connector/tests/recordings/test_conversations_get_activity_members_invalid_conversation_id_fails.yaml",
"repo_id": "botbuilder-python",
"token_count": 1104
}
| 473 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import os
import base64
import asyncio
import pytest
import msrest
from botbuilder.schema import AttachmentData, ErrorResponseException
from botframework.connector.aio import ConnectorClient
from botframework.connector.auth import MicrosoftAppCredentials
from authentication_stub import MicrosoftTokenAuthenticationStub
SERVICE_URL = "https://slack.botframework.com"
CHANNEL_ID = "slack"
BOT_NAME = "botbuilder-pc-bot"
BOT_ID = "B21UTEF8S:T03CWQ0QB"
RECIPIENT_ID = "U19KH8EHJ:T03CWQ0QB"
CONVERSATION_ID = "B21UTEF8S:T03CWQ0QB:D2369CT7C"
async def get_auth_token():
try:
# pylint: disable=import-outside-toplevel
from .app_creds_real import MICROSOFT_APP_ID, MICROSOFT_APP_PASSWORD
# Define a "app_creds_real.py" file with your bot credentials as follows:
# MICROSOFT_APP_ID = '...'
# MICROSOFT_APP_PASSWORD = '...'
return MicrosoftAppCredentials(
MICROSOFT_APP_ID, MICROSOFT_APP_PASSWORD
).get_access_token()
except ImportError:
return "STUB_ACCESS_TOKEN"
def read_base64(path_to_file):
path_to_current_file = os.path.realpath(__file__)
current_directory = os.path.dirname(path_to_current_file)
path_to_file = os.path.join(current_directory, "resources", path_to_file)
with open(path_to_file, "rb") as image_file:
encoded_string = base64.b64encode(image_file.read())
return encoded_string
async def return_sum(attachment_stream):
counter = 0
async for _ in attachment_stream:
counter += len(_)
return counter
LOOP = asyncio.get_event_loop()
AUTH_TOKEN = LOOP.run_until_complete(get_auth_token())
class AttachmentsTest:
def __init__(self):
super(AttachmentsTest, self).__init__()
self.loop = asyncio.get_event_loop()
@property
def credentials(self):
return MicrosoftTokenAuthenticationStub(AUTH_TOKEN)
def test_attachments_upload_and_get_attachment(self):
attachment = AttachmentData(
type="image/png",
name="Bot.png",
original_base64=read_base64("bot.png"),
thumbnail_base64=read_base64("bot_icon.png"),
)
connector = ConnectorClient(self.credentials, base_url=SERVICE_URL)
response = self.loop.run_until_complete(
connector.conversations.upload_attachment(CONVERSATION_ID, attachment)
)
attachment_id = response.id
attachment_info = self.loop.run_until_complete(
connector.attachments.get_attachment_info(attachment_id)
)
assert attachment_info is not None
assert attachment_info.name == "Bot.png"
assert attachment_info.type == "image/png"
assert len(attachment_info.views) == 2
def test_attachments_get_info_invalid_attachment_id_fails(self):
with pytest.raises(ErrorResponseException) as excinfo:
connector = ConnectorClient(self.credentials, base_url=SERVICE_URL)
self.loop.run_until_complete(
connector.attachments.get_attachment_info("bt13796-GJS4yaxDLI")
)
assert "Not Found" in str(excinfo.value)
def test_attachments_get_attachment_view(self):
original = read_base64("bot.png")
attachment = AttachmentData(
type="image/png",
name="Bot.png",
original_base64=original,
thumbnail_base64=read_base64("bot_icon.png"),
)
connector = ConnectorClient(self.credentials, base_url=SERVICE_URL)
response = self.loop.run_until_complete(
connector.conversations.upload_attachment(CONVERSATION_ID, attachment)
)
attachment_id = response.id
attachment_stream = self.loop.run_until_complete(
connector.attachments.get_attachment(attachment_id, "original")
)
assert len(original) == self.loop.run_until_complete(
return_sum(attachment_stream)
)
def test_attachments_get_attachment_view_with_invalid_attachment_id_fails(self):
with pytest.raises(msrest.exceptions.HttpOperationError) as excinfo:
connector = ConnectorClient(self.credentials, base_url=SERVICE_URL)
self.loop.run_until_complete(
connector.attachments.get_attachment("bt13796-GJS4yaxDLI", "original")
)
assert "Not Found" in str(excinfo.value)
def test_attachments_get_attachment_view_with_invalid_view_id_fails(self):
original = read_base64("bot.png")
attachment = AttachmentData(
type="image/png",
name="Bot.png",
original_base64=original,
thumbnail_base64=read_base64("bot_icon.png"),
)
with pytest.raises(msrest.exceptions.HttpOperationError) as excinfo:
connector = ConnectorClient(self.credentials, base_url=SERVICE_URL)
response = self.loop.run_until_complete(
connector.conversations.upload_attachment(CONVERSATION_ID, attachment)
)
attachment_id = response.id
self.loop.run_until_complete(
connector.attachments.get_attachment(attachment_id, "invalid")
)
assert "not found" in str(excinfo.value)
|
botbuilder-python/libraries/botframework-connector/tests/test_attachments_async.py/0
|
{
"file_path": "botbuilder-python/libraries/botframework-connector/tests/test_attachments_async.py",
"repo_id": "botbuilder-python",
"token_count": 2300
}
| 474 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from .content_stream import ContentStream
from .header_serializer import HeaderSerializer
from .payload_assembler_manager import PayloadAssemblerManager
from .request_manager import RequestManager
from .response_message_stream import ResponseMessageStream
from .send_operations import SendOperations
from .stream_manager import StreamManager
__all__ = [
"ContentStream",
"PayloadAssemblerManager",
"RequestManager",
"ResponseMessageStream",
"HeaderSerializer",
"SendOperations",
"StreamManager",
]
|
botbuilder-python/libraries/botframework-streaming/botframework/streaming/payloads/__init__.py/0
|
{
"file_path": "botbuilder-python/libraries/botframework-streaming/botframework/streaming/payloads/__init__.py",
"repo_id": "botbuilder-python",
"token_count": 172
}
| 475 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from .header import Header
class PayloadTypes:
REQUEST = "A"
RESPONSE = "B"
STREAM = "S"
CANCEL_ALL = "X"
CANCEL_STREAM = "C"
@staticmethod
def is_stream(header: Header) -> bool:
return header.type == PayloadTypes.STREAM
|
botbuilder-python/libraries/botframework-streaming/botframework/streaming/payloads/models/payload_types.py/0
|
{
"file_path": "botbuilder-python/libraries/botframework-streaming/botframework/streaming/payloads/models/payload_types.py",
"repo_id": "botbuilder-python",
"token_count": 135
}
| 476 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from .disconnected_event_args import DisconnectedEventArgs
from .streaming_transport_service import StreamingTransportService
from .transport_base import TransportBase
from .transport_constants import TransportConstants
from .transport_receiver_base import TransportReceiverBase
from .transport_sender_base import TransportSenderBase
__all__ = [
"DisconnectedEventArgs",
"StreamingTransportService",
"TransportBase",
"TransportConstants",
"TransportReceiverBase",
"TransportSenderBase",
]
|
botbuilder-python/libraries/botframework-streaming/botframework/streaming/transport/__init__.py/0
|
{
"file_path": "botbuilder-python/libraries/botframework-streaming/botframework/streaming/transport/__init__.py",
"repo_id": "botbuilder-python",
"token_count": 174
}
| 477 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from uuid import uuid4
import aiounittest
from botframework.streaming.payloads import ContentStream
from botframework.streaming.payloads.assemblers import PayloadStreamAssembler
class TestResponses(aiounittest.AsyncTestCase):
async def test_content_stream_ctor_none_assembler_throws(self):
with self.assertRaises(TypeError):
ContentStream(uuid4(), None)
async def test_content_stream_id(self):
test_id = uuid4()
test_assembler = PayloadStreamAssembler(None, test_id)
sut = ContentStream(test_id, test_assembler)
self.assertEqual(test_id, sut.identifier)
async def test_content_stream_type(self):
test_id = uuid4()
test_assembler = PayloadStreamAssembler(None, test_id)
sut = ContentStream(test_id, test_assembler)
test_type = "foo/bar"
sut.content_type = test_type
self.assertEqual(test_type, sut.content_type)
sut.cancel()
|
botbuilder-python/libraries/botframework-streaming/tests/test_content_stream.py/0
|
{
"file_path": "botbuilder-python/libraries/botframework-streaming/tests/test_content_stream.py",
"repo_id": "botbuilder-python",
"token_count": 412
}
| 478 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from botbuilder.core import StatePropertyAccessor, TurnContext
from botbuilder.dialogs import Dialog, DialogSet, DialogTurnStatus
class DialogHelper:
@staticmethod
async def run_dialog(
dialog: Dialog, turn_context: TurnContext, accessor: StatePropertyAccessor
):
dialog_set = DialogSet(accessor)
dialog_set.add(dialog)
dialog_context = await dialog_set.create_context(turn_context)
results = await dialog_context.continue_dialog()
if results.status == DialogTurnStatus.Empty:
await dialog_context.begin_dialog(dialog.id)
|
botbuilder-python/tests/experimental/sso/child/helpers/dialog_helper.py/0
|
{
"file_path": "botbuilder-python/tests/experimental/sso/child/helpers/dialog_helper.py",
"repo_id": "botbuilder-python",
"token_count": 240
}
| 479 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
FROM python:3.7-slim as pkg_holder
ARG EXTRA_INDEX_URL
RUN pip config set global.extra-index-url "${EXTRA_INDEX_URL}"
COPY requirements.txt .
RUN pip download -r requirements.txt -d packages
FROM python:3.7-slim
ENV VIRTUAL_ENV=/opt/venv
RUN python3.7 -m venv $VIRTUAL_ENV
ENV PATH="$VIRTUAL_ENV/bin:$PATH"
COPY . /app
WORKDIR /app
COPY --from=pkg_holder packages packages
RUN pip install -r requirements.txt --no-index --find-links=packages && rm -rf packages
ENTRYPOINT ["python"]
EXPOSE 3978
CMD ["runserver.py"]
|
botbuilder-python/tests/functional-tests/functionaltestbot/Dockfile/0
|
{
"file_path": "botbuilder-python/tests/functional-tests/functionaltestbot/Dockfile",
"repo_id": "botbuilder-python",
"token_count": 232
}
| 480 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import os
from setuptools import setup
REQUIRES = [
"botbuilder-core>=4.9.0",
"flask==2.2.5",
]
root = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(root, "functionaltestbot", "about.py")) as f:
package_info = {}
info = f.read()
exec(info, package_info)
setup(
name=package_info["__title__"],
version=package_info["__version__"],
url=package_info["__uri__"],
author=package_info["__author__"],
description=package_info["__description__"],
keywords="botframework azure botbuilder",
long_description=package_info["__summary__"],
license=package_info["__license__"],
packages=["functionaltestbot"],
install_requires=REQUIRES,
dependency_links=["https://github.com/pytorch/pytorch"],
include_package_data=True,
classifiers=[
"Programming Language :: Python :: 3.6",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Development Status :: 3 - Alpha",
"Topic :: Scientific/Engineering :: Artificial Intelligence",
],
)
|
botbuilder-python/tests/functional-tests/functionaltestbot/setup.py/0
|
{
"file_path": "botbuilder-python/tests/functional-tests/functionaltestbot/setup.py",
"repo_id": "botbuilder-python",
"token_count": 450
}
| 481 |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from .echo_bot import EchoBot
__all__ = ["EchoBot"]
|
botbuilder-python/tests/skills/skills-prototypes/simple-bot-to-bot/simple-child-bot/bots/__init__.py/0
|
{
"file_path": "botbuilder-python/tests/skills/skills-prototypes/simple-bot-to-bot/simple-child-bot/bots/__init__.py",
"repo_id": "botbuilder-python",
"token_count": 42
}
| 482 |
Copyright (c) 2019 - Present, Microsoft Corporation,
with Reserved Font Name Cascadia Code.
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
|
cascadia-code/LICENSE/0
|
{
"file_path": "cascadia-code/LICENSE",
"repo_id": "cascadia-code",
"token_count": 1043
}
| 483 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="Acircumflextilde" format="2">
<advance width="1200"/>
<unicode hex="1EAA"/>
<outline>
<component base="A"/>
<component base="circumflexcomb.case"/>
<component base="tildecomb.case" xOffset="10" yOffset="380"/>
</outline>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/A_circumflextilde.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/A_circumflextilde.glif",
"repo_id": "cascadia-code",
"token_count": 120
}
| 484 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="Ecaron" format="2">
<advance width="1200"/>
<unicode hex="011A"/>
<outline>
<component base="E"/>
<component base="caroncomb.case" xOffset="30"/>
</outline>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/E_caron.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/E_caron.glif",
"repo_id": "cascadia-code",
"token_count": 95
}
| 485 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="Em-cy" format="2">
<advance width="1200"/>
<unicode hex="041C"/>
<outline>
<component base="M"/>
</outline>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/E_m-cy.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/E_m-cy.glif",
"repo_id": "cascadia-code",
"token_count": 76
}
| 486 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="Eth" format="2">
<advance width="1200"/>
<unicode hex="00D0"/>
<outline>
<contour>
<point x="12" y="585" type="line"/>
<point x="651" y="585" type="line"/>
<point x="651" y="829" type="line"/>
<point x="12" y="829" type="line"/>
</contour>
<component base="D"/>
</outline>
<lib>
<dict>
<key>com.schriftgestaltung.Glyphs.ComponentInfo</key>
<array>
<dict>
<key>alignment</key>
<integer>-1</integer>
<key>index</key>
<integer>0</integer>
<key>name</key>
<string>D</string>
</dict>
</array>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/E_th.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/E_th.glif",
"repo_id": "cascadia-code",
"token_count": 368
}
| 487 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="I" format="2">
<advance width="1200"/>
<unicode hex="0049"/>
<anchor x="600" y="0" name="bottom"/>
<anchor x="600" y="10" name="ogonek"/>
<anchor x="600" y="1420" name="top"/>
<anchor x="20" y="1420" name="topleft"/>
<outline>
<contour>
<point x="467" y="0" type="line"/>
<point x="731" y="0" type="line"/>
<point x="731" y="1420" type="line"/>
<point x="467" y="1420" type="line"/>
</contour>
<contour>
<point x="151" y="0" type="line"/>
<point x="1049" y="0" type="line"/>
<point x="1049" y="238" type="line"/>
<point x="151" y="238" type="line"/>
</contour>
<contour>
<point x="151" y="1183" type="line"/>
<point x="1049" y="1183" type="line"/>
<point x="1049" y="1420" type="line"/>
<point x="151" y="1420" type="line"/>
</contour>
</outline>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/I_.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/I_.glif",
"repo_id": "cascadia-code",
"token_count": 438
}
| 488 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="Iigrave-cy" format="2">
<advance width="1200"/>
<unicode hex="040D"/>
<outline>
<component base="Ii-cy"/>
<component base="gravecomb.case" xOffset="-80"/>
</outline>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/I_igrave-cy.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/I_igrave-cy.glif",
"repo_id": "cascadia-code",
"token_count": 100
}
| 489 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="Je-cy" format="2">
<advance width="1200"/>
<unicode hex="0408"/>
<outline>
<component base="J"/>
</outline>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/J_e-cy.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/J_e-cy.glif",
"repo_id": "cascadia-code",
"token_count": 76
}
| 490 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="Lambda" format="2">
<advance width="1200"/>
<unicode hex="039B"/>
<outline>
<component base="El-cy.loclBGR"/>
</outline>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/L_ambda.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/L_ambda.glif",
"repo_id": "cascadia-code",
"token_count": 84
}
| 491 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="Nacute" format="2">
<advance width="1200"/>
<unicode hex="0143"/>
<outline>
<component base="N"/>
<component base="acutecomb.case" xOffset="79"/>
</outline>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/N_acute.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/N_acute.glif",
"repo_id": "cascadia-code",
"token_count": 96
}
| 492 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="Obreve" format="2">
<advance width="1200"/>
<unicode hex="014E"/>
<outline>
<component base="O"/>
<component base="brevecomb.case"/>
</outline>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/O_breve.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/O_breve.glif",
"repo_id": "cascadia-code",
"token_count": 90
}
| 493 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="Ohornhookabove" format="2">
<advance width="1200"/>
<unicode hex="1EDE"/>
<outline>
<component base="Ohorn"/>
<component base="hookabovecomb.case"/>
</outline>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/O_hornhookabove.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/O_hornhookabove.glif",
"repo_id": "cascadia-code",
"token_count": 93
}
| 494 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="Uacute" format="2">
<advance width="1200"/>
<unicode hex="00DA"/>
<outline>
<component base="U"/>
<component base="acutecomb.case" xOffset="79"/>
</outline>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/U_acute.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/U_acute.glif",
"repo_id": "cascadia-code",
"token_count": 96
}
| 495 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="Wacute" format="2">
<advance width="1200"/>
<unicode hex="1E82"/>
<outline>
<component base="W"/>
<component base="acutecomb.case" xOffset="79"/>
</outline>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/W_acute.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/W_acute.glif",
"repo_id": "cascadia-code",
"token_count": 97
}
| 496 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="Yi-cy" format="2">
<advance width="1200"/>
<unicode hex="0407"/>
<outline>
<component base="I"/>
<component base="dieresiscomb.case"/>
</outline>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/Y_i-cy.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/Y_i-cy.glif",
"repo_id": "cascadia-code",
"token_count": 92
}
| 497 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="_alefHamzabelow-ar.fina.rlig" format="2">
<anchor x="0" y="0" name="_overlap"/>
<anchor x="359" y="-492" name="bottom"/>
<anchor x="294" y="1317" name="top"/>
<outline>
<component base="_alef-ar.fina.rlig"/>
<component base="hamzabelow-ar" xOffset="-262" yOffset="-26"/>
</outline>
<lib>
<dict>
<key>com.schriftgestaltung.Glyphs.ComponentInfo</key>
<array>
<dict>
<key>alignment</key>
<integer>-1</integer>
<key>index</key>
<integer>0</integer>
<key>name</key>
<string>_alef-ar.fina.rlig</string>
</dict>
<dict>
<key>alignment</key>
<integer>1</integer>
<key>anchor</key>
<string>bottom.dot</string>
<key>index</key>
<integer>1</integer>
<key>name</key>
<string>hamzabelow-ar</string>
</dict>
</array>
<key>public.markColor</key>
<string>0.98,0.36,0.67,1</string>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/_alefH_amzabelow-ar.fina.rlig.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/_alefH_amzabelow-ar.fina.rlig.glif",
"repo_id": "cascadia-code",
"token_count": 574
}
| 498 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="_fatha-ar" format="2">
<advance width="1200"/>
<outline>
<contour>
<point x="330" y="1241" type="line"/>
<point x="848" y="1385" type="line"/>
<point x="854" y="1548" type="line"/>
<point x="336" y="1404" type="line"/>
</contour>
</outline>
<lib>
<dict>
<key>public.markColor</key>
<string>0.98,0.36,0.67,1</string>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/_fatha-ar.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/_fatha-ar.glif",
"repo_id": "cascadia-code",
"token_count": 225
}
| 499 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="_twodotshorizontal-ar" format="2">
<advance width="1200"/>
<outline>
<component base="_dot-ar" xScale="0.96" yScale="0.96" xOffset="149" yOffset="20"/>
<component base="_dot-ar" xScale="0.96" yScale="0.96" xOffset="-101" yOffset="20"/>
</outline>
<lib>
<dict>
<key>com.schriftgestaltung.Glyphs.ComponentInfo</key>
<array>
<dict>
<key>alignment</key>
<integer>-1</integer>
<key>index</key>
<integer>0</integer>
<key>name</key>
<string>_dot-ar</string>
</dict>
<dict>
<key>alignment</key>
<integer>-1</integer>
<key>index</key>
<integer>1</integer>
<key>name</key>
<string>_dot-ar</string>
</dict>
</array>
<key>public.markColor</key>
<string>0.98,0.36,0.67,1</string>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/_twodotshorizontal-ar.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/_twodotshorizontal-ar.glif",
"repo_id": "cascadia-code",
"token_count": 505
}
| 500 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="abrevetilde" format="2">
<advance width="1200"/>
<unicode hex="1EB5"/>
<outline>
<component base="a"/>
<component base="brevecomb" xOffset="-20"/>
<component base="tildecomb" xOffset="-10" yOffset="480"/>
</outline>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/abrevetilde.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/abrevetilde.glif",
"repo_id": "cascadia-code",
"token_count": 119
}
| 501 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="adieresis" format="2">
<advance width="1200"/>
<unicode hex="00E4"/>
<outline>
<component base="a"/>
<component base="dieresiscomb" xOffset="-18"/>
</outline>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/adieresis.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/adieresis.glif",
"repo_id": "cascadia-code",
"token_count": 97
}
| 502 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="ainThreedots-ar.medi" format="2">
<advance width="1200"/>
<outline>
<component base="ain-ar.medi"/>
<component base="threedotsupabove-ar" xOffset="10" yOffset="273"/>
</outline>
<lib>
<dict>
<key>public.markColor</key>
<string>0.98,0.36,0.67,1</string>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/ainT_hreedots-ar.medi.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/ainT_hreedots-ar.medi.glif",
"repo_id": "cascadia-code",
"token_count": 166
}
| 503 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="alefHamzabelow-ar" format="2">
<advance width="1200"/>
<unicode hex="0625"/>
<anchor x="626" y="-493" name="bottom"/>
<outline>
<component base="alef-ar"/>
<component base="hamzabelow-ar" xOffset="7" yOffset="-26"/>
</outline>
<lib>
<dict>
<key>com.schriftgestaltung.Glyphs.ComponentInfo</key>
<array>
<dict>
<key>anchor</key>
<string>bottom.dot</string>
<key>index</key>
<integer>1</integer>
<key>name</key>
<string>hamzabelow-ar</string>
</dict>
</array>
<key>public.markColor</key>
<string>0.98,0.36,0.67,1</string>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/alefH_amzabelow-ar.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/alefH_amzabelow-ar.glif",
"repo_id": "cascadia-code",
"token_count": 370
}
| 504 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="alefThreeabove-ar.fina.rlig" format="2">
<anchor x="0" y="0" name="_overlap"/>
<anchor x="283" y="-141" name="bottom"/>
<anchor x="7" y="1490" name="top"/>
<outline>
<component base="three-persian.small01" xOffset="-600" yOffset="-151"/>
<component base="alef-ar.fina.short.rlig"/>
</outline>
<lib>
<dict>
<key>com.schriftgestaltung.Glyphs.ComponentInfo</key>
<array>
<dict>
<key>alignment</key>
<integer>-1</integer>
<key>index</key>
<integer>0</integer>
<key>name</key>
<string>three-persian.small01</string>
</dict>
</array>
<key>public.markColor</key>
<string>0.98,0.36,0.67,1</string>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/alefT_hreeabove-ar.fina.rlig.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/alefT_hreeabove-ar.fina.rlig.glif",
"repo_id": "cascadia-code",
"token_count": 402
}
| 505 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="alefWavyhamzabelow-ar.fina.rlig" format="2">
<anchor x="0" y="0" name="_overlap"/>
<anchor x="271" y="-491" name="bottom"/>
<anchor x="274" y="1310" name="top"/>
<outline>
<component base="alef-ar.fina.rlig"/>
<component base="wavyhamzabelow-ar" xOffset="-312" yOffset="-26"/>
</outline>
<lib>
<dict>
<key>com.schriftgestaltung.Glyphs.ComponentInfo</key>
<array>
<dict>
<key>alignment</key>
<integer>-1</integer>
<key>index</key>
<integer>0</integer>
<key>name</key>
<string>alef-ar.fina.rlig</string>
</dict>
<dict>
<key>anchor</key>
<string>bottom.dot</string>
<key>index</key>
<integer>1</integer>
<key>name</key>
<string>wavyhamzabelow-ar</string>
</dict>
</array>
<key>public.markColor</key>
<string>0.98,0.36,0.67,1</string>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/alefW_avyhamzabelow-ar.fina.rlig.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/alefW_avyhamzabelow-ar.fina.rlig.glif",
"repo_id": "cascadia-code",
"token_count": 542
}
| 506 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="baht" format="2">
<advance width="1200"/>
<unicode hex="0E3F"/>
<outline>
<contour>
<point x="457" y="-320" type="line"/>
<point x="710" y="-320" type="line"/>
<point x="710" y="1740" type="line"/>
<point x="457" y="1740" type="line"/>
</contour>
<component base="B"/>
</outline>
<lib>
<dict>
<key>com.schriftgestaltung.Glyphs.ComponentInfo</key>
<array>
<dict>
<key>alignment</key>
<integer>-1</integer>
<key>index</key>
<integer>0</integer>
<key>name</key>
<string>B</string>
</dict>
</array>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/baht.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/baht.glif",
"repo_id": "cascadia-code",
"token_count": 372
}
| 507 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="bar_equal_start.seq" format="2">
<advance width="1200"/>
<outline>
<contour>
<point x="586" y="835" type="line"/>
<point x="1220" y="835" type="line"/>
<point x="1220" y="1085" type="line"/>
<point x="585" y="1085" type="line"/>
</contour>
<contour>
<point x="586" y="333" type="line"/>
<point x="1220" y="333" type="line"/>
<point x="1220" y="583" type="line"/>
<point x="586" y="583" type="line"/>
</contour>
<component base="bar"/>
</outline>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/bar_equal_start.seq.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/bar_equal_start.seq.glif",
"repo_id": "cascadia-code",
"token_count": 270
}
| 508 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="beh-ar.fina.alt" format="2">
<advance width="1200"/>
<outline>
<component base="behDotless-ar.fina.alt"/>
<component base="dotbelow-ar" xOffset="-710" yOffset="-24"/>
</outline>
<lib>
<dict>
<key>com.schriftgestaltung.Glyphs.ComponentInfo</key>
<array>
<dict>
<key>anchor</key>
<string>bottom.dot</string>
<key>index</key>
<integer>1</integer>
<key>name</key>
<string>dotbelow-ar</string>
</dict>
</array>
<key>public.markColor</key>
<string>0.98,0.36,0.67,1</string>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/beh-ar.fina.alt.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/beh-ar.fina.alt.glif",
"repo_id": "cascadia-code",
"token_count": 346
}
| 509 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="behMeemabove-ar" format="2">
<advance width="1200"/>
<unicode hex="08B6"/>
<outline>
<component base="behDotless-ar"/>
<component base="dotbelow-ar" xOffset="-20" yOffset="-24"/>
<component base="meemStopabove-ar" xOffset="-26" yOffset="-369"/>
</outline>
<lib>
<dict>
<key>com.schriftgestaltung.Glyphs.ComponentInfo</key>
<array>
<dict>
<key>anchor</key>
<string>bottom.dot</string>
<key>index</key>
<integer>1</integer>
<key>name</key>
<string>dotbelow-ar</string>
</dict>
<dict>
<key>anchor</key>
<string>top.dot</string>
<key>index</key>
<integer>2</integer>
<key>name</key>
<string>meemStopabove-ar</string>
</dict>
</array>
<key>public.markColor</key>
<string>0.98,0.36,0.67,1</string>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/behM_eemabove-ar.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/behM_eemabove-ar.glif",
"repo_id": "cascadia-code",
"token_count": 509
}
| 510 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="behVabove-ar.alt" format="2">
<advance width="1200"/>
<outline>
<component base="behDotless-ar.alt"/>
<component base="vabove-ar" xOffset="-610" yOffset="93"/>
</outline>
<lib>
<dict>
<key>com.schriftgestaltung.Glyphs.ComponentInfo</key>
<array>
<dict>
<key>anchor</key>
<string>top.dot</string>
<key>index</key>
<integer>1</integer>
<key>name</key>
<string>vabove-ar</string>
</dict>
</array>
<key>public.markColor</key>
<string>0.98,0.36,0.67,1</string>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/behV_above-ar.alt.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/behV_above-ar.alt.glif",
"repo_id": "cascadia-code",
"token_count": 341
}
| 511 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="behVinvertedbelow-ar.fina" format="2">
<advance width="1200"/>
<outline>
<component base="behDotless-ar.fina"/>
<component base="_vinvertedbelow-ar" xOffset="-20" yOffset="-24"/>
</outline>
<lib>
<dict>
<key>public.markColor</key>
<string>0.98,0.36,0.67,1</string>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/behV_invertedbelow-ar.fina.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/behV_invertedbelow-ar.fina.glif",
"repo_id": "cascadia-code",
"token_count": 173
}
| 512 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="behhamzaabove-ar.init" format="2">
<advance width="1200"/>
<outline>
<component base="beh-ar.init"/>
<component base="hamzaabove-ar" xOffset="215" yOffset="-237"/>
</outline>
<lib>
<dict>
<key>public.markColor</key>
<string>0.98,0.36,0.67,1</string>
</dict>
</lib>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/behhamzaabove-ar.init.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/behhamzaabove-ar.init.glif",
"repo_id": "cascadia-code",
"token_count": 165
}
| 513 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="blackMediumDownTriangleCentred" format="2">
<advance width="1200"/>
<unicode hex="2BC6"/>
<note>
uni2BC6
</note>
<outline>
<contour>
<point x="600" y="466" type="line"/>
<point x="938" y="1040" type="line"/>
<point x="262" y="1040" type="line"/>
</contour>
</outline>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/blackM_ediumD_ownT_riangleC_entred.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/blackM_ediumD_ownT_riangleC_entred.glif",
"repo_id": "cascadia-code",
"token_count": 164
}
| 514 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="blockCircle-UC" format="2">
<advance width="1200"/>
<unicode hex="1FBE8"/>
<outline>
<contour>
<point x="0" y="2226" type="line" smooth="yes"/>
<point x="0" y="1549"/>
<point x="300" y="873"/>
<point x="600" y="873" type="curve" smooth="yes"/>
<point x="900" y="873"/>
<point x="1200" y="1549"/>
<point x="1200" y="2226" type="curve" smooth="yes"/>
</contour>
</outline>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/blockC_ircle-UC.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/blockC_ircle-UC.glif",
"repo_id": "cascadia-code",
"token_count": 231
}
| 515 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="blockDiagonal-1FB43" format="2">
<advance width="1200"/>
<unicode hex="1FB43"/>
<outline>
<contour>
<point x="0" y="422" type="line"/>
<point x="600" y="2226" type="line"/>
<point x="1200" y="2226" type="line"/>
<point x="1200" y="-480" type="line"/>
<point x="0" y="-480" type="line"/>
</contour>
</outline>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/blockD_iagonal-1FB43.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/blockD_iagonal-1FB43.glif",
"repo_id": "cascadia-code",
"token_count": 191
}
| 516 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="blockDiagonal-1FB4B" format="2">
<advance width="1200"/>
<unicode hex="1FB4B"/>
<outline>
<contour>
<point x="600" y="-480" type="line"/>
<point x="1200" y="2226" type="line"/>
<point x="1200" y="-480" type="line"/>
</contour>
</outline>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/blockD_iagonal-1FB4B.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/blockD_iagonal-1FB4B.glif",
"repo_id": "cascadia-code",
"token_count": 152
}
| 517 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="blockOctant-1234678" format="2">
<advance width="1200"/>
<unicode hex="1CDDA"/>
<outline>
<contour>
<point x="0" y="2226" type="line"/>
<point x="1200" y="2226" type="line"/>
<point x="1200" y="-480" type="line"/>
<point x="0" y="-480" type="line"/>
<point x="0" y="196" type="line"/>
<point x="600" y="196" type="line"/>
<point x="600" y="873" type="line"/>
<point x="0" y="873" type="line"/>
</contour>
</outline>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/blockO_ctant-1234678.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/blockO_ctant-1234678.glif",
"repo_id": "cascadia-code",
"token_count": 253
}
| 518 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="blockOctant-1237" format="2">
<advance width="1200"/>
<unicode hex="1CD3C"/>
<outline>
<contour>
<point x="0" y="2226" type="line"/>
<point x="1200" y="2226" type="line"/>
<point x="1200" y="1549" type="line"/>
<point x="600" y="1549" type="line"/>
<point x="600" y="873" type="line"/>
<point x="0" y="873" type="line"/>
</contour>
<contour>
<point x="0" y="196" type="line"/>
<point x="600" y="196" type="line"/>
<point x="600" y="-480" type="line"/>
<point x="0" y="-480" type="line"/>
</contour>
</outline>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/blockO_ctant-1237.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/blockO_ctant-1237.glif",
"repo_id": "cascadia-code",
"token_count": 311
}
| 519 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="blockOctant-2578" format="2">
<advance width="1200"/>
<unicode hex="1CDBD"/>
<outline>
<contour>
<point x="600" y="2226" type="line"/>
<point x="1200" y="2226" type="line"/>
<point x="1200" y="1549" type="line"/>
<point x="600" y="1549" type="line"/>
</contour>
<contour>
<point x="0" y="873" type="line"/>
<point x="600" y="873" type="line"/>
<point x="600" y="196" type="line"/>
<point x="1200" y="196" type="line"/>
<point x="1200" y="-480" type="line"/>
<point x="0" y="-480" type="line"/>
</contour>
</outline>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/blockO_ctant-2578.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/blockO_ctant-2578.glif",
"repo_id": "cascadia-code",
"token_count": 310
}
| 520 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="blockOctant-8" format="2">
<advance width="1200"/>
<unicode hex="1CEA0"/>
<outline>
<contour>
<point x="600" y="196" type="line"/>
<point x="1200" y="196" type="line"/>
<point x="1200" y="-480" type="line"/>
<point x="600" y="-480" type="line"/>
</contour>
</outline>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/blockO_ctant-8.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/blockO_ctant-8.glif",
"repo_id": "cascadia-code",
"token_count": 168
}
| 521 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="blockSedecimant-159" format="2">
<advance width="1200"/>
<unicode hex="1CEA6"/>
<outline>
<contour>
<point x="0" y="2226" type="line"/>
<point x="300" y="2226" type="line"/>
<point x="300" y="196" type="line"/>
<point x="0" y="196" type="line"/>
</contour>
</outline>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/blockS_edecimant-159.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/blockS_edecimant-159.glif",
"repo_id": "cascadia-code",
"token_count": 171
}
| 522 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="blockSedecimant-59D" format="2">
<advance width="1200"/>
<unicode hex="1CEA5"/>
<outline>
<contour>
<point x="0" y="1549" type="line"/>
<point x="300" y="1549" type="line"/>
<point x="300" y="-480" type="line"/>
<point x="0" y="-480" type="line"/>
</contour>
</outline>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/blockS_edecimant-59D.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/blockS_edecimant-59D.glif",
"repo_id": "cascadia-code",
"token_count": 174
}
| 523 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="blockSedecimant-B" format="2">
<advance width="1200"/>
<unicode hex="1CE9A"/>
<outline>
<contour>
<point x="600" y="873" type="line"/>
<point x="900" y="873" type="line"/>
<point x="900" y="196" type="line"/>
<point x="600" y="196" type="line"/>
</contour>
</outline>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/blockS_edecimant-B.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/blockS_edecimant-B.glif",
"repo_id": "cascadia-code",
"token_count": 171
}
| 524 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="blockSedecimant-G" format="2">
<advance width="1200"/>
<unicode hex="1CE9F"/>
<outline>
<contour>
<point x="900" y="196" type="line"/>
<point x="1200" y="196" type="line"/>
<point x="1200" y="-480" type="line"/>
<point x="900" y="-480" type="line"/>
</contour>
</outline>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/blockS_edecimant-G.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/blockS_edecimant-G.glif",
"repo_id": "cascadia-code",
"token_count": 171
}
| 525 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="blockSextant-12" format="2">
<advance width="1200"/>
<unicode hex="1FB02"/>
<outline>
<contour>
<point x="0" y="2226" type="line"/>
<point x="1200" y="2226" type="line"/>
<point x="1200" y="1324" type="line"/>
<point x="0" y="1324" type="line"/>
</contour>
</outline>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/blockS_extant-12.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/blockS_extant-12.glif",
"repo_id": "cascadia-code",
"token_count": 170
}
| 526 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="blockSextant-5" format="2">
<advance width="1200"/>
<unicode hex="1FB0F"/>
<outline>
<contour>
<point x="0" y="422" type="line"/>
<point x="600" y="422" type="line"/>
<point x="600" y="-480" type="line"/>
<point x="0" y="-480" type="line"/>
</contour>
</outline>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/blockS_extant-5.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/blockS_extant-5.glif",
"repo_id": "cascadia-code",
"token_count": 169
}
| 527 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="boxHeavyDownAndRight" format="2">
<advance width="1200"/>
<unicode hex="250F"/>
<outline>
<contour>
<point x="336" y="-530" type="line"/>
<point x="864" y="-530" type="line"/>
<point x="864" y="443" type="line"/>
<point x="1332" y="443" type="line"/>
<point x="1332" y="971" type="line"/>
<point x="336" y="971" type="line"/>
</contour>
</outline>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/boxH_eavyD_ownA_ndR_ight.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/boxH_eavyD_ownA_ndR_ight.glif",
"repo_id": "cascadia-code",
"token_count": 210
}
| 528 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="boxHeavyVerticalAndLeft" format="2">
<advance width="1200"/>
<unicode hex="252B"/>
<outline>
<contour>
<point x="336" y="-530" type="line"/>
<point x="864" y="-530" type="line"/>
<point x="864" y="2226" type="line"/>
<point x="336" y="2226" type="line"/>
<point x="336" y="971" type="line"/>
<point x="-132" y="971" type="line"/>
<point x="-132" y="443" type="line"/>
<point x="336" y="443" type="line"/>
</contour>
</outline>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/boxH_eavyV_erticalA_ndL_eft.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/boxH_eavyV_erticalA_ndL_eft.glif",
"repo_id": "cascadia-code",
"token_count": 253
}
| 529 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="boxLightDiagonalUpperRightToLowerLeft" format="2">
<advance width="1200"/>
<unicode hex="2571"/>
<outline>
<contour>
<point x="0" y="-518" type="line"/>
<point x="147" y="-518" type="line"/>
<point x="1200" y="1632" type="line"/>
<point x="1200" y="1932" type="line"/>
<point x="1053" y="1932" type="line"/>
<point x="0" y="-218" type="line"/>
</contour>
</outline>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/boxL_ightD_iagonalU_pperR_ightT_oL_owerL_eft.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/boxL_ightD_iagonalU_pperR_ightT_oL_owerL_eft.glif",
"repo_id": "cascadia-code",
"token_count": 216
}
| 530 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="boxLightUpAndHeavyDown" format="2">
<advance width="1200"/>
<unicode hex="257D"/>
<outline>
<contour>
<point x="336" y="-530" type="line"/>
<point x="864" y="-530" type="line"/>
<point x="864" y="839" type="line"/>
<point x="732" y="839" type="line"/>
<point x="732" y="2226" type="line"/>
<point x="468" y="2226" type="line"/>
<point x="468" y="839" type="line"/>
<point x="336" y="839" type="line"/>
</contour>
</outline>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/boxL_ightU_pA_ndH_eavyD_own.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/boxL_ightU_pA_ndH_eavyD_own.glif",
"repo_id": "cascadia-code",
"token_count": 255
}
| 531 |
<?xml version='1.0' encoding='UTF-8'?>
<glyph name="boxRightDownHeavyAndLeftUpLight" format="2">
<advance width="1200"/>
<unicode hex="2546"/>
<outline>
<contour>
<point x="336" y="-530" type="line"/>
<point x="864" y="-530" type="line"/>
<point x="864" y="443" type="line"/>
<point x="1332" y="443" type="line"/>
<point x="1332" y="971" type="line"/>
<point x="732" y="971" type="line"/>
<point x="732" y="2226" type="line"/>
<point x="468" y="2226" type="line"/>
<point x="468" y="971" type="line"/>
<point x="336" y="971" type="line"/>
<point x="336" y="839" type="line"/>
<point x="-132" y="839" type="line"/>
<point x="-132" y="575" type="line"/>
<point x="336" y="575" type="line"/>
</contour>
</outline>
</glyph>
|
cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/boxR_ightD_ownH_eavyA_ndL_eftU_pL_ight.glif/0
|
{
"file_path": "cascadia-code/sources/CascadiaCode-Bold.ufo/glyphs/boxR_ightD_ownH_eavyA_ndL_eftU_pL_ight.glif",
"repo_id": "cascadia-code",
"token_count": 383
}
| 532 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.