code
string | signature
string | docstring
string | loss_without_docstring
float64 | loss_with_docstring
float64 | factor
float64 |
|---|---|---|---|---|---|
array = super(CallbackQuery, self).to_array()
array['id'] = u(self.id) # py2: type unicode, py3: type str
array['from'] = self.from_peer.to_array() # type User
array['chat_instance'] = u(self.chat_instance) # py2: type unicode, py3: type str
if self.message is not None:
array['message'] = self.message.to_array() # type Message
if self.inline_message_id is not None:
array['inline_message_id'] = u(self.inline_message_id) # py2: type unicode, py3: type str
if self.data is not None:
array['data'] = u(self.data) # py2: type unicode, py3: type str
if self.game_short_name is not None:
array['game_short_name'] = u(self.game_short_name) # py2: type unicode, py3: type str
return array
|
def to_array(self)
|
Serializes this CallbackQuery to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
| 1.591039
| 1.493719
| 1.065153
|
if array is None or not array:
return None
# end if
assert_type_or_raise(array, dict, parameter_name="array")
from ..receivable.peer import User
data = {}
data['id'] = u(array.get('id'))
data['from_peer'] = User.from_array(array.get('from'))
data['chat_instance'] = u(array.get('chat_instance'))
data['message'] = Message.from_array(array.get('message')) if array.get('message') is not None else None
data['inline_message_id'] = u(array.get('inline_message_id')) if array.get('inline_message_id') is not None else None
data['data'] = u(array.get('data')) if array.get('data') is not None else None
data['game_short_name'] = u(array.get('game_short_name')) if array.get('game_short_name') is not None else None
data['_raw'] = array
return CallbackQuery(**data)
|
def from_array(array)
|
Deserialize a new CallbackQuery from a given dictionary.
:return: new CallbackQuery instance.
:rtype: CallbackQuery
| 2.24601
| 1.784995
| 1.258273
|
array = super(ResponseParameters, self).to_array()
if self.migrate_to_chat_id is not None:
array['migrate_to_chat_id'] = int(self.migrate_to_chat_id) # type int
if self.retry_after is not None:
array['retry_after'] = int(self.retry_after) # type int
return array
|
def to_array(self)
|
Serializes this ResponseParameters to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
| 2.601933
| 2.247756
| 1.157569
|
if array is None or not array:
return None
# end if
assert_type_or_raise(array, dict, parameter_name="array")
data = {}
data['migrate_to_chat_id'] = int(array.get('migrate_to_chat_id')) if array.get('migrate_to_chat_id') is not None else None
data['retry_after'] = int(array.get('retry_after')) if array.get('retry_after') is not None else None
data['_raw'] = array
return ResponseParameters(**data)
|
def from_array(array)
|
Deserialize a new ResponseParameters from a given dictionary.
:return: new ResponseParameters instance.
:rtype: ResponseParameters
| 2.743391
| 2.249939
| 1.219318
|
eps = list(eps or [])
args = list(args or [])
if vars is None: vars = {}
for arg in args:
if arg.nodeid is None:
raise XmrsStructureError("RMRS args must have a nodeid.")
# make the EPs more MRS-like (with arguments)
for ep in eps:
if ep.nodeid is None:
raise XmrsStructureError("RMRS EPs must have a nodeid.")
epargs = ep.args
for rargname, value in args.get(ep.nodeid, {}).items():
epargs[rargname] = value
hcons = list(hcons or [])
icons = list(icons or [])
return Xmrs(top=top, index=index, xarg=xarg,
eps=eps, hcons=hcons, icons=icons, vars=vars,
lnk=lnk, surface=surface, identifier=identifier)
|
def Rmrs(top=None, index=None, xarg=None,
eps=None, args=None, hcons=None, icons=None,
lnk=None, surface=None, identifier=None, vars=None)
|
Construct an :class:`Xmrs` from RMRS components.
Robust Minimal Recursion Semantics (RMRS) are like MRS, but all
predications have a nodeid ("anchor"), and arguments are not
contained by the source predications, but instead reference the
nodeid of their predication.
Args:
top: the TOP (or maybe LTOP) variable
index: the INDEX variable
xarg: the XARG variable
eps: an iterable of EPs
args: a nested mapping of `{nodeid: {rargname: value}}`
hcons: an iterable of HandleConstraint objects
icons: an iterable of IndividualConstraint objects
lnk: the Lnk object associating the MRS to the surface form
surface: the surface string
identifier: a discourse-utterance id
vars: a mapping of variables to a list of `(property, value)`
pairs
Example:
>>> m = Rmrs(
>>> top='h0',
>>> index='e2',
>>> eps=[ElementaryPredication(
>>> 10000,
>>> Pred.surface('_rain_v_1_rel'),
>>> 'h1'
>>> )],
>>> args={10000: {'ARG0': 'e2'}},
>>> hcons=[HandleConstraint('h0', 'qeq', 'h1'),
>>> vars={'e2': {'SF': 'prop-or-ques', 'TENSE': 'present'}}
>>> )
| 3.104149
| 2.831473
| 1.096302
|
x = cls()
x.__dict__.update(xmrs.__dict__)
return x
|
def from_xmrs(cls, xmrs, **kwargs)
|
Facilitate conversion among subclasses.
Args:
xmrs (:class:`Xmrs`): instance to convert from; possibly
an instance of a subclass, such as :class:`Mrs` or
:class:`Dmrs`
**kwargs: additional keyword arguments that may be used
by a subclass's redefinition of :meth:`from_xmrs`.
| 5.577391
| 8.37734
| 0.665771
|
# (nodeid, pred, label, args, lnk, surface, base)
_nodeids, _eps, _vars = self._nodeids, self._eps, self._vars
for ep in eps:
try:
if not isinstance(ep, ElementaryPredication):
ep = ElementaryPredication(*ep)
except TypeError:
raise XmrsError('Invalid EP data: {}'.format(repr(ep)))
# eplen = len(ep)
# if eplen < 3:
# raise XmrsError(
# 'EPs must have length >= 3: (nodeid, pred, label, ...)'
# )
nodeid, lbl = ep.nodeid, ep.label
if nodeid in _eps:
raise XmrsError(
'EP already exists in Xmrs: {} ({})'
.format(nodeid, ep[1])
)
_nodeids.append(nodeid)
_eps[nodeid] = ep
if lbl is not None:
_vars[lbl]['refs']['LBL'].append(nodeid)
for role, val in ep.args.items():
# if the val is not in _vars, it might still be a
# variable; check with var_re
if val in _vars or var_re.match(val):
vardict = _vars[val]
vardict['refs'][role].append(nodeid)
|
def add_eps(self, eps)
|
Incorporate the list of EPs given by *eps*.
| 4.270679
| 4.110543
| 1.038957
|
# (hi, relation, lo)
_vars = self._vars
_hcons = self._hcons
for hc in hcons:
try:
if not isinstance(hc, HandleConstraint):
hc = HandleConstraint(*hc)
except TypeError:
raise XmrsError('Invalid HCONS data: {}'.format(repr(hc)))
hi = hc.hi
lo = hc.lo
if hi in _hcons:
raise XmrsError(
'Handle constraint already exists for hole %s.' % hi
)
_hcons[hi] = hc
# the following should also ensure lo and hi are in _vars
if 'hcrefs' not in _vars[lo]:
_vars[lo]['hcrefs'] = []
for role, refs in _vars[hi]['refs'].items():
for nodeid in refs:
_vars[lo]['hcrefs'].append((nodeid, role, hi))
|
def add_hcons(self, hcons)
|
Incorporate the list of HandleConstraints given by *hcons*.
| 4.765386
| 4.48261
| 1.063083
|
_vars, _icons = self._vars, self._icons
for ic in icons:
try:
if not isinstance(ic, IndividualConstraint):
ic = IndividualConstraint(*ic)
except TypeError:
raise XmrsError('Invalid ICONS data: {}'.format(repr(ic)))
left = ic.left
right = ic.right
if left not in _icons:
_icons[left] = []
_icons[left].append(ic)
# the following should also ensure left and right are in _vars
if 'icrefs' not in _vars[right]:
_vars[right]['icrefs'] = []
_vars[right]['icrefs'].append(ic)
_vars[left]
|
def add_icons(self, icons)
|
Incorporate the individual constraints given by *icons*.
| 4.285482
| 3.984972
| 1.075411
|
return next(iter(self.nodeids(ivs=[iv], quantifier=quantifier)), None)
|
def nodeid(self, iv, quantifier=False)
|
Return the nodeid of the predication selected by *iv*.
Args:
iv: the intrinsic variable of the predication to select
quantifier: if `True`, treat *iv* as a bound variable and
find its quantifier; otherwise the non-quantifier will
be returned
| 7.191913
| 8.837465
| 0.813798
|
if ivs is None:
nids = list(self._nodeids)
else:
_vars = self._vars
nids = []
for iv in ivs:
if iv in _vars and IVARG_ROLE in _vars[iv]['refs']:
nids.extend(_vars[iv]['refs'][IVARG_ROLE])
else:
raise KeyError(iv)
if quantifier is not None:
nids = [n for n in nids if self.ep(n).is_quantifier()==quantifier]
return nids
|
def nodeids(self, ivs=None, quantifier=None)
|
Return the list of nodeids given by *ivs*, or all nodeids.
Args:
ivs: the intrinsic variables of the predications to select;
if `None`, return all nodeids (but see *quantifier*)
quantifier: if `True`, only return nodeids of quantifiers;
if `False`, only return non-quantifiers; if `None`
(the default), return both
| 3.423312
| 3.529949
| 0.969791
|
if nodeids is None: nodeids = self._nodeids
_eps = self._eps
return [_eps[nodeid] for nodeid in nodeids]
|
def eps(self, nodeids=None)
|
Return the EPs with the given *nodeid*, or all EPs.
Args:
nodeids: an iterable of nodeids of EPs to return; if
`None`, return all EPs
| 3.503313
| 4.955738
| 0.70692
|
if left is not None:
return self._icons[left]
else:
return list(chain.from_iterable(self._icons.values()))
|
def icons(self, left=None)
|
Return the ICONS with left variable *left*, or all ICONS.
Args:
left: the left variable of the ICONS to return; if `None`,
return all ICONS
| 3.171078
| 3.743469
| 0.847096
|
props = []
if var_or_nodeid in self._vars:
props = self._vars[var_or_nodeid]['props']
elif var_or_nodeid in self._eps:
var = self._eps[var_or_nodeid][3].get(IVARG_ROLE)
props = self._vars.get(var, {}).get('props', [])
else:
raise KeyError(var_or_nodeid)
if not as_list:
props = dict(props)
return props
|
def properties(self, var_or_nodeid, as_list=False)
|
Return a dictionary of variable properties for *var_or_nodeid*.
Args:
var_or_nodeid: if a variable, return the properties
associated with the variable; if a nodeid, return the
properties associated with the intrinsic variable of the
predication given by the nodeid
| 3.090385
| 3.318524
| 0.931253
|
if nodeids is None: nodeids = self._nodeids
_eps = self._eps
return [_eps[nid][1] for nid in nodeids]
|
def preds(self, nodeids=None)
|
Return the Pred objects for *nodeids*, or all Preds.
Args:
nodeids: an iterable of nodeids of predications to return
Preds from; if `None`, return all Preds
| 5.206376
| 8.092163
| 0.643385
|
if nodeids is None: nodeids = self._nodeids
_eps = self._eps
return [_eps[nid][2] for nid in nodeids]
|
def labels(self, nodeids=None)
|
Return the list of labels for *nodeids*, or all labels.
Args:
nodeids: an iterable of nodeids for predications to get
labels from; if `None`, return labels for all
predications
Note:
This returns the label of each predication, even if it's
shared by another predication. Thus,
`zip(nodeids, xmrs.labels(nodeids))` will pair nodeids with
their labels.
Returns:
A list of labels
| 5.284128
| 7.406825
| 0.713413
|
_vars = self._vars
_hcons = self._hcons
args = self.args(nodeid) # args is a copy; we can edit it
for arg, val in list(args.items()):
# don't include constant args or intrinsic args
if arg == IVARG_ROLE or val not in _vars:
del args[arg]
else:
refs = _vars[val]['refs']
# don't include if not HCONS or pointing to other IV or LBL
if not (val in _hcons or IVARG_ROLE in refs or 'LBL' in refs):
del args[arg]
return args
|
def outgoing_args(self, nodeid)
|
Return the arguments going from *nodeid* to other predications.
Valid arguments include regular variable arguments and scopal
(label-selecting or HCONS) arguments. MOD/EQ
links, intrinsic arguments, and constant arguments are not
included.
Args:
nodeid: the nodeid of the EP that is the arguments' source
Returns:
dict: `{role: tgt}`
| 8.084064
| 6.412426
| 1.260687
|
_vars = self._vars
ep = self._eps[nodeid]
lbl = ep[2]
iv = ep[3].get(IVARG_ROLE)
in_args_list = []
# variable args
if iv in _vars:
for role, nids in _vars[iv]['refs'].items():
# ignore intrinsic args, even if shared
if role != IVARG_ROLE:
in_args_list.append((nids, role, iv))
if lbl in _vars:
for role, nids in _vars[lbl]['refs'].items():
# basic label equality isn't "incoming"; ignore
if role != 'LBL':
in_args_list.append((nids, role, lbl))
for nid, role, hi in _vars[lbl].get('hcrefs', []):
in_args_list.append(([nid], role, hi))
in_args = {}
for nids, role, tgt in in_args_list:
for nid in nids:
if nid not in in_args:
in_args[nid] = {}
in_args[nid][role] = tgt
return in_args
|
def incoming_args(self, nodeid)
|
Return the arguments that target *nodeid*.
Valid arguments include regular variable arguments and scopal
(label-selecting or HCONS) arguments. MOD/EQ
links and intrinsic arguments are not included.
Args:
nodeid: the nodeid of the EP that is the arguments' target
Returns:
dict: `{source_nodeid: {rargname: value}}`
| 4.290468
| 3.993825
| 1.074275
|
_eps = self._eps
_vars = self._vars
_hcons = self._hcons
nodeids = {nodeid: _eps[nodeid][3].get(IVARG_ROLE, None)
for nodeid in _vars[label]['refs']['LBL']}
if len(nodeids) <= 1:
return list(nodeids)
scope_sets = {}
for nid in nodeids:
scope_sets[nid] = _ivs_in_scope(nid, _eps, _vars, _hcons)
out = {}
for n in nodeids:
out[n] = 0
for role, val in _eps[n][3].items():
if role == IVARG_ROLE or role == CONSTARG_ROLE:
continue
elif any(val in s for n2, s in scope_sets.items() if n2 != n):
out[n] += 1
candidates = [n for n, out_deg in out.items() if out_deg == 0]
rank = {}
for n in candidates:
iv = nodeids[n]
pred = _eps[n][1]
if iv in _vars and self.nodeid(iv, quantifier=True) is not None:
rank[n] = 0
elif pred.is_quantifier():
rank[n] = 0
elif pred.type == Pred.ABSTRACT:
rank[n] = 2
else:
rank[n] = 1
return sorted(candidates, key=lambda n: rank[n])
|
def labelset_heads(self, label)
|
Return the heads of the labelset selected by *label*.
Args:
label: the label from which to find head nodes/EPs.
Returns:
An iterable of nodeids.
| 4.146256
| 3.99963
| 1.03666
|
_eps, _vars = self._eps, self._vars
_hcons, _icons = self._hcons, self._icons
top = index = xarg = None
eps = [_eps[nid] for nid in nodeids]
lbls = set(ep[2] for ep in eps)
hcons = []
icons = []
subvars = {}
if self.top:
top = self.top
tophc = _hcons.get(top, None)
if tophc is not None and tophc[2] in lbls:
subvars[top] = {}
elif top not in lbls:
top = None # nevermind, set it back to None
# do index after we know if it is an EPs intrinsic variable.
# what about xarg? I'm not really sure.. just put it in
if self.xarg:
xarg = self.xarg
subvars[self.xarg] = _vars[self.xarg]['props']
subvars.update((lbl, {}) for lbl in lbls)
subvars.update(
(var, _vars[var]['props'])
for ep in eps for var in ep[3].values()
if var in _vars
)
if self.index in subvars:
index = self.index
# hcons and icons; only if the targets exist in the new subgraph
for var in subvars:
hc = _hcons.get(var, None)
if hc is not None and hc[2] in lbls:
hcons.append(hc)
for ic in _icons.get(var, []):
if ic[0] in subvars and ic[2] in subvars:
icons.append(ic)
return Xmrs(
top=top, index=index, xarg=xarg,
eps=eps, hcons=hcons, icons=icons, vars=subvars,
lnk=self.lnk, surface=self.surface, identifier=self.identifier
)
|
def subgraph(self, nodeids)
|
Return an Xmrs object with only the specified *nodeids*.
Necessary variables and arguments are also included in order to
connect any nodes that are connected in the original Xmrs.
Args:
nodeids: the nodeids of the nodes/EPs to include in the
subgraph.
Returns:
An :class:`Xmrs` object.
| 4.525742
| 4.144876
| 1.091888
|
nids = set(self._nodeids) # the nids left to find
if len(nids) == 0:
raise XmrsError('Cannot compute connectedness of an empty Xmrs.')
# build a basic dict graph of relations
edges = []
# label connections
for lbl in self.labels():
lblset = self.labelset(lbl)
edges.extend((x, y) for x in lblset for y in lblset if x != y)
# argument connections
_vars = self._vars
for nid in nids:
for rarg, tgt in self.args(nid).items():
if tgt not in _vars:
continue
if IVARG_ROLE in _vars[tgt]['refs']:
tgtnids = list(_vars[tgt]['refs'][IVARG_ROLE])
elif tgt in self._hcons:
tgtnids = list(self.labelset(self.hcon(tgt)[2]))
elif 'LBL' in _vars[tgt]['refs']:
tgtnids = list(_vars[tgt]['refs']['LBL'])
else:
tgtnids = []
# connections are bidirectional
edges.extend((nid, t) for t in tgtnids if nid != t)
edges.extend((t, nid) for t in tgtnids if nid != t)
g = {nid: set() for nid in nids}
for x, y in edges:
g[x].add(y)
connected_nids = _bfs(g)
if connected_nids == nids:
return True
elif connected_nids.difference(nids):
raise XmrsError(
'Possibly bogus nodeids: {}'
.format(', '.join(connected_nids.difference(nids)))
)
return False
|
def is_connected(self)
|
Return `True` if the Xmrs represents a connected graph.
Subgraphs can be connected through things like arguments,
QEQs, and label equalities.
| 4.029206
| 3.628939
| 1.110299
|
errors = []
ivs, bvs = {}, {}
_vars = self._vars
_hcons = self._hcons
labels = defaultdict(set)
# ep_args = {}
for ep in self.eps():
nid, lbl, args, is_q = (
ep.nodeid, ep.label, ep.args, ep.is_quantifier()
)
if lbl is None:
errors.append('EP ({}) is missing a label.'.format(nid))
labels[lbl].add(nid)
iv = args.get(IVARG_ROLE)
if iv is None:
errors.append('EP {nid} is missing an intrinsic variable.'
.format(nid))
if is_q:
if iv in bvs:
errors.append('{} is the bound variable for more than '
'one quantifier.'.format(iv))
bvs[iv] = nid
else:
if iv in ivs:
errors.append('{} is the intrinsic variable for more '
'than one EP.'.format(iv))
ivs[iv] = nid
# ep_args[nid] = args
for hc in _hcons.values():
if hc[2] not in labels:
errors.append('Lo variable of HCONS ({} {} {}) is not the '
'label of any EP.'.format(*hc))
if not self.is_connected():
errors.append('Xmrs structure is not connected.')
if errors:
raise XmrsError('\n'.join(errors))
|
def validate(self)
|
Check that the Xmrs is well-formed.
The Xmrs is analyzed and a list of problems is compiled. If
any problems exist, an :exc:`XmrsError` is raised with the list
joined as the error message. A well-formed Xmrs has the
following properties:
* All predications have an intrinsic variable
* Every intrinsic variable belongs one predication and maybe
one quantifier
* Every predication has no more than one quantifier
* All predications have a label
* The graph of predications form a net (i.e. are connected).
Connectivity can be established with variable arguments,
QEQs, or label-equality.
* The lo-handle for each QEQ must exist as the label of a
predication
| 4.376312
| 3.804172
| 1.150398
|
def _lnk(obj): return {'from': obj.cfrom, 'to': obj.cto}
def _ep(ep, short_pred=True):
p = ep.pred.short_form() if short_pred else ep.pred.string
d = dict(label=ep.label, predicate=p, arguments=ep.args)
if ep.lnk is not None: d['lnk'] = _lnk(ep)
return d
def _hcons(hc): return {'relation':hc[1], 'high':hc[0], 'low':hc[2]}
def _icons(ic): return {'relation':ic[1], 'left':ic[0], 'right':ic[2]}
def _var(v):
d = {'type': var_sort(v)}
if properties and self.properties(v):
d['properties'] = self.properties(v)
return d
d = dict(
relations=[_ep(ep, short_pred=short_pred) for ep in self.eps()],
constraints=([_hcons(hc) for hc in self.hcons()] +
[_icons(ic) for ic in self.icons()]),
variables={v: _var(v) for v in self.variables()}
)
if self.top is not None: d['top'] = self.top
if self.index is not None: d['index'] = self.index
# if self.xarg is not None: d['xarg'] = self.xarg
# if self.lnk is not None: d['lnk'] = self.lnk
# if self.surface is not None: d['surface'] = self.surface
# if self.identifier is not None: d['identifier'] = self.identifier
return d
|
def to_dict(self, short_pred=True, properties=True)
|
Encode the Mrs as a dictionary suitable for JSON serialization.
| 3.04082
| 2.973483
| 1.022646
|
def _lnk(o):
return None if o is None else Lnk.charspan(o['from'], o['to'])
def _ep(ep):
return ElementaryPredication(
nodeid=None,
pred=Pred.surface_or_abstract(ep['predicate']),
label=ep['label'],
args=ep.get('arguments', {}),
lnk=_lnk(ep.get('lnk')),
surface=ep.get('surface'),
base=ep.get('base')
)
eps = [_ep(rel) for rel in d.get('relations', [])]
hcons = [(c['high'], c['relation'], c['low'])
for c in d.get('constraints', []) if 'high' in c]
icons = [(c['high'], c['relation'], c['low'])
for c in d.get('constraints', []) if 'left' in c]
variables = {var: list(data.get('properties', {}).items())
for var, data in d.get('variables', {}).items()}
return cls(
top=d.get('top'),
index=d.get('index'),
xarg=d.get('xarg'),
rels=eps,
hcons=hcons,
icons=icons,
lnk=_lnk(d.get('lnk')),
surface=d.get('surface'),
identifier=d.get('identifier'),
vars=variables
)
|
def from_dict(cls, d)
|
Decode a dictionary, as from :meth:`to_dict`, into an Mrs object.
| 4.146133
| 4.091861
| 1.013263
|
qs = set(self.nodeids(quantifier=True))
def _lnk(obj): return {'from': obj.cfrom, 'to': obj.cto}
def _node(node, short_pred=True):
p = node.pred.short_form() if short_pred else node.pred.string
d = dict(nodeid=node.nodeid, predicate=p)
if node.lnk is not None: d['lnk'] = _lnk(node)
if properties and node.sortinfo:
if node.nodeid not in qs:
d['sortinfo'] = node.sortinfo
if node.surface is not None: d['surface'] = node.surface
if node.base is not None: d['base'] = node.base
if node.carg is not None: d['carg'] = node.carg
return d
def _link(link): return {
'from': link.start, 'to': link.end,
'rargname': link.rargname, 'post': link.post
}
d = dict(
nodes=[_node(n) for n in nodes(self)],
links=[_link(l) for l in links(self)]
)
# if self.top is not None: ... currently handled by links
if self.index is not None:
idx = self.nodeid(self.index)
if idx is not None:
d['index'] = idx
if self.xarg is not None:
xarg = self.nodeid(self.index)
if xarg is not None:
d['index'] = xarg
if self.lnk is not None: d['lnk'] = _lnk(self)
if self.surface is not None: d['surface'] = self.surface
if self.identifier is not None: d['identifier'] = self.identifier
return d
|
def to_dict(self, short_pred=True, properties=True)
|
Encode the Dmrs as a dictionary suitable for JSON serialization.
| 3.136709
| 2.987423
| 1.049972
|
def _node(obj):
return Node(
obj.get('nodeid'),
Pred.surface_or_abstract(obj.get('predicate')),
sortinfo=obj.get('sortinfo'),
lnk=_lnk(obj.get('lnk')),
surface=obj.get('surface'),
base=obj.get('base'),
carg=obj.get('carg')
)
def _link(obj):
return Link(obj.get('from'), obj.get('to'),
obj.get('rargname'), obj.get('post'))
def _lnk(o):
return None if o is None else Lnk.charspan(o['from'], o['to'])
return cls(
nodes=[_node(n) for n in d.get('nodes', [])],
links=[_link(l) for l in d.get('links', [])],
lnk=_lnk(d.get('lnk')),
surface=d.get('surface'),
identifier=d.get('identifier')
)
|
def from_dict(cls, d)
|
Decode a dictionary, as from :meth:`to_dict`, into a Dmrs object.
| 3.389432
| 3.223585
| 1.051448
|
ts = []
qs = set(self.nodeids(quantifier=True))
for n in nodes(self):
pred = n.pred.short_form() if short_pred else n.pred.string
ts.append((n.nodeid, 'predicate', pred))
if n.lnk is not None:
ts.append((n.nodeid, 'lnk', '"{}"'.format(str(n.lnk))))
if n.carg is not None:
ts.append((n.nodeid, 'carg', '"{}"'.format(n.carg)))
if properties and n.nodeid not in qs:
for key, value in n.sortinfo.items():
ts.append((n.nodeid, key.lower(), value))
for l in links(self):
if safe_int(l.start) == LTOP_NODEID:
ts.append((l.start, 'top', l.end))
else:
relation = '{}-{}'.format(l.rargname.upper(), l.post)
ts.append((l.start, relation, l.end))
return ts
|
def to_triples(self, short_pred=True, properties=True)
|
Encode the Dmrs as triples suitable for PENMAN serialization.
| 3.5916
| 3.463587
| 1.03696
|
top_nid = str(LTOP_NODEID)
top = lnk = surface = identifier = None
nids, nd, edges = [], {}, []
for src, rel, tgt in triples:
src, tgt = str(src), str(tgt) # hack for int-converted src/tgt
if src == top_nid and rel == 'top':
top = tgt
continue
elif src not in nd:
if top is None:
top=src
nids.append(src)
nd[src] = {'pred': None, 'lnk': None, 'carg': None, 'si': []}
if rel == 'predicate':
nd[src]['pred'] = Pred.surface_or_abstract(tgt)
elif rel == 'lnk':
cfrom, cto = tgt.strip('"<>').split(':')
nd[src]['lnk'] = Lnk.charspan(int(cfrom), int(cto))
elif rel == 'carg':
if (tgt[0], tgt[-1]) == ('"', '"'):
tgt = tgt[1:-1]
nd[src]['carg'] = tgt
elif rel.islower():
nd[src]['si'].append((rel, tgt))
else:
rargname, post = rel.rsplit('-', 1)
edges.append((src, tgt, rargname, post))
if remap_nodeids:
nidmap = dict((nid, FIRST_NODEID+i) for i, nid in enumerate(nids))
else:
nidmap = dict((nid, nid) for nid in nids)
nodes = [
Node(
nodeid=nidmap[nid],
pred=nd[nid]['pred'],
sortinfo=nd[nid]['si'],
lnk=nd[nid]['lnk'],
carg=nd[nid]['carg']
) for i, nid in enumerate(nids)
]
links = [Link(nidmap[s], nidmap[t], r, p) for s, t, r, p in edges]
if top:
links.append(Link(LTOP_NODEID, nidmap[top], None, H_POST))
return cls(
nodes=nodes,
links=links,
lnk=lnk,
surface=surface,
identifier=identifier
)
|
def from_triples(cls, triples, remap_nodeids=True)
|
Decode triples, as from :meth:`to_triples`, into a Dmrs object.
| 3.356256
| 3.333415
| 1.006852
|
array = super(Invoice, self).to_array()
array['title'] = u(self.title) # py2: type unicode, py3: type str
array['description'] = u(self.description) # py2: type unicode, py3: type str
array['start_parameter'] = u(self.start_parameter) # py2: type unicode, py3: type str
array['currency'] = u(self.currency) # py2: type unicode, py3: type str
array['total_amount'] = int(self.total_amount) # type int
return array
|
def to_array(self)
|
Serializes this Invoice to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
| 2.114088
| 1.970568
| 1.072831
|
array = super(ShippingAddress, self).to_array()
array['country_code'] = u(self.country_code) # py2: type unicode, py3: type str
array['state'] = u(self.state) # py2: type unicode, py3: type str
array['city'] = u(self.city) # py2: type unicode, py3: type str
array['street_line1'] = u(self.street_line1) # py2: type unicode, py3: type str
array['street_line2'] = u(self.street_line2) # py2: type unicode, py3: type str
array['post_code'] = u(self.post_code) # py2: type unicode, py3: type str
return array
|
def to_array(self)
|
Serializes this ShippingAddress to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
| 1.545142
| 1.483624
| 1.041465
|
array = super(OrderInfo, self).to_array()
if self.name is not None:
array['name'] = u(self.name) # py2: type unicode, py3: type str
if self.phone_number is not None:
array['phone_number'] = u(self.phone_number) # py2: type unicode, py3: type str
if self.email is not None:
array['email'] = u(self.email) # py2: type unicode, py3: type str
if self.shipping_address is not None:
array['shipping_address'] = self.shipping_address.to_array() # type ShippingAddress
return array
|
def to_array(self)
|
Serializes this OrderInfo to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
| 1.675388
| 1.675169
| 1.00013
|
if array is None or not array:
return None
# end if
assert_type_or_raise(array, dict, parameter_name="array")
data = {}
data['name'] = u(array.get('name')) if array.get('name') is not None else None
data['phone_number'] = u(array.get('phone_number')) if array.get('phone_number') is not None else None
data['email'] = u(array.get('email')) if array.get('email') is not None else None
data['shipping_address'] = ShippingAddress.from_array(array.get('shipping_address')) if array.get('shipping_address') is not None else None
data['_raw'] = array
return OrderInfo(**data)
|
def from_array(array)
|
Deserialize a new OrderInfo from a given dictionary.
:return: new OrderInfo instance.
:rtype: OrderInfo
| 2.011909
| 1.747031
| 1.151616
|
array = super(SuccessfulPayment, self).to_array()
array['currency'] = u(self.currency) # py2: type unicode, py3: type str
array['total_amount'] = int(self.total_amount) # type int
array['invoice_payload'] = u(self.invoice_payload) # py2: type unicode, py3: type str
array['telegram_payment_charge_id'] = u(self.telegram_payment_charge_id) # py2: type unicode, py3: type str
array['provider_payment_charge_id'] = u(self.provider_payment_charge_id) # py2: type unicode, py3: type str
if self.shipping_option_id is not None:
array['shipping_option_id'] = u(self.shipping_option_id) # py2: type unicode, py3: type str
if self.order_info is not None:
array['order_info'] = self.order_info.to_array() # type OrderInfo
return array
|
def to_array(self)
|
Serializes this SuccessfulPayment to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
| 1.664485
| 1.590439
| 1.046557
|
if array is None or not array:
return None
# end if
assert_type_or_raise(array, dict, parameter_name="array")
data = {}
data['currency'] = u(array.get('currency'))
data['total_amount'] = int(array.get('total_amount'))
data['invoice_payload'] = u(array.get('invoice_payload'))
data['telegram_payment_charge_id'] = u(array.get('telegram_payment_charge_id'))
data['provider_payment_charge_id'] = u(array.get('provider_payment_charge_id'))
data['shipping_option_id'] = u(array.get('shipping_option_id')) if array.get('shipping_option_id') is not None else None
data['order_info'] = OrderInfo.from_array(array.get('order_info')) if array.get('order_info') is not None else None
data['_raw'] = array
return SuccessfulPayment(**data)
|
def from_array(array)
|
Deserialize a new SuccessfulPayment from a given dictionary.
:return: new SuccessfulPayment instance.
:rtype: SuccessfulPayment
| 1.89213
| 1.626608
| 1.163237
|
array = super(ShippingQuery, self).to_array()
array['id'] = u(self.id) # py2: type unicode, py3: type str
array['from'] = self.from_peer.to_array() # type User
array['invoice_payload'] = u(self.invoice_payload) # py2: type unicode, py3: type str
array['shipping_address'] = self.shipping_address.to_array() # type ShippingAddress
return array
|
def to_array(self)
|
Serializes this ShippingQuery to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
| 2.365774
| 2.352871
| 1.005484
|
if array is None or not array:
return None
# end if
assert_type_or_raise(array, dict, parameter_name="array")
from pytgbot.api_types.receivable.peer import User
data = {}
data['id'] = u(array.get('id'))
data['from_peer'] = User.from_array(array.get('from'))
data['invoice_payload'] = u(array.get('invoice_payload'))
data['shipping_address'] = ShippingAddress.from_array(array.get('shipping_address'))
data['_raw'] = array
return ShippingQuery(**data)
|
def from_array(array)
|
Deserialize a new ShippingQuery from a given dictionary.
:return: new ShippingQuery instance.
:rtype: ShippingQuery
| 2.857931
| 2.461482
| 1.161061
|
array = super(PreCheckoutQuery, self).to_array()
array['id'] = u(self.id) # py2: type unicode, py3: type str
array['from'] = self.from_peer.to_array() # type User
array['currency'] = u(self.currency) # py2: type unicode, py3: type str
array['total_amount'] = int(self.total_amount) # type int
array['invoice_payload'] = u(self.invoice_payload) # py2: type unicode, py3: type str
if self.shipping_option_id is not None:
array['shipping_option_id'] = u(self.shipping_option_id) # py2: type unicode, py3: type str
if self.order_info is not None:
array['order_info'] = self.order_info.to_array() # type OrderInfo
return array
|
def to_array(self)
|
Serializes this PreCheckoutQuery to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
| 1.579842
| 1.497338
| 1.055101
|
if array is None or not array:
return None
# end if
assert_type_or_raise(array, dict, parameter_name="array")
from pytgbot.api_types.receivable.peer import User
data = {}
data['id'] = u(array.get('id'))
data['from_peer'] = User.from_array(array.get('from'))
data['currency'] = u(array.get('currency'))
data['total_amount'] = int(array.get('total_amount'))
data['invoice_payload'] = u(array.get('invoice_payload'))
data['shipping_option_id'] = u(array.get('shipping_option_id')) if array.get('shipping_option_id') is not None else None
data['order_info'] = OrderInfo.from_array(array.get('order_info')) if array.get('order_info') is not None else None
data['_raw'] = array
return PreCheckoutQuery(**data)
|
def from_array(array)
|
Deserialize a new PreCheckoutQuery from a given dictionary.
:return: new PreCheckoutQuery instance.
:rtype: PreCheckoutQuery
| 2.103214
| 1.732318
| 1.214104
|
array = super(InputMediaPhoto, self).to_array()
array['type'] = u(self.type) # py2: type unicode, py3: type str
array['media'] = u(self.media) # py2: type unicode, py3: type str
if self.caption is not None:
array['caption'] = u(self.caption) # py2: type unicode, py3: type str
if self.parse_mode is not None:
array['parse_mode'] = u(self.parse_mode) # py2: type unicode, py3: type str
return array
|
def to_array(self)
|
Serializes this InputMediaPhoto to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
| 1.940193
| 1.816085
| 1.068338
|
array = super(InputMediaAnimation, self).to_array()
array['type'] = u(self.type) # py2: type unicode, py3: type str
array['media'] = u(self.media) # py2: type unicode, py3: type str
if self.thumb is not None:
if isinstance(self.thumb, InputFile):
array['thumb'] = self.thumb.to_array() # type InputFile
elif isinstance(self.thumb, str):
array['thumb'] = u(self.thumb) # py2: type unicode, py3: type str
else:
raise TypeError('Unknown type, must be one of InputFile, str.')
# end if
if self.caption is not None:
array['caption'] = u(self.caption) # py2: type unicode, py3: type str
if self.parse_mode is not None:
array['parse_mode'] = u(self.parse_mode) # py2: type unicode, py3: type str
if self.width is not None:
array['width'] = int(self.width) # type int
if self.height is not None:
array['height'] = int(self.height) # type int
if self.duration is not None:
array['duration'] = int(self.duration) # type int
return array
|
def to_array(self)
|
Serializes this InputMediaAnimation to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
| 1.750971
| 1.669304
| 1.048923
|
array = super(InputMediaAudio, self).to_array()
array['type'] = u(self.type) # py2: type unicode, py3: type str
array['media'] = u(self.media) # py2: type unicode, py3: type str
if self.thumb is not None:
if isinstance(self.thumb, InputFile):
array['thumb'] = self.thumb.to_array() # type InputFile
elif isinstance(self.thumb, str):
array['thumb'] = u(self.thumb) # py2: type unicode, py3: type str
else:
raise TypeError('Unknown type, must be one of InputFile, str.')
# end if
if self.caption is not None:
array['caption'] = u(self.caption) # py2: type unicode, py3: type str
if self.parse_mode is not None:
array['parse_mode'] = u(self.parse_mode) # py2: type unicode, py3: type str
if self.duration is not None:
array['duration'] = int(self.duration) # type int
if self.performer is not None:
array['performer'] = u(self.performer) # py2: type unicode, py3: type str
if self.title is not None:
array['title'] = u(self.title) # py2: type unicode, py3: type str
return array
|
def to_array(self)
|
Serializes this InputMediaAudio to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
| 1.679174
| 1.613503
| 1.040701
|
array = super(InputMediaDocument, self).to_array()
array['type'] = u(self.type) # py2: type unicode, py3: type str
array['media'] = u(self.media) # py2: type unicode, py3: type str
if self.thumb is not None:
if isinstance(self.thumb, InputFile):
array['thumb'] = self.thumb.to_array() # type InputFile
elif isinstance(self.thumb, str):
array['thumb'] = u(self.thumb) # py2: type unicode, py3: type str
else:
raise TypeError('Unknown type, must be one of InputFile, str.')
# end if
if self.caption is not None:
array['caption'] = u(self.caption) # py2: type unicode, py3: type str
if self.parse_mode is not None:
array['parse_mode'] = u(self.parse_mode) # py2: type unicode, py3: type str
return array
|
def to_array(self)
|
Serializes this InputMediaDocument to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
| 1.882768
| 1.80497
| 1.043102
|
text = dumps(ms,
single=single,
pretty_print=pretty_print,
**kwargs)
if hasattr(destination, 'write'):
print(text, file=destination)
else:
with open(destination, 'w') as fh:
print(text, file=fh)
|
def dump(destination, ms, single=False, pretty_print=False, **kwargs)
|
Serialize Xmrs objects to the Prolog representation and write to a file.
Args:
destination: filename or file object where data will be written
ms: an iterator of Xmrs objects to serialize (unless the
*single* option is `True`)
single: if `True`, treat *ms* as a single Xmrs object
instead of as an iterator
pretty_print: if `True`, add newlines and indentation
| 2.3221
| 3.337673
| 0.695724
|
if single:
ms = [ms]
return serialize(ms, pretty_print=pretty_print, **kwargs)
|
def dumps(ms, single=False, pretty_print=False, **kwargs)
|
Serialize an Xmrs object to the Prolog representation
Args:
ms: an iterator of Xmrs objects to serialize (unless the
*single* option is `True`)
single: if `True`, treat *ms* as a single Xmrs object instead
of as an iterator
pretty_print: if `True`, add newlines and indentation
Returns:
the Prolog string representation of a corpus of Xmrs
| 3.141034
| 5.154347
| 0.609395
|
if hasattr(source, 'read'):
return _load(source, semi)
else:
with open(source, 'r') as fh:
return _load(fh, semi)
|
def load(source, semi=None)
|
Read a variable-property mapping from *source* and return the VPM.
Args:
source: a filename or file-like object containing the VPM
definitions
semi (:class:`~delphin.mrs.semi.SemI`, optional): if provided,
it is passed to the VPM constructor
Returns:
a :class:`VPM` instance
| 2.403549
| 3.505737
| 0.685604
|
if op in _EQUAL_OPS or semi is None:
return all(
s == v or # value equality
(s == '*' and v is not None) or # non-null wildcard
(
v is None and ( # value is null (any or with matching varsort)
s == '!' or
(s[0], s[-1], s[1:-1]) == ('[', ']', varsort)
)
)
for v, s in zip(vs, ss)
)
else:
pass
|
def _valmatch(vs, ss, op, varsort, semi, section)
|
Return `True` if for every paired *v* and *s* from *vs* and *ss*:
v <> s (subsumption or equality if *semi* is `None`)
v == s (equality)
s == '*'
s == '!' and v == `None`
s == '[xyz]' and varsort == 'xyz'
| 5.832154
| 4.638938
| 1.257218
|
vs, vid = sort_vid_split(var)
if reverse:
# variable type mapping is disabled in reverse
# tms = [(b, op, a) for a, op, b in self._typemap if op in _RL_OPS]
tms = []
else:
tms = [(a, op, b) for a, op, b in self._typemap if op in _LR_OPS]
for src, op, tgt in tms:
if _valmatch([vs], src, op, None, self._semi, 'variables'):
vs = vs if tgt == ['*'] else tgt[0]
break
newvar = '{}{}'.format(vs, vid)
newprops = {}
for featsets, valmap in self._propmap:
if reverse:
tgtfeats, srcfeats = featsets
pms = [(b, op, a) for a, op, b in valmap if op in _RL_OPS]
else:
srcfeats, tgtfeats = featsets
pms = [(a, op, b) for a, op, b in valmap if op in _LR_OPS]
vals = [props.get(f) for f in srcfeats]
for srcvals, op, tgtvals in pms:
if _valmatch(vals, srcvals, op, vs, self._semi, 'properties'):
for i, featval in enumerate(zip(tgtfeats, tgtvals)):
k, v = featval
if v == '*':
print(i, len(vals), vals, k, v)
if i < len(vals) and vals[i] is not None:
newprops[k] = vals[i]
elif v != '!':
newprops[k] = v
break
return newvar, newprops
|
def apply(self, var, props, reverse=False)
|
Apply the VPM to variable *var* and properties *props*.
Args:
var: a variable
props: a dictionary mapping properties to values
reverse: if `True`, apply the rules in reverse (e.g. from
grammar-external to grammar-internal forms)
Returns:
a tuple (v, p) of the mapped variable and properties
| 3.861496
| 3.868806
| 0.998111
|
if array is None or not array:
return None
# end if
assert_type_or_raise(array, dict, parameter_name="array")
from pytgbot.api_types.receivable.payments import ShippingAddress
data = {}
data['name'] = u(array.get('name')) if array.get('name') is not None else None
data['phone_number'] = u(array.get('phone_number')) if array.get('phone_number') is not None else None
data['email'] = u(array.get('email')) if array.get('email') is not None else None
data['shipping_address'] = ShippingAddress.from_array(array.get('shipping_address')) if array.get('shipping_address') is not None else None
data['_raw'] = array
return OrderInfo(**data)
|
def from_array(array)
|
Deserialize a new OrderInfo from a given dictionary.
:return: new OrderInfo instance.
:rtype: OrderInfo
| 2.030506
| 1.876572
| 1.082029
|
if source_fmt.startswith('eds') and not target_fmt.startswith('eds'):
raise ValueError(
'Conversion from EDS to non-EDS currently not supported.')
if indent:
pretty_print = True
indent = 4 if indent is True else safe_int(indent)
if len(tsql.inspect_query('select ' + select)['projection']) != 1:
raise ValueError('Exactly 1 column must be given in selection query: '
'(e.g., result:mrs)')
# read
loads = _get_codec(source_fmt)
if path is None:
xs = loads(sys.stdin.read())
elif hasattr(path, 'read'):
xs = loads(path.read())
elif os.path.isdir(path):
ts = itsdb.TestSuite(path)
xs = [
next(iter(loads(r[0])), None)
for r in tsql.select(select, ts)
]
else:
xs = loads(open(path, 'r').read())
# write
dumps = _get_codec(target_fmt, load=False)
kwargs = {}
if color: kwargs['color'] = color
if pretty_print: kwargs['pretty_print'] = pretty_print
if indent: kwargs['indent'] = indent
if target_fmt == 'eds':
kwargs['pretty_print'] = pretty_print
kwargs['show_status'] = show_status
if target_fmt.startswith('eds'):
kwargs['predicate_modifiers'] = predicate_modifiers
kwargs['properties'] = properties
# this is not a great way to improve robustness when converting
# many representations, but it'll do until v1.0.0. Also, it only
# improves robustness on the output, not the input.
# Note that all the code below is to replace the following:
# return dumps(xs, **kwargs)
head, joiner, tail = _get_output_details(target_fmt)
parts = []
if pretty_print:
joiner = joiner.strip() + '\n'
def _trim(s):
if head and s.startswith(head):
s = s[len(head):].lstrip('\n')
if tail and s.endswith(tail):
s = s[:-len(tail)].rstrip('\n')
return s
for x in xs:
try:
s = dumps([x], **kwargs)
except (PyDelphinException, KeyError, IndexError):
logging.exception('could not convert representation')
else:
s = _trim(s)
parts.append(s)
# set these after so head and tail are used correctly in _trim
if pretty_print:
if head:
head += '\n'
if tail:
tail = '\n' + tail
return head + joiner.join(parts) + tail
|
def convert(path, source_fmt, target_fmt, select='result:mrs',
properties=True, show_status=False, predicate_modifiers=False,
color=False, pretty_print=False, indent=None)
|
Convert between various DELPH-IN Semantics representations.
Args:
path (str, file): filename, testsuite directory, open file, or
stream of input representations
source_fmt (str): convert from this format
target_fmt (str): convert to this format
select (str): TSQL query for selecting data (ignored if *path*
is not a testsuite directory; default: `"result:mrs"`)
properties (bool): include morphosemantic properties if `True`
(default: `True`)
show_status (bool): show disconnected EDS nodes (ignored if
*target_fmt* is not `"eds"`; default: `False`)
predicate_modifiers (bool): apply EDS predicate modification
for certain kinds of patterns (ignored if *target_fmt* is
not an EDS format; default: `False`)
color (bool): apply syntax highlighting if `True` and
*target_fmt* is `"simplemrs"` (default: `False`)
pretty_print (bool): if `True`, format the output with
newlines and default indentation (default: `False`)
indent (int, optional): specifies an explicit number of spaces
for indentation (implies *pretty_print*)
Returns:
str: the converted representation
| 3.961562
| 3.821899
| 1.036543
|
if isinstance(testsuite, itsdb.ItsdbProfile):
testsuite = itsdb.TestSuite(testsuite.root)
elif not isinstance(testsuite, itsdb.TestSuite):
testsuite = itsdb.TestSuite(testsuite)
return tsql.select(dataspec, testsuite, mode=mode, cast=cast)
|
def select(dataspec, testsuite, mode='list', cast=True)
|
Select data from [incr tsdb()] profiles.
Args:
query (str): TSQL select query (e.g., `'i-id i-input mrs'` or
`'* from item where readings > 0'`)
testsuite (str, TestSuite): testsuite or path to testsuite
containing data to select
mode (str): see :func:`delphin.itsdb.select_rows` for a
description of the *mode* parameter (default: `list`)
cast (bool): if `True`, cast column values to their datatype
according to the relations file (default: `True`)
Returns:
a generator that yields selected data
| 3.57189
| 3.779456
| 0.94508
|
from delphin.interfaces import ace
if generate and transfer:
raise ValueError("'generate' is incompatible with 'transfer'")
if source is None:
source = testsuite
if select is None:
select = 'result:mrs' if (generate or transfer) else 'item:i-input'
if generate:
processor = ace.AceGenerator
elif transfer:
processor = ace.AceTransferer
else:
if not all_items:
select += ' where i-wf != 2'
processor = ace.AceParser
if result_id is not None:
select += ' where result-id == {}'.format(result_id)
source = itsdb.TestSuite(source)
target = itsdb.TestSuite(testsuite)
column, tablename, condition = _interpret_selection(select, source)
table = itsdb.Table(
source[tablename].fields,
tsql.select(
'* from {} {}'.format(tablename, condition),
source,
cast=False))
with processor(grammar, cmdargs=options) as cpu:
target.process(cpu, ':' + column, source=table, gzip=gzip)
|
def process(grammar, testsuite, source=None, select=None,
generate=False, transfer=False, options=None,
all_items=False, result_id=None, gzip=False)
|
Process (e.g., parse) a [incr tsdb()] profile.
Results are written to directly to *testsuite*.
If *select* is `None`, the defaults depend on the task:
========== =========================
Task Default value of *select*
========== =========================
Parsing `item:i-input`
Transfer `result:mrs`
Generation `result:mrs`
========== =========================
Args:
grammar (str): path to a compiled grammar image
testsuite (str): path to a [incr tsdb()] testsuite where data
will be read from (see *source*) and written to
source (str): path to a [incr tsdb()] testsuite; if `None`,
*testsuite* is used as the source of data
select (str): TSQL query for selecting processor inputs
(default depends on the processor type)
generate (bool): if `True`, generate instead of parse
(default: `False`)
transfer (bool): if `True`, transfer instead of parse
(default: `False`)
options (list): list of ACE command-line options to use when
invoking the ACE subprocess; unsupported options will
give an error message
all_items (bool): if `True`, don't exclude ignored items
(those with `i-wf==2`) when parsing
result_id (int): if given, only keep items with the specified
`result-id`
gzip (bool): if `True`, non-empty tables will be compressed
with gzip
| 6.573586
| 4.511932
| 1.456934
|
from delphin.repp import REPP
if config is not None and module is not None:
raise ValueError("cannot specify both 'config' and 'module'")
if config is not None and active:
raise ValueError("'active' cannot be used with 'config'")
if config:
r = REPP.from_config(config)
elif module:
r = REPP.from_file(module, active=active)
else:
r = REPP() # just tokenize
if hasattr(file, 'read'):
for line in file:
_repp(r, line, format, trace_level)
else:
with io.open(file, encoding='utf-8') as fh:
for line in fh:
_repp(r, line, format, trace_level)
|
def repp(file, config=None, module=None, active=None,
format=None, trace_level=0)
|
Tokenize with a Regular Expression PreProcessor (REPP).
Results are printed directly to stdout. If more programmatic
access is desired, the :mod:`delphin.repp` module provides a
similar interface.
Args:
file (str, file): filename, open file, or stream of sentence
inputs
config (str): path to a PET REPP configuration (.set) file
module (str): path to a top-level REPP module; other modules
are found by external group calls
active (list): select which modules are active; if `None`, all
are used; incompatible with *config* (default: `None`)
format (str): the output format (`"yy"`, `"string"`, `"line"`,
or `"triple"`; default: `"yy"`)
trace_level (int): if `0` no trace info is printed; if `1`,
applied rules are printed, if greather than `1`, both
applied and unapplied rules (in order) are printed
(default: `0`)
| 2.443359
| 2.370147
| 1.030889
|
from delphin.mrs import simplemrs, compare as mrs_compare
if not isinstance(testsuite, itsdb.TestSuite):
if isinstance(testsuite, itsdb.ItsdbProfile):
testsuite = testsuite.root
testsuite = itsdb.TestSuite(testsuite)
if not isinstance(gold, itsdb.TestSuite):
if isinstance(gold, itsdb.ItsdbProfile):
gold = gold.root
gold = itsdb.TestSuite(gold)
queryobj = tsql.inspect_query('select ' + select)
if len(queryobj['projection']) != 3:
raise ValueError('select does not return 3 fields: ' + select)
input_select = '{} {}'.format(queryobj['projection'][0],
queryobj['projection'][1])
i_inputs = dict(tsql.select(input_select, testsuite))
matched_rows = itsdb.match_rows(
tsql.select(select, testsuite),
tsql.select(select, gold),
0)
for (key, testrows, goldrows) in matched_rows:
(test_unique, shared, gold_unique) = mrs_compare.compare_bags(
[simplemrs.loads_one(row[2]) for row in testrows],
[simplemrs.loads_one(row[2]) for row in goldrows])
yield {'id': key,
'input': i_inputs[key],
'test': test_unique,
'shared': shared,
'gold': gold_unique}
|
def compare(testsuite, gold, select='i-id i-input mrs')
|
Compare two [incr tsdb()] profiles.
Args:
testsuite (str, TestSuite): path to the test [incr tsdb()]
testsuite or a :class:`TestSuite` object
gold (str, TestSuite): path to the gold [incr tsdb()]
testsuite or a :class:`TestSuite` object
select: TSQL query to select (id, input, mrs) triples
(default: `i-id i-input mrs`)
Yields:
dict: Comparison results as::
{"id": "item identifier",
"input": "input sentence",
"test": number_of_unique_results_in_test,
"shared": number_of_shared_results,
"gold": number_of_unique_results_in_gold}
| 3.543973
| 3.047018
| 1.163096
|
def func(xmrs, deps):
edges = []
for src in deps:
for _, tgt in deps[src]:
edges.append((src, tgt))
components = _connected_components(xmrs.nodeids(), edges)
ccmap = {}
for i, component in enumerate(components):
for n in component:
ccmap[n] = i
addl = {}
if not only_connecting or len(components) > 1:
lsh = xmrs.labelset_heads
lblheads = {v: lsh(v) for v, vd in xmrs._vars.items()
if 'LBL' in vd['refs']}
for heads in lblheads.values():
if len(heads) > 1:
first = heads[0]
joined = set([ccmap[first]])
for other in heads[1:]:
occ = ccmap[other]
srt = var_sort(xmrs.args(other).get(role, 'u0'))
needs_edge = not only_connecting or occ not in joined
edge_available = srt == 'u'
if needs_edge and edge_available:
addl.setdefault(other, []).append((role, first))
joined.add(occ)
return addl
return func
|
def non_argument_modifiers(role='ARG1', only_connecting=True)
|
Return a function that finds non-argument modifier dependencies.
Args:
role (str): the role that is assigned to the dependency
only_connecting (bool): if `True`, only return dependencies
that connect separate components in the basic dependencies;
if `False`, all non-argument modifier dependencies are
included
Returns:
a function with signature `func(xmrs, deps)` that returns a
mapping of non-argument modifier dependencies
Examples:
The default function behaves like the LKB:
>>> func = non_argument_modifiers()
A variation is similar to DMRS's MOD/EQ links:
>>> func = non_argument_modifiers(role="MOD", only_connecting=False)
| 5.775948
| 5.658573
| 1.020743
|
if isinstance(fh, stringtypes):
s = open(fh, 'r').read()
else:
s = fh.read()
return loads(s, single=single)
|
def load(fh, single=False)
|
Deserialize :class:`Eds` from a file (handle or filename)
Args:
fh (str, file): input filename or file object
single (bool): if `True`, only return the first Xmrs object
Returns:
a generator of :class:`Eds` objects (unless the *single* option
is `True`)
| 3.369661
| 3.962194
| 0.850453
|
es = deserialize(s)
if single:
return next(es)
return es
|
def loads(s, single=False)
|
Deserialize :class:`Eds` string representations
Args:
s (str): Eds string
single (bool): if `True`, only return the first Xmrs object
Returns:
a generator of :class:`Eds` objects (unless the *single* option
is `True`)
| 6.558067
| 8.349792
| 0.785417
|
if not pretty_print and kwargs.get('indent'):
pretty_print = True
if single:
ms = [ms]
return serialize(
ms,
properties=properties,
pretty_print=pretty_print,
show_status=show_status,
predicate_modifiers=predicate_modifiers,
**kwargs
)
|
def dumps(ms, single=False,
properties=False, pretty_print=True,
show_status=False, predicate_modifiers=False, **kwargs)
|
Serialize an Xmrs object to a Eds representation
Args:
ms: an iterator of :class:`~delphin.mrs.xmrs.Xmrs` objects to
serialize (unless the *single* option is `True`)
single (bool): if `True`, treat *ms* as a single
:class:`~delphin.mrs.xmrs.Xmrs` object instead of as an
iterator
properties (bool): if `False`, suppress variable properties
pretty_print (bool): if `True`, add newlines and indentation
show_status (bool): if `True`, annotate disconnected graphs and
nodes
Returns:
an :class:`Eds` string representation of a corpus of Xmrs
| 2.187912
| 2.65223
| 0.824933
|
eps = xmrs.eps()
deps = _find_basic_dependencies(xmrs, eps)
# if requested, find additional dependencies not captured already
if predicate_modifiers is True:
func = non_argument_modifiers(role='ARG1', only_connecting=True)
addl_deps = func(xmrs, deps)
elif predicate_modifiers is False or predicate_modifiers is None:
addl_deps = {}
elif hasattr(predicate_modifiers, '__call__'):
addl_deps = predicate_modifiers(xmrs, deps)
else:
raise TypeError('a boolean or callable is required')
for nid, deplist in addl_deps.items():
deps.setdefault(nid, []).extend(deplist)
ids = _unique_ids(eps, deps)
root = _find_root(xmrs)
if root is not None:
root = ids[root]
nodes = [Node(ids[n.nodeid], *n[1:]) for n in make_nodes(xmrs)]
edges = [(ids[a], rarg, ids[b]) for a, deplist in deps.items()
for rarg, b in deplist]
return cls(top=root, nodes=nodes, edges=edges)
|
def from_xmrs(cls, xmrs, predicate_modifiers=False, **kwargs)
|
Instantiate an Eds from an Xmrs (lossy conversion).
Args:
xmrs (:class:`~delphin.mrs.xmrs.Xmrs`): Xmrs instance to
convert from
predicate_modifiers (function, bool): function that is
called as `func(xmrs, deps)` after finding the basic
dependencies (`deps`), returning a mapping of
predicate-modifier dependencies; the form of `deps` and
the returned mapping are `{head: [(role, dependent)]}`;
if *predicate_modifiers* is `True`, the function is
created using :func:`non_argument_modifiers` as:
`non_argument_modifiers(role="ARG1", connecting=True);
if *predicate_modifiers* is `False`, only the basic
dependencies are returned
| 4.584812
| 3.732289
| 1.228418
|
getnode = self._nodes.__getitem__
return [getnode(nid) for nid in self._nodeids]
|
def nodes(self)
|
Return the list of nodes.
| 7.440491
| 6.423666
| 1.158293
|
nodes = {}
for node in self.nodes():
nd = {
'label': node.pred.short_form(),
'edges': self.edges(node.nodeid)
}
if node.lnk is not None:
nd['lnk'] = {'from': node.cfrom, 'to': node.cto}
if properties:
if node.cvarsort is not None:
nd['type'] = node.cvarsort
props = node.properties
if props:
nd['properties'] = props
if node.carg is not None:
nd['carg'] = node.carg
nodes[node.nodeid] = nd
return {'top': self.top, 'nodes': nodes}
|
def to_dict(self, properties=True)
|
Encode the Eds as a dictionary suitable for JSON serialization.
| 3.734307
| 3.801549
| 0.982312
|
makepred, charspan = Pred.surface_or_abstract, Lnk.charspan
top = d.get('top')
nodes, edges = [], []
for nid, node in d.get('nodes', {}).items():
props = node.get('properties', {})
if 'type' in node:
props[CVARSORT] = node['type']
if not props:
props = None
lnk = None
if 'lnk' in node:
lnk = charspan(node['lnk']['from'], node['lnk']['to'])
nodes.append(
Node(
nodeid=nid,
pred=makepred(node['label']),
sortinfo=props,
lnk=lnk,
carg=node.get('carg')
)
)
edges.extend(
(nid, rargname, tgtnid)
for rargname, tgtnid in node.get('edges', {}).items()
)
nodes.sort(key=lambda n: (n.cfrom, -n.cto))
return cls(top, nodes=nodes, edges=edges)
|
def from_dict(cls, d)
|
Decode a dictionary, as from :meth:`to_dict`, into an Eds object.
| 4.838665
| 4.889944
| 0.989513
|
node_triples, edge_triples = [], []
# sort nodeids just so top var is first
nodes = sorted(self.nodes(), key=lambda n: n.nodeid != self.top)
for node in nodes:
nid = node.nodeid
pred = node.pred.short_form() if short_pred else node.pred.string
node_triples.append((nid, 'predicate', pred))
if node.lnk:
node_triples.append((nid, 'lnk', '"{}"'.format(str(node.lnk))))
if node.carg:
node_triples.append((nid, 'carg', '"{}"'.format(node.carg)))
if properties:
if node.cvarsort is not None:
node_triples.append((nid, 'type', node.cvarsort))
props = node.properties
node_triples.extend((nid, p, v) for p, v in props.items())
edge_triples.extend(
(nid, rargname, tgt)
for rargname, tgt in sorted(
self.edges(nid).items(),
key=lambda x: rargname_sortkey(x[0])
)
)
return node_triples + edge_triples
|
def to_triples(self, short_pred=True, properties=True)
|
Encode the Eds as triples suitable for PENMAN serialization.
| 3.436761
| 3.354729
| 1.024453
|
nids, nd, edges = [], {}, []
for src, rel, tgt in triples:
if src not in nd:
nids.append(src)
nd[src] = {'pred': None, 'lnk': None, 'carg': None, 'si': []}
if rel == 'predicate':
nd[src]['pred'] = Pred.surface_or_abstract(tgt)
elif rel == 'lnk':
cfrom, cto = tgt.strip('"<>').split(':')
nd[src]['lnk'] = Lnk.charspan(int(cfrom), int(cto))
elif rel == 'carg':
if (tgt[0], tgt[-1]) == ('"', '"'):
tgt = tgt[1:-1]
nd[src]['carg'] = tgt
elif rel == 'type':
nd[src]['si'].append((CVARSORT, tgt))
elif rel.islower():
nd[src]['si'].append((rel, tgt))
else:
edges.append((src, rel, tgt))
nodes = [
Node(
nodeid=nid,
pred=nd[nid]['pred'],
sortinfo=nd[nid]['si'],
lnk=nd[nid]['lnk'],
carg=nd[nid]['carg']
) for nid in nids
]
top = nids[0] if nids else None
return cls(top=top, nodes=nodes, edges=edges)
|
def from_triples(cls, triples)
|
Decode triples, as from :meth:`to_triples`, into an Eds object.
| 3.247684
| 3.186977
| 1.019049
|
buffer = self._buffer
popleft = buffer.popleft
if skip is not None:
while True:
try:
if not skip(buffer[0]):
break
popleft()
except IndexError:
self._buffer_fill()
try:
datum = popleft()
except IndexError:
self._buffer_fill()
datum = popleft()
return datum
|
def next(self, skip=None)
|
Remove the next datum from the buffer and return it.
| 3.321944
| 2.821635
| 1.177312
|
buffer = self._buffer
popleft = buffer.popleft
datum = None
if skip is not None:
stack = []
stackpush = stack.append
while n >= 0:
try:
datum = popleft()
except IndexError:
self._buffer_fill()
datum = popleft()
if not skip(datum):
n -= 1
stackpush(datum)
elif not drop:
stackpush(datum)
buffer.extendleft(reversed(stack))
else:
self._buffer_fill(n + 1)
datum = buffer[n]
return datum
|
def peek(self, n=0, skip=None, drop=False)
|
Return the *n*th datum from the buffer.
| 3.313678
| 3.085457
| 1.073967
|
array = super(InlineQueryResultPhoto, self).to_array()
array['type'] = u(self.type) # py2: type unicode, py3: type str
array['id'] = u(self.id) # py2: type unicode, py3: type str
array['photo_url'] = u(self.photo_url) # py2: type unicode, py3: type str
array['thumb_url'] = u(self.thumb_url) # py2: type unicode, py3: type str
if self.photo_width is not None:
array['photo_width'] = int(self.photo_width) # type int
if self.photo_height is not None:
array['photo_height'] = int(self.photo_height) # type int
if self.title is not None:
array['title'] = u(self.title) # py2: type unicode, py3: type str
if self.description is not None:
array['description'] = u(self.description) # py2: type unicode, py3: type str
if self.caption is not None:
array['caption'] = u(self.caption) # py2: type unicode, py3: type str
if self.parse_mode is not None:
array['parse_mode'] = u(self.parse_mode) # py2: type unicode, py3: type str
if self.reply_markup is not None:
array['reply_markup'] = self.reply_markup.to_array() # type InlineKeyboardMarkup
if self.input_message_content is not None:
array['input_message_content'] = self.input_message_content.to_array() # type InputMessageContent
return array
|
def to_array(self)
|
Serializes this InlineQueryResultPhoto to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
| 1.347878
| 1.304903
| 1.032933
|
array = super(InlineQueryResultMpeg4Gif, self).to_array()
array['type'] = u(self.type) # py2: type unicode, py3: type str
array['id'] = u(self.id) # py2: type unicode, py3: type str
array['mpeg4_url'] = u(self.mpeg4_url) # py2: type unicode, py3: type str
array['thumb_url'] = u(self.thumb_url) # py2: type unicode, py3: type str
if self.mpeg4_width is not None:
array['mpeg4_width'] = int(self.mpeg4_width) # type int
if self.mpeg4_height is not None:
array['mpeg4_height'] = int(self.mpeg4_height) # type int
if self.mpeg4_duration is not None:
array['mpeg4_duration'] = int(self.mpeg4_duration) # type int
if self.title is not None:
array['title'] = u(self.title) # py2: type unicode, py3: type str
if self.caption is not None:
array['caption'] = u(self.caption) # py2: type unicode, py3: type str
if self.parse_mode is not None:
array['parse_mode'] = u(self.parse_mode) # py2: type unicode, py3: type str
if self.reply_markup is not None:
array['reply_markup'] = self.reply_markup.to_array() # type InlineKeyboardMarkup
if self.input_message_content is not None:
array['input_message_content'] = self.input_message_content.to_array() # type InputMessageContent
return array
|
def to_array(self)
|
Serializes this InlineQueryResultMpeg4Gif to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
| 1.348629
| 1.316244
| 1.024604
|
array = super(InlineQueryResultVideo, self).to_array()
array['type'] = u(self.type) # py2: type unicode, py3: type str
array['id'] = u(self.id) # py2: type unicode, py3: type str
array['video_url'] = u(self.video_url) # py2: type unicode, py3: type str
array['mime_type'] = u(self.mime_type) # py2: type unicode, py3: type str
array['thumb_url'] = u(self.thumb_url) # py2: type unicode, py3: type str
array['title'] = u(self.title) # py2: type unicode, py3: type str
if self.caption is not None:
array['caption'] = u(self.caption) # py2: type unicode, py3: type str
if self.parse_mode is not None:
array['parse_mode'] = u(self.parse_mode) # py2: type unicode, py3: type str
if self.video_width is not None:
array['video_width'] = int(self.video_width) # type int
if self.video_height is not None:
array['video_height'] = int(self.video_height) # type int
if self.video_duration is not None:
array['video_duration'] = int(self.video_duration) # type int
if self.description is not None:
array['description'] = u(self.description) # py2: type unicode, py3: type str
if self.reply_markup is not None:
array['reply_markup'] = self.reply_markup.to_array() # type InlineKeyboardMarkup
if self.input_message_content is not None:
array['input_message_content'] = self.input_message_content.to_array() # type InputMessageContent
return array
|
def to_array(self)
|
Serializes this InlineQueryResultVideo to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
| 1.336988
| 1.302509
| 1.026471
|
array = super(InlineQueryResultVoice, self).to_array()
array['type'] = u(self.type) # py2: type unicode, py3: type str
array['id'] = u(self.id) # py2: type unicode, py3: type str
array['voice_url'] = u(self.voice_url) # py2: type unicode, py3: type str
array['title'] = u(self.title) # py2: type unicode, py3: type str
if self.caption is not None:
array['caption'] = u(self.caption) # py2: type unicode, py3: type str
if self.parse_mode is not None:
array['parse_mode'] = u(self.parse_mode) # py2: type unicode, py3: type str
if self.voice_duration is not None:
array['voice_duration'] = int(self.voice_duration) # type int
if self.reply_markup is not None:
array['reply_markup'] = self.reply_markup.to_array() # type InlineKeyboardMarkup
if self.input_message_content is not None:
array['input_message_content'] = self.input_message_content.to_array() # type InputMessageContent
return array
|
def to_array(self)
|
Serializes this InlineQueryResultVoice to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
| 1.505192
| 1.452717
| 1.036122
|
array = super(InlineQueryResultDocument, self).to_array()
array['type'] = u(self.type) # py2: type unicode, py3: type str
array['id'] = u(self.id) # py2: type unicode, py3: type str
array['title'] = u(self.title) # py2: type unicode, py3: type str
array['document_url'] = u(self.document_url) # py2: type unicode, py3: type str
array['mime_type'] = u(self.mime_type) # py2: type unicode, py3: type str
if self.caption is not None:
array['caption'] = u(self.caption) # py2: type unicode, py3: type str
if self.parse_mode is not None:
array['parse_mode'] = u(self.parse_mode) # py2: type unicode, py3: type str
if self.description is not None:
array['description'] = u(self.description) # py2: type unicode, py3: type str
if self.reply_markup is not None:
array['reply_markup'] = self.reply_markup.to_array() # type InlineKeyboardMarkup
if self.input_message_content is not None:
array['input_message_content'] = self.input_message_content.to_array() # type InputMessageContent
if self.thumb_url is not None:
array['thumb_url'] = u(self.thumb_url) # py2: type unicode, py3: type str
if self.thumb_width is not None:
array['thumb_width'] = int(self.thumb_width) # type int
if self.thumb_height is not None:
array['thumb_height'] = int(self.thumb_height) # type int
return array
|
def to_array(self)
|
Serializes this InlineQueryResultDocument to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
| 1.343239
| 1.301734
| 1.031884
|
array = super(InlineQueryResultVenue, self).to_array()
array['type'] = u(self.type) # py2: type unicode, py3: type str
array['id'] = u(self.id) # py2: type unicode, py3: type str
array['latitude'] = float(self.latitude) # type float
array['longitude'] = float(self.longitude) # type float
array['title'] = u(self.title) # py2: type unicode, py3: type str
array['address'] = u(self.address) # py2: type unicode, py3: type str
if self.foursquare_id is not None:
array['foursquare_id'] = u(self.foursquare_id) # py2: type unicode, py3: type str
if self.foursquare_type is not None:
array['foursquare_type'] = u(self.foursquare_type) # py2: type unicode, py3: type str
if self.reply_markup is not None:
array['reply_markup'] = self.reply_markup.to_array() # type InlineKeyboardMarkup
if self.input_message_content is not None:
array['input_message_content'] = self.input_message_content.to_array() # type InputMessageContent
if self.thumb_url is not None:
array['thumb_url'] = u(self.thumb_url) # py2: type unicode, py3: type str
if self.thumb_width is not None:
array['thumb_width'] = int(self.thumb_width) # type int
if self.thumb_height is not None:
array['thumb_height'] = int(self.thumb_height) # type int
return array
|
def to_array(self)
|
Serializes this InlineQueryResultVenue to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
| 1.381333
| 1.329906
| 1.03867
|
array = super(InlineQueryResultGame, self).to_array()
array['type'] = u(self.type) # py2: type unicode, py3: type str
array['id'] = u(self.id) # py2: type unicode, py3: type str
array['game_short_name'] = u(self.game_short_name) # py2: type unicode, py3: type str
if self.reply_markup is not None:
array['reply_markup'] = self.reply_markup.to_array() # type InlineKeyboardMarkup
return array
|
def to_array(self)
|
Serializes this InlineQueryResultGame to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
| 2.152879
| 1.995566
| 1.078832
|
array = super(InlineQueryResultCachedPhoto, self).to_array()
array['type'] = u(self.type) # py2: type unicode, py3: type str
array['id'] = u(self.id) # py2: type unicode, py3: type str
array['photo_file_id'] = u(self.photo_file_id) # py2: type unicode, py3: type str
if self.title is not None:
array['title'] = u(self.title) # py2: type unicode, py3: type str
if self.description is not None:
array['description'] = u(self.description) # py2: type unicode, py3: type str
if self.caption is not None:
array['caption'] = u(self.caption) # py2: type unicode, py3: type str
if self.parse_mode is not None:
array['parse_mode'] = u(self.parse_mode) # py2: type unicode, py3: type str
if self.reply_markup is not None:
array['reply_markup'] = self.reply_markup.to_array() # type InlineKeyboardMarkup
if self.input_message_content is not None:
array['input_message_content'] = self.input_message_content.to_array() # type InputMessageContent
return array
|
def to_array(self)
|
Serializes this InlineQueryResultCachedPhoto to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
| 1.42308
| 1.359532
| 1.046742
|
array = super(InlineQueryResultCachedMpeg4Gif, self).to_array()
array['type'] = u(self.type) # py2: type unicode, py3: type str
array['id'] = u(self.id) # py2: type unicode, py3: type str
array['mpeg4_file_id'] = u(self.mpeg4_file_id) # py2: type unicode, py3: type str
if self.title is not None:
array['title'] = u(self.title) # py2: type unicode, py3: type str
if self.caption is not None:
array['caption'] = u(self.caption) # py2: type unicode, py3: type str
if self.parse_mode is not None:
array['parse_mode'] = u(self.parse_mode) # py2: type unicode, py3: type str
if self.reply_markup is not None:
array['reply_markup'] = self.reply_markup.to_array() # type InlineKeyboardMarkup
if self.input_message_content is not None:
array['input_message_content'] = self.input_message_content.to_array() # type InputMessageContent
return array
|
def to_array(self)
|
Serializes this InlineQueryResultCachedMpeg4Gif to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
| 1.468163
| 1.402356
| 1.046926
|
array = super(InlineQueryResultCachedSticker, self).to_array()
array['type'] = u(self.type) # py2: type unicode, py3: type str
array['id'] = u(self.id) # py2: type unicode, py3: type str
array['sticker_file_id'] = u(self.sticker_file_id) # py2: type unicode, py3: type str
if self.reply_markup is not None:
array['reply_markup'] = self.reply_markup.to_array() # type InlineKeyboardMarkup
if self.input_message_content is not None:
array['input_message_content'] = self.input_message_content.to_array() # type InputMessageContent
return array
|
def to_array(self)
|
Serializes this InlineQueryResultCachedSticker to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
| 1.797929
| 1.690777
| 1.063374
|
array = super(InlineQueryResultCachedVideo, self).to_array()
array['type'] = u(self.type) # py2: type unicode, py3: type str
array['id'] = u(self.id) # py2: type unicode, py3: type str
array['video_file_id'] = u(self.video_file_id) # py2: type unicode, py3: type str
array['title'] = u(self.title) # py2: type unicode, py3: type str
if self.description is not None:
array['description'] = u(self.description) # py2: type unicode, py3: type str
if self.caption is not None:
array['caption'] = u(self.caption) # py2: type unicode, py3: type str
if self.parse_mode is not None:
array['parse_mode'] = u(self.parse_mode) # py2: type unicode, py3: type str
if self.reply_markup is not None:
array['reply_markup'] = self.reply_markup.to_array() # type InlineKeyboardMarkup
if self.input_message_content is not None:
array['input_message_content'] = self.input_message_content.to_array() # type InputMessageContent
return array
|
def to_array(self)
|
Serializes this InlineQueryResultCachedVideo to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
| 1.427501
| 1.367507
| 1.043871
|
array = super(InlineQueryResultCachedAudio, self).to_array()
array['type'] = u(self.type) # py2: type unicode, py3: type str
array['id'] = u(self.id) # py2: type unicode, py3: type str
array['audio_file_id'] = u(self.audio_file_id) # py2: type unicode, py3: type str
if self.caption is not None:
array['caption'] = u(self.caption) # py2: type unicode, py3: type str
if self.parse_mode is not None:
array['parse_mode'] = u(self.parse_mode) # py2: type unicode, py3: type str
if self.reply_markup is not None:
array['reply_markup'] = self.reply_markup.to_array() # type InlineKeyboardMarkup
if self.input_message_content is not None:
array['input_message_content'] = self.input_message_content.to_array() # type InputMessageContent
return array
|
def to_array(self)
|
Serializes this InlineQueryResultCachedAudio to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
| 1.552636
| 1.480572
| 1.048673
|
array = super(MessageEntity, self).to_array()
array['type'] = u(self.type) # py2: type unicode, py3: type str
array['offset'] = int(self.offset) # type int
array['length'] = int(self.length) # type int
if self.url is not None:
array['url'] = u(self.url) # py2: type unicode, py3: type str
if self.user is not None:
array['user'] = self.user.to_array() # type User
return array
|
def to_array(self)
|
Serializes this MessageEntity to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
| 2.163506
| 2.238375
| 0.966552
|
array = super(PhotoSize, self).to_array()
array['file_id'] = u(self.file_id) # py2: type unicode, py3: type str
array['width'] = int(self.width) # type int
array['height'] = int(self.height) # type int
if self.file_size is not None:
array['file_size'] = int(self.file_size) # type int
return array
|
def to_array(self)
|
Serializes this PhotoSize to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
| 2.092216
| 1.948994
| 1.073485
|
array = super(Audio, self).to_array()
array['file_id'] = u(self.file_id) # py2: type unicode, py3: type str
array['duration'] = int(self.duration) # type int
if self.performer is not None:
array['performer'] = u(self.performer) # py2: type unicode, py3: type str
if self.title is not None:
array['title'] = u(self.title) # py2: type unicode, py3: type str
if self.mime_type is not None:
array['mime_type'] = u(self.mime_type) # py2: type unicode, py3: type str
if self.file_size is not None:
array['file_size'] = int(self.file_size) # type int
if self.thumb is not None:
array['thumb'] = self.thumb.to_array() # type PhotoSize
return array
|
def to_array(self)
|
Serializes this Audio to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
| 1.664222
| 1.650958
| 1.008034
|
if array is None or not array:
return None
# end if
assert_type_or_raise(array, dict, parameter_name="array")
from pytgbot.api_types.receivable.media import PhotoSize
data = {}
data['file_id'] = u(array.get('file_id'))
data['duration'] = int(array.get('duration'))
data['performer'] = u(array.get('performer')) if array.get('performer') is not None else None
data['title'] = u(array.get('title')) if array.get('title') is not None else None
data['mime_type'] = u(array.get('mime_type')) if array.get('mime_type') is not None else None
data['file_size'] = int(array.get('file_size')) if array.get('file_size') is not None else None
data['thumb'] = PhotoSize.from_array(array.get('thumb')) if array.get('thumb') is not None else None
data['_raw'] = array
return Audio(**data)
|
def from_array(array)
|
Deserialize a new Audio from a given dictionary.
:return: new Audio instance.
:rtype: Audio
| 1.894211
| 1.793334
| 1.056251
|
array = super(Document, self).to_array()
array['file_id'] = u(self.file_id) # py2: type unicode, py3: type str
if self.thumb is not None:
array['thumb'] = self.thumb.to_array() # type PhotoSize
if self.file_name is not None:
array['file_name'] = u(self.file_name) # py2: type unicode, py3: type str
if self.mime_type is not None:
array['mime_type'] = u(self.mime_type) # py2: type unicode, py3: type str
if self.file_size is not None:
array['file_size'] = int(self.file_size) # type int
return array
|
def to_array(self)
|
Serializes this Document to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
| 1.886934
| 1.857021
| 1.016108
|
array = super(Animation, self).to_array()
array['file_id'] = u(self.file_id) # py2: type unicode, py3: type str
array['width'] = int(self.width) # type int
array['height'] = int(self.height) # type int
array['duration'] = int(self.duration) # type int
if self.thumb is not None:
array['thumb'] = self.thumb.to_array() # type PhotoSize
if self.file_name is not None:
array['file_name'] = u(self.file_name) # py2: type unicode, py3: type str
if self.mime_type is not None:
array['mime_type'] = u(self.mime_type) # py2: type unicode, py3: type str
if self.file_size is not None:
array['file_size'] = int(self.file_size) # type int
return array
|
def to_array(self)
|
Serializes this Animation to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
| 1.695077
| 1.709673
| 0.991463
|
array = super(Voice, self).to_array()
array['file_id'] = u(self.file_id) # py2: type unicode, py3: type str
array['duration'] = int(self.duration) # type int
if self.mime_type is not None:
array['mime_type'] = u(self.mime_type) # py2: type unicode, py3: type str
if self.file_size is not None:
array['file_size'] = int(self.file_size) # type int
return array
|
def to_array(self)
|
Serializes this Voice to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
| 2.100399
| 2.015884
| 1.041925
|
array = super(VideoNote, self).to_array()
array['file_id'] = u(self.file_id) # py2: type unicode, py3: type str
array['length'] = int(self.length) # type int
array['duration'] = int(self.duration) # type int
if self.thumb is not None:
array['thumb'] = self.thumb.to_array() # type PhotoSize
if self.file_size is not None:
array['file_size'] = int(self.file_size) # type int
return array
|
def to_array(self)
|
Serializes this VideoNote to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
| 2.002539
| 1.864076
| 1.07428
|
array = super(Contact, self).to_array()
array['phone_number'] = u(self.phone_number) # py2: type unicode, py3: type str
array['first_name'] = u(self.first_name) # py2: type unicode, py3: type str
if self.last_name is not None:
array['last_name'] = u(self.last_name) # py2: type unicode, py3: type str
if self.user_id is not None:
array['user_id'] = int(self.user_id) # type int
if self.vcard is not None:
array['vcard'] = u(self.vcard) # py2: type unicode, py3: type str
return array
|
def to_array(self)
|
Serializes this Contact to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
| 1.973762
| 1.880943
| 1.049347
|
array = super(Location, self).to_array()
array['longitude'] = float(self.longitude) # type float
array['latitude'] = float(self.latitude) # type float
return array
|
def to_array(self)
|
Serializes this Location to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
| 3.330781
| 3.054877
| 1.090316
|
if array is None or not array:
return None
# end if
assert_type_or_raise(array, dict, parameter_name="array")
data = {}
data['longitude'] = float(array.get('longitude'))
data['latitude'] = float(array.get('latitude'))
data['_raw'] = array
return Location(**data)
|
def from_array(array)
|
Deserialize a new Location from a given dictionary.
:return: new Location instance.
:rtype: Location
| 3.512867
| 2.699186
| 1.301454
|
array = super(Venue, self).to_array()
array['location'] = self.location.to_array() # type Location
array['title'] = u(self.title) # py2: type unicode, py3: type str
array['address'] = u(self.address) # py2: type unicode, py3: type str
if self.foursquare_id is not None:
array['foursquare_id'] = u(self.foursquare_id) # py2: type unicode, py3: type str
if self.foursquare_type is not None:
array['foursquare_type'] = u(self.foursquare_type) # py2: type unicode, py3: type str
return array
|
def to_array(self)
|
Serializes this Venue to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
| 1.931988
| 1.804201
| 1.070828
|
if array is None or not array:
return None
# end if
assert_type_or_raise(array, dict, parameter_name="array")
from pytgbot.api_types.receivable.media import Location
data = {}
data['location'] = Location.from_array(array.get('location'))
data['title'] = u(array.get('title'))
data['address'] = u(array.get('address'))
data['foursquare_id'] = u(array.get('foursquare_id')) if array.get('foursquare_id') is not None else None
data['foursquare_type'] = u(array.get('foursquare_type')) if array.get('foursquare_type') is not None else None
data['_raw'] = array
return Venue(**data)
|
def from_array(array)
|
Deserialize a new Venue from a given dictionary.
:return: new Venue instance.
:rtype: Venue
| 2.172966
| 2.056934
| 1.05641
|
array = super(UserProfilePhotos, self).to_array()
array['total_count'] = int(self.total_count) # type int
array['photos'] = self._as_array(self.photos) # type list of list of PhotoSize
return array
|
def to_array(self)
|
Serializes this UserProfilePhotos to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
| 4.630563
| 3.435751
| 1.347758
|
if array is None or not array:
return None
# end if
assert_type_or_raise(array, dict, parameter_name="array")
from pytgbot.api_types.receivable.media import PhotoSize
data = {}
data['total_count'] = int(array.get('total_count'))
data['photos'] = PhotoSize.from_array_list(array.get('photos'), list_level=2)
data['_raw'] = array
return UserProfilePhotos(**data)
|
def from_array(array)
|
Deserialize a new UserProfilePhotos from a given dictionary.
:return: new UserProfilePhotos instance.
:rtype: UserProfilePhotos
| 3.390811
| 2.989245
| 1.134337
|
array = super(File, self).to_array()
array['file_id'] = u(self.file_id) # py2: type unicode, py3: type str
if self.file_size is not None:
array['file_size'] = int(self.file_size) # type int
if self.file_path is not None:
array['file_path'] = u(self.file_path) # py2: type unicode, py3: type str
return array
|
def to_array(self)
|
Serializes this File to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
| 2.292398
| 2.220667
| 1.032301
|
array = super(ChatPhoto, self).to_array()
array['small_file_id'] = u(self.small_file_id) # py2: type unicode, py3: type str
array['big_file_id'] = u(self.big_file_id) # py2: type unicode, py3: type str
return array
|
def to_array(self)
|
Serializes this ChatPhoto to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
| 2.579571
| 2.224199
| 1.159775
|
array = super(Sticker, self).to_array()
array['file_id'] = u(self.file_id) # py2: type unicode, py3: type str
array['width'] = int(self.width) # type int
array['height'] = int(self.height) # type int
if self.thumb is not None:
array['thumb'] = self.thumb.to_array() # type PhotoSize
if self.emoji is not None:
array['emoji'] = u(self.emoji) # py2: type unicode, py3: type str
if self.set_name is not None:
array['set_name'] = u(self.set_name) # py2: type unicode, py3: type str
if self.mask_position is not None:
array['mask_position'] = self.mask_position.to_array() # type MaskPosition
if self.file_size is not None:
array['file_size'] = int(self.file_size) # type int
return array
|
def to_array(self)
|
Serializes this Sticker to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
| 1.594409
| 1.533067
| 1.040013
|
if array is None or not array:
return None
# end if
assert_type_or_raise(array, dict, parameter_name="array")
from pytgbot.api_types.receivable.media import PhotoSize
from pytgbot.api_types.receivable.stickers import MaskPosition
data = {}
data['file_id'] = u(array.get('file_id'))
data['width'] = int(array.get('width'))
data['height'] = int(array.get('height'))
data['thumb'] = PhotoSize.from_array(array.get('thumb')) if array.get('thumb') is not None else None
data['emoji'] = u(array.get('emoji')) if array.get('emoji') is not None else None
data['set_name'] = u(array.get('set_name')) if array.get('set_name') is not None else None
data['mask_position'] = MaskPosition.from_array(array.get('mask_position')) if array.get('mask_position') is not None else None
data['file_size'] = int(array.get('file_size')) if array.get('file_size') is not None else None
data['_raw'] = array
return Sticker(**data)
|
def from_array(array)
|
Deserialize a new Sticker from a given dictionary.
:return: new Sticker instance.
:rtype: Sticker
| 1.785327
| 1.664922
| 1.072319
|
array = super(Game, self).to_array()
array['title'] = u(self.title) # py2: type unicode, py3: type str
array['description'] = u(self.description) # py2: type unicode, py3: type str
array['photo'] = self._as_array(self.photo) # type list of PhotoSize
if self.text is not None:
array['text'] = u(self.text) # py2: type unicode, py3: type str
if self.text_entities is not None:
array['text_entities'] = self._as_array(self.text_entities) # type list of MessageEntity
if self.animation is not None:
array['animation'] = self.animation.to_array() # type Animation
return array
|
def to_array(self)
|
Serializes this Game to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
| 2.08636
| 1.989472
| 1.0487
|
if array is None or not array:
return None
# end if
assert_type_or_raise(array, dict, parameter_name="array")
from pytgbot.api_types.receivable.media import Animation
from pytgbot.api_types.receivable.media import MessageEntity
from pytgbot.api_types.receivable.media import PhotoSize
data = {}
data['title'] = u(array.get('title'))
data['description'] = u(array.get('description'))
data['photo'] = PhotoSize.from_array_list(array.get('photo'), list_level=1)
data['text'] = u(array.get('text')) if array.get('text') is not None else None
data['text_entities'] = MessageEntity.from_array_list(array.get('text_entities'), list_level=1) if array.get('text_entities') is not None else None
data['animation'] = Animation.from_array(array.get('animation')) if array.get('animation') is not None else None
data['_raw'] = array
return Game(**data)
|
def from_array(array)
|
Deserialize a new Game from a given dictionary.
:return: new Game instance.
:rtype: Game
| 2.101712
| 1.894722
| 1.109246
|
data = super(DownloadableMedia).from_array(array)
data["file_id"] = array.get("file_id")
data["file_size"] = array.get("file_size") # can be None
return data
|
def from_array(array)
|
Subclass for all :class:`Media` which has a :py:attr:`file_id` and optionally a :py:attr:`file_size`
:param array: a array to parse
:type array: dict
:return: a dict with file_id and file_size extracted from the array
:rtype: dict
| 5.357944
| 3.371649
| 1.589117
|
if array is None or not array:
return None
# end if
assert_type_or_raise(array, dict, parameter_name="array")
from .stickers import MaskPosition
data = {}
data['file_id'] = u(array.get('file_id'))
data['width'] = int(array.get('width'))
data['height'] = int(array.get('height'))
data['thumb'] = PhotoSize.from_array(array.get('thumb')) if array.get('thumb') is not None else None
data['emoji'] = u(array.get('emoji')) if array.get('emoji') is not None else None
data['set_name'] = u(array.get('set_name')) if array.get('set_name') is not None else None
data['mask_position'] = MaskPosition.from_array(array.get('mask_position')) if array.get(
'mask_position') is not None else None
data['file_size'] = int(array.get('file_size')) if array.get('file_size') is not None else None
data['_raw'] = array
return Sticker(**data)
|
def from_array(array)
|
Deserialize a new Sticker from a given dictionary.
:return: new Sticker instance.
:rtype: Sticker
| 1.836974
| 1.716373
| 1.070265
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.