code stringlengths 2k 1.04M | repo_path stringlengths 5 517 | parsed_code stringlengths 0 1.04M | quality_prob float64 0.02 0.95 | learning_prob float64 0.02 0.93 |
|---|---|---|---|---|
import numpy as np
import matplotlib.pyplot as plt
from ars_lib.ars import ARSAgent, Normalizer, Policy, ParallelWorker
from mini_bullet.minitaur_gym_env import MinitaurBulletEnv
from tg_lib.tg_policy import TGPolicy
import time
import torch
import os
def main():
""" The main() function. """
print("STARTING MINITAUR ARS")
# TRAINING PARAMETERS
# env_name = "MinitaurBulletEnv-v0"
seed = 0
max_timesteps = 1e6
file_name = "mini_tg_ars_"
# Find abs path to this file
my_path = os.path.abspath(os.path.dirname(__file__))
results_path = os.path.join(my_path, "../results")
models_path = os.path.join(my_path, "../models")
if not os.path.exists(results_path):
os.makedirs(results_path)
if not os.path.exists(models_path):
os.makedirs(models_path)
env = MinitaurBulletEnv(render=True, on_rack=False)
dt = env._time_step
# TRAJECTORY GENERATOR
movetype = "walk"
# movetype = "trot"
# movetype = "bound"
# movetype = "pace"
# movetype = "pronk"
TG = TGPolicy(movetype=movetype,
center_swing=0.0,
amplitude_extension=0.2,
amplitude_lift=0.4)
TG_state_dim = len(TG.get_TG_state())
TG_action_dim = 5 # f_tg, Beta, alpha_tg, h_tg, intensity
state_dim = env.observation_space.shape[0] + TG_state_dim
print("STATE DIM: {}".format(state_dim))
action_dim = env.action_space.shape[0] + TG_action_dim
print("ACTION DIM: {}".format(action_dim))
max_action = float(env.action_space.high[0])
print("RECORDED MAX ACTION: {}".format(max_action))
# Initialize Normalizer
normalizer = Normalizer(state_dim)
# Initialize Policy
policy = Policy(state_dim, action_dim)
# Initialize Agent with normalizer, policy and gym env
agent = ARSAgent(normalizer, policy, env, TGP=TG)
agent_num = raw_input("Policy Number: ")
if os.path.exists(models_path + "/" + file_name + str(agent_num) +
"_policy"):
print("Loading Existing agent")
agent.load(models_path + "/" + file_name + str(agent_num))
agent.policy.episode_steps = 1000
policy = agent.policy
# Set seeds
env.seed(seed)
torch.manual_seed(seed)
np.random.seed(seed)
env.reset()
episode_reward = 0
episode_timesteps = 0
episode_num = 0
print("STARTED MINITAUR TEST SCRIPT")
# Just to store correct action space
action = env.action_space.sample()
# Record extends for plot
# LF_ext = []
# LB_ext = []
# RF_ext = []
# RB_ext = []
LF_tp = []
LB_tp = []
RF_tp = []
RB_tp = []
t = 0
while t < (int(max_timesteps)):
action[:] = 0.0
# # Get Action from TG [no policies here]
# action = TG.get_utg(action, alpha_tg, h_tg, intensity,
# env.minitaur.num_motors)
# LF_ext.append(action[env.minitaur.num_motors / 2])
# LB_ext.append(action[1 + env.minitaur.num_motors / 2])
# RF_ext.append(action[2 + env.minitaur.num_motors / 2])
# RB_ext.append(action[3 + env.minitaur.num_motors / 2])
# # Perform action
# next_state, reward, done, _ = env.step(action)
obs = agent.TGP.get_TG_state()
# LF_tp.append(obs[0])
# LB_tp.append(obs[1])
# RF_tp.append(obs[2])
# RB_tp.append(obs[3])
# # Increment phase
# TG.increment(dt, f_tg, Beta)
# # time.sleep(1.0)
# t += 1
# Maximum timesteps per rollout
t += policy.episode_steps
episode_timesteps += 1
episode_reward = agent.deployTG()
# episode_reward = agent.train()
# +1 to account for 0 indexing.
# +0 on ep_timesteps since it will increment +1 even if done=True
print("Total T: {} Episode Num: {} Episode T: {} Reward: {}".format(
t, episode_num, policy.episode_steps, episode_reward))
# Reset environment
episode_reward = 0
episode_timesteps = 0
episode_num += 1
plt.plot(0)
plt.plot(LF_tp, label="LF")
plt.plot(LB_tp, label="LB")
plt.plot(RF_tp, label="RF")
plt.plot(RB_tp, label="RB")
plt.xlabel("t")
plt.ylabel("EXT")
plt.title("Leg Extensions")
plt.legend()
plt.show()
env.close()
if __name__ == '__main__':
main() | spot_bullet/src/old_eval_scripts/tg_eval.py |
import numpy as np
import matplotlib.pyplot as plt
from ars_lib.ars import ARSAgent, Normalizer, Policy, ParallelWorker
from mini_bullet.minitaur_gym_env import MinitaurBulletEnv
from tg_lib.tg_policy import TGPolicy
import time
import torch
import os
def main():
""" The main() function. """
print("STARTING MINITAUR ARS")
# TRAINING PARAMETERS
# env_name = "MinitaurBulletEnv-v0"
seed = 0
max_timesteps = 1e6
file_name = "mini_tg_ars_"
# Find abs path to this file
my_path = os.path.abspath(os.path.dirname(__file__))
results_path = os.path.join(my_path, "../results")
models_path = os.path.join(my_path, "../models")
if not os.path.exists(results_path):
os.makedirs(results_path)
if not os.path.exists(models_path):
os.makedirs(models_path)
env = MinitaurBulletEnv(render=True, on_rack=False)
dt = env._time_step
# TRAJECTORY GENERATOR
movetype = "walk"
# movetype = "trot"
# movetype = "bound"
# movetype = "pace"
# movetype = "pronk"
TG = TGPolicy(movetype=movetype,
center_swing=0.0,
amplitude_extension=0.2,
amplitude_lift=0.4)
TG_state_dim = len(TG.get_TG_state())
TG_action_dim = 5 # f_tg, Beta, alpha_tg, h_tg, intensity
state_dim = env.observation_space.shape[0] + TG_state_dim
print("STATE DIM: {}".format(state_dim))
action_dim = env.action_space.shape[0] + TG_action_dim
print("ACTION DIM: {}".format(action_dim))
max_action = float(env.action_space.high[0])
print("RECORDED MAX ACTION: {}".format(max_action))
# Initialize Normalizer
normalizer = Normalizer(state_dim)
# Initialize Policy
policy = Policy(state_dim, action_dim)
# Initialize Agent with normalizer, policy and gym env
agent = ARSAgent(normalizer, policy, env, TGP=TG)
agent_num = raw_input("Policy Number: ")
if os.path.exists(models_path + "/" + file_name + str(agent_num) +
"_policy"):
print("Loading Existing agent")
agent.load(models_path + "/" + file_name + str(agent_num))
agent.policy.episode_steps = 1000
policy = agent.policy
# Set seeds
env.seed(seed)
torch.manual_seed(seed)
np.random.seed(seed)
env.reset()
episode_reward = 0
episode_timesteps = 0
episode_num = 0
print("STARTED MINITAUR TEST SCRIPT")
# Just to store correct action space
action = env.action_space.sample()
# Record extends for plot
# LF_ext = []
# LB_ext = []
# RF_ext = []
# RB_ext = []
LF_tp = []
LB_tp = []
RF_tp = []
RB_tp = []
t = 0
while t < (int(max_timesteps)):
action[:] = 0.0
# # Get Action from TG [no policies here]
# action = TG.get_utg(action, alpha_tg, h_tg, intensity,
# env.minitaur.num_motors)
# LF_ext.append(action[env.minitaur.num_motors / 2])
# LB_ext.append(action[1 + env.minitaur.num_motors / 2])
# RF_ext.append(action[2 + env.minitaur.num_motors / 2])
# RB_ext.append(action[3 + env.minitaur.num_motors / 2])
# # Perform action
# next_state, reward, done, _ = env.step(action)
obs = agent.TGP.get_TG_state()
# LF_tp.append(obs[0])
# LB_tp.append(obs[1])
# RF_tp.append(obs[2])
# RB_tp.append(obs[3])
# # Increment phase
# TG.increment(dt, f_tg, Beta)
# # time.sleep(1.0)
# t += 1
# Maximum timesteps per rollout
t += policy.episode_steps
episode_timesteps += 1
episode_reward = agent.deployTG()
# episode_reward = agent.train()
# +1 to account for 0 indexing.
# +0 on ep_timesteps since it will increment +1 even if done=True
print("Total T: {} Episode Num: {} Episode T: {} Reward: {}".format(
t, episode_num, policy.episode_steps, episode_reward))
# Reset environment
episode_reward = 0
episode_timesteps = 0
episode_num += 1
plt.plot(0)
plt.plot(LF_tp, label="LF")
plt.plot(LB_tp, label="LB")
plt.plot(RF_tp, label="RF")
plt.plot(RB_tp, label="RB")
plt.xlabel("t")
plt.ylabel("EXT")
plt.title("Leg Extensions")
plt.legend()
plt.show()
env.close()
if __name__ == '__main__':
main() | 0.416797 | 0.27558 |
import torch
import torch.nn as nn
import torch.nn.functional as F
from mmdet.models.builder import build_loss, HEADS
from mmcv.cnn import normal_init
from mmcv.cnn import ConvModule
from mmcv.runner import force_fp32, auto_fp16
import cv2
import numpy as np
@HEADS.register_module()
class InstanceMaskAttentionHead(nn.Module):
""" Inplemenation of IMA in MANGO[1]. Dynamic convolution strategy refers to Solov2 [2].
Ref: [1] MANGO: A Mask Attention Guided One-Staged Text Spotter. AAAI-21.
<https://arxiv.org/abs/2012.04350>`_
[2] SOLOv2: Dynamic, Faster and Stronger, NeurIPS-20
<https://arxiv.org/abs/2003.10152>`_
"""
def __init__(self,
in_channels,
conv_out_channels,
num_grids,
stacked_convs=4,
text_max_length=25,
featmap_indices=(0, 1, 2, 3),
loss_instance_mask_att=None,
):
"""
Args:
in_channels (int): input feature map channel
conv_out_channels (int): output feature map channel
num_grids (list(int)): split img into S*S grids. List for 4x 8x 16x .. feature maps. e.g. [40, 40, 40, 40]
stacked_convs (int): stacked convolution layers number
text_max_length (int): the max length of recognition words.
featmap_indices (list(int)): selected feature map scales.
loss_instance_mask_att (dict): loss function for IMA supervision, which is requried in pretraining stage.
"""
super().__init__()
assert len(num_grids) == len(featmap_indices)
self.in_channels = in_channels
self.conv_out_channels = conv_out_channels
self.text_max_length = text_max_length
self.stacked_convs = stacked_convs
self.fp16_enabled = False
self.num_grids = num_grids
self.featmap_indices = featmap_indices
if loss_instance_mask_att is not None:
self.loss_instance_mask_att = build_loss(loss_instance_mask_att)
self.loss_weight = loss_instance_mask_att['loss_weight']
else:
self.loss_instance_mask_att = None
norm_cfg = dict(type='GN', num_groups=32, requires_grad=True)
self.kernal_convs = nn.ModuleList()
for i in range(self.stacked_convs):
chn = self.in_channels + 2 if i == 0 else self.conv_out_channels
self.kernal_convs.append(
ConvModule(
chn,
self.conv_out_channels,
kernel_size=3,
stride=1,
padding=1,
norm_cfg=norm_cfg,
bias=norm_cfg is None))
self.kernal_out = nn.Conv2d(self.conv_out_channels,
self.conv_out_channels,
kernel_size=1,
padding=0)
def init_weights(self):
""" Weight initialization. """
for kernal_conv in self.kernal_convs:
normal_init(kernal_conv.conv, std=0.01)
normal_init(self.kernal_out, std=0.01)
def forward_single(self, feats, num_grid):
""" Forward of IMA in single level
Args:
feats (Tensor): Input feature map, in shape of [B, C, H, W]
num_grid (int): An int number to indicate grid split numbers
Returns:
Tensor: in shape of [B, S^2, H, W]
"""
kernal_feature = feats
mask_feature = feats
# Calculate x-axis and y-axis coordinate features
x_range = torch.linspace(-1, 1, kernal_feature.shape[-1], device=kernal_feature.device)
y_range = torch.linspace(-1, 1, kernal_feature.shape[-2], device=kernal_feature.device)
y_coord, x_coord = torch.meshgrid(y_range, x_range)
y_coord = y_coord.expand([kernal_feature.shape[0], 1, -1, -1])
x_coord = x_coord.expand([kernal_feature.shape[0], 1, -1, -1])
coord_feature = torch.cat([x_coord, y_coord], 1)
# B x C x H x W -> B x (C+2) x H x W
kernal_feature = torch.cat([kernal_feature, coord_feature], 1)
# Generate dynamic convolution kernel
for idx in range(self.stacked_convs):
if idx == 0:
# B x (C+2) x H x W -> B x (C+2) x S x S
kernal_feature = F.interpolate(kernal_feature,size=num_grid, mode='bilinear')
kernal_feature = self.kernal_convs[idx](kernal_feature)
kernal_feature = self.kernal_out(kernal_feature) # B x C x S x S
batch, channel, height, width = mask_feature.shape
# B x C x H x W -> BC x H x W -> 1 x BC x H x W
mask_feature = mask_feature.contiguous().view(-1, height, width).unsqueeze(0)
# B x K x CL -> BKL x C-> BSS x C x 1 x 1
kernal_feature = kernal_feature.view(-1, channel).unsqueeze(-1).unsqueeze(-1)
mask_pred = F.conv2d(mask_feature, kernal_feature, groups=batch).contiguous().view(batch,
num_grid**2,
height,
width) # B x S^2 x H x W
return mask_pred
@auto_fp16()
def forward(self, feats):
""" Forward of IMA in multiple levels
Args:
feats (list(Tensor)): Input feature maps, in shapes of [B, C, H, W]
num_grid (list(int)): An int number to indicate grid split numbers
Returns:
list(Tensor): in shape of [B, S^2, H, W]
"""
preds = []
for i in range(len(self.featmap_indices)):
pred = self.forward_single(feats[i], self.num_grids[i])
preds.append(pred)
return preds
def get_target_single(self,
gt_poly_bboxes,
matched_bboxes,
feat_size,
stride,
device='cuda'
):
""" Ground-truth generated according to instance level annotations in single level.
Args:
gt_poly_bboxes (list(list(float)): polygon bounding boxes for text instances, in shape of [K, L]
matched_bboxes (Tensor): A tensor of shape [B, S^2] ot indicate grid categories
feat_size (tuple): inpur feature map shape
stride (int): An int number to indicate feature map stride
device (str): computation device, default in 'cuda'
Returns:
Tensor: ground-truth mask in single level, in shape of [B, S^2, H, W]
Returns:
Tensor: channel-wised weight, in shape of [B, S^2]
"""
batch, _, height, width = feat_size
_, num_grids = matched_bboxes.shape
gt_mask = torch.zeros([batch, num_grids, height, width], dtype=torch.uint8, device=device)
mask_weight = torch.zeros([batch, num_grids], dtype=torch.float, device=device)
for batch_id in range(batch):
gt_poly_bbox = gt_poly_bboxes[batch_id]
batch_matched_bboxes = matched_bboxes[batch_id]
for idx, poly_bbox in enumerate(gt_poly_bbox):
# Calculate the valid grid corresponding to text instance
indices = torch.where(batch_matched_bboxes == idx + 1)[0]
if len(indices) == 0:
continue
# Fill gt mask according to the gt_poly_bboxes
poly_bbox = poly_bbox.reshape(-1, 2)
poly_bbox_downsample = (poly_bbox / float(stride)).astype(int)
target_mask = np.zeros((height, width), dtype=np.uint8)
cv2.fillPoly(target_mask, [poly_bbox_downsample], color=1)
target_mask = torch.Tensor(target_mask)
# Assign gt to the corresponding grid
for ind in indices:
gt_mask[batch_id, ind, ...] = target_mask
mask_weight[batch_id, ind] = 1
return gt_mask, mask_weight
def get_target(self, feats, gt_poly_bboxes, matched_bboxes):
""" Ground-truth generated according to instance level annotations in multiple levels.
Args:
feats (list(Tensor)): input feature maps, in shape of [B, C, H, W]
gt_poly_bboxes (list(list(float)): polygon bounding boxes for text instances, in shape of [K, L]
matched_bboxes (list(Tensor)): A tensor of shape [B, S^2] ot indicate grid categories
Returns:
list(tuple(Tensor)): ground-truth mask in single level, in shape of [B, S^2, H, W] and
channel-wised weight, in shape of [B, S^2]
"""
mask_targets = []
for i, stride_idx in enumerate(self.featmap_indices):
stride = 4 * (2 ** stride_idx)
target = self.get_target_single(
gt_poly_bboxes,
matched_bboxes[i],
feats[i].shape,
stride,
device=feats[i].device
)
mask_targets.append(target)
return mask_targets
@force_fp32(apply_to=('mask_preds', ))
def loss(self, mask_preds, mask_targets):
""" Loss computation.
Args:
mask_preds (list(Tensor)): feature map predictions, in shape of [B, S^2, H, W]
mask_targets (list(Tensor)): feature map targets, in shape of [B, S^2]
Returns:
dict: losses in a dict.
"""
loss = dict()
for i, stride_idx in enumerate(self.featmap_indices):
stride = 4 * (2 ** stride_idx)
mask_pred = mask_preds[i]
mask_pred = torch.sigmoid(mask_pred)
_, _, height, width = mask_pred.shape
gt_mask, mask_weight = mask_targets[i]
mask_pred = mask_pred.view(-1, 1, height, width)
gt_mask = gt_mask.view(-1, 1, height, width)
mask_weight = mask_weight.view(-1, 1).unsqueeze(-1).unsqueeze(-1)
loss_mask_att = self.loss_instance_mask_att(mask_pred, gt_mask, weight_in_channel=mask_weight)
loss.update({"loss_ima_{}x".format(stride):loss_mask_att})
return loss | davarocr/davarocr/davar_spotting/models/seg_heads/instance_mask_att_head.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from mmdet.models.builder import build_loss, HEADS
from mmcv.cnn import normal_init
from mmcv.cnn import ConvModule
from mmcv.runner import force_fp32, auto_fp16
import cv2
import numpy as np
@HEADS.register_module()
class InstanceMaskAttentionHead(nn.Module):
""" Inplemenation of IMA in MANGO[1]. Dynamic convolution strategy refers to Solov2 [2].
Ref: [1] MANGO: A Mask Attention Guided One-Staged Text Spotter. AAAI-21.
<https://arxiv.org/abs/2012.04350>`_
[2] SOLOv2: Dynamic, Faster and Stronger, NeurIPS-20
<https://arxiv.org/abs/2003.10152>`_
"""
def __init__(self,
in_channels,
conv_out_channels,
num_grids,
stacked_convs=4,
text_max_length=25,
featmap_indices=(0, 1, 2, 3),
loss_instance_mask_att=None,
):
"""
Args:
in_channels (int): input feature map channel
conv_out_channels (int): output feature map channel
num_grids (list(int)): split img into S*S grids. List for 4x 8x 16x .. feature maps. e.g. [40, 40, 40, 40]
stacked_convs (int): stacked convolution layers number
text_max_length (int): the max length of recognition words.
featmap_indices (list(int)): selected feature map scales.
loss_instance_mask_att (dict): loss function for IMA supervision, which is requried in pretraining stage.
"""
super().__init__()
assert len(num_grids) == len(featmap_indices)
self.in_channels = in_channels
self.conv_out_channels = conv_out_channels
self.text_max_length = text_max_length
self.stacked_convs = stacked_convs
self.fp16_enabled = False
self.num_grids = num_grids
self.featmap_indices = featmap_indices
if loss_instance_mask_att is not None:
self.loss_instance_mask_att = build_loss(loss_instance_mask_att)
self.loss_weight = loss_instance_mask_att['loss_weight']
else:
self.loss_instance_mask_att = None
norm_cfg = dict(type='GN', num_groups=32, requires_grad=True)
self.kernal_convs = nn.ModuleList()
for i in range(self.stacked_convs):
chn = self.in_channels + 2 if i == 0 else self.conv_out_channels
self.kernal_convs.append(
ConvModule(
chn,
self.conv_out_channels,
kernel_size=3,
stride=1,
padding=1,
norm_cfg=norm_cfg,
bias=norm_cfg is None))
self.kernal_out = nn.Conv2d(self.conv_out_channels,
self.conv_out_channels,
kernel_size=1,
padding=0)
def init_weights(self):
""" Weight initialization. """
for kernal_conv in self.kernal_convs:
normal_init(kernal_conv.conv, std=0.01)
normal_init(self.kernal_out, std=0.01)
def forward_single(self, feats, num_grid):
""" Forward of IMA in single level
Args:
feats (Tensor): Input feature map, in shape of [B, C, H, W]
num_grid (int): An int number to indicate grid split numbers
Returns:
Tensor: in shape of [B, S^2, H, W]
"""
kernal_feature = feats
mask_feature = feats
# Calculate x-axis and y-axis coordinate features
x_range = torch.linspace(-1, 1, kernal_feature.shape[-1], device=kernal_feature.device)
y_range = torch.linspace(-1, 1, kernal_feature.shape[-2], device=kernal_feature.device)
y_coord, x_coord = torch.meshgrid(y_range, x_range)
y_coord = y_coord.expand([kernal_feature.shape[0], 1, -1, -1])
x_coord = x_coord.expand([kernal_feature.shape[0], 1, -1, -1])
coord_feature = torch.cat([x_coord, y_coord], 1)
# B x C x H x W -> B x (C+2) x H x W
kernal_feature = torch.cat([kernal_feature, coord_feature], 1)
# Generate dynamic convolution kernel
for idx in range(self.stacked_convs):
if idx == 0:
# B x (C+2) x H x W -> B x (C+2) x S x S
kernal_feature = F.interpolate(kernal_feature,size=num_grid, mode='bilinear')
kernal_feature = self.kernal_convs[idx](kernal_feature)
kernal_feature = self.kernal_out(kernal_feature) # B x C x S x S
batch, channel, height, width = mask_feature.shape
# B x C x H x W -> BC x H x W -> 1 x BC x H x W
mask_feature = mask_feature.contiguous().view(-1, height, width).unsqueeze(0)
# B x K x CL -> BKL x C-> BSS x C x 1 x 1
kernal_feature = kernal_feature.view(-1, channel).unsqueeze(-1).unsqueeze(-1)
mask_pred = F.conv2d(mask_feature, kernal_feature, groups=batch).contiguous().view(batch,
num_grid**2,
height,
width) # B x S^2 x H x W
return mask_pred
@auto_fp16()
def forward(self, feats):
""" Forward of IMA in multiple levels
Args:
feats (list(Tensor)): Input feature maps, in shapes of [B, C, H, W]
num_grid (list(int)): An int number to indicate grid split numbers
Returns:
list(Tensor): in shape of [B, S^2, H, W]
"""
preds = []
for i in range(len(self.featmap_indices)):
pred = self.forward_single(feats[i], self.num_grids[i])
preds.append(pred)
return preds
def get_target_single(self,
gt_poly_bboxes,
matched_bboxes,
feat_size,
stride,
device='cuda'
):
""" Ground-truth generated according to instance level annotations in single level.
Args:
gt_poly_bboxes (list(list(float)): polygon bounding boxes for text instances, in shape of [K, L]
matched_bboxes (Tensor): A tensor of shape [B, S^2] ot indicate grid categories
feat_size (tuple): inpur feature map shape
stride (int): An int number to indicate feature map stride
device (str): computation device, default in 'cuda'
Returns:
Tensor: ground-truth mask in single level, in shape of [B, S^2, H, W]
Returns:
Tensor: channel-wised weight, in shape of [B, S^2]
"""
batch, _, height, width = feat_size
_, num_grids = matched_bboxes.shape
gt_mask = torch.zeros([batch, num_grids, height, width], dtype=torch.uint8, device=device)
mask_weight = torch.zeros([batch, num_grids], dtype=torch.float, device=device)
for batch_id in range(batch):
gt_poly_bbox = gt_poly_bboxes[batch_id]
batch_matched_bboxes = matched_bboxes[batch_id]
for idx, poly_bbox in enumerate(gt_poly_bbox):
# Calculate the valid grid corresponding to text instance
indices = torch.where(batch_matched_bboxes == idx + 1)[0]
if len(indices) == 0:
continue
# Fill gt mask according to the gt_poly_bboxes
poly_bbox = poly_bbox.reshape(-1, 2)
poly_bbox_downsample = (poly_bbox / float(stride)).astype(int)
target_mask = np.zeros((height, width), dtype=np.uint8)
cv2.fillPoly(target_mask, [poly_bbox_downsample], color=1)
target_mask = torch.Tensor(target_mask)
# Assign gt to the corresponding grid
for ind in indices:
gt_mask[batch_id, ind, ...] = target_mask
mask_weight[batch_id, ind] = 1
return gt_mask, mask_weight
def get_target(self, feats, gt_poly_bboxes, matched_bboxes):
""" Ground-truth generated according to instance level annotations in multiple levels.
Args:
feats (list(Tensor)): input feature maps, in shape of [B, C, H, W]
gt_poly_bboxes (list(list(float)): polygon bounding boxes for text instances, in shape of [K, L]
matched_bboxes (list(Tensor)): A tensor of shape [B, S^2] ot indicate grid categories
Returns:
list(tuple(Tensor)): ground-truth mask in single level, in shape of [B, S^2, H, W] and
channel-wised weight, in shape of [B, S^2]
"""
mask_targets = []
for i, stride_idx in enumerate(self.featmap_indices):
stride = 4 * (2 ** stride_idx)
target = self.get_target_single(
gt_poly_bboxes,
matched_bboxes[i],
feats[i].shape,
stride,
device=feats[i].device
)
mask_targets.append(target)
return mask_targets
@force_fp32(apply_to=('mask_preds', ))
def loss(self, mask_preds, mask_targets):
""" Loss computation.
Args:
mask_preds (list(Tensor)): feature map predictions, in shape of [B, S^2, H, W]
mask_targets (list(Tensor)): feature map targets, in shape of [B, S^2]
Returns:
dict: losses in a dict.
"""
loss = dict()
for i, stride_idx in enumerate(self.featmap_indices):
stride = 4 * (2 ** stride_idx)
mask_pred = mask_preds[i]
mask_pred = torch.sigmoid(mask_pred)
_, _, height, width = mask_pred.shape
gt_mask, mask_weight = mask_targets[i]
mask_pred = mask_pred.view(-1, 1, height, width)
gt_mask = gt_mask.view(-1, 1, height, width)
mask_weight = mask_weight.view(-1, 1).unsqueeze(-1).unsqueeze(-1)
loss_mask_att = self.loss_instance_mask_att(mask_pred, gt_mask, weight_in_channel=mask_weight)
loss.update({"loss_ima_{}x".format(stride):loss_mask_att})
return loss | 0.947003 | 0.525734 |
import pprint
import re # noqa: F401
import six
class ItemCounts(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
swagger_types = {
'movie_count': 'int',
'series_count': 'int',
'episode_count': 'int',
'game_count': 'int',
'artist_count': 'int',
'program_count': 'int',
'game_system_count': 'int',
'trailer_count': 'int',
'song_count': 'int',
'album_count': 'int',
'music_video_count': 'int',
'box_set_count': 'int',
'book_count': 'int',
'item_count': 'int'
}
attribute_map = {
'movie_count': 'MovieCount',
'series_count': 'SeriesCount',
'episode_count': 'EpisodeCount',
'game_count': 'GameCount',
'artist_count': 'ArtistCount',
'program_count': 'ProgramCount',
'game_system_count': 'GameSystemCount',
'trailer_count': 'TrailerCount',
'song_count': 'SongCount',
'album_count': 'AlbumCount',
'music_video_count': 'MusicVideoCount',
'box_set_count': 'BoxSetCount',
'book_count': 'BookCount',
'item_count': 'ItemCount'
}
def __init__(self, movie_count=None, series_count=None, episode_count=None, game_count=None, artist_count=None, program_count=None, game_system_count=None, trailer_count=None, song_count=None, album_count=None, music_video_count=None, box_set_count=None, book_count=None, item_count=None): # noqa: E501
"""ItemCounts - a model defined in Swagger""" # noqa: E501
self._movie_count = None
self._series_count = None
self._episode_count = None
self._game_count = None
self._artist_count = None
self._program_count = None
self._game_system_count = None
self._trailer_count = None
self._song_count = None
self._album_count = None
self._music_video_count = None
self._box_set_count = None
self._book_count = None
self._item_count = None
self.discriminator = None
if movie_count is not None:
self.movie_count = movie_count
if series_count is not None:
self.series_count = series_count
if episode_count is not None:
self.episode_count = episode_count
if game_count is not None:
self.game_count = game_count
if artist_count is not None:
self.artist_count = artist_count
if program_count is not None:
self.program_count = program_count
if game_system_count is not None:
self.game_system_count = game_system_count
if trailer_count is not None:
self.trailer_count = trailer_count
if song_count is not None:
self.song_count = song_count
if album_count is not None:
self.album_count = album_count
if music_video_count is not None:
self.music_video_count = music_video_count
if box_set_count is not None:
self.box_set_count = box_set_count
if book_count is not None:
self.book_count = book_count
if item_count is not None:
self.item_count = item_count
@property
def movie_count(self):
"""Gets the movie_count of this ItemCounts. # noqa: E501
:return: The movie_count of this ItemCounts. # noqa: E501
:rtype: int
"""
return self._movie_count
@movie_count.setter
def movie_count(self, movie_count):
"""Sets the movie_count of this ItemCounts.
:param movie_count: The movie_count of this ItemCounts. # noqa: E501
:type: int
"""
self._movie_count = movie_count
@property
def series_count(self):
"""Gets the series_count of this ItemCounts. # noqa: E501
:return: The series_count of this ItemCounts. # noqa: E501
:rtype: int
"""
return self._series_count
@series_count.setter
def series_count(self, series_count):
"""Sets the series_count of this ItemCounts.
:param series_count: The series_count of this ItemCounts. # noqa: E501
:type: int
"""
self._series_count = series_count
@property
def episode_count(self):
"""Gets the episode_count of this ItemCounts. # noqa: E501
:return: The episode_count of this ItemCounts. # noqa: E501
:rtype: int
"""
return self._episode_count
@episode_count.setter
def episode_count(self, episode_count):
"""Sets the episode_count of this ItemCounts.
:param episode_count: The episode_count of this ItemCounts. # noqa: E501
:type: int
"""
self._episode_count = episode_count
@property
def game_count(self):
"""Gets the game_count of this ItemCounts. # noqa: E501
:return: The game_count of this ItemCounts. # noqa: E501
:rtype: int
"""
return self._game_count
@game_count.setter
def game_count(self, game_count):
"""Sets the game_count of this ItemCounts.
:param game_count: The game_count of this ItemCounts. # noqa: E501
:type: int
"""
self._game_count = game_count
@property
def artist_count(self):
"""Gets the artist_count of this ItemCounts. # noqa: E501
:return: The artist_count of this ItemCounts. # noqa: E501
:rtype: int
"""
return self._artist_count
@artist_count.setter
def artist_count(self, artist_count):
"""Sets the artist_count of this ItemCounts.
:param artist_count: The artist_count of this ItemCounts. # noqa: E501
:type: int
"""
self._artist_count = artist_count
@property
def program_count(self):
"""Gets the program_count of this ItemCounts. # noqa: E501
:return: The program_count of this ItemCounts. # noqa: E501
:rtype: int
"""
return self._program_count
@program_count.setter
def program_count(self, program_count):
"""Sets the program_count of this ItemCounts.
:param program_count: The program_count of this ItemCounts. # noqa: E501
:type: int
"""
self._program_count = program_count
@property
def game_system_count(self):
"""Gets the game_system_count of this ItemCounts. # noqa: E501
:return: The game_system_count of this ItemCounts. # noqa: E501
:rtype: int
"""
return self._game_system_count
@game_system_count.setter
def game_system_count(self, game_system_count):
"""Sets the game_system_count of this ItemCounts.
:param game_system_count: The game_system_count of this ItemCounts. # noqa: E501
:type: int
"""
self._game_system_count = game_system_count
@property
def trailer_count(self):
"""Gets the trailer_count of this ItemCounts. # noqa: E501
:return: The trailer_count of this ItemCounts. # noqa: E501
:rtype: int
"""
return self._trailer_count
@trailer_count.setter
def trailer_count(self, trailer_count):
"""Sets the trailer_count of this ItemCounts.
:param trailer_count: The trailer_count of this ItemCounts. # noqa: E501
:type: int
"""
self._trailer_count = trailer_count
@property
def song_count(self):
"""Gets the song_count of this ItemCounts. # noqa: E501
:return: The song_count of this ItemCounts. # noqa: E501
:rtype: int
"""
return self._song_count
@song_count.setter
def song_count(self, song_count):
"""Sets the song_count of this ItemCounts.
:param song_count: The song_count of this ItemCounts. # noqa: E501
:type: int
"""
self._song_count = song_count
@property
def album_count(self):
"""Gets the album_count of this ItemCounts. # noqa: E501
:return: The album_count of this ItemCounts. # noqa: E501
:rtype: int
"""
return self._album_count
@album_count.setter
def album_count(self, album_count):
"""Sets the album_count of this ItemCounts.
:param album_count: The album_count of this ItemCounts. # noqa: E501
:type: int
"""
self._album_count = album_count
@property
def music_video_count(self):
"""Gets the music_video_count of this ItemCounts. # noqa: E501
:return: The music_video_count of this ItemCounts. # noqa: E501
:rtype: int
"""
return self._music_video_count
@music_video_count.setter
def music_video_count(self, music_video_count):
"""Sets the music_video_count of this ItemCounts.
:param music_video_count: The music_video_count of this ItemCounts. # noqa: E501
:type: int
"""
self._music_video_count = music_video_count
@property
def box_set_count(self):
"""Gets the box_set_count of this ItemCounts. # noqa: E501
:return: The box_set_count of this ItemCounts. # noqa: E501
:rtype: int
"""
return self._box_set_count
@box_set_count.setter
def box_set_count(self, box_set_count):
"""Sets the box_set_count of this ItemCounts.
:param box_set_count: The box_set_count of this ItemCounts. # noqa: E501
:type: int
"""
self._box_set_count = box_set_count
@property
def book_count(self):
"""Gets the book_count of this ItemCounts. # noqa: E501
:return: The book_count of this ItemCounts. # noqa: E501
:rtype: int
"""
return self._book_count
@book_count.setter
def book_count(self, book_count):
"""Sets the book_count of this ItemCounts.
:param book_count: The book_count of this ItemCounts. # noqa: E501
:type: int
"""
self._book_count = book_count
@property
def item_count(self):
"""Gets the item_count of this ItemCounts. # noqa: E501
:return: The item_count of this ItemCounts. # noqa: E501
:rtype: int
"""
return self._item_count
@item_count.setter
def item_count(self, item_count):
"""Sets the item_count of this ItemCounts.
:param item_count: The item_count of this ItemCounts. # noqa: E501
:type: int
"""
self._item_count = item_count
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
if issubclass(ItemCounts, dict):
for key, value in self.items():
result[key] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, ItemCounts):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other | embyapi/models/item_counts.py | import pprint
import re # noqa: F401
import six
class ItemCounts(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
swagger_types = {
'movie_count': 'int',
'series_count': 'int',
'episode_count': 'int',
'game_count': 'int',
'artist_count': 'int',
'program_count': 'int',
'game_system_count': 'int',
'trailer_count': 'int',
'song_count': 'int',
'album_count': 'int',
'music_video_count': 'int',
'box_set_count': 'int',
'book_count': 'int',
'item_count': 'int'
}
attribute_map = {
'movie_count': 'MovieCount',
'series_count': 'SeriesCount',
'episode_count': 'EpisodeCount',
'game_count': 'GameCount',
'artist_count': 'ArtistCount',
'program_count': 'ProgramCount',
'game_system_count': 'GameSystemCount',
'trailer_count': 'TrailerCount',
'song_count': 'SongCount',
'album_count': 'AlbumCount',
'music_video_count': 'MusicVideoCount',
'box_set_count': 'BoxSetCount',
'book_count': 'BookCount',
'item_count': 'ItemCount'
}
def __init__(self, movie_count=None, series_count=None, episode_count=None, game_count=None, artist_count=None, program_count=None, game_system_count=None, trailer_count=None, song_count=None, album_count=None, music_video_count=None, box_set_count=None, book_count=None, item_count=None): # noqa: E501
"""ItemCounts - a model defined in Swagger""" # noqa: E501
self._movie_count = None
self._series_count = None
self._episode_count = None
self._game_count = None
self._artist_count = None
self._program_count = None
self._game_system_count = None
self._trailer_count = None
self._song_count = None
self._album_count = None
self._music_video_count = None
self._box_set_count = None
self._book_count = None
self._item_count = None
self.discriminator = None
if movie_count is not None:
self.movie_count = movie_count
if series_count is not None:
self.series_count = series_count
if episode_count is not None:
self.episode_count = episode_count
if game_count is not None:
self.game_count = game_count
if artist_count is not None:
self.artist_count = artist_count
if program_count is not None:
self.program_count = program_count
if game_system_count is not None:
self.game_system_count = game_system_count
if trailer_count is not None:
self.trailer_count = trailer_count
if song_count is not None:
self.song_count = song_count
if album_count is not None:
self.album_count = album_count
if music_video_count is not None:
self.music_video_count = music_video_count
if box_set_count is not None:
self.box_set_count = box_set_count
if book_count is not None:
self.book_count = book_count
if item_count is not None:
self.item_count = item_count
@property
def movie_count(self):
"""Gets the movie_count of this ItemCounts. # noqa: E501
:return: The movie_count of this ItemCounts. # noqa: E501
:rtype: int
"""
return self._movie_count
@movie_count.setter
def movie_count(self, movie_count):
"""Sets the movie_count of this ItemCounts.
:param movie_count: The movie_count of this ItemCounts. # noqa: E501
:type: int
"""
self._movie_count = movie_count
@property
def series_count(self):
"""Gets the series_count of this ItemCounts. # noqa: E501
:return: The series_count of this ItemCounts. # noqa: E501
:rtype: int
"""
return self._series_count
@series_count.setter
def series_count(self, series_count):
"""Sets the series_count of this ItemCounts.
:param series_count: The series_count of this ItemCounts. # noqa: E501
:type: int
"""
self._series_count = series_count
@property
def episode_count(self):
"""Gets the episode_count of this ItemCounts. # noqa: E501
:return: The episode_count of this ItemCounts. # noqa: E501
:rtype: int
"""
return self._episode_count
@episode_count.setter
def episode_count(self, episode_count):
"""Sets the episode_count of this ItemCounts.
:param episode_count: The episode_count of this ItemCounts. # noqa: E501
:type: int
"""
self._episode_count = episode_count
@property
def game_count(self):
"""Gets the game_count of this ItemCounts. # noqa: E501
:return: The game_count of this ItemCounts. # noqa: E501
:rtype: int
"""
return self._game_count
@game_count.setter
def game_count(self, game_count):
"""Sets the game_count of this ItemCounts.
:param game_count: The game_count of this ItemCounts. # noqa: E501
:type: int
"""
self._game_count = game_count
@property
def artist_count(self):
"""Gets the artist_count of this ItemCounts. # noqa: E501
:return: The artist_count of this ItemCounts. # noqa: E501
:rtype: int
"""
return self._artist_count
@artist_count.setter
def artist_count(self, artist_count):
"""Sets the artist_count of this ItemCounts.
:param artist_count: The artist_count of this ItemCounts. # noqa: E501
:type: int
"""
self._artist_count = artist_count
@property
def program_count(self):
"""Gets the program_count of this ItemCounts. # noqa: E501
:return: The program_count of this ItemCounts. # noqa: E501
:rtype: int
"""
return self._program_count
@program_count.setter
def program_count(self, program_count):
"""Sets the program_count of this ItemCounts.
:param program_count: The program_count of this ItemCounts. # noqa: E501
:type: int
"""
self._program_count = program_count
@property
def game_system_count(self):
"""Gets the game_system_count of this ItemCounts. # noqa: E501
:return: The game_system_count of this ItemCounts. # noqa: E501
:rtype: int
"""
return self._game_system_count
@game_system_count.setter
def game_system_count(self, game_system_count):
"""Sets the game_system_count of this ItemCounts.
:param game_system_count: The game_system_count of this ItemCounts. # noqa: E501
:type: int
"""
self._game_system_count = game_system_count
@property
def trailer_count(self):
"""Gets the trailer_count of this ItemCounts. # noqa: E501
:return: The trailer_count of this ItemCounts. # noqa: E501
:rtype: int
"""
return self._trailer_count
@trailer_count.setter
def trailer_count(self, trailer_count):
"""Sets the trailer_count of this ItemCounts.
:param trailer_count: The trailer_count of this ItemCounts. # noqa: E501
:type: int
"""
self._trailer_count = trailer_count
@property
def song_count(self):
"""Gets the song_count of this ItemCounts. # noqa: E501
:return: The song_count of this ItemCounts. # noqa: E501
:rtype: int
"""
return self._song_count
@song_count.setter
def song_count(self, song_count):
"""Sets the song_count of this ItemCounts.
:param song_count: The song_count of this ItemCounts. # noqa: E501
:type: int
"""
self._song_count = song_count
@property
def album_count(self):
"""Gets the album_count of this ItemCounts. # noqa: E501
:return: The album_count of this ItemCounts. # noqa: E501
:rtype: int
"""
return self._album_count
@album_count.setter
def album_count(self, album_count):
"""Sets the album_count of this ItemCounts.
:param album_count: The album_count of this ItemCounts. # noqa: E501
:type: int
"""
self._album_count = album_count
@property
def music_video_count(self):
"""Gets the music_video_count of this ItemCounts. # noqa: E501
:return: The music_video_count of this ItemCounts. # noqa: E501
:rtype: int
"""
return self._music_video_count
@music_video_count.setter
def music_video_count(self, music_video_count):
"""Sets the music_video_count of this ItemCounts.
:param music_video_count: The music_video_count of this ItemCounts. # noqa: E501
:type: int
"""
self._music_video_count = music_video_count
@property
def box_set_count(self):
"""Gets the box_set_count of this ItemCounts. # noqa: E501
:return: The box_set_count of this ItemCounts. # noqa: E501
:rtype: int
"""
return self._box_set_count
@box_set_count.setter
def box_set_count(self, box_set_count):
"""Sets the box_set_count of this ItemCounts.
:param box_set_count: The box_set_count of this ItemCounts. # noqa: E501
:type: int
"""
self._box_set_count = box_set_count
@property
def book_count(self):
"""Gets the book_count of this ItemCounts. # noqa: E501
:return: The book_count of this ItemCounts. # noqa: E501
:rtype: int
"""
return self._book_count
@book_count.setter
def book_count(self, book_count):
"""Sets the book_count of this ItemCounts.
:param book_count: The book_count of this ItemCounts. # noqa: E501
:type: int
"""
self._book_count = book_count
@property
def item_count(self):
"""Gets the item_count of this ItemCounts. # noqa: E501
:return: The item_count of this ItemCounts. # noqa: E501
:rtype: int
"""
return self._item_count
@item_count.setter
def item_count(self, item_count):
"""Sets the item_count of this ItemCounts.
:param item_count: The item_count of this ItemCounts. # noqa: E501
:type: int
"""
self._item_count = item_count
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
if issubclass(ItemCounts, dict):
for key, value in self.items():
result[key] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, ItemCounts):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other | 0.621311 | 0.103386 |
class SketchKnowledgeBase(object):
'''
SketchKnowledgeBase
'''
def __init__(self):
super(SketchKnowledgeBase, self).__init__()
self.entities = {}
self.actions = {}
# Reversed IS-A actions
self.asi = {}
self._idcounter = {}
def add_entity(self, entity):
self.entities[entity.name] = entity
for p in entity.isa:
if p in self.asi:
self.asi[p].append(entity.name)
else:
self.asi[p] = [entity.name]
def add_action(self, act):
unqid = self._unique_act_id(act.name)
self.actions[unqid] = act
for p in act.isa:
punqid = self._unique_act_id(p)
if p in self.asi:
self.asi[punqid].append(unqid)
else:
self.asi[punqid] = [unqid]
def _unique_act_id(self, actname):
if actname not in self._idcounter:
self._idcounter[actname] = -1
self._idcounter[actname] += 1
return actname + str(self._idcounter[actname])
def __str__(self):
return '(\n ENTITIES:\n ' + str(self.entities) + '\n ACTIONS:\n ' + str(self.actions) + '\n)\n'
class SNEntity(object):
'''
SketchNet Entity
'''
def __init__(self, name, sketch, isa=[], partof=[]):
super(SNEntity, self).__init__()
self.name, self.sketch, self.isa, self.partof = \
name, sketch, isa, partof
def __repr__(self):
# Strips str(self.isa) of ' characters
return '<SNE:' + self.name + '::' + str(self.isa).replace("'", "") + '>'
def __str__(self):
return self.__repr__()
class SNAction(object):
'''
Action over SketchNet entities
'''
def __init__(self, name, components, sketch, isa=[], partof=[]):
super(SNAction, self).__init__()
self.name, self.components, self.sketch, self.isa, self.partof = \
name, components, sketch, isa, partof
def __repr__(self):
# Strips list reprs of ' characters
return '<SNR:' + self.name + '(' + str(self.components)[1:-1].replace("'", "") + ')::' + str(self.isa).replace("'", "") + '>'
def __str__(self):
return self.__repr__() | knowledge_repr.py | class SketchKnowledgeBase(object):
'''
SketchKnowledgeBase
'''
def __init__(self):
super(SketchKnowledgeBase, self).__init__()
self.entities = {}
self.actions = {}
# Reversed IS-A actions
self.asi = {}
self._idcounter = {}
def add_entity(self, entity):
self.entities[entity.name] = entity
for p in entity.isa:
if p in self.asi:
self.asi[p].append(entity.name)
else:
self.asi[p] = [entity.name]
def add_action(self, act):
unqid = self._unique_act_id(act.name)
self.actions[unqid] = act
for p in act.isa:
punqid = self._unique_act_id(p)
if p in self.asi:
self.asi[punqid].append(unqid)
else:
self.asi[punqid] = [unqid]
def _unique_act_id(self, actname):
if actname not in self._idcounter:
self._idcounter[actname] = -1
self._idcounter[actname] += 1
return actname + str(self._idcounter[actname])
def __str__(self):
return '(\n ENTITIES:\n ' + str(self.entities) + '\n ACTIONS:\n ' + str(self.actions) + '\n)\n'
class SNEntity(object):
'''
SketchNet Entity
'''
def __init__(self, name, sketch, isa=[], partof=[]):
super(SNEntity, self).__init__()
self.name, self.sketch, self.isa, self.partof = \
name, sketch, isa, partof
def __repr__(self):
# Strips str(self.isa) of ' characters
return '<SNE:' + self.name + '::' + str(self.isa).replace("'", "") + '>'
def __str__(self):
return self.__repr__()
class SNAction(object):
'''
Action over SketchNet entities
'''
def __init__(self, name, components, sketch, isa=[], partof=[]):
super(SNAction, self).__init__()
self.name, self.components, self.sketch, self.isa, self.partof = \
name, components, sketch, isa, partof
def __repr__(self):
# Strips list reprs of ' characters
return '<SNR:' + self.name + '(' + str(self.components)[1:-1].replace("'", "") + ')::' + str(self.isa).replace("'", "") + '>'
def __str__(self):
return self.__repr__() | 0.414425 | 0.141252 |
from ..builder import DETECTORS
from .gl_two_stage import GLTwoStage
import torch
import torch.nn as nn
import cv2
import numpy as np
import mmcv
@DETECTORS.register_module
class GlobalGLGA(GLTwoStage):
def __init__(self,
p_size,
batch_size,
mode,
ori_shape,
rpn_head,
roi_head,
train_cfg,
test_cfg,
neck=None,
pretrained=None):
super(GlobalGLGA, self).__init__(
mode=mode,
neck=neck,
rpn_head=rpn_head,
roi_head=roi_head,
train_cfg=train_cfg,
test_cfg=test_cfg,
pretrained=pretrained)
self.batch_size = batch_size
self.p_size = p_size
self.ori_shape = ori_shape
def extract_feat(self, img):
"""Directly extract features from the backbone+neck."""
x = self.neck(img, None, None, None, mode=self.MODE)
return x
def forward_train(self,
img,
img_metas,
gt_bboxes,
gt_labels,
gt_bboxes_ignore=None,
gt_masks=None,
proposals=None,
**kwargs):
if self.MODE == 1:
x = self.neck(img, None, None, None, mode=self.MODE)
elif self.MODE == 3:
input_img = cv2.imread(img_metas[0]['filename'])
input_img = input_img.astype(np.float32)
input_img, scale_factor = self.img_resize(input_img, self.ori_shape)
patches, coordinates, templates, sizes, ratios = \
self.global_to_patch(input_img, self.p_size)
x = self.neck(img, patches, coordinates, ratios, templates, mode=self.MODE)
else:
raise ValueError('In global mode,mode should be 1 or 3 ...')
losses = dict()
# RPN forward and loss
if self.with_rpn:
proposal_cfg = self.train_cfg.get('rpn_proposal',
self.test_cfg.rpn)
rpn_losses, proposal_list = self.rpn_head.forward_train(x,
img_metas,
gt_bboxes,
gt_labels=None,
gt_bboxes_ignore=gt_bboxes_ignore,
proposal_cfg=proposal_cfg)
losses.update(rpn_losses)
else:
proposal_list = proposals
# ROI forward and loss
roi_losses = self.roi_head.forward_train(x, img_metas, proposal_list,
gt_bboxes, gt_labels,
gt_bboxes_ignore, gt_masks,
**kwargs)
losses.update(roi_losses)
return losses
def simple_test(self, img, img_metas, proposals=None, rescale=False, **kwargs):
"""Test without augmentation."""
assert self.with_bbox, 'Bbox head must be implemented.'
import numpy as np
if self.MODE == 1:
x = self.neck(img, None, None, None, mode=self.MODE)
elif self.MODE == 3:
input_img = cv2.imread(img_metas[0]['filename'])
input_img = input_img.astype(np.float32)
input_img, scale_factor = self.img_resize(input_img, self.ori_shape)
patches, coordinates, templates, sizes, ratios = self.global_to_patch(input_img, self.p_size)
x = self.neck(img, patches, coordinates, ratios, templates, mode=self.MODE)
else:
raise ValueError('wrong mode:{}'.format(self.MODE))
# get origin input shape to onnx dynamic input shape
if torch.onnx.is_in_onnx_export():
img_shape = torch._shape_as_tensor(img)[2:]
img_metas[0]['img_shape_for_onnx'] = img_shape
if proposals is None:
proposal_list = self.rpn_head.simple_test_rpn(x, img_metas)
else:
proposal_list = proposals
# ------------------------------------------------------------------------------------
if self.assess_proposal_quality:
from mmdet.core.bbox.iou_calculators import build_iou_calculator
import numpy as np
gt_bboxes = kwargs['gt_bboxes'][0][0]
bboxes = proposal_list[0]
iou_calculator = dict(type='BboxOverlaps2D')
iou_calculator = build_iou_calculator(iou_calculator)
if len(gt_bboxes) != 0:
overlaps = iou_calculator(gt_bboxes, bboxes)
max_overlaps, _ = overlaps.max(dim=0)
max_overlaps = max_overlaps.cpu().numpy()
idx = max_overlaps >= 0.5
max_overlaps = max_overlaps[idx].tolist()
self.matched_proposal.extend(max_overlaps)
# ------------------------------------------------------------------------------------
return self.roi_head.simple_test(
x, proposal_list, img_metas, rescale=rescale)
def img_resize(self, img, size):
# img = (img[0].cpu()).numpy()
# img = img.transpose(1, 2, 0)
img, w_scale, h_scale = mmcv.imresize(
img, size, return_scale=True)
# img = img.transpose(2, 0, 1)
scale_factor = np.array([w_scale, h_scale, w_scale, h_scale],
dtype=np.float32)
mean = np.array([123.675, 116.28, 103.53], dtype=np.float32)
std = np.array([58.395, 57.12, 57.375], dtype=np.float32)
img = mmcv.imnormalize(img, mean, std, True)
img = img.transpose(2, 0, 1) # img = bgr2rgb(img)
img = torch.from_numpy(img).cuda()
img = img.unsqueeze(0)
return img, scale_factor | mmdet/models/detectors/global_gl_ga.py | from ..builder import DETECTORS
from .gl_two_stage import GLTwoStage
import torch
import torch.nn as nn
import cv2
import numpy as np
import mmcv
@DETECTORS.register_module
class GlobalGLGA(GLTwoStage):
def __init__(self,
p_size,
batch_size,
mode,
ori_shape,
rpn_head,
roi_head,
train_cfg,
test_cfg,
neck=None,
pretrained=None):
super(GlobalGLGA, self).__init__(
mode=mode,
neck=neck,
rpn_head=rpn_head,
roi_head=roi_head,
train_cfg=train_cfg,
test_cfg=test_cfg,
pretrained=pretrained)
self.batch_size = batch_size
self.p_size = p_size
self.ori_shape = ori_shape
def extract_feat(self, img):
"""Directly extract features from the backbone+neck."""
x = self.neck(img, None, None, None, mode=self.MODE)
return x
def forward_train(self,
img,
img_metas,
gt_bboxes,
gt_labels,
gt_bboxes_ignore=None,
gt_masks=None,
proposals=None,
**kwargs):
if self.MODE == 1:
x = self.neck(img, None, None, None, mode=self.MODE)
elif self.MODE == 3:
input_img = cv2.imread(img_metas[0]['filename'])
input_img = input_img.astype(np.float32)
input_img, scale_factor = self.img_resize(input_img, self.ori_shape)
patches, coordinates, templates, sizes, ratios = \
self.global_to_patch(input_img, self.p_size)
x = self.neck(img, patches, coordinates, ratios, templates, mode=self.MODE)
else:
raise ValueError('In global mode,mode should be 1 or 3 ...')
losses = dict()
# RPN forward and loss
if self.with_rpn:
proposal_cfg = self.train_cfg.get('rpn_proposal',
self.test_cfg.rpn)
rpn_losses, proposal_list = self.rpn_head.forward_train(x,
img_metas,
gt_bboxes,
gt_labels=None,
gt_bboxes_ignore=gt_bboxes_ignore,
proposal_cfg=proposal_cfg)
losses.update(rpn_losses)
else:
proposal_list = proposals
# ROI forward and loss
roi_losses = self.roi_head.forward_train(x, img_metas, proposal_list,
gt_bboxes, gt_labels,
gt_bboxes_ignore, gt_masks,
**kwargs)
losses.update(roi_losses)
return losses
def simple_test(self, img, img_metas, proposals=None, rescale=False, **kwargs):
"""Test without augmentation."""
assert self.with_bbox, 'Bbox head must be implemented.'
import numpy as np
if self.MODE == 1:
x = self.neck(img, None, None, None, mode=self.MODE)
elif self.MODE == 3:
input_img = cv2.imread(img_metas[0]['filename'])
input_img = input_img.astype(np.float32)
input_img, scale_factor = self.img_resize(input_img, self.ori_shape)
patches, coordinates, templates, sizes, ratios = self.global_to_patch(input_img, self.p_size)
x = self.neck(img, patches, coordinates, ratios, templates, mode=self.MODE)
else:
raise ValueError('wrong mode:{}'.format(self.MODE))
# get origin input shape to onnx dynamic input shape
if torch.onnx.is_in_onnx_export():
img_shape = torch._shape_as_tensor(img)[2:]
img_metas[0]['img_shape_for_onnx'] = img_shape
if proposals is None:
proposal_list = self.rpn_head.simple_test_rpn(x, img_metas)
else:
proposal_list = proposals
# ------------------------------------------------------------------------------------
if self.assess_proposal_quality:
from mmdet.core.bbox.iou_calculators import build_iou_calculator
import numpy as np
gt_bboxes = kwargs['gt_bboxes'][0][0]
bboxes = proposal_list[0]
iou_calculator = dict(type='BboxOverlaps2D')
iou_calculator = build_iou_calculator(iou_calculator)
if len(gt_bboxes) != 0:
overlaps = iou_calculator(gt_bboxes, bboxes)
max_overlaps, _ = overlaps.max(dim=0)
max_overlaps = max_overlaps.cpu().numpy()
idx = max_overlaps >= 0.5
max_overlaps = max_overlaps[idx].tolist()
self.matched_proposal.extend(max_overlaps)
# ------------------------------------------------------------------------------------
return self.roi_head.simple_test(
x, proposal_list, img_metas, rescale=rescale)
def img_resize(self, img, size):
# img = (img[0].cpu()).numpy()
# img = img.transpose(1, 2, 0)
img, w_scale, h_scale = mmcv.imresize(
img, size, return_scale=True)
# img = img.transpose(2, 0, 1)
scale_factor = np.array([w_scale, h_scale, w_scale, h_scale],
dtype=np.float32)
mean = np.array([123.675, 116.28, 103.53], dtype=np.float32)
std = np.array([58.395, 57.12, 57.375], dtype=np.float32)
img = mmcv.imnormalize(img, mean, std, True)
img = img.transpose(2, 0, 1) # img = bgr2rgb(img)
img = torch.from_numpy(img).cuda()
img = img.unsqueeze(0)
return img, scale_factor | 0.82559 | 0.265803 |
import pkg_resources
import sys
import os
import shutil
import subprocess
import argparse
from .shared_methods import set_up_logging
helpstring = """
Welcome to the ribo try! Here we test the integration of several parts of the
riboSeed pipeline. First, `ribo run` is performed on the included test
dataset. Then, essentially the same thing is done, but calling the
individual subcommands (`ribo scan`, `ribo select`, etc)
If all goes well, no errors should occur, and you should essentially have
two "identical" riboSeed assemblies (although due to random assignments
of mapping duplicates, the nature of error correction, etc, I can't
guarantee that you will get the exact same result
Have fun!
"""
def get_args(test_args=None): # pragma: no cover
parser = argparse.ArgumentParser(
prog="ribo try",
description=helpstring,
add_help=False) # to allow for custom help
parser.prog = "ribo try"
parser.add_argument("-o", "--output", dest='output', action="store",
help="output directory; " +
"default: %(default)s",
default=os.path.join(
os.getcwd(), "riboSeed_sample_results"),
type=str)
parser.add_argument("-v", "--verbosity", dest='verbosity',
action="store",
default=2, type=int, choices=[1, 2, 3, 4, 5],
help="Logger writes debug to file in output dir; " +
"this sets verbosity level sent to stderr. " +
" 1 = debug(), 2 = info(), 3 = warning(), " +
"4 = error() and 5 = critical(); " +
"default: %(default)s")
parser.add_argument("-c", "--cores", dest='cores', action="store",
default=2, type=int,
help="cores to be used" +
"; default: %(default)s")
parser.add_argument("-t", "--threads", dest='threads',
action="store",
default=1, type=int,
choices=[1, 2, 4],
help="if your cores are hyperthreaded, set number" +
" threads to the number of threads per processer." +
"If unsure, see 'cat /proc/cpuinfo' under 'cpu " +
"cores', or 'lscpu' under 'Thread(s) per core'." +
": %(default)s")
parser.add_argument("-m", "--memory", dest='memory', action="store",
default=8, type=int,
help="system memory available" +
"; default: %(default)s")
parser.add_argument("-h", "--help",
action="help", default=argparse.SUPPRESS,
help="Displays this help message")
args = parser.parse_args(sys.argv[2:])
return args
def main(args, logger=None):
output_root = os.path.abspath(os.path.expanduser(args.output))
try:
os.makedirs(output_root, exist_ok=False)
except OSError:
print("Output directory %s already exists; exiting..." % output_root)
sys.exit(1)
log_path = os.path.join(output_root, "riboTry.log")
if logger is None:
logger = set_up_logging(verbosity=args.verbosity,
outfile=log_path,
name=__name__)
logger.info("Testing your installation of riboSeed on some test data")
# here we locate the test data we packaged with riboSeed -
# some reads and a reference
resource_package = pkg_resources.Requirement.parse("riboSeed")
logger.debug(resource_package)
# this looks like I should be using os.path.join, but the package resource
# stuff needs unix-style path seps
resource_path_fasta = '/'.join(('riboSeed',
'integration_data', 'concatenated_seq.fasta'))
resource_path_reffasta = '/'.join(('riboSeed',
'integration_data', 'NC_000913.3.fasta'))
resource_path_1 = '/'.join(('riboSeed',
'integration_data', 'test_reads1.fq'))
resource_path_2 = '/'.join(('riboSeed',
'integration_data', 'test_reads2.fq'))
logger.debug(resource_path_fasta)
fasta = pkg_resources.resource_filename(resource_package, resource_path_fasta)
reffasta = pkg_resources.resource_filename(resource_package,
resource_path_reffasta)
fastq1 = pkg_resources.resource_filename(resource_package, resource_path_1)
fastq2 = pkg_resources.resource_filename(resource_package, resource_path_2)
# fasta_path = pkg_resources.resource_string("/", resource_path)
logger.debug(fasta)
logger.debug(reffasta)
logger.debug(fastq1)
logger.debug(fastq2)
for i in ["blastn", "spades.py", "bwa", "mafft",
"samtools", "barrnap"]:
assert shutil.which(i) is not None, \
"{0} executable not found in PATH!".format(i)
ribo_run_cmd = str(
"ribo run -r {0} -o {1} -F {2} -R {3} --serialize -v 1 " +
"--subassembler skesa " +
"--stages stack score spec --cores {4} --threads {5} --memory {6}"
).format(
fasta,
os.path.join(output_root, "run"),
fastq1,
fastq2,
args.cores,
args.threads,
args.memory)
logger.info("running " + ribo_run_cmd)
logger.info("This usually take about ~4-5 minutes to run all the modules")
subprocess.run([ribo_run_cmd],
shell=sys.platform != "win32",
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
check=True)
logger.info("finished running integration test with ribo run!") | riboSeed/riboTry.py |
import pkg_resources
import sys
import os
import shutil
import subprocess
import argparse
from .shared_methods import set_up_logging
helpstring = """
Welcome to the ribo try! Here we test the integration of several parts of the
riboSeed pipeline. First, `ribo run` is performed on the included test
dataset. Then, essentially the same thing is done, but calling the
individual subcommands (`ribo scan`, `ribo select`, etc)
If all goes well, no errors should occur, and you should essentially have
two "identical" riboSeed assemblies (although due to random assignments
of mapping duplicates, the nature of error correction, etc, I can't
guarantee that you will get the exact same result
Have fun!
"""
def get_args(test_args=None): # pragma: no cover
parser = argparse.ArgumentParser(
prog="ribo try",
description=helpstring,
add_help=False) # to allow for custom help
parser.prog = "ribo try"
parser.add_argument("-o", "--output", dest='output', action="store",
help="output directory; " +
"default: %(default)s",
default=os.path.join(
os.getcwd(), "riboSeed_sample_results"),
type=str)
parser.add_argument("-v", "--verbosity", dest='verbosity',
action="store",
default=2, type=int, choices=[1, 2, 3, 4, 5],
help="Logger writes debug to file in output dir; " +
"this sets verbosity level sent to stderr. " +
" 1 = debug(), 2 = info(), 3 = warning(), " +
"4 = error() and 5 = critical(); " +
"default: %(default)s")
parser.add_argument("-c", "--cores", dest='cores', action="store",
default=2, type=int,
help="cores to be used" +
"; default: %(default)s")
parser.add_argument("-t", "--threads", dest='threads',
action="store",
default=1, type=int,
choices=[1, 2, 4],
help="if your cores are hyperthreaded, set number" +
" threads to the number of threads per processer." +
"If unsure, see 'cat /proc/cpuinfo' under 'cpu " +
"cores', or 'lscpu' under 'Thread(s) per core'." +
": %(default)s")
parser.add_argument("-m", "--memory", dest='memory', action="store",
default=8, type=int,
help="system memory available" +
"; default: %(default)s")
parser.add_argument("-h", "--help",
action="help", default=argparse.SUPPRESS,
help="Displays this help message")
args = parser.parse_args(sys.argv[2:])
return args
def main(args, logger=None):
output_root = os.path.abspath(os.path.expanduser(args.output))
try:
os.makedirs(output_root, exist_ok=False)
except OSError:
print("Output directory %s already exists; exiting..." % output_root)
sys.exit(1)
log_path = os.path.join(output_root, "riboTry.log")
if logger is None:
logger = set_up_logging(verbosity=args.verbosity,
outfile=log_path,
name=__name__)
logger.info("Testing your installation of riboSeed on some test data")
# here we locate the test data we packaged with riboSeed -
# some reads and a reference
resource_package = pkg_resources.Requirement.parse("riboSeed")
logger.debug(resource_package)
# this looks like I should be using os.path.join, but the package resource
# stuff needs unix-style path seps
resource_path_fasta = '/'.join(('riboSeed',
'integration_data', 'concatenated_seq.fasta'))
resource_path_reffasta = '/'.join(('riboSeed',
'integration_data', 'NC_000913.3.fasta'))
resource_path_1 = '/'.join(('riboSeed',
'integration_data', 'test_reads1.fq'))
resource_path_2 = '/'.join(('riboSeed',
'integration_data', 'test_reads2.fq'))
logger.debug(resource_path_fasta)
fasta = pkg_resources.resource_filename(resource_package, resource_path_fasta)
reffasta = pkg_resources.resource_filename(resource_package,
resource_path_reffasta)
fastq1 = pkg_resources.resource_filename(resource_package, resource_path_1)
fastq2 = pkg_resources.resource_filename(resource_package, resource_path_2)
# fasta_path = pkg_resources.resource_string("/", resource_path)
logger.debug(fasta)
logger.debug(reffasta)
logger.debug(fastq1)
logger.debug(fastq2)
for i in ["blastn", "spades.py", "bwa", "mafft",
"samtools", "barrnap"]:
assert shutil.which(i) is not None, \
"{0} executable not found in PATH!".format(i)
ribo_run_cmd = str(
"ribo run -r {0} -o {1} -F {2} -R {3} --serialize -v 1 " +
"--subassembler skesa " +
"--stages stack score spec --cores {4} --threads {5} --memory {6}"
).format(
fasta,
os.path.join(output_root, "run"),
fastq1,
fastq2,
args.cores,
args.threads,
args.memory)
logger.info("running " + ribo_run_cmd)
logger.info("This usually take about ~4-5 minutes to run all the modules")
subprocess.run([ribo_run_cmd],
shell=sys.platform != "win32",
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
check=True)
logger.info("finished running integration test with ribo run!") | 0.346541 | 0.186817 |
import logging
from .base import GeckoAutomationBase
from ..driver import GeckoWatercareProtocolHandler
from ..const import GeckoConstants
_LOGGER = logging.getLogger(__name__)
class GeckoWaterCare(GeckoAutomationBase):
""" Watercare manangement class """
def __init__(self, facade):
super().__init__(facade, "WaterCare", "WATERCARE")
self.active_mode = None
self._water_care_handler = None
@property
def mode(self):
""" Return the active water care mode """
return self.active_mode
@property
def modes(self):
""" Return all the possible water care modes """
return GeckoConstants.WATERCARE_MODE_STRING
def set_mode(self, new_mode):
"""Set the active watercare mode to new_mode.
new_mode can be a string, in which case the value must be a member of
GeckoConstants.WATERCARE_MODE_STRING, or it can be an integer from
GeckoConstants.WATERCARE_MODE
"""
if isinstance(new_mode, str):
new_mode = GeckoConstants.WATERCARE_MODE_STRING.index(new_mode)
self._spa.queue_send(
GeckoWatercareProtocolHandler.set(
self._spa.get_and_increment_sequence_counter(),
new_mode,
parms=self._spa.sendparms,
),
self._spa.sendparms,
)
def _on_watercare(self, handler, socket, sender):
if self.active_mode != handler.mode:
old_mode = self.active_mode
self.active_mode = handler.mode
self._on_change(self, old_mode, self.active_mode)
self._water_care_handler = None
def update(self):
if self._water_care_handler is not None:
return
self._water_care_handler = GeckoWatercareProtocolHandler.request(
self._spa.get_and_increment_sequence_counter(),
on_handled=self._on_watercare,
parms=self._spa.sendparms,
)
self._spa.add_receive_handler(self._water_care_handler)
self._spa.queue_send(self._water_care_handler, self._spa.sendparms)
def __str__(self):
if self.active_mode is None:
return f"{self.name}: Waiting..."
return f"{self.name}: {GeckoConstants.WATERCARE_MODE_STRING[self.active_mode]}" | gecko/geckolib/automation/watercare.py |
import logging
from .base import GeckoAutomationBase
from ..driver import GeckoWatercareProtocolHandler
from ..const import GeckoConstants
_LOGGER = logging.getLogger(__name__)
class GeckoWaterCare(GeckoAutomationBase):
""" Watercare manangement class """
def __init__(self, facade):
super().__init__(facade, "WaterCare", "WATERCARE")
self.active_mode = None
self._water_care_handler = None
@property
def mode(self):
""" Return the active water care mode """
return self.active_mode
@property
def modes(self):
""" Return all the possible water care modes """
return GeckoConstants.WATERCARE_MODE_STRING
def set_mode(self, new_mode):
"""Set the active watercare mode to new_mode.
new_mode can be a string, in which case the value must be a member of
GeckoConstants.WATERCARE_MODE_STRING, or it can be an integer from
GeckoConstants.WATERCARE_MODE
"""
if isinstance(new_mode, str):
new_mode = GeckoConstants.WATERCARE_MODE_STRING.index(new_mode)
self._spa.queue_send(
GeckoWatercareProtocolHandler.set(
self._spa.get_and_increment_sequence_counter(),
new_mode,
parms=self._spa.sendparms,
),
self._spa.sendparms,
)
def _on_watercare(self, handler, socket, sender):
if self.active_mode != handler.mode:
old_mode = self.active_mode
self.active_mode = handler.mode
self._on_change(self, old_mode, self.active_mode)
self._water_care_handler = None
def update(self):
if self._water_care_handler is not None:
return
self._water_care_handler = GeckoWatercareProtocolHandler.request(
self._spa.get_and_increment_sequence_counter(),
on_handled=self._on_watercare,
parms=self._spa.sendparms,
)
self._spa.add_receive_handler(self._water_care_handler)
self._spa.queue_send(self._water_care_handler, self._spa.sendparms)
def __str__(self):
if self.active_mode is None:
return f"{self.name}: Waiting..."
return f"{self.name}: {GeckoConstants.WATERCARE_MODE_STRING[self.active_mode]}" | 0.753376 | 0.077518 |
from django.shortcuts import render
from django.contrib.auth.decorators import login_required, permission_required
from django.contrib.auth import get_user_model
# utils
from .utils import get_context, get_hitmans, get_role
from .constants import FAILED, HITMAN, MANAGER, BOSS, COMPLETED
# Models
from .models import Hit, HitStatus, TeamManager, TeamMembers
# Forms
from .forms import ReassignHitForm, HitForm, TeamForm, TeamMembersForm, DeleteMembersForm
Spy = get_user_model()
@login_required
def create_team(request):
team_form = TeamForm(request.POST or None)
context = {
'team_form':team_form,
'msn':None,
'msn_type': "danger"
}
if request.method == 'POST':
if team_form.is_valid():
data_form = team_form.cleaned_data
manager_team = data_form.get('team_manager')
team = TeamManager(manager=manager_team)
team.save()
context['msn_type'] = "success"
context['msn'] = "Team created successfully"
return render(request, 'team/create_team.html', context)
@login_required
@permission_required('auth_app.can_see_hitmen')
def hitman_detail(request, pk):
spy = request.user
context = {
'hitman':None,
'members': None,
'members_form':None,
'msn':None,
'msn_type': "danger"
}
rol = get_role(spy)
members_form = TeamMembersForm(request.POST or None)
delete_members_form = DeleteMembersForm(request.POST or None)
context['members_form'] = members_form
context['delete_members_form'] = delete_members_form
team = None
hitman = Spy.objects.filter(pk=pk).first()
if hitman:
if rol==MANAGER:
team = TeamManager.objects.filter(manager=spy.id).first()
if team:
member = TeamMembers.objects.filter(team=team.id).filter(hitman=hitman.id).first()
if member:
context['hitman'] = hitman
elif rol==BOSS:
if get_role(hitman) == MANAGER:
members = get_hitmans(hitman,MANAGER, inactive=True)
team = TeamManager.objects.filter(manager=hitman.id).first()
list_hitmen = members.values_list("id")
available_hitmen = Spy.objects.filter(is_staff=False).filter(is_superuser=False).exclude(id__in=list_hitmen)
members_form.fields['hitman'].queryset = available_hitmen
delete_members_form.fields['hitman_member'].queryset = members
context['hitman'] = hitman
context['members'] = members
else:
context['hitman'] = hitman
if request.method == 'POST':
try:
data = request.POST['inactive_hitman']
if data == '1':
hitman.is_active = False
hitman.save()
context['msn_type'] = "success"
context['msn'] = "Hitman status updated"
except:
next
if members_form.is_valid():
if team:
data_form = members_form.cleaned_data
member_team = data_form.get('hitman')
new_member = TeamMembers(hitman=member_team, team=team)
new_member.save()
context['msn_type'] = "success"
context['msn'] = "Member added successfully"
else:
context['msn_type'] = "danger"
context['msn'] = "Manager has not been assigned to a team"
if delete_members_form.is_valid():
data_form = delete_members_form.cleaned_data
member_team = data_form.get('hitman_member')
hitman = TeamMembers.objects.filter(hitman=member_team.id)
hitman.delete()
context['msn_type'] = "success"
context['msn'] = "Member deleted successfully"
return render(request, 'hitmen/hitman_detail.html', context)
@login_required
@permission_required('auth_app.can_see_hitmen')
def hitmen_list(request):
spy = request.user
rol = get_role(spy)
context = {
'hitmen':None
}
hitmen = None
if rol == MANAGER:
hitmen = get_hitmans(spy, rol, inactive=True)
elif rol == BOSS:
hitmen = get_hitmans(spy, rol, inactive=False)
context['hitmen'] = hitmen
return render(request, 'hitmen/hitmen.html', context)
@login_required
@permission_required('spy_app.can_create_hit')
def hit_create(request):
spy = request.user
rol = None
hit_form = HitForm(request.POST or None)
context = {
'hit_form':hit_form,
'msn':None,
'msn_type': "danger"
}
if request.method == "POST":
if hit_form.is_valid():
data_form = hit_form.cleaned_data
target_name = data_form.get('target_name')
target_location = data_form.get('target_location')
description = data_form.get('description')
hitman_assigned = data_form.get('hitman_assigned')
status = HitStatus.objects.filter(name="On progress").first()
assigment_creator = Spy.objects.filter(pk=spy.id).first()
hit = Hit(target_name=target_name, target_location=target_location,
description=description, hitman_assigned=hitman_assigned,
status=status, assigment_creator=assigment_creator)
hit.save()
context['msn_type'] = "success"
context['msn'] = "Hit created successfully"
else:
context['msn_type'] = "danger"
context['msn'] = "Somthing went wrong, check the fields inputs."
if spy.is_superuser:
rol = BOSS
hit_form.fields['hitman_assigned'].queryset = get_hitmans(spy, rol)
elif spy.is_staff:
rol = MANAGER
hit_form.fields['hitman_assigned'].queryset = get_hitmans(spy, rol)
return render(request, 'hits/create_hit.html', context)
@login_required
def hits_view(request):
spy = request.user
if spy.is_staff and spy.is_superuser: # Boss
context = get_context(spy, BOSS)
return render(request, 'hits/boss_hits_view.html', context)
elif spy.is_staff and not spy.is_superuser: # manager
context = get_context(spy, MANAGER)
return render(request, 'hits/manager_hits.html', context)
elif not spy.is_staff and not spy.is_superuser: # hitman
context = get_context(spy, HITMAN)
return render(request, 'hits/hitman_hits.html', context)
@login_required
def hit_detail(request, pk):
hit = None
context = {
'spy_rol':HITMAN,
'hit':None,
'assigned_hit':False,
}
try:
hit = Hit.objects.get(pk=pk)
except:
return render(request, 'hits/hit_detail.html', context)
reassign_form = ReassignHitForm(request.POST or None, initial={'hitman':hit.hitman_assigned.pk})
context['reassign_form']=reassign_form
if request.method == 'POST':
try:
data = request.POST['hit_status']
if data == '1':
status = HitStatus.objects.get(name=COMPLETED)
hit.status = status
hit.save()
elif data == '0':
status = HitStatus.objects.get(name=FAILED)
hit.status = status
hit.save()
except:
next
if reassign_form.is_valid():
data_form = reassign_form.cleaned_data
new_hitman = data_form['hitman']
hit.hitman_assigned = Spy.objects.get(email=new_hitman)
hit.save()
spy = request.user
if spy.is_superuser:
context['spy_rol'] = BOSS
elif not spy.is_superuser and spy.is_staff:
context['spy_rol'] = MANAGER
if hit.hitman_assigned.id == request.user.id:
context['hit'] = hit
context['assigned_hit'] = True
return render(request, 'hits/hit_detail.html', context)
elif context['spy_rol']==MANAGER or context['spy_rol']==BOSS:
context['hit'] = hit
return render(request, 'hits/hit_detail.html', context)
return render(request, 'hits/hit_detail.html', context) | src/spy_app/views.py | from django.shortcuts import render
from django.contrib.auth.decorators import login_required, permission_required
from django.contrib.auth import get_user_model
# utils
from .utils import get_context, get_hitmans, get_role
from .constants import FAILED, HITMAN, MANAGER, BOSS, COMPLETED
# Models
from .models import Hit, HitStatus, TeamManager, TeamMembers
# Forms
from .forms import ReassignHitForm, HitForm, TeamForm, TeamMembersForm, DeleteMembersForm
Spy = get_user_model()
@login_required
def create_team(request):
team_form = TeamForm(request.POST or None)
context = {
'team_form':team_form,
'msn':None,
'msn_type': "danger"
}
if request.method == 'POST':
if team_form.is_valid():
data_form = team_form.cleaned_data
manager_team = data_form.get('team_manager')
team = TeamManager(manager=manager_team)
team.save()
context['msn_type'] = "success"
context['msn'] = "Team created successfully"
return render(request, 'team/create_team.html', context)
@login_required
@permission_required('auth_app.can_see_hitmen')
def hitman_detail(request, pk):
spy = request.user
context = {
'hitman':None,
'members': None,
'members_form':None,
'msn':None,
'msn_type': "danger"
}
rol = get_role(spy)
members_form = TeamMembersForm(request.POST or None)
delete_members_form = DeleteMembersForm(request.POST or None)
context['members_form'] = members_form
context['delete_members_form'] = delete_members_form
team = None
hitman = Spy.objects.filter(pk=pk).first()
if hitman:
if rol==MANAGER:
team = TeamManager.objects.filter(manager=spy.id).first()
if team:
member = TeamMembers.objects.filter(team=team.id).filter(hitman=hitman.id).first()
if member:
context['hitman'] = hitman
elif rol==BOSS:
if get_role(hitman) == MANAGER:
members = get_hitmans(hitman,MANAGER, inactive=True)
team = TeamManager.objects.filter(manager=hitman.id).first()
list_hitmen = members.values_list("id")
available_hitmen = Spy.objects.filter(is_staff=False).filter(is_superuser=False).exclude(id__in=list_hitmen)
members_form.fields['hitman'].queryset = available_hitmen
delete_members_form.fields['hitman_member'].queryset = members
context['hitman'] = hitman
context['members'] = members
else:
context['hitman'] = hitman
if request.method == 'POST':
try:
data = request.POST['inactive_hitman']
if data == '1':
hitman.is_active = False
hitman.save()
context['msn_type'] = "success"
context['msn'] = "Hitman status updated"
except:
next
if members_form.is_valid():
if team:
data_form = members_form.cleaned_data
member_team = data_form.get('hitman')
new_member = TeamMembers(hitman=member_team, team=team)
new_member.save()
context['msn_type'] = "success"
context['msn'] = "Member added successfully"
else:
context['msn_type'] = "danger"
context['msn'] = "Manager has not been assigned to a team"
if delete_members_form.is_valid():
data_form = delete_members_form.cleaned_data
member_team = data_form.get('hitman_member')
hitman = TeamMembers.objects.filter(hitman=member_team.id)
hitman.delete()
context['msn_type'] = "success"
context['msn'] = "Member deleted successfully"
return render(request, 'hitmen/hitman_detail.html', context)
@login_required
@permission_required('auth_app.can_see_hitmen')
def hitmen_list(request):
spy = request.user
rol = get_role(spy)
context = {
'hitmen':None
}
hitmen = None
if rol == MANAGER:
hitmen = get_hitmans(spy, rol, inactive=True)
elif rol == BOSS:
hitmen = get_hitmans(spy, rol, inactive=False)
context['hitmen'] = hitmen
return render(request, 'hitmen/hitmen.html', context)
@login_required
@permission_required('spy_app.can_create_hit')
def hit_create(request):
spy = request.user
rol = None
hit_form = HitForm(request.POST or None)
context = {
'hit_form':hit_form,
'msn':None,
'msn_type': "danger"
}
if request.method == "POST":
if hit_form.is_valid():
data_form = hit_form.cleaned_data
target_name = data_form.get('target_name')
target_location = data_form.get('target_location')
description = data_form.get('description')
hitman_assigned = data_form.get('hitman_assigned')
status = HitStatus.objects.filter(name="On progress").first()
assigment_creator = Spy.objects.filter(pk=spy.id).first()
hit = Hit(target_name=target_name, target_location=target_location,
description=description, hitman_assigned=hitman_assigned,
status=status, assigment_creator=assigment_creator)
hit.save()
context['msn_type'] = "success"
context['msn'] = "Hit created successfully"
else:
context['msn_type'] = "danger"
context['msn'] = "Somthing went wrong, check the fields inputs."
if spy.is_superuser:
rol = BOSS
hit_form.fields['hitman_assigned'].queryset = get_hitmans(spy, rol)
elif spy.is_staff:
rol = MANAGER
hit_form.fields['hitman_assigned'].queryset = get_hitmans(spy, rol)
return render(request, 'hits/create_hit.html', context)
@login_required
def hits_view(request):
spy = request.user
if spy.is_staff and spy.is_superuser: # Boss
context = get_context(spy, BOSS)
return render(request, 'hits/boss_hits_view.html', context)
elif spy.is_staff and not spy.is_superuser: # manager
context = get_context(spy, MANAGER)
return render(request, 'hits/manager_hits.html', context)
elif not spy.is_staff and not spy.is_superuser: # hitman
context = get_context(spy, HITMAN)
return render(request, 'hits/hitman_hits.html', context)
@login_required
def hit_detail(request, pk):
hit = None
context = {
'spy_rol':HITMAN,
'hit':None,
'assigned_hit':False,
}
try:
hit = Hit.objects.get(pk=pk)
except:
return render(request, 'hits/hit_detail.html', context)
reassign_form = ReassignHitForm(request.POST or None, initial={'hitman':hit.hitman_assigned.pk})
context['reassign_form']=reassign_form
if request.method == 'POST':
try:
data = request.POST['hit_status']
if data == '1':
status = HitStatus.objects.get(name=COMPLETED)
hit.status = status
hit.save()
elif data == '0':
status = HitStatus.objects.get(name=FAILED)
hit.status = status
hit.save()
except:
next
if reassign_form.is_valid():
data_form = reassign_form.cleaned_data
new_hitman = data_form['hitman']
hit.hitman_assigned = Spy.objects.get(email=new_hitman)
hit.save()
spy = request.user
if spy.is_superuser:
context['spy_rol'] = BOSS
elif not spy.is_superuser and spy.is_staff:
context['spy_rol'] = MANAGER
if hit.hitman_assigned.id == request.user.id:
context['hit'] = hit
context['assigned_hit'] = True
return render(request, 'hits/hit_detail.html', context)
elif context['spy_rol']==MANAGER or context['spy_rol']==BOSS:
context['hit'] = hit
return render(request, 'hits/hit_detail.html', context)
return render(request, 'hits/hit_detail.html', context) | 0.274157 | 0.090735 |
import decimal
import logging
import enum
import arrow
from dos.parsers import extract_arrow, extract_number
LOGGER = logging.getLogger()
LOGGER.setLevel(logging.CRITICAL)
NO_VALUE = object()
class OpenAPIPropType(enum.Enum):
INTEGER = "integer"
NUMBER = "number"
STRING = "string"
BOOLEAN = "boolean"
ARRAY = "array"
OBJECT = "object"
class ValidationError(ValueError):
def __init__(self, message):
super().__init__(message)
self.message = message
class Prop:
def __init__(self, description=None, required=True, nullable=False, validators=None):
self.description = description
self.required = required
self.nullable = nullable
self.validators = validators
def __deepcopy__(self, memo): # pylint: disable=unused-argument
return type(self)(
description=self.description,
required=self.required,
nullable=self.nullable,
validators=self.validators
)
def parse_input(self, prop_value): # pylint: disable=no-self-use
return prop_value
def format_output(self, prop_value): # pylint: disable=no-self-use
return prop_value
def parse_input_and_validate(self, input_structure_field_name, body, prop_value=NO_VALUE):
if prop_value is NO_VALUE:
prop_value = body.get(input_structure_field_name)
try:
prop_value = self.parse_input(prop_value)
except (ValueError, TypeError, decimal.InvalidOperation) as ambiguous_error:
error = (f"The value {prop_value!r} from field '{input_structure_field_name}' "
f"is the wrong type, expected: {self.__class__.__name__}")
LOGGER.critical(error + " /// Error: " + str(ambiguous_error)) # pylint: disable=logging-not-lazy
raise ValidationError(error)
return self.validate(input_structure_field_name, body, prop_value)
def format_output_and_validate(self, output_structure_field_name, body, prop_value=NO_VALUE):
if prop_value is NO_VALUE:
if body is None:
prop_value = None
else:
prop_value = body.get(output_structure_field_name)
prop_value = self.validate(output_structure_field_name, body, prop_value)
return self.format_output(prop_value)
def validate(self, output_structure_field_name, body, prop_value):
if self.required:
if output_structure_field_name is not None and body is not None:
if output_structure_field_name not in body:
raise ValidationError(
f"The field '{output_structure_field_name}' is required "
f"but not found in the body!"
)
if not self.nullable:
if body is not None:
if output_structure_field_name in body:
if prop_value is None:
raise ValidationError(
f"Non nullable field '{output_structure_field_name}' "
f"is null!"
)
if prop_value is not None:
if not isinstance(prop_value, self.types): # pylint: disable=no-member
raise ValidationError(
f"The value {prop_value!r} from field '{output_structure_field_name}' "
f"is the wrong type, expected: {self.__class__.__name__}"
)
if self.validators is not None:
for validator in self.validators:
error_message = validator.validate_prop(prop_class=type(self), prop_value=prop_value)
if error_message is not None:
raise ValidationError(error_message)
return prop_value
class Integer(Prop):
prop_type = OpenAPIPropType.INTEGER
types = int
def parse_input(self, prop_value):
if prop_value is None:
return None
return int(prop_value)
class Number(Prop):
prop_type = OpenAPIPropType.NUMBER
types = (int, float, decimal.Decimal)
def parse_input(self, prop_value):
if prop_value is None:
return None
return extract_number(prop_value)
class Numeric(Number):
types = (int, float, decimal.Decimal, str)
class String(Prop):
prop_type = OpenAPIPropType.STRING
types = str
format = None
class DateTime(String):
types = (str, arrow.Arrow)
format = "date-time"
def parse_input(self, prop_value):
if prop_value is None:
return None
return extract_arrow(prop_value)
def format_output(self, prop_value):
if prop_value is None:
return None
return str(prop_value)
class Enum(String):
types = enum.Enum
def format_output(self, prop_value):
if prop_value is None:
return None
return str(prop_value.value)
class Boolean(Prop):
prop_type = OpenAPIPropType.BOOLEAN
types = bool
class Object(Prop):
prop_type = OpenAPIPropType.OBJECT
types = dict
def __init__(self, structure, description=None, required=True, nullable=False, validators=None):
super().__init__(description=description, required=required, nullable=nullable, validators=validators)
self.structure = structure
def __deepcopy__(self, memo): # pylint: disable=unused-argument
return Object(
self.structure,
description=self.description,
required=self.required,
nullable=self.nullable,
)
def format_output_and_validate(self, output_structure_field_name, body, prop_value=NO_VALUE):
prop_value = super().format_output_and_validate(
output_structure_field_name,
body,
prop_value,
)
validated_dict = {}
for field_name, field_prop in self.structure.items():
validated_dict[field_name] = field_prop.format_output_and_validate(field_name, prop_value)
return validated_dict
class Array(Prop):
prop_type = OpenAPIPropType.ARRAY
types = list
def __init__(self, repeated_structure, description=None, required=True, nullable=False, validators=None):
super().__init__(description=description, required=required, nullable=nullable, validators=validators)
self.repeated_structure = repeated_structure
def __deepcopy__(self, memo): # pylint: disable=unused-argument
return Array(
self.repeated_structure,
description=self.description,
required=self.required,
nullable=self.nullable,
)
def format_output_and_validate(self, output_structure_field_name, body, prop_value=NO_VALUE):
prop_value = super().format_output_and_validate(
output_structure_field_name,
body,
prop_value,
)
validated_list = []
if prop_value:
for value in prop_value:
validated_list.append(self.repeated_structure.format_output_and_validate(None, None, value))
return validated_list | src/dos/prop.py | import decimal
import logging
import enum
import arrow
from dos.parsers import extract_arrow, extract_number
LOGGER = logging.getLogger()
LOGGER.setLevel(logging.CRITICAL)
NO_VALUE = object()
class OpenAPIPropType(enum.Enum):
INTEGER = "integer"
NUMBER = "number"
STRING = "string"
BOOLEAN = "boolean"
ARRAY = "array"
OBJECT = "object"
class ValidationError(ValueError):
def __init__(self, message):
super().__init__(message)
self.message = message
class Prop:
def __init__(self, description=None, required=True, nullable=False, validators=None):
self.description = description
self.required = required
self.nullable = nullable
self.validators = validators
def __deepcopy__(self, memo): # pylint: disable=unused-argument
return type(self)(
description=self.description,
required=self.required,
nullable=self.nullable,
validators=self.validators
)
def parse_input(self, prop_value): # pylint: disable=no-self-use
return prop_value
def format_output(self, prop_value): # pylint: disable=no-self-use
return prop_value
def parse_input_and_validate(self, input_structure_field_name, body, prop_value=NO_VALUE):
if prop_value is NO_VALUE:
prop_value = body.get(input_structure_field_name)
try:
prop_value = self.parse_input(prop_value)
except (ValueError, TypeError, decimal.InvalidOperation) as ambiguous_error:
error = (f"The value {prop_value!r} from field '{input_structure_field_name}' "
f"is the wrong type, expected: {self.__class__.__name__}")
LOGGER.critical(error + " /// Error: " + str(ambiguous_error)) # pylint: disable=logging-not-lazy
raise ValidationError(error)
return self.validate(input_structure_field_name, body, prop_value)
def format_output_and_validate(self, output_structure_field_name, body, prop_value=NO_VALUE):
if prop_value is NO_VALUE:
if body is None:
prop_value = None
else:
prop_value = body.get(output_structure_field_name)
prop_value = self.validate(output_structure_field_name, body, prop_value)
return self.format_output(prop_value)
def validate(self, output_structure_field_name, body, prop_value):
if self.required:
if output_structure_field_name is not None and body is not None:
if output_structure_field_name not in body:
raise ValidationError(
f"The field '{output_structure_field_name}' is required "
f"but not found in the body!"
)
if not self.nullable:
if body is not None:
if output_structure_field_name in body:
if prop_value is None:
raise ValidationError(
f"Non nullable field '{output_structure_field_name}' "
f"is null!"
)
if prop_value is not None:
if not isinstance(prop_value, self.types): # pylint: disable=no-member
raise ValidationError(
f"The value {prop_value!r} from field '{output_structure_field_name}' "
f"is the wrong type, expected: {self.__class__.__name__}"
)
if self.validators is not None:
for validator in self.validators:
error_message = validator.validate_prop(prop_class=type(self), prop_value=prop_value)
if error_message is not None:
raise ValidationError(error_message)
return prop_value
class Integer(Prop):
prop_type = OpenAPIPropType.INTEGER
types = int
def parse_input(self, prop_value):
if prop_value is None:
return None
return int(prop_value)
class Number(Prop):
prop_type = OpenAPIPropType.NUMBER
types = (int, float, decimal.Decimal)
def parse_input(self, prop_value):
if prop_value is None:
return None
return extract_number(prop_value)
class Numeric(Number):
types = (int, float, decimal.Decimal, str)
class String(Prop):
prop_type = OpenAPIPropType.STRING
types = str
format = None
class DateTime(String):
types = (str, arrow.Arrow)
format = "date-time"
def parse_input(self, prop_value):
if prop_value is None:
return None
return extract_arrow(prop_value)
def format_output(self, prop_value):
if prop_value is None:
return None
return str(prop_value)
class Enum(String):
types = enum.Enum
def format_output(self, prop_value):
if prop_value is None:
return None
return str(prop_value.value)
class Boolean(Prop):
prop_type = OpenAPIPropType.BOOLEAN
types = bool
class Object(Prop):
prop_type = OpenAPIPropType.OBJECT
types = dict
def __init__(self, structure, description=None, required=True, nullable=False, validators=None):
super().__init__(description=description, required=required, nullable=nullable, validators=validators)
self.structure = structure
def __deepcopy__(self, memo): # pylint: disable=unused-argument
return Object(
self.structure,
description=self.description,
required=self.required,
nullable=self.nullable,
)
def format_output_and_validate(self, output_structure_field_name, body, prop_value=NO_VALUE):
prop_value = super().format_output_and_validate(
output_structure_field_name,
body,
prop_value,
)
validated_dict = {}
for field_name, field_prop in self.structure.items():
validated_dict[field_name] = field_prop.format_output_and_validate(field_name, prop_value)
return validated_dict
class Array(Prop):
prop_type = OpenAPIPropType.ARRAY
types = list
def __init__(self, repeated_structure, description=None, required=True, nullable=False, validators=None):
super().__init__(description=description, required=required, nullable=nullable, validators=validators)
self.repeated_structure = repeated_structure
def __deepcopy__(self, memo): # pylint: disable=unused-argument
return Array(
self.repeated_structure,
description=self.description,
required=self.required,
nullable=self.nullable,
)
def format_output_and_validate(self, output_structure_field_name, body, prop_value=NO_VALUE):
prop_value = super().format_output_and_validate(
output_structure_field_name,
body,
prop_value,
)
validated_list = []
if prop_value:
for value in prop_value:
validated_list.append(self.repeated_structure.format_output_and_validate(None, None, value))
return validated_list | 0.599837 | 0.160332 |
import logging
import unittest
import mock
from qgis.core import QgsFeature, QgsFeatureRequest, QgsVectorLayer
from catatom2osm.app import QgsSingleton
from catatom2osm.geo.geometry import Geometry
from catatom2osm.geo.layer.polygon import PolygonLayer
from catatom2osm.geo.point import Point
qgs = QgsSingleton()
m_log = mock.MagicMock()
m_log.app_level = logging.INFO
class TestPolygonLayer(unittest.TestCase):
@mock.patch("catatom2osm.geo.layer.base.log", m_log)
@mock.patch("catatom2osm.geo.layer.base.tqdm", mock.MagicMock())
def setUp(self):
fn = "test/fixtures/cons.shp"
self.fixture = QgsVectorLayer(fn, "building", "ogr")
self.assertTrue(self.fixture.isValid(), f"Loading {fn}")
fn = "test_layer.shp"
PolygonLayer.create_shp(fn, self.fixture.crs())
self.layer = PolygonLayer(fn, "building", "ogr")
self.assertTrue(self.layer.isValid(), "Init QGIS")
self.layer.append(self.fixture, rename="")
self.assertEqual(self.layer.featureCount(), self.fixture.featureCount())
def tearDown(self):
del self.layer
PolygonLayer.delete_shp("test_layer.shp")
@mock.patch("catatom2osm.geo.layer.polygon.log", m_log)
def test_get_area(self):
area = self.layer.get_area()
self.assertEqual(round(area, 1), 1140234.8)
@mock.patch("catatom2osm.geo.layer.base.log", m_log)
@mock.patch("catatom2osm.geo.layer.base.tqdm", mock.MagicMock())
def test_explode_multi_parts(self):
multiparts = [
f for f in self.layer.getFeatures() if len(Geometry.get_multipolygon(f)) > 1
]
self.assertGreater(len(multiparts), 0, "There are multipart features")
features_before = self.layer.featureCount()
request = QgsFeatureRequest()
request.setFilterFid(multiparts[0].id())
nparts = len(Geometry.get_multipolygon(multiparts[0]))
self.layer.explode_multi_parts(request)
self.assertEqual(features_before + nparts - 1, self.layer.featureCount())
nparts = sum([len(Geometry.get_multipolygon(f)) for f in multiparts])
self.assertGreater(nparts, len(multiparts), "With more than one part")
self.assertTrue(nparts > 1, "Find a multipart feature")
self.layer.explode_multi_parts()
m = "After exploding there must be more features than before"
self.assertGreater(self.layer.featureCount(), features_before, m)
m = (
"Number of features before plus number of parts minus multiparts "
"equals actual number of features"
)
self.assertEqual(
features_before + nparts - len(multiparts), self.layer.featureCount(), m
)
m = "Parts must be single polygons"
self.assertTrue(
all(
[
len(Geometry.get_multipolygon(f)) == 1
for f in self.layer.getFeatures()
]
),
m,
)
@mock.patch("catatom2osm.geo.layer.base.log", m_log)
def test_get_parents_per_vertex_and_geometries(self):
(
parents_per_vertex,
geometries,
) = self.layer.get_parents_per_vertex_and_geometries()
self.assertEqual(len(geometries), self.layer.featureCount())
self.assertTrue(
all(
[
Geometry.get_multipolygon(geometries[f.id()])
== Geometry.get_multipolygon(f)
for f in self.layer.getFeatures()
]
)
)
self.assertGreater(len(parents_per_vertex), 0)
self.assertTrue(
all(
[
Geometry.fromPointXY(Point(vertex)).intersects(geometries[fid])
for (vertex, fids) in list(parents_per_vertex.items())
for fid in fids
]
)
)
@mock.patch("catatom2osm.geo.layer.base.log", m_log)
@mock.patch("catatom2osm.geo.layer.base.tqdm", mock.MagicMock())
def test_difference(self):
layer1 = PolygonLayer("Polygon", "test1", "memory")
layer2 = PolygonLayer("Polygon", "test2", "memory")
g1 = Geometry.fromPolygonXY(
[
[
Point(10, 10),
Point(20, 10),
Point(20, 20),
Point(10, 20),
Point(10, 10),
]
]
)
g2 = Geometry.fromPolygonXY(
[
[
Point(30, 10),
Point(40, 10),
Point(40, 20),
Point(30, 20),
Point(30, 10),
]
]
)
h1 = Geometry.fromPolygonXY(
[
[
Point(14, 14),
Point(16, 14),
Point(16, 16),
Point(14, 16),
Point(14, 14),
]
]
)
h2 = Geometry.fromPolygonXY(
[
[
Point(20, 10),
Point(30, 10),
Point(30, 20),
Point(20, 20),
Point(20, 10),
]
]
)
h3 = Geometry.fromPolygonXY(
[
[
Point(38, 10),
Point(42, 10),
Point(42, 20),
Point(38, 20),
Point(38, 10),
]
]
)
h4 = Geometry.fromPolygonXY(
[
[
Point(30, 30),
Point(40, 30),
Point(40, 40),
Point(40, 30),
Point(30, 30),
]
]
)
r1 = g1.difference(h1)
r2 = g2.difference(h3)
layer1.writer.addFeatures([QgsFeature() for i in range(2)])
layer1.writer.changeGeometryValues({1: g1, 2: g2})
layer2.writer.addFeatures([QgsFeature() for i in range(4)])
layer2.writer.changeGeometryValues({1: h1, 2: h2, 3: h3, 4: h4})
layer1.difference(layer2)
self.assertEqual(layer1.featureCount(), 2)
request = QgsFeatureRequest().setFilterFid(1)
f1 = next(layer1.getFeatures(request))
request = QgsFeatureRequest().setFilterFid(2)
f2 = next(layer1.getFeatures(request))
self.assertEqual(f1.geometry().difference(r1).area(), 0)
self.assertEqual(f2.geometry().difference(r2).area(), 0) | test/geo/layer/test_polygon.py | import logging
import unittest
import mock
from qgis.core import QgsFeature, QgsFeatureRequest, QgsVectorLayer
from catatom2osm.app import QgsSingleton
from catatom2osm.geo.geometry import Geometry
from catatom2osm.geo.layer.polygon import PolygonLayer
from catatom2osm.geo.point import Point
qgs = QgsSingleton()
m_log = mock.MagicMock()
m_log.app_level = logging.INFO
class TestPolygonLayer(unittest.TestCase):
@mock.patch("catatom2osm.geo.layer.base.log", m_log)
@mock.patch("catatom2osm.geo.layer.base.tqdm", mock.MagicMock())
def setUp(self):
fn = "test/fixtures/cons.shp"
self.fixture = QgsVectorLayer(fn, "building", "ogr")
self.assertTrue(self.fixture.isValid(), f"Loading {fn}")
fn = "test_layer.shp"
PolygonLayer.create_shp(fn, self.fixture.crs())
self.layer = PolygonLayer(fn, "building", "ogr")
self.assertTrue(self.layer.isValid(), "Init QGIS")
self.layer.append(self.fixture, rename="")
self.assertEqual(self.layer.featureCount(), self.fixture.featureCount())
def tearDown(self):
del self.layer
PolygonLayer.delete_shp("test_layer.shp")
@mock.patch("catatom2osm.geo.layer.polygon.log", m_log)
def test_get_area(self):
area = self.layer.get_area()
self.assertEqual(round(area, 1), 1140234.8)
@mock.patch("catatom2osm.geo.layer.base.log", m_log)
@mock.patch("catatom2osm.geo.layer.base.tqdm", mock.MagicMock())
def test_explode_multi_parts(self):
multiparts = [
f for f in self.layer.getFeatures() if len(Geometry.get_multipolygon(f)) > 1
]
self.assertGreater(len(multiparts), 0, "There are multipart features")
features_before = self.layer.featureCount()
request = QgsFeatureRequest()
request.setFilterFid(multiparts[0].id())
nparts = len(Geometry.get_multipolygon(multiparts[0]))
self.layer.explode_multi_parts(request)
self.assertEqual(features_before + nparts - 1, self.layer.featureCount())
nparts = sum([len(Geometry.get_multipolygon(f)) for f in multiparts])
self.assertGreater(nparts, len(multiparts), "With more than one part")
self.assertTrue(nparts > 1, "Find a multipart feature")
self.layer.explode_multi_parts()
m = "After exploding there must be more features than before"
self.assertGreater(self.layer.featureCount(), features_before, m)
m = (
"Number of features before plus number of parts minus multiparts "
"equals actual number of features"
)
self.assertEqual(
features_before + nparts - len(multiparts), self.layer.featureCount(), m
)
m = "Parts must be single polygons"
self.assertTrue(
all(
[
len(Geometry.get_multipolygon(f)) == 1
for f in self.layer.getFeatures()
]
),
m,
)
@mock.patch("catatom2osm.geo.layer.base.log", m_log)
def test_get_parents_per_vertex_and_geometries(self):
(
parents_per_vertex,
geometries,
) = self.layer.get_parents_per_vertex_and_geometries()
self.assertEqual(len(geometries), self.layer.featureCount())
self.assertTrue(
all(
[
Geometry.get_multipolygon(geometries[f.id()])
== Geometry.get_multipolygon(f)
for f in self.layer.getFeatures()
]
)
)
self.assertGreater(len(parents_per_vertex), 0)
self.assertTrue(
all(
[
Geometry.fromPointXY(Point(vertex)).intersects(geometries[fid])
for (vertex, fids) in list(parents_per_vertex.items())
for fid in fids
]
)
)
@mock.patch("catatom2osm.geo.layer.base.log", m_log)
@mock.patch("catatom2osm.geo.layer.base.tqdm", mock.MagicMock())
def test_difference(self):
layer1 = PolygonLayer("Polygon", "test1", "memory")
layer2 = PolygonLayer("Polygon", "test2", "memory")
g1 = Geometry.fromPolygonXY(
[
[
Point(10, 10),
Point(20, 10),
Point(20, 20),
Point(10, 20),
Point(10, 10),
]
]
)
g2 = Geometry.fromPolygonXY(
[
[
Point(30, 10),
Point(40, 10),
Point(40, 20),
Point(30, 20),
Point(30, 10),
]
]
)
h1 = Geometry.fromPolygonXY(
[
[
Point(14, 14),
Point(16, 14),
Point(16, 16),
Point(14, 16),
Point(14, 14),
]
]
)
h2 = Geometry.fromPolygonXY(
[
[
Point(20, 10),
Point(30, 10),
Point(30, 20),
Point(20, 20),
Point(20, 10),
]
]
)
h3 = Geometry.fromPolygonXY(
[
[
Point(38, 10),
Point(42, 10),
Point(42, 20),
Point(38, 20),
Point(38, 10),
]
]
)
h4 = Geometry.fromPolygonXY(
[
[
Point(30, 30),
Point(40, 30),
Point(40, 40),
Point(40, 30),
Point(30, 30),
]
]
)
r1 = g1.difference(h1)
r2 = g2.difference(h3)
layer1.writer.addFeatures([QgsFeature() for i in range(2)])
layer1.writer.changeGeometryValues({1: g1, 2: g2})
layer2.writer.addFeatures([QgsFeature() for i in range(4)])
layer2.writer.changeGeometryValues({1: h1, 2: h2, 3: h3, 4: h4})
layer1.difference(layer2)
self.assertEqual(layer1.featureCount(), 2)
request = QgsFeatureRequest().setFilterFid(1)
f1 = next(layer1.getFeatures(request))
request = QgsFeatureRequest().setFilterFid(2)
f2 = next(layer1.getFeatures(request))
self.assertEqual(f1.geometry().difference(r1).area(), 0)
self.assertEqual(f2.geometry().difference(r2).area(), 0) | 0.679498 | 0.516169 |
import pytest
from time import time
from base10.base import Dialect, Metric, Reader, Writer
from base10.exceptions import DialectError
class TestDialects:
def test_dialect_construction(self):
assert isinstance(Dialect(), Dialect)
def test_dialect_from_string_exception(self):
dialect = Dialect()
with pytest.raises(DialectError) as exc:
dialect.from_string('')
assert 'Attempt to read with a write-only dialect' == str(exc.value)
def test_dialect_to_string_exception(self):
dialect = Dialect()
with pytest.raises(DialectError) as exc:
dialect.to_string(None)
assert 'Attempt to write with a read-only dialect' == str(exc.value)
class TestMetrics:
def setup_method(self):
self.metric_name = 'metric'
self.metric_fields = ['value']
self.metric_metadata = ['hostname']
self.metric_values = {'value': 0, 'hostname': 'test', 'time': time()}
def test_metric_properties(self):
metric = Metric(
self.metric_name, self.metric_fields, self.metric_metadata,
**self.metric_values
)
assert metric.name == self.metric_name
assert metric.fields == self.metric_fields
assert metric.metadata == self.metric_metadata
assert metric.values == self.metric_values
def test_metric_handle_time_field(self):
metric = Metric(
self.metric_name, self.metric_fields + ['time'],
self.metric_metadata, **self.metric_values
)
assert 'time' not in metric.fields
def test_metric_add_time(self):
alternative_values = {
'value': 0,
'hostname': 'test'
} # Note: No explicit time
metric = Metric(
self.metric_name, self.metric_fields, self.metric_metadata,
**alternative_values
)
assert 'time' in metric.values
def test_metric_repr(self):
import re
from ast import literal_eval
metric = Metric(
self.metric_name, self.metric_fields, self.metric_metadata,
**self.metric_values
)
regex = '<Metric:"([^"]+)" Fields:(\[[^\]]+\]) Metadata:(\[[^\]]+\]) Values:({[^}]+})>'
match = re.match(regex, repr(metric))
assert match is not None
assert match.lastindex == 4
assert match.group(1) == self.metric_name
assert literal_eval(match.group(2)) == self.metric_fields
assert literal_eval(match.group(3)) == self.metric_metadata
assert literal_eval(match.group(4)) == self.metric_values
def test_metric_name_exception(self):
alternative_values = {
'value': 0,
'host': 'test',
'time': time()
} # Note: "host" not "hostname"
with pytest.raises(NameError) as exc:
metric = Metric(
self.metric_name, self.metric_fields, self.metric_metadata,
**alternative_values
)
assert "Expected ['hostname', 'value'] but got ['host', 'value']" in str(
exc.value
)
class TestTransports:
def test_reader_construction(self):
with pytest.raises(TypeError) as exc:
reader = Reader()
assert "Can't instantiate" in str(exc.value)
def test_writer_construction(self):
with pytest.raises(TypeError) as exc:
writer = Writer()
assert "Can't instantiate" in str(exc.value) | base10/test/test_base.py | import pytest
from time import time
from base10.base import Dialect, Metric, Reader, Writer
from base10.exceptions import DialectError
class TestDialects:
def test_dialect_construction(self):
assert isinstance(Dialect(), Dialect)
def test_dialect_from_string_exception(self):
dialect = Dialect()
with pytest.raises(DialectError) as exc:
dialect.from_string('')
assert 'Attempt to read with a write-only dialect' == str(exc.value)
def test_dialect_to_string_exception(self):
dialect = Dialect()
with pytest.raises(DialectError) as exc:
dialect.to_string(None)
assert 'Attempt to write with a read-only dialect' == str(exc.value)
class TestMetrics:
def setup_method(self):
self.metric_name = 'metric'
self.metric_fields = ['value']
self.metric_metadata = ['hostname']
self.metric_values = {'value': 0, 'hostname': 'test', 'time': time()}
def test_metric_properties(self):
metric = Metric(
self.metric_name, self.metric_fields, self.metric_metadata,
**self.metric_values
)
assert metric.name == self.metric_name
assert metric.fields == self.metric_fields
assert metric.metadata == self.metric_metadata
assert metric.values == self.metric_values
def test_metric_handle_time_field(self):
metric = Metric(
self.metric_name, self.metric_fields + ['time'],
self.metric_metadata, **self.metric_values
)
assert 'time' not in metric.fields
def test_metric_add_time(self):
alternative_values = {
'value': 0,
'hostname': 'test'
} # Note: No explicit time
metric = Metric(
self.metric_name, self.metric_fields, self.metric_metadata,
**alternative_values
)
assert 'time' in metric.values
def test_metric_repr(self):
import re
from ast import literal_eval
metric = Metric(
self.metric_name, self.metric_fields, self.metric_metadata,
**self.metric_values
)
regex = '<Metric:"([^"]+)" Fields:(\[[^\]]+\]) Metadata:(\[[^\]]+\]) Values:({[^}]+})>'
match = re.match(regex, repr(metric))
assert match is not None
assert match.lastindex == 4
assert match.group(1) == self.metric_name
assert literal_eval(match.group(2)) == self.metric_fields
assert literal_eval(match.group(3)) == self.metric_metadata
assert literal_eval(match.group(4)) == self.metric_values
def test_metric_name_exception(self):
alternative_values = {
'value': 0,
'host': 'test',
'time': time()
} # Note: "host" not "hostname"
with pytest.raises(NameError) as exc:
metric = Metric(
self.metric_name, self.metric_fields, self.metric_metadata,
**alternative_values
)
assert "Expected ['hostname', 'value'] but got ['host', 'value']" in str(
exc.value
)
class TestTransports:
def test_reader_construction(self):
with pytest.raises(TypeError) as exc:
reader = Reader()
assert "Can't instantiate" in str(exc.value)
def test_writer_construction(self):
with pytest.raises(TypeError) as exc:
writer = Writer()
assert "Can't instantiate" in str(exc.value) | 0.826397 | 0.603172 |
import numpy as np
from tqdm import tqdm
import h5py
from pathlib import Path
from urllib.request import urlretrieve
from zipfile import ZipFile
from scipy.io import loadmat
from hsdatasets.utils import TqdmUpTo
DATASETS_CONFIG = {
'HyKo2-VIS': {
'name': 'vis_annotated.zip',
'url': 'https://hyko-proxy.uni-koblenz.de/hyko-dataset/HyKo2/vis/vis_annotated.zip',
'Semantic': {
'data_key' : 'data',
'label_key' : 'label_Semantic Classes for Urban Scenes',
},
},
'HyKo2-NIR': {
'name': '',
'url':'',
},
}
def download_dataset(base_dir, name):
# configure paths for data dirs
if len(name.split('_')) == 2: # HyKo2 Datasets
name, label_semantics = name.split('_')
base_dir = Path(base_dir).expanduser().joinpath(name)
filepath_data = base_dir.joinpath(DATASETS_CONFIG[name]['name'])
else :
raise RuntimeError(f'Dataset {name} unknown!')
# create dir if not existing
base_dir.mkdir(parents=True, exist_ok=True)
# download zip archive
if not filepath_data.is_file():
with TqdmUpTo(unit='B', unit_scale=True, miniters=1,
desc="Downloading {}".format(filepath_data)) as t:
url = DATASETS_CONFIG[name]['url']
urlretrieve(url, filename=filepath_data, reporthook=t.update_to)
# export data into hdf5
filepath_hdf = base_dir.joinpath(f'{name}_{label_semantics}.h5')
## extract data + labels from archive and store in hdf5-file
with ZipFile(filepath_data, 'r') as zip_ref:
if not filepath_hdf.is_file():
with h5py.File(filepath_hdf, "w") as f:
f.attrs['name'] = name
f.attrs['label_semantics'] = label_semantics
for filename in zip_ref.namelist():
mat = loadmat(zip_ref.open(filename))
data = mat.get(DATASETS_CONFIG[name][label_semantics]['data_key'])
labels = mat.get(DATASETS_CONFIG[name][label_semantics]['label_key'])
# skip if data or label do not exist
if data is not None and labels is not None :
matgroup = f.create_group(filename)
matgroup.create_dataset("data",
data=data)
matgroup.create_dataset("labels",
data=labels)
else :
# print name of file and keys to find broken or incomplete files
print(f'File {filename} is incomplete. Keys are {mat.keys()}.')
return filepath_hdf | hsdatasets/groundbased/prep.py | import numpy as np
from tqdm import tqdm
import h5py
from pathlib import Path
from urllib.request import urlretrieve
from zipfile import ZipFile
from scipy.io import loadmat
from hsdatasets.utils import TqdmUpTo
DATASETS_CONFIG = {
'HyKo2-VIS': {
'name': 'vis_annotated.zip',
'url': 'https://hyko-proxy.uni-koblenz.de/hyko-dataset/HyKo2/vis/vis_annotated.zip',
'Semantic': {
'data_key' : 'data',
'label_key' : 'label_Semantic Classes for Urban Scenes',
},
},
'HyKo2-NIR': {
'name': '',
'url':'',
},
}
def download_dataset(base_dir, name):
# configure paths for data dirs
if len(name.split('_')) == 2: # HyKo2 Datasets
name, label_semantics = name.split('_')
base_dir = Path(base_dir).expanduser().joinpath(name)
filepath_data = base_dir.joinpath(DATASETS_CONFIG[name]['name'])
else :
raise RuntimeError(f'Dataset {name} unknown!')
# create dir if not existing
base_dir.mkdir(parents=True, exist_ok=True)
# download zip archive
if not filepath_data.is_file():
with TqdmUpTo(unit='B', unit_scale=True, miniters=1,
desc="Downloading {}".format(filepath_data)) as t:
url = DATASETS_CONFIG[name]['url']
urlretrieve(url, filename=filepath_data, reporthook=t.update_to)
# export data into hdf5
filepath_hdf = base_dir.joinpath(f'{name}_{label_semantics}.h5')
## extract data + labels from archive and store in hdf5-file
with ZipFile(filepath_data, 'r') as zip_ref:
if not filepath_hdf.is_file():
with h5py.File(filepath_hdf, "w") as f:
f.attrs['name'] = name
f.attrs['label_semantics'] = label_semantics
for filename in zip_ref.namelist():
mat = loadmat(zip_ref.open(filename))
data = mat.get(DATASETS_CONFIG[name][label_semantics]['data_key'])
labels = mat.get(DATASETS_CONFIG[name][label_semantics]['label_key'])
# skip if data or label do not exist
if data is not None and labels is not None :
matgroup = f.create_group(filename)
matgroup.create_dataset("data",
data=data)
matgroup.create_dataset("labels",
data=labels)
else :
# print name of file and keys to find broken or incomplete files
print(f'File {filename} is incomplete. Keys are {mat.keys()}.')
return filepath_hdf | 0.150216 | 0.207757 |
import sys
import time
import os
import socket
import errno
#----------------------------------------------------------------------
# FlashPolicy
#----------------------------------------------------------------------
class policysvr (object):
def __init__ (self):
self._clients = {}
self._sock4 = None
self._sock6 = None
self._timeout = 10
self._errd = [ errno.EINPROGRESS, errno.EALREADY, errno.EWOULDBLOCK ]
if 'WSAEWOULDBLOCK' in errno.__dict__:
self._errd.append(errno.WSAEWOULDBLOCK)
self._errd = tuple(self._errd)
self._history = []
self._count = 0
self._startts = time.time()
self._startdt = time.strftime('%Y-%m-%d %H:%M:%S')
def startup (self, port = 8430, policy = '', timeout = 10):
self.shutdown()
self._port = port
self._policy = policy
binding = '0.0.0.0'
self._sock4 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._sock4.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
try:
self._sock4.bind((binding, port))
except:
try: self._sock4.close()
except: pass
self._sock4 = None
return -1
self._sock4.listen(10)
self._sock4.setblocking(0)
if 'AF_INET6' in socket.__dict__ and socket.has_ipv6:
try:
self._sock6 = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
self._sock6.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
if 'IPPROTO_IPV6' in socket.__dict__:
self._sock6.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 1)
self._sock6.bind(('', port))
except:
try: self._sock6.close()
except: pass
self._sock6 = None
if self._sock6:
self._sock6.listen(10)
self._sock6.setblocking(0)
self._current = time.time()
self._timeout = timeout
self._history = []
self._count = 0
self._startts = time.time()
self._startdt = time.strftime('%Y-%m-%d %H:%M:%S')
return 0
def shutdown (self):
if self._sock4:
try: self._sock4.close()
except: pass
if self._sock6:
try: self._sock6.close()
except: pass
self._sock4 = None
self._sock6 = None
self._index = 0
cidlist = [ cid for cid in self._clients ]
for cid in cidlist:
client = self._clients[cid]
try: client[0].close()
except: pass
client[0] = None
client[1] = ''
client[2] = ''
client[3] = -1
client[4] = 0
del self._clients[cid]
self._clients = {}
return 0
def __handle_accept (self, xsock):
if not xsock:
return -1
sock = None
try:
sock, remote = xsock.accept()
sock.setblocking(0)
except: pass
if not sock:
return -2
client = [ sock, '', '', 0, self._current + self._timeout, remote ]
self._clients[self._index] = client
self._index += 1
return 0
def __handle_client (self, client):
sock, rbuf, sbuf, state, timeout, remote = client
if state == 0:
rdata = ''
while 1:
text = ''
try:
text = sock.recv(1024)
if not text:
errc = 10000
sock.close()
return -1
except socket.error,(code, strerror):
if not code in self._errd:
sock.close()
return -2
if text == '':
break
rdata += text
rbuf += rdata
client[1] = rbuf
request = '<policy-file-request/>'
if rbuf[:len(request)] == request:
client[3] = 1
client[2] = self._policy
state = 1
self._count += 1
ts = time.strftime('%Y-%m-%d %H:%M:%S')
self._history.append('[%s] %s'%(ts, str(remote)))
if len(self._history) > 16:
self._history = self._history[-16:]
elif rbuf[:4].lower() == 'get ' and rbuf[-4:] == '\r\n\r\n':
request = rbuf[4:rbuf.find('\n')].strip('\r\n')
if request[-8:-3] == 'HTTP/':
request = request[:-9]
try:
hr = self.http(request.strip('\r\n\t '), rbuf, remote)
except:
import cStringIO, traceback
sio = cStringIO.StringIO()
traceback.print_exc(file = sio)
err = 'INTERNAL SERVER ERROR\r\n\r\n' + sio.getvalue()
hr = ('500 INTERNAL SERVER ERROR', 'text/plain', err)
if not hr:
hr = ('404 NOT FIND', 'text/plain', 'NOT FIND')
code, mime, text = hr
output = 'HTTP/1.0 %s\r\nConnection: Close\r\n'%code
output += 'Content-Type: %s\r\n'%mime
output += 'Content-Length: %d\r\n\r\n'%len(text)
client[2] = output + text
client[3] = 1
state = 1
if state == 1:
wsize = 0
sbuf = client[2]
if len(sbuf) > 0:
try:
wsize = sock.send(sbuf)
except socket.error,(code, strerror):
if not code in self._errd:
sock.close()
return -3
sbuf = sbuf[wsize:]
client[2] = sbuf
if len(sbuf) == 0:
client[3] = 2
state = 2
client[4] = self._current + 0.05
if state == 2:
return 1
if self._current > timeout:
return -4
return 0
def http (self, request, head, remote):
if request == '/':
p = sys.platform
output = 'Flash Polcy Server 1.2 (on %s)\r\n'%p
p, t = self._startdt, (time.time() - self._startts)
c = self._count
output += 'running for %d seconds (since %s) and handle %d requests\r\n'%(t, p, c)
if self._history:
output += '\r\nlogging:\n'
for x in self._history:
output += x + '\r\n'
return ('200 OK', 'text/plain', output)
return None
def process (self):
if self._sock4 == None and self._sock6 == None:
return 0
self._current = time.time()
while 1:
if self.__handle_accept(self._sock4) != 0:
break
while 1:
if self.__handle_accept(self._sock6) != 0:
break
cleanlist = []
for cid in self._clients:
client = self._clients[cid]
if self.__handle_client(client) != 0:
cleanlist.append(cid)
for cid in cleanlist:
client = self._clients[cid]
try: client[0].close()
except: pass
client[0] = None
client[1] = ''
client[2] = ''
client[3] = -1
client[4] = 0
del self._clients[cid]
return 0
#----------------------------------------------------------------------
# daemon
#----------------------------------------------------------------------
def daemon():
if sys.platform[:3] == 'win':
return -1
try:
if os.fork() > 0: os._exit(0)
except OSError, error:
os._exit(1)
os.setsid()
os.umask(0)
try:
if os.fork() > 0: os._exit(0)
except OSError, error:
os._exit(1)
return 0
#----------------------------------------------------------------------
# signals
#----------------------------------------------------------------------
closing = False
def sig_exit (signum, frame):
global closing
closing = True
def signal_initialize():
import signal
signal.signal(signal.SIGTERM, sig_exit)
signal.signal(signal.SIGINT, sig_exit)
signal.signal(signal.SIGABRT, sig_exit)
if 'SIGQUIT' in signal.__dict__:
signal.signal(signal.SIGQUIT, sig_exit)
if 'SIGPIPE' in signal.__dict__:
signal.signal(signal.SIGPIPE, signal.SIG_IGN)
return 0
#----------------------------------------------------------------------
# main
#----------------------------------------------------------------------
def main(argv = None):
argv = [ n for n in (argv and argv or sys.argv) ]
import optparse
p = optparse.OptionParser('usage: %prog [options] to start policy server')
p.add_option('-p', '--port', dest = 'port', help = 'flash policy server listening port')
p.add_option('-f', '--filename', dest = 'filename', metavar='FILE', help = 'policy filename')
p.add_option('-i', '--pid', dest = 'pid', help = 'pid file path')
p.add_option('-t', '--timeout', dest = 'timeout', help = 'connection time out (in second)')
p.add_option('-d', '--daemon', action = 'store_true', dest = 'daemon', help = 'run as daemon')
options, args = p.parse_args(argv)
if not options.port:
print 'No listening port. Try --help for more information.'
return 2
if not options.filename:
print 'No policy filename. Try --help for more information.'
return 2
try:
port = int(options.port)
except:
print 'bad port number "%s"'%options.port
return 3
filename = options.filename
if filename:
if not os.path.exists(filename):
filename = None
if not filename:
print 'invalid file name'
return 4
try:
text = open(filename, 'rb').read()
except:
print 'cannot read %s'%filename
return 5
timeout = 10
if options.timeout:
try:
timeout = int(options.timeout)
except:
print 'bad timeout "%s"'%options.timeout
return 6
svr = policysvr()
if svr.startup (port, text, timeout) != 0:
print 'can not listen port %d'%port
svr.shutdown()
return 1
if options.daemon:
if sys.platform[:3] == 'win':
print 'daemon mode does support in windows'
elif not 'fork' in os.__dict__:
print 'can not fork myself'
else:
daemon()
if options.pid:
try:
fp = open(options.pid, 'w')
fp.write('%d'%os.getpid())
fp.close()
except:
pass
if sys.platform[:3] != 'win':
signal_initialize()
try:
while not closing:
svr.process()
time.sleep(0.1)
except KeyboardInterrupt:
pass
svr.shutdown()
if options.pid:
if os.path.exists(options.pid):
os.remove(options.pid)
return 0
#----------------------------------------------------------------------
# testing case
#----------------------------------------------------------------------
if __name__ == '__main__':
def test1():
#main(['--daemon'])
#main(['--help'])
main(['--filename=../conf/flashpolicy.xml', '--pid=fuck.pid', '--port=8430', '--timeout=5'])
return 0
#test1()
#main(['--help'])
#main(['--port=1111'])
main() | cannon/bin/flashsvr.py | import sys
import time
import os
import socket
import errno
#----------------------------------------------------------------------
# FlashPolicy
#----------------------------------------------------------------------
class policysvr (object):
def __init__ (self):
self._clients = {}
self._sock4 = None
self._sock6 = None
self._timeout = 10
self._errd = [ errno.EINPROGRESS, errno.EALREADY, errno.EWOULDBLOCK ]
if 'WSAEWOULDBLOCK' in errno.__dict__:
self._errd.append(errno.WSAEWOULDBLOCK)
self._errd = tuple(self._errd)
self._history = []
self._count = 0
self._startts = time.time()
self._startdt = time.strftime('%Y-%m-%d %H:%M:%S')
def startup (self, port = 8430, policy = '', timeout = 10):
self.shutdown()
self._port = port
self._policy = policy
binding = '0.0.0.0'
self._sock4 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._sock4.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
try:
self._sock4.bind((binding, port))
except:
try: self._sock4.close()
except: pass
self._sock4 = None
return -1
self._sock4.listen(10)
self._sock4.setblocking(0)
if 'AF_INET6' in socket.__dict__ and socket.has_ipv6:
try:
self._sock6 = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
self._sock6.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
if 'IPPROTO_IPV6' in socket.__dict__:
self._sock6.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 1)
self._sock6.bind(('', port))
except:
try: self._sock6.close()
except: pass
self._sock6 = None
if self._sock6:
self._sock6.listen(10)
self._sock6.setblocking(0)
self._current = time.time()
self._timeout = timeout
self._history = []
self._count = 0
self._startts = time.time()
self._startdt = time.strftime('%Y-%m-%d %H:%M:%S')
return 0
def shutdown (self):
if self._sock4:
try: self._sock4.close()
except: pass
if self._sock6:
try: self._sock6.close()
except: pass
self._sock4 = None
self._sock6 = None
self._index = 0
cidlist = [ cid for cid in self._clients ]
for cid in cidlist:
client = self._clients[cid]
try: client[0].close()
except: pass
client[0] = None
client[1] = ''
client[2] = ''
client[3] = -1
client[4] = 0
del self._clients[cid]
self._clients = {}
return 0
def __handle_accept (self, xsock):
if not xsock:
return -1
sock = None
try:
sock, remote = xsock.accept()
sock.setblocking(0)
except: pass
if not sock:
return -2
client = [ sock, '', '', 0, self._current + self._timeout, remote ]
self._clients[self._index] = client
self._index += 1
return 0
def __handle_client (self, client):
sock, rbuf, sbuf, state, timeout, remote = client
if state == 0:
rdata = ''
while 1:
text = ''
try:
text = sock.recv(1024)
if not text:
errc = 10000
sock.close()
return -1
except socket.error,(code, strerror):
if not code in self._errd:
sock.close()
return -2
if text == '':
break
rdata += text
rbuf += rdata
client[1] = rbuf
request = '<policy-file-request/>'
if rbuf[:len(request)] == request:
client[3] = 1
client[2] = self._policy
state = 1
self._count += 1
ts = time.strftime('%Y-%m-%d %H:%M:%S')
self._history.append('[%s] %s'%(ts, str(remote)))
if len(self._history) > 16:
self._history = self._history[-16:]
elif rbuf[:4].lower() == 'get ' and rbuf[-4:] == '\r\n\r\n':
request = rbuf[4:rbuf.find('\n')].strip('\r\n')
if request[-8:-3] == 'HTTP/':
request = request[:-9]
try:
hr = self.http(request.strip('\r\n\t '), rbuf, remote)
except:
import cStringIO, traceback
sio = cStringIO.StringIO()
traceback.print_exc(file = sio)
err = 'INTERNAL SERVER ERROR\r\n\r\n' + sio.getvalue()
hr = ('500 INTERNAL SERVER ERROR', 'text/plain', err)
if not hr:
hr = ('404 NOT FIND', 'text/plain', 'NOT FIND')
code, mime, text = hr
output = 'HTTP/1.0 %s\r\nConnection: Close\r\n'%code
output += 'Content-Type: %s\r\n'%mime
output += 'Content-Length: %d\r\n\r\n'%len(text)
client[2] = output + text
client[3] = 1
state = 1
if state == 1:
wsize = 0
sbuf = client[2]
if len(sbuf) > 0:
try:
wsize = sock.send(sbuf)
except socket.error,(code, strerror):
if not code in self._errd:
sock.close()
return -3
sbuf = sbuf[wsize:]
client[2] = sbuf
if len(sbuf) == 0:
client[3] = 2
state = 2
client[4] = self._current + 0.05
if state == 2:
return 1
if self._current > timeout:
return -4
return 0
def http (self, request, head, remote):
if request == '/':
p = sys.platform
output = 'Flash Polcy Server 1.2 (on %s)\r\n'%p
p, t = self._startdt, (time.time() - self._startts)
c = self._count
output += 'running for %d seconds (since %s) and handle %d requests\r\n'%(t, p, c)
if self._history:
output += '\r\nlogging:\n'
for x in self._history:
output += x + '\r\n'
return ('200 OK', 'text/plain', output)
return None
def process (self):
if self._sock4 == None and self._sock6 == None:
return 0
self._current = time.time()
while 1:
if self.__handle_accept(self._sock4) != 0:
break
while 1:
if self.__handle_accept(self._sock6) != 0:
break
cleanlist = []
for cid in self._clients:
client = self._clients[cid]
if self.__handle_client(client) != 0:
cleanlist.append(cid)
for cid in cleanlist:
client = self._clients[cid]
try: client[0].close()
except: pass
client[0] = None
client[1] = ''
client[2] = ''
client[3] = -1
client[4] = 0
del self._clients[cid]
return 0
#----------------------------------------------------------------------
# daemon
#----------------------------------------------------------------------
def daemon():
if sys.platform[:3] == 'win':
return -1
try:
if os.fork() > 0: os._exit(0)
except OSError, error:
os._exit(1)
os.setsid()
os.umask(0)
try:
if os.fork() > 0: os._exit(0)
except OSError, error:
os._exit(1)
return 0
#----------------------------------------------------------------------
# signals
#----------------------------------------------------------------------
closing = False
def sig_exit (signum, frame):
global closing
closing = True
def signal_initialize():
import signal
signal.signal(signal.SIGTERM, sig_exit)
signal.signal(signal.SIGINT, sig_exit)
signal.signal(signal.SIGABRT, sig_exit)
if 'SIGQUIT' in signal.__dict__:
signal.signal(signal.SIGQUIT, sig_exit)
if 'SIGPIPE' in signal.__dict__:
signal.signal(signal.SIGPIPE, signal.SIG_IGN)
return 0
#----------------------------------------------------------------------
# main
#----------------------------------------------------------------------
def main(argv = None):
argv = [ n for n in (argv and argv or sys.argv) ]
import optparse
p = optparse.OptionParser('usage: %prog [options] to start policy server')
p.add_option('-p', '--port', dest = 'port', help = 'flash policy server listening port')
p.add_option('-f', '--filename', dest = 'filename', metavar='FILE', help = 'policy filename')
p.add_option('-i', '--pid', dest = 'pid', help = 'pid file path')
p.add_option('-t', '--timeout', dest = 'timeout', help = 'connection time out (in second)')
p.add_option('-d', '--daemon', action = 'store_true', dest = 'daemon', help = 'run as daemon')
options, args = p.parse_args(argv)
if not options.port:
print 'No listening port. Try --help for more information.'
return 2
if not options.filename:
print 'No policy filename. Try --help for more information.'
return 2
try:
port = int(options.port)
except:
print 'bad port number "%s"'%options.port
return 3
filename = options.filename
if filename:
if not os.path.exists(filename):
filename = None
if not filename:
print 'invalid file name'
return 4
try:
text = open(filename, 'rb').read()
except:
print 'cannot read %s'%filename
return 5
timeout = 10
if options.timeout:
try:
timeout = int(options.timeout)
except:
print 'bad timeout "%s"'%options.timeout
return 6
svr = policysvr()
if svr.startup (port, text, timeout) != 0:
print 'can not listen port %d'%port
svr.shutdown()
return 1
if options.daemon:
if sys.platform[:3] == 'win':
print 'daemon mode does support in windows'
elif not 'fork' in os.__dict__:
print 'can not fork myself'
else:
daemon()
if options.pid:
try:
fp = open(options.pid, 'w')
fp.write('%d'%os.getpid())
fp.close()
except:
pass
if sys.platform[:3] != 'win':
signal_initialize()
try:
while not closing:
svr.process()
time.sleep(0.1)
except KeyboardInterrupt:
pass
svr.shutdown()
if options.pid:
if os.path.exists(options.pid):
os.remove(options.pid)
return 0
#----------------------------------------------------------------------
# testing case
#----------------------------------------------------------------------
if __name__ == '__main__':
def test1():
#main(['--daemon'])
#main(['--help'])
main(['--filename=../conf/flashpolicy.xml', '--pid=fuck.pid', '--port=8430', '--timeout=5'])
return 0
#test1()
#main(['--help'])
#main(['--port=1111'])
main() | 0.0713 | 0.066509 |
from y2h.parser.base import BaseParser
from y2h.parser.factory import ElemParserFactory
TABLE_STYLE_CLASSES = {
'default': 'table',
'striped': 'table table-striped',
'bordered': 'table table-bordered',
'hover': 'table table-hover',
'condensed': 'table table-condensed',
}
class TableParser(BaseParser):
def __init__(self, template, elem_type, elem_value):
super(TableParser, self).__init__(template, elem_type, elem_value)
self.specific_attrs = {
'thead': self.parse_table_thead,
'tbody': self.parse_table_tbody,
}
# number of columns
self.col_num = 0
def pre_parse(self):
# after pre paresing, self.attr_dict has been built
super(TableParser, self).pre_parse()
# handle keyword 'style'
KEYWORD_STYLE = 'table-style'
table_style = self.attr_dict.get(KEYWORD_STYLE, 'default')
table_class = TABLE_STYLE_CLASSES.get(table_style, TABLE_STYLE_CLASSES['default'])
self.add_class(table_class)
if KEYWORD_STYLE in self.attr_dict.keys():
del self.attr_dict[KEYWORD_STYLE]
def parse_table_thead(self, spec_attr_name):
""" Parse panel header, now only support text in header """
ATTR_NAME = 'thead'
if spec_attr_name != ATTR_NAME:
raise ValueError('Invalid spec_attr_name:{0} in parse_table_thead'.format(spec_attr_name))
if not isinstance(self.elem_value, dict):
return
thead_value = self.elem_value.get(ATTR_NAME, None)
if isinstance(thead_value, list):
self._[ATTR_NAME] = thead_value
# save number of columns
self.col_num = len(thead_value)
def parse_table_tbody(self, spec_attr_name):
""" There may exist multiple items under panel-body"""
ATTR_NAME = 'tbody'
if spec_attr_name != ATTR_NAME:
raise ValueError('Invalid spec_attr_name:{0} in parse_table_tbody'.format(spec_attr_name))
if not isinstance(self.elem_value, dict):
return
tbody_value = self.elem_value.get(ATTR_NAME, None)
if isinstance(tbody_value, list):
# as we already make sure tbody_value is a list
for tr in tbody_value:
if not isinstance(tr, list):
raise ValueError('Invalid table row, it should be a list')
if len(tr) != self.col_num:
raise ValueError('Invalid table row, it should equals to number of columns:{0}'.format(self.col_num))
self._[ATTR_NAME] = tbody_value | y2h/parser/elems/table.py | from y2h.parser.base import BaseParser
from y2h.parser.factory import ElemParserFactory
TABLE_STYLE_CLASSES = {
'default': 'table',
'striped': 'table table-striped',
'bordered': 'table table-bordered',
'hover': 'table table-hover',
'condensed': 'table table-condensed',
}
class TableParser(BaseParser):
def __init__(self, template, elem_type, elem_value):
super(TableParser, self).__init__(template, elem_type, elem_value)
self.specific_attrs = {
'thead': self.parse_table_thead,
'tbody': self.parse_table_tbody,
}
# number of columns
self.col_num = 0
def pre_parse(self):
# after pre paresing, self.attr_dict has been built
super(TableParser, self).pre_parse()
# handle keyword 'style'
KEYWORD_STYLE = 'table-style'
table_style = self.attr_dict.get(KEYWORD_STYLE, 'default')
table_class = TABLE_STYLE_CLASSES.get(table_style, TABLE_STYLE_CLASSES['default'])
self.add_class(table_class)
if KEYWORD_STYLE in self.attr_dict.keys():
del self.attr_dict[KEYWORD_STYLE]
def parse_table_thead(self, spec_attr_name):
""" Parse panel header, now only support text in header """
ATTR_NAME = 'thead'
if spec_attr_name != ATTR_NAME:
raise ValueError('Invalid spec_attr_name:{0} in parse_table_thead'.format(spec_attr_name))
if not isinstance(self.elem_value, dict):
return
thead_value = self.elem_value.get(ATTR_NAME, None)
if isinstance(thead_value, list):
self._[ATTR_NAME] = thead_value
# save number of columns
self.col_num = len(thead_value)
def parse_table_tbody(self, spec_attr_name):
""" There may exist multiple items under panel-body"""
ATTR_NAME = 'tbody'
if spec_attr_name != ATTR_NAME:
raise ValueError('Invalid spec_attr_name:{0} in parse_table_tbody'.format(spec_attr_name))
if not isinstance(self.elem_value, dict):
return
tbody_value = self.elem_value.get(ATTR_NAME, None)
if isinstance(tbody_value, list):
# as we already make sure tbody_value is a list
for tr in tbody_value:
if not isinstance(tr, list):
raise ValueError('Invalid table row, it should be a list')
if len(tr) != self.col_num:
raise ValueError('Invalid table row, it should equals to number of columns:{0}'.format(self.col_num))
self._[ATTR_NAME] = tbody_value | 0.444083 | 0.159217 |
from django.test import TestCase
from core import factories, models
from core.models.base import DeadlineFrequency, PieceType, Phase, Season
from core.tests import DiplomacyTestCaseMixin
class TestTurn(TestCase, DiplomacyTestCaseMixin):
def setUp(self):
self.variant = models.Variant.objects.get(id='standard')
self.user = factories.UserFactory()
self.game = models.Game.objects.create(
name='Test game',
variant=self.variant,
num_players=7,
created_by=self.user,
)
self.game.participants.add(self.user)
def test_ready_to_process_retreat(self):
retreat_turn = models.Turn.objects.create(
game=self.game,
phase=Phase.RETREAT,
season=Season.FALL,
year=1901,
)
england = self.variant.nations.get(name='England')
france = self.variant.nations.get(name='France')
other_user = factories.UserFactory()
self.game.participants.add(other_user)
models.NationState.objects.create(
turn=retreat_turn,
nation=england,
user=other_user
)
france_state = models.NationState.objects.create(
turn=retreat_turn,
nation=france,
user=self.user
)
piece = models.Piece.objects.create(
game=self.game,
nation=france,
type=PieceType.ARMY,
)
models.PieceState.objects.create(
piece=piece,
turn=retreat_turn,
must_retreat=True,
)
self.assertFalse(retreat_turn.ready_to_process)
# only nation states which have orders to submit must finalize
france_state.orders_finalized = True
france_state.save()
self.assertTrue(retreat_turn.ready_to_process)
def test_ready_to_process_build(self):
build_turn = models.Turn.objects.create(
game=self.game,
phase=Phase.BUILD,
season=Season.FALL,
year=1901,
)
england = self.variant.nations.get(name='England')
france = self.variant.nations.get(name='France')
other_user = factories.UserFactory()
self.game.participants.add(other_user)
models.NationState.objects.create(
turn=build_turn,
nation=england,
user=other_user
)
france_state = models.NationState.objects.create(
turn=build_turn,
nation=france,
user=self.user
)
territory = models.Territory.objects.get(
name='Marseilles',
)
models.TerritoryState.objects.create(
turn=build_turn,
territory=territory,
controlled_by=france,
)
self.assertFalse(build_turn.ready_to_process)
# only nation states which have orders to submit must finalize
france_state.orders_finalized = True
france_state.save()
self.assertTrue(build_turn.ready_to_process)
def test_check_for_winning_nation(self):
turn = models.Turn.objects.create(
game=self.game,
phase=Phase.ORDER,
season=Season.FALL,
year=1901,
)
france = self.variant.nations.get(name='France')
france_state = models.NationState.objects.create(
turn=turn,
nation=france,
user=self.user
)
for i in range(17):
territory = models.Territory.objects.create(
name='Territory Name ' + str(i),
variant=self.variant,
nationality=france,
supply_center=True,
)
models.TerritoryState.objects.create(
territory=territory,
turn=turn,
controlled_by=france,
)
self.assertEqual(france_state.supply_centers.count(), 17)
self.assertFalse(turn.check_for_winning_nation())
territory = models.Territory.objects.create(
name='Winning territory',
variant=self.variant,
nationality=france,
supply_center=True,
)
models.TerritoryState.objects.create(
territory=territory,
turn=turn,
controlled_by=france,
)
self.assertEqual(france_state.supply_centers.count(), 18)
self.assertTrue(turn.check_for_winning_nation())
def test_turn_end_none(self):
turn = self.create_test_turn(game=self.game)
self.assertIsNone(turn.turn_end)
def test_deadline_order(self):
self.game.order_deadline = DeadlineFrequency.SEVEN_DAYS
self.game.save()
turn = self.create_test_turn(game=self.game)
self.assertEqual(turn.deadline, DeadlineFrequency.SEVEN_DAYS)
def test_deadline_retreat(self):
self.game.retreat_deadline = DeadlineFrequency.FIVE_DAYS
self.game.save()
turn = self.create_test_turn(
game=self.game,
phase=Phase.RETREAT
)
self.assertEqual(turn.deadline, DeadlineFrequency.FIVE_DAYS)
def test_deadline_build(self):
self.game.build_deadline = DeadlineFrequency.THREE_DAYS
self.game.save()
turn = self.create_test_turn(game=self.game, phase=Phase.BUILD)
self.assertEqual(turn.deadline, DeadlineFrequency.THREE_DAYS)
class TestLinkedTurns(TestCase):
def setUp(self):
self.variant = factories.StandardVariantFactory()
self.user = factories.UserFactory()
self.game_a = models.Game.objects.create(
name='Test game A',
variant=self.variant,
num_players=7,
created_by=self.user,
)
self.game_b = models.Game.objects.create(
name='Test game B',
variant=self.variant,
num_players=7,
created_by=self.user,
)
self.game_a_spring_order_turn = models.Turn.objects.create(
game=self.game_a,
phase=Phase.ORDER,
season=Season.SPRING,
year=1901,
)
self.game_b_spring_order_turn = models.Turn.objects.create(
game=self.game_b,
phase=Phase.ORDER,
season=Season.SPRING,
year=1901,
)
self.game_a_spring_retreat_turn = models.Turn.objects.create(
game=self.game_a,
phase=Phase.RETREAT,
season=Season.SPRING,
year=1901,
)
self.game_b_spring_retreat_turn = models.Turn.objects.create(
game=self.game_b,
phase=Phase.RETREAT,
season=Season.SPRING,
year=1901,
)
self.game_a_fall_order_turn = models.Turn.objects.create(
game=self.game_a,
phase=Phase.ORDER,
season=Season.FALL,
year=1901,
)
self.game_b_fall_order_turn = models.Turn.objects.create(
game=self.game_b,
phase=Phase.ORDER,
season=Season.FALL,
year=1901,
)
self.game_a_fall_retreat_turn = models.Turn.objects.create(
game=self.game_a,
phase=Phase.RETREAT,
season=Season.FALL,
year=1901,
)
self.game_b_fall_retreat_turn = models.Turn.objects.create(
game=self.game_b,
phase=Phase.RETREAT,
season=Season.FALL,
year=1901,
)
self.game_a_fall_build_turn = models.Turn.objects.create(
game=self.game_a,
phase=Phase.BUILD,
season=Season.FALL,
year=1901,
)
self.game_b_fall_build_turn = models.Turn.objects.create(
game=self.game_b,
phase=Phase.BUILD,
season=Season.FALL,
year=1901,
)
self.game_a_spring_order_turn_1902 = models.Turn.objects.create(
game=self.game_a,
phase=Phase.ORDER,
season=Season.SPRING,
year=1902,
)
self.game_b_spring_order_turn_1902 = models.Turn.objects.create(
game=self.game_b,
phase=Phase.ORDER,
season=Season.SPRING,
year=1902,
)
def test_get_next_turn(self):
turn = self.game_a_spring_order_turn
turn = models.Turn.get_next(turn)
self.assertEqual(turn, self.game_a_spring_retreat_turn)
turn = models.Turn.get_next(turn)
self.assertEqual(turn, self.game_a_fall_order_turn)
turn = models.Turn.get_next(turn)
self.assertEqual(turn, self.game_a_fall_retreat_turn)
turn = models.Turn.get_next(turn)
self.assertEqual(turn, self.game_a_fall_build_turn)
turn = models.Turn.get_next(turn)
self.assertEqual(turn, self.game_a_spring_order_turn_1902)
turn = models.Turn.get_next(turn)
self.assertIsNone(turn)
turn = self.game_b_spring_order_turn
turn = models.Turn.get_next(turn)
self.assertEqual(turn, self.game_b_spring_retreat_turn)
turn = models.Turn.get_next(turn)
self.assertEqual(turn, self.game_b_fall_order_turn)
turn = models.Turn.get_next(turn)
self.assertEqual(turn, self.game_b_fall_retreat_turn)
turn = models.Turn.get_next(turn)
self.assertEqual(turn, self.game_b_fall_build_turn)
turn = models.Turn.get_next(turn)
self.assertEqual(turn, self.game_b_spring_order_turn_1902)
turn = models.Turn.get_next(turn)
self.assertIsNone(turn)
def test_get_previous_turn(self):
turn = self.game_a_spring_order_turn_1902
turn = models.Turn.get_previous(turn)
self.assertEqual(turn, self.game_a_fall_build_turn)
turn = models.Turn.get_previous(turn)
self.assertEqual(turn, self.game_a_fall_retreat_turn)
turn = models.Turn.get_previous(turn)
self.assertEqual(turn, self.game_a_fall_order_turn)
turn = models.Turn.get_previous(turn)
self.assertEqual(turn, self.game_a_spring_retreat_turn)
turn = models.Turn.get_previous(turn)
self.assertEqual(turn, self.game_a_spring_order_turn)
turn = models.Turn.get_previous(turn)
self.assertIsNone(turn)
turn = self.game_b_spring_order_turn_1902
turn = models.Turn.get_previous(turn)
self.assertEqual(turn, self.game_b_fall_build_turn)
turn = models.Turn.get_previous(turn)
self.assertEqual(turn, self.game_b_fall_retreat_turn)
turn = models.Turn.get_previous(turn)
self.assertEqual(turn, self.game_b_fall_order_turn)
turn = models.Turn.get_previous(turn)
self.assertEqual(turn, self.game_b_spring_retreat_turn)
turn = models.Turn.get_previous(turn)
self.assertEqual(turn, self.game_b_spring_order_turn)
turn = models.Turn.get_previous(turn)
self.assertIsNone(turn)
class TestTurnManager(TestCase, DiplomacyTestCaseMixin):
def setUp(self):
self.variant = models.Variant.objects.get(id='standard')
self.user = factories.UserFactory()
self.game = self.create_test_game()
self.game.participants.add(self.user)
self.patch_process_turn_apply_async()
def test_new(self):
self.assertEqual(models.TurnEnd.objects.count(), 0)
self.game.retreat_deadline = DeadlineFrequency.FIVE_DAYS
self.game.save()
turn = models.Turn.objects.new(
game=self.game,
phase=Phase.RETREAT,
season=Season.FALL,
year=1901,
)
turn_end = models.TurnEnd.objects.get()
self.assertEqual(turn_end.turn, turn)
self.assertSimilarTimestamp(turn_end.datetime, self.tomorrow)
def test_new_no_deadline(self):
self.assertEqual(models.TurnEnd.objects.count(), 0)
self.game.order_deadline = None
self.game.save()
turn = models.Turn.objects.new(
game=self.game,
phase=Phase.ORDER,
season=Season.SPRING,
year=1901,
)
with self.assertRaises(models.TurnEnd.DoesNotExist):
turn.turnend | core/tests/test_turn.py | from django.test import TestCase
from core import factories, models
from core.models.base import DeadlineFrequency, PieceType, Phase, Season
from core.tests import DiplomacyTestCaseMixin
class TestTurn(TestCase, DiplomacyTestCaseMixin):
def setUp(self):
self.variant = models.Variant.objects.get(id='standard')
self.user = factories.UserFactory()
self.game = models.Game.objects.create(
name='Test game',
variant=self.variant,
num_players=7,
created_by=self.user,
)
self.game.participants.add(self.user)
def test_ready_to_process_retreat(self):
retreat_turn = models.Turn.objects.create(
game=self.game,
phase=Phase.RETREAT,
season=Season.FALL,
year=1901,
)
england = self.variant.nations.get(name='England')
france = self.variant.nations.get(name='France')
other_user = factories.UserFactory()
self.game.participants.add(other_user)
models.NationState.objects.create(
turn=retreat_turn,
nation=england,
user=other_user
)
france_state = models.NationState.objects.create(
turn=retreat_turn,
nation=france,
user=self.user
)
piece = models.Piece.objects.create(
game=self.game,
nation=france,
type=PieceType.ARMY,
)
models.PieceState.objects.create(
piece=piece,
turn=retreat_turn,
must_retreat=True,
)
self.assertFalse(retreat_turn.ready_to_process)
# only nation states which have orders to submit must finalize
france_state.orders_finalized = True
france_state.save()
self.assertTrue(retreat_turn.ready_to_process)
def test_ready_to_process_build(self):
build_turn = models.Turn.objects.create(
game=self.game,
phase=Phase.BUILD,
season=Season.FALL,
year=1901,
)
england = self.variant.nations.get(name='England')
france = self.variant.nations.get(name='France')
other_user = factories.UserFactory()
self.game.participants.add(other_user)
models.NationState.objects.create(
turn=build_turn,
nation=england,
user=other_user
)
france_state = models.NationState.objects.create(
turn=build_turn,
nation=france,
user=self.user
)
territory = models.Territory.objects.get(
name='Marseilles',
)
models.TerritoryState.objects.create(
turn=build_turn,
territory=territory,
controlled_by=france,
)
self.assertFalse(build_turn.ready_to_process)
# only nation states which have orders to submit must finalize
france_state.orders_finalized = True
france_state.save()
self.assertTrue(build_turn.ready_to_process)
def test_check_for_winning_nation(self):
turn = models.Turn.objects.create(
game=self.game,
phase=Phase.ORDER,
season=Season.FALL,
year=1901,
)
france = self.variant.nations.get(name='France')
france_state = models.NationState.objects.create(
turn=turn,
nation=france,
user=self.user
)
for i in range(17):
territory = models.Territory.objects.create(
name='Territory Name ' + str(i),
variant=self.variant,
nationality=france,
supply_center=True,
)
models.TerritoryState.objects.create(
territory=territory,
turn=turn,
controlled_by=france,
)
self.assertEqual(france_state.supply_centers.count(), 17)
self.assertFalse(turn.check_for_winning_nation())
territory = models.Territory.objects.create(
name='Winning territory',
variant=self.variant,
nationality=france,
supply_center=True,
)
models.TerritoryState.objects.create(
territory=territory,
turn=turn,
controlled_by=france,
)
self.assertEqual(france_state.supply_centers.count(), 18)
self.assertTrue(turn.check_for_winning_nation())
def test_turn_end_none(self):
turn = self.create_test_turn(game=self.game)
self.assertIsNone(turn.turn_end)
def test_deadline_order(self):
self.game.order_deadline = DeadlineFrequency.SEVEN_DAYS
self.game.save()
turn = self.create_test_turn(game=self.game)
self.assertEqual(turn.deadline, DeadlineFrequency.SEVEN_DAYS)
def test_deadline_retreat(self):
self.game.retreat_deadline = DeadlineFrequency.FIVE_DAYS
self.game.save()
turn = self.create_test_turn(
game=self.game,
phase=Phase.RETREAT
)
self.assertEqual(turn.deadline, DeadlineFrequency.FIVE_DAYS)
def test_deadline_build(self):
self.game.build_deadline = DeadlineFrequency.THREE_DAYS
self.game.save()
turn = self.create_test_turn(game=self.game, phase=Phase.BUILD)
self.assertEqual(turn.deadline, DeadlineFrequency.THREE_DAYS)
class TestLinkedTurns(TestCase):
def setUp(self):
self.variant = factories.StandardVariantFactory()
self.user = factories.UserFactory()
self.game_a = models.Game.objects.create(
name='Test game A',
variant=self.variant,
num_players=7,
created_by=self.user,
)
self.game_b = models.Game.objects.create(
name='Test game B',
variant=self.variant,
num_players=7,
created_by=self.user,
)
self.game_a_spring_order_turn = models.Turn.objects.create(
game=self.game_a,
phase=Phase.ORDER,
season=Season.SPRING,
year=1901,
)
self.game_b_spring_order_turn = models.Turn.objects.create(
game=self.game_b,
phase=Phase.ORDER,
season=Season.SPRING,
year=1901,
)
self.game_a_spring_retreat_turn = models.Turn.objects.create(
game=self.game_a,
phase=Phase.RETREAT,
season=Season.SPRING,
year=1901,
)
self.game_b_spring_retreat_turn = models.Turn.objects.create(
game=self.game_b,
phase=Phase.RETREAT,
season=Season.SPRING,
year=1901,
)
self.game_a_fall_order_turn = models.Turn.objects.create(
game=self.game_a,
phase=Phase.ORDER,
season=Season.FALL,
year=1901,
)
self.game_b_fall_order_turn = models.Turn.objects.create(
game=self.game_b,
phase=Phase.ORDER,
season=Season.FALL,
year=1901,
)
self.game_a_fall_retreat_turn = models.Turn.objects.create(
game=self.game_a,
phase=Phase.RETREAT,
season=Season.FALL,
year=1901,
)
self.game_b_fall_retreat_turn = models.Turn.objects.create(
game=self.game_b,
phase=Phase.RETREAT,
season=Season.FALL,
year=1901,
)
self.game_a_fall_build_turn = models.Turn.objects.create(
game=self.game_a,
phase=Phase.BUILD,
season=Season.FALL,
year=1901,
)
self.game_b_fall_build_turn = models.Turn.objects.create(
game=self.game_b,
phase=Phase.BUILD,
season=Season.FALL,
year=1901,
)
self.game_a_spring_order_turn_1902 = models.Turn.objects.create(
game=self.game_a,
phase=Phase.ORDER,
season=Season.SPRING,
year=1902,
)
self.game_b_spring_order_turn_1902 = models.Turn.objects.create(
game=self.game_b,
phase=Phase.ORDER,
season=Season.SPRING,
year=1902,
)
def test_get_next_turn(self):
turn = self.game_a_spring_order_turn
turn = models.Turn.get_next(turn)
self.assertEqual(turn, self.game_a_spring_retreat_turn)
turn = models.Turn.get_next(turn)
self.assertEqual(turn, self.game_a_fall_order_turn)
turn = models.Turn.get_next(turn)
self.assertEqual(turn, self.game_a_fall_retreat_turn)
turn = models.Turn.get_next(turn)
self.assertEqual(turn, self.game_a_fall_build_turn)
turn = models.Turn.get_next(turn)
self.assertEqual(turn, self.game_a_spring_order_turn_1902)
turn = models.Turn.get_next(turn)
self.assertIsNone(turn)
turn = self.game_b_spring_order_turn
turn = models.Turn.get_next(turn)
self.assertEqual(turn, self.game_b_spring_retreat_turn)
turn = models.Turn.get_next(turn)
self.assertEqual(turn, self.game_b_fall_order_turn)
turn = models.Turn.get_next(turn)
self.assertEqual(turn, self.game_b_fall_retreat_turn)
turn = models.Turn.get_next(turn)
self.assertEqual(turn, self.game_b_fall_build_turn)
turn = models.Turn.get_next(turn)
self.assertEqual(turn, self.game_b_spring_order_turn_1902)
turn = models.Turn.get_next(turn)
self.assertIsNone(turn)
def test_get_previous_turn(self):
turn = self.game_a_spring_order_turn_1902
turn = models.Turn.get_previous(turn)
self.assertEqual(turn, self.game_a_fall_build_turn)
turn = models.Turn.get_previous(turn)
self.assertEqual(turn, self.game_a_fall_retreat_turn)
turn = models.Turn.get_previous(turn)
self.assertEqual(turn, self.game_a_fall_order_turn)
turn = models.Turn.get_previous(turn)
self.assertEqual(turn, self.game_a_spring_retreat_turn)
turn = models.Turn.get_previous(turn)
self.assertEqual(turn, self.game_a_spring_order_turn)
turn = models.Turn.get_previous(turn)
self.assertIsNone(turn)
turn = self.game_b_spring_order_turn_1902
turn = models.Turn.get_previous(turn)
self.assertEqual(turn, self.game_b_fall_build_turn)
turn = models.Turn.get_previous(turn)
self.assertEqual(turn, self.game_b_fall_retreat_turn)
turn = models.Turn.get_previous(turn)
self.assertEqual(turn, self.game_b_fall_order_turn)
turn = models.Turn.get_previous(turn)
self.assertEqual(turn, self.game_b_spring_retreat_turn)
turn = models.Turn.get_previous(turn)
self.assertEqual(turn, self.game_b_spring_order_turn)
turn = models.Turn.get_previous(turn)
self.assertIsNone(turn)
class TestTurnManager(TestCase, DiplomacyTestCaseMixin):
def setUp(self):
self.variant = models.Variant.objects.get(id='standard')
self.user = factories.UserFactory()
self.game = self.create_test_game()
self.game.participants.add(self.user)
self.patch_process_turn_apply_async()
def test_new(self):
self.assertEqual(models.TurnEnd.objects.count(), 0)
self.game.retreat_deadline = DeadlineFrequency.FIVE_DAYS
self.game.save()
turn = models.Turn.objects.new(
game=self.game,
phase=Phase.RETREAT,
season=Season.FALL,
year=1901,
)
turn_end = models.TurnEnd.objects.get()
self.assertEqual(turn_end.turn, turn)
self.assertSimilarTimestamp(turn_end.datetime, self.tomorrow)
def test_new_no_deadline(self):
self.assertEqual(models.TurnEnd.objects.count(), 0)
self.game.order_deadline = None
self.game.save()
turn = models.Turn.objects.new(
game=self.game,
phase=Phase.ORDER,
season=Season.SPRING,
year=1901,
)
with self.assertRaises(models.TurnEnd.DoesNotExist):
turn.turnend | 0.570331 | 0.306268 |
from elasticsearch.client.utils import AddonClient, query_params, _make_path, SKIP_IN_PATH
# COPYPASTA ingredient list:
# https://github.com/elastic/elasticsearch-py/blob/1.x/elasticsearch/client/__init__.py#L809
# https://github.com/elastic/elasticsearch-watcher-py/blob/master/elasticsearch_watcher/watcher.py
class DeleteByQuery(AddonClient):
namespace = 'delete_by_query'
@query_params('allow_no_indices', 'analyzer', 'consistency',
'default_operator', 'df', 'expand_wildcards', 'ignore_unavailable', 'q',
'replication', 'routing', 'timeout')
def delete_by_query(self, index, doc_type=None, body=None, params=None):
"""
Delete documents from one or more indices and one or more types based on a query.
`<http://www.elastic.co/guide/en/elasticsearch/reference/current/docs-delete-by-query.html>`_
:arg index: A comma-separated list of indices to restrict the operation;
use `_all` to perform the operation on all indices
:arg doc_type: A comma-separated list of types to restrict the operation
:arg body: A query to restrict the operation specified with the Query
DSL
:arg allow_no_indices: Whether to ignore if a wildcard indices
expression resolves into no concrete indices. (This includes `_all`
string or when no indices have been specified)
:arg analyzer: The analyzer to use for the query string
:arg consistency: Specific write consistency setting for the operation
:arg default_operator: The default operator for query string query (AND
or OR), default u'OR'
:arg df: The field to use as default where no field prefix is given in
the query string
:arg expand_wildcards: Whether to expand wildcard expression to concrete
indices that are open, closed or both., default u'open'
:arg ignore_unavailable: Whether specified concrete indices should be
ignored when unavailable (missing or closed)
:arg q: Query in the Lucene query string syntax
:arg replication: Specific replication type, default 'sync', valid
choices are: 'sync', 'async'
:arg routing: Specific routing value
:arg timeout: Explicit operation timeout
"""
if index in SKIP_IN_PATH:
raise ValueError("Empty value passed for a required argument 'index'.")
_, data = self.transport.perform_request('DELETE', _make_path(index, doc_type, '_query'),
params=params, body=body)
return data | elasticsearch_delete_by_query/plugin.py | from elasticsearch.client.utils import AddonClient, query_params, _make_path, SKIP_IN_PATH
# COPYPASTA ingredient list:
# https://github.com/elastic/elasticsearch-py/blob/1.x/elasticsearch/client/__init__.py#L809
# https://github.com/elastic/elasticsearch-watcher-py/blob/master/elasticsearch_watcher/watcher.py
class DeleteByQuery(AddonClient):
namespace = 'delete_by_query'
@query_params('allow_no_indices', 'analyzer', 'consistency',
'default_operator', 'df', 'expand_wildcards', 'ignore_unavailable', 'q',
'replication', 'routing', 'timeout')
def delete_by_query(self, index, doc_type=None, body=None, params=None):
"""
Delete documents from one or more indices and one or more types based on a query.
`<http://www.elastic.co/guide/en/elasticsearch/reference/current/docs-delete-by-query.html>`_
:arg index: A comma-separated list of indices to restrict the operation;
use `_all` to perform the operation on all indices
:arg doc_type: A comma-separated list of types to restrict the operation
:arg body: A query to restrict the operation specified with the Query
DSL
:arg allow_no_indices: Whether to ignore if a wildcard indices
expression resolves into no concrete indices. (This includes `_all`
string or when no indices have been specified)
:arg analyzer: The analyzer to use for the query string
:arg consistency: Specific write consistency setting for the operation
:arg default_operator: The default operator for query string query (AND
or OR), default u'OR'
:arg df: The field to use as default where no field prefix is given in
the query string
:arg expand_wildcards: Whether to expand wildcard expression to concrete
indices that are open, closed or both., default u'open'
:arg ignore_unavailable: Whether specified concrete indices should be
ignored when unavailable (missing or closed)
:arg q: Query in the Lucene query string syntax
:arg replication: Specific replication type, default 'sync', valid
choices are: 'sync', 'async'
:arg routing: Specific routing value
:arg timeout: Explicit operation timeout
"""
if index in SKIP_IN_PATH:
raise ValueError("Empty value passed for a required argument 'index'.")
_, data = self.transport.perform_request('DELETE', _make_path(index, doc_type, '_query'),
params=params, body=body)
return data | 0.920607 | 0.221014 |
from rest_framework import serializers
from .models import Article, Tag
from authors.apps.articles.relations import TagsRelation
class ArticleSerializers(serializers.ModelSerializer):
def format_date(self, date):
return date.strftime('%d %b %Y %H:%M:%S')
def to_representation(self, instance):
representation = super(ArticleSerializers,
self).to_representation(instance)
representation['created_at'] = self.format_date(instance.created_at)
representation['updated_at'] = self.format_date(instance.updated_at)
return representation
title = serializers.CharField(
required=True,
max_length=140,
error_messages={
'required': 'Title is required',
'max_length': 'Title cannot be more than 140'
}
)
description = serializers.CharField(
required=False,
max_length=250,
error_messages={
'max_length': 'Description cannot be more than 250'
}
)
body = serializers.CharField(
required=True,
error_messages={
'required': 'Body cannot be empty'
}
)
author = serializers.SerializerMethodField(read_only=True)
slug = serializers.CharField(read_only=True)
averageRating = serializers.SerializerMethodField()
ratingsCount = serializers.SerializerMethodField()
liked_by = serializers.PrimaryKeyRelatedField(
many=True, read_only=True)
disliked_by = serializers.PrimaryKeyRelatedField(
many=True, read_only=True)
likes_count = serializers.SerializerMethodField()
dislikes_count = serializers.SerializerMethodField()
tags = TagsRelation(many=True, required=False)
@staticmethod
def get_averageRating(article):
"""
Calculates weighted average rating.
:param article: The article whose ratings we are calculating
:return: None if no one has rated, The weighted average to 2 decimal
places
:rtype: float or None
"""
all_ratings = article.ratings.all().count()
fives = article.ratings.filter(stars=5).count()
fours = article.ratings.filter(stars=4).count()
threes = article.ratings.filter(stars=3).count()
twos = article.ratings.filter(stars=2).count()
ones = article.ratings.filter(stars=1).count()
if all_ratings < 1:
return None
else:
weighted_total = (5 * fives) + (4 * fours) + (3 * threes) + (
2 * twos) + (1 * ones)
weighted_average = weighted_total / all_ratings
return round(weighted_average, 2)
@staticmethod
def get_ratingsCount(article):
"""
Method for getting the number of people who have rated.
:param article: The article to be rated
:return:
:rtype: int
"""
return article.ratings.all().count()
def get_author(self, obj):
return obj.author.username
class Meta:
model = Article
fields = (
'title',
'description',
'body',
'slug',
'image',
'image_url',
'author',
'tags',
'created_at',
'updated_at',
'averageRating',
'ratingsCount',
'liked_by',
'disliked_by',
'likes_count',
'dislikes_count'
)
extra_kwargs = {"image": {"write_only": True}}
def get_likes_count(self, obj):
""""Total Likes"""
return obj.liked_by.count()
def get_dislikes_count(self, obj):
"""Total Dislikes"""
return obj.disliked_by.count()
class TagsSerializer(serializers.ModelSerializer):
class Meta:
model = Tag
fields = ('tag')
def to_representation(self, instance):
return instance.tag | authors/apps/articles/serializers.py | from rest_framework import serializers
from .models import Article, Tag
from authors.apps.articles.relations import TagsRelation
class ArticleSerializers(serializers.ModelSerializer):
def format_date(self, date):
return date.strftime('%d %b %Y %H:%M:%S')
def to_representation(self, instance):
representation = super(ArticleSerializers,
self).to_representation(instance)
representation['created_at'] = self.format_date(instance.created_at)
representation['updated_at'] = self.format_date(instance.updated_at)
return representation
title = serializers.CharField(
required=True,
max_length=140,
error_messages={
'required': 'Title is required',
'max_length': 'Title cannot be more than 140'
}
)
description = serializers.CharField(
required=False,
max_length=250,
error_messages={
'max_length': 'Description cannot be more than 250'
}
)
body = serializers.CharField(
required=True,
error_messages={
'required': 'Body cannot be empty'
}
)
author = serializers.SerializerMethodField(read_only=True)
slug = serializers.CharField(read_only=True)
averageRating = serializers.SerializerMethodField()
ratingsCount = serializers.SerializerMethodField()
liked_by = serializers.PrimaryKeyRelatedField(
many=True, read_only=True)
disliked_by = serializers.PrimaryKeyRelatedField(
many=True, read_only=True)
likes_count = serializers.SerializerMethodField()
dislikes_count = serializers.SerializerMethodField()
tags = TagsRelation(many=True, required=False)
@staticmethod
def get_averageRating(article):
"""
Calculates weighted average rating.
:param article: The article whose ratings we are calculating
:return: None if no one has rated, The weighted average to 2 decimal
places
:rtype: float or None
"""
all_ratings = article.ratings.all().count()
fives = article.ratings.filter(stars=5).count()
fours = article.ratings.filter(stars=4).count()
threes = article.ratings.filter(stars=3).count()
twos = article.ratings.filter(stars=2).count()
ones = article.ratings.filter(stars=1).count()
if all_ratings < 1:
return None
else:
weighted_total = (5 * fives) + (4 * fours) + (3 * threes) + (
2 * twos) + (1 * ones)
weighted_average = weighted_total / all_ratings
return round(weighted_average, 2)
@staticmethod
def get_ratingsCount(article):
"""
Method for getting the number of people who have rated.
:param article: The article to be rated
:return:
:rtype: int
"""
return article.ratings.all().count()
def get_author(self, obj):
return obj.author.username
class Meta:
model = Article
fields = (
'title',
'description',
'body',
'slug',
'image',
'image_url',
'author',
'tags',
'created_at',
'updated_at',
'averageRating',
'ratingsCount',
'liked_by',
'disliked_by',
'likes_count',
'dislikes_count'
)
extra_kwargs = {"image": {"write_only": True}}
def get_likes_count(self, obj):
""""Total Likes"""
return obj.liked_by.count()
def get_dislikes_count(self, obj):
"""Total Dislikes"""
return obj.disliked_by.count()
class TagsSerializer(serializers.ModelSerializer):
class Meta:
model = Tag
fields = ('tag')
def to_representation(self, instance):
return instance.tag | 0.849129 | 0.197232 |
"""Provide tools for managing blade geometries."""
from io import BytesIO
from typing import Iterable, Sequence, Union
import numpy as np
import stl
from numpy.typing import NDArray
from .io import generic_vertex_ordering
from .profile import Airfoil
class Blade:
"""Define a simple, generic blade object."""
slots = ("sections",)
def __init__(self, sections: Sequence[Airfoil]) -> None:
self.sections = sections
def scale(self, factor: float) -> None:
"""Scale the blade by a given factor.
Parameters
----------
factor
The scaling factor.
"""
for section in self.sections:
section.scale(factor)
def translate(
self, vector: Union[Sequence[float], NDArray[np.float64]]
) -> None:
"""Translate the blade by a given vector.
Parameters
----------
vector
The three-dimensional translation vector.
"""
for section in self.sections:
section.translate(vector)
def rotate(
self,
angles: Sequence[float],
degrees: bool = True,
rotate_about: Union[Sequence[float], NDArray[np.float64]] = None,
) -> None:
"""Rotate the blade about a reference point.
Create a three-dimensional rotation matrix based on the intrinsic
Tait-Bryan angles (aka. yaw, pitch, and roll).
Parameters
----------
angles
The angle values as [yaw, pitch, roll].
degrees : optional
Assume angle values in degrees rather than in radians.
rotate_about : optional
The point about which to rotate.
"""
for section in self.sections:
section.rotate(
angles=angles, degrees=degrees, rotate_about=rotate_about
)
# WARNING: currently only works for sections of same shape.
def export_stl(
self,
name: str,
file_handler: BytesIO,
invert: bool = False,
) -> BytesIO:
"""Export the surface to stl.
Parameters
----------
name
the solid name to be used as prefix.
file_handler : optional
the IO handler. If not specified, a new one is created and
returned.
invert : optional
invert the vertices order. default = False (points outwards).
"""
# Check whether all sections have the same shape.
if np.any(np.diff([x.coords.shape for x in self.sections], axis=0)):
raise ValueError(
"all the coordinates must have the same dimensions"
)
# List all points as vertices.
vertices = np.reshape(
[section.coords for section in self.sections], (-1, 3)
)
# Create a list of solids
solids = {}
# It seems odd to attribute -1 to the number of points. However, this
# way we manage to export an empty file even when the blade has no
# sections. This seems a much more elegant solution than stack a bunch
# of if-else statements.
N = self.sections[0].coords.shape[0] if self.sections else -1
# Lateral surface
# --------------------------------------------------------------------
# Create a generic representation for two consecutive sections. Then,
# we just need to offset this representation to cover the whole blade.
lateral_consecutive_secs = np.reshape(
[
generic_vertex_ordering(i, N, invert=invert)
for i in range(N - 1)
],
(-1, 3),
)
solids["lateral"] = np.reshape(
[
lateral_consecutive_secs + N * i
for i in range(0, len(self.sections) - 1)
],
(-1, 3),
)
# Trailing edge surface
# --------------------------------------------------------------------
te_consecutive_secs = np.reshape(
generic_vertex_ordering(
0, N, inc_i=N - 1, inc_j=N - 1, invert=invert
),
(-1, 3),
)
solids["trailing_edge"] = np.reshape(
[
te_consecutive_secs + N * i
for i in range(0, len(self.sections) - 1)
],
(-1, 3),
)
# Top and bottom surfaces
# --------------------------------------------------------------------
def top_bottom_secs(invert: bool):
return np.reshape(
[
generic_vertex_ordering(
i,
N,
j=lambda i, N: N - i - 1,
inc_j=-1,
invert=invert,
)
for i in range(N // 2)
],
(-1, 3),
)
solids["top"] = top_bottom_secs(False) + N * (len(self.sections) - 1)
solids["bottom"] = top_bottom_secs(True)
for sname, faces in solids.items():
solid = stl.mesh.Mesh(
np.zeros(faces.shape[0], dtype=stl.mesh.Mesh.dtype)
)
for i, face in enumerate(faces):
for j in range(3):
solid.vectors[i][j] = vertices[face[j], :]
solid.save(f"{name}_{sname}", fh=file_handler, mode=stl.Mode.ASCII)
return file_handler
def __getitem__(self, index: int) -> Airfoil:
return self.sections[index]
def __next__(self) -> Iterable:
return self.sections | klingo/blade.py | """Provide tools for managing blade geometries."""
from io import BytesIO
from typing import Iterable, Sequence, Union
import numpy as np
import stl
from numpy.typing import NDArray
from .io import generic_vertex_ordering
from .profile import Airfoil
class Blade:
"""Define a simple, generic blade object."""
slots = ("sections",)
def __init__(self, sections: Sequence[Airfoil]) -> None:
self.sections = sections
def scale(self, factor: float) -> None:
"""Scale the blade by a given factor.
Parameters
----------
factor
The scaling factor.
"""
for section in self.sections:
section.scale(factor)
def translate(
self, vector: Union[Sequence[float], NDArray[np.float64]]
) -> None:
"""Translate the blade by a given vector.
Parameters
----------
vector
The three-dimensional translation vector.
"""
for section in self.sections:
section.translate(vector)
def rotate(
self,
angles: Sequence[float],
degrees: bool = True,
rotate_about: Union[Sequence[float], NDArray[np.float64]] = None,
) -> None:
"""Rotate the blade about a reference point.
Create a three-dimensional rotation matrix based on the intrinsic
Tait-Bryan angles (aka. yaw, pitch, and roll).
Parameters
----------
angles
The angle values as [yaw, pitch, roll].
degrees : optional
Assume angle values in degrees rather than in radians.
rotate_about : optional
The point about which to rotate.
"""
for section in self.sections:
section.rotate(
angles=angles, degrees=degrees, rotate_about=rotate_about
)
# WARNING: currently only works for sections of same shape.
def export_stl(
self,
name: str,
file_handler: BytesIO,
invert: bool = False,
) -> BytesIO:
"""Export the surface to stl.
Parameters
----------
name
the solid name to be used as prefix.
file_handler : optional
the IO handler. If not specified, a new one is created and
returned.
invert : optional
invert the vertices order. default = False (points outwards).
"""
# Check whether all sections have the same shape.
if np.any(np.diff([x.coords.shape for x in self.sections], axis=0)):
raise ValueError(
"all the coordinates must have the same dimensions"
)
# List all points as vertices.
vertices = np.reshape(
[section.coords for section in self.sections], (-1, 3)
)
# Create a list of solids
solids = {}
# It seems odd to attribute -1 to the number of points. However, this
# way we manage to export an empty file even when the blade has no
# sections. This seems a much more elegant solution than stack a bunch
# of if-else statements.
N = self.sections[0].coords.shape[0] if self.sections else -1
# Lateral surface
# --------------------------------------------------------------------
# Create a generic representation for two consecutive sections. Then,
# we just need to offset this representation to cover the whole blade.
lateral_consecutive_secs = np.reshape(
[
generic_vertex_ordering(i, N, invert=invert)
for i in range(N - 1)
],
(-1, 3),
)
solids["lateral"] = np.reshape(
[
lateral_consecutive_secs + N * i
for i in range(0, len(self.sections) - 1)
],
(-1, 3),
)
# Trailing edge surface
# --------------------------------------------------------------------
te_consecutive_secs = np.reshape(
generic_vertex_ordering(
0, N, inc_i=N - 1, inc_j=N - 1, invert=invert
),
(-1, 3),
)
solids["trailing_edge"] = np.reshape(
[
te_consecutive_secs + N * i
for i in range(0, len(self.sections) - 1)
],
(-1, 3),
)
# Top and bottom surfaces
# --------------------------------------------------------------------
def top_bottom_secs(invert: bool):
return np.reshape(
[
generic_vertex_ordering(
i,
N,
j=lambda i, N: N - i - 1,
inc_j=-1,
invert=invert,
)
for i in range(N // 2)
],
(-1, 3),
)
solids["top"] = top_bottom_secs(False) + N * (len(self.sections) - 1)
solids["bottom"] = top_bottom_secs(True)
for sname, faces in solids.items():
solid = stl.mesh.Mesh(
np.zeros(faces.shape[0], dtype=stl.mesh.Mesh.dtype)
)
for i, face in enumerate(faces):
for j in range(3):
solid.vectors[i][j] = vertices[face[j], :]
solid.save(f"{name}_{sname}", fh=file_handler, mode=stl.Mode.ASCII)
return file_handler
def __getitem__(self, index: int) -> Airfoil:
return self.sections[index]
def __next__(self) -> Iterable:
return self.sections | 0.960676 | 0.643917 |
from mock import MagicMock, patch
from nose.plugins.attrib import attr
from ion.agents.data.handlers.handler_utils import _get_type, list_file_info, \
list_file_info_http, list_file_info_ftp, list_file_info_fs, \
get_time_from_filename, calculate_iteration_count, get_sbuffer
from pyon.util.unit_test import PyonTestCase
import requests
from ftplib import FTP
from StringIO import StringIO
@attr('UNIT', group='eoi')
class TestHandlerUtils(PyonTestCase):
def test__get_type_http(self):
self.assertEqual(_get_type('http://'), 'http')
def test__get_type_ftp(self):
self.assertEqual(_get_type('ftp://'), 'ftp')
def test__get_type_fs(self):
self.assertEqual(_get_type(''), 'fs')
@patch('ion.agents.data.handlers.handler_utils._get_type')
@patch('ion.agents.data.handlers.handler_utils.list_file_info_http')
def test_list_file_info_by_http(self, list_file_info_http_mock, _get_type_mock):
_get_type_mock.return_value = 'http'
list_file_info_http_mock.return_value = ['file1', 'file2']
self.assertEqual(list_file_info('http', 'pattern'), ['file1', 'file2'])
@patch('ion.agents.data.handlers.handler_utils._get_type')
@patch('ion.agents.data.handlers.handler_utils.list_file_info_ftp')
def test_list_file_info_by_ftp(self, list_file_info_ftp_mock, _get_type_mock):
_get_type_mock.return_value = 'ftp'
list_file_info_ftp_mock.return_value = ['file1', 'file2']
self.assertEqual(list_file_info('ftp', 'pattern'), ['file1', 'file2'])
@patch('ion.agents.data.handlers.handler_utils._get_type')
@patch('ion.agents.data.handlers.handler_utils.list_file_info_fs')
def test_list_file_info_by_fs(self, list_file_info_fs_mock, _get_type_mock):
_get_type_mock.return_value = 'fs'
list_file_info_fs_mock.return_value = ['file1', 'file2']
self.assertEqual(list_file_info('fs', 'pattern'), ['file1', 'file2'])
@patch('ion.agents.data.handlers.handler_utils.re.findall')
@patch('ion.agents.data.handlers.handler_utils.requests.get')
def test_list_file_info_http(self, requests_mock, re_mock):
retval = MagicMock(spec=requests.models.Response)
retval.url = 'http://marine.rutgers.edu/cool/maracoos/codar/ooi/radials/BELM/'
retval.content = '<http><body>' \
'<a href="RDLm_BELM_2012_08_14_1200.ruv">RDLm_BELM_2012_08_14_1200.ruv</a> ' \
'14-Aug-2012 08:42 88K \n<img src="/icons/unknown.gif" alt="[ ]"> ' \
'<a href="RDLm_BELM_2012_08_14_1300.ruv">RDLm_BELM_2012_08_14_1300.ruv</a> ' \
'14-Aug-2012 09:41 90K \n</body></html>'
requests_mock.return_value = retval
re_mock.return_value = ['RDLm_BELM_2012_08_14_1200.ruv', 'RDLm_BELM_2012_08_14_1300.ruv']
lst = [('http://marine.rutgers.edu/cool/maracoos/codar/ooi/radials/BELM/RDLm_BELM_2012_08_14_1200.ruv',),
('http://marine.rutgers.edu/cool/maracoos/codar/ooi/radials/BELM/RDLm_BELM_2012_08_14_1300.ruv',)]
self.assertEqual(list_file_info_http(base='http://marine.rutgers.edu/cool/maracoos/codar/ooi/radials/BELM/', pattern='*.ruv'), lst)
@patch('ion.agents.data.handlers.handler_utils.FTP')
def test_list_file_info_ftp(self, ftp_mock):
retval = MagicMock(spec=FTP)
retval.nlst.return_value = ['RDLm_BELM_2012_08_14_1200.ruv', 'RDLm_BELM_2012_08_14_1300.ruv']
ftp_mock.return_value = retval
lst = ['RDLm_BELM_2012_08_14_1200.ruv',
'RDLm_BELM_2012_08_14_1300.ruv']
self.assertEqual(list_file_info_ftp(base='ftp://marine.rutgers.edu/cool/maracoos/codar/ooi/radials/BELM/', pattern='*.ruv'), lst)
@patch('ion.agents.data.handlers.handler_utils.glob.glob')
@patch('ion.agents.data.handlers.handler_utils.os.path.getmtime')
@patch('ion.agents.data.handlers.handler_utils.os.path.getsize')
@patch('ion.agents.data.handlers.handler_utils.os.path.isdir')
@patch('ion.agents.data.handlers.handler_utils.os.path.exists')
def test_list_file_info_fs(self, exists_mock, isdir_mock, getsize_mock, getmtime_mock, glob_mock):
exists_mock.return_value = True
isdir_mock.return_value = True
getsize_mock.return_value = 100
getmtime_mock.return_value = 1313712000
lst1 = ['RDLm_BELM_2012_08_14_1200.ruv',
'RDLm_BELM_2012_08_14_1300.ruv']
glob_mock.return_value = lst1
lst2 = [('RDLm_BELM_2012_08_14_1200.ruv', 1313712000, 100, 0),
('RDLm_BELM_2012_08_14_1300.ruv', 1313712000, 100, 0)]
self.assertEqual(list_file_info_fs(base='test_data/ruv', pattern='*.ruv'), lst2)
@patch('ion.agents.data.handlers.handler_utils.os.path.exists')
def test_list_file_info_fs_exists_false(self, exists_mock):
exists_mock.return_value = False
with self.assertRaises(StandardError) as cm:
list_file_info_fs(base='test_data/ruv', pattern='*.ruv')
ex = cm.exception
self.assertEqual(ex.message, 'base \'test_data/ruv\' does not exist')
@patch('ion.agents.data.handlers.handler_utils.os.path.isdir')
@patch('ion.agents.data.handlers.handler_utils.os.path.exists')
def test_list_file_info_fs_isdir_false(self, exists_mock, isdir_mock):
exists_mock.return_value = True
isdir_mock.return_value = False
with self.assertRaises(StandardError) as cm:
list_file_info_fs(base='test_data/ruv', pattern='*.ruv')
ex = cm.exception
self.assertEqual(ex.message, 'base \'test_data/ruv\' is not a directory')
@patch('ion.agents.data.handlers.handler_utils.time.mktime')
@patch('ion.agents.data.handlers.handler_utils.re.match')
@patch('ion.agents.data.handlers.handler_utils.os.path.basename')
def test_get_time_from_filename(self, basename_mock, re_mock, mktime_mock):
basename_mock.return_value = 'test_data/ruv'
retval = MagicMock()
retval.groups.return_value = ('2012', '06', '06', '12', '00')
re_mock.return_value = retval
mktime_mock.return_value = 1338998400.0
self.assertEqual(get_time_from_filename(file_name='test_data/ruv/RDLm_SEAB_2012_06_06_1200.ruv',
date_extraction_pattern='RDLm_SEAB_([\d]{4})_([\d]{2})_([\d]{2})_([\d]{2})([\d]{2}).ruv',
date_pattern='%Y %m %d %H %M'), 1338998400.0)
def test_calculate_iteration_count(self):
total_recs = 100
max_rec = 10
self.assertEqual(calculate_iteration_count(total_recs=total_recs, max_rec=max_rec), 10)
def test_calculate_iteration_count_not_even(self):
total_recs = 101
max_rec = 10
self.assertEqual(calculate_iteration_count(total_recs=total_recs, max_rec=max_rec), 11)
@patch('ion.agents.data.handlers.handler_utils.StringIO')
@patch('ion.agents.data.handlers.handler_utils._get_type')
@patch('ion.agents.data.handlers.handler_utils.requests.get')
def test_get_sbuffer_http(self, requests_mock, get_type_mock, StringIO_mock):
retval = MagicMock(spec=requests.models.Response)
retval.url = 'http://marine.rutgers.edu/cool/maracoos/codar/ooi/radials/BELM/'
retval.content = '<http><body>'\
'<a href="RDLm_BELM_2012_08_14_1200.ruv">RDLm_BELM_2012_08_14_1200.ruv</a> '\
'14-Aug-2012 08:42 88K \n<img src="/icons/unknown.gif" alt="[ ]"> '\
'<a href="RDLm_BELM_2012_08_14_1300.ruv">RDLm_BELM_2012_08_14_1300.ruv</a> '\
'14-Aug-2012 09:41 90K \n</body></html>'
requests_mock.return_value = retval
get_type_mock.return_value = 'http'
StringIO_mock.return_value = MagicMock(spec=StringIO)
self.assertTrue(isinstance(get_sbuffer(url=retval.url), StringIO))
def test_get_sbuffer_ftp(self):
with self.assertRaises(NotImplementedError):
get_sbuffer(url='http://marine.rutgers.edu/cool/maracoos/codar/ooi/radials/BELM/', type='ftp') | ion/agents/data/handlers/test/test_handler_utils.py | from mock import MagicMock, patch
from nose.plugins.attrib import attr
from ion.agents.data.handlers.handler_utils import _get_type, list_file_info, \
list_file_info_http, list_file_info_ftp, list_file_info_fs, \
get_time_from_filename, calculate_iteration_count, get_sbuffer
from pyon.util.unit_test import PyonTestCase
import requests
from ftplib import FTP
from StringIO import StringIO
@attr('UNIT', group='eoi')
class TestHandlerUtils(PyonTestCase):
def test__get_type_http(self):
self.assertEqual(_get_type('http://'), 'http')
def test__get_type_ftp(self):
self.assertEqual(_get_type('ftp://'), 'ftp')
def test__get_type_fs(self):
self.assertEqual(_get_type(''), 'fs')
@patch('ion.agents.data.handlers.handler_utils._get_type')
@patch('ion.agents.data.handlers.handler_utils.list_file_info_http')
def test_list_file_info_by_http(self, list_file_info_http_mock, _get_type_mock):
_get_type_mock.return_value = 'http'
list_file_info_http_mock.return_value = ['file1', 'file2']
self.assertEqual(list_file_info('http', 'pattern'), ['file1', 'file2'])
@patch('ion.agents.data.handlers.handler_utils._get_type')
@patch('ion.agents.data.handlers.handler_utils.list_file_info_ftp')
def test_list_file_info_by_ftp(self, list_file_info_ftp_mock, _get_type_mock):
_get_type_mock.return_value = 'ftp'
list_file_info_ftp_mock.return_value = ['file1', 'file2']
self.assertEqual(list_file_info('ftp', 'pattern'), ['file1', 'file2'])
@patch('ion.agents.data.handlers.handler_utils._get_type')
@patch('ion.agents.data.handlers.handler_utils.list_file_info_fs')
def test_list_file_info_by_fs(self, list_file_info_fs_mock, _get_type_mock):
_get_type_mock.return_value = 'fs'
list_file_info_fs_mock.return_value = ['file1', 'file2']
self.assertEqual(list_file_info('fs', 'pattern'), ['file1', 'file2'])
@patch('ion.agents.data.handlers.handler_utils.re.findall')
@patch('ion.agents.data.handlers.handler_utils.requests.get')
def test_list_file_info_http(self, requests_mock, re_mock):
retval = MagicMock(spec=requests.models.Response)
retval.url = 'http://marine.rutgers.edu/cool/maracoos/codar/ooi/radials/BELM/'
retval.content = '<http><body>' \
'<a href="RDLm_BELM_2012_08_14_1200.ruv">RDLm_BELM_2012_08_14_1200.ruv</a> ' \
'14-Aug-2012 08:42 88K \n<img src="/icons/unknown.gif" alt="[ ]"> ' \
'<a href="RDLm_BELM_2012_08_14_1300.ruv">RDLm_BELM_2012_08_14_1300.ruv</a> ' \
'14-Aug-2012 09:41 90K \n</body></html>'
requests_mock.return_value = retval
re_mock.return_value = ['RDLm_BELM_2012_08_14_1200.ruv', 'RDLm_BELM_2012_08_14_1300.ruv']
lst = [('http://marine.rutgers.edu/cool/maracoos/codar/ooi/radials/BELM/RDLm_BELM_2012_08_14_1200.ruv',),
('http://marine.rutgers.edu/cool/maracoos/codar/ooi/radials/BELM/RDLm_BELM_2012_08_14_1300.ruv',)]
self.assertEqual(list_file_info_http(base='http://marine.rutgers.edu/cool/maracoos/codar/ooi/radials/BELM/', pattern='*.ruv'), lst)
@patch('ion.agents.data.handlers.handler_utils.FTP')
def test_list_file_info_ftp(self, ftp_mock):
retval = MagicMock(spec=FTP)
retval.nlst.return_value = ['RDLm_BELM_2012_08_14_1200.ruv', 'RDLm_BELM_2012_08_14_1300.ruv']
ftp_mock.return_value = retval
lst = ['RDLm_BELM_2012_08_14_1200.ruv',
'RDLm_BELM_2012_08_14_1300.ruv']
self.assertEqual(list_file_info_ftp(base='ftp://marine.rutgers.edu/cool/maracoos/codar/ooi/radials/BELM/', pattern='*.ruv'), lst)
@patch('ion.agents.data.handlers.handler_utils.glob.glob')
@patch('ion.agents.data.handlers.handler_utils.os.path.getmtime')
@patch('ion.agents.data.handlers.handler_utils.os.path.getsize')
@patch('ion.agents.data.handlers.handler_utils.os.path.isdir')
@patch('ion.agents.data.handlers.handler_utils.os.path.exists')
def test_list_file_info_fs(self, exists_mock, isdir_mock, getsize_mock, getmtime_mock, glob_mock):
exists_mock.return_value = True
isdir_mock.return_value = True
getsize_mock.return_value = 100
getmtime_mock.return_value = 1313712000
lst1 = ['RDLm_BELM_2012_08_14_1200.ruv',
'RDLm_BELM_2012_08_14_1300.ruv']
glob_mock.return_value = lst1
lst2 = [('RDLm_BELM_2012_08_14_1200.ruv', 1313712000, 100, 0),
('RDLm_BELM_2012_08_14_1300.ruv', 1313712000, 100, 0)]
self.assertEqual(list_file_info_fs(base='test_data/ruv', pattern='*.ruv'), lst2)
@patch('ion.agents.data.handlers.handler_utils.os.path.exists')
def test_list_file_info_fs_exists_false(self, exists_mock):
exists_mock.return_value = False
with self.assertRaises(StandardError) as cm:
list_file_info_fs(base='test_data/ruv', pattern='*.ruv')
ex = cm.exception
self.assertEqual(ex.message, 'base \'test_data/ruv\' does not exist')
@patch('ion.agents.data.handlers.handler_utils.os.path.isdir')
@patch('ion.agents.data.handlers.handler_utils.os.path.exists')
def test_list_file_info_fs_isdir_false(self, exists_mock, isdir_mock):
exists_mock.return_value = True
isdir_mock.return_value = False
with self.assertRaises(StandardError) as cm:
list_file_info_fs(base='test_data/ruv', pattern='*.ruv')
ex = cm.exception
self.assertEqual(ex.message, 'base \'test_data/ruv\' is not a directory')
@patch('ion.agents.data.handlers.handler_utils.time.mktime')
@patch('ion.agents.data.handlers.handler_utils.re.match')
@patch('ion.agents.data.handlers.handler_utils.os.path.basename')
def test_get_time_from_filename(self, basename_mock, re_mock, mktime_mock):
basename_mock.return_value = 'test_data/ruv'
retval = MagicMock()
retval.groups.return_value = ('2012', '06', '06', '12', '00')
re_mock.return_value = retval
mktime_mock.return_value = 1338998400.0
self.assertEqual(get_time_from_filename(file_name='test_data/ruv/RDLm_SEAB_2012_06_06_1200.ruv',
date_extraction_pattern='RDLm_SEAB_([\d]{4})_([\d]{2})_([\d]{2})_([\d]{2})([\d]{2}).ruv',
date_pattern='%Y %m %d %H %M'), 1338998400.0)
def test_calculate_iteration_count(self):
total_recs = 100
max_rec = 10
self.assertEqual(calculate_iteration_count(total_recs=total_recs, max_rec=max_rec), 10)
def test_calculate_iteration_count_not_even(self):
total_recs = 101
max_rec = 10
self.assertEqual(calculate_iteration_count(total_recs=total_recs, max_rec=max_rec), 11)
@patch('ion.agents.data.handlers.handler_utils.StringIO')
@patch('ion.agents.data.handlers.handler_utils._get_type')
@patch('ion.agents.data.handlers.handler_utils.requests.get')
def test_get_sbuffer_http(self, requests_mock, get_type_mock, StringIO_mock):
retval = MagicMock(spec=requests.models.Response)
retval.url = 'http://marine.rutgers.edu/cool/maracoos/codar/ooi/radials/BELM/'
retval.content = '<http><body>'\
'<a href="RDLm_BELM_2012_08_14_1200.ruv">RDLm_BELM_2012_08_14_1200.ruv</a> '\
'14-Aug-2012 08:42 88K \n<img src="/icons/unknown.gif" alt="[ ]"> '\
'<a href="RDLm_BELM_2012_08_14_1300.ruv">RDLm_BELM_2012_08_14_1300.ruv</a> '\
'14-Aug-2012 09:41 90K \n</body></html>'
requests_mock.return_value = retval
get_type_mock.return_value = 'http'
StringIO_mock.return_value = MagicMock(spec=StringIO)
self.assertTrue(isinstance(get_sbuffer(url=retval.url), StringIO))
def test_get_sbuffer_ftp(self):
with self.assertRaises(NotImplementedError):
get_sbuffer(url='http://marine.rutgers.edu/cool/maracoos/codar/ooi/radials/BELM/', type='ftp') | 0.516839 | 0.113359 |
from optparse import OptionParser
import pysam
import statistics
class Molecule:
def __init__(self, rname, start, end, \
newMolecID, barcode, \
interArrivals, count, \
mapqMedian, asMedian, nmMedian):
self.rname = rname
self.start = start
self.end = end
self.barcode = barcode
self.newMolecID = newMolecID
self.interArrivals = interArrivals
self.count = count
self.mapqMedian = mapqMedian
self.asMedian = asMedian
self.nmMedian = nmMedian
def asTSV(self):
return self.rname + "\t" + str(self.start+1) + "\t" + str(self.end+1) \
+ "\t" + str(self.end - self.start) + "\t" + self.barcode \
+ "\t" + str(self.newMolecID) + "\t" + str(self.count) \
+ "\t" + str(self.mapqMedian) + "\t" + str(self.asMedian) \
+ "\t" + str(self.nmMedian)
def getLength(self):
return self.end-self.start
class MolecIdentifier:
def setBAM(self,bam):
self._bam = bam
def setDist(self, dist):
self._maxDist = int(dist)
def setMin(self, min):
self._min = int(min)
def setMAPQ(self, mapq):
self._mapq = int(mapq)
def setASRatio(self, asRatio):
self._asRatio = float(asRatio)
def setNM(self, nm):
self._nm = int(nm)
def setNewBam(self, filename):
self._newBamFilename = filename
def setOutput(self, filename):
self._tsvFilename = filename
def printTSV(self, molec):
if self._tsvFilename:
self._newMolecFH.write(molec.asTSV() + "\n")
else:
print(molec.asTSV())
def __init__(self):
"""
Constructor, identifies molecules based on inter-arrival time threshold
"""
self._min = 4
self._maxDist = 60000
self._mapq = 1
self._asRatio = 0.8
self._nm = 5
self._newBamFilename = ""
self._tsvFilename = ""
self._bam = ""
def run(self):
if self._bam:
samfile = pysam.AlignmentFile(self._bam, "rb")
else:
samfile = pysam.AlignmentFile("-", "rb")
if self._newBamFilename:
self._outfilebam = pysam.AlignmentFile(self._newBamFilename, "wb", template=samfile)
else:
self._outfilebam = None
header = "Rname\tStart\tEnd\tSize\tBX\tMI\tReads\tMapq_median\tAS_median\tNM_median"
if self._tsvFilename:
self._newMolecFH = open(self._tsvFilename, "w");
self._newMolecFH.write(header + "\n")
else:
self._newMolecFH = None
print(header)
prevBarcode = ""
prevChr = ""
curReads = []
trueMolecs = {}
newMolecID = 0
for read in samfile:
barcode = ""
if read.is_unmapped or \
read.is_supplementary or \
read.mapping_quality < self._mapq or \
read.get_tag("AS") < self._asRatio*len(read.query_sequence) or \
read.get_tag("NM") >= self._nm:
continue
# extract barcode
barcodeList = [bc for bc in read.tags if "BX" in bc]
if len(barcodeList) != 0:
barcode = barcodeList[0][1]
else:
if self._newBamFilename:
self._outfilebam.write(read)
continue
if prevChr == "" or prevBarcode == "":
prevBarcode = barcode
prevChr = read.reference_id
if prevBarcode != barcode or read.reference_id != prevChr:
prevVal = 0
prevRead = curReads[0]
prevVal1 = 0
prevVal2 = 0
start = curReads[0].pos
rname = curReads[0].reference_name
interArrivals = []
mapQs = []
alSs = []
noMs = []
count = 0
for curRead in curReads:
value = curRead.pos
absDist = value - prevVal
mapQs.append(curRead.mapping_quality)
alSs.append(curRead.get_tag("AS"))
noMs.append(curRead.get_tag("NM"))
#check if molecules should be terminated
if absDist > self._maxDist and prevVal > 0:
end = prevRead.reference_end
#find distance from nearest read
molec = Molecule(rname, start, end, \
newMolecID, prevBarcode, \
interArrivals, count, \
statistics.median(mapQs), \
statistics.median(alSs), \
statistics.median(noMs))
if prevRead.is_reverse:
prevVal2 = value
prevVal1 = 0
else:
prevVal1 = value
prevVal2 = 0
start = value;
if count >= self._min:
self.printTSV(molec)
newMolecID += 1
if self._newBamFilename:
curRead.tags += [("MI", newMolecID)]
self._outfilebam.write(curRead)
interArrivals = []
mapQs = []
alSs = []
noMs = []
mapQs.append(curRead.mapping_quality)
alSs.append(curRead.get_tag("AS"))
noMs.append(curRead.get_tag("NM"))
prevVal = value
count = 0
continue
else:
if self._newBamFilename:
curRead.tags += [("MI", newMolecID)]
self._outfilebam.write(curRead)
#inter arrival time is distance between read of the same direction
interArrival = 0
if curRead.is_reverse:
if prevVal2 == 0:
prevVal2 = value
prevVal = value
count += 1
continue
else:
interArrival = value - prevVal2
prevVal2 = value
else:
if prevVal1 == 0:
prevVal1 = value
prevVal = value
count += 1
continue
else:
interArrival = value - prevVal1
prevVal1 = value
if interArrival > 0:
count += 1
interArrivals.append(interArrival)
prevVal = value
prevRead = curRead
end = prevRead.reference_end
molec = Molecule(rname, start, end, \
newMolecID, prevBarcode, \
interArrivals, count, \
statistics.median(mapQs), \
statistics.median(alSs), \
statistics.median(noMs))
if count >= self._min:
self.printTSV(molec)
newMolecID += 1
curReads = []
curReads.append(read)
prevBarcode = barcode
prevChr = read.reference_id
#clean up
samfile.close()
if self._newMolecFH != None:
self._newMolecFH.close()
if self._outfilebam != None:
self._outfilebam.close()
if __name__ == '__main__':
# specify parser options
parser = OptionParser()
parser.set_description("Takes a bam file via stdin and outputs molecules to a bed-like (1-based coordinates) TSV file. Read to genome bam file used must be sorted by BX tag and then by position.")
parser.add_option("-b", "--bam", dest="bam",
help="Read to genome BAM file file instead of stdin (optional)", metavar="BAM")
parser.add_option("-d", "--dist", dest="dist",
help="Minimum distance between reads to be considered the same molecule [60000]", metavar="DIST")
parser.add_option("-o", "--output", dest="output",
help="file name of tsv file instead of stdout (optional)", metavar="OUTPUT")
parser.add_option("-w", "--new_bam", dest="newBam",
help="New bam file with MI tags added (optional)", metavar="NEWBAM")
parser.add_option("-m", "--min", dest="min",
help="minimum number of reads in alignment to consider (dupes are not considered) [4]", metavar="MIN")
parser.add_option("-q", "--mapq", dest="mapq",
help="Reads MAPQ greater or equal to this will be kept [1]", metavar="MAPQ")
parser.add_option("-a", "--asRatio", dest="asRatio",
help="Reads with an AS/Read length ratio greater or equal to this will be kept [0.8]", metavar="AS")
parser.add_option("-n", "--nm", dest="nm",
help="Reads that have NM tag lower than this will be kept [5]", metavar="NM")
(options, args) = parser.parse_args()
molecID = MolecIdentifier()
if options.bam:
molecID.setBAM(options.bam)
if options.dist:
molecID.setDist(options.dist)
if options.min:
molecID.setMin(options.min)
if options.mapq:
molecID.setMAPQ(options.mapq)
if options.asRatio:
molecID.setASRatio(options.asRatio)
if options.nm:
molecID.setNM(options.nm)
if options.newBam:
molecID.setNewBam(options.newBam)
if options.output:
molecID.setOutput(options.output)
molecID.run() | MolecEst/MolecLenEst.py | from optparse import OptionParser
import pysam
import statistics
class Molecule:
def __init__(self, rname, start, end, \
newMolecID, barcode, \
interArrivals, count, \
mapqMedian, asMedian, nmMedian):
self.rname = rname
self.start = start
self.end = end
self.barcode = barcode
self.newMolecID = newMolecID
self.interArrivals = interArrivals
self.count = count
self.mapqMedian = mapqMedian
self.asMedian = asMedian
self.nmMedian = nmMedian
def asTSV(self):
return self.rname + "\t" + str(self.start+1) + "\t" + str(self.end+1) \
+ "\t" + str(self.end - self.start) + "\t" + self.barcode \
+ "\t" + str(self.newMolecID) + "\t" + str(self.count) \
+ "\t" + str(self.mapqMedian) + "\t" + str(self.asMedian) \
+ "\t" + str(self.nmMedian)
def getLength(self):
return self.end-self.start
class MolecIdentifier:
def setBAM(self,bam):
self._bam = bam
def setDist(self, dist):
self._maxDist = int(dist)
def setMin(self, min):
self._min = int(min)
def setMAPQ(self, mapq):
self._mapq = int(mapq)
def setASRatio(self, asRatio):
self._asRatio = float(asRatio)
def setNM(self, nm):
self._nm = int(nm)
def setNewBam(self, filename):
self._newBamFilename = filename
def setOutput(self, filename):
self._tsvFilename = filename
def printTSV(self, molec):
if self._tsvFilename:
self._newMolecFH.write(molec.asTSV() + "\n")
else:
print(molec.asTSV())
def __init__(self):
"""
Constructor, identifies molecules based on inter-arrival time threshold
"""
self._min = 4
self._maxDist = 60000
self._mapq = 1
self._asRatio = 0.8
self._nm = 5
self._newBamFilename = ""
self._tsvFilename = ""
self._bam = ""
def run(self):
if self._bam:
samfile = pysam.AlignmentFile(self._bam, "rb")
else:
samfile = pysam.AlignmentFile("-", "rb")
if self._newBamFilename:
self._outfilebam = pysam.AlignmentFile(self._newBamFilename, "wb", template=samfile)
else:
self._outfilebam = None
header = "Rname\tStart\tEnd\tSize\tBX\tMI\tReads\tMapq_median\tAS_median\tNM_median"
if self._tsvFilename:
self._newMolecFH = open(self._tsvFilename, "w");
self._newMolecFH.write(header + "\n")
else:
self._newMolecFH = None
print(header)
prevBarcode = ""
prevChr = ""
curReads = []
trueMolecs = {}
newMolecID = 0
for read in samfile:
barcode = ""
if read.is_unmapped or \
read.is_supplementary or \
read.mapping_quality < self._mapq or \
read.get_tag("AS") < self._asRatio*len(read.query_sequence) or \
read.get_tag("NM") >= self._nm:
continue
# extract barcode
barcodeList = [bc for bc in read.tags if "BX" in bc]
if len(barcodeList) != 0:
barcode = barcodeList[0][1]
else:
if self._newBamFilename:
self._outfilebam.write(read)
continue
if prevChr == "" or prevBarcode == "":
prevBarcode = barcode
prevChr = read.reference_id
if prevBarcode != barcode or read.reference_id != prevChr:
prevVal = 0
prevRead = curReads[0]
prevVal1 = 0
prevVal2 = 0
start = curReads[0].pos
rname = curReads[0].reference_name
interArrivals = []
mapQs = []
alSs = []
noMs = []
count = 0
for curRead in curReads:
value = curRead.pos
absDist = value - prevVal
mapQs.append(curRead.mapping_quality)
alSs.append(curRead.get_tag("AS"))
noMs.append(curRead.get_tag("NM"))
#check if molecules should be terminated
if absDist > self._maxDist and prevVal > 0:
end = prevRead.reference_end
#find distance from nearest read
molec = Molecule(rname, start, end, \
newMolecID, prevBarcode, \
interArrivals, count, \
statistics.median(mapQs), \
statistics.median(alSs), \
statistics.median(noMs))
if prevRead.is_reverse:
prevVal2 = value
prevVal1 = 0
else:
prevVal1 = value
prevVal2 = 0
start = value;
if count >= self._min:
self.printTSV(molec)
newMolecID += 1
if self._newBamFilename:
curRead.tags += [("MI", newMolecID)]
self._outfilebam.write(curRead)
interArrivals = []
mapQs = []
alSs = []
noMs = []
mapQs.append(curRead.mapping_quality)
alSs.append(curRead.get_tag("AS"))
noMs.append(curRead.get_tag("NM"))
prevVal = value
count = 0
continue
else:
if self._newBamFilename:
curRead.tags += [("MI", newMolecID)]
self._outfilebam.write(curRead)
#inter arrival time is distance between read of the same direction
interArrival = 0
if curRead.is_reverse:
if prevVal2 == 0:
prevVal2 = value
prevVal = value
count += 1
continue
else:
interArrival = value - prevVal2
prevVal2 = value
else:
if prevVal1 == 0:
prevVal1 = value
prevVal = value
count += 1
continue
else:
interArrival = value - prevVal1
prevVal1 = value
if interArrival > 0:
count += 1
interArrivals.append(interArrival)
prevVal = value
prevRead = curRead
end = prevRead.reference_end
molec = Molecule(rname, start, end, \
newMolecID, prevBarcode, \
interArrivals, count, \
statistics.median(mapQs), \
statistics.median(alSs), \
statistics.median(noMs))
if count >= self._min:
self.printTSV(molec)
newMolecID += 1
curReads = []
curReads.append(read)
prevBarcode = barcode
prevChr = read.reference_id
#clean up
samfile.close()
if self._newMolecFH != None:
self._newMolecFH.close()
if self._outfilebam != None:
self._outfilebam.close()
if __name__ == '__main__':
# specify parser options
parser = OptionParser()
parser.set_description("Takes a bam file via stdin and outputs molecules to a bed-like (1-based coordinates) TSV file. Read to genome bam file used must be sorted by BX tag and then by position.")
parser.add_option("-b", "--bam", dest="bam",
help="Read to genome BAM file file instead of stdin (optional)", metavar="BAM")
parser.add_option("-d", "--dist", dest="dist",
help="Minimum distance between reads to be considered the same molecule [60000]", metavar="DIST")
parser.add_option("-o", "--output", dest="output",
help="file name of tsv file instead of stdout (optional)", metavar="OUTPUT")
parser.add_option("-w", "--new_bam", dest="newBam",
help="New bam file with MI tags added (optional)", metavar="NEWBAM")
parser.add_option("-m", "--min", dest="min",
help="minimum number of reads in alignment to consider (dupes are not considered) [4]", metavar="MIN")
parser.add_option("-q", "--mapq", dest="mapq",
help="Reads MAPQ greater or equal to this will be kept [1]", metavar="MAPQ")
parser.add_option("-a", "--asRatio", dest="asRatio",
help="Reads with an AS/Read length ratio greater or equal to this will be kept [0.8]", metavar="AS")
parser.add_option("-n", "--nm", dest="nm",
help="Reads that have NM tag lower than this will be kept [5]", metavar="NM")
(options, args) = parser.parse_args()
molecID = MolecIdentifier()
if options.bam:
molecID.setBAM(options.bam)
if options.dist:
molecID.setDist(options.dist)
if options.min:
molecID.setMin(options.min)
if options.mapq:
molecID.setMAPQ(options.mapq)
if options.asRatio:
molecID.setASRatio(options.asRatio)
if options.nm:
molecID.setNM(options.nm)
if options.newBam:
molecID.setNewBam(options.newBam)
if options.output:
molecID.setOutput(options.output)
molecID.run() | 0.358016 | 0.195844 |
import sys
from PyQt5 import uic, QtCore, QtGui
from PyQt5.QtWidgets import *
import build_db
import datetime
class CredibilityKnowledge:
def __init__(self):
self.ui = uic.loadUi("./ui/credibility.ui") # 组件名称查看credibility.ui
self.set_ui()
self.show_knowledge('', '') # 展示所有知识
self.ui.add.clicked.connect(self.add_knowledge)
self.ui.update.clicked.connect(self.update_knowledge)
self.ui.delete_2.clicked.connect(self.delete_knowledge)
self.ui.search_2.clicked.connect(self.search_knowledge)
self.ui.clear.clicked.connect(self.clear_all)
build_db.create_credibility_knowledge_table()
def set_ui(self):
ico_path = './image/light.ico'
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap(ico_path), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.ui.setWindowIcon(icon)
self.ui.setWindowTitle('可信度知识库')
self.ui.resize(1600, 600)
self.ui.table.horizontalHeader().setStretchLastSection(True)
self.ui.table.setRowCount(20)
self.ui.table.setColumnWidth(0, 180)
self.ui.table.setColumnWidth(1, 180)
self.ui.table.setColumnWidth(2, 100)
self.ui.table.setColumnWidth(3, 100)
self.ui.table.setColumnWidth(4, 100)
self.ui.table.setColumnWidth(5, 100)
def show_knowledge(self, type, content):
self.ui.table.clearContents()
res = build_db.search_credibility_knowledge(type, content)
line = 0
if res != None:
for row in range(len(res)):
for i in range(6):
if i < 4:
item1 = QTableWidgetItem(str(res[row][i + 1]))
item1.setFlags(QtCore.Qt.ItemIsEditable)
self.ui.table.setItem(row, i, item1)
elif i == 4:
item2 = QTableWidgetItem(str(res[row][6]))
item2.setFlags(QtCore.Qt.ItemIsEditable)
self.ui.table.setItem(row, i, item2)
elif i == 5:
item3 = QTableWidgetItem(str(res[row][5]))
item3.setFlags(QtCore.Qt.ItemIsEditable)
self.ui.table.setItem(row, i, item3)
def search_knowledge(self):
msg = ''
limit = 0
which = 0
condition = self.ui.condition_line.text().strip()
if condition != '':
limit += 1
which = 0
conclusion = self.ui.conclusion_line.text().strip()
if conclusion != '':
limit += 1
which = 1
condition_credibility = self.ui.condition_credibility.text().strip()
if condition_credibility != '':
limit += 1
which = 2
if (self.IsFloat(condition_credibility)):
condition_credibility = float(condition_credibility)
if condition_credibility > 1 or condition_credibility < 0:
msg += '条件可信度不在0-1之间!\n'
else:
msg += '表示条件可信度的不是一个数!\n'
knowledge_credibility = self.ui.knowledge_credibility.text().strip()
if knowledge_credibility != '':
limit += 1
which = 3
if self.IsFloat(knowledge_credibility):
knowledge_credibility = float(knowledge_credibility)
if knowledge_credibility > 1 or knowledge_credibility < 0:
msg += '结论可信度不在0-1之间!\n'
else:
msg += '表示结论可信度的不是一个数!\n'
update_person = self.ui.update_person.text().strip()
if update_person != '':
limit += 1
which = 4
if limit > 1:
QMessageBox.critical(self.ui, 'Error', '只能输入一个约束条件!')
return
if msg != '':
QMessageBox.critical(self.ui, 'Error', msg)
return
if limit == 1:
type = ['CONDITION', 'CONCLUSION', 'CONDITION_CREDIBILITY', 'KNOWLEDGE_CREDIBILITY', 'UPDATE_PERSON']
content = [condition, conclusion, condition_credibility, knowledge_credibility, update_person]
self.show_knowledge(type[which], content[which])
def update_knowledge(self):
if build_db.num_of_record() == 0:
QMessageBox.critical(self.ui, 'Error', '知识库中无知识')
return
id = self.ui.ID_line.text().strip()
if id == '':
QMessageBox.critical(self.ui, 'Error', 'ID为空')
return
if id.isnumeric():
id = int(id)
if id > build_db.num_of_record() or id < 0:
QMessageBox.critical(self.ui, 'Error', 'ID超出范围')
else:
msg = ''
condition = self.ui.condition_line.text().strip()
print(type(condition))
conclusion = self.ui.conclusion_line.text().strip()
condition_credibility = self.ui.condition_credibility.text().strip()
if condition_credibility != '':
if (self.IsFloat(condition_credibility)):
condition_credibility = float(condition_credibility)
if condition_credibility > 1 or condition_credibility < 0:
msg += '条件可信度不在0-1之间!\n'
else:
msg += '表示条件可信度的不是一个数!\n'
knowledge_credibility = self.ui.knowledge_credibility.text().strip()
if knowledge_credibility != '':
if self.IsFloat(knowledge_credibility):
knowledge_credibility = float(knowledge_credibility)
if knowledge_credibility > 1 or knowledge_credibility < 0:
msg += '结论可信度不在0-1之间!\n'
else:
msg += '表示结论可信度的不是一个数!\n'
update_person = self.ui.update_person.text().strip()
if msg != '':
QMessageBox.critical(self.ui, 'Error', msg)
return
else:
coolection_time = datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d %H:%M:%S')
if condition != '':
build_db.update_credibility_knowledge('ID', id, 'CONDITION', condition)
coolection_time = datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d %H:%M:%S')
self.ui.table.item(id - 1, 5).setText(coolection_time)
self.ui.table.item(id - 1, 0).setText(condition)
if conclusion != '':
build_db.update_credibility_knowledge('ID', id, 'CONCLUSION', conclusion)
coolection_time = datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d %H:%M:%S')
self.ui.table.item(id - 1, 5).setText(coolection_time)
self.ui.table.item(id - 1, 1).setText(conclusion)
if isinstance(condition_credibility,
float) and condition_credibility < 1 and condition_credibility > 0:
build_db.update_credibility_knowledge('ID', id, 'CONDITION_CREDIBILITY', condition_credibility)
coolection_time = datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d %H:%M:%S')
self.ui.table.item(id - 1, 5).setText(coolection_time)
self.ui.table.item(id - 1, 2).setText(str(condition_credibility))
if isinstance(knowledge_credibility,
float) and knowledge_credibility < 1 and knowledge_credibility > 0:
build_db.update_credibility_knowledge('ID', id, 'KNOWLEDGE_CREDIBILITY', knowledge_credibility)
coolection_time = datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d %H:%M:%S')
self.ui.table.item(id - 1, 5).setText(coolection_time)
self.ui.table.item(id - 1, 3).setText(str(knowledge_credibility))
if update_person != '':
build_db.update_credibility_knowledge('ID', id, 'UPDATE_PERSON', update_person)
coolection_time = datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d %H:%M:%S')
self.ui.table.item(id - 1, 5).setText(coolection_time)
self.ui.table.item(id - 1, 4).setText(update_person)
self.clear_all()
elif id[0] == '-' and id[1:].isnumeric():
QMessageBox.critical(self.ui, 'Error', 'ID为负数')
else:
QMessageBox.critical(self.ui, 'Error', 'ID不为整数')
def delete_knowledge(self):
if build_db.num_of_record() == 0:
QMessageBox.critical(self.ui, 'Error', '知识库中无知识')
return
id = self.ui.ID_line.text().strip()
if id == '':
QMessageBox.critical(self.ui, 'Error', 'ID为空')
return
if id.isnumeric():
id = int(id)
if id > build_db.num_of_record() or id < 0:
QMessageBox.critical(self.ui, 'Error', 'ID超出范围')
else:
build_db.del_credibility_knowledge('ID', id)
self.ui.table.removeRow(id - 1)
elif id[0] == '-' and id[1:].isnumeric():
QMessageBox.critical(self.ui, 'Error', 'ID为负数')
else:
QMessageBox.critical(self.ui, 'Error', 'ID不为整数')
def add_knowledge(self):
msg = ''
condition = self.ui.condition_line.text().strip()
if condition == '':
msg += '缺少条件!\n'
conclusion = self.ui.conclusion_line.text().strip()
if conclusion == '':
msg += '缺少结论!\n'
condition_credibility = self.ui.condition_credibility.text().strip()
if condition_credibility != '':
if (self.IsFloat(condition_credibility)):
condition_credibility = float(condition_credibility)
if condition_credibility > 1 or condition_credibility < 0:
msg += '条件可信度不在0-1之间!\n'
else:
msg += '表示条件可信度的不是一个数!\n'
else:
msg += '缺少条件可信度!\n'
knowledge_credibility = self.ui.knowledge_credibility.text().strip()
if knowledge_credibility != '':
if self.IsFloat(knowledge_credibility):
knowledge_credibility = float(knowledge_credibility)
if knowledge_credibility > 1 or knowledge_credibility < 0:
msg += '结论可信度不在0-1之间!\n'
else:
msg += '表示结论可信度的不是一个数!\n'
else:
msg += '缺少知识可信度!\n'
update_person = self.ui.update_person.text().strip()
if update_person == '':
msg += '缺少更新人!\n'
if msg != '':
QMessageBox.critical(self.ui, 'Error', msg)
return
else:
build_db.add_credibility_knowledge(condition, conclusion, condition_credibility, knowledge_credibility,
update_person) # 数据库中添加记录
coolection_time = datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d %H:%M:%S')
row = build_db.num_of_record()
if row >= 20:
self.ui.table.insertRow(self.ui.table.rowCount())
row = row - 1
self.ui.table.setItem(row, 5, QTableWidgetItem(coolection_time))
self.ui.table.item(row, 5).setFlags(QtCore.Qt.ItemIsEditable)
self.ui.table.setItem(row, 0, QTableWidgetItem(condition))
self.ui.table.item(row, 0).setFlags(QtCore.Qt.ItemIsEditable)
self.ui.table.setItem(row, 1, QTableWidgetItem(conclusion))
self.ui.table.item(row, 1).setFlags(QtCore.Qt.ItemIsEditable)
self.ui.table.setItem(row, 2, QTableWidgetItem(str(condition_credibility)))
self.ui.table.item(row, 2).setFlags(QtCore.Qt.ItemIsEditable)
self.ui.table.setItem(row, 3, QTableWidgetItem(str(knowledge_credibility)))
self.ui.table.item(row, 3).setFlags(QtCore.Qt.ItemIsEditable)
self.ui.table.setItem(row, 4, QTableWidgetItem(update_person))
self.ui.table.item(row, 4).setFlags(QtCore.Qt.ItemIsEditable)
return
def clear_all(self): # 清空所有的输入项
self.ui.ID_line.clear()
self.ui.condition_line.clear()
self.ui.conclusion_line.clear()
self.ui.condition_credibility.clear()
self.ui.knowledge_credibility.clear()
self.ui.update_person.clear()
self.show_knowledge('', '')
def IsFloat(self, str):
s = str.split('.')
if len(s) > 2:
return False
else:
for si in s:
if not si.isnumeric():
return False
return True
if __name__ == "__main__":
gui = CredibilityKnowledge() | sourcecode/credibilityKnowledge.py | import sys
from PyQt5 import uic, QtCore, QtGui
from PyQt5.QtWidgets import *
import build_db
import datetime
class CredibilityKnowledge:
def __init__(self):
self.ui = uic.loadUi("./ui/credibility.ui") # 组件名称查看credibility.ui
self.set_ui()
self.show_knowledge('', '') # 展示所有知识
self.ui.add.clicked.connect(self.add_knowledge)
self.ui.update.clicked.connect(self.update_knowledge)
self.ui.delete_2.clicked.connect(self.delete_knowledge)
self.ui.search_2.clicked.connect(self.search_knowledge)
self.ui.clear.clicked.connect(self.clear_all)
build_db.create_credibility_knowledge_table()
def set_ui(self):
ico_path = './image/light.ico'
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap(ico_path), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.ui.setWindowIcon(icon)
self.ui.setWindowTitle('可信度知识库')
self.ui.resize(1600, 600)
self.ui.table.horizontalHeader().setStretchLastSection(True)
self.ui.table.setRowCount(20)
self.ui.table.setColumnWidth(0, 180)
self.ui.table.setColumnWidth(1, 180)
self.ui.table.setColumnWidth(2, 100)
self.ui.table.setColumnWidth(3, 100)
self.ui.table.setColumnWidth(4, 100)
self.ui.table.setColumnWidth(5, 100)
def show_knowledge(self, type, content):
self.ui.table.clearContents()
res = build_db.search_credibility_knowledge(type, content)
line = 0
if res != None:
for row in range(len(res)):
for i in range(6):
if i < 4:
item1 = QTableWidgetItem(str(res[row][i + 1]))
item1.setFlags(QtCore.Qt.ItemIsEditable)
self.ui.table.setItem(row, i, item1)
elif i == 4:
item2 = QTableWidgetItem(str(res[row][6]))
item2.setFlags(QtCore.Qt.ItemIsEditable)
self.ui.table.setItem(row, i, item2)
elif i == 5:
item3 = QTableWidgetItem(str(res[row][5]))
item3.setFlags(QtCore.Qt.ItemIsEditable)
self.ui.table.setItem(row, i, item3)
def search_knowledge(self):
msg = ''
limit = 0
which = 0
condition = self.ui.condition_line.text().strip()
if condition != '':
limit += 1
which = 0
conclusion = self.ui.conclusion_line.text().strip()
if conclusion != '':
limit += 1
which = 1
condition_credibility = self.ui.condition_credibility.text().strip()
if condition_credibility != '':
limit += 1
which = 2
if (self.IsFloat(condition_credibility)):
condition_credibility = float(condition_credibility)
if condition_credibility > 1 or condition_credibility < 0:
msg += '条件可信度不在0-1之间!\n'
else:
msg += '表示条件可信度的不是一个数!\n'
knowledge_credibility = self.ui.knowledge_credibility.text().strip()
if knowledge_credibility != '':
limit += 1
which = 3
if self.IsFloat(knowledge_credibility):
knowledge_credibility = float(knowledge_credibility)
if knowledge_credibility > 1 or knowledge_credibility < 0:
msg += '结论可信度不在0-1之间!\n'
else:
msg += '表示结论可信度的不是一个数!\n'
update_person = self.ui.update_person.text().strip()
if update_person != '':
limit += 1
which = 4
if limit > 1:
QMessageBox.critical(self.ui, 'Error', '只能输入一个约束条件!')
return
if msg != '':
QMessageBox.critical(self.ui, 'Error', msg)
return
if limit == 1:
type = ['CONDITION', 'CONCLUSION', 'CONDITION_CREDIBILITY', 'KNOWLEDGE_CREDIBILITY', 'UPDATE_PERSON']
content = [condition, conclusion, condition_credibility, knowledge_credibility, update_person]
self.show_knowledge(type[which], content[which])
def update_knowledge(self):
if build_db.num_of_record() == 0:
QMessageBox.critical(self.ui, 'Error', '知识库中无知识')
return
id = self.ui.ID_line.text().strip()
if id == '':
QMessageBox.critical(self.ui, 'Error', 'ID为空')
return
if id.isnumeric():
id = int(id)
if id > build_db.num_of_record() or id < 0:
QMessageBox.critical(self.ui, 'Error', 'ID超出范围')
else:
msg = ''
condition = self.ui.condition_line.text().strip()
print(type(condition))
conclusion = self.ui.conclusion_line.text().strip()
condition_credibility = self.ui.condition_credibility.text().strip()
if condition_credibility != '':
if (self.IsFloat(condition_credibility)):
condition_credibility = float(condition_credibility)
if condition_credibility > 1 or condition_credibility < 0:
msg += '条件可信度不在0-1之间!\n'
else:
msg += '表示条件可信度的不是一个数!\n'
knowledge_credibility = self.ui.knowledge_credibility.text().strip()
if knowledge_credibility != '':
if self.IsFloat(knowledge_credibility):
knowledge_credibility = float(knowledge_credibility)
if knowledge_credibility > 1 or knowledge_credibility < 0:
msg += '结论可信度不在0-1之间!\n'
else:
msg += '表示结论可信度的不是一个数!\n'
update_person = self.ui.update_person.text().strip()
if msg != '':
QMessageBox.critical(self.ui, 'Error', msg)
return
else:
coolection_time = datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d %H:%M:%S')
if condition != '':
build_db.update_credibility_knowledge('ID', id, 'CONDITION', condition)
coolection_time = datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d %H:%M:%S')
self.ui.table.item(id - 1, 5).setText(coolection_time)
self.ui.table.item(id - 1, 0).setText(condition)
if conclusion != '':
build_db.update_credibility_knowledge('ID', id, 'CONCLUSION', conclusion)
coolection_time = datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d %H:%M:%S')
self.ui.table.item(id - 1, 5).setText(coolection_time)
self.ui.table.item(id - 1, 1).setText(conclusion)
if isinstance(condition_credibility,
float) and condition_credibility < 1 and condition_credibility > 0:
build_db.update_credibility_knowledge('ID', id, 'CONDITION_CREDIBILITY', condition_credibility)
coolection_time = datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d %H:%M:%S')
self.ui.table.item(id - 1, 5).setText(coolection_time)
self.ui.table.item(id - 1, 2).setText(str(condition_credibility))
if isinstance(knowledge_credibility,
float) and knowledge_credibility < 1 and knowledge_credibility > 0:
build_db.update_credibility_knowledge('ID', id, 'KNOWLEDGE_CREDIBILITY', knowledge_credibility)
coolection_time = datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d %H:%M:%S')
self.ui.table.item(id - 1, 5).setText(coolection_time)
self.ui.table.item(id - 1, 3).setText(str(knowledge_credibility))
if update_person != '':
build_db.update_credibility_knowledge('ID', id, 'UPDATE_PERSON', update_person)
coolection_time = datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d %H:%M:%S')
self.ui.table.item(id - 1, 5).setText(coolection_time)
self.ui.table.item(id - 1, 4).setText(update_person)
self.clear_all()
elif id[0] == '-' and id[1:].isnumeric():
QMessageBox.critical(self.ui, 'Error', 'ID为负数')
else:
QMessageBox.critical(self.ui, 'Error', 'ID不为整数')
def delete_knowledge(self):
if build_db.num_of_record() == 0:
QMessageBox.critical(self.ui, 'Error', '知识库中无知识')
return
id = self.ui.ID_line.text().strip()
if id == '':
QMessageBox.critical(self.ui, 'Error', 'ID为空')
return
if id.isnumeric():
id = int(id)
if id > build_db.num_of_record() or id < 0:
QMessageBox.critical(self.ui, 'Error', 'ID超出范围')
else:
build_db.del_credibility_knowledge('ID', id)
self.ui.table.removeRow(id - 1)
elif id[0] == '-' and id[1:].isnumeric():
QMessageBox.critical(self.ui, 'Error', 'ID为负数')
else:
QMessageBox.critical(self.ui, 'Error', 'ID不为整数')
def add_knowledge(self):
msg = ''
condition = self.ui.condition_line.text().strip()
if condition == '':
msg += '缺少条件!\n'
conclusion = self.ui.conclusion_line.text().strip()
if conclusion == '':
msg += '缺少结论!\n'
condition_credibility = self.ui.condition_credibility.text().strip()
if condition_credibility != '':
if (self.IsFloat(condition_credibility)):
condition_credibility = float(condition_credibility)
if condition_credibility > 1 or condition_credibility < 0:
msg += '条件可信度不在0-1之间!\n'
else:
msg += '表示条件可信度的不是一个数!\n'
else:
msg += '缺少条件可信度!\n'
knowledge_credibility = self.ui.knowledge_credibility.text().strip()
if knowledge_credibility != '':
if self.IsFloat(knowledge_credibility):
knowledge_credibility = float(knowledge_credibility)
if knowledge_credibility > 1 or knowledge_credibility < 0:
msg += '结论可信度不在0-1之间!\n'
else:
msg += '表示结论可信度的不是一个数!\n'
else:
msg += '缺少知识可信度!\n'
update_person = self.ui.update_person.text().strip()
if update_person == '':
msg += '缺少更新人!\n'
if msg != '':
QMessageBox.critical(self.ui, 'Error', msg)
return
else:
build_db.add_credibility_knowledge(condition, conclusion, condition_credibility, knowledge_credibility,
update_person) # 数据库中添加记录
coolection_time = datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d %H:%M:%S')
row = build_db.num_of_record()
if row >= 20:
self.ui.table.insertRow(self.ui.table.rowCount())
row = row - 1
self.ui.table.setItem(row, 5, QTableWidgetItem(coolection_time))
self.ui.table.item(row, 5).setFlags(QtCore.Qt.ItemIsEditable)
self.ui.table.setItem(row, 0, QTableWidgetItem(condition))
self.ui.table.item(row, 0).setFlags(QtCore.Qt.ItemIsEditable)
self.ui.table.setItem(row, 1, QTableWidgetItem(conclusion))
self.ui.table.item(row, 1).setFlags(QtCore.Qt.ItemIsEditable)
self.ui.table.setItem(row, 2, QTableWidgetItem(str(condition_credibility)))
self.ui.table.item(row, 2).setFlags(QtCore.Qt.ItemIsEditable)
self.ui.table.setItem(row, 3, QTableWidgetItem(str(knowledge_credibility)))
self.ui.table.item(row, 3).setFlags(QtCore.Qt.ItemIsEditable)
self.ui.table.setItem(row, 4, QTableWidgetItem(update_person))
self.ui.table.item(row, 4).setFlags(QtCore.Qt.ItemIsEditable)
return
def clear_all(self): # 清空所有的输入项
self.ui.ID_line.clear()
self.ui.condition_line.clear()
self.ui.conclusion_line.clear()
self.ui.condition_credibility.clear()
self.ui.knowledge_credibility.clear()
self.ui.update_person.clear()
self.show_knowledge('', '')
def IsFloat(self, str):
s = str.split('.')
if len(s) > 2:
return False
else:
for si in s:
if not si.isnumeric():
return False
return True
if __name__ == "__main__":
gui = CredibilityKnowledge() | 0.121451 | 0.059565 |
import os
from time import sleep
import subprocess
import logging
import glob
import db
import keystoneclient.v2_0.client as ksclient
from novaclient import client as novaclient
import glanceclient
from credentials import get_keystone_creds
from credentials import get_nova_creds
from dest_credentials import get_dest_keystone_creds
from dest_credentials import get_dest_nova_creds
class Auth(object):
def __init__(self):
self.kcreds = get_keystone_creds()
self.keystone = ksclient.Client(**self.kcreds)
self.ncreds = get_nova_creds()
self.nova = novaclient.Client("1.1",**self.ncreds)
self.glance_endpoint = self.keystone.service_catalog.url_for(service_type='image',endpoint_type='publicURL')
self.glance = glanceclient.Client('1',self.glance_endpoint, token=self.keystone.auth_token)
class Images(Auth):
script_path = os.path.dirname(os.path.abspath(__file__))
logfile = "{0}/dr.log".format(script_path)
logging.basicConfig(level=logging.INFO,format='%(asctime)s %(levelname)-8s %(message)s',datefmt='%a, %d %b %Y %H:%M:%S',filename=logfile)
def __init__(self):
super(Images, self).__init__()
self.servers = self.nova.servers.list()
self.mysql = db.Database()
def get_property(self,id):
property = self.glance.images.get(id)
return property
def backup_server(self,**kwargs):
"""Backup all running servers."""
self.nova.servers.backup(kwargs['server_id'], kwargs['backup_name'], kwargs['backup_type'], kwargs['rotation'])
def make_backup_dir(self):
if not os.path.exists("{0}/backups".format( self.script_path )):
os.makedirs("backups")
else: return
def prepared_list(self):
get_imags = self.glance.images.list()
get_servers = self.nova.servers.list()
images_names_list = []
for img in get_imags:
images_names_list.append(img.name)
servers_names_list = []
for srvr in get_servers:
servers_names_list.append(srvr.name+"_backup")
down_list = [elem for elem in images_names_list if elem in servers_names_list]
get_imags_casted = self.glance.images.list()
imagss_list = list(get_imags_casted)
result = []
for x in xrange(0,len(down_list)):
server_name = down_list[x]
for y in xrange(0,len(imagss_list)):
imgs_name = imagss_list[y].name
if server_name == imgs_name:
imgs_id = imagss_list[y].id
rs_img = {}
rs_img['name'] = imgs_name
rs_img['id'] = imgs_id
list_imgg = [rs_img]
get_img = self.glance.images.get(imgs_id)
while get_img.status != 'active':
sleep(5)
get_imgg = self.glance.images.get(imgs_id)
if get_imgg.status == 'active':
break
rs_img['disk_format'] = get_img.disk_format
rs_img['container_format'] = get_img.container_format
rs_img['is_public'] = get_img.is_public
rs_img['img_path'] = self.script_path+"/backups/"+imgs_name+".img"
rs_img['exc'] = self.script_path
result.append(list_imgg)
break
return result
def download_image(self,**kwargs):
"""Download images using glance client."""
image_name = kwargs['image_name'].replace (" ", "_")
try:
os.chdir(kwargs['down_path'])
except OSError as e:
logging.warning(e)
if kwargs['is_ami']:
if kwargs['aki']=='aki':
print "AKI"
cmd = "glance image-download %s >> %s-vmlinuz" %(kwargs['kernel_id'],image_name)
os.system(cmd)
if kwargs['ari']=='ari':
print "ARI"
cmd = "glance image-download %s >> %s-loader" %(kwargs['ramdisk_id'],image_name)
os.system(cmd)
print "AMI"
cmd = "glance image-download %s >> %s.img" %(kwargs['image_id'],image_name)
os.system(cmd)
else:
print"Not ami"
cmd = "glance image-download %s >> %s.img" %(kwargs['image_id'],image_name)
os.system(cmd)
def upload_img(self,**kwargs):
"""Upload image to destination glance."""
with open(kwargs['img_path']) as fimage:
self.glance.images.create(name=kwargs['img_name'], is_public=kwargs['is_public'], disk_format=kwargs['disk_format'],container_format=kwargs['container_format'], data=fimage)
def get_backup_id(self,images):
ids=[]
for x in xrange(0,len(images)):
ids.append(images[x][0]['id'])
return ids
def execute_backups(self,backup_list=None):
backup_vars = {}
if backup_list is None:
servers_list = self.nova.servers.list()
else:
servers_list = backup_list
for i in xrange(0,len(servers_list)):
check = self.mysql.check_image_exists(self.keystone.tenant_id, servers_list[i].id)
if not check :
logging.info("No servers")
if servers_list[i].status == 'ACTIVE':
backup_vars['server_id'] = servers_list[i].id
backup_vars['backup_name'] = "{0}_backup".format(servers_list[i].name)
backup_vars['backup_type'] = 'daily'
backup_vars['rotation'] = 1
self.backup_server(**backup_vars)
self.print_format("Backing up... {0}".format(servers_list[i].name ))
logging.info("Backing up... {0}".format(servers_list[i].name ))
self.mysql.insert_data(self.keystone.tenant_id,self.keystone.username,servers_list[i].id,'',servers_list[i].name)
else:
self.print_format("{0} is not active and will be ignored".format(servers_list[i].name ))
else:
logging.info("pass")
def update_backup(self,backup_list=None):
backup_vars = {}
if backup_list is None:
servers_list = self.nova.servers.list()
else:
servers_list = backup_list
for i in xrange(0,len(servers_list)):
if servers_list[i].status == 'ACTIVE':
backup_vars['server_id'] = servers_list[i].id
backup_vars['backup_name'] = "{0}_backup".format(servers_list[i].name)
backup_vars['backup_type'] = 'daily'
backup_vars['rotation'] = 1
self.backup_server(**backup_vars)
self.print_format("Backing up... {0}".format(servers_list[i].name ))
logging.info("Backing up... {0}".format(servers_list[i].name ))
self.mysql.insert_data(self.keystone.tenant_id,self.keystone.username,servers_list[i].id,'',servers_list[i].name)
else:
self.print_format("{0} is not active and will be ignored".format(servers_list[i].name ))
def print_format(self,string):
print "+%s+" %("-" * len(string))
print "|%s|" % string
print "+%s+" %("-" * len(string))
def get_meta_and_return_servers(self):
meta = []
_servers = self.nova.servers.list()
for srvrs in _servers:
rs = {}
gets = self.nova.servers.get(srvrs.id)
rs['dr'] = gets.metadata.values()
rs['id'] = srvrs.id
meta_list = [rs]
meta.append(meta_list)
res = [k for k in meta if '1' in k[0]['dr']]
servers =[]
for i in xrange(0,len(res)):
get_servers = self.nova.servers.get(res[i][0]['id'])
servers.append(get_servers)
return servers
if __name__ == "__main__":
obj=Images()
if not obj.prepared_list():
obj.print_format("First backup...")
if not obj.get_meta_and_return_servers():
logging.info("No custom servers list")
obj.execute_backups()
else:
logging.info("custom servers list with dr key")
obj.execute_backups(obj.get_meta_and_return_servers())
else:
obj.print_format("Updating backups...")
backup_list_index = obj.get_backup_id(obj.prepared_list())
for x in xrange(0,len( backup_list_index )):
obj.glance.images.delete(backup_list_index[x])
obj.mysql.delete_data(obj.keystone.tenant_id)
if not obj.get_meta_and_return_servers():
logging.info("No custom servers list")
obj.execute_backups()
else:
logging.info("custom servers list with dr key")
obj.execute_backups(obj.get_meta_and_return_servers()) | main.py |
import os
from time import sleep
import subprocess
import logging
import glob
import db
import keystoneclient.v2_0.client as ksclient
from novaclient import client as novaclient
import glanceclient
from credentials import get_keystone_creds
from credentials import get_nova_creds
from dest_credentials import get_dest_keystone_creds
from dest_credentials import get_dest_nova_creds
class Auth(object):
def __init__(self):
self.kcreds = get_keystone_creds()
self.keystone = ksclient.Client(**self.kcreds)
self.ncreds = get_nova_creds()
self.nova = novaclient.Client("1.1",**self.ncreds)
self.glance_endpoint = self.keystone.service_catalog.url_for(service_type='image',endpoint_type='publicURL')
self.glance = glanceclient.Client('1',self.glance_endpoint, token=self.keystone.auth_token)
class Images(Auth):
script_path = os.path.dirname(os.path.abspath(__file__))
logfile = "{0}/dr.log".format(script_path)
logging.basicConfig(level=logging.INFO,format='%(asctime)s %(levelname)-8s %(message)s',datefmt='%a, %d %b %Y %H:%M:%S',filename=logfile)
def __init__(self):
super(Images, self).__init__()
self.servers = self.nova.servers.list()
self.mysql = db.Database()
def get_property(self,id):
property = self.glance.images.get(id)
return property
def backup_server(self,**kwargs):
"""Backup all running servers."""
self.nova.servers.backup(kwargs['server_id'], kwargs['backup_name'], kwargs['backup_type'], kwargs['rotation'])
def make_backup_dir(self):
if not os.path.exists("{0}/backups".format( self.script_path )):
os.makedirs("backups")
else: return
def prepared_list(self):
get_imags = self.glance.images.list()
get_servers = self.nova.servers.list()
images_names_list = []
for img in get_imags:
images_names_list.append(img.name)
servers_names_list = []
for srvr in get_servers:
servers_names_list.append(srvr.name+"_backup")
down_list = [elem for elem in images_names_list if elem in servers_names_list]
get_imags_casted = self.glance.images.list()
imagss_list = list(get_imags_casted)
result = []
for x in xrange(0,len(down_list)):
server_name = down_list[x]
for y in xrange(0,len(imagss_list)):
imgs_name = imagss_list[y].name
if server_name == imgs_name:
imgs_id = imagss_list[y].id
rs_img = {}
rs_img['name'] = imgs_name
rs_img['id'] = imgs_id
list_imgg = [rs_img]
get_img = self.glance.images.get(imgs_id)
while get_img.status != 'active':
sleep(5)
get_imgg = self.glance.images.get(imgs_id)
if get_imgg.status == 'active':
break
rs_img['disk_format'] = get_img.disk_format
rs_img['container_format'] = get_img.container_format
rs_img['is_public'] = get_img.is_public
rs_img['img_path'] = self.script_path+"/backups/"+imgs_name+".img"
rs_img['exc'] = self.script_path
result.append(list_imgg)
break
return result
def download_image(self,**kwargs):
"""Download images using glance client."""
image_name = kwargs['image_name'].replace (" ", "_")
try:
os.chdir(kwargs['down_path'])
except OSError as e:
logging.warning(e)
if kwargs['is_ami']:
if kwargs['aki']=='aki':
print "AKI"
cmd = "glance image-download %s >> %s-vmlinuz" %(kwargs['kernel_id'],image_name)
os.system(cmd)
if kwargs['ari']=='ari':
print "ARI"
cmd = "glance image-download %s >> %s-loader" %(kwargs['ramdisk_id'],image_name)
os.system(cmd)
print "AMI"
cmd = "glance image-download %s >> %s.img" %(kwargs['image_id'],image_name)
os.system(cmd)
else:
print"Not ami"
cmd = "glance image-download %s >> %s.img" %(kwargs['image_id'],image_name)
os.system(cmd)
def upload_img(self,**kwargs):
"""Upload image to destination glance."""
with open(kwargs['img_path']) as fimage:
self.glance.images.create(name=kwargs['img_name'], is_public=kwargs['is_public'], disk_format=kwargs['disk_format'],container_format=kwargs['container_format'], data=fimage)
def get_backup_id(self,images):
ids=[]
for x in xrange(0,len(images)):
ids.append(images[x][0]['id'])
return ids
def execute_backups(self,backup_list=None):
backup_vars = {}
if backup_list is None:
servers_list = self.nova.servers.list()
else:
servers_list = backup_list
for i in xrange(0,len(servers_list)):
check = self.mysql.check_image_exists(self.keystone.tenant_id, servers_list[i].id)
if not check :
logging.info("No servers")
if servers_list[i].status == 'ACTIVE':
backup_vars['server_id'] = servers_list[i].id
backup_vars['backup_name'] = "{0}_backup".format(servers_list[i].name)
backup_vars['backup_type'] = 'daily'
backup_vars['rotation'] = 1
self.backup_server(**backup_vars)
self.print_format("Backing up... {0}".format(servers_list[i].name ))
logging.info("Backing up... {0}".format(servers_list[i].name ))
self.mysql.insert_data(self.keystone.tenant_id,self.keystone.username,servers_list[i].id,'',servers_list[i].name)
else:
self.print_format("{0} is not active and will be ignored".format(servers_list[i].name ))
else:
logging.info("pass")
def update_backup(self,backup_list=None):
backup_vars = {}
if backup_list is None:
servers_list = self.nova.servers.list()
else:
servers_list = backup_list
for i in xrange(0,len(servers_list)):
if servers_list[i].status == 'ACTIVE':
backup_vars['server_id'] = servers_list[i].id
backup_vars['backup_name'] = "{0}_backup".format(servers_list[i].name)
backup_vars['backup_type'] = 'daily'
backup_vars['rotation'] = 1
self.backup_server(**backup_vars)
self.print_format("Backing up... {0}".format(servers_list[i].name ))
logging.info("Backing up... {0}".format(servers_list[i].name ))
self.mysql.insert_data(self.keystone.tenant_id,self.keystone.username,servers_list[i].id,'',servers_list[i].name)
else:
self.print_format("{0} is not active and will be ignored".format(servers_list[i].name ))
def print_format(self,string):
print "+%s+" %("-" * len(string))
print "|%s|" % string
print "+%s+" %("-" * len(string))
def get_meta_and_return_servers(self):
meta = []
_servers = self.nova.servers.list()
for srvrs in _servers:
rs = {}
gets = self.nova.servers.get(srvrs.id)
rs['dr'] = gets.metadata.values()
rs['id'] = srvrs.id
meta_list = [rs]
meta.append(meta_list)
res = [k for k in meta if '1' in k[0]['dr']]
servers =[]
for i in xrange(0,len(res)):
get_servers = self.nova.servers.get(res[i][0]['id'])
servers.append(get_servers)
return servers
if __name__ == "__main__":
obj=Images()
if not obj.prepared_list():
obj.print_format("First backup...")
if not obj.get_meta_and_return_servers():
logging.info("No custom servers list")
obj.execute_backups()
else:
logging.info("custom servers list with dr key")
obj.execute_backups(obj.get_meta_and_return_servers())
else:
obj.print_format("Updating backups...")
backup_list_index = obj.get_backup_id(obj.prepared_list())
for x in xrange(0,len( backup_list_index )):
obj.glance.images.delete(backup_list_index[x])
obj.mysql.delete_data(obj.keystone.tenant_id)
if not obj.get_meta_and_return_servers():
logging.info("No custom servers list")
obj.execute_backups()
else:
logging.info("custom servers list with dr key")
obj.execute_backups(obj.get_meta_and_return_servers()) | 0.17824 | 0.068475 |
import sqlite3
from time import time
import psutil
import os
from AnkiTools.tools.path import get_collection_path
from AnkiTools.tools.create import AnkiContentCreator
from AnkiTools.tools.write import write_anki_json, write_anki_table, write_anki_schema
from AnkiTools.tools.read import read_anki_json, read_anki_table
from .verify import AnkiContentVerify
class AnkiDirect:
def __init__(self, anki_database: str=None):
if anki_database is None:
anki_database = get_collection_path()
try:
assert 'Anki' not in (p.name() for p in psutil.process_iter()), \
"Please close Anki first before accessing Application Data collection.anki2 directly."
except psutil.ZombieProcess as e:
print(e)
do_init = False
if not os.path.exists(anki_database):
do_init = True
self.conn = sqlite3.connect(anki_database)
if do_init:
self.creator = AnkiContentCreator()
write_anki_schema(self.conn)
anki_collection = self.creator.new_collection()
write_anki_table(self.conn, 'col', [anki_collection], do_commit=True)
self.models = self.get_models()
self.decks = self.get_decks()
self.notes = dict()
self.cards = dict()
else:
self.models = self.get_models()
self.decks = self.get_decks()
self.notes = self.get_notes()
self.cards = self.get_cards()
self.creator = AnkiContentCreator({'notes': self.notes, 'cards': self.cards,
'models': self.models, 'decks': self.decks})
self._name_to_id = self.name_to_id
self.verify = AnkiContentVerify({'notes': self.notes, 'cards': self.cards,
'models': self.models, 'decks': self.decks})
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.close()
def close(self):
self.conn.close()
@property
def name_to_id(self):
name_to_id = {
'models': dict(),
'decks': dict()
}
for k, v in self.models.items():
name_to_id['models'][v['name']] = k
for k, v in self.decks.items():
name_to_id['decks'][v['name']] = k
return name_to_id
def _get_model_id(self, model_name, model_header, model_definition, **kwargs):
try:
model_id = self._name_to_id['models'][model_name]
except KeyError:
anki_model = self.creator.new_model(model_name, model_header, model_definition,
modified=kwargs.get('modified', None))
self.models[str(anki_model['id'])] = anki_model
write_anki_json(self.conn, 'models', [anki_model], do_commit=True)
model_id = anki_model['id']
self._name_to_id['models'][model_name] = model_id
return model_id
def _get_card_ordering(self, model_id, note_side):
note_sides = [template['name'] for template in self.models[str(model_id)]['tmpls']]
return note_sides.index(note_side)
def get_models(self):
return read_anki_json(self.conn, 'models')
def get_decks(self):
return read_anki_json(self.conn, 'decks')
def get_notes(self):
note_dict = dict()
for note in read_anki_table(self.conn, 'notes'):
note_dict[str(note['id'])] = note
return note_dict
def get_cards(self):
card_dict = dict()
for card in read_anki_table(self.conn, 'cards'):
card_dict[str(card['id'])] = card
return card_dict
def add(self, data):
if not self.verify.verify_add_info(data):
return False
modified = int(time())
for model_name, notes in data['data'].items():
model_id = self._get_model_id(model_name,
notes[0]['data'].keys(),
data.get('definitions', dict()).get(model_name, dict()))
anki_notes = []
anki_cards = []
anki_decks = []
for note in notes:
anki_note = self.creator.new_note(flds_list=list(note['data'].values()),
model_id=model_id,
modified=modified)
self.notes[str(anki_note['id'])] = anki_note
anki_notes.append(anki_note)
for note_side, deck_name in note['decks'].items():
try:
deck_id = self._name_to_id['decks'][deck_name]
except KeyError:
anki_deck = self.creator.new_deck(deck_name)
self.decks[str(anki_deck['id'])] = anki_deck
anki_decks.append(anki_deck)
deck_id = anki_deck['id']
self._name_to_id['decks'][deck_name] = deck_id
anki_card = self.creator.new_card(anki_note['id'],
deck_id,
self._get_card_ordering(model_id, note_side),
modified=modified)
self.cards[str(anki_card['id'])] = anki_card
anki_cards.append(anki_card)
missing_deck_names = self.verify.missing_decks()
for deck_name in missing_deck_names:
anki_deck = self.creator.new_deck(deck_name)
self.decks[str(anki_deck['id'])] = anki_deck
anki_decks.append(anki_deck)
write_anki_table(self.conn, 'notes', anki_notes, do_commit=False)
write_anki_table(self.conn, 'cards', anki_cards, do_commit=False)
write_anki_json(self.conn, 'decks', anki_decks, do_commit=False)
self.conn.commit()
return True | AnkiTools/api/app.py | import sqlite3
from time import time
import psutil
import os
from AnkiTools.tools.path import get_collection_path
from AnkiTools.tools.create import AnkiContentCreator
from AnkiTools.tools.write import write_anki_json, write_anki_table, write_anki_schema
from AnkiTools.tools.read import read_anki_json, read_anki_table
from .verify import AnkiContentVerify
class AnkiDirect:
def __init__(self, anki_database: str=None):
if anki_database is None:
anki_database = get_collection_path()
try:
assert 'Anki' not in (p.name() for p in psutil.process_iter()), \
"Please close Anki first before accessing Application Data collection.anki2 directly."
except psutil.ZombieProcess as e:
print(e)
do_init = False
if not os.path.exists(anki_database):
do_init = True
self.conn = sqlite3.connect(anki_database)
if do_init:
self.creator = AnkiContentCreator()
write_anki_schema(self.conn)
anki_collection = self.creator.new_collection()
write_anki_table(self.conn, 'col', [anki_collection], do_commit=True)
self.models = self.get_models()
self.decks = self.get_decks()
self.notes = dict()
self.cards = dict()
else:
self.models = self.get_models()
self.decks = self.get_decks()
self.notes = self.get_notes()
self.cards = self.get_cards()
self.creator = AnkiContentCreator({'notes': self.notes, 'cards': self.cards,
'models': self.models, 'decks': self.decks})
self._name_to_id = self.name_to_id
self.verify = AnkiContentVerify({'notes': self.notes, 'cards': self.cards,
'models': self.models, 'decks': self.decks})
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.close()
def close(self):
self.conn.close()
@property
def name_to_id(self):
name_to_id = {
'models': dict(),
'decks': dict()
}
for k, v in self.models.items():
name_to_id['models'][v['name']] = k
for k, v in self.decks.items():
name_to_id['decks'][v['name']] = k
return name_to_id
def _get_model_id(self, model_name, model_header, model_definition, **kwargs):
try:
model_id = self._name_to_id['models'][model_name]
except KeyError:
anki_model = self.creator.new_model(model_name, model_header, model_definition,
modified=kwargs.get('modified', None))
self.models[str(anki_model['id'])] = anki_model
write_anki_json(self.conn, 'models', [anki_model], do_commit=True)
model_id = anki_model['id']
self._name_to_id['models'][model_name] = model_id
return model_id
def _get_card_ordering(self, model_id, note_side):
note_sides = [template['name'] for template in self.models[str(model_id)]['tmpls']]
return note_sides.index(note_side)
def get_models(self):
return read_anki_json(self.conn, 'models')
def get_decks(self):
return read_anki_json(self.conn, 'decks')
def get_notes(self):
note_dict = dict()
for note in read_anki_table(self.conn, 'notes'):
note_dict[str(note['id'])] = note
return note_dict
def get_cards(self):
card_dict = dict()
for card in read_anki_table(self.conn, 'cards'):
card_dict[str(card['id'])] = card
return card_dict
def add(self, data):
if not self.verify.verify_add_info(data):
return False
modified = int(time())
for model_name, notes in data['data'].items():
model_id = self._get_model_id(model_name,
notes[0]['data'].keys(),
data.get('definitions', dict()).get(model_name, dict()))
anki_notes = []
anki_cards = []
anki_decks = []
for note in notes:
anki_note = self.creator.new_note(flds_list=list(note['data'].values()),
model_id=model_id,
modified=modified)
self.notes[str(anki_note['id'])] = anki_note
anki_notes.append(anki_note)
for note_side, deck_name in note['decks'].items():
try:
deck_id = self._name_to_id['decks'][deck_name]
except KeyError:
anki_deck = self.creator.new_deck(deck_name)
self.decks[str(anki_deck['id'])] = anki_deck
anki_decks.append(anki_deck)
deck_id = anki_deck['id']
self._name_to_id['decks'][deck_name] = deck_id
anki_card = self.creator.new_card(anki_note['id'],
deck_id,
self._get_card_ordering(model_id, note_side),
modified=modified)
self.cards[str(anki_card['id'])] = anki_card
anki_cards.append(anki_card)
missing_deck_names = self.verify.missing_decks()
for deck_name in missing_deck_names:
anki_deck = self.creator.new_deck(deck_name)
self.decks[str(anki_deck['id'])] = anki_deck
anki_decks.append(anki_deck)
write_anki_table(self.conn, 'notes', anki_notes, do_commit=False)
write_anki_table(self.conn, 'cards', anki_cards, do_commit=False)
write_anki_json(self.conn, 'decks', anki_decks, do_commit=False)
self.conn.commit()
return True | 0.286269 | 0.166472 |
import discord
import discord.ext.commands as commands
import random
import sys
import os
import requests
import asyncio
import logging
import threading
sys.path.insert(0, "../")
import util
class Streets(commands.Cog):
def __init__(self, bot, timeouts, generic_responses):
self.logger = logging.getLogger(__name__)
self.bot = bot
self.timeouts = timeouts
self.generic_responses = generic_responses
self.strassen_osm_txt = open("strassen_osm.txt", "r").readlines()
self.staedte_osm_txt = open("staedte_osm.txt", "r").readlines()
self.image_search_cache = list()
bot.loop.create_task(self.refresh_search_cache_loop())
def refresh_search_cache(self):
self.logger.info("Refreshing image cache...")
if 1 == 1:
self.logger.info("Debugging is on, not downloading image cache.")
return
self.image_search_cache = list()
search_terms = ("house", "building", "apartment house", "small house")
for term in search_terms:
self.image_search_cache += next(util.duckduckgo_api.search(term, max_results=200))
self.logger.info(str(search_terms.index(term) + 1) + "/" + str(len(search_terms)))
self.logger.info("Done. Got " + str(len(self.image_search_cache)) + " results.")
async def refresh_search_cache_loop(self):
await asyncio.sleep(5)
while True:
try:
thread = threading.Thread(target=self.refresh_search_cache)
thread.start()
thread.join(timeout=5)
except Exception as exc:
self.logger.error("Couldn't refresh search cache: " + str(exc))
if len(self.image_search_cache) == 0:
await asyncio.sleep(30)
else:
await asyncio.sleep(30 * 60 + random.randint(-100, 100)) # adding a bit of randomness so it doesn't seem like a bot ;))))))
@commands.command()
async def address(self, ctx):
if self.timeouts.is_timeout(ctx.message.channel.id, "address"):
await ctx.send(content=self.generic_responses["timeout"])
return
if len(self.image_search_cache) == 0:
await ctx.send("The image search cache is not ready yet! Try again in a few seconds.")
return
self.timeouts.add_timeout(ctx.message.channel.id, "address", 7)
city = random.choice(self.staedte_osm_txt)[1:-2]
street = random.choice(self.strassen_osm_txt)[1:-2]
number = random.randint(1, 24)
chosen_image = random.choice(self.image_search_cache)
filename = "cache/" + str(ctx.message.channel.id) + "_address.png"
response = requests.get(chosen_image["thumbnail"], stream=True)
with open(filename , "wb") as file:
for buffer in response.iter_content(chunk_size=2048):
file.write(buffer)
await ctx.send(content=street + " " + str(number) + ", " + city, file=discord.File(filename))
os.unlink(filename) | commands/streets.py | import discord
import discord.ext.commands as commands
import random
import sys
import os
import requests
import asyncio
import logging
import threading
sys.path.insert(0, "../")
import util
class Streets(commands.Cog):
def __init__(self, bot, timeouts, generic_responses):
self.logger = logging.getLogger(__name__)
self.bot = bot
self.timeouts = timeouts
self.generic_responses = generic_responses
self.strassen_osm_txt = open("strassen_osm.txt", "r").readlines()
self.staedte_osm_txt = open("staedte_osm.txt", "r").readlines()
self.image_search_cache = list()
bot.loop.create_task(self.refresh_search_cache_loop())
def refresh_search_cache(self):
self.logger.info("Refreshing image cache...")
if 1 == 1:
self.logger.info("Debugging is on, not downloading image cache.")
return
self.image_search_cache = list()
search_terms = ("house", "building", "apartment house", "small house")
for term in search_terms:
self.image_search_cache += next(util.duckduckgo_api.search(term, max_results=200))
self.logger.info(str(search_terms.index(term) + 1) + "/" + str(len(search_terms)))
self.logger.info("Done. Got " + str(len(self.image_search_cache)) + " results.")
async def refresh_search_cache_loop(self):
await asyncio.sleep(5)
while True:
try:
thread = threading.Thread(target=self.refresh_search_cache)
thread.start()
thread.join(timeout=5)
except Exception as exc:
self.logger.error("Couldn't refresh search cache: " + str(exc))
if len(self.image_search_cache) == 0:
await asyncio.sleep(30)
else:
await asyncio.sleep(30 * 60 + random.randint(-100, 100)) # adding a bit of randomness so it doesn't seem like a bot ;))))))
@commands.command()
async def address(self, ctx):
if self.timeouts.is_timeout(ctx.message.channel.id, "address"):
await ctx.send(content=self.generic_responses["timeout"])
return
if len(self.image_search_cache) == 0:
await ctx.send("The image search cache is not ready yet! Try again in a few seconds.")
return
self.timeouts.add_timeout(ctx.message.channel.id, "address", 7)
city = random.choice(self.staedte_osm_txt)[1:-2]
street = random.choice(self.strassen_osm_txt)[1:-2]
number = random.randint(1, 24)
chosen_image = random.choice(self.image_search_cache)
filename = "cache/" + str(ctx.message.channel.id) + "_address.png"
response = requests.get(chosen_image["thumbnail"], stream=True)
with open(filename , "wb") as file:
for buffer in response.iter_content(chunk_size=2048):
file.write(buffer)
await ctx.send(content=street + " " + str(number) + ", " + city, file=discord.File(filename))
os.unlink(filename) | 0.21428 | 0.079353 |
import sys
import click
from . import fplapi
from . import configure as conf
from .cliprinter import out
from .cliprinter import pretty_league
from .cliprinter import pretty_liveleague
from .cliprinter import pretty_leagues
from .cliprinter import pretty_picks_info
from .cliprinter import pretty_picks_players
from .cliprinter import pretty_players
from .cliprinter import pretty_entry
def get_team_id():
try:
config = conf.get_config()
return config["DEFAULT"]["team_id"]
except KeyError:
sys.exit("FPL CLI is not configured. Type: fpl configure")
@click.group()
def main():
"""
FPL CLI - Command Line Interface for Fantasy Premier League.
"""
out("FPL CLI", color="cyan", figlet=True)
out("FPL CLI - Fantasy Premier League in your terminal \n", color="red")
@main.command()
def players():
"""Returns all players"""
players = fplapi.players()
out(pretty_players(players))
@main.command()
def leagues():
"""Returns all leagues for my team entry"""
leagues = fplapi.leagues_entered(get_team_id())
out(pretty_leagues(leagues))
@main.command()
@click.argument("league_id")
def league(league_id):
"""Returns confirmed scores for a league by id"""
league = fplapi.league(league_id)
out(pretty_league(league))
@main.command()
@click.argument("league_id")
def liveleague(league_id):
"""Returns live scores for a league by id"""
league = fplapi.live_league(league_id)
out(pretty_liveleague(league))
@main.command()
def entry():
"""
Returns information about your team entry,
using the team_id as configured in 'fpl configure'
"""
my_entry = fplapi.entry(get_team_id())
out(pretty_entry(my_entry))
@main.command()
def points():
"""Returns live points for your team"""
picks = fplapi.live_points(get_team_id())
out(pretty_picks_info(picks))
out(pretty_picks_players(picks))
@main.command()
def configure():
"""
Set up team_id (required)
"""
conf.configure()
out("fpl-cli configured. Type 'fpl' for instructions")
if __name__ == '__main__':
main() | fplcli/cli.py | import sys
import click
from . import fplapi
from . import configure as conf
from .cliprinter import out
from .cliprinter import pretty_league
from .cliprinter import pretty_liveleague
from .cliprinter import pretty_leagues
from .cliprinter import pretty_picks_info
from .cliprinter import pretty_picks_players
from .cliprinter import pretty_players
from .cliprinter import pretty_entry
def get_team_id():
try:
config = conf.get_config()
return config["DEFAULT"]["team_id"]
except KeyError:
sys.exit("FPL CLI is not configured. Type: fpl configure")
@click.group()
def main():
"""
FPL CLI - Command Line Interface for Fantasy Premier League.
"""
out("FPL CLI", color="cyan", figlet=True)
out("FPL CLI - Fantasy Premier League in your terminal \n", color="red")
@main.command()
def players():
"""Returns all players"""
players = fplapi.players()
out(pretty_players(players))
@main.command()
def leagues():
"""Returns all leagues for my team entry"""
leagues = fplapi.leagues_entered(get_team_id())
out(pretty_leagues(leagues))
@main.command()
@click.argument("league_id")
def league(league_id):
"""Returns confirmed scores for a league by id"""
league = fplapi.league(league_id)
out(pretty_league(league))
@main.command()
@click.argument("league_id")
def liveleague(league_id):
"""Returns live scores for a league by id"""
league = fplapi.live_league(league_id)
out(pretty_liveleague(league))
@main.command()
def entry():
"""
Returns information about your team entry,
using the team_id as configured in 'fpl configure'
"""
my_entry = fplapi.entry(get_team_id())
out(pretty_entry(my_entry))
@main.command()
def points():
"""Returns live points for your team"""
picks = fplapi.live_points(get_team_id())
out(pretty_picks_info(picks))
out(pretty_picks_players(picks))
@main.command()
def configure():
"""
Set up team_id (required)
"""
conf.configure()
out("fpl-cli configured. Type 'fpl' for instructions")
if __name__ == '__main__':
main() | 0.367384 | 0.071949 |
import json
import pytest
from rest_framework import status
from django.conf import settings
from usaspending_api.common.experimental_api_flags import ELASTICSEARCH_HEADER_VALUE, EXPERIMENTAL_API_HEADER
@pytest.mark.django_db
def test_elasticsearch_headers(client, monkeypatch, elasticsearch_transaction_index):
elasticsearch_http_header_helper(client, monkeypatch, elasticsearch_transaction_index, "awarding_agency")
elasticsearch_http_header_helper(client, monkeypatch, elasticsearch_transaction_index, "awarding_subagency")
elasticsearch_http_header_helper(client, monkeypatch, elasticsearch_transaction_index, "funding_agency")
elasticsearch_http_header_helper(client, monkeypatch, elasticsearch_transaction_index, "funding_subagency")
def elasticsearch_http_header_helper(client, monkeypatch, elasticsearch_transaction_index, endpoint_name):
logging_statements = []
monkeypatch.setattr(
"usaspending_api.search.v2.views.spending_by_category_views.base_spending_by_category.logger.info",
lambda message: logging_statements.append(message),
)
monkeypatch.setattr(
"usaspending_api.common.elasticsearch.search_wrappers.TransactionSearch._index_name",
settings.ES_TRANSACTIONS_QUERY_ALIAS_PREFIX,
)
elasticsearch_transaction_index.update_index()
# Logging statement is triggered for Prime Awards when Header is present
resp = client.post(
f"/api/v2/search/spending_by_category/{endpoint_name}",
content_type="application/json",
data=json.dumps({"filters": {"keywords": ["test", "testing"]}}),
**{EXPERIMENTAL_API_HEADER: ELASTICSEARCH_HEADER_VALUE},
)
assert resp.status_code == status.HTTP_200_OK
assert len(logging_statements) == 1, "Expected one logging statement"
assert (
logging_statements[0]
== f"Using experimental Elasticsearch functionality for 'spending_by_category/{endpoint_name}'"
), "Expected a different logging statement"
# Logging statement is NOT triggered for Prime Awards when Header is NOT present
logging_statements.clear()
resp = client.post(
f"/api/v2/search/spending_by_category/{endpoint_name}",
content_type="application/json",
data=json.dumps({"filters": {"keywords": ["test", "testing"]}}),
)
assert resp.status_code == status.HTTP_200_OK
assert len(logging_statements) == 0, "Expected zero logging statements for Prime Awards without the Header"
# Logging statement is NOT triggered for Sub Awards when Header is present
logging_statements.clear()
resp = client.post(
f"/api/v2/search/spending_by_category/{endpoint_name}",
content_type="application/json",
data=json.dumps({"subawards": True, "filters": {"keywords": ["test", "testing"]}}),
**{EXPERIMENTAL_API_HEADER: ELASTICSEARCH_HEADER_VALUE},
)
assert resp.status_code == status.HTTP_200_OK
assert len(logging_statements) == 0, "Expected zero logging statements for Sub Awards with the Header"
# Logging statement is NOT triggered for Sub Awards when Header is NOT present
logging_statements.clear()
resp = client.post(
f"/api/v2/search/spending_by_category/{endpoint_name}",
content_type="application/json",
data=json.dumps({"subawards": True, "filters": {"keywords": ["test", "testing"]}}),
)
assert resp.status_code == status.HTTP_200_OK
assert len(logging_statements) == 0, "Expected zero logging statements for Sub Awards without the Header" | usaspending_api/search/tests/integration/spending_by_category/test_elasticsearch_header.py | import json
import pytest
from rest_framework import status
from django.conf import settings
from usaspending_api.common.experimental_api_flags import ELASTICSEARCH_HEADER_VALUE, EXPERIMENTAL_API_HEADER
@pytest.mark.django_db
def test_elasticsearch_headers(client, monkeypatch, elasticsearch_transaction_index):
elasticsearch_http_header_helper(client, monkeypatch, elasticsearch_transaction_index, "awarding_agency")
elasticsearch_http_header_helper(client, monkeypatch, elasticsearch_transaction_index, "awarding_subagency")
elasticsearch_http_header_helper(client, monkeypatch, elasticsearch_transaction_index, "funding_agency")
elasticsearch_http_header_helper(client, monkeypatch, elasticsearch_transaction_index, "funding_subagency")
def elasticsearch_http_header_helper(client, monkeypatch, elasticsearch_transaction_index, endpoint_name):
logging_statements = []
monkeypatch.setattr(
"usaspending_api.search.v2.views.spending_by_category_views.base_spending_by_category.logger.info",
lambda message: logging_statements.append(message),
)
monkeypatch.setattr(
"usaspending_api.common.elasticsearch.search_wrappers.TransactionSearch._index_name",
settings.ES_TRANSACTIONS_QUERY_ALIAS_PREFIX,
)
elasticsearch_transaction_index.update_index()
# Logging statement is triggered for Prime Awards when Header is present
resp = client.post(
f"/api/v2/search/spending_by_category/{endpoint_name}",
content_type="application/json",
data=json.dumps({"filters": {"keywords": ["test", "testing"]}}),
**{EXPERIMENTAL_API_HEADER: ELASTICSEARCH_HEADER_VALUE},
)
assert resp.status_code == status.HTTP_200_OK
assert len(logging_statements) == 1, "Expected one logging statement"
assert (
logging_statements[0]
== f"Using experimental Elasticsearch functionality for 'spending_by_category/{endpoint_name}'"
), "Expected a different logging statement"
# Logging statement is NOT triggered for Prime Awards when Header is NOT present
logging_statements.clear()
resp = client.post(
f"/api/v2/search/spending_by_category/{endpoint_name}",
content_type="application/json",
data=json.dumps({"filters": {"keywords": ["test", "testing"]}}),
)
assert resp.status_code == status.HTTP_200_OK
assert len(logging_statements) == 0, "Expected zero logging statements for Prime Awards without the Header"
# Logging statement is NOT triggered for Sub Awards when Header is present
logging_statements.clear()
resp = client.post(
f"/api/v2/search/spending_by_category/{endpoint_name}",
content_type="application/json",
data=json.dumps({"subawards": True, "filters": {"keywords": ["test", "testing"]}}),
**{EXPERIMENTAL_API_HEADER: ELASTICSEARCH_HEADER_VALUE},
)
assert resp.status_code == status.HTTP_200_OK
assert len(logging_statements) == 0, "Expected zero logging statements for Sub Awards with the Header"
# Logging statement is NOT triggered for Sub Awards when Header is NOT present
logging_statements.clear()
resp = client.post(
f"/api/v2/search/spending_by_category/{endpoint_name}",
content_type="application/json",
data=json.dumps({"subawards": True, "filters": {"keywords": ["test", "testing"]}}),
)
assert resp.status_code == status.HTTP_200_OK
assert len(logging_statements) == 0, "Expected zero logging statements for Sub Awards without the Header" | 0.461259 | 0.204521 |
import functools
import os
import time
from absl import logging
from clu import metric_writers
import flax
import jax
import jax.numpy as jnp
import ml_collections
import numpy as np
import tensorflow as tf
from vit_jax import checkpoint
from vit_jax import input_pipeline
from vit_jax import models
from vit_jax import momentum_clip
from vit_jax import utils
def make_update_fn(*, apply_fn, accum_steps, lr_fn):
"""Returns update step for data parallel training."""
def update_fn(opt, step, batch, rng):
_, new_rng = jax.random.split(rng)
# Bind the rng key to the device id (which is unique across hosts)
# Note: This is only used for multi-host training (i.e. multiple computers
# each with multiple accelerators).
dropout_rng = jax.random.fold_in(rng, jax.lax.axis_index('batch'))
def cross_entropy_loss(*, logits, labels):
logp = jax.nn.log_softmax(logits)
return -jnp.mean(jnp.sum(logp * labels, axis=1))
def loss_fn(params, images, labels):
logits = apply_fn(
dict(params=params),
rngs=dict(dropout=dropout_rng),
inputs=images,
train=True)
return cross_entropy_loss(logits=logits, labels=labels)
l, g = utils.accumulate_gradient(
jax.value_and_grad(loss_fn), opt.target, batch['image'], batch['label'],
accum_steps)
g = jax.tree_map(lambda x: jax.lax.pmean(x, axis_name='batch'), g)
l = jax.lax.pmean(l, axis_name='batch')
opt = opt.apply_gradient(g, learning_rate=lr_fn(step))
return opt, l, new_rng
return jax.pmap(update_fn, axis_name='batch', donate_argnums=(0,))
def train_and_evaluate(config: ml_collections.ConfigDict, workdir: str):
"""Runs training interleaved with evaluation."""
# Setup input pipeline
dataset_info = input_pipeline.get_dataset_info(config.dataset, 'train')
ds_train = input_pipeline.get_data(
dataset=config.dataset,
mode='train',
repeats=None,
mixup_alpha=config.mixup_alpha,
batch_size=config.batch,
pp_config=config.pp,
shuffle_buffer=config.shuffle_buffer,
tfds_data_dir=config.tfds_data_dir,
tfds_manual_dir=config.tfds_manual_dir)
batch = next(iter(ds_train))
logging.info(ds_train)
ds_test = input_pipeline.get_data(
dataset=config.dataset,
mode='test',
repeats=1,
batch_size=config.batch_eval,
pp_config=config.pp,
tfds_data_dir=config.tfds_data_dir,
tfds_manual_dir=config.tfds_manual_dir)
logging.info(ds_test)
# Build VisionTransformer architecture
model_cls = {'ViT': models.VisionTransformer,
'Mixer': models.MlpMixer}[config.get('model_type', 'ViT')]
model = model_cls(num_classes=dataset_info['num_classes'], **config.model)
def init_model():
return model.init(
jax.random.PRNGKey(0),
# Discard the "num_local_devices" dimension for initialization.
jnp.ones(batch['image'].shape[1:], batch['image'].dtype.name),
train=False)
# Use JIT to make sure params reside in CPU memory.
variables = jax.jit(init_model, backend='cpu')()
pretrained_path = os.path.join(config.pretrained_dir,
f'{config.model.name}.npz')
if not tf.io.gfile.exists(pretrained_path):
raise ValueError(
f'Could not find "{pretrained_path}" - you can download models from '
'"gs://vit_models/imagenet21k" or directly set '
'--config.pretrained_dir="gs://vit_models/imagenet21k".')
params = checkpoint.load_pretrained(
pretrained_path=pretrained_path,
init_params=variables['params'],
model_config=config.model)
total_steps = config.total_steps
lr_fn = utils.create_learning_rate_schedule(total_steps, config.base_lr,
config.decay_type,
config.warmup_steps)
update_fn_repl = make_update_fn(
apply_fn=model.apply, accum_steps=config.accum_steps, lr_fn=lr_fn)
infer_fn_repl = jax.pmap(functools.partial(model.apply, train=False))
# Create optimizer and replicate it over all TPUs/GPUs
opt = momentum_clip.Optimizer(
dtype=config.optim_dtype,
grad_norm_clip=config.grad_norm_clip).create(params)
opt_repl = flax.jax_utils.replicate(opt)
# Delete references to the objects that are not needed anymore
del opt
del params
# Prepare the learning-rate and pre-fetch it to device to avoid delays.
update_rng_repl = flax.jax_utils.replicate(jax.random.PRNGKey(0))
# Run training loop
writer = metric_writers.create_default_writer(workdir, asynchronous=False)
writer.write_hparams(config.to_dict())
logging.info('Starting training loop; initial compile can take a while...')
t0 = lt0 = time.time()
for step, batch in zip(
range(1, total_steps + 1),
input_pipeline.prefetch(ds_train, config.prefetch)):
opt_repl, loss_repl, update_rng_repl = update_fn_repl(
opt_repl, flax.jax_utils.replicate(step), batch, update_rng_repl)
if step == 1:
logging.info('First step took %.1f seconds.', time.time() - t0)
t0 = time.time()
lt0, lstep = time.time(), step
# Report training metrics
if config.progress_every and step % config.progress_every == 0:
img_sec_core_train = (config.batch * (step - lstep) /
(time.time() - lt0)) / jax.device_count()
lt0, lstep = time.time(), step
writer.write_scalars(
step,
dict(
train_loss=float(flax.jax_utils.unreplicate(loss_repl)),
img_sec_core_train=img_sec_core_train))
done = step / total_steps
logging.info(f'Step: {step}/{total_steps} {100*done:.1f}%, ' # pylint: disable=logging-format-interpolation
f'img/sec/core: {img_sec_core_train:.1f}, '
f'ETA: {(time.time()-t0)/done*(1-done)/3600:.2f}h')
# Run evaluation
if ((config.eval_every and step % config.eval_every == 0) or
(step == total_steps)):
accuracies = []
lt0 = time.time()
for test_batch in input_pipeline.prefetch(ds_test, config.prefetch):
logits = infer_fn_repl(
dict(params=opt_repl.target), test_batch['image'])
accuracies.append(
(np.argmax(logits,
axis=-1) == np.argmax(test_batch['label'],
axis=-1)).mean())
accuracy_test = np.mean(accuracies)
img_sec_core_test = (
config.batch_eval * ds_test.cardinality().numpy() /
(time.time() - lt0) / jax.device_count())
lt0 = time.time()
lr = float(lr_fn(step))
logging.info(f'Step: {step} ' # pylint: disable=logging-format-interpolation
f'Learning rate: {lr:.7f}, '
f'Test accuracy: {accuracy_test:0.5f}, '
f'img/sec/core: {img_sec_core_test:.1f}')
writer.write_scalars(
step,
dict(
accuracy_test=accuracy_test,
lr=lr,
img_sec_core_test=img_sec_core_test))
opt = flax.jax_utils.unreplicate(opt_repl)
del opt_repl
checkpoint.save(opt.target, f'{workdir}/model.npz')
logging.info('Stored fine tuned checkpoint to %s', workdir)
return opt | vit_jax/train.py |
import functools
import os
import time
from absl import logging
from clu import metric_writers
import flax
import jax
import jax.numpy as jnp
import ml_collections
import numpy as np
import tensorflow as tf
from vit_jax import checkpoint
from vit_jax import input_pipeline
from vit_jax import models
from vit_jax import momentum_clip
from vit_jax import utils
def make_update_fn(*, apply_fn, accum_steps, lr_fn):
"""Returns update step for data parallel training."""
def update_fn(opt, step, batch, rng):
_, new_rng = jax.random.split(rng)
# Bind the rng key to the device id (which is unique across hosts)
# Note: This is only used for multi-host training (i.e. multiple computers
# each with multiple accelerators).
dropout_rng = jax.random.fold_in(rng, jax.lax.axis_index('batch'))
def cross_entropy_loss(*, logits, labels):
logp = jax.nn.log_softmax(logits)
return -jnp.mean(jnp.sum(logp * labels, axis=1))
def loss_fn(params, images, labels):
logits = apply_fn(
dict(params=params),
rngs=dict(dropout=dropout_rng),
inputs=images,
train=True)
return cross_entropy_loss(logits=logits, labels=labels)
l, g = utils.accumulate_gradient(
jax.value_and_grad(loss_fn), opt.target, batch['image'], batch['label'],
accum_steps)
g = jax.tree_map(lambda x: jax.lax.pmean(x, axis_name='batch'), g)
l = jax.lax.pmean(l, axis_name='batch')
opt = opt.apply_gradient(g, learning_rate=lr_fn(step))
return opt, l, new_rng
return jax.pmap(update_fn, axis_name='batch', donate_argnums=(0,))
def train_and_evaluate(config: ml_collections.ConfigDict, workdir: str):
"""Runs training interleaved with evaluation."""
# Setup input pipeline
dataset_info = input_pipeline.get_dataset_info(config.dataset, 'train')
ds_train = input_pipeline.get_data(
dataset=config.dataset,
mode='train',
repeats=None,
mixup_alpha=config.mixup_alpha,
batch_size=config.batch,
pp_config=config.pp,
shuffle_buffer=config.shuffle_buffer,
tfds_data_dir=config.tfds_data_dir,
tfds_manual_dir=config.tfds_manual_dir)
batch = next(iter(ds_train))
logging.info(ds_train)
ds_test = input_pipeline.get_data(
dataset=config.dataset,
mode='test',
repeats=1,
batch_size=config.batch_eval,
pp_config=config.pp,
tfds_data_dir=config.tfds_data_dir,
tfds_manual_dir=config.tfds_manual_dir)
logging.info(ds_test)
# Build VisionTransformer architecture
model_cls = {'ViT': models.VisionTransformer,
'Mixer': models.MlpMixer}[config.get('model_type', 'ViT')]
model = model_cls(num_classes=dataset_info['num_classes'], **config.model)
def init_model():
return model.init(
jax.random.PRNGKey(0),
# Discard the "num_local_devices" dimension for initialization.
jnp.ones(batch['image'].shape[1:], batch['image'].dtype.name),
train=False)
# Use JIT to make sure params reside in CPU memory.
variables = jax.jit(init_model, backend='cpu')()
pretrained_path = os.path.join(config.pretrained_dir,
f'{config.model.name}.npz')
if not tf.io.gfile.exists(pretrained_path):
raise ValueError(
f'Could not find "{pretrained_path}" - you can download models from '
'"gs://vit_models/imagenet21k" or directly set '
'--config.pretrained_dir="gs://vit_models/imagenet21k".')
params = checkpoint.load_pretrained(
pretrained_path=pretrained_path,
init_params=variables['params'],
model_config=config.model)
total_steps = config.total_steps
lr_fn = utils.create_learning_rate_schedule(total_steps, config.base_lr,
config.decay_type,
config.warmup_steps)
update_fn_repl = make_update_fn(
apply_fn=model.apply, accum_steps=config.accum_steps, lr_fn=lr_fn)
infer_fn_repl = jax.pmap(functools.partial(model.apply, train=False))
# Create optimizer and replicate it over all TPUs/GPUs
opt = momentum_clip.Optimizer(
dtype=config.optim_dtype,
grad_norm_clip=config.grad_norm_clip).create(params)
opt_repl = flax.jax_utils.replicate(opt)
# Delete references to the objects that are not needed anymore
del opt
del params
# Prepare the learning-rate and pre-fetch it to device to avoid delays.
update_rng_repl = flax.jax_utils.replicate(jax.random.PRNGKey(0))
# Run training loop
writer = metric_writers.create_default_writer(workdir, asynchronous=False)
writer.write_hparams(config.to_dict())
logging.info('Starting training loop; initial compile can take a while...')
t0 = lt0 = time.time()
for step, batch in zip(
range(1, total_steps + 1),
input_pipeline.prefetch(ds_train, config.prefetch)):
opt_repl, loss_repl, update_rng_repl = update_fn_repl(
opt_repl, flax.jax_utils.replicate(step), batch, update_rng_repl)
if step == 1:
logging.info('First step took %.1f seconds.', time.time() - t0)
t0 = time.time()
lt0, lstep = time.time(), step
# Report training metrics
if config.progress_every and step % config.progress_every == 0:
img_sec_core_train = (config.batch * (step - lstep) /
(time.time() - lt0)) / jax.device_count()
lt0, lstep = time.time(), step
writer.write_scalars(
step,
dict(
train_loss=float(flax.jax_utils.unreplicate(loss_repl)),
img_sec_core_train=img_sec_core_train))
done = step / total_steps
logging.info(f'Step: {step}/{total_steps} {100*done:.1f}%, ' # pylint: disable=logging-format-interpolation
f'img/sec/core: {img_sec_core_train:.1f}, '
f'ETA: {(time.time()-t0)/done*(1-done)/3600:.2f}h')
# Run evaluation
if ((config.eval_every and step % config.eval_every == 0) or
(step == total_steps)):
accuracies = []
lt0 = time.time()
for test_batch in input_pipeline.prefetch(ds_test, config.prefetch):
logits = infer_fn_repl(
dict(params=opt_repl.target), test_batch['image'])
accuracies.append(
(np.argmax(logits,
axis=-1) == np.argmax(test_batch['label'],
axis=-1)).mean())
accuracy_test = np.mean(accuracies)
img_sec_core_test = (
config.batch_eval * ds_test.cardinality().numpy() /
(time.time() - lt0) / jax.device_count())
lt0 = time.time()
lr = float(lr_fn(step))
logging.info(f'Step: {step} ' # pylint: disable=logging-format-interpolation
f'Learning rate: {lr:.7f}, '
f'Test accuracy: {accuracy_test:0.5f}, '
f'img/sec/core: {img_sec_core_test:.1f}')
writer.write_scalars(
step,
dict(
accuracy_test=accuracy_test,
lr=lr,
img_sec_core_test=img_sec_core_test))
opt = flax.jax_utils.unreplicate(opt_repl)
del opt_repl
checkpoint.save(opt.target, f'{workdir}/model.npz')
logging.info('Stored fine tuned checkpoint to %s', workdir)
return opt | 0.747432 | 0.259334 |
import pygame
from settings import *
import random
class Cell:
def __init__(self, game, x, y, bombs):
self.game = game
self.x = x
self.y = y
self.i = x // TILESIZE
self.j = y // TILESIZE
self.revelada = False
self.bomba = False
self.bombas_total = bombs
self.bombs_around = 0
self.flag_enabled = False
def reveal(self):
if not self.game.is_game_over:
self.revelada = True
if self.bombs_around == 0:
self.flood()
if self.bomba:
self.game.is_game_over = True
self.game.score = 0
EFFECT.play()
def check_neighbours(self, grid):
"""
This function will count how many bombs there is around a particular cell
"""
if self.bomba:
self.bombs_around = -1
return
total = 0
for x in range(-1, 2):
for y in range(-1, 2):
i = self.i + x
j = self.j + y
if i > -1 and i < len(grid) and j > -1 and j < len(grid[1]):
neighbor = grid[i][j]
if neighbor.bomba:
total += 1
self.bombs_around = total
def flood(self):
for x in range(-1, 2):
for y in range(-1, 2):
i = self.i + x
j = self.j + y
if i > -1 and i < len(self.game.grid) and j > -1 and j < len(self.game.grid[1]):
neighbor = self.game.grid[i][j]
if not neighbor.revelada and not neighbor.flag_enabled and not self.game.is_game_over:
neighbor.reveal()
def enable_flag(self):
self.flag_enabled = not self.flag_enabled
if self.bomba: # TODO: and self.flag_enabled
self.game.score += 1
# TODO: else: self.game.score -= 1
# all the spots revealed shouldn't be a bomb
def draw_number(self):
"""
This function will draw the numbers according to the total of bombs around the cell.
Also it will give colors to some numbers
"""
text_color = (0, 0, 0)
if self.bombs_around == 1:
text_color = (0, 0, 150)
if self.bombs_around == 2:
text_color = (0, 150, 0)
if self.bombs_around == 3:
text_color = (150, 0, 0)
if self.bombs_around == 4:
text_color = (133, 39, 138)
if self.bombs_around == 5:
text_color = (128, 0, 0)
if self.bombs_around == 6:
text_color = (175, 238, 238)
if self.bombs_around == 7:
text_color = (0, 0, 0)
if self.bombs_around == 8:
text_color = (33, 161, 166)
font = pygame.font.Font("fonts/JetBrainsMono-Bold.ttf", 24)
if self.bombs_around > 0 and self.revelada:
text = font.render(
str(self.bombs_around), False, text_color)
self.game.screen.blit(text, (self.x + 12, self.y))
def set_bomb(self):
"""
This function will turn this cell into a cell with a bomb
(just to keep organized)
"""
self.bomba = True
def draw_cell(self):
pygame.draw.rect(
self.game.screen, WHITE, (self.x, self.y, TILESIZE - 1, TILESIZE - 1))
if self.revelada:
if self.bomba:
pygame.draw.rect(
self.game.screen, RED, (self.x + 10, self.y + 10, TILESIZE - 23, TILESIZE - 23))
else:
pygame.draw.rect(
self.game.screen, GRAY, (self.x, self.y, TILESIZE - 1, TILESIZE - 1))
if self.flag_enabled and not self.revelada:
self.game.flag.draw(self.game.screen, self.x + 10, self.y + 10)
def get_mouse_pos(self):
mouse = pygame.mouse.get_pos()
return [mouse[0] // TILESIZE, mouse[1] // TILESIZE] | src/cell.py | import pygame
from settings import *
import random
class Cell:
def __init__(self, game, x, y, bombs):
self.game = game
self.x = x
self.y = y
self.i = x // TILESIZE
self.j = y // TILESIZE
self.revelada = False
self.bomba = False
self.bombas_total = bombs
self.bombs_around = 0
self.flag_enabled = False
def reveal(self):
if not self.game.is_game_over:
self.revelada = True
if self.bombs_around == 0:
self.flood()
if self.bomba:
self.game.is_game_over = True
self.game.score = 0
EFFECT.play()
def check_neighbours(self, grid):
"""
This function will count how many bombs there is around a particular cell
"""
if self.bomba:
self.bombs_around = -1
return
total = 0
for x in range(-1, 2):
for y in range(-1, 2):
i = self.i + x
j = self.j + y
if i > -1 and i < len(grid) and j > -1 and j < len(grid[1]):
neighbor = grid[i][j]
if neighbor.bomba:
total += 1
self.bombs_around = total
def flood(self):
for x in range(-1, 2):
for y in range(-1, 2):
i = self.i + x
j = self.j + y
if i > -1 and i < len(self.game.grid) and j > -1 and j < len(self.game.grid[1]):
neighbor = self.game.grid[i][j]
if not neighbor.revelada and not neighbor.flag_enabled and not self.game.is_game_over:
neighbor.reveal()
def enable_flag(self):
self.flag_enabled = not self.flag_enabled
if self.bomba: # TODO: and self.flag_enabled
self.game.score += 1
# TODO: else: self.game.score -= 1
# all the spots revealed shouldn't be a bomb
def draw_number(self):
"""
This function will draw the numbers according to the total of bombs around the cell.
Also it will give colors to some numbers
"""
text_color = (0, 0, 0)
if self.bombs_around == 1:
text_color = (0, 0, 150)
if self.bombs_around == 2:
text_color = (0, 150, 0)
if self.bombs_around == 3:
text_color = (150, 0, 0)
if self.bombs_around == 4:
text_color = (133, 39, 138)
if self.bombs_around == 5:
text_color = (128, 0, 0)
if self.bombs_around == 6:
text_color = (175, 238, 238)
if self.bombs_around == 7:
text_color = (0, 0, 0)
if self.bombs_around == 8:
text_color = (33, 161, 166)
font = pygame.font.Font("fonts/JetBrainsMono-Bold.ttf", 24)
if self.bombs_around > 0 and self.revelada:
text = font.render(
str(self.bombs_around), False, text_color)
self.game.screen.blit(text, (self.x + 12, self.y))
def set_bomb(self):
"""
This function will turn this cell into a cell with a bomb
(just to keep organized)
"""
self.bomba = True
def draw_cell(self):
pygame.draw.rect(
self.game.screen, WHITE, (self.x, self.y, TILESIZE - 1, TILESIZE - 1))
if self.revelada:
if self.bomba:
pygame.draw.rect(
self.game.screen, RED, (self.x + 10, self.y + 10, TILESIZE - 23, TILESIZE - 23))
else:
pygame.draw.rect(
self.game.screen, GRAY, (self.x, self.y, TILESIZE - 1, TILESIZE - 1))
if self.flag_enabled and not self.revelada:
self.game.flag.draw(self.game.screen, self.x + 10, self.y + 10)
def get_mouse_pos(self):
mouse = pygame.mouse.get_pos()
return [mouse[0] // TILESIZE, mouse[1] // TILESIZE] | 0.191101 | 0.337722 |
from torch import nn
from ..layers import TFEncoder, TFDecoder
from ..utils.nn import LabelSmoothingLoss
from . import SimultaneousNMT
class SimultaneousTFNMT(SimultaneousNMT):
def __init__(self, opts):
"""
Creates a SimultaneousNMTTransformer.
:param opts: The options.
"""
self.defaults = None
super().__init__(opts)
# These will be initialized in the setup method, similarly to other models.
self.encoders = {}
self.dec = None
self.loss = None
self.current_batch = None
def setup(self, is_train=True):
"""
Initialises the necessary model components.
:param is_train: Whether the model is in training mode or not.
"""
encoders = {}
for key in self.topology.srcs.keys():
encoders[key] = getattr(self, f'_create_{key}_encoder')()
self.encoders = nn.ModuleDict(encoders)
self.dec = self._create_decoder()
self.loss = LabelSmoothingLoss(
trg_vocab_size=self.n_trg_vocab, reduction='sum', ignore_index=0,
with_logits=False)
# Share encoder and decoder weights
if self.opts.model['tied_emb'] == '3way':
assert self.n_src_vocab == self.n_trg_vocab, \
"The vocabulary sizes do not match for 3way tied embeddings."
self.encoders[str(self.sl)].src_embedding.weight = self.dec.trg_embedding.weight
def reset_parameters(self):
"""
Initialize the model parameters.
"""
for param in self.parameters():
if param.requires_grad and param.dim() > 1:
nn.init.xavier_uniform_(param)
def set_defaults(self):
self.defaults = {
'model_dim': 512, # Source and target embedding sizes,
'num_heads': 8, # The number of attention heads
'direction': None, # Network directionality, i.e. en->de
'max_len': 80, # Reject sentences where 'bucket_by' length > 80
'bucket_by': None, # A key like 'en' to define w.r.t which dataset
# the batches will be sorted
'bucket_order': None, # Curriculum: ascending/descending/None
'sampler_type': 'bucket', # bucket or approximate
'short_list': 0, # Short list vocabularies (0: disabled)
'enc_n_layers': 6, # The number of encoder layers
'dec_n_layers': 6, # The number of decoder layers
'enc_ff_dim': 2048, # The number of encoder feed forward dimensions
'dec_ff_dim': 2048, # The number of decoder feed forward dimensions
'enc_bidirectional': False, # Whether the encoder is bidirectional or unidirectional.
'tied_emb': False, # Whether the embedding should be tied.
'ff_activ': 'gelu', # The feed forward layer activation function. Default 'gelu'.
'dropout': 0.1, # The dropout.
'attn_dropout': 0.0, # The attention dropout.
'pre_norm': True, # Indicates whether to use pre_norm (recent) or post_norm (original) layers.
# Visual features (optional)
'feat_mode': None,
'aux_dim': None, # Auxiliary features dim (# channels for conv features)
'aux_dropout': 0.0, # Auxiliary features dropout
'aux_lnorm': False, # layer-norm
'aux_l2norm': False, # L2-normalize
'aux_proj_dim': None, # Projection layer for features
'aux_proj_activ': None, # Projection layer non-linearity
'img_boxes_dim': None, # The vector dimension for the boxes, associated with a region.
'num_regions': 36, # The number of regions to use. Valid only for OD features. Default: 36.
'mm_fusion_op': None, # fusion type
'mm_fusion_dropout': 0.0, # fusion dropout
'tf_dec_img_attn': None, # The decoder visual attention; could be: 'serial', 'parallel' or None.
'tf_n_mm_hier_heads': 8, # Used with hierarchical image attention to specify the number of hierarchical heads. Default 8.
# Default: None.
# Decoding/training simultaneous NMT args
'translator_type': 'gs', # This model implements plain unidirectional MT
# so the decoding is normal greedy-search
'translator_args': {}, # No extra arguments to translator
}
def _create_src_encoder(self):
"""
Returns a transformer encoder.
:return: a transformer encoder.
"""
return TFEncoder(
model_dim=self.opts.model["model_dim"],
n_heads=self.opts.model["num_heads"],
ff_dim=self.opts.model["enc_ff_dim"],
n_layers=self.opts.model["enc_n_layers"],
num_embeddings=self.n_src_vocab,
ff_activ=self.opts.model["ff_activ"],
dropout=self.opts.model["dropout"],
attn_dropout=self.opts.model["attn_dropout"],
pre_norm=self.opts.model["pre_norm"],
enc_bidirectional=self.opts.model["enc_bidirectional"]
)
def _create_decoder(self):
"""
Returns a transformer decoder.
:return: a transformer decoder.
"""
return TFDecoder(
model_dim=self.opts.model["model_dim"],
n_heads=self.opts.model["num_heads"],
ff_dim=self.opts.model["dec_ff_dim"],
n_layers=self.opts.model["dec_n_layers"],
num_embeddings=self.n_trg_vocab,
tied_emb=self.opts.model["tied_emb"],
ff_activ=self.opts.model["ff_activ"],
dropout=self.opts.model["dropout"],
attn_dropout=self.opts.model["attn_dropout"],
pre_norm=self.opts.model["pre_norm"],
img_attn=self.opts.model["tf_dec_img_attn"],
n_mm_hier_heads=self.opts.model["tf_n_mm_hier_heads"],
)
def get_attention_weights(self):
return {
'encoder_src': self.encoders['src'].get_attention_weights(),
'decoder': self.dec.get_attention_weights()
}
def cache_enc_states(self, batch, **kwargs):
if self.opts.model["enc_bidirectional"]:
# It is tricky to cache the encoder's states if it's bidirectional,
# as they are dependent on future positions due to the
# self-attention module. Therefore, we are just going to cache the data
# and perform the forward pass in get_enc_state_dict.
self.current_batch = batch
else:
for key, enc in self.encoders.items():
_ = enc(batch[key])
def get_enc_state_dict(self, up_to=int(1e6)):
"""Encodes the batch optionally by partial encoding up to `up_to`
words for derived simultaneous NMT classes. By default, the value
is large enough to leave it as vanilla NMT. """
if self.opts.model["enc_bidirectional"]:
# In the bidirectional case, perform a forward pass through the encoder.
return {str(key): encoder(self.current_batch[key][:up_to, :]) for key, encoder in self.encoders.items()}
else:
return super().get_enc_state_dict(up_to=up_to)
def forward(self, batch, **kwargs):
self.cache_enc_states(batch)
encoded_src = self.get_enc_state_dict()
# The input to the transformer should include the <bos> token but not the <eos> token.
target_input = batch[self.tl][:-1, :]
# The actual values should not have the <bos> token but should include the <eos>
target_real = batch[self.tl][1:, :]
result, _ = self.dec(encoded_src, target_input, **kwargs)
total_loss = self.loss(
result.contiguous().view(-1, result.size(-1)), target_real.contiguous().view(-1))
return {
'loss': total_loss,
'n_items': target_real.nonzero(as_tuple=False).size(0),
} | pysimt/models/snmt_tf.py | from torch import nn
from ..layers import TFEncoder, TFDecoder
from ..utils.nn import LabelSmoothingLoss
from . import SimultaneousNMT
class SimultaneousTFNMT(SimultaneousNMT):
def __init__(self, opts):
"""
Creates a SimultaneousNMTTransformer.
:param opts: The options.
"""
self.defaults = None
super().__init__(opts)
# These will be initialized in the setup method, similarly to other models.
self.encoders = {}
self.dec = None
self.loss = None
self.current_batch = None
def setup(self, is_train=True):
"""
Initialises the necessary model components.
:param is_train: Whether the model is in training mode or not.
"""
encoders = {}
for key in self.topology.srcs.keys():
encoders[key] = getattr(self, f'_create_{key}_encoder')()
self.encoders = nn.ModuleDict(encoders)
self.dec = self._create_decoder()
self.loss = LabelSmoothingLoss(
trg_vocab_size=self.n_trg_vocab, reduction='sum', ignore_index=0,
with_logits=False)
# Share encoder and decoder weights
if self.opts.model['tied_emb'] == '3way':
assert self.n_src_vocab == self.n_trg_vocab, \
"The vocabulary sizes do not match for 3way tied embeddings."
self.encoders[str(self.sl)].src_embedding.weight = self.dec.trg_embedding.weight
def reset_parameters(self):
"""
Initialize the model parameters.
"""
for param in self.parameters():
if param.requires_grad and param.dim() > 1:
nn.init.xavier_uniform_(param)
def set_defaults(self):
self.defaults = {
'model_dim': 512, # Source and target embedding sizes,
'num_heads': 8, # The number of attention heads
'direction': None, # Network directionality, i.e. en->de
'max_len': 80, # Reject sentences where 'bucket_by' length > 80
'bucket_by': None, # A key like 'en' to define w.r.t which dataset
# the batches will be sorted
'bucket_order': None, # Curriculum: ascending/descending/None
'sampler_type': 'bucket', # bucket or approximate
'short_list': 0, # Short list vocabularies (0: disabled)
'enc_n_layers': 6, # The number of encoder layers
'dec_n_layers': 6, # The number of decoder layers
'enc_ff_dim': 2048, # The number of encoder feed forward dimensions
'dec_ff_dim': 2048, # The number of decoder feed forward dimensions
'enc_bidirectional': False, # Whether the encoder is bidirectional or unidirectional.
'tied_emb': False, # Whether the embedding should be tied.
'ff_activ': 'gelu', # The feed forward layer activation function. Default 'gelu'.
'dropout': 0.1, # The dropout.
'attn_dropout': 0.0, # The attention dropout.
'pre_norm': True, # Indicates whether to use pre_norm (recent) or post_norm (original) layers.
# Visual features (optional)
'feat_mode': None,
'aux_dim': None, # Auxiliary features dim (# channels for conv features)
'aux_dropout': 0.0, # Auxiliary features dropout
'aux_lnorm': False, # layer-norm
'aux_l2norm': False, # L2-normalize
'aux_proj_dim': None, # Projection layer for features
'aux_proj_activ': None, # Projection layer non-linearity
'img_boxes_dim': None, # The vector dimension for the boxes, associated with a region.
'num_regions': 36, # The number of regions to use. Valid only for OD features. Default: 36.
'mm_fusion_op': None, # fusion type
'mm_fusion_dropout': 0.0, # fusion dropout
'tf_dec_img_attn': None, # The decoder visual attention; could be: 'serial', 'parallel' or None.
'tf_n_mm_hier_heads': 8, # Used with hierarchical image attention to specify the number of hierarchical heads. Default 8.
# Default: None.
# Decoding/training simultaneous NMT args
'translator_type': 'gs', # This model implements plain unidirectional MT
# so the decoding is normal greedy-search
'translator_args': {}, # No extra arguments to translator
}
def _create_src_encoder(self):
"""
Returns a transformer encoder.
:return: a transformer encoder.
"""
return TFEncoder(
model_dim=self.opts.model["model_dim"],
n_heads=self.opts.model["num_heads"],
ff_dim=self.opts.model["enc_ff_dim"],
n_layers=self.opts.model["enc_n_layers"],
num_embeddings=self.n_src_vocab,
ff_activ=self.opts.model["ff_activ"],
dropout=self.opts.model["dropout"],
attn_dropout=self.opts.model["attn_dropout"],
pre_norm=self.opts.model["pre_norm"],
enc_bidirectional=self.opts.model["enc_bidirectional"]
)
def _create_decoder(self):
"""
Returns a transformer decoder.
:return: a transformer decoder.
"""
return TFDecoder(
model_dim=self.opts.model["model_dim"],
n_heads=self.opts.model["num_heads"],
ff_dim=self.opts.model["dec_ff_dim"],
n_layers=self.opts.model["dec_n_layers"],
num_embeddings=self.n_trg_vocab,
tied_emb=self.opts.model["tied_emb"],
ff_activ=self.opts.model["ff_activ"],
dropout=self.opts.model["dropout"],
attn_dropout=self.opts.model["attn_dropout"],
pre_norm=self.opts.model["pre_norm"],
img_attn=self.opts.model["tf_dec_img_attn"],
n_mm_hier_heads=self.opts.model["tf_n_mm_hier_heads"],
)
def get_attention_weights(self):
return {
'encoder_src': self.encoders['src'].get_attention_weights(),
'decoder': self.dec.get_attention_weights()
}
def cache_enc_states(self, batch, **kwargs):
if self.opts.model["enc_bidirectional"]:
# It is tricky to cache the encoder's states if it's bidirectional,
# as they are dependent on future positions due to the
# self-attention module. Therefore, we are just going to cache the data
# and perform the forward pass in get_enc_state_dict.
self.current_batch = batch
else:
for key, enc in self.encoders.items():
_ = enc(batch[key])
def get_enc_state_dict(self, up_to=int(1e6)):
"""Encodes the batch optionally by partial encoding up to `up_to`
words for derived simultaneous NMT classes. By default, the value
is large enough to leave it as vanilla NMT. """
if self.opts.model["enc_bidirectional"]:
# In the bidirectional case, perform a forward pass through the encoder.
return {str(key): encoder(self.current_batch[key][:up_to, :]) for key, encoder in self.encoders.items()}
else:
return super().get_enc_state_dict(up_to=up_to)
def forward(self, batch, **kwargs):
self.cache_enc_states(batch)
encoded_src = self.get_enc_state_dict()
# The input to the transformer should include the <bos> token but not the <eos> token.
target_input = batch[self.tl][:-1, :]
# The actual values should not have the <bos> token but should include the <eos>
target_real = batch[self.tl][1:, :]
result, _ = self.dec(encoded_src, target_input, **kwargs)
total_loss = self.loss(
result.contiguous().view(-1, result.size(-1)), target_real.contiguous().view(-1))
return {
'loss': total_loss,
'n_items': target_real.nonzero(as_tuple=False).size(0),
} | 0.951222 | 0.361165 |
from dataclasses import dataclass
from typing import List, Literal, Mapping, Set
from kgdata.wikidata.models.wdentity import WDEntity
import orjson
from kgdata.config import WIKIDATA_DIR
from kgdata.wikidata.models.multilingual import (
MultiLingualString,
MultiLingualStringList,
)
from sm.misc.deser import deserialize_jl, deserialize_json
@dataclass
class WDProperty:
__slots__ = (
"id",
"label",
"description",
"aliases",
"datatype",
"parents",
"related_properties",
"equivalent_properties",
"subjects",
"inverse_properties",
"instanceof",
"ancestors",
)
id: str
label: MultiLingualString
description: MultiLingualString
aliases: MultiLingualStringList
# wikibase-lexeme, monolingualtext, wikibase-sense, url, wikibase-property,
# wikibase-form, external-id, time, commonsMedia, quantity, wikibase-item, musical-notation,
# tabular-data, string, math, geo-shape, globe-coordinate
datatype: Literal[
"wikibase-lexeme",
"monolingualtext",
"wikibase-sense",
"url",
"wikibase-property",
"wikibase-form",
"external-id",
"time",
"commonsMedia",
"quantity",
"wikibase-item",
"musical-notation",
"tabular-data",
"string",
"math",
"geo-shape",
"globe-coordinate",
]
parents: List[str]
related_properties: List[str]
equivalent_properties: List[str]
subjects: List[str]
inverse_properties: List[str]
instanceof: List[str]
ancestors: Set[str]
@staticmethod
def from_dict(o):
o["label"] = MultiLingualString(**o["label"])
o["description"] = MultiLingualString(**o["description"])
o["aliases"] = MultiLingualStringList(**o["aliases"])
o["ancestors"] = set(o["ancestors"])
return WDProperty(**o)
@staticmethod
def from_entity(ent: WDEntity):
parents = []
for stmt in ent.props.get("P1647", []):
assert stmt.value.is_entity_id(stmt.value)
parents.append(stmt.value.as_entity_id())
related_properties = []
for stmt in ent.props.get("P1659", []):
assert stmt.value.is_entity_id(stmt.value)
related_properties.append(stmt.value.as_entity_id())
equivalent_properties = []
for stmt in ent.props.get("P1628", []):
if stmt.value.is_entity_id(stmt.value):
equivalent_properties.append(stmt.value.as_entity_id())
elif stmt.value.is_string(stmt.value):
# external url is represented as a string
equivalent_properties.append(stmt.value.as_string())
else:
assert False, f"Unknown type: {stmt.value.to_dict()}"
subjects = []
for stmt in ent.props.get("P1629", []):
assert stmt.value.is_entity_id(stmt.value)
subjects.append(stmt.value.as_entity_id())
inverse_properties = []
for stmt in ent.props.get("P1696", []):
assert stmt.value.is_entity_id(stmt.value)
inverse_properties.append(stmt.value.as_entity_id())
instanceof = []
for stmt in ent.props.get("P31", []):
assert stmt.value.is_entity_id(stmt.value)
instanceof.append(stmt.value.as_entity_id())
return WDProperty(
id=ent.id,
label=ent.label,
description=ent.description,
datatype=ent.datatype, # type: ignore
aliases=ent.aliases,
parents=sorted(parents),
related_properties=sorted(related_properties),
equivalent_properties=sorted(equivalent_properties),
subjects=sorted(subjects),
inverse_properties=sorted(inverse_properties),
instanceof=sorted(instanceof),
ancestors=set(),
)
def to_dict(self):
return {
"id": self.id,
"label": self.label.to_dict(),
"description": self.description.to_dict(),
"datatype": self.datatype,
"aliases": self.aliases.to_dict(),
"parents": self.parents,
"related_properties": self.related_properties,
"equivalent_properties": self.equivalent_properties,
"subjects": self.subjects,
"inverse_properties": self.inverse_properties,
"instanceof": self.instanceof,
"ancestors": list(self.ancestors),
}
def is_object_property(self):
return self.datatype == "wikibase-item"
def is_data_property(self):
return not self.is_object_property()
def is_transitive(self):
return "Q18647515" in self.instanceof
# domains of a property, mapping from the class id to the number of instances of the class having this property
WDPropertyDomains = Mapping[str, int]
# ranges of a property, mapping from the class id to the number of instances of the class having this incoming property
WDPropertyRanges = Mapping[str, int] | kgdata/wikidata/models/wdproperty.py | from dataclasses import dataclass
from typing import List, Literal, Mapping, Set
from kgdata.wikidata.models.wdentity import WDEntity
import orjson
from kgdata.config import WIKIDATA_DIR
from kgdata.wikidata.models.multilingual import (
MultiLingualString,
MultiLingualStringList,
)
from sm.misc.deser import deserialize_jl, deserialize_json
@dataclass
class WDProperty:
__slots__ = (
"id",
"label",
"description",
"aliases",
"datatype",
"parents",
"related_properties",
"equivalent_properties",
"subjects",
"inverse_properties",
"instanceof",
"ancestors",
)
id: str
label: MultiLingualString
description: MultiLingualString
aliases: MultiLingualStringList
# wikibase-lexeme, monolingualtext, wikibase-sense, url, wikibase-property,
# wikibase-form, external-id, time, commonsMedia, quantity, wikibase-item, musical-notation,
# tabular-data, string, math, geo-shape, globe-coordinate
datatype: Literal[
"wikibase-lexeme",
"monolingualtext",
"wikibase-sense",
"url",
"wikibase-property",
"wikibase-form",
"external-id",
"time",
"commonsMedia",
"quantity",
"wikibase-item",
"musical-notation",
"tabular-data",
"string",
"math",
"geo-shape",
"globe-coordinate",
]
parents: List[str]
related_properties: List[str]
equivalent_properties: List[str]
subjects: List[str]
inverse_properties: List[str]
instanceof: List[str]
ancestors: Set[str]
@staticmethod
def from_dict(o):
o["label"] = MultiLingualString(**o["label"])
o["description"] = MultiLingualString(**o["description"])
o["aliases"] = MultiLingualStringList(**o["aliases"])
o["ancestors"] = set(o["ancestors"])
return WDProperty(**o)
@staticmethod
def from_entity(ent: WDEntity):
parents = []
for stmt in ent.props.get("P1647", []):
assert stmt.value.is_entity_id(stmt.value)
parents.append(stmt.value.as_entity_id())
related_properties = []
for stmt in ent.props.get("P1659", []):
assert stmt.value.is_entity_id(stmt.value)
related_properties.append(stmt.value.as_entity_id())
equivalent_properties = []
for stmt in ent.props.get("P1628", []):
if stmt.value.is_entity_id(stmt.value):
equivalent_properties.append(stmt.value.as_entity_id())
elif stmt.value.is_string(stmt.value):
# external url is represented as a string
equivalent_properties.append(stmt.value.as_string())
else:
assert False, f"Unknown type: {stmt.value.to_dict()}"
subjects = []
for stmt in ent.props.get("P1629", []):
assert stmt.value.is_entity_id(stmt.value)
subjects.append(stmt.value.as_entity_id())
inverse_properties = []
for stmt in ent.props.get("P1696", []):
assert stmt.value.is_entity_id(stmt.value)
inverse_properties.append(stmt.value.as_entity_id())
instanceof = []
for stmt in ent.props.get("P31", []):
assert stmt.value.is_entity_id(stmt.value)
instanceof.append(stmt.value.as_entity_id())
return WDProperty(
id=ent.id,
label=ent.label,
description=ent.description,
datatype=ent.datatype, # type: ignore
aliases=ent.aliases,
parents=sorted(parents),
related_properties=sorted(related_properties),
equivalent_properties=sorted(equivalent_properties),
subjects=sorted(subjects),
inverse_properties=sorted(inverse_properties),
instanceof=sorted(instanceof),
ancestors=set(),
)
def to_dict(self):
return {
"id": self.id,
"label": self.label.to_dict(),
"description": self.description.to_dict(),
"datatype": self.datatype,
"aliases": self.aliases.to_dict(),
"parents": self.parents,
"related_properties": self.related_properties,
"equivalent_properties": self.equivalent_properties,
"subjects": self.subjects,
"inverse_properties": self.inverse_properties,
"instanceof": self.instanceof,
"ancestors": list(self.ancestors),
}
def is_object_property(self):
return self.datatype == "wikibase-item"
def is_data_property(self):
return not self.is_object_property()
def is_transitive(self):
return "Q18647515" in self.instanceof
# domains of a property, mapping from the class id to the number of instances of the class having this property
WDPropertyDomains = Mapping[str, int]
# ranges of a property, mapping from the class id to the number of instances of the class having this incoming property
WDPropertyRanges = Mapping[str, int] | 0.826782 | 0.290116 |
"""Client and server classes corresponding to protobuf-defined services."""
import grpc
from github.com.metaprov.modelaapi.services.labelingpipelinerun.v1 import labelingpipelinerun_pb2 as github_dot_com_dot_metaprov_dot_modelaapi_dot_services_dot_labelingpipelinerun_dot_v1_dot_labelingpipelinerun__pb2
class LabelingPipelineRunServiceStub(object):
"""Missing associated documentation comment in .proto file."""
def __init__(self, channel):
"""Constructor.
Args:
channel: A grpc.Channel.
"""
self.ListLabelingPipelineRuns = channel.unary_unary(
'/github.com.metaprov.modelaapi.services.labelingpipelinerun.v1.LabelingPipelineRunService/ListLabelingPipelineRuns',
request_serializer=github_dot_com_dot_metaprov_dot_modelaapi_dot_services_dot_labelingpipelinerun_dot_v1_dot_labelingpipelinerun__pb2.ListLabelingPipelineRunRequest.SerializeToString,
response_deserializer=github_dot_com_dot_metaprov_dot_modelaapi_dot_services_dot_labelingpipelinerun_dot_v1_dot_labelingpipelinerun__pb2.ListLabelingPipelineRunResponse.FromString,
)
self.CreateLabelingPipelineRun = channel.unary_unary(
'/github.com.metaprov.modelaapi.services.labelingpipelinerun.v1.LabelingPipelineRunService/CreateLabelingPipelineRun',
request_serializer=github_dot_com_dot_metaprov_dot_modelaapi_dot_services_dot_labelingpipelinerun_dot_v1_dot_labelingpipelinerun__pb2.CreateLabelingPipelineRunRequest.SerializeToString,
response_deserializer=github_dot_com_dot_metaprov_dot_modelaapi_dot_services_dot_labelingpipelinerun_dot_v1_dot_labelingpipelinerun__pb2.CreateLabelingPipelineRunResponse.FromString,
)
self.GetLabelingPipelineRun = channel.unary_unary(
'/github.com.metaprov.modelaapi.services.labelingpipelinerun.v1.LabelingPipelineRunService/GetLabelingPipelineRun',
request_serializer=github_dot_com_dot_metaprov_dot_modelaapi_dot_services_dot_labelingpipelinerun_dot_v1_dot_labelingpipelinerun__pb2.GetLabelingPipelineRunRequest.SerializeToString,
response_deserializer=github_dot_com_dot_metaprov_dot_modelaapi_dot_services_dot_labelingpipelinerun_dot_v1_dot_labelingpipelinerun__pb2.GetLabelingPipelineRunResponse.FromString,
)
self.UpdateLabelingPipelineRun = channel.unary_unary(
'/github.com.metaprov.modelaapi.services.labelingpipelinerun.v1.LabelingPipelineRunService/UpdateLabelingPipelineRun',
request_serializer=github_dot_com_dot_metaprov_dot_modelaapi_dot_services_dot_labelingpipelinerun_dot_v1_dot_labelingpipelinerun__pb2.UpdateLabelingPipelineRunRequest.SerializeToString,
response_deserializer=github_dot_com_dot_metaprov_dot_modelaapi_dot_services_dot_labelingpipelinerun_dot_v1_dot_labelingpipelinerun__pb2.UpdateLabelingPipelineRunResponse.FromString,
)
self.DeleteLabelingPipelineRun = channel.unary_unary(
'/github.com.metaprov.modelaapi.services.labelingpipelinerun.v1.LabelingPipelineRunService/DeleteLabelingPipelineRun',
request_serializer=github_dot_com_dot_metaprov_dot_modelaapi_dot_services_dot_labelingpipelinerun_dot_v1_dot_labelingpipelinerun__pb2.DeleteLabelingPipelineRunRequest.SerializeToString,
response_deserializer=github_dot_com_dot_metaprov_dot_modelaapi_dot_services_dot_labelingpipelinerun_dot_v1_dot_labelingpipelinerun__pb2.DeleteLabelingPipelineRunResponse.FromString,
)
class LabelingPipelineRunServiceServicer(object):
"""Missing associated documentation comment in .proto file."""
def ListLabelingPipelineRuns(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def CreateLabelingPipelineRun(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def GetLabelingPipelineRun(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def UpdateLabelingPipelineRun(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def DeleteLabelingPipelineRun(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def add_LabelingPipelineRunServiceServicer_to_server(servicer, server):
rpc_method_handlers = {
'ListLabelingPipelineRuns': grpc.unary_unary_rpc_method_handler(
servicer.ListLabelingPipelineRuns,
request_deserializer=github_dot_com_dot_metaprov_dot_modelaapi_dot_services_dot_labelingpipelinerun_dot_v1_dot_labelingpipelinerun__pb2.ListLabelingPipelineRunRequest.FromString,
response_serializer=github_dot_com_dot_metaprov_dot_modelaapi_dot_services_dot_labelingpipelinerun_dot_v1_dot_labelingpipelinerun__pb2.ListLabelingPipelineRunResponse.SerializeToString,
),
'CreateLabelingPipelineRun': grpc.unary_unary_rpc_method_handler(
servicer.CreateLabelingPipelineRun,
request_deserializer=github_dot_com_dot_metaprov_dot_modelaapi_dot_services_dot_labelingpipelinerun_dot_v1_dot_labelingpipelinerun__pb2.CreateLabelingPipelineRunRequest.FromString,
response_serializer=github_dot_com_dot_metaprov_dot_modelaapi_dot_services_dot_labelingpipelinerun_dot_v1_dot_labelingpipelinerun__pb2.CreateLabelingPipelineRunResponse.SerializeToString,
),
'GetLabelingPipelineRun': grpc.unary_unary_rpc_method_handler(
servicer.GetLabelingPipelineRun,
request_deserializer=github_dot_com_dot_metaprov_dot_modelaapi_dot_services_dot_labelingpipelinerun_dot_v1_dot_labelingpipelinerun__pb2.GetLabelingPipelineRunRequest.FromString,
response_serializer=github_dot_com_dot_metaprov_dot_modelaapi_dot_services_dot_labelingpipelinerun_dot_v1_dot_labelingpipelinerun__pb2.GetLabelingPipelineRunResponse.SerializeToString,
),
'UpdateLabelingPipelineRun': grpc.unary_unary_rpc_method_handler(
servicer.UpdateLabelingPipelineRun,
request_deserializer=github_dot_com_dot_metaprov_dot_modelaapi_dot_services_dot_labelingpipelinerun_dot_v1_dot_labelingpipelinerun__pb2.UpdateLabelingPipelineRunRequest.FromString,
response_serializer=github_dot_com_dot_metaprov_dot_modelaapi_dot_services_dot_labelingpipelinerun_dot_v1_dot_labelingpipelinerun__pb2.UpdateLabelingPipelineRunResponse.SerializeToString,
),
'DeleteLabelingPipelineRun': grpc.unary_unary_rpc_method_handler(
servicer.DeleteLabelingPipelineRun,
request_deserializer=github_dot_com_dot_metaprov_dot_modelaapi_dot_services_dot_labelingpipelinerun_dot_v1_dot_labelingpipelinerun__pb2.DeleteLabelingPipelineRunRequest.FromString,
response_serializer=github_dot_com_dot_metaprov_dot_modelaapi_dot_services_dot_labelingpipelinerun_dot_v1_dot_labelingpipelinerun__pb2.DeleteLabelingPipelineRunResponse.SerializeToString,
),
}
generic_handler = grpc.method_handlers_generic_handler(
'github.com.metaprov.modelaapi.services.labelingpipelinerun.v1.LabelingPipelineRunService', rpc_method_handlers)
server.add_generic_rpc_handlers((generic_handler,))
# This class is part of an EXPERIMENTAL API.
class LabelingPipelineRunService(object):
"""Missing associated documentation comment in .proto file."""
@staticmethod
def ListLabelingPipelineRuns(request,
target,
options=(),
channel_credentials=None,
call_credentials=None,
insecure=False,
compression=None,
wait_for_ready=None,
timeout=None,
metadata=None):
return grpc.experimental.unary_unary(request, target, '/github.com.metaprov.modelaapi.services.labelingpipelinerun.v1.LabelingPipelineRunService/ListLabelingPipelineRuns',
github_dot_com_dot_metaprov_dot_modelaapi_dot_services_dot_labelingpipelinerun_dot_v1_dot_labelingpipelinerun__pb2.ListLabelingPipelineRunRequest.SerializeToString,
github_dot_com_dot_metaprov_dot_modelaapi_dot_services_dot_labelingpipelinerun_dot_v1_dot_labelingpipelinerun__pb2.ListLabelingPipelineRunResponse.FromString,
options, channel_credentials,
insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
@staticmethod
def CreateLabelingPipelineRun(request,
target,
options=(),
channel_credentials=None,
call_credentials=None,
insecure=False,
compression=None,
wait_for_ready=None,
timeout=None,
metadata=None):
return grpc.experimental.unary_unary(request, target, '/github.com.metaprov.modelaapi.services.labelingpipelinerun.v1.LabelingPipelineRunService/CreateLabelingPipelineRun',
github_dot_com_dot_metaprov_dot_modelaapi_dot_services_dot_labelingpipelinerun_dot_v1_dot_labelingpipelinerun__pb2.CreateLabelingPipelineRunRequest.SerializeToString,
github_dot_com_dot_metaprov_dot_modelaapi_dot_services_dot_labelingpipelinerun_dot_v1_dot_labelingpipelinerun__pb2.CreateLabelingPipelineRunResponse.FromString,
options, channel_credentials,
insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
@staticmethod
def GetLabelingPipelineRun(request,
target,
options=(),
channel_credentials=None,
call_credentials=None,
insecure=False,
compression=None,
wait_for_ready=None,
timeout=None,
metadata=None):
return grpc.experimental.unary_unary(request, target, '/github.com.metaprov.modelaapi.services.labelingpipelinerun.v1.LabelingPipelineRunService/GetLabelingPipelineRun',
github_dot_com_dot_metaprov_dot_modelaapi_dot_services_dot_labelingpipelinerun_dot_v1_dot_labelingpipelinerun__pb2.GetLabelingPipelineRunRequest.SerializeToString,
github_dot_com_dot_metaprov_dot_modelaapi_dot_services_dot_labelingpipelinerun_dot_v1_dot_labelingpipelinerun__pb2.GetLabelingPipelineRunResponse.FromString,
options, channel_credentials,
insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
@staticmethod
def UpdateLabelingPipelineRun(request,
target,
options=(),
channel_credentials=None,
call_credentials=None,
insecure=False,
compression=None,
wait_for_ready=None,
timeout=None,
metadata=None):
return grpc.experimental.unary_unary(request, target, '/github.com.metaprov.modelaapi.services.labelingpipelinerun.v1.LabelingPipelineRunService/UpdateLabelingPipelineRun',
github_dot_com_dot_metaprov_dot_modelaapi_dot_services_dot_labelingpipelinerun_dot_v1_dot_labelingpipelinerun__pb2.UpdateLabelingPipelineRunRequest.SerializeToString,
github_dot_com_dot_metaprov_dot_modelaapi_dot_services_dot_labelingpipelinerun_dot_v1_dot_labelingpipelinerun__pb2.UpdateLabelingPipelineRunResponse.FromString,
options, channel_credentials,
insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
@staticmethod
def DeleteLabelingPipelineRun(request,
target,
options=(),
channel_credentials=None,
call_credentials=None,
insecure=False,
compression=None,
wait_for_ready=None,
timeout=None,
metadata=None):
return grpc.experimental.unary_unary(request, target, '/github.com.metaprov.modelaapi.services.labelingpipelinerun.v1.LabelingPipelineRunService/DeleteLabelingPipelineRun',
github_dot_com_dot_metaprov_dot_modelaapi_dot_services_dot_labelingpipelinerun_dot_v1_dot_labelingpipelinerun__pb2.DeleteLabelingPipelineRunRequest.SerializeToString,
github_dot_com_dot_metaprov_dot_modelaapi_dot_services_dot_labelingpipelinerun_dot_v1_dot_labelingpipelinerun__pb2.DeleteLabelingPipelineRunResponse.FromString,
options, channel_credentials,
insecure, call_credentials, compression, wait_for_ready, timeout, metadata) | lang/python/github/com/metaprov/modelaapi/services/labelingpipelinerun/v1/labelingpipelinerun_pb2_grpc.py | """Client and server classes corresponding to protobuf-defined services."""
import grpc
from github.com.metaprov.modelaapi.services.labelingpipelinerun.v1 import labelingpipelinerun_pb2 as github_dot_com_dot_metaprov_dot_modelaapi_dot_services_dot_labelingpipelinerun_dot_v1_dot_labelingpipelinerun__pb2
class LabelingPipelineRunServiceStub(object):
"""Missing associated documentation comment in .proto file."""
def __init__(self, channel):
"""Constructor.
Args:
channel: A grpc.Channel.
"""
self.ListLabelingPipelineRuns = channel.unary_unary(
'/github.com.metaprov.modelaapi.services.labelingpipelinerun.v1.LabelingPipelineRunService/ListLabelingPipelineRuns',
request_serializer=github_dot_com_dot_metaprov_dot_modelaapi_dot_services_dot_labelingpipelinerun_dot_v1_dot_labelingpipelinerun__pb2.ListLabelingPipelineRunRequest.SerializeToString,
response_deserializer=github_dot_com_dot_metaprov_dot_modelaapi_dot_services_dot_labelingpipelinerun_dot_v1_dot_labelingpipelinerun__pb2.ListLabelingPipelineRunResponse.FromString,
)
self.CreateLabelingPipelineRun = channel.unary_unary(
'/github.com.metaprov.modelaapi.services.labelingpipelinerun.v1.LabelingPipelineRunService/CreateLabelingPipelineRun',
request_serializer=github_dot_com_dot_metaprov_dot_modelaapi_dot_services_dot_labelingpipelinerun_dot_v1_dot_labelingpipelinerun__pb2.CreateLabelingPipelineRunRequest.SerializeToString,
response_deserializer=github_dot_com_dot_metaprov_dot_modelaapi_dot_services_dot_labelingpipelinerun_dot_v1_dot_labelingpipelinerun__pb2.CreateLabelingPipelineRunResponse.FromString,
)
self.GetLabelingPipelineRun = channel.unary_unary(
'/github.com.metaprov.modelaapi.services.labelingpipelinerun.v1.LabelingPipelineRunService/GetLabelingPipelineRun',
request_serializer=github_dot_com_dot_metaprov_dot_modelaapi_dot_services_dot_labelingpipelinerun_dot_v1_dot_labelingpipelinerun__pb2.GetLabelingPipelineRunRequest.SerializeToString,
response_deserializer=github_dot_com_dot_metaprov_dot_modelaapi_dot_services_dot_labelingpipelinerun_dot_v1_dot_labelingpipelinerun__pb2.GetLabelingPipelineRunResponse.FromString,
)
self.UpdateLabelingPipelineRun = channel.unary_unary(
'/github.com.metaprov.modelaapi.services.labelingpipelinerun.v1.LabelingPipelineRunService/UpdateLabelingPipelineRun',
request_serializer=github_dot_com_dot_metaprov_dot_modelaapi_dot_services_dot_labelingpipelinerun_dot_v1_dot_labelingpipelinerun__pb2.UpdateLabelingPipelineRunRequest.SerializeToString,
response_deserializer=github_dot_com_dot_metaprov_dot_modelaapi_dot_services_dot_labelingpipelinerun_dot_v1_dot_labelingpipelinerun__pb2.UpdateLabelingPipelineRunResponse.FromString,
)
self.DeleteLabelingPipelineRun = channel.unary_unary(
'/github.com.metaprov.modelaapi.services.labelingpipelinerun.v1.LabelingPipelineRunService/DeleteLabelingPipelineRun',
request_serializer=github_dot_com_dot_metaprov_dot_modelaapi_dot_services_dot_labelingpipelinerun_dot_v1_dot_labelingpipelinerun__pb2.DeleteLabelingPipelineRunRequest.SerializeToString,
response_deserializer=github_dot_com_dot_metaprov_dot_modelaapi_dot_services_dot_labelingpipelinerun_dot_v1_dot_labelingpipelinerun__pb2.DeleteLabelingPipelineRunResponse.FromString,
)
class LabelingPipelineRunServiceServicer(object):
"""Missing associated documentation comment in .proto file."""
def ListLabelingPipelineRuns(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def CreateLabelingPipelineRun(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def GetLabelingPipelineRun(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def UpdateLabelingPipelineRun(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def DeleteLabelingPipelineRun(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def add_LabelingPipelineRunServiceServicer_to_server(servicer, server):
rpc_method_handlers = {
'ListLabelingPipelineRuns': grpc.unary_unary_rpc_method_handler(
servicer.ListLabelingPipelineRuns,
request_deserializer=github_dot_com_dot_metaprov_dot_modelaapi_dot_services_dot_labelingpipelinerun_dot_v1_dot_labelingpipelinerun__pb2.ListLabelingPipelineRunRequest.FromString,
response_serializer=github_dot_com_dot_metaprov_dot_modelaapi_dot_services_dot_labelingpipelinerun_dot_v1_dot_labelingpipelinerun__pb2.ListLabelingPipelineRunResponse.SerializeToString,
),
'CreateLabelingPipelineRun': grpc.unary_unary_rpc_method_handler(
servicer.CreateLabelingPipelineRun,
request_deserializer=github_dot_com_dot_metaprov_dot_modelaapi_dot_services_dot_labelingpipelinerun_dot_v1_dot_labelingpipelinerun__pb2.CreateLabelingPipelineRunRequest.FromString,
response_serializer=github_dot_com_dot_metaprov_dot_modelaapi_dot_services_dot_labelingpipelinerun_dot_v1_dot_labelingpipelinerun__pb2.CreateLabelingPipelineRunResponse.SerializeToString,
),
'GetLabelingPipelineRun': grpc.unary_unary_rpc_method_handler(
servicer.GetLabelingPipelineRun,
request_deserializer=github_dot_com_dot_metaprov_dot_modelaapi_dot_services_dot_labelingpipelinerun_dot_v1_dot_labelingpipelinerun__pb2.GetLabelingPipelineRunRequest.FromString,
response_serializer=github_dot_com_dot_metaprov_dot_modelaapi_dot_services_dot_labelingpipelinerun_dot_v1_dot_labelingpipelinerun__pb2.GetLabelingPipelineRunResponse.SerializeToString,
),
'UpdateLabelingPipelineRun': grpc.unary_unary_rpc_method_handler(
servicer.UpdateLabelingPipelineRun,
request_deserializer=github_dot_com_dot_metaprov_dot_modelaapi_dot_services_dot_labelingpipelinerun_dot_v1_dot_labelingpipelinerun__pb2.UpdateLabelingPipelineRunRequest.FromString,
response_serializer=github_dot_com_dot_metaprov_dot_modelaapi_dot_services_dot_labelingpipelinerun_dot_v1_dot_labelingpipelinerun__pb2.UpdateLabelingPipelineRunResponse.SerializeToString,
),
'DeleteLabelingPipelineRun': grpc.unary_unary_rpc_method_handler(
servicer.DeleteLabelingPipelineRun,
request_deserializer=github_dot_com_dot_metaprov_dot_modelaapi_dot_services_dot_labelingpipelinerun_dot_v1_dot_labelingpipelinerun__pb2.DeleteLabelingPipelineRunRequest.FromString,
response_serializer=github_dot_com_dot_metaprov_dot_modelaapi_dot_services_dot_labelingpipelinerun_dot_v1_dot_labelingpipelinerun__pb2.DeleteLabelingPipelineRunResponse.SerializeToString,
),
}
generic_handler = grpc.method_handlers_generic_handler(
'github.com.metaprov.modelaapi.services.labelingpipelinerun.v1.LabelingPipelineRunService', rpc_method_handlers)
server.add_generic_rpc_handlers((generic_handler,))
# This class is part of an EXPERIMENTAL API.
class LabelingPipelineRunService(object):
"""Missing associated documentation comment in .proto file."""
@staticmethod
def ListLabelingPipelineRuns(request,
target,
options=(),
channel_credentials=None,
call_credentials=None,
insecure=False,
compression=None,
wait_for_ready=None,
timeout=None,
metadata=None):
return grpc.experimental.unary_unary(request, target, '/github.com.metaprov.modelaapi.services.labelingpipelinerun.v1.LabelingPipelineRunService/ListLabelingPipelineRuns',
github_dot_com_dot_metaprov_dot_modelaapi_dot_services_dot_labelingpipelinerun_dot_v1_dot_labelingpipelinerun__pb2.ListLabelingPipelineRunRequest.SerializeToString,
github_dot_com_dot_metaprov_dot_modelaapi_dot_services_dot_labelingpipelinerun_dot_v1_dot_labelingpipelinerun__pb2.ListLabelingPipelineRunResponse.FromString,
options, channel_credentials,
insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
@staticmethod
def CreateLabelingPipelineRun(request,
target,
options=(),
channel_credentials=None,
call_credentials=None,
insecure=False,
compression=None,
wait_for_ready=None,
timeout=None,
metadata=None):
return grpc.experimental.unary_unary(request, target, '/github.com.metaprov.modelaapi.services.labelingpipelinerun.v1.LabelingPipelineRunService/CreateLabelingPipelineRun',
github_dot_com_dot_metaprov_dot_modelaapi_dot_services_dot_labelingpipelinerun_dot_v1_dot_labelingpipelinerun__pb2.CreateLabelingPipelineRunRequest.SerializeToString,
github_dot_com_dot_metaprov_dot_modelaapi_dot_services_dot_labelingpipelinerun_dot_v1_dot_labelingpipelinerun__pb2.CreateLabelingPipelineRunResponse.FromString,
options, channel_credentials,
insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
@staticmethod
def GetLabelingPipelineRun(request,
target,
options=(),
channel_credentials=None,
call_credentials=None,
insecure=False,
compression=None,
wait_for_ready=None,
timeout=None,
metadata=None):
return grpc.experimental.unary_unary(request, target, '/github.com.metaprov.modelaapi.services.labelingpipelinerun.v1.LabelingPipelineRunService/GetLabelingPipelineRun',
github_dot_com_dot_metaprov_dot_modelaapi_dot_services_dot_labelingpipelinerun_dot_v1_dot_labelingpipelinerun__pb2.GetLabelingPipelineRunRequest.SerializeToString,
github_dot_com_dot_metaprov_dot_modelaapi_dot_services_dot_labelingpipelinerun_dot_v1_dot_labelingpipelinerun__pb2.GetLabelingPipelineRunResponse.FromString,
options, channel_credentials,
insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
@staticmethod
def UpdateLabelingPipelineRun(request,
target,
options=(),
channel_credentials=None,
call_credentials=None,
insecure=False,
compression=None,
wait_for_ready=None,
timeout=None,
metadata=None):
return grpc.experimental.unary_unary(request, target, '/github.com.metaprov.modelaapi.services.labelingpipelinerun.v1.LabelingPipelineRunService/UpdateLabelingPipelineRun',
github_dot_com_dot_metaprov_dot_modelaapi_dot_services_dot_labelingpipelinerun_dot_v1_dot_labelingpipelinerun__pb2.UpdateLabelingPipelineRunRequest.SerializeToString,
github_dot_com_dot_metaprov_dot_modelaapi_dot_services_dot_labelingpipelinerun_dot_v1_dot_labelingpipelinerun__pb2.UpdateLabelingPipelineRunResponse.FromString,
options, channel_credentials,
insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
@staticmethod
def DeleteLabelingPipelineRun(request,
target,
options=(),
channel_credentials=None,
call_credentials=None,
insecure=False,
compression=None,
wait_for_ready=None,
timeout=None,
metadata=None):
return grpc.experimental.unary_unary(request, target, '/github.com.metaprov.modelaapi.services.labelingpipelinerun.v1.LabelingPipelineRunService/DeleteLabelingPipelineRun',
github_dot_com_dot_metaprov_dot_modelaapi_dot_services_dot_labelingpipelinerun_dot_v1_dot_labelingpipelinerun__pb2.DeleteLabelingPipelineRunRequest.SerializeToString,
github_dot_com_dot_metaprov_dot_modelaapi_dot_services_dot_labelingpipelinerun_dot_v1_dot_labelingpipelinerun__pb2.DeleteLabelingPipelineRunResponse.FromString,
options, channel_credentials,
insecure, call_credentials, compression, wait_for_ready, timeout, metadata) | 0.760562 | 0.093761 |
import sys
import click
from tabulate import tabulate
from . import admin
from ...session import Session, is_legacy_server
from ..pretty import print_error
@admin.command()
@click.option('-i', '--id', 'agent_id', required=True,
help='The agent Id to inspect.')
def agent(agent_id):
'''
Show the information about the given agent.
'''
fields = [
('ID', 'id'),
('Status', 'status'),
('Region', 'region'),
('First Contact', 'first_contact'),
('CPU Usage (%)', 'cpu_cur_pct'),
('Used Memory (MiB)', 'mem_cur_bytes'),
('Total slots', 'available_slots'),
('Occupied slots', 'occupied_slots'),
]
if is_legacy_server():
del fields[9]
del fields[6]
with Session() as session:
try:
resp = session.Agent.detail(agent_id=agent_id,
fields=(item[1] for item in fields))
except Exception as e:
print_error(e)
sys.exit(1)
rows = []
for name, key in fields:
if key == 'mem_cur_bytes' and resp[key] is not None:
resp[key] = round(resp[key] / 2 ** 20, 1)
if key in resp:
rows.append((name, resp[key]))
print(tabulate(rows, headers=('Field', 'Value')))
@admin.command()
@click.option('-s', '--status', type=str, default='ALIVE',
help='Filter agents by the given status.')
@click.option('--all', is_flag=True, help='Display all agents.')
def agents(status, all):
'''
List and manage agents.
(admin privilege required)
'''
fields = [
('ID', 'id'),
('Status', 'status'),
('Region', 'region'),
('First Contact', 'first_contact'),
('CPU Usage (%)', 'cpu_cur_pct'),
('Used Memory (MiB)', 'mem_cur_bytes'),
('Total slots', 'available_slots'),
('Occupied slots', 'occupied_slots'),
]
if is_legacy_server():
del fields[9]
del fields[6]
def execute_paginated_query(limit, offset):
try:
resp_agents = session.Agent.list_with_limit(
limit, offset, status, fields=(item[1] for item in fields))
except Exception as e:
print_error(e)
sys.exit(1)
return resp_agents
def round_mem(results):
for item in results:
if 'mem_cur_bytes' in item and item['mem_cur_bytes'] is not None:
item['mem_cur_bytes'] = round(item['mem_cur_bytes'] / 2 ** 20, 1)
return results
def _generate_paginated_results(interval):
offset = 0
is_first = True
total_count = -1
while True:
limit = (interval if is_first else
min(interval, total_count - offset))
try:
result = execute_paginated_query(limit, offset)
except Exception as e:
print_error(e)
sys.exit(1)
offset += interval
total_count = result['total_count']
items = result['items']
items = round_mem(items)
table = tabulate((item.values() for item in items),
headers=(item[0] for item in fields))
if is_first:
is_first = False
else:
table_rows = table.split('\n')
table = '\n'.join(table_rows[2:])
yield table + '\n'
if not offset < total_count:
break
with Session() as session:
paginating_interval = 10
if all:
click.echo_via_pager(_generate_paginated_results(paginating_interval))
else:
result = execute_paginated_query(paginating_interval, offset=0)
total_count = result['total_count']
if total_count == 0:
print('There are no matching agents.')
return
items = result['items']
items = round_mem(items)
fields = [field for field in fields if field[1] in items[0]]
print(tabulate((item.values() for item in items),
headers=(item[0] for item in fields)))
if total_count > paginating_interval:
print("More agents can be displayed by using --all option.")
@admin.group()
def watcher():
'''Provides agent watcher operations.
Watcher operations are available only for Linux distributions.
'''
@watcher.command()
@click.argument('agent', type=str)
def status(agent):
'''
Get agent and watcher status.
(superadmin privilege required)
\b
AGENT: Agent id.
'''
with Session() as session:
try:
status = session.AgentWatcher.get_status(agent)
print(status)
except Exception as e:
print_error(e)
sys.exit(1)
@watcher.command()
@click.argument('agent', type=str)
def agent_start(agent):
'''
Start agent service.
(superadmin privilege required)
\b
AGENT: Agent id.
'''
with Session() as session:
try:
status = session.AgentWatcher.agent_start(agent)
print(status)
except Exception as e:
print_error(e)
sys.exit(1)
@watcher.command()
@click.argument('agent', type=str)
def agent_stop(agent):
'''
Stop agent service.
(superadmin privilege required)
\b
AGENT: Agent id.
'''
with Session() as session:
try:
status = session.AgentWatcher.agent_stop(agent)
print(status)
except Exception as e:
print_error(e)
sys.exit(1)
@watcher.command()
@click.argument('agent', type=str)
def agent_restart(agent):
'''
Restart agent service.
(superadmin privilege required)
\b
AGENT: Agent id.
'''
with Session() as session:
try:
status = session.AgentWatcher.agent_restart(agent)
print(status)
except Exception as e:
print_error(e)
sys.exit(1) | src/ai/backend/client/cli/admin/agents.py | import sys
import click
from tabulate import tabulate
from . import admin
from ...session import Session, is_legacy_server
from ..pretty import print_error
@admin.command()
@click.option('-i', '--id', 'agent_id', required=True,
help='The agent Id to inspect.')
def agent(agent_id):
'''
Show the information about the given agent.
'''
fields = [
('ID', 'id'),
('Status', 'status'),
('Region', 'region'),
('First Contact', 'first_contact'),
('CPU Usage (%)', 'cpu_cur_pct'),
('Used Memory (MiB)', 'mem_cur_bytes'),
('Total slots', 'available_slots'),
('Occupied slots', 'occupied_slots'),
]
if is_legacy_server():
del fields[9]
del fields[6]
with Session() as session:
try:
resp = session.Agent.detail(agent_id=agent_id,
fields=(item[1] for item in fields))
except Exception as e:
print_error(e)
sys.exit(1)
rows = []
for name, key in fields:
if key == 'mem_cur_bytes' and resp[key] is not None:
resp[key] = round(resp[key] / 2 ** 20, 1)
if key in resp:
rows.append((name, resp[key]))
print(tabulate(rows, headers=('Field', 'Value')))
@admin.command()
@click.option('-s', '--status', type=str, default='ALIVE',
help='Filter agents by the given status.')
@click.option('--all', is_flag=True, help='Display all agents.')
def agents(status, all):
'''
List and manage agents.
(admin privilege required)
'''
fields = [
('ID', 'id'),
('Status', 'status'),
('Region', 'region'),
('First Contact', 'first_contact'),
('CPU Usage (%)', 'cpu_cur_pct'),
('Used Memory (MiB)', 'mem_cur_bytes'),
('Total slots', 'available_slots'),
('Occupied slots', 'occupied_slots'),
]
if is_legacy_server():
del fields[9]
del fields[6]
def execute_paginated_query(limit, offset):
try:
resp_agents = session.Agent.list_with_limit(
limit, offset, status, fields=(item[1] for item in fields))
except Exception as e:
print_error(e)
sys.exit(1)
return resp_agents
def round_mem(results):
for item in results:
if 'mem_cur_bytes' in item and item['mem_cur_bytes'] is not None:
item['mem_cur_bytes'] = round(item['mem_cur_bytes'] / 2 ** 20, 1)
return results
def _generate_paginated_results(interval):
offset = 0
is_first = True
total_count = -1
while True:
limit = (interval if is_first else
min(interval, total_count - offset))
try:
result = execute_paginated_query(limit, offset)
except Exception as e:
print_error(e)
sys.exit(1)
offset += interval
total_count = result['total_count']
items = result['items']
items = round_mem(items)
table = tabulate((item.values() for item in items),
headers=(item[0] for item in fields))
if is_first:
is_first = False
else:
table_rows = table.split('\n')
table = '\n'.join(table_rows[2:])
yield table + '\n'
if not offset < total_count:
break
with Session() as session:
paginating_interval = 10
if all:
click.echo_via_pager(_generate_paginated_results(paginating_interval))
else:
result = execute_paginated_query(paginating_interval, offset=0)
total_count = result['total_count']
if total_count == 0:
print('There are no matching agents.')
return
items = result['items']
items = round_mem(items)
fields = [field for field in fields if field[1] in items[0]]
print(tabulate((item.values() for item in items),
headers=(item[0] for item in fields)))
if total_count > paginating_interval:
print("More agents can be displayed by using --all option.")
@admin.group()
def watcher():
'''Provides agent watcher operations.
Watcher operations are available only for Linux distributions.
'''
@watcher.command()
@click.argument('agent', type=str)
def status(agent):
'''
Get agent and watcher status.
(superadmin privilege required)
\b
AGENT: Agent id.
'''
with Session() as session:
try:
status = session.AgentWatcher.get_status(agent)
print(status)
except Exception as e:
print_error(e)
sys.exit(1)
@watcher.command()
@click.argument('agent', type=str)
def agent_start(agent):
'''
Start agent service.
(superadmin privilege required)
\b
AGENT: Agent id.
'''
with Session() as session:
try:
status = session.AgentWatcher.agent_start(agent)
print(status)
except Exception as e:
print_error(e)
sys.exit(1)
@watcher.command()
@click.argument('agent', type=str)
def agent_stop(agent):
'''
Stop agent service.
(superadmin privilege required)
\b
AGENT: Agent id.
'''
with Session() as session:
try:
status = session.AgentWatcher.agent_stop(agent)
print(status)
except Exception as e:
print_error(e)
sys.exit(1)
@watcher.command()
@click.argument('agent', type=str)
def agent_restart(agent):
'''
Restart agent service.
(superadmin privilege required)
\b
AGENT: Agent id.
'''
with Session() as session:
try:
status = session.AgentWatcher.agent_restart(agent)
print(status)
except Exception as e:
print_error(e)
sys.exit(1) | 0.215351 | 0.122944 |
__author__ = '<NAME> (yy(at)rikkyo.ac.jp)'
__version__= '1.0'
import sys
import os
import inspect
from absl import app, flags
from typing import Union, Dict, List, Tuple
import numpy as np
from astropy.io import fits as iofits
from astropy.coordinates import Angle
from regions import read_ds9 as read_ds9_region
from regions import ds9_objects_to_string
from regions import CircleAnnulusPixelRegion, RectanglePixelRegion, PixCoord
RADII = {
'3arcmin': 172.584, # pixel
'5arcmin': 287.64, # pixel
'7arcmin': 402.69663 # pixel
}
SRC_REGION_META = {
'include': True
}
BKG_REGION_META = {
'include': True,
'comment': '# background'
}
def logger(string: str, level: int, frame=None) -> None:
status = {
0: 'DEBUG',
1: 'INFO',
2: 'WARNING',
3: 'ERROR'}
if not frame == None:
function_name = inspect.getframeinfo(frame)[2]
console_msg = '[%s] %s : %s' % (
status[level], function_name, str(string))
else:
console_msg = '[%s] %s' % (status[level], str(string))
if (level >= flag_values.loglv):
print(console_msg)
def make_output_directory():
out_dir = flag_values.out_directory
os.makedirs(out_dir, exist_ok=True)
logger(f'{out_dir} is generated', 0)
def open_image_fits(file_name:str,index) -> Union[
iofits.hdu.image.PrimaryHDU,iofits.hdu.table.BinTableHDU]:
hdulist = iofits.open(file_name)
return hdulist[index]
def get_necessary_parameters(hdu: iofits.hdu.image.PrimaryHDU) -> Dict[str,Union[int,float]]:
parameters = dict(
win_opt = hdu.header['WINOPT'], # (0:Off, 1:1/4, 2:1/8, 3:1/16)
win_size = hdu.header['WIN_SIZ'],
win_start = hdu.header['WIN_ST'],
pa_nom = hdu.header['PA_NOM'],
xref_pix = hdu.header['CRPIX1'],
yref_pix = hdu.header['CRPIX2'],
xis_id = int(hdu.header['INSTRUME'].strip('XIS')))
return parameters
def define_rotation_angle_deg(paramters: dict) -> float:
rot_angle_deg = {
0: paramters['pa_nom'],
1: paramters['pa_nom'] - 90.,
2: paramters['pa_nom'] + 90.,
3: paramters['pa_nom']
}
return rot_angle_deg[paramters['xis_id']]
def define_rotaion_matrix(parameters: dict) -> Tuple[np.ndarray, np.ndarray]:
rot_angle_rad = np.radians(define_rotation_angle_deg(parameters))
normal_rotaion_matrix = np.matrix([
[np.cos(rot_angle_rad), -np.sin(rot_angle_rad)],
[np.sin(rot_angle_rad), np.cos(rot_angle_rad)]], dtype=float)
inverse_rotaion_matrix = np.matrix([
[np.cos(rot_angle_rad), np.sin(rot_angle_rad)],
[-np.sin(rot_angle_rad), -np.cos(rot_angle_rad)]], dtype=float)
return normal_rotaion_matrix, inverse_rotaion_matrix
def convert_reference_coodinate(ref: np.ndarray, parameters: dict) -> np.matrix:
nrm_rot_mtx, _ = define_rotaion_matrix(parameters)
org = np.array([parameters['xref_pix'], parameters['yref_pix']]).reshape(2,1)
ref = ref.reshape(2,1)
ref = nrm_rot_mtx * ref
ref = ref + org
return ref
def read_pileup_region() -> CircleAnnulusPixelRegion:
regions = read_ds9_region(flag_values.pileup_region)
return regions[0]
def define_regions(hdu: iofits.hdu.image.PrimaryHDU, parameters: dict) -> Dict[str, Union[
CircleAnnulusPixelRegion, RectanglePixelRegion]]:
regions = dict()
pileup_region = read_pileup_region()
rot_angle_deg = define_rotation_angle_deg(parameters)
windel = parameters['win_start'] - 512
# source region
regions['src'] = CircleAnnulusPixelRegion(
center=pileup_region.center,
inner_radius=pileup_region.inner_radius,
outer_radius=RADII['3arcmin'],
meta=SRC_REGION_META)
# background region
regions['bkg'] = CircleAnnulusPixelRegion(
center=pileup_region.center,
inner_radius=RADII['5arcmin'],
outer_radius=RADII['7arcmin'],
meta=BKG_REGION_META)
# exclude region 1
ref = np.array([0, windel - 256.])
ref = convert_reference_coodinate(ref, parameters)
regions['rct1'] = RectanglePixelRegion(
center=PixCoord(float(ref[0][0]), float(ref[1][0])),
width=1024.,
height=512.,
angle=Angle(rot_angle_deg,'deg'))
# exclude region 2
ref = np.array([0, windel + parameters['win_size'] + 256.])
ref = convert_reference_coodinate(ref, parameters)
regions['rct2'] = RectanglePixelRegion(
center=PixCoord(float(ref[0][0]), float(ref[1][0])),
width=1024.,
height=512.,
angle=Angle(rot_angle_deg,'deg'))
# exclude region 3
ref = np.array([512. + 128., windel + parameters['win_size'] * 0.5])
ref = convert_reference_coodinate(ref, parameters)
regions['rct3'] = RectanglePixelRegion(
center=PixCoord(float(ref[0][0]), float(ref[1][0])),
width=256.,
height=parameters['win_size']+1024.,
angle=Angle(rot_angle_deg,'deg'))
# exclude region 4
ref = np.array([-512 - 128, windel + parameters['win_size'] * 0.5])
ref = convert_reference_coodinate(ref, parameters)
regions['rct4'] = RectanglePixelRegion(
center=PixCoord(float(ref[0][0]), float(ref[1][0])),
width=256.,
height=parameters['win_size']+1024.,
angle=Angle(rot_angle_deg,'deg'))
return regions
def generate_region(context: str, regions: list, xis_id: int) -> None:
region_filename = os.path.join(
flag_values.out_directory, f'x{xis_id}_{context}.reg')
write_ds9_region(regions,region_filename)
logger(f'{region_filename} is generated',1)
def write_ds9_region(regions: list, region_filename: str) -> None:
output = ds9_objects_to_string(regions,coordsys='physical')
output = output.replace('box','-box')
logger(f'DESCRIPTION OF OUTPUT REGION: {region_filename}\n{output}',0)
with open(region_filename, 'w') as f:
f.write(output)
def main(argv) -> None:
if flag_values.debug:
flag_values.loglv = 0
hdu = open_image_fits(flag_values.image,0)
par = get_necessary_parameters(hdu)
regions = define_regions(hdu,par)
make_output_directory()
generate_region(
'src',[regions['src'],regions['rct1'],regions['rct2']],
par['xis_id'])
generate_region(
'bkg',[regions['bkg'],regions['rct1'],regions['rct2'],regions['rct3'],regions['rct4']],
par['xis_id'])
if __name__ == '__main__':
flag_values = flags.FLAGS
flags.DEFINE_string('image', None, 'XIS image FITS file.', short_name='i')
flags.DEFINE_string('pileup_region',
None,
'Region file generated by aepileupcheckup.py.',
short_name='r')
flags.DEFINE_string('out_directory',
'src',
'Output directory.',
short_name='o')
flags.DEFINE_boolean('debug', False, 'enable debug trace.', short_name='d')
flags.DEFINE_integer('loglv', 1, 'logging level.', lower_bound=0, upper_bound=3)
flags.mark_flags_as_required(['image', 'pileup_region'])
sys.exit(app.run(main)) | astro/linux/xismkreg.py |
__author__ = '<NAME> (yy(at)rikkyo.ac.jp)'
__version__= '1.0'
import sys
import os
import inspect
from absl import app, flags
from typing import Union, Dict, List, Tuple
import numpy as np
from astropy.io import fits as iofits
from astropy.coordinates import Angle
from regions import read_ds9 as read_ds9_region
from regions import ds9_objects_to_string
from regions import CircleAnnulusPixelRegion, RectanglePixelRegion, PixCoord
RADII = {
'3arcmin': 172.584, # pixel
'5arcmin': 287.64, # pixel
'7arcmin': 402.69663 # pixel
}
SRC_REGION_META = {
'include': True
}
BKG_REGION_META = {
'include': True,
'comment': '# background'
}
def logger(string: str, level: int, frame=None) -> None:
status = {
0: 'DEBUG',
1: 'INFO',
2: 'WARNING',
3: 'ERROR'}
if not frame == None:
function_name = inspect.getframeinfo(frame)[2]
console_msg = '[%s] %s : %s' % (
status[level], function_name, str(string))
else:
console_msg = '[%s] %s' % (status[level], str(string))
if (level >= flag_values.loglv):
print(console_msg)
def make_output_directory():
out_dir = flag_values.out_directory
os.makedirs(out_dir, exist_ok=True)
logger(f'{out_dir} is generated', 0)
def open_image_fits(file_name:str,index) -> Union[
iofits.hdu.image.PrimaryHDU,iofits.hdu.table.BinTableHDU]:
hdulist = iofits.open(file_name)
return hdulist[index]
def get_necessary_parameters(hdu: iofits.hdu.image.PrimaryHDU) -> Dict[str,Union[int,float]]:
parameters = dict(
win_opt = hdu.header['WINOPT'], # (0:Off, 1:1/4, 2:1/8, 3:1/16)
win_size = hdu.header['WIN_SIZ'],
win_start = hdu.header['WIN_ST'],
pa_nom = hdu.header['PA_NOM'],
xref_pix = hdu.header['CRPIX1'],
yref_pix = hdu.header['CRPIX2'],
xis_id = int(hdu.header['INSTRUME'].strip('XIS')))
return parameters
def define_rotation_angle_deg(paramters: dict) -> float:
rot_angle_deg = {
0: paramters['pa_nom'],
1: paramters['pa_nom'] - 90.,
2: paramters['pa_nom'] + 90.,
3: paramters['pa_nom']
}
return rot_angle_deg[paramters['xis_id']]
def define_rotaion_matrix(parameters: dict) -> Tuple[np.ndarray, np.ndarray]:
rot_angle_rad = np.radians(define_rotation_angle_deg(parameters))
normal_rotaion_matrix = np.matrix([
[np.cos(rot_angle_rad), -np.sin(rot_angle_rad)],
[np.sin(rot_angle_rad), np.cos(rot_angle_rad)]], dtype=float)
inverse_rotaion_matrix = np.matrix([
[np.cos(rot_angle_rad), np.sin(rot_angle_rad)],
[-np.sin(rot_angle_rad), -np.cos(rot_angle_rad)]], dtype=float)
return normal_rotaion_matrix, inverse_rotaion_matrix
def convert_reference_coodinate(ref: np.ndarray, parameters: dict) -> np.matrix:
nrm_rot_mtx, _ = define_rotaion_matrix(parameters)
org = np.array([parameters['xref_pix'], parameters['yref_pix']]).reshape(2,1)
ref = ref.reshape(2,1)
ref = nrm_rot_mtx * ref
ref = ref + org
return ref
def read_pileup_region() -> CircleAnnulusPixelRegion:
regions = read_ds9_region(flag_values.pileup_region)
return regions[0]
def define_regions(hdu: iofits.hdu.image.PrimaryHDU, parameters: dict) -> Dict[str, Union[
CircleAnnulusPixelRegion, RectanglePixelRegion]]:
regions = dict()
pileup_region = read_pileup_region()
rot_angle_deg = define_rotation_angle_deg(parameters)
windel = parameters['win_start'] - 512
# source region
regions['src'] = CircleAnnulusPixelRegion(
center=pileup_region.center,
inner_radius=pileup_region.inner_radius,
outer_radius=RADII['3arcmin'],
meta=SRC_REGION_META)
# background region
regions['bkg'] = CircleAnnulusPixelRegion(
center=pileup_region.center,
inner_radius=RADII['5arcmin'],
outer_radius=RADII['7arcmin'],
meta=BKG_REGION_META)
# exclude region 1
ref = np.array([0, windel - 256.])
ref = convert_reference_coodinate(ref, parameters)
regions['rct1'] = RectanglePixelRegion(
center=PixCoord(float(ref[0][0]), float(ref[1][0])),
width=1024.,
height=512.,
angle=Angle(rot_angle_deg,'deg'))
# exclude region 2
ref = np.array([0, windel + parameters['win_size'] + 256.])
ref = convert_reference_coodinate(ref, parameters)
regions['rct2'] = RectanglePixelRegion(
center=PixCoord(float(ref[0][0]), float(ref[1][0])),
width=1024.,
height=512.,
angle=Angle(rot_angle_deg,'deg'))
# exclude region 3
ref = np.array([512. + 128., windel + parameters['win_size'] * 0.5])
ref = convert_reference_coodinate(ref, parameters)
regions['rct3'] = RectanglePixelRegion(
center=PixCoord(float(ref[0][0]), float(ref[1][0])),
width=256.,
height=parameters['win_size']+1024.,
angle=Angle(rot_angle_deg,'deg'))
# exclude region 4
ref = np.array([-512 - 128, windel + parameters['win_size'] * 0.5])
ref = convert_reference_coodinate(ref, parameters)
regions['rct4'] = RectanglePixelRegion(
center=PixCoord(float(ref[0][0]), float(ref[1][0])),
width=256.,
height=parameters['win_size']+1024.,
angle=Angle(rot_angle_deg,'deg'))
return regions
def generate_region(context: str, regions: list, xis_id: int) -> None:
region_filename = os.path.join(
flag_values.out_directory, f'x{xis_id}_{context}.reg')
write_ds9_region(regions,region_filename)
logger(f'{region_filename} is generated',1)
def write_ds9_region(regions: list, region_filename: str) -> None:
output = ds9_objects_to_string(regions,coordsys='physical')
output = output.replace('box','-box')
logger(f'DESCRIPTION OF OUTPUT REGION: {region_filename}\n{output}',0)
with open(region_filename, 'w') as f:
f.write(output)
def main(argv) -> None:
if flag_values.debug:
flag_values.loglv = 0
hdu = open_image_fits(flag_values.image,0)
par = get_necessary_parameters(hdu)
regions = define_regions(hdu,par)
make_output_directory()
generate_region(
'src',[regions['src'],regions['rct1'],regions['rct2']],
par['xis_id'])
generate_region(
'bkg',[regions['bkg'],regions['rct1'],regions['rct2'],regions['rct3'],regions['rct4']],
par['xis_id'])
if __name__ == '__main__':
flag_values = flags.FLAGS
flags.DEFINE_string('image', None, 'XIS image FITS file.', short_name='i')
flags.DEFINE_string('pileup_region',
None,
'Region file generated by aepileupcheckup.py.',
short_name='r')
flags.DEFINE_string('out_directory',
'src',
'Output directory.',
short_name='o')
flags.DEFINE_boolean('debug', False, 'enable debug trace.', short_name='d')
flags.DEFINE_integer('loglv', 1, 'logging level.', lower_bound=0, upper_bound=3)
flags.mark_flags_as_required(['image', 'pileup_region'])
sys.exit(app.run(main)) | 0.535098 | 0.356139 |
import os
import logging
import datetime
from dateutil.tz import gettz
import math
from decimal import Decimal
from common import (line, utils)
import members_card_const
# 環境変数の宣言
LIFF_ID = os.getenv('LIFF_ID')
LOGGER_LEVEL = os.getenv("LOGGER_LEVEL")
# ログ出力の設定
logger = logging.getLogger()
if LOGGER_LEVEL == 'DEBUG':
logger.setLevel(logging.DEBUG)
else:
logger.setLevel(logging.INFO)
def send_push_message(channel_access_token, user_id, product_obj, language):
"""
プッシュメッセージを送信する
Parameters
----------
channel_access_token : str
OAのチャネルアクセストークン
user_id : str
送信対象のユーザーID
product_obj : dict
データベースより取得した商品データ
language : str
多言語化対応用のパラメータ
"""
logger.info('productObj: %s', product_obj)
modified_product_obj = modify_product_obj(product_obj, language)
flex_dict = make_flex_recept(**modified_product_obj, language=language)
line.send_push_message(
channel_access_token, flex_dict, user_id)
def send_service_message(channel_access_token, notification_token, product_obj, language): # noqa: E501
"""
サービスメッセージを送信
Parameters
----------
channel_access_token : str
MINIアプリのチャネルアクセストークン
notification_token : str
MINIアプリの通知用トークン
product_obj : dict
データベースより取得した商品データ
language : str
多言語化対応用のパラメータ
"""
# サービスメッセ―ジで代引き手数料と支払手数料を表示させないため以下を0にする
product_obj['fee'] = 0
product_obj['postage'] = 0
modified_product_obj = modify_product_obj(product_obj)
params = {
"sum": modified_product_obj['total'] + '円',
"tax": modified_product_obj['tax'] + '円',
"date": modified_product_obj['date'],
"price": modified_product_obj['product_price'] + '円',
"btn1_url": "https://line.me",
"discount": modified_product_obj['discount'] + '円',
"quantity": "1点",
"shop_name": "Use Case STORE",
# "payment_fee": modifiedProductObj['fee'] + '円',
"product_name": modified_product_obj['product_name'],
# "delivery_cash": modifiedProductObj['postage'] + '円'
}
line.send_service_message(
channel_access_token, 'ec_comp_d_s_ja', params, notification_token)
def modify_product_obj(product_obj, language, discount=0):
"""
データベースより取得した商品データをメッセージ送信に適した状態のdict型に加工する
Parameters
----------
product_obj : dict
データベースより取得した商品データ
language : str
多言語化対応用のパラメータ
discount : int, optional
値引き率。
指定が無い場合0とする。
Returns
-------
dict
加工後の商品データ
"""
now = datetime.datetime.now(
gettz('Asia/Tokyo')).strftime('%Y/%m/%d %H:%M:%S')
subtotal = product_obj['unitPrice'] + \
product_obj['postage'] + product_obj['fee'] - discount
tax = math.floor(subtotal * Decimal(0.10))
total = subtotal + tax
point = math.floor(product_obj['unitPrice'] * Decimal(0.05))
logger.info('point: %s', point)
modified_product_obj = {
'date': now,
'product_name': product_obj['productName'][language],
'product_price': utils.separate_comma(product_obj['unitPrice']),
'postage': utils.separate_comma(product_obj['postage']),
'fee': utils.separate_comma(product_obj['fee']),
'discount': utils.separate_comma(discount),
'subtotal': utils.separate_comma(subtotal),
'tax': utils.separate_comma(tax),
'total': utils.separate_comma(total),
'point': utils.separate_comma(point),
'img_url': product_obj['imgUrl'],
}
return modified_product_obj
def make_flex_recept(date, product_name, product_price, postage,
fee, discount, subtotal, tax, total,
point, img_url, language):
"""
電子レシートのフレックスメッセージのdict型データを作成する
Parameters
----------
date: str
yyyy/MM/dd hh:mm:ss形式の日付時刻
product_name: str
商品名
product_price: str
商品代金
postage: str
送料
commission: str
手数料
discount: str
値下げ料
subtotal: str
小計
tax: str
消費税
total: str
合計
point: str
付与ポイント
img_url: str
商品画像のURL
language: str
言語設定
Returns
-------
result : dict
Flexmessageの元になる辞書型データ
"""
return {
"type": "flex",
"altText": members_card_const.const.MESSAGE_ALT_TEXT[language],
"contents": {
"type": "bubble",
"header": {
"type": "box",
"layout": "vertical",
"contents": [
{
"type": "text",
"text": "Use Case STORE",
"size": "xxl",
"weight": "bold"
},
{
"type": "text",
"text": date,
"color": "#767676"
},
{
"type": "text",
"wrap": True,
"text": members_card_const.const.MESSAGE_NOTES[language], # noqa: E501
"color": "#ff6347"
}
]
},
"body": {
"type": "box",
"layout": "vertical",
"contents": [
{
"type": "box",
"layout": "vertical",
"margin": "lg",
"spacing": "sm",
"contents": [
{
"type": "box",
"layout": "baseline",
"spacing": "sm",
"contents": [
{
"type": "text",
"text": product_name,
"color": "#5B5B5B",
"size": "sm",
"flex": 5
},
{
"type": "text",
"text": product_price,
"wrap": True,
"color": "#666666",
"size": "sm",
"flex": 2,
"align": "end"
}
]
},
{
"type": "box",
"layout": "baseline",
"spacing": "sm",
"contents": [
{
"type": "text",
"text": members_card_const.const.MESSAGE_POSTAGE[language], # noqa: E501
"color": "#5B5B5B",
"size": "sm",
"flex": 5
},
{
"type": "text",
"text": postage,
"wrap": True,
"color": "#666666",
"size": "sm",
"flex": 2,
"align": "end"
}
]
},
{
"type": "box",
"layout": "baseline",
"spacing": "sm",
"contents": [
{
"type": "text",
"text": members_card_const.const.MESSAGE_FEE[language], # noqa: E501
"color": "#5B5B5B",
"size": "sm",
"flex": 5
},
{
"type": "text",
"text": fee,
"wrap": True,
"color": "#666666",
"size": "sm",
"flex": 2,
"align": "end"
}
]
},
{
"type": "box",
"layout": "baseline",
"spacing": "sm",
"contents": [
{
"type": "text",
"text": members_card_const.const.MESSAGE_DISCOUNT[language], # noqa: E501
"color": "#5B5B5B",
"size": "sm",
"flex": 5
},
{
"type": "text",
"text": discount,
"wrap": True,
"color": "#666666",
"size": "sm",
"flex": 2,
"align": "end"
}
]
},
{
"type": "box",
"layout": "baseline",
"spacing": "sm",
"contents": [
{
"type": "text",
"text": members_card_const.const.MESSAGE_SUBTOTAL[language], # noqa: E501
"color": "#5B5B5B",
"size": "sm",
"flex": 5
},
{
"type": "text",
"text": subtotal,
"wrap": True,
"color": "#666666",
"size": "sm",
"flex": 2,
"align": "end"
}
]
},
{
"type": "box",
"layout": "baseline",
"spacing": "sm",
"contents": [
{
"type": "text",
"text": members_card_const.const.MESSAGE_TAX[language], # noqa: E501
"color": "#5B5B5B",
"size": "sm",
"flex": 5
},
{
"type": "text",
"text": tax,
"wrap": True,
"color": "#666666",
"size": "sm",
"flex": 2,
"align": "end"
}
]
},
{
"type": "box",
"layout": "baseline",
"spacing": "sm",
"contents": [
{
"type": "text",
"text": members_card_const.const.MESSAGE_TOTAL[language], # noqa: E501
"color": "#5B5B5B",
"size": "sm",
"flex": 5
},
{
"type": "text",
"text": total,
"wrap": True,
"color": "#666666",
"size": "sm",
"flex": 2,
"align": "end"
}
]
},
{
"type": "box",
"layout": "baseline",
"spacing": "sm",
"contents": [
{
"type": "text",
"text": members_card_const.const.MESSAGE_AWARD_POINTS[language], # noqa: E501
"color": "#5B5B5B",
"size": "sm",
"flex": 5
},
{
"type": "text",
"text": point,
"wrap": True,
"color": "#666666",
"size": "sm",
"flex": 2,
"align": "end"
}
]
},
],
"paddingBottom": "xxl"
},
{
"type": "box",
"layout": "vertical",
"contents": [
{
"type": "text",
"text": members_card_const.const.MESSAGE_THANKS[language], # noqa: E501
"wrap": True,
"size": "sm",
"color": "#767676"
}
]
},
{
"type": "box",
"layout": "vertical",
"contents": [
{
"type": "image",
"url": img_url,
"size": "lg"
}
],
"margin": "xxl"
}
],
"paddingTop": "0%"
},
"footer": {
"type": "box",
"layout": "vertical",
"spacing": "sm",
"contents": [
{
"type": "button",
"style": "link",
"height": "sm",
"action": {
"type": "uri",
"label": members_card_const.const.MESSAGE_VIEW[language], # noqa: E501
"uri": "https://liff.line.me/{liff_id}?lang={language}".format(liff_id=LIFF_ID, language=language) # noqa: E501
},
"color": "#0033cc"
},
{
"type": "spacer",
"size": "md"
}
],
"flex": 0
}
}
} | backend/APP/members_card/send_message.py | import os
import logging
import datetime
from dateutil.tz import gettz
import math
from decimal import Decimal
from common import (line, utils)
import members_card_const
# 環境変数の宣言
LIFF_ID = os.getenv('LIFF_ID')
LOGGER_LEVEL = os.getenv("LOGGER_LEVEL")
# ログ出力の設定
logger = logging.getLogger()
if LOGGER_LEVEL == 'DEBUG':
logger.setLevel(logging.DEBUG)
else:
logger.setLevel(logging.INFO)
def send_push_message(channel_access_token, user_id, product_obj, language):
"""
プッシュメッセージを送信する
Parameters
----------
channel_access_token : str
OAのチャネルアクセストークン
user_id : str
送信対象のユーザーID
product_obj : dict
データベースより取得した商品データ
language : str
多言語化対応用のパラメータ
"""
logger.info('productObj: %s', product_obj)
modified_product_obj = modify_product_obj(product_obj, language)
flex_dict = make_flex_recept(**modified_product_obj, language=language)
line.send_push_message(
channel_access_token, flex_dict, user_id)
def send_service_message(channel_access_token, notification_token, product_obj, language): # noqa: E501
"""
サービスメッセージを送信
Parameters
----------
channel_access_token : str
MINIアプリのチャネルアクセストークン
notification_token : str
MINIアプリの通知用トークン
product_obj : dict
データベースより取得した商品データ
language : str
多言語化対応用のパラメータ
"""
# サービスメッセ―ジで代引き手数料と支払手数料を表示させないため以下を0にする
product_obj['fee'] = 0
product_obj['postage'] = 0
modified_product_obj = modify_product_obj(product_obj)
params = {
"sum": modified_product_obj['total'] + '円',
"tax": modified_product_obj['tax'] + '円',
"date": modified_product_obj['date'],
"price": modified_product_obj['product_price'] + '円',
"btn1_url": "https://line.me",
"discount": modified_product_obj['discount'] + '円',
"quantity": "1点",
"shop_name": "Use Case STORE",
# "payment_fee": modifiedProductObj['fee'] + '円',
"product_name": modified_product_obj['product_name'],
# "delivery_cash": modifiedProductObj['postage'] + '円'
}
line.send_service_message(
channel_access_token, 'ec_comp_d_s_ja', params, notification_token)
def modify_product_obj(product_obj, language, discount=0):
"""
データベースより取得した商品データをメッセージ送信に適した状態のdict型に加工する
Parameters
----------
product_obj : dict
データベースより取得した商品データ
language : str
多言語化対応用のパラメータ
discount : int, optional
値引き率。
指定が無い場合0とする。
Returns
-------
dict
加工後の商品データ
"""
now = datetime.datetime.now(
gettz('Asia/Tokyo')).strftime('%Y/%m/%d %H:%M:%S')
subtotal = product_obj['unitPrice'] + \
product_obj['postage'] + product_obj['fee'] - discount
tax = math.floor(subtotal * Decimal(0.10))
total = subtotal + tax
point = math.floor(product_obj['unitPrice'] * Decimal(0.05))
logger.info('point: %s', point)
modified_product_obj = {
'date': now,
'product_name': product_obj['productName'][language],
'product_price': utils.separate_comma(product_obj['unitPrice']),
'postage': utils.separate_comma(product_obj['postage']),
'fee': utils.separate_comma(product_obj['fee']),
'discount': utils.separate_comma(discount),
'subtotal': utils.separate_comma(subtotal),
'tax': utils.separate_comma(tax),
'total': utils.separate_comma(total),
'point': utils.separate_comma(point),
'img_url': product_obj['imgUrl'],
}
return modified_product_obj
def make_flex_recept(date, product_name, product_price, postage,
fee, discount, subtotal, tax, total,
point, img_url, language):
"""
電子レシートのフレックスメッセージのdict型データを作成する
Parameters
----------
date: str
yyyy/MM/dd hh:mm:ss形式の日付時刻
product_name: str
商品名
product_price: str
商品代金
postage: str
送料
commission: str
手数料
discount: str
値下げ料
subtotal: str
小計
tax: str
消費税
total: str
合計
point: str
付与ポイント
img_url: str
商品画像のURL
language: str
言語設定
Returns
-------
result : dict
Flexmessageの元になる辞書型データ
"""
return {
"type": "flex",
"altText": members_card_const.const.MESSAGE_ALT_TEXT[language],
"contents": {
"type": "bubble",
"header": {
"type": "box",
"layout": "vertical",
"contents": [
{
"type": "text",
"text": "Use Case STORE",
"size": "xxl",
"weight": "bold"
},
{
"type": "text",
"text": date,
"color": "#767676"
},
{
"type": "text",
"wrap": True,
"text": members_card_const.const.MESSAGE_NOTES[language], # noqa: E501
"color": "#ff6347"
}
]
},
"body": {
"type": "box",
"layout": "vertical",
"contents": [
{
"type": "box",
"layout": "vertical",
"margin": "lg",
"spacing": "sm",
"contents": [
{
"type": "box",
"layout": "baseline",
"spacing": "sm",
"contents": [
{
"type": "text",
"text": product_name,
"color": "#5B5B5B",
"size": "sm",
"flex": 5
},
{
"type": "text",
"text": product_price,
"wrap": True,
"color": "#666666",
"size": "sm",
"flex": 2,
"align": "end"
}
]
},
{
"type": "box",
"layout": "baseline",
"spacing": "sm",
"contents": [
{
"type": "text",
"text": members_card_const.const.MESSAGE_POSTAGE[language], # noqa: E501
"color": "#5B5B5B",
"size": "sm",
"flex": 5
},
{
"type": "text",
"text": postage,
"wrap": True,
"color": "#666666",
"size": "sm",
"flex": 2,
"align": "end"
}
]
},
{
"type": "box",
"layout": "baseline",
"spacing": "sm",
"contents": [
{
"type": "text",
"text": members_card_const.const.MESSAGE_FEE[language], # noqa: E501
"color": "#5B5B5B",
"size": "sm",
"flex": 5
},
{
"type": "text",
"text": fee,
"wrap": True,
"color": "#666666",
"size": "sm",
"flex": 2,
"align": "end"
}
]
},
{
"type": "box",
"layout": "baseline",
"spacing": "sm",
"contents": [
{
"type": "text",
"text": members_card_const.const.MESSAGE_DISCOUNT[language], # noqa: E501
"color": "#5B5B5B",
"size": "sm",
"flex": 5
},
{
"type": "text",
"text": discount,
"wrap": True,
"color": "#666666",
"size": "sm",
"flex": 2,
"align": "end"
}
]
},
{
"type": "box",
"layout": "baseline",
"spacing": "sm",
"contents": [
{
"type": "text",
"text": members_card_const.const.MESSAGE_SUBTOTAL[language], # noqa: E501
"color": "#5B5B5B",
"size": "sm",
"flex": 5
},
{
"type": "text",
"text": subtotal,
"wrap": True,
"color": "#666666",
"size": "sm",
"flex": 2,
"align": "end"
}
]
},
{
"type": "box",
"layout": "baseline",
"spacing": "sm",
"contents": [
{
"type": "text",
"text": members_card_const.const.MESSAGE_TAX[language], # noqa: E501
"color": "#5B5B5B",
"size": "sm",
"flex": 5
},
{
"type": "text",
"text": tax,
"wrap": True,
"color": "#666666",
"size": "sm",
"flex": 2,
"align": "end"
}
]
},
{
"type": "box",
"layout": "baseline",
"spacing": "sm",
"contents": [
{
"type": "text",
"text": members_card_const.const.MESSAGE_TOTAL[language], # noqa: E501
"color": "#5B5B5B",
"size": "sm",
"flex": 5
},
{
"type": "text",
"text": total,
"wrap": True,
"color": "#666666",
"size": "sm",
"flex": 2,
"align": "end"
}
]
},
{
"type": "box",
"layout": "baseline",
"spacing": "sm",
"contents": [
{
"type": "text",
"text": members_card_const.const.MESSAGE_AWARD_POINTS[language], # noqa: E501
"color": "#5B5B5B",
"size": "sm",
"flex": 5
},
{
"type": "text",
"text": point,
"wrap": True,
"color": "#666666",
"size": "sm",
"flex": 2,
"align": "end"
}
]
},
],
"paddingBottom": "xxl"
},
{
"type": "box",
"layout": "vertical",
"contents": [
{
"type": "text",
"text": members_card_const.const.MESSAGE_THANKS[language], # noqa: E501
"wrap": True,
"size": "sm",
"color": "#767676"
}
]
},
{
"type": "box",
"layout": "vertical",
"contents": [
{
"type": "image",
"url": img_url,
"size": "lg"
}
],
"margin": "xxl"
}
],
"paddingTop": "0%"
},
"footer": {
"type": "box",
"layout": "vertical",
"spacing": "sm",
"contents": [
{
"type": "button",
"style": "link",
"height": "sm",
"action": {
"type": "uri",
"label": members_card_const.const.MESSAGE_VIEW[language], # noqa: E501
"uri": "https://liff.line.me/{liff_id}?lang={language}".format(liff_id=LIFF_ID, language=language) # noqa: E501
},
"color": "#0033cc"
},
{
"type": "spacer",
"size": "md"
}
],
"flex": 0
}
}
} | 0.417271 | 0.171165 |
import unittest
from vgio.quake.tests.basecase import TestCase
from vgio.quake import protocol
class TestProtocolReadWrite(TestCase):
def test_bad_message(self):
protocol.Bad.write(self.buff)
self.buff.seek(0)
protocol.Bad.read(self.buff)
def test_nop_message(self):
protocol.Nop.write(self.buff)
self.buff.seek(0)
protocol.Nop.read(self.buff)
def test_disconnect_message(self):
protocol.Disconnect.write(self.buff)
self.buff.seek(0)
protocol.Disconnect.read(self.buff)
def test_update_stat_message(self):
u0 = protocol.UpdateStat()
u0.index = 0
u0.value = 75
protocol.UpdateStat.write(self.buff, u0)
self.buff.seek(0)
u1 = protocol.UpdateStat.read(self.buff)
self.assertEqual(u0.index, u1.index,
'Update stat indexes should be equal')
self.assertEqual(u0.value, u1.value,
'Update stat values should be equal')
def test_version_message(self):
v0 = protocol.Version()
v0.protocol_version = 15
protocol.Version.write(self.buff, v0)
self.buff.seek(0)
v1 = protocol.Version.read(self.buff)
self.assertEqual(v0.protocol_version, v1.protocol_version,
'Protocol versions should be equal')
def test_set_view_message(self):
s0 = protocol.SetView()
s0.entity = 16
protocol.SetView.write(self.buff, s0)
self.buff.seek(0)
s1 = protocol.SetView.read(self.buff)
self.assertEqual(s0.entity, s1.entity, 'Entities should be equal')
def test_sound_message(self):
# No optional arguments
s0 = protocol.Sound()
s0.entity = 16
s0.channel = 2
s0.sound_number = 4
s0.origin = -512, 256, 2048
protocol.Sound.write(self.buff, s0)
self.buff.seek(0)
s1 = protocol.Sound.read(self.buff)
self.assertEqual(s0.entity, s1.entity, 'Entity should be equal')
self.assertEqual(s0.channel, s1.channel, 'Channel should be equal')
self.assertEqual(s0.sound_number, s1.sound_number,
'Sound number should be equal')
self.assertEqual(s0.origin, s1.origin, 'Origin should be equal')
self.clear_buffer()
# Both optional arguments
s0 = protocol.Sound()
s0.entity = 16
s0.channel = 2
s0.sound_number = 4
s0.origin = -512, 256, 2048
s0.attenuation = 0.5
s0.volume = 64
s0.bit_mask |= protocol.SND_ATTENUATION | protocol.SND_VOLUME
protocol.Sound.write(self.buff, s0)
self.buff.seek(0)
s1 = protocol.Sound.read(self.buff)
self.assertEqual(s0.entity, s1.entity, 'Entities should be equal')
self.assertEqual(s0.channel, s1.channel, 'Channels should be equal')
self.assertEqual(s0.sound_number, s1.sound_number,
'Sound numbers should be equal')
self.assertEqual(s0.origin, s1.origin, 'Origins should be equal')
self.assertEqual(s0.attenuation, s1.attenuation,
'Attenuations should be equal')
self.assertEqual(s0.volume, s1.volume, 'Volumes should be equal')
protocol.Sound.write(self.buff, s0)
self.buff.seek(0)
def test_time_message(self):
t0 = protocol.Time()
t0.time = 4.125
protocol.Time.write(self.buff, t0)
self.buff.seek(0)
t1 = protocol.Time.read(self.buff)
self.assertEqual(t0.time, t1.time, 'Should be equal')
def test_print_message(self):
p0 = protocol.Print()
p0.text = "This hall selects EASY skill"
protocol.Print.write(self.buff, p0)
self.buff.seek(0)
p1 = protocol.Print.read(self.buff)
self.assertEqual(p0.text, p1.text, 'Text values should be equal')
def test_stuff_text_message(self):
s0 = protocol.StuffText()
s0.text = "This hall selects NORMAL skill"
protocol.StuffText.write(self.buff, s0)
self.buff.seek(0)
s1 = protocol.StuffText.read(self.buff)
self.assertEqual(s0.text, s1.text, 'Text values should be equal')
def test_set_angle_message(self):
s0 = protocol.SetAngle()
s0.angles = 0, -90, 22.5
protocol.SetAngle.write(self.buff, s0)
self.buff.seek(0)
s1 = protocol.SetAngle.read(self.buff)
self.assertEqual(s0.angles, s1.angles, 'Angles should be equal')
def test_server_info_message(self):
s0 = protocol.ServerInfo()
s0.protocol_version = 15
s0.max_clients = 1
s0.multi = 0
s0.map_name = 'the Necropolis'
s0.models = 'maps/e1m3.bsp', 'progs/player.mdl'
s0.sounds = 'weapons/ric1.wav', 'weapons/ric2.wav'
protocol.ServerInfo.write(self.buff, s0)
self.buff.seek(0)
s1 = protocol.ServerInfo.read(self.buff)
self.assertEqual(s0.protocol_version, s1.protocol_version,
'Protocol versions should be equal')
self.assertEqual(s0.max_clients, s1.max_clients,
'Max clients should be equal')
self.assertEqual(s0.multi, s1.multi, 'Multi values should be equal')
self.assertEqual(s0.map_name, s1.map_name, 'Map names Should be equal')
self.assertEqual(s0.models, s1.models, 'Models should be equal')
self.assertEqual(s0.sounds, s1.sounds, 'Sounds should be equal')
def test_light_style_message(self):
l0 = protocol.LightStyle()
l0.style = 15
l0.string = 'azazaaazzz'
protocol.LightStyle.write(self.buff, l0)
self.buff.seek(0)
l1 = protocol.LightStyle.read(self.buff)
self.assertEqual(l0.style, l1.style, 'Styles should be equal')
self.assertEqual(l0.string, l1.string, 'Strings should be equal')
def test_update_name_message(self):
u0 = protocol.UpdateName()
u0.player = 0
u0.name = "Player"
protocol.UpdateName.write(self.buff, u0)
self.buff.seek(0)
u1 = protocol.UpdateName.read(self.buff)
self.assertEqual(u0.player, u1.player, 'Player values should be equal')
self.assertEqual(u0.name, u1.name, 'Names should be equal')
def test_update_frags_message(self):
u0 = protocol.UpdateFrags()
u0.player = 1
u0.frags = 100
protocol.UpdateFrags.write(self.buff, u0)
self.buff.seek(0)
u1 = protocol.UpdateFrags.read(self.buff)
self.assertEqual(u0.player, u1.player, 'Player values should be equal')
self.assertEqual(u0.frags, u1.frags, 'Frags should be equal')
def test_client_data_message(self):
c0 = protocol.ClientData()
c0.on_ground = True
c0.in_water = False
c0.health = 75
c0.active_ammo = 1
c0.ammo = 25, 0, 0, 0
c0.active_weapon = 16
protocol.ClientData.write(self.buff, c0)
self.buff.seek(0)
c1 = protocol.ClientData.read(self.buff)
self.assertEqual(c0.on_ground, c1.on_ground,
'On ground flags should be equal')
self.assertEqual(c0.in_water, c1.in_water,
'In water flags should be equal')
self.assertEqual(c0.health, c1.health, 'Health values should be equal')
self.assertEqual(c0.active_ammo, c1.active_ammo,
'Active ammo values should be equal')
self.assertEqual(c0.ammo, c1.ammo, 'Ammo counts should be equal')
self.assertEqual(c0.active_weapon, c1.active_weapon,
'Active weapons should be equal')
self.clear_buffer()
c0 = protocol.ClientData()
c0.bit_mask = 0b0111111111111111
c0.view_height = 18
c0.ideal_pitch = 45
c0.punch_angle = -22.5, 0, 90
c0.velocity = 0, 16, -32
c0.item_bit_mask = 0b01111111111111111111111111111111
c0.on_ground = True
c0.in_water = True
c0.weapon_frame = 8
c0.armor = 2
c0.weapon = 32
c0.health = 99
c0.active_ammo = 1
c0.ammo = 25, 0, 0, 0
c0.active_weapon = 16
protocol.ClientData.write(self.buff, c0)
self.buff.seek(0)
c1 = protocol.ClientData.read(self.buff)
self.assertEqual(c0.bit_mask, c1.bit_mask, 'Bit masks should be equal')
self.assertEqual(c0.view_height, c1.view_height,
'View heights should be equal')
self.assertEqual(c0.ideal_pitch, c1.ideal_pitch,
'Ideal pitches should be equal')
self.assertEqual(c0.punch_angle, c1.punch_angle,
'Punch angles should be equal')
self.assertEqual(c0.velocity, c1.velocity,
'Velocities should be equal')
self.assertEqual(c0.item_bit_mask, c1.item_bit_mask,
'Item bit masks should be equal')
self.assertEqual(c0.on_ground, c1.on_ground,
'On ground flags should be equal')
self.assertEqual(c0.in_water, c1.in_water,
'In water flags should be equal')
self.assertEqual(c0.weapon_frame, c1.weapon_frame,
'Weapon frames should be equal')
self.assertEqual(c0.armor, c1.armor, 'Armor values should be equal')
self.assertEqual(c0.weapon, c1.weapon, 'Weapon values should be equal')
self.assertEqual(c0.health, c1.health, 'Health values should be equal')
self.assertEqual(c0.active_ammo, c1.active_ammo,
'Active ammo values should be equal')
self.assertEqual(c0.ammo, c1.ammo, 'Ammo values should be equal')
self.assertEqual(c0.active_weapon, c1.active_weapon,
'Active weapon values should be equal')
def test_stop_sound_message(self):
s0 = protocol.StopSound()
s0.channel = 2
s0.entity = 64
protocol.StopSound.write(self.buff, s0)
self.buff.seek(0)
s1 = protocol.StopSound.read(self.buff)
self.assertEqual(s0.channel, s1.channel, 'Channels should be equal')
self.assertEqual(s0.entity, s1.entity, 'Entities should be equal')
def test_update_colors_message(self):
u0 = protocol.UpdateColors()
u0.player = 1
u0.colors = 0b00010001
protocol.UpdateColors.write(self.buff, u0)
self.buff.seek(0)
u1 = protocol.UpdateColors.read(self.buff)
self.assertEqual(u0.player, u1.player, 'Player values should be equal')
self.assertEqual(u0.colors, u1.colors, 'Colors values should be equal')
def test_particle_message(self):
p0 = protocol.Particle()
p0.origin = 0, 16, -1024
p0.direction = 0, 1, 2
p0.count = 8
p0.color = 73
protocol.Particle.write(self.buff, p0)
self.buff.seek(0)
p1 = protocol.Particle.read(self.buff)
self.assertEqual(p0.origin, p1.origin, 'Origin should be equal')
self.assertEqual(p0.direction, p1.direction,
'Direction should be equal')
self.assertEqual(p0.count, p1.count, 'Count should be equal')
self.assertEqual(p0.color, p1.color, 'Color should be equal')
def test_damage_message(self):
d0 = protocol.Damage()
d0.armor = 8
d0.blood = 4
d0.origin = 0, 16, -512
protocol.Damage.write(self.buff, d0)
self.buff.seek(0)
d1 = protocol.Damage.read(self.buff)
self.assertEqual(d0.armor, d1.armor, 'Armor values should be equal')
self.assertEqual(d0.blood, d1.blood, 'Blood values should be equal')
self.assertEqual(d0.origin, d1.origin, 'Origins should be equal')
def test_spawn_static_message(self):
s0 = protocol.SpawnStatic()
s0.model_index = 127
s0.frame = 8
s0.color_map = 1
s0.skin = 2
s0.origin = 0, -32, 1600
s0.angles = 22.5, 0, -45
protocol.SpawnStatic.write(self.buff, s0)
self.buff.seek(0)
s1 = protocol.SpawnStatic.read(self.buff)
self.assertEqual(s0.model_index, s1.model_index,
'Model indices should be equal')
self.assertEqual(s0.frame, s1.frame, 'Frames should be equal')
self.assertEqual(s0.color_map, s1.color_map,
'Color maps should be equal')
self.assertEqual(s0.skin, s1.skin, 'Skins should be equal')
self.assertEqual(s0.origin, s1.origin, 'Origins should be equal')
self.assertEqual(s0.angles, s1.angles, 'Angles should be equal')
def test_spawn_binary_message(self):
with self.assertRaises(protocol.BadMessage):
protocol.SpawnBinary.write(self.buff)
with self.assertRaises(protocol.BadMessage):
protocol.SpawnBinary.read(self.buff)
def test_spawn_baseline_message(self):
s0 = protocol.SpawnBaseline()
s0.entity = 10
s0.model_index = 127
s0.frame = 8
s0.color_map = 1
s0.skin = 2
s0.origin = 0, -32, 1600
s0.angles = 22.5, 0, -45
protocol.SpawnBaseline.write(self.buff, s0)
self.buff.seek(0)
s1 = protocol.SpawnBaseline.read(self.buff)
self.assertEqual(s0.entity, s1.entity, 'Entities should be equal')
self.assertEqual(s0.model_index, s1.model_index,
'Model indices should be equal')
self.assertEqual(s0.frame, s1.frame, 'Frames should be equal')
self.assertEqual(s0.color_map, s1.color_map,
'Color maps should be equal')
self.assertEqual(s0.skin, s1.skin, 'Skins should be equal')
self.assertEqual(s0.origin, s1.origin, 'Origins should be equal')
self.assertEqual(s0.angles, s1.angles, 'Angles should be equal')
def test_temp_entity_message(self):
t0 = protocol.TempEntity()
t0.type = protocol.TE_WIZSPIKE
t0.origin = 0, 128, -768
protocol.TempEntity.write(self.buff, t0)
self.buff.seek(0)
t1 = protocol.TempEntity.read(self.buff)
self.assertEqual(t0.type, t1.type, 'Types should be equal')
self.assertEqual(t0.origin, t1.origin, 'Origins should be equal')
self.clear_buffer()
t0 = protocol.TempEntity()
t0.type = protocol.TE_LIGHTNING1
t0.entity = 8
t0.start = 0, 0, 0
t0.end = 16, -96, 2048
protocol.TempEntity.write(self.buff, t0)
self.buff.seek(0)
t1 = protocol.TempEntity.read(self.buff)
self.assertEqual(t0.type, t1.type, 'Types should be equal')
self.assertEqual(t0.entity, t1.entity, 'Entity values should be equal')
self.assertEqual(t0.start, t1.start, 'Start vectors should be equal')
self.assertEqual(t0.end, t1.end, 'End vectors should be equal')
self.clear_buffer()
t0 = protocol.TempEntity()
t0.type = protocol.TE_EXPLOSION2
t0.origin = 0, 128, -768
t0.color_start = 0
t0.color_length = 16
protocol.TempEntity.write(self.buff, t0)
self.buff.seek(0)
t1 = protocol.TempEntity.read(self.buff)
self.assertEqual(t0.type, t1.type, 'Types should be equal')
self.assertEqual(t0.origin, t1.origin, 'Origins should be equal')
self.assertEqual(t0.color_start, t1.color_start,
'Color start values should be equal')
self.assertEqual(t0.color_length, t1.color_length,
'Color length values should be equal')
self.clear_buffer()
with self.assertRaises(protocol.BadMessage):
t0 = protocol.TempEntity()
t0.type = 14
protocol.TempEntity.write(self.buff, t0)
self.clear_buffer()
with self.assertRaises(protocol.BadMessage):
self.buff.write(b'\x17\x0e')
self.buff.seek(0)
protocol.TempEntity.read(self.buff)
def test_set_pause_message(self):
s0 = protocol.SetPause()
s0.paused = 1
protocol.SetPause.write(self.buff, s0)
self.buff.seek(0)
s1 = protocol.SetPause.read(self.buff)
self.assertEqual(s0.paused, s1.paused, 'Paused values should be equal')
def test_sign_on_num_message(self):
s0 = protocol.SignOnNum()
s0.sign_on = 1
protocol.SignOnNum.write(self.buff, s0)
self.buff.seek(0)
s1 = protocol.SignOnNum.read(self.buff)
self.assertEqual(s0.sign_on, s1.sign_on,
'Sign on values should be equal')
def test_center_print_message(self):
c0 = protocol.CenterPrint()
c0.text = 'This hall selects HARD skill'
protocol.CenterPrint.write(self.buff, c0)
self.buff.seek(0)
c1 = protocol.CenterPrint.read(self.buff)
self.assertEqual(c0.text, c1.text, 'Text values should be equal')
def test_killed_monster_message(self):
protocol.KilledMonster.write(self.buff)
self.buff.seek(0)
protocol.KilledMonster.read(self.buff)
def test_found_secret_message(self):
protocol.FoundSecret.write(self.buff)
self.buff.seek(0)
protocol.FoundSecret.read(self.buff)
def test_spawn_static_sound_message(self):
s0 = protocol.SpawnStaticSound()
s0.origin = 0, -32, 1096
s0.sound_number = 2
s0.volume = 0.5
s0.attenuation = 0.25
protocol.SpawnStaticSound.write(self.buff, s0)
self.buff.seek(0)
s1 = protocol.SpawnStaticSound.read(self.buff)
self.assertEqual(s0.origin, s1.origin, 'Origins should be equal')
self.assertEqual(s0.sound_number, s1.sound_number,
'Sound numbers should be equal')
self.assertEqual(s0.volume, s1.volume, 'Volume values should be equal')
self.assertEqual(s0.attenuation, s1.attenuation,
'Attenuation values should be equal')
def test_intermission_message(self):
protocol.Intermission.write(self.buff)
self.buff.seek(0)
protocol.Intermission.read(self.buff)
def test_finale_message(self):
f0 = protocol.Finale()
f0.text = 'Game Over'
protocol.Finale.write(self.buff, f0)
self.buff.seek(0)
f1 = protocol.Finale.read(self.buff)
self.assertEqual(f0.text, f1.text, 'Should be equal')
def test_cd_track_message(self):
c0 = protocol.CdTrack()
c0.from_track = 2
c0.to_track = 3
protocol.CdTrack.write(self.buff, c0)
self.buff.seek(0)
c1 = protocol.CdTrack.read(self.buff)
self.assertEqual(c0.from_track, c1.from_track,
'From track values should be equal')
self.assertEqual(c0.to_track, c1.to_track, 'To track should be equal')
def test_sell_screen_message(self):
protocol.SellScreen.write(self.buff)
self.buff.seek(0)
protocol.SellScreen.read(self.buff)
def test_cut_scene_message(self):
c0 = protocol.CutScene()
c0.text = 'Cut scene'
protocol.CutScene.write(self.buff, c0)
self.buff.seek(0)
c1 = protocol.CutScene.read(self.buff)
self.assertEqual(c0.text, c1.text, 'Text values should be equal')
def test_update_entity_message(self):
# Quick update
u0 = protocol.UpdateEntity()
u0.bit_mask |= protocol.U_ORIGIN1 | protocol.U_ORIGIN2 | protocol.U_ORIGIN3 | protocol.U_ANGLE2 | protocol.U_FRAME
u0.entity = 4
u0.origin = u0.origin = 128.5, 250, -980
u0.angles = None, 90, None
u0.frame = 1
protocol.UpdateEntity.write(self.buff, u0)
self.buff.seek(0)
u1 = protocol.UpdateEntity.read(self.buff)
self.assertEqual(u0.bit_mask, u1.bit_mask, 'Bit masks should be equal')
self.assertEqual(u0.entity, u1.entity, 'Entities should be equal')
self.assertEqual(u0.origin, u1.origin, 'Origins should be equal')
self.assertEqual(u0.angles, u1.angles, 'Angles should be equal')
self.assertEqual(u0.frame, u1.frame, 'Frames should be equal')
self.clear_buffer()
# Full update
u0 = protocol.UpdateEntity()
u0.bit_mask |= 0x7F7F
u0.entity = 4
u0.model_index = 8
u0.frame = 0
u0.colormap = 1
u0.skin = 2
u0.effects = 3
u0.origin = 128.5, 250, -980
u0.angles = 22.5, 0, -90
protocol.UpdateEntity.write(self.buff, u0)
self.buff.seek(0)
u1 = protocol.UpdateEntity.read(self.buff)
self.assertEqual(u0.bit_mask, u1.bit_mask, 'Bit masks should be equal')
self.assertEqual(u0.entity, u1.entity, 'Entities should be equal')
self.assertEqual(u0.model_index, u1.model_index,
'Models should be equal')
self.assertEqual(u0.frame, u1.frame, 'Frames should be equal')
self.assertEqual(u0.colormap, u1.colormap, 'Colormaps should be equal')
self.assertEqual(u0.skin, u1.skin, 'Skins should be equal')
self.assertEqual(u0.effects, u1.effects, 'Effects should be equal')
self.assertEqual(u0.origin, u1.origin, 'Origins should be equal')
self.assertEqual(u0.angles, u1.angles, 'Angles should be equal')
if __name__ == '__main__':
unittest.main() | vgio/quake/tests/test_protocol.py | import unittest
from vgio.quake.tests.basecase import TestCase
from vgio.quake import protocol
class TestProtocolReadWrite(TestCase):
def test_bad_message(self):
protocol.Bad.write(self.buff)
self.buff.seek(0)
protocol.Bad.read(self.buff)
def test_nop_message(self):
protocol.Nop.write(self.buff)
self.buff.seek(0)
protocol.Nop.read(self.buff)
def test_disconnect_message(self):
protocol.Disconnect.write(self.buff)
self.buff.seek(0)
protocol.Disconnect.read(self.buff)
def test_update_stat_message(self):
u0 = protocol.UpdateStat()
u0.index = 0
u0.value = 75
protocol.UpdateStat.write(self.buff, u0)
self.buff.seek(0)
u1 = protocol.UpdateStat.read(self.buff)
self.assertEqual(u0.index, u1.index,
'Update stat indexes should be equal')
self.assertEqual(u0.value, u1.value,
'Update stat values should be equal')
def test_version_message(self):
v0 = protocol.Version()
v0.protocol_version = 15
protocol.Version.write(self.buff, v0)
self.buff.seek(0)
v1 = protocol.Version.read(self.buff)
self.assertEqual(v0.protocol_version, v1.protocol_version,
'Protocol versions should be equal')
def test_set_view_message(self):
s0 = protocol.SetView()
s0.entity = 16
protocol.SetView.write(self.buff, s0)
self.buff.seek(0)
s1 = protocol.SetView.read(self.buff)
self.assertEqual(s0.entity, s1.entity, 'Entities should be equal')
def test_sound_message(self):
# No optional arguments
s0 = protocol.Sound()
s0.entity = 16
s0.channel = 2
s0.sound_number = 4
s0.origin = -512, 256, 2048
protocol.Sound.write(self.buff, s0)
self.buff.seek(0)
s1 = protocol.Sound.read(self.buff)
self.assertEqual(s0.entity, s1.entity, 'Entity should be equal')
self.assertEqual(s0.channel, s1.channel, 'Channel should be equal')
self.assertEqual(s0.sound_number, s1.sound_number,
'Sound number should be equal')
self.assertEqual(s0.origin, s1.origin, 'Origin should be equal')
self.clear_buffer()
# Both optional arguments
s0 = protocol.Sound()
s0.entity = 16
s0.channel = 2
s0.sound_number = 4
s0.origin = -512, 256, 2048
s0.attenuation = 0.5
s0.volume = 64
s0.bit_mask |= protocol.SND_ATTENUATION | protocol.SND_VOLUME
protocol.Sound.write(self.buff, s0)
self.buff.seek(0)
s1 = protocol.Sound.read(self.buff)
self.assertEqual(s0.entity, s1.entity, 'Entities should be equal')
self.assertEqual(s0.channel, s1.channel, 'Channels should be equal')
self.assertEqual(s0.sound_number, s1.sound_number,
'Sound numbers should be equal')
self.assertEqual(s0.origin, s1.origin, 'Origins should be equal')
self.assertEqual(s0.attenuation, s1.attenuation,
'Attenuations should be equal')
self.assertEqual(s0.volume, s1.volume, 'Volumes should be equal')
protocol.Sound.write(self.buff, s0)
self.buff.seek(0)
def test_time_message(self):
t0 = protocol.Time()
t0.time = 4.125
protocol.Time.write(self.buff, t0)
self.buff.seek(0)
t1 = protocol.Time.read(self.buff)
self.assertEqual(t0.time, t1.time, 'Should be equal')
def test_print_message(self):
p0 = protocol.Print()
p0.text = "This hall selects EASY skill"
protocol.Print.write(self.buff, p0)
self.buff.seek(0)
p1 = protocol.Print.read(self.buff)
self.assertEqual(p0.text, p1.text, 'Text values should be equal')
def test_stuff_text_message(self):
s0 = protocol.StuffText()
s0.text = "This hall selects NORMAL skill"
protocol.StuffText.write(self.buff, s0)
self.buff.seek(0)
s1 = protocol.StuffText.read(self.buff)
self.assertEqual(s0.text, s1.text, 'Text values should be equal')
def test_set_angle_message(self):
s0 = protocol.SetAngle()
s0.angles = 0, -90, 22.5
protocol.SetAngle.write(self.buff, s0)
self.buff.seek(0)
s1 = protocol.SetAngle.read(self.buff)
self.assertEqual(s0.angles, s1.angles, 'Angles should be equal')
def test_server_info_message(self):
s0 = protocol.ServerInfo()
s0.protocol_version = 15
s0.max_clients = 1
s0.multi = 0
s0.map_name = 'the Necropolis'
s0.models = 'maps/e1m3.bsp', 'progs/player.mdl'
s0.sounds = 'weapons/ric1.wav', 'weapons/ric2.wav'
protocol.ServerInfo.write(self.buff, s0)
self.buff.seek(0)
s1 = protocol.ServerInfo.read(self.buff)
self.assertEqual(s0.protocol_version, s1.protocol_version,
'Protocol versions should be equal')
self.assertEqual(s0.max_clients, s1.max_clients,
'Max clients should be equal')
self.assertEqual(s0.multi, s1.multi, 'Multi values should be equal')
self.assertEqual(s0.map_name, s1.map_name, 'Map names Should be equal')
self.assertEqual(s0.models, s1.models, 'Models should be equal')
self.assertEqual(s0.sounds, s1.sounds, 'Sounds should be equal')
def test_light_style_message(self):
l0 = protocol.LightStyle()
l0.style = 15
l0.string = 'azazaaazzz'
protocol.LightStyle.write(self.buff, l0)
self.buff.seek(0)
l1 = protocol.LightStyle.read(self.buff)
self.assertEqual(l0.style, l1.style, 'Styles should be equal')
self.assertEqual(l0.string, l1.string, 'Strings should be equal')
def test_update_name_message(self):
u0 = protocol.UpdateName()
u0.player = 0
u0.name = "Player"
protocol.UpdateName.write(self.buff, u0)
self.buff.seek(0)
u1 = protocol.UpdateName.read(self.buff)
self.assertEqual(u0.player, u1.player, 'Player values should be equal')
self.assertEqual(u0.name, u1.name, 'Names should be equal')
def test_update_frags_message(self):
u0 = protocol.UpdateFrags()
u0.player = 1
u0.frags = 100
protocol.UpdateFrags.write(self.buff, u0)
self.buff.seek(0)
u1 = protocol.UpdateFrags.read(self.buff)
self.assertEqual(u0.player, u1.player, 'Player values should be equal')
self.assertEqual(u0.frags, u1.frags, 'Frags should be equal')
def test_client_data_message(self):
c0 = protocol.ClientData()
c0.on_ground = True
c0.in_water = False
c0.health = 75
c0.active_ammo = 1
c0.ammo = 25, 0, 0, 0
c0.active_weapon = 16
protocol.ClientData.write(self.buff, c0)
self.buff.seek(0)
c1 = protocol.ClientData.read(self.buff)
self.assertEqual(c0.on_ground, c1.on_ground,
'On ground flags should be equal')
self.assertEqual(c0.in_water, c1.in_water,
'In water flags should be equal')
self.assertEqual(c0.health, c1.health, 'Health values should be equal')
self.assertEqual(c0.active_ammo, c1.active_ammo,
'Active ammo values should be equal')
self.assertEqual(c0.ammo, c1.ammo, 'Ammo counts should be equal')
self.assertEqual(c0.active_weapon, c1.active_weapon,
'Active weapons should be equal')
self.clear_buffer()
c0 = protocol.ClientData()
c0.bit_mask = 0b0111111111111111
c0.view_height = 18
c0.ideal_pitch = 45
c0.punch_angle = -22.5, 0, 90
c0.velocity = 0, 16, -32
c0.item_bit_mask = 0b01111111111111111111111111111111
c0.on_ground = True
c0.in_water = True
c0.weapon_frame = 8
c0.armor = 2
c0.weapon = 32
c0.health = 99
c0.active_ammo = 1
c0.ammo = 25, 0, 0, 0
c0.active_weapon = 16
protocol.ClientData.write(self.buff, c0)
self.buff.seek(0)
c1 = protocol.ClientData.read(self.buff)
self.assertEqual(c0.bit_mask, c1.bit_mask, 'Bit masks should be equal')
self.assertEqual(c0.view_height, c1.view_height,
'View heights should be equal')
self.assertEqual(c0.ideal_pitch, c1.ideal_pitch,
'Ideal pitches should be equal')
self.assertEqual(c0.punch_angle, c1.punch_angle,
'Punch angles should be equal')
self.assertEqual(c0.velocity, c1.velocity,
'Velocities should be equal')
self.assertEqual(c0.item_bit_mask, c1.item_bit_mask,
'Item bit masks should be equal')
self.assertEqual(c0.on_ground, c1.on_ground,
'On ground flags should be equal')
self.assertEqual(c0.in_water, c1.in_water,
'In water flags should be equal')
self.assertEqual(c0.weapon_frame, c1.weapon_frame,
'Weapon frames should be equal')
self.assertEqual(c0.armor, c1.armor, 'Armor values should be equal')
self.assertEqual(c0.weapon, c1.weapon, 'Weapon values should be equal')
self.assertEqual(c0.health, c1.health, 'Health values should be equal')
self.assertEqual(c0.active_ammo, c1.active_ammo,
'Active ammo values should be equal')
self.assertEqual(c0.ammo, c1.ammo, 'Ammo values should be equal')
self.assertEqual(c0.active_weapon, c1.active_weapon,
'Active weapon values should be equal')
def test_stop_sound_message(self):
s0 = protocol.StopSound()
s0.channel = 2
s0.entity = 64
protocol.StopSound.write(self.buff, s0)
self.buff.seek(0)
s1 = protocol.StopSound.read(self.buff)
self.assertEqual(s0.channel, s1.channel, 'Channels should be equal')
self.assertEqual(s0.entity, s1.entity, 'Entities should be equal')
def test_update_colors_message(self):
u0 = protocol.UpdateColors()
u0.player = 1
u0.colors = 0b00010001
protocol.UpdateColors.write(self.buff, u0)
self.buff.seek(0)
u1 = protocol.UpdateColors.read(self.buff)
self.assertEqual(u0.player, u1.player, 'Player values should be equal')
self.assertEqual(u0.colors, u1.colors, 'Colors values should be equal')
def test_particle_message(self):
p0 = protocol.Particle()
p0.origin = 0, 16, -1024
p0.direction = 0, 1, 2
p0.count = 8
p0.color = 73
protocol.Particle.write(self.buff, p0)
self.buff.seek(0)
p1 = protocol.Particle.read(self.buff)
self.assertEqual(p0.origin, p1.origin, 'Origin should be equal')
self.assertEqual(p0.direction, p1.direction,
'Direction should be equal')
self.assertEqual(p0.count, p1.count, 'Count should be equal')
self.assertEqual(p0.color, p1.color, 'Color should be equal')
def test_damage_message(self):
d0 = protocol.Damage()
d0.armor = 8
d0.blood = 4
d0.origin = 0, 16, -512
protocol.Damage.write(self.buff, d0)
self.buff.seek(0)
d1 = protocol.Damage.read(self.buff)
self.assertEqual(d0.armor, d1.armor, 'Armor values should be equal')
self.assertEqual(d0.blood, d1.blood, 'Blood values should be equal')
self.assertEqual(d0.origin, d1.origin, 'Origins should be equal')
def test_spawn_static_message(self):
s0 = protocol.SpawnStatic()
s0.model_index = 127
s0.frame = 8
s0.color_map = 1
s0.skin = 2
s0.origin = 0, -32, 1600
s0.angles = 22.5, 0, -45
protocol.SpawnStatic.write(self.buff, s0)
self.buff.seek(0)
s1 = protocol.SpawnStatic.read(self.buff)
self.assertEqual(s0.model_index, s1.model_index,
'Model indices should be equal')
self.assertEqual(s0.frame, s1.frame, 'Frames should be equal')
self.assertEqual(s0.color_map, s1.color_map,
'Color maps should be equal')
self.assertEqual(s0.skin, s1.skin, 'Skins should be equal')
self.assertEqual(s0.origin, s1.origin, 'Origins should be equal')
self.assertEqual(s0.angles, s1.angles, 'Angles should be equal')
def test_spawn_binary_message(self):
with self.assertRaises(protocol.BadMessage):
protocol.SpawnBinary.write(self.buff)
with self.assertRaises(protocol.BadMessage):
protocol.SpawnBinary.read(self.buff)
def test_spawn_baseline_message(self):
s0 = protocol.SpawnBaseline()
s0.entity = 10
s0.model_index = 127
s0.frame = 8
s0.color_map = 1
s0.skin = 2
s0.origin = 0, -32, 1600
s0.angles = 22.5, 0, -45
protocol.SpawnBaseline.write(self.buff, s0)
self.buff.seek(0)
s1 = protocol.SpawnBaseline.read(self.buff)
self.assertEqual(s0.entity, s1.entity, 'Entities should be equal')
self.assertEqual(s0.model_index, s1.model_index,
'Model indices should be equal')
self.assertEqual(s0.frame, s1.frame, 'Frames should be equal')
self.assertEqual(s0.color_map, s1.color_map,
'Color maps should be equal')
self.assertEqual(s0.skin, s1.skin, 'Skins should be equal')
self.assertEqual(s0.origin, s1.origin, 'Origins should be equal')
self.assertEqual(s0.angles, s1.angles, 'Angles should be equal')
def test_temp_entity_message(self):
t0 = protocol.TempEntity()
t0.type = protocol.TE_WIZSPIKE
t0.origin = 0, 128, -768
protocol.TempEntity.write(self.buff, t0)
self.buff.seek(0)
t1 = protocol.TempEntity.read(self.buff)
self.assertEqual(t0.type, t1.type, 'Types should be equal')
self.assertEqual(t0.origin, t1.origin, 'Origins should be equal')
self.clear_buffer()
t0 = protocol.TempEntity()
t0.type = protocol.TE_LIGHTNING1
t0.entity = 8
t0.start = 0, 0, 0
t0.end = 16, -96, 2048
protocol.TempEntity.write(self.buff, t0)
self.buff.seek(0)
t1 = protocol.TempEntity.read(self.buff)
self.assertEqual(t0.type, t1.type, 'Types should be equal')
self.assertEqual(t0.entity, t1.entity, 'Entity values should be equal')
self.assertEqual(t0.start, t1.start, 'Start vectors should be equal')
self.assertEqual(t0.end, t1.end, 'End vectors should be equal')
self.clear_buffer()
t0 = protocol.TempEntity()
t0.type = protocol.TE_EXPLOSION2
t0.origin = 0, 128, -768
t0.color_start = 0
t0.color_length = 16
protocol.TempEntity.write(self.buff, t0)
self.buff.seek(0)
t1 = protocol.TempEntity.read(self.buff)
self.assertEqual(t0.type, t1.type, 'Types should be equal')
self.assertEqual(t0.origin, t1.origin, 'Origins should be equal')
self.assertEqual(t0.color_start, t1.color_start,
'Color start values should be equal')
self.assertEqual(t0.color_length, t1.color_length,
'Color length values should be equal')
self.clear_buffer()
with self.assertRaises(protocol.BadMessage):
t0 = protocol.TempEntity()
t0.type = 14
protocol.TempEntity.write(self.buff, t0)
self.clear_buffer()
with self.assertRaises(protocol.BadMessage):
self.buff.write(b'\x17\x0e')
self.buff.seek(0)
protocol.TempEntity.read(self.buff)
def test_set_pause_message(self):
s0 = protocol.SetPause()
s0.paused = 1
protocol.SetPause.write(self.buff, s0)
self.buff.seek(0)
s1 = protocol.SetPause.read(self.buff)
self.assertEqual(s0.paused, s1.paused, 'Paused values should be equal')
def test_sign_on_num_message(self):
s0 = protocol.SignOnNum()
s0.sign_on = 1
protocol.SignOnNum.write(self.buff, s0)
self.buff.seek(0)
s1 = protocol.SignOnNum.read(self.buff)
self.assertEqual(s0.sign_on, s1.sign_on,
'Sign on values should be equal')
def test_center_print_message(self):
c0 = protocol.CenterPrint()
c0.text = 'This hall selects HARD skill'
protocol.CenterPrint.write(self.buff, c0)
self.buff.seek(0)
c1 = protocol.CenterPrint.read(self.buff)
self.assertEqual(c0.text, c1.text, 'Text values should be equal')
def test_killed_monster_message(self):
protocol.KilledMonster.write(self.buff)
self.buff.seek(0)
protocol.KilledMonster.read(self.buff)
def test_found_secret_message(self):
protocol.FoundSecret.write(self.buff)
self.buff.seek(0)
protocol.FoundSecret.read(self.buff)
def test_spawn_static_sound_message(self):
s0 = protocol.SpawnStaticSound()
s0.origin = 0, -32, 1096
s0.sound_number = 2
s0.volume = 0.5
s0.attenuation = 0.25
protocol.SpawnStaticSound.write(self.buff, s0)
self.buff.seek(0)
s1 = protocol.SpawnStaticSound.read(self.buff)
self.assertEqual(s0.origin, s1.origin, 'Origins should be equal')
self.assertEqual(s0.sound_number, s1.sound_number,
'Sound numbers should be equal')
self.assertEqual(s0.volume, s1.volume, 'Volume values should be equal')
self.assertEqual(s0.attenuation, s1.attenuation,
'Attenuation values should be equal')
def test_intermission_message(self):
protocol.Intermission.write(self.buff)
self.buff.seek(0)
protocol.Intermission.read(self.buff)
def test_finale_message(self):
f0 = protocol.Finale()
f0.text = 'Game Over'
protocol.Finale.write(self.buff, f0)
self.buff.seek(0)
f1 = protocol.Finale.read(self.buff)
self.assertEqual(f0.text, f1.text, 'Should be equal')
def test_cd_track_message(self):
c0 = protocol.CdTrack()
c0.from_track = 2
c0.to_track = 3
protocol.CdTrack.write(self.buff, c0)
self.buff.seek(0)
c1 = protocol.CdTrack.read(self.buff)
self.assertEqual(c0.from_track, c1.from_track,
'From track values should be equal')
self.assertEqual(c0.to_track, c1.to_track, 'To track should be equal')
def test_sell_screen_message(self):
protocol.SellScreen.write(self.buff)
self.buff.seek(0)
protocol.SellScreen.read(self.buff)
def test_cut_scene_message(self):
c0 = protocol.CutScene()
c0.text = 'Cut scene'
protocol.CutScene.write(self.buff, c0)
self.buff.seek(0)
c1 = protocol.CutScene.read(self.buff)
self.assertEqual(c0.text, c1.text, 'Text values should be equal')
def test_update_entity_message(self):
# Quick update
u0 = protocol.UpdateEntity()
u0.bit_mask |= protocol.U_ORIGIN1 | protocol.U_ORIGIN2 | protocol.U_ORIGIN3 | protocol.U_ANGLE2 | protocol.U_FRAME
u0.entity = 4
u0.origin = u0.origin = 128.5, 250, -980
u0.angles = None, 90, None
u0.frame = 1
protocol.UpdateEntity.write(self.buff, u0)
self.buff.seek(0)
u1 = protocol.UpdateEntity.read(self.buff)
self.assertEqual(u0.bit_mask, u1.bit_mask, 'Bit masks should be equal')
self.assertEqual(u0.entity, u1.entity, 'Entities should be equal')
self.assertEqual(u0.origin, u1.origin, 'Origins should be equal')
self.assertEqual(u0.angles, u1.angles, 'Angles should be equal')
self.assertEqual(u0.frame, u1.frame, 'Frames should be equal')
self.clear_buffer()
# Full update
u0 = protocol.UpdateEntity()
u0.bit_mask |= 0x7F7F
u0.entity = 4
u0.model_index = 8
u0.frame = 0
u0.colormap = 1
u0.skin = 2
u0.effects = 3
u0.origin = 128.5, 250, -980
u0.angles = 22.5, 0, -90
protocol.UpdateEntity.write(self.buff, u0)
self.buff.seek(0)
u1 = protocol.UpdateEntity.read(self.buff)
self.assertEqual(u0.bit_mask, u1.bit_mask, 'Bit masks should be equal')
self.assertEqual(u0.entity, u1.entity, 'Entities should be equal')
self.assertEqual(u0.model_index, u1.model_index,
'Models should be equal')
self.assertEqual(u0.frame, u1.frame, 'Frames should be equal')
self.assertEqual(u0.colormap, u1.colormap, 'Colormaps should be equal')
self.assertEqual(u0.skin, u1.skin, 'Skins should be equal')
self.assertEqual(u0.effects, u1.effects, 'Effects should be equal')
self.assertEqual(u0.origin, u1.origin, 'Origins should be equal')
self.assertEqual(u0.angles, u1.angles, 'Angles should be equal')
if __name__ == '__main__':
unittest.main() | 0.588061 | 0.210807 |
from .client import Client
class Ftp(Client):
"""Ftp管理
"""
def web_ftp_list(self, page='1', limit='15', type='-1', order='id desc', tojs='', search=''):
"""获取网站FTP列表
Args:
page (str, optional): 当前分页. Defaults to '1'.
limit (str, optional): 取出的数据行数. Defaults to '15'.
type (str, optional): 分类标识 -1: 分部分类 0: 默认分类. Defaults to '-1'.
order (str, optional): 排序规则 使用 id 降序:id desc 使用名称升序:name desc. Defaults to 'id desc'.
tojs (str, optional): 分页 JS 回调,若不传则构造 URI 分页连接. Defaults to ''.
search (str, optional): 搜索内容. Defaults to ''.
"""
endpoint = self.config["WebFtpList"]
data = {}
data['p'] = page
data['limit'] = limit
data['type'] = type
data['order'] = order
data['tojs'] = tojs
data['search'] = search
return self.post_data(endpoint, data=data)
def get_ftp_id(self, ftp_username):
"""根据Ftp_Username获取FTPID
Args:
ftp_username (str): 用户名
"""
data = self.web_ftp_list()
for i in data['data']:
if i['name'] == ftp_username:
return i['id']
return -1
def set_user_password(self, ftp_username, new_password):
"""修改FTP账号密码
Args:
ftp_username (str): 用户名
new_password (str): 密码
"""
endpoint = self.config["SetUserPassword"]
data = {}
data["id"] = self.__get_ftp_id(ftp_username)
data["ftp_username"] = ftp_username
data["new_password"] = <PASSWORD>
return self.post_data(endpoint, data=data)
def set_status(self, ftp_username, status):
"""启用/禁用FTP
ftp_username
status
Args:
ftp_username (str): 用户名
status (str): 状态 0->关闭;1->开启
"""
endpoint = self.config["SetStatus"]
data = {}
data["id"] = self.get_ftp_id(ftp_username)
data["username"] = ftp_username
data["status"] = status
return self.post_data(endpoint, data=data) | pybt/ftp.py | from .client import Client
class Ftp(Client):
"""Ftp管理
"""
def web_ftp_list(self, page='1', limit='15', type='-1', order='id desc', tojs='', search=''):
"""获取网站FTP列表
Args:
page (str, optional): 当前分页. Defaults to '1'.
limit (str, optional): 取出的数据行数. Defaults to '15'.
type (str, optional): 分类标识 -1: 分部分类 0: 默认分类. Defaults to '-1'.
order (str, optional): 排序规则 使用 id 降序:id desc 使用名称升序:name desc. Defaults to 'id desc'.
tojs (str, optional): 分页 JS 回调,若不传则构造 URI 分页连接. Defaults to ''.
search (str, optional): 搜索内容. Defaults to ''.
"""
endpoint = self.config["WebFtpList"]
data = {}
data['p'] = page
data['limit'] = limit
data['type'] = type
data['order'] = order
data['tojs'] = tojs
data['search'] = search
return self.post_data(endpoint, data=data)
def get_ftp_id(self, ftp_username):
"""根据Ftp_Username获取FTPID
Args:
ftp_username (str): 用户名
"""
data = self.web_ftp_list()
for i in data['data']:
if i['name'] == ftp_username:
return i['id']
return -1
def set_user_password(self, ftp_username, new_password):
"""修改FTP账号密码
Args:
ftp_username (str): 用户名
new_password (str): 密码
"""
endpoint = self.config["SetUserPassword"]
data = {}
data["id"] = self.__get_ftp_id(ftp_username)
data["ftp_username"] = ftp_username
data["new_password"] = <PASSWORD>
return self.post_data(endpoint, data=data)
def set_status(self, ftp_username, status):
"""启用/禁用FTP
ftp_username
status
Args:
ftp_username (str): 用户名
status (str): 状态 0->关闭;1->开启
"""
endpoint = self.config["SetStatus"]
data = {}
data["id"] = self.get_ftp_id(ftp_username)
data["username"] = ftp_username
data["status"] = status
return self.post_data(endpoint, data=data) | 0.403214 | 0.208864 |
def get_CUDA(vectorSize = 10, momentums = [0.,0.], shifts = [0.35,0.65], sigmas = [0.05, 0.05] , **kwargs):
if len(shifts)%2==1:
print "Must have even number of wavefunctions (pairs). Quitting..."
quit()
if (len(momentums)!= len(shifts)) or (len(momentums)!= len(sigmas)) or (len(shifts)!= len(sigmas)):
print "Input arrays must have the same length. Quitting..."
quit()
variableString = """"""
for i in xrange(len(shifts)):
variableString += """double sigma""" + str(i) + """ = """ + str(sigmas[i]) + r"""*Qx/2.;
double shift""" + str(i) + """ = """ + str(shifts[i]) + r"""*Qx/2.;
double p""" + str(i) + """ = """ + str(momentums[i]) + """;"""
funcString = "norm*("
for i in xrange(0,len(shifts)-1,2):
if i>0:
funcString += "+"
funcString += """make_odd_gaussian(floor((double)alpha/2.),floor((double)beta/2.), sigma""" + str(i) + """, sigma""" + str(i+1) + """, shift""" + str(i) + """, shift""" + str(i+1) + """, p""" + str(i) + """, p""" + str(i+1) + """, (double)Qx/2.)"""
return r'''
__device__ double gaussian(double x, double sigma, double shift){
double arg = ((x-shift)/(sqrt(2.)*sigma));
return exp(-arg*arg)/sqrt(sigma*sqrt(pi));
}
__device__ dcmplx make_odd_gaussian(double x1, double x2, double sigma1, double sigma2,double shift1, double shift2, double p1, double p2, double L){
dcmplx i(0.,1.);
dcmplx kick1 = exp(i*(2.*pi*p1)*(-x1/L));
dcmplx kick2 = exp(i*(2.*pi*p2)*(-x1/L));
dcmplx kick3 = exp(i*(2.*pi*p1)*(-x2/L));
dcmplx kick4 = exp(i*(2.*pi*p2)*(-x2/L));
return (1./sqrt(2.))*(gaussian(x1,sigma1,shift1)*kick1*gaussian(x2,sigma2,shift2)*kick4-gaussian(x2,sigma1,shift1)*kick3*gaussian(x1,sigma2,shift2)*kick2);
}
__global__ void initialize(dcmplx *QField, int* lattice, int* gpu_params){
int x = blockIdx.x * blockDim.x + threadIdx.x;
int y = blockIdx.y * blockDim.y + threadIdx.y;
int z = blockIdx.z * blockDim.z + threadIdx.z;
int deviceNum = gpu_params[0];
int numGPUs = gpu_params[2];
int local_xSize = lattice[0];
int xSize = lattice[0]*numGPUs;
int ySize = lattice[2];
int zSize = lattice[4];
int vectorSize = ''' + str(int(vectorSize)) + r''';
int Qx = lattice[6];
double numGaussPairs = ''' + str(float(len(shifts))) + r''';
double norm = (1./(sqrt(2.)*numGaussPairs));
''' + variableString + r'''
int n;
index_pair iToNum = index_to_number(Qx, x + deviceNum*local_xSize);
int alpha = iToNum.index0;
int beta = iToNum.index1;
dcmplx i(0.,1.);
for(n=0; n < vectorSize; n++){
QField[n+z*vectorSize+y*vectorSize*zSize+x*zSize*ySize*vectorSize] =''' + funcString + r''');
}
}
''' | Code/Initialization/CUDA_Initializations/Default/Gaussians_1D_2P.py | def get_CUDA(vectorSize = 10, momentums = [0.,0.], shifts = [0.35,0.65], sigmas = [0.05, 0.05] , **kwargs):
if len(shifts)%2==1:
print "Must have even number of wavefunctions (pairs). Quitting..."
quit()
if (len(momentums)!= len(shifts)) or (len(momentums)!= len(sigmas)) or (len(shifts)!= len(sigmas)):
print "Input arrays must have the same length. Quitting..."
quit()
variableString = """"""
for i in xrange(len(shifts)):
variableString += """double sigma""" + str(i) + """ = """ + str(sigmas[i]) + r"""*Qx/2.;
double shift""" + str(i) + """ = """ + str(shifts[i]) + r"""*Qx/2.;
double p""" + str(i) + """ = """ + str(momentums[i]) + """;"""
funcString = "norm*("
for i in xrange(0,len(shifts)-1,2):
if i>0:
funcString += "+"
funcString += """make_odd_gaussian(floor((double)alpha/2.),floor((double)beta/2.), sigma""" + str(i) + """, sigma""" + str(i+1) + """, shift""" + str(i) + """, shift""" + str(i+1) + """, p""" + str(i) + """, p""" + str(i+1) + """, (double)Qx/2.)"""
return r'''
__device__ double gaussian(double x, double sigma, double shift){
double arg = ((x-shift)/(sqrt(2.)*sigma));
return exp(-arg*arg)/sqrt(sigma*sqrt(pi));
}
__device__ dcmplx make_odd_gaussian(double x1, double x2, double sigma1, double sigma2,double shift1, double shift2, double p1, double p2, double L){
dcmplx i(0.,1.);
dcmplx kick1 = exp(i*(2.*pi*p1)*(-x1/L));
dcmplx kick2 = exp(i*(2.*pi*p2)*(-x1/L));
dcmplx kick3 = exp(i*(2.*pi*p1)*(-x2/L));
dcmplx kick4 = exp(i*(2.*pi*p2)*(-x2/L));
return (1./sqrt(2.))*(gaussian(x1,sigma1,shift1)*kick1*gaussian(x2,sigma2,shift2)*kick4-gaussian(x2,sigma1,shift1)*kick3*gaussian(x1,sigma2,shift2)*kick2);
}
__global__ void initialize(dcmplx *QField, int* lattice, int* gpu_params){
int x = blockIdx.x * blockDim.x + threadIdx.x;
int y = blockIdx.y * blockDim.y + threadIdx.y;
int z = blockIdx.z * blockDim.z + threadIdx.z;
int deviceNum = gpu_params[0];
int numGPUs = gpu_params[2];
int local_xSize = lattice[0];
int xSize = lattice[0]*numGPUs;
int ySize = lattice[2];
int zSize = lattice[4];
int vectorSize = ''' + str(int(vectorSize)) + r''';
int Qx = lattice[6];
double numGaussPairs = ''' + str(float(len(shifts))) + r''';
double norm = (1./(sqrt(2.)*numGaussPairs));
''' + variableString + r'''
int n;
index_pair iToNum = index_to_number(Qx, x + deviceNum*local_xSize);
int alpha = iToNum.index0;
int beta = iToNum.index1;
dcmplx i(0.,1.);
for(n=0; n < vectorSize; n++){
QField[n+z*vectorSize+y*vectorSize*zSize+x*zSize*ySize*vectorSize] =''' + funcString + r''');
}
}
''' | 0.297266 | 0.45641 |
import os
import numpy
from sklearn.model_selection import train_test_split
from sklearn.base import ClusterMixin
from sklearn.metrics import silhouette_score
from pyquickhelper.loghelper import noLOG
from pyquickhelper.benchhelper import GridBenchMark
class MlGridBenchMark(GridBenchMark):
"""
The class tests a list of model over a list of datasets.
"""
def __init__(self, name, datasets, clog=None, fLOG=noLOG, path_to_images=".",
cache_file=None, progressbar=None, graphx=None, graphy=None,
**params):
"""
@param name name of the test
@param datasets list of dictionary of dataframes
@param clog see @see cl CustomLog or string
@param fLOG logging function
@param params extra parameters
@param path_to_images path to images and intermediate results
@param cache_file cache file
@param progressbar relies on *tqdm*, example *tnrange*
@param graphx list of variables to use as X axis
@param graphy list of variables to use as Y axis
If *cache_file* is specified, the class will store the results of the
method :meth:`bench <pyquickhelper.benchhelper.benchmark.GridBenchMark.bench>`.
On a second run, the function load the cache
and run modified or new run (in *param_list*).
*datasets* should be a dictionary with dataframes a values
with the following keys:
* ``'X'``: features
* ``'Y'``: labels (optional)
"""
GridBenchMark.__init__(self, name=name, datasets=datasets, clog=clog, fLOG=fLOG,
path_to_images=path_to_images, cache_file=cache_file,
progressbar=progressbar, **params)
self._xaxis = graphx
self._yaxis = graphy
def preprocess_dataset(self, dsi, **params):
"""
Splits the dataset into train and test.
@param dsi dataset index
@param params additional parameters
@return dataset (like info), dictionary for metrics
"""
ds, appe, params = GridBenchMark.preprocess_dataset(
self, dsi, **params)
no_split = ds["no_split"] if "no_split" in ds else False
if no_split:
self.fLOG("[MlGridBenchMark.preprocess_dataset] no split")
return (ds, ds), appe, params
self.fLOG("[MlGridBenchMark.preprocess_dataset] split train test")
spl = ["X", "Y", "weight", "group"]
names = [_ for _ in spl if _ in ds]
if len(names) == 0:
raise ValueError( # pragma: no cover
"No dataframe or matrix was found.")
mats = [ds[_] for _ in names]
pars = {"train_size", "test_size"}
options = {k: v for k, v in params.items() if k in pars}
for k in pars:
if k in params:
del params[k]
res = train_test_split(*mats, **options)
train = {}
for i, n in enumerate(names):
train[n] = res[i * 2]
test = {}
for i, n in enumerate(names):
test[n] = res[i * 2 + 1]
self.fLOG("[MlGridBenchMark.preprocess_dataset] done")
return (train, test), appe, params
def bench_experiment(self, ds, **params): # pylint: disable=W0237
"""
Calls meth *fit*.
"""
if not isinstance(ds, tuple) and len(ds) != 2:
raise TypeError( # pragma: no cover
"ds must a tuple with two dictionaries train, test")
if "model" not in params:
raise KeyError( # pragma: no cover
"params must contains key 'model'")
model = params["model"]
# we assume model is a function which creates a model
model = model()
del params["model"]
return self.fit(ds[0], model, **params)
def predict_score_experiment(self, ds, model, **params): # pylint: disable=W0237
"""
Calls method *score*.
"""
if not isinstance(ds, tuple) and len(ds) != 2:
raise TypeError( # pragma: no cover
"ds must a tuple with two dictionaries train, test")
if "model" in params:
raise KeyError( # pragma: no cover
"params must not contains key 'model'")
return self.score(ds[1], model, **params)
def fit(self, ds, model, **params):
"""
Trains a model.
@param ds dictionary with the data to use for training
@param model model to train
"""
if "X" not in ds:
raise KeyError( # pragma: no cover
"ds must contain key 'X'")
if "model" in params:
raise KeyError( # pragma: no cover
"params must not contain key 'model', this is the model to train")
X = ds["X"]
Y = ds.get("Y", None)
weight = ds.get("weight", None)
self.fLOG("[MlGridBenchMark.fit] fit", params)
train_params = params.get("train_params", {})
if weight is not None:
model.fit(X=X, y=Y, weight=weight, **train_params)
else:
model.fit(X=X, y=Y, **train_params)
self.fLOG("[MlGridBenchMark.fit] Done.")
return model
def score(self, ds, model, **params):
"""
Scores a model.
"""
X = ds["X"]
Y = ds.get("Y", None)
if "weight" in ds:
raise NotImplementedError( # pragma: no cover
"weight are not used yet")
metrics = {}
appe = {}
if hasattr(model, "score"):
score = model.score(X, Y)
metrics["own_score"] = score
if isinstance(model, ClusterMixin):
# add silhouette
if hasattr(model, "predict"):
ypred = model.predict(X)
elif hasattr(model, "transform"):
ypred = model.transform(X)
elif hasattr(model, "labels_"):
ypred = model.labels_
if len(ypred.shape) > 1 and ypred.shape[1] > 1:
ypred = numpy.argmax(ypred, axis=1)
score = silhouette_score(X, ypred)
metrics["silhouette"] = score
return metrics, appe
def end(self):
"""
nothing to do
"""
pass
def graphs(self, path_to_images):
"""
Plots multiples graphs.
@param path_to_images where to store images
@return list of tuple (image_name, function to create the graph)
"""
import matplotlib.pyplot as plt # pylint: disable=C0415
import matplotlib.cm as mcm # pylint: disable=C0415
df = self.to_df()
def local_graph(vx, vy, ax=None, text=True, figsize=(5, 5)):
btrys = set(df["_btry"])
ymin = df[vy].min()
ymax = df[vy].max()
decy = (ymax - ymin) / 50
colors = mcm.rainbow(numpy.linspace(0, 1, len(btrys)))
if len(btrys) == 0:
raise ValueError("The benchmark is empty.") # pragma: no cover
if ax is None:
_, ax = plt.subplots(1, 1, figsize=figsize) # pragma: no cover
ax.grid(True) # pragma: no cover
for i, btry in enumerate(sorted(btrys)):
subset = df[df["_btry"] == btry]
if subset.shape[0] > 0:
tx = subset[vx].mean()
ty = subset[vy].mean()
if not numpy.isnan(tx) and not numpy.isnan(ty):
subset.plot(x=vx, y=vy, kind="scatter",
label=btry, ax=ax, color=colors[i])
if text:
ax.text(tx, ty + decy, btry, size='small',
color=colors[i], ha='center', va='bottom')
ax.set_xlabel(vx)
ax.set_ylabel(vy)
return ax
res = []
if self._xaxis is not None and self._yaxis is not None:
for vx in self._xaxis:
for vy in self._yaxis:
self.fLOG("Plotting {0} x {1}".format(vx, vy))
func_graph = lambda ax=None, text=True, vx=vx, vy=vy, **kwargs: \
local_graph(vx, vy, ax=ax, text=text, **kwargs)
if path_to_images is not None:
img = os.path.join(
path_to_images, "img-{0}-{1}x{2}.png".format(self.Name, vx, vy))
gr = self.LocalGraph(
func_graph, img, root=path_to_images)
self.fLOG("Saving '{0}'".format(img))
fig, ax = plt.subplots(1, 1, figsize=(8, 8))
gr.plot(ax=ax, text=True)
fig.savefig(img)
self.fLOG("Done")
res.append(gr)
plt.close('all')
else:
gr = self.LocalGraph(func_graph)
res.append(gr)
return res
def plot_graphs(self, grid=None, text=True, **kwargs):
"""
Plots all graphs in the same graphs.
@param grid grid of axes
@param text add legend title on the graph
@return grid
"""
nb = len(self.Graphs)
if nb == 0:
raise ValueError("No graph to plot.") # pragma: no cover
nb = len(self.Graphs)
if nb % 2 == 0:
size = nb // 2, 2
else:
size = nb // 2 + 1, 2
if grid is None:
import matplotlib.pyplot as plt # pylint: disable=C0415
fg = kwargs.get('figsize', (5 * size[0], 10))
_, grid = plt.subplots(size[0], size[1], figsize=fg)
if 'figsize' in kwargs:
del kwargs['figsize'] # pragma: no cover
else:
shape = grid.shape
if shape[0] * shape[1] < nb:
raise ValueError( # pragma: no cover
"The graph is not big enough {0} < {1}".format(shape, nb))
x = 0
y = 0
for i, gr in enumerate(self.Graphs):
self.fLOG("Plot graph {0}/{1}".format(i + 1, nb))
gr.plot(ax=grid[y, x], text=text, **kwargs)
x += 1
if x >= grid.shape[1]:
x = 0
y += 1
return grid | src/mlstatpy/ml/ml_grid_benchmark.py | import os
import numpy
from sklearn.model_selection import train_test_split
from sklearn.base import ClusterMixin
from sklearn.metrics import silhouette_score
from pyquickhelper.loghelper import noLOG
from pyquickhelper.benchhelper import GridBenchMark
class MlGridBenchMark(GridBenchMark):
"""
The class tests a list of model over a list of datasets.
"""
def __init__(self, name, datasets, clog=None, fLOG=noLOG, path_to_images=".",
cache_file=None, progressbar=None, graphx=None, graphy=None,
**params):
"""
@param name name of the test
@param datasets list of dictionary of dataframes
@param clog see @see cl CustomLog or string
@param fLOG logging function
@param params extra parameters
@param path_to_images path to images and intermediate results
@param cache_file cache file
@param progressbar relies on *tqdm*, example *tnrange*
@param graphx list of variables to use as X axis
@param graphy list of variables to use as Y axis
If *cache_file* is specified, the class will store the results of the
method :meth:`bench <pyquickhelper.benchhelper.benchmark.GridBenchMark.bench>`.
On a second run, the function load the cache
and run modified or new run (in *param_list*).
*datasets* should be a dictionary with dataframes a values
with the following keys:
* ``'X'``: features
* ``'Y'``: labels (optional)
"""
GridBenchMark.__init__(self, name=name, datasets=datasets, clog=clog, fLOG=fLOG,
path_to_images=path_to_images, cache_file=cache_file,
progressbar=progressbar, **params)
self._xaxis = graphx
self._yaxis = graphy
def preprocess_dataset(self, dsi, **params):
"""
Splits the dataset into train and test.
@param dsi dataset index
@param params additional parameters
@return dataset (like info), dictionary for metrics
"""
ds, appe, params = GridBenchMark.preprocess_dataset(
self, dsi, **params)
no_split = ds["no_split"] if "no_split" in ds else False
if no_split:
self.fLOG("[MlGridBenchMark.preprocess_dataset] no split")
return (ds, ds), appe, params
self.fLOG("[MlGridBenchMark.preprocess_dataset] split train test")
spl = ["X", "Y", "weight", "group"]
names = [_ for _ in spl if _ in ds]
if len(names) == 0:
raise ValueError( # pragma: no cover
"No dataframe or matrix was found.")
mats = [ds[_] for _ in names]
pars = {"train_size", "test_size"}
options = {k: v for k, v in params.items() if k in pars}
for k in pars:
if k in params:
del params[k]
res = train_test_split(*mats, **options)
train = {}
for i, n in enumerate(names):
train[n] = res[i * 2]
test = {}
for i, n in enumerate(names):
test[n] = res[i * 2 + 1]
self.fLOG("[MlGridBenchMark.preprocess_dataset] done")
return (train, test), appe, params
def bench_experiment(self, ds, **params): # pylint: disable=W0237
"""
Calls meth *fit*.
"""
if not isinstance(ds, tuple) and len(ds) != 2:
raise TypeError( # pragma: no cover
"ds must a tuple with two dictionaries train, test")
if "model" not in params:
raise KeyError( # pragma: no cover
"params must contains key 'model'")
model = params["model"]
# we assume model is a function which creates a model
model = model()
del params["model"]
return self.fit(ds[0], model, **params)
def predict_score_experiment(self, ds, model, **params): # pylint: disable=W0237
"""
Calls method *score*.
"""
if not isinstance(ds, tuple) and len(ds) != 2:
raise TypeError( # pragma: no cover
"ds must a tuple with two dictionaries train, test")
if "model" in params:
raise KeyError( # pragma: no cover
"params must not contains key 'model'")
return self.score(ds[1], model, **params)
def fit(self, ds, model, **params):
"""
Trains a model.
@param ds dictionary with the data to use for training
@param model model to train
"""
if "X" not in ds:
raise KeyError( # pragma: no cover
"ds must contain key 'X'")
if "model" in params:
raise KeyError( # pragma: no cover
"params must not contain key 'model', this is the model to train")
X = ds["X"]
Y = ds.get("Y", None)
weight = ds.get("weight", None)
self.fLOG("[MlGridBenchMark.fit] fit", params)
train_params = params.get("train_params", {})
if weight is not None:
model.fit(X=X, y=Y, weight=weight, **train_params)
else:
model.fit(X=X, y=Y, **train_params)
self.fLOG("[MlGridBenchMark.fit] Done.")
return model
def score(self, ds, model, **params):
"""
Scores a model.
"""
X = ds["X"]
Y = ds.get("Y", None)
if "weight" in ds:
raise NotImplementedError( # pragma: no cover
"weight are not used yet")
metrics = {}
appe = {}
if hasattr(model, "score"):
score = model.score(X, Y)
metrics["own_score"] = score
if isinstance(model, ClusterMixin):
# add silhouette
if hasattr(model, "predict"):
ypred = model.predict(X)
elif hasattr(model, "transform"):
ypred = model.transform(X)
elif hasattr(model, "labels_"):
ypred = model.labels_
if len(ypred.shape) > 1 and ypred.shape[1] > 1:
ypred = numpy.argmax(ypred, axis=1)
score = silhouette_score(X, ypred)
metrics["silhouette"] = score
return metrics, appe
def end(self):
"""
nothing to do
"""
pass
def graphs(self, path_to_images):
"""
Plots multiples graphs.
@param path_to_images where to store images
@return list of tuple (image_name, function to create the graph)
"""
import matplotlib.pyplot as plt # pylint: disable=C0415
import matplotlib.cm as mcm # pylint: disable=C0415
df = self.to_df()
def local_graph(vx, vy, ax=None, text=True, figsize=(5, 5)):
btrys = set(df["_btry"])
ymin = df[vy].min()
ymax = df[vy].max()
decy = (ymax - ymin) / 50
colors = mcm.rainbow(numpy.linspace(0, 1, len(btrys)))
if len(btrys) == 0:
raise ValueError("The benchmark is empty.") # pragma: no cover
if ax is None:
_, ax = plt.subplots(1, 1, figsize=figsize) # pragma: no cover
ax.grid(True) # pragma: no cover
for i, btry in enumerate(sorted(btrys)):
subset = df[df["_btry"] == btry]
if subset.shape[0] > 0:
tx = subset[vx].mean()
ty = subset[vy].mean()
if not numpy.isnan(tx) and not numpy.isnan(ty):
subset.plot(x=vx, y=vy, kind="scatter",
label=btry, ax=ax, color=colors[i])
if text:
ax.text(tx, ty + decy, btry, size='small',
color=colors[i], ha='center', va='bottom')
ax.set_xlabel(vx)
ax.set_ylabel(vy)
return ax
res = []
if self._xaxis is not None and self._yaxis is not None:
for vx in self._xaxis:
for vy in self._yaxis:
self.fLOG("Plotting {0} x {1}".format(vx, vy))
func_graph = lambda ax=None, text=True, vx=vx, vy=vy, **kwargs: \
local_graph(vx, vy, ax=ax, text=text, **kwargs)
if path_to_images is not None:
img = os.path.join(
path_to_images, "img-{0}-{1}x{2}.png".format(self.Name, vx, vy))
gr = self.LocalGraph(
func_graph, img, root=path_to_images)
self.fLOG("Saving '{0}'".format(img))
fig, ax = plt.subplots(1, 1, figsize=(8, 8))
gr.plot(ax=ax, text=True)
fig.savefig(img)
self.fLOG("Done")
res.append(gr)
plt.close('all')
else:
gr = self.LocalGraph(func_graph)
res.append(gr)
return res
def plot_graphs(self, grid=None, text=True, **kwargs):
"""
Plots all graphs in the same graphs.
@param grid grid of axes
@param text add legend title on the graph
@return grid
"""
nb = len(self.Graphs)
if nb == 0:
raise ValueError("No graph to plot.") # pragma: no cover
nb = len(self.Graphs)
if nb % 2 == 0:
size = nb // 2, 2
else:
size = nb // 2 + 1, 2
if grid is None:
import matplotlib.pyplot as plt # pylint: disable=C0415
fg = kwargs.get('figsize', (5 * size[0], 10))
_, grid = plt.subplots(size[0], size[1], figsize=fg)
if 'figsize' in kwargs:
del kwargs['figsize'] # pragma: no cover
else:
shape = grid.shape
if shape[0] * shape[1] < nb:
raise ValueError( # pragma: no cover
"The graph is not big enough {0} < {1}".format(shape, nb))
x = 0
y = 0
for i, gr in enumerate(self.Graphs):
self.fLOG("Plot graph {0}/{1}".format(i + 1, nb))
gr.plot(ax=grid[y, x], text=text, **kwargs)
x += 1
if x >= grid.shape[1]:
x = 0
y += 1
return grid | 0.782704 | 0.375306 |
import os
import re
from fabric.api import hide, lcd, local, prompt, settings
PROJECT_PATH = os.path.dirname(os.path.realpath(__file__))
def test():
"""Runs the blingalytics test suite."""
os.environ['PYTHONPATH'] = PROJECT_PATH
with settings(hide('warnings'), warn_only=True):
local('python test/test_runner.py')
def update_pypi():
"""Updates versions and packages for PyPI."""
# Verify that we want to do this...
sure = prompt('Are you sure you want to release a new version to PyPI? '
'Have you pushed all changes to origin/master? [y/n]',
validate=r'^[yYnN]')
if sure.lower()[0] != 'y':
return
# First update version numbers
with lcd(PROJECT_PATH):
old_version = local('grep version= setup.py', capture=True)
old_version = re.search(r'\'([0-9a-zA-Z.]+)\'', old_version).group(1)
new_version = prompt(
'What version number (previous: {0})?'.format(old_version),
validate=r'^\d+\.\d+\.\d+\w*$')
local('sed -i -r -e "s/{before}/{after}/g" {filename}'.format(
filename=os.path.join(PROJECT_PATH, 'setup.py'),
before=r"version='[0-9a-zA-Z.]+'",
after="version='{0}'".format(new_version)))
local('sed -i -r -e "s/{before}/{after}/g" {filename}'.format(
filename=os.path.join(PROJECT_PATH, 'docs', 'conf.py'),
before=r"version = '[0-9]+\.[0-9]+'",
after="version = '{0}'".format('.'.join(new_version.split('.')[:2]))))
local('sed -i -r -e "s/{before}/{after}/g" {filename}'.format(
filename=os.path.join(PROJECT_PATH, 'docs', 'conf.py'),
before=r"release = '[0-9]+\.[0-9]+\.[0-9a-zA-Z]+'",
after="release = '{0}'".format(new_version)))
# Then tag and push to git
local('git commit -a -m "Revs version to v{0}"'.format(new_version))
local('git tag -f -a v{0} -m "v{0}"'.format(new_version))
local('git push origin master --tags')
# Register new version on PyPI
# Note: copy to /tmp because vagrant shared directories don't handle
# links well, which are part of the sdist process
local('cp -f -r {0} /tmp/'.format(PROJECT_PATH))
with lcd('/tmp/vagrant'):
local('python setup.py register')
local('python setup.py sdist upload') | fabfile.py | import os
import re
from fabric.api import hide, lcd, local, prompt, settings
PROJECT_PATH = os.path.dirname(os.path.realpath(__file__))
def test():
"""Runs the blingalytics test suite."""
os.environ['PYTHONPATH'] = PROJECT_PATH
with settings(hide('warnings'), warn_only=True):
local('python test/test_runner.py')
def update_pypi():
"""Updates versions and packages for PyPI."""
# Verify that we want to do this...
sure = prompt('Are you sure you want to release a new version to PyPI? '
'Have you pushed all changes to origin/master? [y/n]',
validate=r'^[yYnN]')
if sure.lower()[0] != 'y':
return
# First update version numbers
with lcd(PROJECT_PATH):
old_version = local('grep version= setup.py', capture=True)
old_version = re.search(r'\'([0-9a-zA-Z.]+)\'', old_version).group(1)
new_version = prompt(
'What version number (previous: {0})?'.format(old_version),
validate=r'^\d+\.\d+\.\d+\w*$')
local('sed -i -r -e "s/{before}/{after}/g" {filename}'.format(
filename=os.path.join(PROJECT_PATH, 'setup.py'),
before=r"version='[0-9a-zA-Z.]+'",
after="version='{0}'".format(new_version)))
local('sed -i -r -e "s/{before}/{after}/g" {filename}'.format(
filename=os.path.join(PROJECT_PATH, 'docs', 'conf.py'),
before=r"version = '[0-9]+\.[0-9]+'",
after="version = '{0}'".format('.'.join(new_version.split('.')[:2]))))
local('sed -i -r -e "s/{before}/{after}/g" {filename}'.format(
filename=os.path.join(PROJECT_PATH, 'docs', 'conf.py'),
before=r"release = '[0-9]+\.[0-9]+\.[0-9a-zA-Z]+'",
after="release = '{0}'".format(new_version)))
# Then tag and push to git
local('git commit -a -m "Revs version to v{0}"'.format(new_version))
local('git tag -f -a v{0} -m "v{0}"'.format(new_version))
local('git push origin master --tags')
# Register new version on PyPI
# Note: copy to /tmp because vagrant shared directories don't handle
# links well, which are part of the sdist process
local('cp -f -r {0} /tmp/'.format(PROJECT_PATH))
with lcd('/tmp/vagrant'):
local('python setup.py register')
local('python setup.py sdist upload') | 0.371023 | 0.090293 |
import sys
from time import sleep
from cadence.clock_decision_context import DEFAULT_VERSION
from cadence.workerfactory import WorkerFactory
from cadence.workflow import workflow_method, Workflow, WorkflowClient
TASK_LIST = "TestWorkflowGetVersion"
DOMAIN = "sample"
v1_hits = 0
v2_hits = 0
version_found_in_v2_step_1_0 = None
version_found_in_v2_step_1_1 = None
version_found_in_v2_step_2_0 = None
version_found_in_v2_step_2_1 = None
v2_done = False
class TestWorkflowGetVersion:
@workflow_method(task_list=TASK_LIST)
async def get_greetings(self) -> list:
raise NotImplementedError
class TestWorkflowGetVersionImplV1(TestWorkflowGetVersion):
def __init__(self):
pass
async def get_greetings(self):
global v1_hits
v1_hits += 1
await Workflow.sleep(60)
class TestWorkflowGetVersionImplV2(TestWorkflowGetVersion):
def __init__(self):
pass
async def get_greetings(self):
global v2_hits
global version_found_in_v2_step_1_0, version_found_in_v2_step_1_1
global version_found_in_v2_step_2_0, version_found_in_v2_step_2_1
global v2_done
v2_hits += 1
version_found_in_v2_step_1_0 = Workflow.get_version("first-item", DEFAULT_VERSION, 2)
version_found_in_v2_step_1_1 = Workflow.get_version("first-item", DEFAULT_VERSION, 2)
await Workflow.sleep(60)
version_found_in_v2_step_2_0 = Workflow.get_version("first-item", DEFAULT_VERSION, 2)
version_found_in_v2_step_2_1 = Workflow.get_version("first-item", DEFAULT_VERSION, 2)
v2_done = True
def test_workflow_workflow_get_version():
global v1_hits, v2_hits
factory = WorkerFactory("localhost", 7933, DOMAIN)
worker = factory.new_worker(TASK_LIST)
worker.register_workflow_implementation_type(TestWorkflowGetVersionImplV1)
factory.start()
client = WorkflowClient.new_client(domain=DOMAIN)
workflow: TestWorkflowGetVersion = client.new_workflow_stub(TestWorkflowGetVersion)
client.start(workflow.get_greetings)
while v1_hits == 0:
print(".", end="")
sleep(2)
worker.register_workflow_implementation_type(TestWorkflowGetVersionImplV2)
while not v2_done:
print(".", end="")
sleep(2)
assert v1_hits == 1
assert v2_hits == 1
assert version_found_in_v2_step_1_0 == DEFAULT_VERSION
assert version_found_in_v2_step_1_1 == DEFAULT_VERSION
assert version_found_in_v2_step_2_0 == DEFAULT_VERSION
assert version_found_in_v2_step_2_1 == DEFAULT_VERSION
# TODO: Assert that there are no markers recorded
print("Stopping workers")
worker.stop(background=True) | cadence/tests/test_workflow_get_version.py | import sys
from time import sleep
from cadence.clock_decision_context import DEFAULT_VERSION
from cadence.workerfactory import WorkerFactory
from cadence.workflow import workflow_method, Workflow, WorkflowClient
TASK_LIST = "TestWorkflowGetVersion"
DOMAIN = "sample"
v1_hits = 0
v2_hits = 0
version_found_in_v2_step_1_0 = None
version_found_in_v2_step_1_1 = None
version_found_in_v2_step_2_0 = None
version_found_in_v2_step_2_1 = None
v2_done = False
class TestWorkflowGetVersion:
@workflow_method(task_list=TASK_LIST)
async def get_greetings(self) -> list:
raise NotImplementedError
class TestWorkflowGetVersionImplV1(TestWorkflowGetVersion):
def __init__(self):
pass
async def get_greetings(self):
global v1_hits
v1_hits += 1
await Workflow.sleep(60)
class TestWorkflowGetVersionImplV2(TestWorkflowGetVersion):
def __init__(self):
pass
async def get_greetings(self):
global v2_hits
global version_found_in_v2_step_1_0, version_found_in_v2_step_1_1
global version_found_in_v2_step_2_0, version_found_in_v2_step_2_1
global v2_done
v2_hits += 1
version_found_in_v2_step_1_0 = Workflow.get_version("first-item", DEFAULT_VERSION, 2)
version_found_in_v2_step_1_1 = Workflow.get_version("first-item", DEFAULT_VERSION, 2)
await Workflow.sleep(60)
version_found_in_v2_step_2_0 = Workflow.get_version("first-item", DEFAULT_VERSION, 2)
version_found_in_v2_step_2_1 = Workflow.get_version("first-item", DEFAULT_VERSION, 2)
v2_done = True
def test_workflow_workflow_get_version():
global v1_hits, v2_hits
factory = WorkerFactory("localhost", 7933, DOMAIN)
worker = factory.new_worker(TASK_LIST)
worker.register_workflow_implementation_type(TestWorkflowGetVersionImplV1)
factory.start()
client = WorkflowClient.new_client(domain=DOMAIN)
workflow: TestWorkflowGetVersion = client.new_workflow_stub(TestWorkflowGetVersion)
client.start(workflow.get_greetings)
while v1_hits == 0:
print(".", end="")
sleep(2)
worker.register_workflow_implementation_type(TestWorkflowGetVersionImplV2)
while not v2_done:
print(".", end="")
sleep(2)
assert v1_hits == 1
assert v2_hits == 1
assert version_found_in_v2_step_1_0 == DEFAULT_VERSION
assert version_found_in_v2_step_1_1 == DEFAULT_VERSION
assert version_found_in_v2_step_2_0 == DEFAULT_VERSION
assert version_found_in_v2_step_2_1 == DEFAULT_VERSION
# TODO: Assert that there are no markers recorded
print("Stopping workers")
worker.stop(background=True) | 0.237841 | 0.167015 |
from datetime import datetime, timedelta
import json
import numpy as np
import os
from PIL import Image, ImageTk
import tkinter as tk
from utils.downloading import SH_TCI_retrieve_successor
from utils.utils import rows_to_pairs, consolidate_name
class ImagePanel(tk.Canvas):
def __init__(self, master, img):
#self.grid(row=0, column=0)
hei, wid = img.shape[0], img.shape[1]
self.width=master.magnification*wid
self.height=master.magnification*hei
tk.Canvas.__init__(self, master, width=self.width, height=self.height)
self.bind("<Button-1>", self.pixelclick)
self.img_orig = img
self.draw_image(self.img_orig, self.master.pxs)
def draw_image(self, img_orig, l):
if len(l)>0:
img = img_orig.copy()
for px in l:
# Black:
#img[px[0], px[1], :] = 0
# Magenta:
#img[px[0], px[1], 0] = 192
#img[px[0], px[1], 1] = 0
#img[px[0], px[1], 2] = 192
img[px[0], px[1], 0] = self.master.colour_for_selection[0]
img[px[0], px[1], 1] = self.master.colour_for_selection[1]
img[px[0], px[1], 2] = self.master.colour_for_selection[2]
else:
img = img_orig.copy()
img = np.kron(img, np.ones((self.master.magnification, self.master.magnification), dtype=np.uint8)[:,:,np.newaxis])
self.imgPIL=ImageTk.PhotoImage(Image.fromarray(img))
self.create_image((0, 0), image=self.imgPIL, anchor='nw', state="normal")
def pixelclick(self, event):
col, row = event.x//self.master.magnification, event.y//self.master.magnification
#print("Clicked at row {0}, column {1}.".format(row, col))
if [row, col] in self.master.pxs:
self.master.pxs.remove([row, col])
else:
self.master.pxs.append([row, col])
self.draw_image(self.img_orig, self.master.pxs)
class ButtonsPanel(tk.Frame):
def __init__(self, master):
frame = tk.Frame.__init__(self, master)
#self.grid(row=0, column=1, sticky="s")
self.createWidgets()
return frame
def createWidgets(self):
self.skip = tk.Button(self, text="Skip", command=self.skp, padx=5)
self.skip.grid(row=0)
self.savencontinue = tk.Button(self, text="Save & Continue", command=self.snc)
self.savencontinue.grid(row=1)
self.savenquit = tk.Button(self, text="Save & Quit", command=self.snq, padx=2)
self.savenquit.grid(row=2)
self.cancel = tk.Button(self, text="Cancel", command=self.cnq, padx=4)
self.cancel.grid(row=3)
def skp(self):
# active_date, next_date are strings in YYYY-MM-DD format
active_date = self.master.location['date']
print("Skipping " + active_date)
# increment date by 1 day
next_date = datetime.strftime(datetime.strptime(active_date, '%Y-%m-%d') + timedelta(1),
'%Y-%m-%d')
self.master.location['date'] = next_date
#local_location = self.master.location.copy()
#local_location['date'] = next_date
active_date = self.master.create_workspace(self.master, self.master.location)
#active_date = self.master.create_workspace(self.master, local_location)
self.master.location['date'] = active_date
def snc(self):
# active_date, next_date are strings in YYYY-MM-DD format
active_date = self.master.location['date']
print("Saving {0} & Continuing".format(active_date))
self.master.locations_json[active_date] = self.master.location.copy()
self.master.locations_json[active_date]['px'] = self.master.pxs.copy()
self.savetofile()
# increment date by 1 day
next_date = datetime.strftime(datetime.strptime(active_date, '%Y-%m-%d') + timedelta(1), '%Y-%m-%d')
self.master.location['date'] = next_date
active_date = self.master.create_workspace(self.master, self.master.location)
self.master.location['date'] = active_date
def snq(self):
# active_date is a string in YYYY-MM-DD format
active_date = self.master.location['date']
print("Saving {0} & Quitting".format(active_date))
self.master.locations_json[active_date] = self.master.location.copy()
self.master.locations_json[active_date]['px'] = self.master.pxs.copy()
self.savetofile()
self.master.destroy()
def cnq(self):
active_date = self.master.location['date']
print("Cancel. Quitting without saving {0}.".format(active_date))
self.master.destroy()
def savetofile(self):
if not os.path.exists(self.master.output_folder):
os.makedirs(self.master.output_folder)
# save dict of dates and pixels in JSON, named using locations[k]['name']
with open(os.path.join(self.master.output_folder, consolidate_name(self.master.location['name']) + '_' + self.master.level_choice + '_locations.json'), 'w') as openfile:
openfile.write(json.dumps(self.master.locations_json, ensure_ascii=False, indent=0))
# Saving pixel intensity values will be done separately.
class BigFrame(tk.Tk):
def __init__(self, location, INSTANCE_ID, LAYER_NAME_TCI, DATA_SOURCE, magnification, colour_for_selection, output_folder, level_choice):
tk.Tk.__init__(self)
# location['px'] (px) is an np.array of size (2 x nr_of_pixels). self.master.pxs is a list of pairs.
self.location = location
self.pxs = rows_to_pairs(location['px'])
self.INSTANCE_ID = INSTANCE_ID
self.LAYER_NAME_TCI = LAYER_NAME_TCI
self.DATA_SOURCE = DATA_SOURCE
self.magnification = magnification
self.colour_for_selection = colour_for_selection
self.output_folder = output_folder
self.level_choice = level_choice
self.canvas = tk.Canvas().grid(row=0, column=0)
self.but = ButtonsPanel(master=self).grid(row=0, column=1)#, sticky="s")
active_date = self.create_workspace(self, self.location)
self.location['date'] = active_date
self.locations_json = dict()
def create_workspace(self, root, location):
wms_true_color_imgs, available_dates = SH_TCI_retrieve_successor(location, self.INSTANCE_ID, self.LAYER_NAME_TCI, self.DATA_SOURCE)
print('Next available dates: ', [datetime.strftime(ad, '%Y-%m-%d %H:%M:%S') for ad in available_dates])
if len(available_dates)>0:
img = wms_true_color_imgs[0]
#px = location['px']
self.imgpanel = ImagePanel(root, img).grid(row=0, column=0)
#self.imgpanel = ImagePanel(root, img, px).grid(row=0, column=0)
#self.imgpanel = ImagePanel(self.canvas, img, px, magnification, root.colour_for_selection).grid(row=0, column=0)
return datetime.strftime(available_dates[0], '%Y-%m-%d')
else:
print('You reached the present.')
#self.but.cnq()
#self.bbb
#self.destroy()
root.destroy() | utils/gui.py |
from datetime import datetime, timedelta
import json
import numpy as np
import os
from PIL import Image, ImageTk
import tkinter as tk
from utils.downloading import SH_TCI_retrieve_successor
from utils.utils import rows_to_pairs, consolidate_name
class ImagePanel(tk.Canvas):
def __init__(self, master, img):
#self.grid(row=0, column=0)
hei, wid = img.shape[0], img.shape[1]
self.width=master.magnification*wid
self.height=master.magnification*hei
tk.Canvas.__init__(self, master, width=self.width, height=self.height)
self.bind("<Button-1>", self.pixelclick)
self.img_orig = img
self.draw_image(self.img_orig, self.master.pxs)
def draw_image(self, img_orig, l):
if len(l)>0:
img = img_orig.copy()
for px in l:
# Black:
#img[px[0], px[1], :] = 0
# Magenta:
#img[px[0], px[1], 0] = 192
#img[px[0], px[1], 1] = 0
#img[px[0], px[1], 2] = 192
img[px[0], px[1], 0] = self.master.colour_for_selection[0]
img[px[0], px[1], 1] = self.master.colour_for_selection[1]
img[px[0], px[1], 2] = self.master.colour_for_selection[2]
else:
img = img_orig.copy()
img = np.kron(img, np.ones((self.master.magnification, self.master.magnification), dtype=np.uint8)[:,:,np.newaxis])
self.imgPIL=ImageTk.PhotoImage(Image.fromarray(img))
self.create_image((0, 0), image=self.imgPIL, anchor='nw', state="normal")
def pixelclick(self, event):
col, row = event.x//self.master.magnification, event.y//self.master.magnification
#print("Clicked at row {0}, column {1}.".format(row, col))
if [row, col] in self.master.pxs:
self.master.pxs.remove([row, col])
else:
self.master.pxs.append([row, col])
self.draw_image(self.img_orig, self.master.pxs)
class ButtonsPanel(tk.Frame):
def __init__(self, master):
frame = tk.Frame.__init__(self, master)
#self.grid(row=0, column=1, sticky="s")
self.createWidgets()
return frame
def createWidgets(self):
self.skip = tk.Button(self, text="Skip", command=self.skp, padx=5)
self.skip.grid(row=0)
self.savencontinue = tk.Button(self, text="Save & Continue", command=self.snc)
self.savencontinue.grid(row=1)
self.savenquit = tk.Button(self, text="Save & Quit", command=self.snq, padx=2)
self.savenquit.grid(row=2)
self.cancel = tk.Button(self, text="Cancel", command=self.cnq, padx=4)
self.cancel.grid(row=3)
def skp(self):
# active_date, next_date are strings in YYYY-MM-DD format
active_date = self.master.location['date']
print("Skipping " + active_date)
# increment date by 1 day
next_date = datetime.strftime(datetime.strptime(active_date, '%Y-%m-%d') + timedelta(1),
'%Y-%m-%d')
self.master.location['date'] = next_date
#local_location = self.master.location.copy()
#local_location['date'] = next_date
active_date = self.master.create_workspace(self.master, self.master.location)
#active_date = self.master.create_workspace(self.master, local_location)
self.master.location['date'] = active_date
def snc(self):
# active_date, next_date are strings in YYYY-MM-DD format
active_date = self.master.location['date']
print("Saving {0} & Continuing".format(active_date))
self.master.locations_json[active_date] = self.master.location.copy()
self.master.locations_json[active_date]['px'] = self.master.pxs.copy()
self.savetofile()
# increment date by 1 day
next_date = datetime.strftime(datetime.strptime(active_date, '%Y-%m-%d') + timedelta(1), '%Y-%m-%d')
self.master.location['date'] = next_date
active_date = self.master.create_workspace(self.master, self.master.location)
self.master.location['date'] = active_date
def snq(self):
# active_date is a string in YYYY-MM-DD format
active_date = self.master.location['date']
print("Saving {0} & Quitting".format(active_date))
self.master.locations_json[active_date] = self.master.location.copy()
self.master.locations_json[active_date]['px'] = self.master.pxs.copy()
self.savetofile()
self.master.destroy()
def cnq(self):
active_date = self.master.location['date']
print("Cancel. Quitting without saving {0}.".format(active_date))
self.master.destroy()
def savetofile(self):
if not os.path.exists(self.master.output_folder):
os.makedirs(self.master.output_folder)
# save dict of dates and pixels in JSON, named using locations[k]['name']
with open(os.path.join(self.master.output_folder, consolidate_name(self.master.location['name']) + '_' + self.master.level_choice + '_locations.json'), 'w') as openfile:
openfile.write(json.dumps(self.master.locations_json, ensure_ascii=False, indent=0))
# Saving pixel intensity values will be done separately.
class BigFrame(tk.Tk):
def __init__(self, location, INSTANCE_ID, LAYER_NAME_TCI, DATA_SOURCE, magnification, colour_for_selection, output_folder, level_choice):
tk.Tk.__init__(self)
# location['px'] (px) is an np.array of size (2 x nr_of_pixels). self.master.pxs is a list of pairs.
self.location = location
self.pxs = rows_to_pairs(location['px'])
self.INSTANCE_ID = INSTANCE_ID
self.LAYER_NAME_TCI = LAYER_NAME_TCI
self.DATA_SOURCE = DATA_SOURCE
self.magnification = magnification
self.colour_for_selection = colour_for_selection
self.output_folder = output_folder
self.level_choice = level_choice
self.canvas = tk.Canvas().grid(row=0, column=0)
self.but = ButtonsPanel(master=self).grid(row=0, column=1)#, sticky="s")
active_date = self.create_workspace(self, self.location)
self.location['date'] = active_date
self.locations_json = dict()
def create_workspace(self, root, location):
wms_true_color_imgs, available_dates = SH_TCI_retrieve_successor(location, self.INSTANCE_ID, self.LAYER_NAME_TCI, self.DATA_SOURCE)
print('Next available dates: ', [datetime.strftime(ad, '%Y-%m-%d %H:%M:%S') for ad in available_dates])
if len(available_dates)>0:
img = wms_true_color_imgs[0]
#px = location['px']
self.imgpanel = ImagePanel(root, img).grid(row=0, column=0)
#self.imgpanel = ImagePanel(root, img, px).grid(row=0, column=0)
#self.imgpanel = ImagePanel(self.canvas, img, px, magnification, root.colour_for_selection).grid(row=0, column=0)
return datetime.strftime(available_dates[0], '%Y-%m-%d')
else:
print('You reached the present.')
#self.but.cnq()
#self.bbb
#self.destroy()
root.destroy() | 0.334481 | 0.213459 |
import torch
import torch.nn
import torch.nn.functional as F
from typing import Dict, Any
from dataclasses import dataclass
from ..common import separate_output_digits
from ..result import Result
from ..model_interface import ModelInterface
@dataclass
class TupleRunResult(Result):
reference_order: torch.Tensor
loss: torch.Tensor
n_tuples: int
@property
def batch_size(self) -> int:
return self.reference_order.shape[0]
class TupleArithmeticDatasetInterface(ModelInterface):
def __init__(self, model: torch.nn.Module, n_tuples: int, steps_per_tuple: int = 3, mode: str = "together"):
self.model = model
self.steps_per_tuple = steps_per_tuple
self.n_tuples = n_tuples
self.train_only_tuple = -1
self.mode = mode
def apply_mode(self, data: torch.Tensor) -> torch.Tensor:
if self.mode in ["together", "same_output"]:
res = data
elif self.mode in ["only_one", "only_one_io"]:
res = torch.zeros_like(data)
for t in range(self.n_tuples):
this_tuple = slice(t * self.steps_per_tuple, (t + 1) * self.steps_per_tuple)
res[this_tuple, :, t] = data[this_tuple, :, t]
elif self.mode in ["same_input", "same_io"]:
res = torch.zeros_like(data[:,:,0])
for t in range(self.n_tuples):
this_tuple = slice(t * self.steps_per_tuple, (t + 1) * self.steps_per_tuple)
res[this_tuple] = data[this_tuple, :, t]
else:
assert False, f"Invalid mode: {self.mode}"
return res
def create_input(self, data: Dict[str, torch.Tensor]) -> torch.Tensor:
onehot_inputs = F.one_hot(data["input"].long(), 10)
if self.train_only_tuple >= 0:
onehot_inputs[:, 0:self.train_only_tuple].fill_(0)
onehot_inputs[:, self.train_only_tuple+1:].fill_(0)
onehot_inputs = onehot_inputs.float()
res = onehot_inputs.unsqueeze(0).expand(self.n_tuples * self.steps_per_tuple, *([-1]*onehot_inputs.ndim))
res = self.apply_mode(res)
return res.flatten(2)
def restrict(self, train_only_tuple: int):
self.train_only_tuple = train_only_tuple
def to_reference_order(self, outputs: torch.Tensor) -> torch.Tensor:
if self.mode in ["together", "only_one", "same_input"]:
res = outputs[-1].view(outputs.shape[1], self.n_tuples, -1)
elif self.mode in ["same_output", "same_io"]:
res = outputs[self.steps_per_tuple - 1 :: self.steps_per_tuple].transpose(1,0)
elif self.mode in ["only_one_io"]:
res = outputs.view(*outputs.shape[:2], self.n_tuples, -1)
return torch.stack([res[self.steps_per_tuple * (i+1) - 1, :, i] for i in range(self.n_tuples)], dim=1)
else:
assert False, f"Invalid mode {self.mode}"
return res
def loss(self, outputs: torch.Tensor, data: Dict[str, torch.Tensor]) -> torch.Tensor:
outputs = separate_output_digits(outputs)
ref = data["output"]
if self.train_only_tuple >= 0:
outputs = outputs[:, self.train_only_tuple:self.train_only_tuple+1]
ref = ref[:, self.train_only_tuple:self.train_only_tuple+1]
return F.cross_entropy(outputs.flatten(end_dim=-2), ref.long().flatten())
def decode_outputs(self, outputs: TupleRunResult) -> torch.Tensor:
return separate_output_digits(outputs.reference_order).argmax(-1)
def __call__(self, data: Dict[str, torch.Tensor]) -> TupleRunResult:
res = self.model(self.create_input(data))
reforder = self.to_reference_order(res)
loss = self.loss(reforder, data)
return TupleRunResult(reforder, loss, self.n_tuples) | interfaces/recurrent/tuple_arithmetic.py | import torch
import torch.nn
import torch.nn.functional as F
from typing import Dict, Any
from dataclasses import dataclass
from ..common import separate_output_digits
from ..result import Result
from ..model_interface import ModelInterface
@dataclass
class TupleRunResult(Result):
reference_order: torch.Tensor
loss: torch.Tensor
n_tuples: int
@property
def batch_size(self) -> int:
return self.reference_order.shape[0]
class TupleArithmeticDatasetInterface(ModelInterface):
def __init__(self, model: torch.nn.Module, n_tuples: int, steps_per_tuple: int = 3, mode: str = "together"):
self.model = model
self.steps_per_tuple = steps_per_tuple
self.n_tuples = n_tuples
self.train_only_tuple = -1
self.mode = mode
def apply_mode(self, data: torch.Tensor) -> torch.Tensor:
if self.mode in ["together", "same_output"]:
res = data
elif self.mode in ["only_one", "only_one_io"]:
res = torch.zeros_like(data)
for t in range(self.n_tuples):
this_tuple = slice(t * self.steps_per_tuple, (t + 1) * self.steps_per_tuple)
res[this_tuple, :, t] = data[this_tuple, :, t]
elif self.mode in ["same_input", "same_io"]:
res = torch.zeros_like(data[:,:,0])
for t in range(self.n_tuples):
this_tuple = slice(t * self.steps_per_tuple, (t + 1) * self.steps_per_tuple)
res[this_tuple] = data[this_tuple, :, t]
else:
assert False, f"Invalid mode: {self.mode}"
return res
def create_input(self, data: Dict[str, torch.Tensor]) -> torch.Tensor:
onehot_inputs = F.one_hot(data["input"].long(), 10)
if self.train_only_tuple >= 0:
onehot_inputs[:, 0:self.train_only_tuple].fill_(0)
onehot_inputs[:, self.train_only_tuple+1:].fill_(0)
onehot_inputs = onehot_inputs.float()
res = onehot_inputs.unsqueeze(0).expand(self.n_tuples * self.steps_per_tuple, *([-1]*onehot_inputs.ndim))
res = self.apply_mode(res)
return res.flatten(2)
def restrict(self, train_only_tuple: int):
self.train_only_tuple = train_only_tuple
def to_reference_order(self, outputs: torch.Tensor) -> torch.Tensor:
if self.mode in ["together", "only_one", "same_input"]:
res = outputs[-1].view(outputs.shape[1], self.n_tuples, -1)
elif self.mode in ["same_output", "same_io"]:
res = outputs[self.steps_per_tuple - 1 :: self.steps_per_tuple].transpose(1,0)
elif self.mode in ["only_one_io"]:
res = outputs.view(*outputs.shape[:2], self.n_tuples, -1)
return torch.stack([res[self.steps_per_tuple * (i+1) - 1, :, i] for i in range(self.n_tuples)], dim=1)
else:
assert False, f"Invalid mode {self.mode}"
return res
def loss(self, outputs: torch.Tensor, data: Dict[str, torch.Tensor]) -> torch.Tensor:
outputs = separate_output_digits(outputs)
ref = data["output"]
if self.train_only_tuple >= 0:
outputs = outputs[:, self.train_only_tuple:self.train_only_tuple+1]
ref = ref[:, self.train_only_tuple:self.train_only_tuple+1]
return F.cross_entropy(outputs.flatten(end_dim=-2), ref.long().flatten())
def decode_outputs(self, outputs: TupleRunResult) -> torch.Tensor:
return separate_output_digits(outputs.reference_order).argmax(-1)
def __call__(self, data: Dict[str, torch.Tensor]) -> TupleRunResult:
res = self.model(self.create_input(data))
reforder = self.to_reference_order(res)
loss = self.loss(reforder, data)
return TupleRunResult(reforder, loss, self.n_tuples) | 0.918224 | 0.497437 |
import logging
import json
from ..contents import *
from azure.iot.device import Message
from azure.iot.device import MethodResponse
logger = logging.getLogger(__name__)
class IoTHubDeviceClient:
def set_iot_hub_device_client(self, client):
self.__iot_hub_device_client = client
async def connect(self):
# Connect the Azure IoT Hub
await self.__iot_hub_device_client.connect()
# Processing Device Twin document
twin = await self.__iot_hub_device_client.get_twin()
await self.__twin_document_handler(twin)
# Attach Device Twin patch handler
self.__iot_hub_device_client.on_twin_desired_properties_patch_received = self.__twin_patch_handler
# Attach Direct Method handler
self.__iot_hub_device_client.on_method_request_received = self.__direct_method_handler
async def disconnect(self):
# Disconnect the Azure IoT Hub
await self.__iot_hub_device_client.disconnect()
async def send_telemetry(self, name):
payload = {}
if isinstance(name, str):
payload[name] = getattr(self, name).value
elif isinstance(name, tuple):
for n in name:
payload[n] = getattr(self, n).value
else:
raise RuntimeError()
msg = Message(json.dumps(payload))
msg.content_encoding = "utf-8"
msg.content_type = "application/json"
await self.__iot_hub_device_client.send_message(msg)
async def __send_readonly_property(self, name, value):
await self.__iot_hub_device_client.patch_twin_reported_properties({name: value})
async def __send_writable_property_confirm(self, name, value, ack_code, ack_version, description="Completed"):
prop_dict = {}
prop_dict[name] = {
"value": value,
"ac": ack_code,
"av": ack_version,
"ad": description,
}
await self.__iot_hub_device_client.patch_twin_reported_properties(prop_dict)
async def __twin_document_handler(self, twin):
logger.info(f"[twin] Received twin = {twin}")
if "$version" not in twin["desired"]:
raise RuntimeError()
for name in self.__dict__:
content = getattr(self, name)
if isinstance(content, Telemetry):
pass
elif isinstance(content, ReadOnlyProperty):
send_reported = False
if name in twin["reported"]:
if twin["reported"][name] != content.value:
send_reported = True
else:
send_reported = True
if send_reported:
logger.info(f"[twin] Send ReadOnlyProperty {name} = {content.value}")
await self.__send_readonly_property(name, content.value)
elif isinstance(content, WritableProperty):
if name in twin["desired"]:
version = twin["desired"]["$version"]
content.value = twin["desired"][name]
logger.info(f"[twin] Received WritableProperty {name} = {content.value}")
else:
version = 1
logger.info(f"[twin] Send WritableProperty {name} = {content.value}")
await self.__send_writable_property_confirm(name, content.value, 200, version)
elif isinstance(content, Command):
pass
async def __twin_patch_handler(self, patch):
logger.info(f"[patch] Received patch = {patch}")
ack_code = 200
for name in patch.keys():
if name == '$version':
continue
logger.info(f"[patch] Receive WritableProperty {name} = {patch[name]}")
ack_code = 400
if name in self.__dict__:
content = getattr(self, name)
if isinstance(content, WritableProperty):
content.value = patch[name]
ack_code = 200
await self.__send_writable_property_confirm(name, patch[name], ack_code, patch["$version"])
async def __direct_method_handler(self, command_request):
name = command_request.name
payload = command_request.payload
logger.info(f"[command] Received request = {name}, payload={payload}")
response_status = 400
response_payload = None
if name in self.__dict__:
content = getattr(self, name)
if content.handler is not None:
response_status, response_payload = content.handler(payload)
command_response = MethodResponse.create_from_method_request(command_request, response_status, response_payload)
await self.__iot_hub_device_client.send_method_response(command_response) | mj_azure_iot_pnp_device/device/iothub_device_client.py | import logging
import json
from ..contents import *
from azure.iot.device import Message
from azure.iot.device import MethodResponse
logger = logging.getLogger(__name__)
class IoTHubDeviceClient:
def set_iot_hub_device_client(self, client):
self.__iot_hub_device_client = client
async def connect(self):
# Connect the Azure IoT Hub
await self.__iot_hub_device_client.connect()
# Processing Device Twin document
twin = await self.__iot_hub_device_client.get_twin()
await self.__twin_document_handler(twin)
# Attach Device Twin patch handler
self.__iot_hub_device_client.on_twin_desired_properties_patch_received = self.__twin_patch_handler
# Attach Direct Method handler
self.__iot_hub_device_client.on_method_request_received = self.__direct_method_handler
async def disconnect(self):
# Disconnect the Azure IoT Hub
await self.__iot_hub_device_client.disconnect()
async def send_telemetry(self, name):
payload = {}
if isinstance(name, str):
payload[name] = getattr(self, name).value
elif isinstance(name, tuple):
for n in name:
payload[n] = getattr(self, n).value
else:
raise RuntimeError()
msg = Message(json.dumps(payload))
msg.content_encoding = "utf-8"
msg.content_type = "application/json"
await self.__iot_hub_device_client.send_message(msg)
async def __send_readonly_property(self, name, value):
await self.__iot_hub_device_client.patch_twin_reported_properties({name: value})
async def __send_writable_property_confirm(self, name, value, ack_code, ack_version, description="Completed"):
prop_dict = {}
prop_dict[name] = {
"value": value,
"ac": ack_code,
"av": ack_version,
"ad": description,
}
await self.__iot_hub_device_client.patch_twin_reported_properties(prop_dict)
async def __twin_document_handler(self, twin):
logger.info(f"[twin] Received twin = {twin}")
if "$version" not in twin["desired"]:
raise RuntimeError()
for name in self.__dict__:
content = getattr(self, name)
if isinstance(content, Telemetry):
pass
elif isinstance(content, ReadOnlyProperty):
send_reported = False
if name in twin["reported"]:
if twin["reported"][name] != content.value:
send_reported = True
else:
send_reported = True
if send_reported:
logger.info(f"[twin] Send ReadOnlyProperty {name} = {content.value}")
await self.__send_readonly_property(name, content.value)
elif isinstance(content, WritableProperty):
if name in twin["desired"]:
version = twin["desired"]["$version"]
content.value = twin["desired"][name]
logger.info(f"[twin] Received WritableProperty {name} = {content.value}")
else:
version = 1
logger.info(f"[twin] Send WritableProperty {name} = {content.value}")
await self.__send_writable_property_confirm(name, content.value, 200, version)
elif isinstance(content, Command):
pass
async def __twin_patch_handler(self, patch):
logger.info(f"[patch] Received patch = {patch}")
ack_code = 200
for name in patch.keys():
if name == '$version':
continue
logger.info(f"[patch] Receive WritableProperty {name} = {patch[name]}")
ack_code = 400
if name in self.__dict__:
content = getattr(self, name)
if isinstance(content, WritableProperty):
content.value = patch[name]
ack_code = 200
await self.__send_writable_property_confirm(name, patch[name], ack_code, patch["$version"])
async def __direct_method_handler(self, command_request):
name = command_request.name
payload = command_request.payload
logger.info(f"[command] Received request = {name}, payload={payload}")
response_status = 400
response_payload = None
if name in self.__dict__:
content = getattr(self, name)
if content.handler is not None:
response_status, response_payload = content.handler(payload)
command_response = MethodResponse.create_from_method_request(command_request, response_status, response_payload)
await self.__iot_hub_device_client.send_method_response(command_response) | 0.497803 | 0.073099 |
from datetime import datetime
class base():
def identify(self, fields):
return all(elem in fields for elem in list(self.fields_map.keys())[:-4]) # last 4 keys are optional
def txn_from_checking(self, data):
return data == self._from_checking
def txn_currency_conversion(self, data):
return data == self._currency_conversion
def decimal(self, data):
return data
def parse_date(self, data):
return datetime.strptime(data, self._format)
def normalize_keys(self, row):
return { self.fields_map.get(k, k):row[k] for k in row }
class en(base):
fields_map = {
"Date": "date",
"Time": "time",
"TimeZone": "timezone",
"Name": "name",
"Type": "txn_type",
"Status": "status",
"Currency": "currency",
"Gross": "gross",
"Fee": "fee",
"Net": "net",
"From Email Address": "from",
"To Email Address": "to",
"Transaction ID": "txn_id",
"Reference Txn ID": "reference_txn_id",
"Receipt ID": "receipt_id",
# Optional keys:
"Item Title": "item_title",
"Subject": "subject",
"Note": "note",
"Balance": "balance",
}
metadata_map = {
"uuid": "Transaction ID",
"sender": "From Email Address",
"recipient": "To Email Address",
}
_format = "%d/%m/%Y"
_from_checking = "Bank Deposit to PP Account "
_currency_conversion = "General Currency Conversion"
def decimal(self, data):
return data.replace(".", "").replace(",", ".")
class de(base):
fields_map = {
"Datum": "date",
"Uhrzeit": "time",
"Zeitzone": "timezone",
"Name": "name",
"Typ": "txn_type",
"Status": "status",
"Währung": "currency",
"Brutto": "gross",
"Gebühr": "fee",
"Netto": "net",
"Absender E-Mail-Adresse": "from",
"Empfänger E-Mail-Adresse": "to",
"Transaktionscode": "txn_id",
"Zugehöriger Transaktionscode": "reference_txn_id",
"Empfangsnummer": "receipt_id",
# Optional keys:
"Artikelbezeichnung": "item_title",
"Betreff": "subject",
"Hinweis": "note",
"Guthaben": "balance",
}
metadata_map = {
"uuid": "Transaktionscode",
"sender": "Absender E-Mail-Adresse",
"recipient": "Empfänger E-Mail-Adresse",
}
_format = "%d.%m.%Y"
_from_checking = "Bankgutschrift auf PayPal-Konto"
_currency_conversion = "Allgemeine Währungsumrechnung"
def decimal(self, data):
return data.replace(".", "").replace(",", ".") | beancount_paypal/lang.py | from datetime import datetime
class base():
def identify(self, fields):
return all(elem in fields for elem in list(self.fields_map.keys())[:-4]) # last 4 keys are optional
def txn_from_checking(self, data):
return data == self._from_checking
def txn_currency_conversion(self, data):
return data == self._currency_conversion
def decimal(self, data):
return data
def parse_date(self, data):
return datetime.strptime(data, self._format)
def normalize_keys(self, row):
return { self.fields_map.get(k, k):row[k] for k in row }
class en(base):
fields_map = {
"Date": "date",
"Time": "time",
"TimeZone": "timezone",
"Name": "name",
"Type": "txn_type",
"Status": "status",
"Currency": "currency",
"Gross": "gross",
"Fee": "fee",
"Net": "net",
"From Email Address": "from",
"To Email Address": "to",
"Transaction ID": "txn_id",
"Reference Txn ID": "reference_txn_id",
"Receipt ID": "receipt_id",
# Optional keys:
"Item Title": "item_title",
"Subject": "subject",
"Note": "note",
"Balance": "balance",
}
metadata_map = {
"uuid": "Transaction ID",
"sender": "From Email Address",
"recipient": "To Email Address",
}
_format = "%d/%m/%Y"
_from_checking = "Bank Deposit to PP Account "
_currency_conversion = "General Currency Conversion"
def decimal(self, data):
return data.replace(".", "").replace(",", ".")
class de(base):
fields_map = {
"Datum": "date",
"Uhrzeit": "time",
"Zeitzone": "timezone",
"Name": "name",
"Typ": "txn_type",
"Status": "status",
"Währung": "currency",
"Brutto": "gross",
"Gebühr": "fee",
"Netto": "net",
"Absender E-Mail-Adresse": "from",
"Empfänger E-Mail-Adresse": "to",
"Transaktionscode": "txn_id",
"Zugehöriger Transaktionscode": "reference_txn_id",
"Empfangsnummer": "receipt_id",
# Optional keys:
"Artikelbezeichnung": "item_title",
"Betreff": "subject",
"Hinweis": "note",
"Guthaben": "balance",
}
metadata_map = {
"uuid": "Transaktionscode",
"sender": "Absender E-Mail-Adresse",
"recipient": "Empfänger E-Mail-Adresse",
}
_format = "%d.%m.%Y"
_from_checking = "Bankgutschrift auf PayPal-Konto"
_currency_conversion = "Allgemeine Währungsumrechnung"
def decimal(self, data):
return data.replace(".", "").replace(",", ".") | 0.719285 | 0.506958 |
from collections import OrderedDict
import numpy as np
import os
import torch
def create_utt2spkid_pairs(utt2spkid):
_utt2spkid = OrderedDict()
with open(utt2spkid, 'r') as u:
for line in u:
utt, spk = line.split()
_utt2spkid[utt] = int(spk)
return _utt2spkid
def create_utt2spkid(utt2spk, spk2id, utt2spkid, min_spk_size=0):
'''create spk2id and utt2spkid files
and remove spks that contain too few utts
'''
def _create_spk2id(utt2spk, spk2id, min_spk_size):
# get spk2utt first
spk2utt = os.path.dirname(utt2spk) + "/spk2utt"
os.system("utils/utt2spk_to_spk2utt.pl {0} > {1}".format(utt2spk, spk2utt))
num_spks = 0
num_errs = 0
num_skips = 0
with open(spk2utt, 'r') as su, open(spk2id, 'w') as si:
try:
for line in su:
line_sp = line.split()
spk = line_sp[0]
if not len(line_sp[1:]) < min_spk_size:
si.write(spk + ' ' + str(num_spks) + '\n')
num_spks += 1
else:
num_skips += 1
except:
num_errs += 1
print('number of err spks: {0}'.format(num_errs))
print('number of skipped spks: {0}'.format(num_skips))
return num_spks
if not os.path.exists(spk2id):
num_spks = _create_spk2id(utt2spk, spk2id, min_spk_size)
else:
num_spks = sum(1 for line in open(spk2id, 'r'))
spk_id_list = OrderedDict()
with open(spk2id, 'r') as si:
for line in si:
tspk, tspkid = line.split()
spk_id_list[tspk] = tspkid
num_errs = 0
with open(utt2spk, 'r') as us, open(utt2spkid, 'w') as usi:
for line in us:
utt, tspk = line.split()
if tspk in spk_id_list.keys():
usi.write(utt + ' ' + spk_id_list[tspk] + '\n')
else:
num_errs += 1
print('number of err utts: {0}'.format(num_errs))
return num_spks | espnet2/sid/extractor/utils.py | from collections import OrderedDict
import numpy as np
import os
import torch
def create_utt2spkid_pairs(utt2spkid):
_utt2spkid = OrderedDict()
with open(utt2spkid, 'r') as u:
for line in u:
utt, spk = line.split()
_utt2spkid[utt] = int(spk)
return _utt2spkid
def create_utt2spkid(utt2spk, spk2id, utt2spkid, min_spk_size=0):
'''create spk2id and utt2spkid files
and remove spks that contain too few utts
'''
def _create_spk2id(utt2spk, spk2id, min_spk_size):
# get spk2utt first
spk2utt = os.path.dirname(utt2spk) + "/spk2utt"
os.system("utils/utt2spk_to_spk2utt.pl {0} > {1}".format(utt2spk, spk2utt))
num_spks = 0
num_errs = 0
num_skips = 0
with open(spk2utt, 'r') as su, open(spk2id, 'w') as si:
try:
for line in su:
line_sp = line.split()
spk = line_sp[0]
if not len(line_sp[1:]) < min_spk_size:
si.write(spk + ' ' + str(num_spks) + '\n')
num_spks += 1
else:
num_skips += 1
except:
num_errs += 1
print('number of err spks: {0}'.format(num_errs))
print('number of skipped spks: {0}'.format(num_skips))
return num_spks
if not os.path.exists(spk2id):
num_spks = _create_spk2id(utt2spk, spk2id, min_spk_size)
else:
num_spks = sum(1 for line in open(spk2id, 'r'))
spk_id_list = OrderedDict()
with open(spk2id, 'r') as si:
for line in si:
tspk, tspkid = line.split()
spk_id_list[tspk] = tspkid
num_errs = 0
with open(utt2spk, 'r') as us, open(utt2spkid, 'w') as usi:
for line in us:
utt, tspk = line.split()
if tspk in spk_id_list.keys():
usi.write(utt + ' ' + spk_id_list[tspk] + '\n')
else:
num_errs += 1
print('number of err utts: {0}'.format(num_errs))
return num_spks | 0.201499 | 0.235361 |
import scipy.signal as s
import numpy as np
import matplotlib.pyplot as plt
import pyabf
from patch_clamp import database as db
QUERY = """SELECT metadata.fname,
metadata.cell_side,
metadata.cell_n,
metadata.mouse_id,
metadata.treatment_group AS treatment,
peaks.fpath,
peaks.peak_index,
peaks.fpath,
peaks.sweep
FROM peaks INNER JOIN metadata
ON peaks.fname = metadata.fname
WHERE peaks.sweep = REPLACEME"""
def peaks_to_int_list(ditem):
"""helper to convert indicies from database to integers"""
ditem["peak_index"] = db.str_list_to_list_ints(ditem["peak_index"])
return ditem
def _distance(y1, y2):
"""1D distance calculator"""
inner = (y2 - y1) ** 2
d = np.sqrt(inner)
return d
def _fwhm(d_ap):
"""Helper function to calculate the FWHM based on preliminary results from `ap_features`"""
half1y = d_ap["ap_y"][0 : d_ap["ap_max_index"]]
half1x = d_ap["ap_x"][0 : d_ap["ap_max_index"]]
half2y = d_ap["ap_y"][d_ap["ap_max_index"] :]
half2x = d_ap["ap_x"][d_ap["ap_max_index"] :]
half_amplitude = d_ap["ap_max_voltage"] - (d_ap["ap_amplitude"] / 2)
distances1 = [_distance(half_amplitude, i) for i in half1y]
distances2 = [_distance(half_amplitude, i) for i in half2y]
half_max_ind1 = np.where(distances1 == np.min(distances1))[0]
half_max_ind2 = np.where(distances2 == np.min(distances2))[0]
actual_x_1 = half1x[half_max_ind1]
actual_x_2 = half2x[half_max_ind2]
ap_x1_index = np.where(d_ap["ap_x"] == actual_x_1)[0]
ap_x2_index = np.where(d_ap["ap_x"] == actual_x_2)[0]
WIDTH = actual_x_2 - actual_x_1
return int(ap_x1_index[0]), int(ap_x2_index[0]), float(WIDTH[0])
def ap_features(d, ms_window_pre, ms_window_post, threshold, golay_window_pts=19):
"""extract relevant features from the first spike of an action potential"""
ditem = d.copy()
try:
# bail out if no peaks, and return empty lists for all of the
# new keys.
first_index = ditem["peak_index"][0]
except IndexError:
ditem["ap_x"] = []
ditem["ap_y"] = []
ditem["dydx"] = []
ditem["max_dydx"] = []
ditem["max_dydx_index"] = []
ditem["ap_max_index"] = []
ditem["ap_max_voltage"] = []
ditem["firing_threshold_voltage"] = []
ditem["firing_threshold_index"] = []
ditem["ap_amplitude"] = []
ditem["ap_min_index"] = []
ditem["ap_min_voltage"] = []
ditem["AHP_amplitude"] = []
ditem["half_x1_index"] = []
ditem["half_x2_index"] = []
ditem["fwhm"] = []
return ditem
abf = pyabf.ABF(ditem["fpath"])
abf.setSweep(ditem["sweep"])
y_filtered = s.savgol_filter(abf.sweepY, golay_window_pts, 3)
ms_window_pre = int(abf.dataPointsPerMs * ms_window_pre)
ms_window_post = int(abf.dataPointsPerMs * ms_window_post)
start = first_index - ms_window_pre
stop = first_index + ms_window_post
ditem["ap_y"] = y_filtered[start:stop]
ditem["ap_x"] = abf.sweepX[start:stop]
max_ind = np.where(ditem["ap_y"] == np.max(ditem["ap_y"]))[0]
min_ind = np.where(ditem["ap_y"] == np.min(ditem["ap_y"]))[0]
ditem["ap_min_index"] = min_ind[0]
ditem["ap_min_voltage"] = ditem["ap_y"][min_ind]
ditem["ap_max_index"] = max_ind[0]
ditem["ap_max_voltage"] = ditem["ap_y"][max_ind]
ditem["dydx"] = (
np.diff(ditem["ap_y"]) / np.diff(ditem["ap_x"])
) / 1000 # to V from mV
max_dydx_ind = np.where(ditem["dydx"] == np.max(ditem["dydx"]))[0]
max_dydx = ditem["dydx"][max_dydx_ind]
ditem["max_dydx"] = max_dydx
ditem["max_dydx_index"] = max_dydx_ind
f_thresh_index = np.where(ditem["dydx"] > threshold)[0][0]
ditem["firing_threshold_voltage"] = ditem["ap_y"][f_thresh_index]
ditem["firing_threshold_index"] = f_thresh_index
ditem["ap_amplitude"] = _distance(
ditem["ap_max_voltage"], ditem["firing_threshold_voltage"]
)[0]
ditem["AHP_amplitude"] = _distance(
ditem["firing_threshold_voltage"], ditem["ap_min_voltage"]
)
ap_x1_index, ap_x2_index, width = _fwhm(ditem)
ditem["half_x1_index"] = ap_x1_index
ditem["half_x2_index"] = ap_x2_index
ditem["fwhm"] = width
return ditem
def serialize_ap_features(apdict):
"""serialize ap features to add to database"""
out = {}
out["fname"] = apdict["fname"]
out["fpath"] = apdict["fpath"]
out["mouse_id"] = apdict["mouse_id"]
out["sweep"] = apdict["sweep"]
out["treatment"] = apdict["treatment"].lower().strip()
out["cell_side"] = apdict["cell_side"].lower().strip()
out["cell_n"] = apdict["cell_n"]
if not apdict["peak_index"]:
out["ap_max_voltage"] = None
out["max_dydx"] = None
out["firing_threshold_voltage"] = None
out["ap_amplitude"] = None
out["AHP_amplitude"] = None
out["FWHM"] = None
return out
out["ap_max_voltage"] = float(apdict["ap_max_voltage"][0])
out["max_dydx"] = float(apdict["max_dydx"][0])
out["firing_threshold_voltage"] = float(apdict["firing_threshold_voltage"])
out["ap_amplitude"] = float(apdict["ap_amplitude"])
out["AHP_amplitude"] = float(apdict["AHP_amplitude"])
out["FWHM"] = float(apdict["fwhm"])
return out
def plot_ap_features(d):
"""inspect AP feature results returned by `ap_features` via matplotlib"""
fig = plt.figure(figsize=(10, 6))
ax1 = fig.add_subplot(1, 2, 1)
ax2 = fig.add_subplot(1, 2, 2)
if isinstance(d["ap_y"], list):
print("No data")
print(f"{d['fname']}-{d['treatment']}-{d['cell_side']}")
return fig
ax1.plot(d["ap_x"], d["ap_y"])
ax1.plot(
d["ap_x"][d["firing_threshold_index"]],
d["ap_y"][d["firing_threshold_index"]],
"r*",
label="Threshold",
)
ax1.plot(
d["ap_x"][d["ap_max_index"]],
d["ap_y"][d["ap_max_index"]],
"y*",
label="Max amplitude",
)
ax1.plot(
[d["ap_x"][d["half_x1_index"]], d["ap_x"][d["half_x2_index"]]],
[d["ap_y"][d["half_x1_index"]], d["ap_y"][d["half_x2_index"]]],
label="FWHM",
)
ax1.plot(
[
d["ap_x"][d["firing_threshold_index"]],
d["ap_x"][d["firing_threshold_index"]],
],
[d["firing_threshold_voltage"], d["ap_max_voltage"]],
color="red",
label="Max amplitude",
)
ax1.plot(
[d["ap_x"][d["ap_min_index"]], d["ap_x"][d["ap_min_index"]]],
[d["ap_min_voltage"], d["firing_threshold_voltage"]],
color="green",
label="AHP amplitude",
)
ax2.plot(d["ap_y"][:-1], d["dydx"])
ax2.plot(
d["ap_y"][d["firing_threshold_index"]],
d["dydx"][d["firing_threshold_index"]],
"r*",
label="Threshold",
)
ax2.plot(
d["ap_y"][d["ap_max_index"]],
d["dydx"][d["ap_max_index"]],
"y*",
label="Max amplitude",
)
ax2.plot(
d["ap_y"][d["max_dydx_index"]],
d["dydx"][d["max_dydx_index"]],
"b*",
label="max dydx",
)
ax2.legend()
ax1.legend()
fig.suptitle(f"{d['fname']}-{d['treatment']}-{d['cell_side']}")
return fig | patch_clamp/ap_analysis.py | import scipy.signal as s
import numpy as np
import matplotlib.pyplot as plt
import pyabf
from patch_clamp import database as db
QUERY = """SELECT metadata.fname,
metadata.cell_side,
metadata.cell_n,
metadata.mouse_id,
metadata.treatment_group AS treatment,
peaks.fpath,
peaks.peak_index,
peaks.fpath,
peaks.sweep
FROM peaks INNER JOIN metadata
ON peaks.fname = metadata.fname
WHERE peaks.sweep = REPLACEME"""
def peaks_to_int_list(ditem):
"""helper to convert indicies from database to integers"""
ditem["peak_index"] = db.str_list_to_list_ints(ditem["peak_index"])
return ditem
def _distance(y1, y2):
"""1D distance calculator"""
inner = (y2 - y1) ** 2
d = np.sqrt(inner)
return d
def _fwhm(d_ap):
"""Helper function to calculate the FWHM based on preliminary results from `ap_features`"""
half1y = d_ap["ap_y"][0 : d_ap["ap_max_index"]]
half1x = d_ap["ap_x"][0 : d_ap["ap_max_index"]]
half2y = d_ap["ap_y"][d_ap["ap_max_index"] :]
half2x = d_ap["ap_x"][d_ap["ap_max_index"] :]
half_amplitude = d_ap["ap_max_voltage"] - (d_ap["ap_amplitude"] / 2)
distances1 = [_distance(half_amplitude, i) for i in half1y]
distances2 = [_distance(half_amplitude, i) for i in half2y]
half_max_ind1 = np.where(distances1 == np.min(distances1))[0]
half_max_ind2 = np.where(distances2 == np.min(distances2))[0]
actual_x_1 = half1x[half_max_ind1]
actual_x_2 = half2x[half_max_ind2]
ap_x1_index = np.where(d_ap["ap_x"] == actual_x_1)[0]
ap_x2_index = np.where(d_ap["ap_x"] == actual_x_2)[0]
WIDTH = actual_x_2 - actual_x_1
return int(ap_x1_index[0]), int(ap_x2_index[0]), float(WIDTH[0])
def ap_features(d, ms_window_pre, ms_window_post, threshold, golay_window_pts=19):
"""extract relevant features from the first spike of an action potential"""
ditem = d.copy()
try:
# bail out if no peaks, and return empty lists for all of the
# new keys.
first_index = ditem["peak_index"][0]
except IndexError:
ditem["ap_x"] = []
ditem["ap_y"] = []
ditem["dydx"] = []
ditem["max_dydx"] = []
ditem["max_dydx_index"] = []
ditem["ap_max_index"] = []
ditem["ap_max_voltage"] = []
ditem["firing_threshold_voltage"] = []
ditem["firing_threshold_index"] = []
ditem["ap_amplitude"] = []
ditem["ap_min_index"] = []
ditem["ap_min_voltage"] = []
ditem["AHP_amplitude"] = []
ditem["half_x1_index"] = []
ditem["half_x2_index"] = []
ditem["fwhm"] = []
return ditem
abf = pyabf.ABF(ditem["fpath"])
abf.setSweep(ditem["sweep"])
y_filtered = s.savgol_filter(abf.sweepY, golay_window_pts, 3)
ms_window_pre = int(abf.dataPointsPerMs * ms_window_pre)
ms_window_post = int(abf.dataPointsPerMs * ms_window_post)
start = first_index - ms_window_pre
stop = first_index + ms_window_post
ditem["ap_y"] = y_filtered[start:stop]
ditem["ap_x"] = abf.sweepX[start:stop]
max_ind = np.where(ditem["ap_y"] == np.max(ditem["ap_y"]))[0]
min_ind = np.where(ditem["ap_y"] == np.min(ditem["ap_y"]))[0]
ditem["ap_min_index"] = min_ind[0]
ditem["ap_min_voltage"] = ditem["ap_y"][min_ind]
ditem["ap_max_index"] = max_ind[0]
ditem["ap_max_voltage"] = ditem["ap_y"][max_ind]
ditem["dydx"] = (
np.diff(ditem["ap_y"]) / np.diff(ditem["ap_x"])
) / 1000 # to V from mV
max_dydx_ind = np.where(ditem["dydx"] == np.max(ditem["dydx"]))[0]
max_dydx = ditem["dydx"][max_dydx_ind]
ditem["max_dydx"] = max_dydx
ditem["max_dydx_index"] = max_dydx_ind
f_thresh_index = np.where(ditem["dydx"] > threshold)[0][0]
ditem["firing_threshold_voltage"] = ditem["ap_y"][f_thresh_index]
ditem["firing_threshold_index"] = f_thresh_index
ditem["ap_amplitude"] = _distance(
ditem["ap_max_voltage"], ditem["firing_threshold_voltage"]
)[0]
ditem["AHP_amplitude"] = _distance(
ditem["firing_threshold_voltage"], ditem["ap_min_voltage"]
)
ap_x1_index, ap_x2_index, width = _fwhm(ditem)
ditem["half_x1_index"] = ap_x1_index
ditem["half_x2_index"] = ap_x2_index
ditem["fwhm"] = width
return ditem
def serialize_ap_features(apdict):
"""serialize ap features to add to database"""
out = {}
out["fname"] = apdict["fname"]
out["fpath"] = apdict["fpath"]
out["mouse_id"] = apdict["mouse_id"]
out["sweep"] = apdict["sweep"]
out["treatment"] = apdict["treatment"].lower().strip()
out["cell_side"] = apdict["cell_side"].lower().strip()
out["cell_n"] = apdict["cell_n"]
if not apdict["peak_index"]:
out["ap_max_voltage"] = None
out["max_dydx"] = None
out["firing_threshold_voltage"] = None
out["ap_amplitude"] = None
out["AHP_amplitude"] = None
out["FWHM"] = None
return out
out["ap_max_voltage"] = float(apdict["ap_max_voltage"][0])
out["max_dydx"] = float(apdict["max_dydx"][0])
out["firing_threshold_voltage"] = float(apdict["firing_threshold_voltage"])
out["ap_amplitude"] = float(apdict["ap_amplitude"])
out["AHP_amplitude"] = float(apdict["AHP_amplitude"])
out["FWHM"] = float(apdict["fwhm"])
return out
def plot_ap_features(d):
"""inspect AP feature results returned by `ap_features` via matplotlib"""
fig = plt.figure(figsize=(10, 6))
ax1 = fig.add_subplot(1, 2, 1)
ax2 = fig.add_subplot(1, 2, 2)
if isinstance(d["ap_y"], list):
print("No data")
print(f"{d['fname']}-{d['treatment']}-{d['cell_side']}")
return fig
ax1.plot(d["ap_x"], d["ap_y"])
ax1.plot(
d["ap_x"][d["firing_threshold_index"]],
d["ap_y"][d["firing_threshold_index"]],
"r*",
label="Threshold",
)
ax1.plot(
d["ap_x"][d["ap_max_index"]],
d["ap_y"][d["ap_max_index"]],
"y*",
label="Max amplitude",
)
ax1.plot(
[d["ap_x"][d["half_x1_index"]], d["ap_x"][d["half_x2_index"]]],
[d["ap_y"][d["half_x1_index"]], d["ap_y"][d["half_x2_index"]]],
label="FWHM",
)
ax1.plot(
[
d["ap_x"][d["firing_threshold_index"]],
d["ap_x"][d["firing_threshold_index"]],
],
[d["firing_threshold_voltage"], d["ap_max_voltage"]],
color="red",
label="Max amplitude",
)
ax1.plot(
[d["ap_x"][d["ap_min_index"]], d["ap_x"][d["ap_min_index"]]],
[d["ap_min_voltage"], d["firing_threshold_voltage"]],
color="green",
label="AHP amplitude",
)
ax2.plot(d["ap_y"][:-1], d["dydx"])
ax2.plot(
d["ap_y"][d["firing_threshold_index"]],
d["dydx"][d["firing_threshold_index"]],
"r*",
label="Threshold",
)
ax2.plot(
d["ap_y"][d["ap_max_index"]],
d["dydx"][d["ap_max_index"]],
"y*",
label="Max amplitude",
)
ax2.plot(
d["ap_y"][d["max_dydx_index"]],
d["dydx"][d["max_dydx_index"]],
"b*",
label="max dydx",
)
ax2.legend()
ax1.legend()
fig.suptitle(f"{d['fname']}-{d['treatment']}-{d['cell_side']}")
return fig | 0.517571 | 0.429848 |
import http.server
import time
import threading
import io
import subprocess
import os
import numpy as np
from PIL import Image, ImageChops
from selenium import webdriver
# Set to true to create a new set of reference images
CREATE_REF = False
# Run web server
print("Starting web server...")
os.chdir(os.path.dirname(os.path.abspath(__file__))) # cd to script dir
os.chdir("..")
httpd = http.server.HTTPServer(
("localhost", 8000), http.server.SimpleHTTPRequestHandler
)
thread = threading.Thread(None, httpd.serve_forever)
thread.start()
# Create a new instance of the Firefox driver
print("Starting web driver...")
if os.environ.get("TRAVIS_JOB_NUMBER"):
# Configuration for Travis CI / Sauce Labs testing
driver = webdriver.Remote(
command_executor="https://ondemand.saucelabs.com:443/wd/hub",
desired_capabilities={
"username": os.environ["SAUCE_USERNAME"],
"accessKey": os.environ["SAUCE_ACCESS_KEY"],
"tunnel-identifier": os.environ["TRAVIS_JOB_NUMBER"],
"build": os.environ["TRAVIS_JOB_NUMBER"],
"browserName": "firefox",
"seleniumVersion": "3.141.0",
},
)
else:
fp = webdriver.FirefoxProfile()
fp.set_preference("layout.css.devPixelsPerPx", "1.0")
driver = webdriver.Firefox(firefox_profile=fp)
driver.set_window_size(800, 600)
def run_tests():
# Load page
print("Loading page...")
driver.get("http://localhost:8000/tests/tests.html")
# Make sure viewer loaded
print("Running tests...")
time.sleep(5)
viewer = driver.find_element_by_id("panorama")
assert driver.execute_script("return viewer.isLoaded()") == True
# Check equirectangular
assert driver.execute_script("return viewer.getScene() == 'equirectangular'")
if CREATE_REF:
viewer.screenshot("tests/equirectangular.png")
subprocess.call(["optipng", "-o7", "-strip", "all", "equirectangular.png"])
else:
reference = Image.open("tests/equirectangular.png")
screenshot = Image.open(io.BytesIO(viewer.screenshot_as_png)).convert("RGB")
diff = np.mean(np.array(ImageChops.difference(screenshot, reference)))
print("equirectangular difference:", diff)
assert diff < 3
print("PASS: equirectangular")
# Check movement
driver.execute_script("viewer.setPitch(30).setYaw(-20).setHfov(90)")
time.sleep(2)
assert driver.execute_script(
"return viewer.getPitch() == 30 && viewer.getYaw() == -20 && viewer.getHfov() == 90"
)
driver.find_element_by_class_name("pnlm-zoom-in").click()
time.sleep(1)
assert driver.execute_script("return viewer.getHfov() == 85")
driver.find_element_by_class_name("pnlm-zoom-out").click()
time.sleep(1)
assert driver.execute_script("return viewer.getHfov() == 90")
print("PASS: movement")
# Check look at
driver.execute_script("viewer.lookAt(-10, 90, 100)")
time.sleep(2)
assert driver.execute_script(
"return viewer.getPitch() == -10 && viewer.getYaw() == 90 && viewer.getHfov() == 100"
)
print("PASS: look at")
# Check cube
driver.execute_script("viewer.loadScene('cube')")
time.sleep(5)
assert driver.execute_script("return viewer.getScene() == 'cube'")
if CREATE_REF:
viewer.screenshot("tests/cube.png")
subprocess.call(["optipng", "-o7", "-strip", "all", "cube.png"])
else:
reference = Image.open("tests/cube.png")
screenshot = Image.open(io.BytesIO(viewer.screenshot_as_png)).convert("RGB")
diff = np.mean(np.array(ImageChops.difference(screenshot, reference)))
print("cube difference:", diff)
assert diff < 3
print("PASS: cube")
# Check hot spot
driver.find_element_by_class_name("pnlm-scene").click()
time.sleep(5)
assert driver.execute_script("return viewer.getScene() == 'multires'")
print("PASS: hot spot")
# Check multires
if CREATE_REF:
viewer.screenshot("tests/multires.png")
subprocess.call(["optipng", "-o7", "-strip", "all", "multires.png"])
else:
reference = Image.open("tests/multires.png")
screenshot = Image.open(io.BytesIO(viewer.screenshot_as_png)).convert("RGB")
diff = np.mean(np.array(ImageChops.difference(screenshot, reference)))
print("multires difference:", diff)
assert diff < 3
print("PASS: multires")
try:
run_tests()
finally:
driver.quit()
httpd.shutdown()
thread.join() | tests/run_tests.py | import http.server
import time
import threading
import io
import subprocess
import os
import numpy as np
from PIL import Image, ImageChops
from selenium import webdriver
# Set to true to create a new set of reference images
CREATE_REF = False
# Run web server
print("Starting web server...")
os.chdir(os.path.dirname(os.path.abspath(__file__))) # cd to script dir
os.chdir("..")
httpd = http.server.HTTPServer(
("localhost", 8000), http.server.SimpleHTTPRequestHandler
)
thread = threading.Thread(None, httpd.serve_forever)
thread.start()
# Create a new instance of the Firefox driver
print("Starting web driver...")
if os.environ.get("TRAVIS_JOB_NUMBER"):
# Configuration for Travis CI / Sauce Labs testing
driver = webdriver.Remote(
command_executor="https://ondemand.saucelabs.com:443/wd/hub",
desired_capabilities={
"username": os.environ["SAUCE_USERNAME"],
"accessKey": os.environ["SAUCE_ACCESS_KEY"],
"tunnel-identifier": os.environ["TRAVIS_JOB_NUMBER"],
"build": os.environ["TRAVIS_JOB_NUMBER"],
"browserName": "firefox",
"seleniumVersion": "3.141.0",
},
)
else:
fp = webdriver.FirefoxProfile()
fp.set_preference("layout.css.devPixelsPerPx", "1.0")
driver = webdriver.Firefox(firefox_profile=fp)
driver.set_window_size(800, 600)
def run_tests():
# Load page
print("Loading page...")
driver.get("http://localhost:8000/tests/tests.html")
# Make sure viewer loaded
print("Running tests...")
time.sleep(5)
viewer = driver.find_element_by_id("panorama")
assert driver.execute_script("return viewer.isLoaded()") == True
# Check equirectangular
assert driver.execute_script("return viewer.getScene() == 'equirectangular'")
if CREATE_REF:
viewer.screenshot("tests/equirectangular.png")
subprocess.call(["optipng", "-o7", "-strip", "all", "equirectangular.png"])
else:
reference = Image.open("tests/equirectangular.png")
screenshot = Image.open(io.BytesIO(viewer.screenshot_as_png)).convert("RGB")
diff = np.mean(np.array(ImageChops.difference(screenshot, reference)))
print("equirectangular difference:", diff)
assert diff < 3
print("PASS: equirectangular")
# Check movement
driver.execute_script("viewer.setPitch(30).setYaw(-20).setHfov(90)")
time.sleep(2)
assert driver.execute_script(
"return viewer.getPitch() == 30 && viewer.getYaw() == -20 && viewer.getHfov() == 90"
)
driver.find_element_by_class_name("pnlm-zoom-in").click()
time.sleep(1)
assert driver.execute_script("return viewer.getHfov() == 85")
driver.find_element_by_class_name("pnlm-zoom-out").click()
time.sleep(1)
assert driver.execute_script("return viewer.getHfov() == 90")
print("PASS: movement")
# Check look at
driver.execute_script("viewer.lookAt(-10, 90, 100)")
time.sleep(2)
assert driver.execute_script(
"return viewer.getPitch() == -10 && viewer.getYaw() == 90 && viewer.getHfov() == 100"
)
print("PASS: look at")
# Check cube
driver.execute_script("viewer.loadScene('cube')")
time.sleep(5)
assert driver.execute_script("return viewer.getScene() == 'cube'")
if CREATE_REF:
viewer.screenshot("tests/cube.png")
subprocess.call(["optipng", "-o7", "-strip", "all", "cube.png"])
else:
reference = Image.open("tests/cube.png")
screenshot = Image.open(io.BytesIO(viewer.screenshot_as_png)).convert("RGB")
diff = np.mean(np.array(ImageChops.difference(screenshot, reference)))
print("cube difference:", diff)
assert diff < 3
print("PASS: cube")
# Check hot spot
driver.find_element_by_class_name("pnlm-scene").click()
time.sleep(5)
assert driver.execute_script("return viewer.getScene() == 'multires'")
print("PASS: hot spot")
# Check multires
if CREATE_REF:
viewer.screenshot("tests/multires.png")
subprocess.call(["optipng", "-o7", "-strip", "all", "multires.png"])
else:
reference = Image.open("tests/multires.png")
screenshot = Image.open(io.BytesIO(viewer.screenshot_as_png)).convert("RGB")
diff = np.mean(np.array(ImageChops.difference(screenshot, reference)))
print("multires difference:", diff)
assert diff < 3
print("PASS: multires")
try:
run_tests()
finally:
driver.quit()
httpd.shutdown()
thread.join() | 0.378804 | 0.146423 |
import time, pygame, sys, os, shutil, derpapi
os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (0,0)
pygame.init()
screen = pygame.display.set_mode([480,320], pygame.NOFRAME)
pygame.display.flip()
derpapi.store('BOOT', data=time.time())
pygame.mouse.set_cursor(*pygame.cursors.diamond)
pygame.mouse.set_visible(False)
'''
#run intro
dpos = 0
dlogo = pygame.image.load('derplogo.png')
for i in range(50):
screen.fill([230,230,230])
pygame.draw.rect(screen, pygame.Color(0,0,0,0), pygame.Rect(200, 220, 40, 100))
pygame.display.flip()
screen.blit(dlogo, (220, dpos))
pygame.display.flip()
dpos += 4
time.sleep(0.05)
pygame.event.get()
start = pygame.mixer.Sound('start.wav')
start.play()
time.sleep(6)
for i in range(70):
screen.fill([230,230,230])
pygame.draw.rect(screen, pygame.Color(0,0,0,0), pygame.Rect(200, 220, 40, 100))
pygame.display.flip()
dlogo = pygame.transform.rotate(dlogo, -2)
screen.blit(dlogo, (220, dpos))
pygame.display.flip()
time.sleep(0.05)
pygame.event.get()
opacity = 255
box = pygame.Surface((40, 100), pygame.SRCALPHA)
for i in range(52):
screen.fill([230,230,230])
box.fill([0,0,0,opacity])
screen.blit(box, (200,220))
pygame.display.flip()
opacity -= 5
time.sleep(0.02)
pygame.event.get()
screen.fill([230,230,230])
pygame.display.flip()
#intro complete
'''
pR = pygame.image.load('pointerR.png')
pL = pygame.image.load('pointerL.png')
pygame.mouse.set_visible(True)
apps = []
for DIR in os.listdir('apps'):
df = open('apps\\' + DIR + '\\data.txt', 'r')
data = df.read().splitlines()
df.close()
apps.append({'path': 'apps\\' + DIR + '\\', 'icon': pygame.transform.scale(pygame.image.load('apps\\' + DIR + '\\icon.png'), (96, 96)), 'main': open('apps\\' + DIR + '\\main.py', 'r').read(), 'name': data[0]})
main_font = pygame.font.Font('font_main.otf', 32)
def launch(app):
pygame.display.quit()
os.chdir(app['path'])
try:
exec(app['main'])
except SystemExit:
pass
except derpapi.EndApp:
pass
except derpapi.Shutdown: #shutdown
sys.exit(0)
os.chdir('..\\..\\')
pygame.display.init()
pygame.font.init()
screen = pygame.display.set_mode([480,320], pygame.NOFRAME)
pygame.display.flip()
pygame.mouse.set_cursor(*pygame.cursors.diamond)
apps = []
for DIR in os.listdir('apps'):
df = open('apps\\' + DIR + '\\data.txt', 'r')
data = df.read().splitlines()
df.close()
apps.append({'path': 'apps\\' + DIR + '\\', 'icon': pygame.transform.scale(pygame.image.load('apps\\' + DIR + '\\icon.png'), (96, 96)), 'main': open('apps\\' + DIR + '\\main.py', 'r').read(), 'name': data[0]})
return screen, apps
curpos = 0
while True:
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN:
if event.pos[0] >= 400 and event.pos[0] <= 450 and event.pos[1] >= 110 and event.pos[1] <= 210:
curpos += 1
if curpos == len(apps):
curpos = 0
if event.pos[0] >= 30 and event.pos[0] <= 80 and event.pos[1] >= 110 and event.pos[1] <= 210:
curpos -= 1
if curpos < 0:
curpos = len(apps) - 1
if event.pos[0] >= 192 and event.pos[0] <= 288 and event.pos[1] >= 112 and event.pos[1] <= 208:
screen, apps = launch(apps[curpos])
#print(curpos)
screen.fill([230,230,230])
screen.blit(pR, (400, 110))
screen.blit(pL, (30, 110))
screen.blit(apps[curpos]['icon'], (192, 112))
try:
screen.blit(main_font.render(apps[curpos]['name'], True, (0,0,0)), (30, 260))
except:
main_font = pygame.font.Font('font_main.otf', 32)
screen.blit(main_font.render(apps[curpos]['name'] + ' ', True, (0,0,0)), (30, 260))
pygame.display.flip() | DerPi/main_os.py | import time, pygame, sys, os, shutil, derpapi
os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (0,0)
pygame.init()
screen = pygame.display.set_mode([480,320], pygame.NOFRAME)
pygame.display.flip()
derpapi.store('BOOT', data=time.time())
pygame.mouse.set_cursor(*pygame.cursors.diamond)
pygame.mouse.set_visible(False)
'''
#run intro
dpos = 0
dlogo = pygame.image.load('derplogo.png')
for i in range(50):
screen.fill([230,230,230])
pygame.draw.rect(screen, pygame.Color(0,0,0,0), pygame.Rect(200, 220, 40, 100))
pygame.display.flip()
screen.blit(dlogo, (220, dpos))
pygame.display.flip()
dpos += 4
time.sleep(0.05)
pygame.event.get()
start = pygame.mixer.Sound('start.wav')
start.play()
time.sleep(6)
for i in range(70):
screen.fill([230,230,230])
pygame.draw.rect(screen, pygame.Color(0,0,0,0), pygame.Rect(200, 220, 40, 100))
pygame.display.flip()
dlogo = pygame.transform.rotate(dlogo, -2)
screen.blit(dlogo, (220, dpos))
pygame.display.flip()
time.sleep(0.05)
pygame.event.get()
opacity = 255
box = pygame.Surface((40, 100), pygame.SRCALPHA)
for i in range(52):
screen.fill([230,230,230])
box.fill([0,0,0,opacity])
screen.blit(box, (200,220))
pygame.display.flip()
opacity -= 5
time.sleep(0.02)
pygame.event.get()
screen.fill([230,230,230])
pygame.display.flip()
#intro complete
'''
pR = pygame.image.load('pointerR.png')
pL = pygame.image.load('pointerL.png')
pygame.mouse.set_visible(True)
apps = []
for DIR in os.listdir('apps'):
df = open('apps\\' + DIR + '\\data.txt', 'r')
data = df.read().splitlines()
df.close()
apps.append({'path': 'apps\\' + DIR + '\\', 'icon': pygame.transform.scale(pygame.image.load('apps\\' + DIR + '\\icon.png'), (96, 96)), 'main': open('apps\\' + DIR + '\\main.py', 'r').read(), 'name': data[0]})
main_font = pygame.font.Font('font_main.otf', 32)
def launch(app):
pygame.display.quit()
os.chdir(app['path'])
try:
exec(app['main'])
except SystemExit:
pass
except derpapi.EndApp:
pass
except derpapi.Shutdown: #shutdown
sys.exit(0)
os.chdir('..\\..\\')
pygame.display.init()
pygame.font.init()
screen = pygame.display.set_mode([480,320], pygame.NOFRAME)
pygame.display.flip()
pygame.mouse.set_cursor(*pygame.cursors.diamond)
apps = []
for DIR in os.listdir('apps'):
df = open('apps\\' + DIR + '\\data.txt', 'r')
data = df.read().splitlines()
df.close()
apps.append({'path': 'apps\\' + DIR + '\\', 'icon': pygame.transform.scale(pygame.image.load('apps\\' + DIR + '\\icon.png'), (96, 96)), 'main': open('apps\\' + DIR + '\\main.py', 'r').read(), 'name': data[0]})
return screen, apps
curpos = 0
while True:
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN:
if event.pos[0] >= 400 and event.pos[0] <= 450 and event.pos[1] >= 110 and event.pos[1] <= 210:
curpos += 1
if curpos == len(apps):
curpos = 0
if event.pos[0] >= 30 and event.pos[0] <= 80 and event.pos[1] >= 110 and event.pos[1] <= 210:
curpos -= 1
if curpos < 0:
curpos = len(apps) - 1
if event.pos[0] >= 192 and event.pos[0] <= 288 and event.pos[1] >= 112 and event.pos[1] <= 208:
screen, apps = launch(apps[curpos])
#print(curpos)
screen.fill([230,230,230])
screen.blit(pR, (400, 110))
screen.blit(pL, (30, 110))
screen.blit(apps[curpos]['icon'], (192, 112))
try:
screen.blit(main_font.render(apps[curpos]['name'], True, (0,0,0)), (30, 260))
except:
main_font = pygame.font.Font('font_main.otf', 32)
screen.blit(main_font.render(apps[curpos]['name'] + ' ', True, (0,0,0)), (30, 260))
pygame.display.flip() | 0.038421 | 0.167934 |
import pytest
from support.socket import DummySocketIO
from core.constants import CellEvents, CellExecutionStatus
from ..socket import LocalSocketIO, CellEventsSocket
__author__ = '<NAME> (<EMAIL>)'
@pytest.mark.unit
@pytest.mark.utils
def test_local_socketio(mocker):
gsio = DummySocketIO()
mocked = mocker.patch.object(gsio, 'emit', autospec=True)
sio = LocalSocketIO(gsio, 'channel', 'namespace')
sio.emit('test_event', 'test_args')
assert mocked.call_count == 1
mocked.assert_called_once_with('test_event',
'test_args',
room='channel',
namespace='namespace')
@pytest.mark.unit
@pytest.mark.utils
def test_cell_events_socket_start(mocker):
lio = LocalSocketIO(DummySocketIO(), 'c', 'n')
csocket = CellEventsSocket(lio, 'cid')
mocked = mocker.patch.object(lio, 'emit', autospec=True)
csocket.start()
assert mocked.call_count == 1
mocked.assert_called_once_with(CellEvents.START_RUN, {
'id': 'cid',
'status': CellExecutionStatus.BUSY
})
@pytest.mark.unit
@pytest.mark.utils
def test_cell_events_socket_stdout(mocker):
lio = LocalSocketIO(DummySocketIO(), 'c', 'n')
csocket = CellEventsSocket(lio, 'cid')
mocked = mocker.patch.object(lio, 'emit', autospec=True)
csocket.stdout(['a', 'b'])
assert mocked.call_count == 1
mocked.assert_called_once_with(CellEvents.RESULT, {
'id': 'cid',
'output': 'a\nb'
})
@pytest.mark.unit
@pytest.mark.utils
def test_cell_events_socket_stderr(mocker):
lio = LocalSocketIO(DummySocketIO(), 'c', 'n')
csocket = CellEventsSocket(lio, 'cid')
mocked = mocker.patch.object(lio, 'emit', autospec=True)
csocket.stderr(['a', 'b'])
assert mocked.call_count == 1
mocked.assert_called_once_with(CellEvents.RESULT, {
'id': 'cid',
'error': 'a\nb'
})
@pytest.mark.unit
@pytest.mark.utils
def test_cell_events_socket_done_success(mocker):
lio = LocalSocketIO(DummySocketIO(), 'c', 'n')
csocket = CellEventsSocket(lio, 'cid')
mocked = mocker.patch.object(lio, 'emit', autospec=True)
csocket.done(0)
assert mocked.call_count == 1
mocked.assert_called_once_with(CellEvents.END_RUN, {
'id': 'cid',
'status': CellExecutionStatus.DONE
})
@pytest.mark.unit
@pytest.mark.utils
def test_cell_events_socket_done_error(mocker):
lio = LocalSocketIO(DummySocketIO(), 'c', 'n')
csocket = CellEventsSocket(lio, 'cid')
mocked = mocker.patch.object(lio, 'emit', autospec=True)
csocket.done(1)
assert mocked.call_count == 1
mocked.assert_called_once_with(CellEvents.END_RUN, {
'id': 'cid',
'status': CellExecutionStatus.ERROR
}) | core/utils/tests/test_socket.py | import pytest
from support.socket import DummySocketIO
from core.constants import CellEvents, CellExecutionStatus
from ..socket import LocalSocketIO, CellEventsSocket
__author__ = '<NAME> (<EMAIL>)'
@pytest.mark.unit
@pytest.mark.utils
def test_local_socketio(mocker):
gsio = DummySocketIO()
mocked = mocker.patch.object(gsio, 'emit', autospec=True)
sio = LocalSocketIO(gsio, 'channel', 'namespace')
sio.emit('test_event', 'test_args')
assert mocked.call_count == 1
mocked.assert_called_once_with('test_event',
'test_args',
room='channel',
namespace='namespace')
@pytest.mark.unit
@pytest.mark.utils
def test_cell_events_socket_start(mocker):
lio = LocalSocketIO(DummySocketIO(), 'c', 'n')
csocket = CellEventsSocket(lio, 'cid')
mocked = mocker.patch.object(lio, 'emit', autospec=True)
csocket.start()
assert mocked.call_count == 1
mocked.assert_called_once_with(CellEvents.START_RUN, {
'id': 'cid',
'status': CellExecutionStatus.BUSY
})
@pytest.mark.unit
@pytest.mark.utils
def test_cell_events_socket_stdout(mocker):
lio = LocalSocketIO(DummySocketIO(), 'c', 'n')
csocket = CellEventsSocket(lio, 'cid')
mocked = mocker.patch.object(lio, 'emit', autospec=True)
csocket.stdout(['a', 'b'])
assert mocked.call_count == 1
mocked.assert_called_once_with(CellEvents.RESULT, {
'id': 'cid',
'output': 'a\nb'
})
@pytest.mark.unit
@pytest.mark.utils
def test_cell_events_socket_stderr(mocker):
lio = LocalSocketIO(DummySocketIO(), 'c', 'n')
csocket = CellEventsSocket(lio, 'cid')
mocked = mocker.patch.object(lio, 'emit', autospec=True)
csocket.stderr(['a', 'b'])
assert mocked.call_count == 1
mocked.assert_called_once_with(CellEvents.RESULT, {
'id': 'cid',
'error': 'a\nb'
})
@pytest.mark.unit
@pytest.mark.utils
def test_cell_events_socket_done_success(mocker):
lio = LocalSocketIO(DummySocketIO(), 'c', 'n')
csocket = CellEventsSocket(lio, 'cid')
mocked = mocker.patch.object(lio, 'emit', autospec=True)
csocket.done(0)
assert mocked.call_count == 1
mocked.assert_called_once_with(CellEvents.END_RUN, {
'id': 'cid',
'status': CellExecutionStatus.DONE
})
@pytest.mark.unit
@pytest.mark.utils
def test_cell_events_socket_done_error(mocker):
lio = LocalSocketIO(DummySocketIO(), 'c', 'n')
csocket = CellEventsSocket(lio, 'cid')
mocked = mocker.patch.object(lio, 'emit', autospec=True)
csocket.done(1)
assert mocked.call_count == 1
mocked.assert_called_once_with(CellEvents.END_RUN, {
'id': 'cid',
'status': CellExecutionStatus.ERROR
}) | 0.545528 | 0.4206 |
import os
import serial
import pysynth as ps
import paho.mqtt.client as mqtt
SERIAL_PORT = '/dev/ttyACM0'
SERIAL_RATE = 115200
MQTT_BROKER = "mqtt.eclipse.org"
MQTT_PORT = 1883
MQTT_PUB_TOPIC = "kuviyam/chandrasekar/piano"
keystate0 = [False] * 12
keystate1 = [False] * 12
keystate2 = [False] * 12
oct_cur = 0
oct_state = False
octave_select = "4"
def play_sound(duration, note, client1):
global MQTT_PUB_TOPIC
freq = float(ps.getfreq()[0][note])
print(note)
ret= client1.publish(MQTT_PUB_TOPIC,note)
os.system('play -nq -t alsa synth {} sine {} &'.format(duration, freq))
# sudo apt install sox
def play(octave_select, zero, one, two, three, four, five, six, client1):
global keystate0, keystate1, keystate2
note = ['c', 'c#', 'd', 'd#', 'e', 'f', 'f#', 'g', 'g#', 'a', 'a#', 'b', 'b#']
oct0 = "000000000"+zero
for i in range(0,12):
if oct0[i] == '0' and keystate0[i] == False:
keystate0[i] = True
play_sound(0.1, note[i]+str(int(octave_select)-1), client1)
elif oct0[i] == '1':
keystate0[i] = False
oct1 = one + two + three
for i in range(0,12):
if oct1[i] == '0' and keystate1[i] == False:
keystate1[i] = True
play_sound(0.1, note[i]+octave_select, client1)
elif oct1[i] == '1':
keystate1[i] = False
oct2 = four + five + six
for i in range(0,12):
if oct2[i] == '0' and keystate2[i] == False:
keystate2[i] = True
play_sound(0.1, note[i]+str(int(octave_select)+1), client1)
elif oct2[i] == '1':
keystate2[i] = False
def main(client1):
global oct_cur, octave_select
ser = serial.Serial(SERIAL_PORT, SERIAL_RATE)
while True:
try:
reading = ser.readline().decode('utf-8').rstrip().upper()
if len(reading) == 7:
zero = str("{0:04b}".format(int(reading[0], 16))) # SWITCH a3 a#3 b3
one = str("{0:04b}".format(int(reading[1], 16))) # c4 c#4 d4 d#4
two = str("{0:04b}".format(int(reading[2], 16))) # e4 f4 f#4 g4
three = str("{0:04b}".format(int(reading[3], 16)))# g#4 a4 a#4 b4
four = str("{0:04b}".format(int(reading[4], 16))) # c5 c#5 d5 d#5
five = str("{0:04b}".format(int(reading[5], 16))) # e5 f5 f#5 g5
six = str("{0:04b}".format(int(reading[6], 16))) # g#5 a5 a#5 b5
# Toggle octave select switch state
if zero[3] == '0' and oct_state == False:
oct_state = True
if (oct_cur < 1):
oct_cur = oct_cur + 1
else:
oct_cur = 0
elif zero[3] == '1':
oct_state = False
octave_select = str(oct_cur + 4)
play(octave_select, zero[0:3][::-1], one[::-1], two[::-1], three[::-1],
four[::-1], five[::-1], six[::-1], client1)
except Exception as e:
print("Exception occured",e)
if __name__ == "__main__":
client1= mqtt.Client("control1")
client1.connect(MQTT_BROKER, MQTT_PORT)
main(client1) | Arduino-python-piano/python_code/keyboard_mqtt_publish_notes.py |
import os
import serial
import pysynth as ps
import paho.mqtt.client as mqtt
SERIAL_PORT = '/dev/ttyACM0'
SERIAL_RATE = 115200
MQTT_BROKER = "mqtt.eclipse.org"
MQTT_PORT = 1883
MQTT_PUB_TOPIC = "kuviyam/chandrasekar/piano"
keystate0 = [False] * 12
keystate1 = [False] * 12
keystate2 = [False] * 12
oct_cur = 0
oct_state = False
octave_select = "4"
def play_sound(duration, note, client1):
global MQTT_PUB_TOPIC
freq = float(ps.getfreq()[0][note])
print(note)
ret= client1.publish(MQTT_PUB_TOPIC,note)
os.system('play -nq -t alsa synth {} sine {} &'.format(duration, freq))
# sudo apt install sox
def play(octave_select, zero, one, two, three, four, five, six, client1):
global keystate0, keystate1, keystate2
note = ['c', 'c#', 'd', 'd#', 'e', 'f', 'f#', 'g', 'g#', 'a', 'a#', 'b', 'b#']
oct0 = "000000000"+zero
for i in range(0,12):
if oct0[i] == '0' and keystate0[i] == False:
keystate0[i] = True
play_sound(0.1, note[i]+str(int(octave_select)-1), client1)
elif oct0[i] == '1':
keystate0[i] = False
oct1 = one + two + three
for i in range(0,12):
if oct1[i] == '0' and keystate1[i] == False:
keystate1[i] = True
play_sound(0.1, note[i]+octave_select, client1)
elif oct1[i] == '1':
keystate1[i] = False
oct2 = four + five + six
for i in range(0,12):
if oct2[i] == '0' and keystate2[i] == False:
keystate2[i] = True
play_sound(0.1, note[i]+str(int(octave_select)+1), client1)
elif oct2[i] == '1':
keystate2[i] = False
def main(client1):
global oct_cur, octave_select
ser = serial.Serial(SERIAL_PORT, SERIAL_RATE)
while True:
try:
reading = ser.readline().decode('utf-8').rstrip().upper()
if len(reading) == 7:
zero = str("{0:04b}".format(int(reading[0], 16))) # SWITCH a3 a#3 b3
one = str("{0:04b}".format(int(reading[1], 16))) # c4 c#4 d4 d#4
two = str("{0:04b}".format(int(reading[2], 16))) # e4 f4 f#4 g4
three = str("{0:04b}".format(int(reading[3], 16)))# g#4 a4 a#4 b4
four = str("{0:04b}".format(int(reading[4], 16))) # c5 c#5 d5 d#5
five = str("{0:04b}".format(int(reading[5], 16))) # e5 f5 f#5 g5
six = str("{0:04b}".format(int(reading[6], 16))) # g#5 a5 a#5 b5
# Toggle octave select switch state
if zero[3] == '0' and oct_state == False:
oct_state = True
if (oct_cur < 1):
oct_cur = oct_cur + 1
else:
oct_cur = 0
elif zero[3] == '1':
oct_state = False
octave_select = str(oct_cur + 4)
play(octave_select, zero[0:3][::-1], one[::-1], two[::-1], three[::-1],
four[::-1], five[::-1], six[::-1], client1)
except Exception as e:
print("Exception occured",e)
if __name__ == "__main__":
client1= mqtt.Client("control1")
client1.connect(MQTT_BROKER, MQTT_PORT)
main(client1) | 0.196441 | 0.187616 |
from kivy.app import App
from kivy.base import runTouchApp
from kivy.lang import Builder
from kivy.properties import (
ObjectProperty,
ListProperty,
StringProperty,
NumericProperty,
Clock,
partial,
)
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.textinput import TextInput
import os
import sys
Builder.load_string(
"""
<KivyConsole>:
console_output: console_output
scroll_view: scroll_view
ScrollView:
id: scroll_view
bar_width: 10
ConsoleOutput:
id: console_output
readonly: True
padding: 6, 6
size_hint: (1, None)
font_name: root.font_name
font_size: root.font_size
foreground_color: root.foreground_color
background_color: root.background_color
height: max(self.parent.height, self.minimum_height)
"""
)
class ConsoleOutput(TextInput):
# __events__ = ('on_start', )
def __init__(self, **kwargs):
super(ConsoleOutput, self).__init__(**kwargs)
app = App.get_running_app()
app.bind(on_start=self.my_on_start)
def is_at_bottom(self):
return self.parent.scroll_y <= 0.05
def scroll_to_bottom(self):
self.parent.scroll_y = 0
def add_text(self, text):
text += "\n"
is_locked = self.is_at_bottom()
self.text += text
self.parent.scroll_y = 0
if is_locked:
self.scroll_to_bottom()
# print("FORCE SCROLL", self.parent.scroll_y)
# self.parent.scroll_y = 1 # lock-to-bottom behaviour
##print(output)
# Clock.schedule_once(self.parent.scroll_y = 1)
def my_on_start(self, *args, **kwargs):
print(">MY ON START", args, kwargs, self.parent)
self.add_text("\n".join(str(i) for i in range(50)))
class KivyConsole(BoxLayout):
console_output = ObjectProperty(None)
"""Instance of ConsoleOutput
:data:`console_output` is an :class:`~kivy.properties.ObjectProperty`
"""
scroll_view = ObjectProperty(None)
"""Instance of :class:`~kivy.uix.scrollview.ScrollView`
:data:`scroll_view` is an :class:`~kivy.properties.ObjectProperty`
"""
foreground_color = ListProperty((1, 1, 1, 1))
"""This defines the color of the text in the console
:data:`foreground_color` is an :class:`~kivy.properties.ListProperty`,
Default to '(.5, .5, .5, .93)'
"""
background_color = ListProperty((0, 0, 0, 1))
"""This defines the color of the background in the console
:data:`foreground_color` is an :class:`~kivy.properties.ListProperty`,
Default to '(0, 0, 0, 1)"""
font_name = StringProperty("data/fonts/Roboto-Regular.ttf")
"""Indicates the font Style used in the console
:data:`font` is a :class:`~kivy.properties.StringProperty`,
Default to 'DroidSansMono'
"""
font_size = NumericProperty(14)
"""Indicates the size of the font used for the console
:data:`font_size` is a :class:`~kivy.properties.NumericProperty`,
Default to '9'
"""
def __init__(self, **kwargs):
super(KivyConsole, self).__init__(**kwargs)
if __name__ == "__main__":
runTouchApp(KivyConsole()) | src/waclient/console.py | from kivy.app import App
from kivy.base import runTouchApp
from kivy.lang import Builder
from kivy.properties import (
ObjectProperty,
ListProperty,
StringProperty,
NumericProperty,
Clock,
partial,
)
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.textinput import TextInput
import os
import sys
Builder.load_string(
"""
<KivyConsole>:
console_output: console_output
scroll_view: scroll_view
ScrollView:
id: scroll_view
bar_width: 10
ConsoleOutput:
id: console_output
readonly: True
padding: 6, 6
size_hint: (1, None)
font_name: root.font_name
font_size: root.font_size
foreground_color: root.foreground_color
background_color: root.background_color
height: max(self.parent.height, self.minimum_height)
"""
)
class ConsoleOutput(TextInput):
# __events__ = ('on_start', )
def __init__(self, **kwargs):
super(ConsoleOutput, self).__init__(**kwargs)
app = App.get_running_app()
app.bind(on_start=self.my_on_start)
def is_at_bottom(self):
return self.parent.scroll_y <= 0.05
def scroll_to_bottom(self):
self.parent.scroll_y = 0
def add_text(self, text):
text += "\n"
is_locked = self.is_at_bottom()
self.text += text
self.parent.scroll_y = 0
if is_locked:
self.scroll_to_bottom()
# print("FORCE SCROLL", self.parent.scroll_y)
# self.parent.scroll_y = 1 # lock-to-bottom behaviour
##print(output)
# Clock.schedule_once(self.parent.scroll_y = 1)
def my_on_start(self, *args, **kwargs):
print(">MY ON START", args, kwargs, self.parent)
self.add_text("\n".join(str(i) for i in range(50)))
class KivyConsole(BoxLayout):
console_output = ObjectProperty(None)
"""Instance of ConsoleOutput
:data:`console_output` is an :class:`~kivy.properties.ObjectProperty`
"""
scroll_view = ObjectProperty(None)
"""Instance of :class:`~kivy.uix.scrollview.ScrollView`
:data:`scroll_view` is an :class:`~kivy.properties.ObjectProperty`
"""
foreground_color = ListProperty((1, 1, 1, 1))
"""This defines the color of the text in the console
:data:`foreground_color` is an :class:`~kivy.properties.ListProperty`,
Default to '(.5, .5, .5, .93)'
"""
background_color = ListProperty((0, 0, 0, 1))
"""This defines the color of the background in the console
:data:`foreground_color` is an :class:`~kivy.properties.ListProperty`,
Default to '(0, 0, 0, 1)"""
font_name = StringProperty("data/fonts/Roboto-Regular.ttf")
"""Indicates the font Style used in the console
:data:`font` is a :class:`~kivy.properties.StringProperty`,
Default to 'DroidSansMono'
"""
font_size = NumericProperty(14)
"""Indicates the size of the font used for the console
:data:`font_size` is a :class:`~kivy.properties.NumericProperty`,
Default to '9'
"""
def __init__(self, **kwargs):
super(KivyConsole, self).__init__(**kwargs)
if __name__ == "__main__":
runTouchApp(KivyConsole()) | 0.406862 | 0.118487 |
import os,sys,json,redis
from ssh import SSH_SSH
from ssh_error import SSHError
import threading
import ssh_settings
r = redis.StrictRedis(host=ssh_settings.redisip, port=ssh_settings.redisport, db=0)
class SSHControler(object):
def __init__(self):
self.SSH = SSH_SSH()
def controler_center(self, parameter={}):
cmd = parameter.get("cmd", False)
tid = parameter["tid"]
pass
def connect(self, ip=""):
ssh_info = {"content": "", "status": False}
try:
server_config = self.convert_id_to_ip(ip)
# print server_config
if not server_config["status"]: raise SSHError(server_config["content"])
if server_config["status"]:
ssh_info = self.SSH.login(**server_config["content"])
else:
ssh_info["content"] = server_config["content"]
except Exception, e:
print "ssh错误", str(e)
ssh_info["content"] = str(e)
ssh_info["status"] = False
return ssh_info
def command_controler(self, tid='', cmd='', ip=""):
log_name = "log.%s.%s" % (tid, ip)
log_content = {
"content": "",
"stage": "done",
"status": False,
}
ssh_info = {"content": "", "status": False}
try:
current = "current.%s" % tid
data = self.connect(ip=ip)
if data["status"]:
ssh = data["content"] ###登录界面
self.SSH.execute(cmd=cmd, ip=ip, tid=tid)
ssh_info["status"] = True
else:
raise SSHError(data["content"])
except Exception, e:
print "程序错误", e,'controller'
log_content["content"] = str(e)
log_content = json.dumps(log_content, encoding="utf8", ensure_ascii=False)
r.rpush(log_name, log_content)
ssh_info["content"] = str(e)
ssh_info["status"] = False
print ssh_info,'60'
r.incr(current)
return ssh_info
# @staticmethod
def convert_id_to_ip(self,ip=""):
ssh_info = {"status": False, "content": "指定的ID不存在"}
try:
servers_list = r.lrange("server", 0, -1)
if servers_list is None:
pass
else:
for _line in servers_list:
line = json.loads(_line)
if str(ip) == line["ip"]:
ssh_info["content"] = line
ssh_info["status"] = True
break
except Exception, e:
ssh_info["status"] = False
ssh_info["content"] = str(e)
return ssh_info | devops/ops/views/ssh_module_controller.py | import os,sys,json,redis
from ssh import SSH_SSH
from ssh_error import SSHError
import threading
import ssh_settings
r = redis.StrictRedis(host=ssh_settings.redisip, port=ssh_settings.redisport, db=0)
class SSHControler(object):
def __init__(self):
self.SSH = SSH_SSH()
def controler_center(self, parameter={}):
cmd = parameter.get("cmd", False)
tid = parameter["tid"]
pass
def connect(self, ip=""):
ssh_info = {"content": "", "status": False}
try:
server_config = self.convert_id_to_ip(ip)
# print server_config
if not server_config["status"]: raise SSHError(server_config["content"])
if server_config["status"]:
ssh_info = self.SSH.login(**server_config["content"])
else:
ssh_info["content"] = server_config["content"]
except Exception, e:
print "ssh错误", str(e)
ssh_info["content"] = str(e)
ssh_info["status"] = False
return ssh_info
def command_controler(self, tid='', cmd='', ip=""):
log_name = "log.%s.%s" % (tid, ip)
log_content = {
"content": "",
"stage": "done",
"status": False,
}
ssh_info = {"content": "", "status": False}
try:
current = "current.%s" % tid
data = self.connect(ip=ip)
if data["status"]:
ssh = data["content"] ###登录界面
self.SSH.execute(cmd=cmd, ip=ip, tid=tid)
ssh_info["status"] = True
else:
raise SSHError(data["content"])
except Exception, e:
print "程序错误", e,'controller'
log_content["content"] = str(e)
log_content = json.dumps(log_content, encoding="utf8", ensure_ascii=False)
r.rpush(log_name, log_content)
ssh_info["content"] = str(e)
ssh_info["status"] = False
print ssh_info,'60'
r.incr(current)
return ssh_info
# @staticmethod
def convert_id_to_ip(self,ip=""):
ssh_info = {"status": False, "content": "指定的ID不存在"}
try:
servers_list = r.lrange("server", 0, -1)
if servers_list is None:
pass
else:
for _line in servers_list:
line = json.loads(_line)
if str(ip) == line["ip"]:
ssh_info["content"] = line
ssh_info["status"] = True
break
except Exception, e:
ssh_info["status"] = False
ssh_info["content"] = str(e)
return ssh_info | 0.047316 | 0.055336 |
import unittest
import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import NoSuchElementException
class TC_Renter_SuccessfulLogin(unittest.TestCase):
@classmethod
def setUp(self):
self.driver = webdriver.Chrome()
def test_aafr(self):
user = "testrenter_1"
pwd = "<PASSWORD>"
driver = self.driver
driver.maximize_window()
driver.get("https://dry-reef-78127.herokuapp.com/loginuser/")
elem = driver.find_element_by_name("username")
elem.send_keys(user)
elem = driver.find_element_by_name("password")
elem.send_keys(<PASSWORD>)
time.sleep(5)
elem = driver.find_element_by_xpath("/html/body/section/div[2]/div/form/div/button")
elem.click()
time.sleep(3)
try:
# attempt to find the 'logout' - if found, logged in
logout_link = driver.find_element_by_xpath("/html/body/section/div[1]/div[1]/div/div[2]/div/ul/li/div/a[2]").text
if "Logout" in logout_link:
print("TC_Renter_SuccessfulLogin - User Successfully logged in")
assert True
else:
assert False
except NoSuchElementException:
self.fail("TC_Renter_SuccessfulLogin - Login Failed - user may not exist")
assert False
try:
# attempt to find the 'username' - when user logs in
greetings = driver.find_element_by_xpath(
"/html/body/section/div[1]/div[1]/div/div[2]/div/ul/li/div/a[1]").text
if "Hello "+ user in greetings:
print("TC_Renter_SuccessfulLogin - User Name is displayed correctly")
assert True
else:
print("TC_Renter_SuccessfulLogin - User Name is not displayed correctly")
assert False
except NoSuchElementException:
self.fail("NoSuchElementException")
assert False
@classmethod
def tearDown(self):
self.driver.close()
self.driver.quit()
if __name__ == "__main__":
unittest.main() | SeleniumTestScripts/TC_Renter_SuccessfulLogin.py | import unittest
import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import NoSuchElementException
class TC_Renter_SuccessfulLogin(unittest.TestCase):
@classmethod
def setUp(self):
self.driver = webdriver.Chrome()
def test_aafr(self):
user = "testrenter_1"
pwd = "<PASSWORD>"
driver = self.driver
driver.maximize_window()
driver.get("https://dry-reef-78127.herokuapp.com/loginuser/")
elem = driver.find_element_by_name("username")
elem.send_keys(user)
elem = driver.find_element_by_name("password")
elem.send_keys(<PASSWORD>)
time.sleep(5)
elem = driver.find_element_by_xpath("/html/body/section/div[2]/div/form/div/button")
elem.click()
time.sleep(3)
try:
# attempt to find the 'logout' - if found, logged in
logout_link = driver.find_element_by_xpath("/html/body/section/div[1]/div[1]/div/div[2]/div/ul/li/div/a[2]").text
if "Logout" in logout_link:
print("TC_Renter_SuccessfulLogin - User Successfully logged in")
assert True
else:
assert False
except NoSuchElementException:
self.fail("TC_Renter_SuccessfulLogin - Login Failed - user may not exist")
assert False
try:
# attempt to find the 'username' - when user logs in
greetings = driver.find_element_by_xpath(
"/html/body/section/div[1]/div[1]/div/div[2]/div/ul/li/div/a[1]").text
if "Hello "+ user in greetings:
print("TC_Renter_SuccessfulLogin - User Name is displayed correctly")
assert True
else:
print("TC_Renter_SuccessfulLogin - User Name is not displayed correctly")
assert False
except NoSuchElementException:
self.fail("NoSuchElementException")
assert False
@classmethod
def tearDown(self):
self.driver.close()
self.driver.quit()
if __name__ == "__main__":
unittest.main() | 0.244363 | 0.165661 |
from ConfigParser import ConfigParser
import os
import re
import subprocess
import sys
from termcolor import colored
config = ConfigParser()
ANSI_ESCAPE_RE = re.compile(r'\x1b[^m]*m')
RANGE_RE = re.compile(r'(\d+)-(\d+)')
ID_FILE = 'hgnids.txt'
CONFIG_FILE = '.hgnrc'
def fail(msg):
print colored(msg, 'red')
sys.exit(1)
def id_file_path():
return os.path.join(hg_root(), '.hg', ID_FILE)
def config_file_path():
return os.path.join(os.path.expanduser('~'), CONFIG_FILE)
def hg_status():
args = ['hg', 'st']
if config_getboolean('color', False):
args.extend(['--color', 'always'])
try:
return subprocess.check_output(args).strip()
except:
exit(1)
def hg_root():
try:
return subprocess.check_output(['hg', 'root']).strip()
except:
exit(1)
def get_filenames():
path = id_file_path()
if not os.path.exists(path):
fail(path + " doesn't exist. Run hg-number with no arguments first to generate this file.")
with open(path) as f:
status_output = f.read()
lines = status_output.split('\n')
return map(lambda l: l.split(' ')[1], lines)
def save_status_output(status_output):
# Strip colors
status_output = ANSI_ESCAPE_RE.sub('', status_output)
with open(id_file_path(), 'w+') as f:
f.write(status_output)
def to_int(val, max_num):
num = int(val)
if num <= 0:
fail(val + ' is not a positive number')
elif num > max_num:
fail(val + ' is exceeds the number of files')
return num
def substitute_filenames(files, args, shell_command):
num_files = len(files)
new_args = []
double_dash_pos = None
for i, arg in enumerate(args):
# After a '--' don't replace any numbers
if arg == '--':
double_dash_pos = i
break
try:
m = RANGE_RE.match(arg)
if m:
start, end = m.group(1, 2)
start, end = to_int(start, num_files), to_int(end, num_files)
for i in range(start, end + 1):
new_args.append(files[i - 1])
else:
num = to_int(arg, num_files)
new_args.append(files[num - 1])
except ValueError:
new_args.append(arg)
if double_dash_pos != None:
# This is safe because out of bounds slicing isn't an error
new_args.extend(args[double_dash_pos + 1:])
if not shell_command:
new_args.insert(0, 'hg')
if config_getboolean('color', False):
new_args.extend(['--color', 'always'])
return new_args
def prepend_numbers(lines):
output = []
for i, l in enumerate(lines.split('\n')):
output.append(str(i + 1) + ' ' + l)
return '\n'.join(output)
def load_config():
global config
path = config_file_path()
if os.path.exists(path):
with open(path) as f:
config.read(path)
def config_get(name, default, func):
if config.has_option('main', name):
return func('main', name)
else:
return default
def config_getboolean(name, default):
return bool(config_get(name, default, config.getboolean))
def print_usage():
print 'usage: %s [-h] [-c] command [-- other_args]' % os.path.basename(sys.argv[0])
def main():
load_config()
shell_command = False
if len(sys.argv) > 1:
if sys.argv[1] == '-c':
shell_command = True
elif sys.argv[1] in ['-h', '--help']:
print_usage()
exit(0)
if len(sys.argv) == 1 or sys.argv[1] in ['st', 'status']:
status_output = hg_status()
save_status_output(status_output)
if status_output != '':
print prepend_numbers(status_output)
else:
files = get_filenames()
args = sys.argv[2:] if shell_command else sys.argv[1:]
new_args = substitute_filenames(files, args, shell_command)
print ' '.join(new_args)
try:
cmd_output = subprocess.check_output(new_args, cwd=hg_root()).strip()
if cmd_output != '':
print cmd_output
except:
exit(1)
if __name__ == '__main__':
main() | hg_number.py |
from ConfigParser import ConfigParser
import os
import re
import subprocess
import sys
from termcolor import colored
config = ConfigParser()
ANSI_ESCAPE_RE = re.compile(r'\x1b[^m]*m')
RANGE_RE = re.compile(r'(\d+)-(\d+)')
ID_FILE = 'hgnids.txt'
CONFIG_FILE = '.hgnrc'
def fail(msg):
print colored(msg, 'red')
sys.exit(1)
def id_file_path():
return os.path.join(hg_root(), '.hg', ID_FILE)
def config_file_path():
return os.path.join(os.path.expanduser('~'), CONFIG_FILE)
def hg_status():
args = ['hg', 'st']
if config_getboolean('color', False):
args.extend(['--color', 'always'])
try:
return subprocess.check_output(args).strip()
except:
exit(1)
def hg_root():
try:
return subprocess.check_output(['hg', 'root']).strip()
except:
exit(1)
def get_filenames():
path = id_file_path()
if not os.path.exists(path):
fail(path + " doesn't exist. Run hg-number with no arguments first to generate this file.")
with open(path) as f:
status_output = f.read()
lines = status_output.split('\n')
return map(lambda l: l.split(' ')[1], lines)
def save_status_output(status_output):
# Strip colors
status_output = ANSI_ESCAPE_RE.sub('', status_output)
with open(id_file_path(), 'w+') as f:
f.write(status_output)
def to_int(val, max_num):
num = int(val)
if num <= 0:
fail(val + ' is not a positive number')
elif num > max_num:
fail(val + ' is exceeds the number of files')
return num
def substitute_filenames(files, args, shell_command):
num_files = len(files)
new_args = []
double_dash_pos = None
for i, arg in enumerate(args):
# After a '--' don't replace any numbers
if arg == '--':
double_dash_pos = i
break
try:
m = RANGE_RE.match(arg)
if m:
start, end = m.group(1, 2)
start, end = to_int(start, num_files), to_int(end, num_files)
for i in range(start, end + 1):
new_args.append(files[i - 1])
else:
num = to_int(arg, num_files)
new_args.append(files[num - 1])
except ValueError:
new_args.append(arg)
if double_dash_pos != None:
# This is safe because out of bounds slicing isn't an error
new_args.extend(args[double_dash_pos + 1:])
if not shell_command:
new_args.insert(0, 'hg')
if config_getboolean('color', False):
new_args.extend(['--color', 'always'])
return new_args
def prepend_numbers(lines):
output = []
for i, l in enumerate(lines.split('\n')):
output.append(str(i + 1) + ' ' + l)
return '\n'.join(output)
def load_config():
global config
path = config_file_path()
if os.path.exists(path):
with open(path) as f:
config.read(path)
def config_get(name, default, func):
if config.has_option('main', name):
return func('main', name)
else:
return default
def config_getboolean(name, default):
return bool(config_get(name, default, config.getboolean))
def print_usage():
print 'usage: %s [-h] [-c] command [-- other_args]' % os.path.basename(sys.argv[0])
def main():
load_config()
shell_command = False
if len(sys.argv) > 1:
if sys.argv[1] == '-c':
shell_command = True
elif sys.argv[1] in ['-h', '--help']:
print_usage()
exit(0)
if len(sys.argv) == 1 or sys.argv[1] in ['st', 'status']:
status_output = hg_status()
save_status_output(status_output)
if status_output != '':
print prepend_numbers(status_output)
else:
files = get_filenames()
args = sys.argv[2:] if shell_command else sys.argv[1:]
new_args = substitute_filenames(files, args, shell_command)
print ' '.join(new_args)
try:
cmd_output = subprocess.check_output(new_args, cwd=hg_root()).strip()
if cmd_output != '':
print cmd_output
except:
exit(1)
if __name__ == '__main__':
main() | 0.215351 | 0.131731 |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.io import loadmat
#Be careful with the file path!
data = loadmat('data/hw4.mat')
from sklearn.preprocessing import OneHotEncoder
encoder = OneHotEncoder(sparse=False, categories='auto')
y_onehot = encoder.fit_transform(data['y'])
def sigmoid(z):
return 1 / (1 + np.exp(-z))
def forward_propagate(X, theta1, theta2):
m = X.shape[0]
# foward propagation
a1 = np.c_[np.ones((m, 1)), X] # need to add bias here
z2 = a1 * theta1.T
a2 = np.c_[np.ones((m, 1)), sigmoid(z2)] # need to add bias here
z3 = a2 * theta2.T
h = sigmoid(z3)
return a1, z2, a2, z3, h
def cost(params, input_size, hidden_size, num_labels, X, y, learning_rate):
m = X.shape[0]
X = np.matrix(X)
y = np.matrix(y)
# reshape the parameter array into parameter matrices for each layer
theta1 = np.matrix(
np.reshape(params[:hidden_size * (input_size + 1)],
(hidden_size, (input_size + 1))))
theta2 = np.matrix(
np.reshape(params[hidden_size * (input_size + 1):],
(num_labels, (hidden_size + 1))))
# run the feed-forward pass
a1, z2, a2, z3, h = forward_propagate(X, theta1, theta2)
# compute the cost
J = 0
for i in range(m):
first_term = np.multiply(-y[i, :], np.log(h[i, :]))
second_term = np.multiply((1 - y[i, :]), np.log(1 - h[i, :]))
J += np.sum(first_term - second_term)
J = J / m
J += (float(learning_rate) / (2 * m) * (np.sum(np.power(
theta1[:, 1:], 2)) + np.sum(np.power(theta2[:, 1:], 2))))
return J
# initial setup
input_size = 400
hidden_size = 10
num_labels = 10
learning_rate = 1
# randomly initialize a parameter array of the size of the full network's parameters
params = (np.random.random(size=hidden_size * (input_size + 1) + num_labels *
(hidden_size + 1)) - 0.5) * 0.2
m = data['X'].shape[0]
X = np.matrix(data['X'])
y = np.matrix(data['y'])
# unravel the parameter array into parameter matrices for each layer
theta1 = np.matrix(
np.reshape(params[:hidden_size * (input_size + 1)], (hidden_size,
(input_size + 1))))
theta2 = np.matrix(
np.reshape(params[hidden_size * (input_size + 1):], (num_labels,
(hidden_size + 1))))
a1, z2, a2, z3, h = forward_propagate(X, theta1, theta2)
def sigmoid_gradient(z):
return np.multiply(sigmoid(z), (1 - sigmoid(z)))
def backprop(params, input_size, hidden_size, num_labels, X, y, learning_rate):
m = X.shape[0]
#Write codes here
theta1 = np.matrix(
np.reshape(params[:hidden_size * (input_size + 1)],
(hidden_size, (input_size + 1))))
theta2 = np.matrix(
np.reshape(params[hidden_size * (input_size + 1):],
(num_labels, (hidden_size + 1))))
# do forward_propagation first
a1, z2, a2, _, h = forward_propagate(X, theta1, theta2)
# inits
J = 0
theta1_grad = np.zeros(theta1.shape)
theta2_grad = np.zeros(theta2.shape)
# compute the cost
J = np.sum(
np.multiply(-y, np.log(h)) - np.multiply((1 - y), np.log(1 - h)))
J /= m
J += (float(learning_rate) / (2 * m)) * (np.sum(
np.power(theta1[:, 1:], 2)) + np.sum(np.power(theta2[:, 1:], 2)))
# do backpropagation
delta3 = h - y
delta2 = np.multiply((theta2.T * delta3.T).T,
sigmoid_gradient(np.c_[np.ones((m, 1)), z2]))
theta1_grad += (delta2[:, 1:]).T * a1
theta2_grad += delta3.T * a2
theta1_grad /= m
theta2_grad /= m
theta1_grad[:, 1:] += (theta1[:, 1:] * learning_rate) / m
theta2_grad[:, 1:] += (theta2[:, 1:] * learning_rate) / m
grad = np.concatenate((np.ravel(theta1_grad), np.ravel(theta2_grad)))
return J, grad
from scipy.optimize import minimize
# minimize the objective function
fmin = minimize(
fun=backprop,
x0=params,
args=(input_size, hidden_size, num_labels, X, y_onehot, learning_rate),
method='TNC',
jac=True,
options={'maxiter': 250})
X = np.matrix(X)
theta1 = np.matrix(
np.reshape(fmin.x[:hidden_size * (input_size + 1)], (hidden_size,
(input_size + 1))))
theta2 = np.matrix(
np.reshape(fmin.x[hidden_size * (input_size + 1):], (num_labels,
(hidden_size + 1))))
a1, z2, a2, z3, h = forward_propagate(X, theta1, theta2)
y_pred = np.array(np.argmax(h, axis=1) + 1)
correct = [1 if a == b else 0 for (a, b) in zip(y_pred, y)]
accuracy = (sum(map(int, correct)) / float(len(correct)))
print('accuracy = {0}%'.format(accuracy * 100)) | IML_2018_Fall/Project4/hw4.py | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.io import loadmat
#Be careful with the file path!
data = loadmat('data/hw4.mat')
from sklearn.preprocessing import OneHotEncoder
encoder = OneHotEncoder(sparse=False, categories='auto')
y_onehot = encoder.fit_transform(data['y'])
def sigmoid(z):
return 1 / (1 + np.exp(-z))
def forward_propagate(X, theta1, theta2):
m = X.shape[0]
# foward propagation
a1 = np.c_[np.ones((m, 1)), X] # need to add bias here
z2 = a1 * theta1.T
a2 = np.c_[np.ones((m, 1)), sigmoid(z2)] # need to add bias here
z3 = a2 * theta2.T
h = sigmoid(z3)
return a1, z2, a2, z3, h
def cost(params, input_size, hidden_size, num_labels, X, y, learning_rate):
m = X.shape[0]
X = np.matrix(X)
y = np.matrix(y)
# reshape the parameter array into parameter matrices for each layer
theta1 = np.matrix(
np.reshape(params[:hidden_size * (input_size + 1)],
(hidden_size, (input_size + 1))))
theta2 = np.matrix(
np.reshape(params[hidden_size * (input_size + 1):],
(num_labels, (hidden_size + 1))))
# run the feed-forward pass
a1, z2, a2, z3, h = forward_propagate(X, theta1, theta2)
# compute the cost
J = 0
for i in range(m):
first_term = np.multiply(-y[i, :], np.log(h[i, :]))
second_term = np.multiply((1 - y[i, :]), np.log(1 - h[i, :]))
J += np.sum(first_term - second_term)
J = J / m
J += (float(learning_rate) / (2 * m) * (np.sum(np.power(
theta1[:, 1:], 2)) + np.sum(np.power(theta2[:, 1:], 2))))
return J
# initial setup
input_size = 400
hidden_size = 10
num_labels = 10
learning_rate = 1
# randomly initialize a parameter array of the size of the full network's parameters
params = (np.random.random(size=hidden_size * (input_size + 1) + num_labels *
(hidden_size + 1)) - 0.5) * 0.2
m = data['X'].shape[0]
X = np.matrix(data['X'])
y = np.matrix(data['y'])
# unravel the parameter array into parameter matrices for each layer
theta1 = np.matrix(
np.reshape(params[:hidden_size * (input_size + 1)], (hidden_size,
(input_size + 1))))
theta2 = np.matrix(
np.reshape(params[hidden_size * (input_size + 1):], (num_labels,
(hidden_size + 1))))
a1, z2, a2, z3, h = forward_propagate(X, theta1, theta2)
def sigmoid_gradient(z):
return np.multiply(sigmoid(z), (1 - sigmoid(z)))
def backprop(params, input_size, hidden_size, num_labels, X, y, learning_rate):
m = X.shape[0]
#Write codes here
theta1 = np.matrix(
np.reshape(params[:hidden_size * (input_size + 1)],
(hidden_size, (input_size + 1))))
theta2 = np.matrix(
np.reshape(params[hidden_size * (input_size + 1):],
(num_labels, (hidden_size + 1))))
# do forward_propagation first
a1, z2, a2, _, h = forward_propagate(X, theta1, theta2)
# inits
J = 0
theta1_grad = np.zeros(theta1.shape)
theta2_grad = np.zeros(theta2.shape)
# compute the cost
J = np.sum(
np.multiply(-y, np.log(h)) - np.multiply((1 - y), np.log(1 - h)))
J /= m
J += (float(learning_rate) / (2 * m)) * (np.sum(
np.power(theta1[:, 1:], 2)) + np.sum(np.power(theta2[:, 1:], 2)))
# do backpropagation
delta3 = h - y
delta2 = np.multiply((theta2.T * delta3.T).T,
sigmoid_gradient(np.c_[np.ones((m, 1)), z2]))
theta1_grad += (delta2[:, 1:]).T * a1
theta2_grad += delta3.T * a2
theta1_grad /= m
theta2_grad /= m
theta1_grad[:, 1:] += (theta1[:, 1:] * learning_rate) / m
theta2_grad[:, 1:] += (theta2[:, 1:] * learning_rate) / m
grad = np.concatenate((np.ravel(theta1_grad), np.ravel(theta2_grad)))
return J, grad
from scipy.optimize import minimize
# minimize the objective function
fmin = minimize(
fun=backprop,
x0=params,
args=(input_size, hidden_size, num_labels, X, y_onehot, learning_rate),
method='TNC',
jac=True,
options={'maxiter': 250})
X = np.matrix(X)
theta1 = np.matrix(
np.reshape(fmin.x[:hidden_size * (input_size + 1)], (hidden_size,
(input_size + 1))))
theta2 = np.matrix(
np.reshape(fmin.x[hidden_size * (input_size + 1):], (num_labels,
(hidden_size + 1))))
a1, z2, a2, z3, h = forward_propagate(X, theta1, theta2)
y_pred = np.array(np.argmax(h, axis=1) + 1)
correct = [1 if a == b else 0 for (a, b) in zip(y_pred, y)]
accuracy = (sum(map(int, correct)) / float(len(correct)))
print('accuracy = {0}%'.format(accuracy * 100)) | 0.754373 | 0.714254 |
import os
from collections import OrderedDict
from RouToolPa.Tools.Alignment import LongRanger
from Pipelines.Abstract import Pipeline
class TenXAlignmentPipeline(Pipeline):
def __init__(self, max_threads=1, max_memory=10, longranger_dir=""):
Pipeline.__init__(self, max_threads=max_threads, max_memory=max_memory)
self.longranger_dir = longranger_dir if not (longranger_dir is None) else ""
def prepare_directories(self, output_directory, sample_list):
print(output_directory)
directories_dict = {output_directory: OrderedDict()}
for sample in sample_list:
directories_dict[output_directory][sample] = OrderedDict()
self.recursive_mkdir(directories_dict)
def align_and_call(self, samples_directory, output_directory, reference, samples_to_handle=None,
variant_calling_mode=None, gatk_jar_path=None, use_somatic_sv_caller=None,
precalled_vcf=None, sample_sex=None,
variant_calling_only=None, threads=None, max_memory=None, longranger_dir=None):
start_dir = os.getcwd()
out_dir_abs = os.path.abspath(output_directory)
LongRanger.path = longranger_dir if longranger_dir else self.longranger_dir
LongRanger.threads = threads if threads else self.threads
LongRanger.max_memory = max_memory if max_memory else self.max_memory
sample_list = samples_to_handle if samples_to_handle else self.get_sample_list(samples_directory)
self.prepare_directories(out_dir_abs, sample_list)
os.chdir(out_dir_abs)
for sample in sample_list:
fastq_dir = "%s/%s/" % (samples_directory, sample)
LongRanger.run_wgs_analysis(reference, sample, fastq_dir, description=sample, library_name=sample,
lane_list=None, indice_list=None, project_name=None,
variant_calling_mode=variant_calling_mode,
gatk_jar_path=gatk_jar_path, use_somatic_sv_caller=use_somatic_sv_caller,
precalled_vcf=precalled_vcf, sample_sex=sample_sex,
variant_calling_only=variant_calling_only,
max_memory=max_memory if max_memory else self.max_memory)
os.chdir(start_dir) | Pipelines/TenX/Alignment.py |
import os
from collections import OrderedDict
from RouToolPa.Tools.Alignment import LongRanger
from Pipelines.Abstract import Pipeline
class TenXAlignmentPipeline(Pipeline):
def __init__(self, max_threads=1, max_memory=10, longranger_dir=""):
Pipeline.__init__(self, max_threads=max_threads, max_memory=max_memory)
self.longranger_dir = longranger_dir if not (longranger_dir is None) else ""
def prepare_directories(self, output_directory, sample_list):
print(output_directory)
directories_dict = {output_directory: OrderedDict()}
for sample in sample_list:
directories_dict[output_directory][sample] = OrderedDict()
self.recursive_mkdir(directories_dict)
def align_and_call(self, samples_directory, output_directory, reference, samples_to_handle=None,
variant_calling_mode=None, gatk_jar_path=None, use_somatic_sv_caller=None,
precalled_vcf=None, sample_sex=None,
variant_calling_only=None, threads=None, max_memory=None, longranger_dir=None):
start_dir = os.getcwd()
out_dir_abs = os.path.abspath(output_directory)
LongRanger.path = longranger_dir if longranger_dir else self.longranger_dir
LongRanger.threads = threads if threads else self.threads
LongRanger.max_memory = max_memory if max_memory else self.max_memory
sample_list = samples_to_handle if samples_to_handle else self.get_sample_list(samples_directory)
self.prepare_directories(out_dir_abs, sample_list)
os.chdir(out_dir_abs)
for sample in sample_list:
fastq_dir = "%s/%s/" % (samples_directory, sample)
LongRanger.run_wgs_analysis(reference, sample, fastq_dir, description=sample, library_name=sample,
lane_list=None, indice_list=None, project_name=None,
variant_calling_mode=variant_calling_mode,
gatk_jar_path=gatk_jar_path, use_somatic_sv_caller=use_somatic_sv_caller,
precalled_vcf=precalled_vcf, sample_sex=sample_sex,
variant_calling_only=variant_calling_only,
max_memory=max_memory if max_memory else self.max_memory)
os.chdir(start_dir) | 0.398289 | 0.073596 |
import re
from collections import namedtuple
from datetime import datetime, date, time
import times
from dateutil import rrule
from zitkino import parsers
from zitkino.utils import clean_whitespace
from zitkino.models import Cinema, Showtime, ScrapedFilm
from zitkino.scrapers import scrapers, Scraper
cinema = Cinema(
name=u'<NAME>',
url='http://www.kinolucerna.info',
street=u'Minská 19',
town=u'Brno',
coords=(49.2104939, 16.5855358)
)
FilmInfo = namedtuple('FilmInfo', ['title_main', 'tags', 'directors'])
@scrapers.register(cinema)
class KinolucernaScraper(Scraper):
url = ('http://www.kinolucerna.info/index.php?option=com_content'
'&view=article&id=37&Itemid=61')
url_booking = ('http://www.kinolucerna.info/index.php?option=com_contact'
'&view=contact&id=1&Itemid=63')
tz = 'Europe/Prague'
entry_re = re.compile(r'\d+:\d+')
entry_split_re = re.compile(r'[\b\s]+(?=\d+\.\d+)')
entry_split_price_re = re.compile(ur'vstupné', re.U | re.I)
range_re = re.compile(
r'(\d+)\.(\d+)\.-(\d+)\.(\d+)\.' # date range
r'((\s+(ve?|a)\s+\d+:\d+)+)' # times
)
standalone_re = re.compile(
r'(\d+)\.(\d+)\.(\s*\+\s*(\d+)\.(\d+)\.)?' # single dates or date+date
r'((\s+(ve?|a)\s+\d+:\d+)+)' # times
)
time_re = re.compile(r'(\d+):(\d+)')
tag_re = (
# order is not arbitrary!
(re.compile(ur'[–\-] titulky', re.I), u'titulky'),
(re.compile(ur'[–\-] (český )?dabing', re.I), u'dabing'),
(re.compile(ur' titulky', re.I), u'titulky'),
(re.compile(ur' (český )?dabing', re.I), u'dabing'),
(re.compile(r've? 2[dD]$'), '2D'),
(re.compile(r've? 3[dD]$'), '3D'),
(re.compile(r' 2[dD]$'), '2D'),
(re.compile(r' 3[dD]$'), '3D'),
)
def __call__(self):
for texts in self._scrape_entries():
for showtime in self._parse_entry_text(*texts):
yield showtime
def _is_entry(self, el):
"""Tests if given STRONG element looks like film entry."""
def looks_like_entry(el):
return (
el.tag == 'strong' and
self.entry_re.search(el.text_content())
)
if looks_like_entry(el):
next_el = el.getnext() # get next sibling
# let's look for the next BR tag
while next_el is not None and next_el.tag != 'br':
if looks_like_entry(next_el):
# we found another entry candidate until BR tag is found,
# that means examined element is probably not a film header
return False
next_el = next_el.getnext() # get next sibling
if next_el is None:
return False
# we found BR tag - does it have tail (standalone text after the
# element) with some film details?
return bool(next_el.tail)
return False
def _extract_entry_siblings_text(self, el, direction):
text = ''
while True:
el = getattr(el, 'get' + direction)()
if el is not None and el.tag == 'strong': # continuation
if direction != 'previous' or el.tail is None:
text += (el.text_content(whitespace=True) or '')
else:
return text
def _extract_entry_tail_text(self, el):
text = ''
seen_text = False
while True:
next_el = el.getnext()
if next_el is None:
return text
if next_el.tag == 'strong':
if not seen_text:
text = next_el.tail or ''
el = next_el
continue
else:
return text
else:
seen_text = True
text += next_el.text_content() + ' ' + (next_el.tail or '')
el = next_el
def _extract_entry_text(self, entry):
"""Extracts relevant entry text from given STRONG element and it's
siblings (sometimes film entry actually consists of multiple STRONG
elements as someone made the text bold by selecting multiple
parts of it and pushing the button in WYSIWYG editor).
"""
title_text = self._extract_entry_siblings_text(entry, 'previous')
title_text += (entry.text_content(whitespace=True) or '')
title_text += self._extract_entry_siblings_text(entry, 'next')
details_text = self._extract_entry_tail_text(entry)
return title_text.strip(), clean_whitespace(details_text)
def _scrape_entries(self):
"""Downloads and scrapes text of HTML elements, each with film
header line.
"""
resp = self.session.get(self.url)
html = parsers.html(resp.content, base_url=resp.url)
for el in html.cssselect('.contentpaneopen strong'):
if self._is_entry(el):
yield self._extract_entry_text(el)
def _determine_year(self, month):
"""Determines the right year of datetime from given month."""
tod = date.today()
month = int(month)
if tod.month <= month:
# this month or future month this year
return tod.year
elif tod.month - month < 6:
# looks like future month next year, but it is too far - therefore
# it is month in the past this year, which just passed
return tod.year
else:
# future month next year
return tod.year + 1
def _parse_times(self, times_text):
"""Takes text with time information, parses out and generates
hour & minute pairs.
"""
return [
map(int, [time_match.group(1), time_match.group(2)]) # hr, min
for time_match in self.time_re.finditer(times_text)
]
def _parse_date_ranges(self, dates_text):
"""Takes text with date & time information, parses out and generates
showtimes within date ranges.
"""
for match in self.range_re.finditer(dates_text):
# days
start_day = int(match.group(1))
end_day = int(match.group(3))
# months
start_month = int(match.group(2))
end_month = int(match.group(4))
# times
time_args_list = self._parse_times(match.group(5))
# years
start_year = self._determine_year(start_month)
end_year = self._determine_year(end_month)
# bounds for rrule
start = datetime(start_year, start_month, start_day)
end = datetime(end_year, end_month, end_day)
# construct and yield datetimes
for day in rrule.rrule(rrule.DAILY, dtstart=start, until=end):
for time_args in time_args_list:
yield times.to_universal(
datetime.combine(day, time(*time_args)),
self.tz
)
def _parse_standalone_dates(self, dates_text):
"""Takes text with date & time information, parses out and generates
standalone showtimes.
"""
dates_text = self.range_re.sub('', dates_text)
for match in self.standalone_re.finditer(dates_text):
date_args_list = []
# standalone date
date_args_list.append(map(int, [
self._determine_year(match.group(2)), # year
match.group(2), # month
match.group(1), # day
]))
# date+date, let's process the second one
if match.group(3):
date_args_list.append(map(int, [
self._determine_year(match.group(5)), # year
match.group(5), # month
match.group(4), # day
]))
# parse times
time_args_list = self._parse_times(match.group(6))
# construct and yield datetimes
for date_args in date_args_list:
for time_args in time_args_list:
yield times.to_universal(
datetime(*(date_args + time_args)),
self.tz
)
def _split_entry_text(self, text):
"""Takes main entry text and returns tuple with title part
and a part containing information about dates & times.
"""
if '\n' in text:
parts = text.split('\n')
title = parts[0]
for info in parts[1:]:
dates = self.entry_split_price_re.split(info, maxsplit=1)[0]
yield clean_whitespace(title), clean_whitespace(dates)
else:
title, info = self.entry_split_re.split(text, maxsplit=1)
dates = self.entry_split_price_re.split(info, maxsplit=1)[0]
yield clean_whitespace(title), clean_whitespace(dates)
def _parse_info(self, title_text, details_text):
tags = []
directors = {}
# tags
for regexp, tag in self.tag_re:
if regexp.search(title_text):
tags.append(tag)
title_text = regexp.sub('', title_text).strip()
if regexp.search(details_text):
tags.append(tag)
# TODO directors
return FilmInfo(title_text.strip(), tags, directors)
def _parse_entry_text(self, title_text, details_text):
"""Takes HTML element with film header line and generates showtimes."""
for title_text, dates_text in self._split_entry_text(title_text):
info = self._parse_info(title_text, details_text)
date_ranges = self._parse_date_ranges(dates_text)
standalone_dates = self._parse_standalone_dates(dates_text)
dates = list(date_ranges) + list(standalone_dates)
for starts_at in dates:
yield Showtime(
cinema=cinema,
film_scraped=ScrapedFilm(
title_main_scraped=info.title_main,
directors=info.directors,
),
starts_at=starts_at,
url=self.url,
url_booking=self.url_booking,
tags={tag: None for tag in info.tags},
) | zitkino/scrapers/turned_off/kino_lucerna.py |
import re
from collections import namedtuple
from datetime import datetime, date, time
import times
from dateutil import rrule
from zitkino import parsers
from zitkino.utils import clean_whitespace
from zitkino.models import Cinema, Showtime, ScrapedFilm
from zitkino.scrapers import scrapers, Scraper
cinema = Cinema(
name=u'<NAME>',
url='http://www.kinolucerna.info',
street=u'Minská 19',
town=u'Brno',
coords=(49.2104939, 16.5855358)
)
FilmInfo = namedtuple('FilmInfo', ['title_main', 'tags', 'directors'])
@scrapers.register(cinema)
class KinolucernaScraper(Scraper):
url = ('http://www.kinolucerna.info/index.php?option=com_content'
'&view=article&id=37&Itemid=61')
url_booking = ('http://www.kinolucerna.info/index.php?option=com_contact'
'&view=contact&id=1&Itemid=63')
tz = 'Europe/Prague'
entry_re = re.compile(r'\d+:\d+')
entry_split_re = re.compile(r'[\b\s]+(?=\d+\.\d+)')
entry_split_price_re = re.compile(ur'vstupné', re.U | re.I)
range_re = re.compile(
r'(\d+)\.(\d+)\.-(\d+)\.(\d+)\.' # date range
r'((\s+(ve?|a)\s+\d+:\d+)+)' # times
)
standalone_re = re.compile(
r'(\d+)\.(\d+)\.(\s*\+\s*(\d+)\.(\d+)\.)?' # single dates or date+date
r'((\s+(ve?|a)\s+\d+:\d+)+)' # times
)
time_re = re.compile(r'(\d+):(\d+)')
tag_re = (
# order is not arbitrary!
(re.compile(ur'[–\-] titulky', re.I), u'titulky'),
(re.compile(ur'[–\-] (český )?dabing', re.I), u'dabing'),
(re.compile(ur' titulky', re.I), u'titulky'),
(re.compile(ur' (český )?dabing', re.I), u'dabing'),
(re.compile(r've? 2[dD]$'), '2D'),
(re.compile(r've? 3[dD]$'), '3D'),
(re.compile(r' 2[dD]$'), '2D'),
(re.compile(r' 3[dD]$'), '3D'),
)
def __call__(self):
for texts in self._scrape_entries():
for showtime in self._parse_entry_text(*texts):
yield showtime
def _is_entry(self, el):
"""Tests if given STRONG element looks like film entry."""
def looks_like_entry(el):
return (
el.tag == 'strong' and
self.entry_re.search(el.text_content())
)
if looks_like_entry(el):
next_el = el.getnext() # get next sibling
# let's look for the next BR tag
while next_el is not None and next_el.tag != 'br':
if looks_like_entry(next_el):
# we found another entry candidate until BR tag is found,
# that means examined element is probably not a film header
return False
next_el = next_el.getnext() # get next sibling
if next_el is None:
return False
# we found BR tag - does it have tail (standalone text after the
# element) with some film details?
return bool(next_el.tail)
return False
def _extract_entry_siblings_text(self, el, direction):
text = ''
while True:
el = getattr(el, 'get' + direction)()
if el is not None and el.tag == 'strong': # continuation
if direction != 'previous' or el.tail is None:
text += (el.text_content(whitespace=True) or '')
else:
return text
def _extract_entry_tail_text(self, el):
text = ''
seen_text = False
while True:
next_el = el.getnext()
if next_el is None:
return text
if next_el.tag == 'strong':
if not seen_text:
text = next_el.tail or ''
el = next_el
continue
else:
return text
else:
seen_text = True
text += next_el.text_content() + ' ' + (next_el.tail or '')
el = next_el
def _extract_entry_text(self, entry):
"""Extracts relevant entry text from given STRONG element and it's
siblings (sometimes film entry actually consists of multiple STRONG
elements as someone made the text bold by selecting multiple
parts of it and pushing the button in WYSIWYG editor).
"""
title_text = self._extract_entry_siblings_text(entry, 'previous')
title_text += (entry.text_content(whitespace=True) or '')
title_text += self._extract_entry_siblings_text(entry, 'next')
details_text = self._extract_entry_tail_text(entry)
return title_text.strip(), clean_whitespace(details_text)
def _scrape_entries(self):
"""Downloads and scrapes text of HTML elements, each with film
header line.
"""
resp = self.session.get(self.url)
html = parsers.html(resp.content, base_url=resp.url)
for el in html.cssselect('.contentpaneopen strong'):
if self._is_entry(el):
yield self._extract_entry_text(el)
def _determine_year(self, month):
"""Determines the right year of datetime from given month."""
tod = date.today()
month = int(month)
if tod.month <= month:
# this month or future month this year
return tod.year
elif tod.month - month < 6:
# looks like future month next year, but it is too far - therefore
# it is month in the past this year, which just passed
return tod.year
else:
# future month next year
return tod.year + 1
def _parse_times(self, times_text):
"""Takes text with time information, parses out and generates
hour & minute pairs.
"""
return [
map(int, [time_match.group(1), time_match.group(2)]) # hr, min
for time_match in self.time_re.finditer(times_text)
]
def _parse_date_ranges(self, dates_text):
"""Takes text with date & time information, parses out and generates
showtimes within date ranges.
"""
for match in self.range_re.finditer(dates_text):
# days
start_day = int(match.group(1))
end_day = int(match.group(3))
# months
start_month = int(match.group(2))
end_month = int(match.group(4))
# times
time_args_list = self._parse_times(match.group(5))
# years
start_year = self._determine_year(start_month)
end_year = self._determine_year(end_month)
# bounds for rrule
start = datetime(start_year, start_month, start_day)
end = datetime(end_year, end_month, end_day)
# construct and yield datetimes
for day in rrule.rrule(rrule.DAILY, dtstart=start, until=end):
for time_args in time_args_list:
yield times.to_universal(
datetime.combine(day, time(*time_args)),
self.tz
)
def _parse_standalone_dates(self, dates_text):
"""Takes text with date & time information, parses out and generates
standalone showtimes.
"""
dates_text = self.range_re.sub('', dates_text)
for match in self.standalone_re.finditer(dates_text):
date_args_list = []
# standalone date
date_args_list.append(map(int, [
self._determine_year(match.group(2)), # year
match.group(2), # month
match.group(1), # day
]))
# date+date, let's process the second one
if match.group(3):
date_args_list.append(map(int, [
self._determine_year(match.group(5)), # year
match.group(5), # month
match.group(4), # day
]))
# parse times
time_args_list = self._parse_times(match.group(6))
# construct and yield datetimes
for date_args in date_args_list:
for time_args in time_args_list:
yield times.to_universal(
datetime(*(date_args + time_args)),
self.tz
)
def _split_entry_text(self, text):
"""Takes main entry text and returns tuple with title part
and a part containing information about dates & times.
"""
if '\n' in text:
parts = text.split('\n')
title = parts[0]
for info in parts[1:]:
dates = self.entry_split_price_re.split(info, maxsplit=1)[0]
yield clean_whitespace(title), clean_whitespace(dates)
else:
title, info = self.entry_split_re.split(text, maxsplit=1)
dates = self.entry_split_price_re.split(info, maxsplit=1)[0]
yield clean_whitespace(title), clean_whitespace(dates)
def _parse_info(self, title_text, details_text):
tags = []
directors = {}
# tags
for regexp, tag in self.tag_re:
if regexp.search(title_text):
tags.append(tag)
title_text = regexp.sub('', title_text).strip()
if regexp.search(details_text):
tags.append(tag)
# TODO directors
return FilmInfo(title_text.strip(), tags, directors)
def _parse_entry_text(self, title_text, details_text):
"""Takes HTML element with film header line and generates showtimes."""
for title_text, dates_text in self._split_entry_text(title_text):
info = self._parse_info(title_text, details_text)
date_ranges = self._parse_date_ranges(dates_text)
standalone_dates = self._parse_standalone_dates(dates_text)
dates = list(date_ranges) + list(standalone_dates)
for starts_at in dates:
yield Showtime(
cinema=cinema,
film_scraped=ScrapedFilm(
title_main_scraped=info.title_main,
directors=info.directors,
),
starts_at=starts_at,
url=self.url,
url_booking=self.url_booking,
tags={tag: None for tag in info.tags},
) | 0.555676 | 0.264765 |
from pathlib import Path
import os
import pytest
from examples_tests.test_util import SubProcessChecker
working_path = Path(__file__).parent.parent
@pytest.mark.usefixtures("ipu_sparse_ops")
class TestTensorFlowSparseFcBenchmarks(SubProcessChecker):
"""High-level integration tests for TensorFlow dynamic sparse FC layer benchmarks"""
@pytest.mark.category1
def test_help(self):
self.run_command("python3 dynamic_sparse_fc.py --help",
working_path,
"usage: dynamic_sparse_fc.py")
@pytest.mark.category1
@pytest.mark.ipus(1)
def test_default(self):
self.run_command("python3 dynamic_sparse_fc.py",
working_path,
[r"(\w+.\w+) items/sec (\w+.\w+) TFLOPS/sec"])
@pytest.mark.category1
@pytest.mark.ipus(1)
def test_16x16_blocks(self):
self.run_command("python3 dynamic_sparse_fc.py --block-size 16 --batch-size=1 --input-size=160 --output-size=160",
working_path,
[r"(\w+.\w+) items/sec (\w+.\w+) TFLOPS/sec"])
@pytest.mark.category1
@pytest.mark.ipus(1)
def test_default_fp16(self):
self.run_command("python3 dynamic_sparse_fc.py --data-type fp16",
working_path,
[r"(\w+.\w+) items/sec (\w+.\w+) TFLOPS/sec"])
@pytest.mark.category1
@pytest.mark.ipus(1)
def test_all_args(self):
self.run_command("python3 dynamic_sparse_fc.py --input-size 512 --output-size 1024 --batch-size 16 --batches-per-step 10 --density 0.2",
working_path,
[r"(\w+.\w+) items/sec (\w+.\w+) TFLOPS/sec"])
@pytest.mark.category1
@pytest.mark.ipus(1)
def test_train(self):
self.run_command("python3 dynamic_sparse_fc.py --mode train",
working_path,
[r"(\w+.\w+) items/sec (\w+.\w+) TFLOPS/sec"])
@pytest.mark.category1
@pytest.mark.ipus(1)
def test_train_real_data(self):
self.run_command("python3 dynamic_sparse_fc.py --mode train --use-generated-data",
working_path,
[r"(\w+.\w+) items/sec (\w+.\w+) TFLOPS/sec"]) | code_examples/tensorflow/kernel_benchmarks/test/test_dynamic_sparse_fc.py | from pathlib import Path
import os
import pytest
from examples_tests.test_util import SubProcessChecker
working_path = Path(__file__).parent.parent
@pytest.mark.usefixtures("ipu_sparse_ops")
class TestTensorFlowSparseFcBenchmarks(SubProcessChecker):
"""High-level integration tests for TensorFlow dynamic sparse FC layer benchmarks"""
@pytest.mark.category1
def test_help(self):
self.run_command("python3 dynamic_sparse_fc.py --help",
working_path,
"usage: dynamic_sparse_fc.py")
@pytest.mark.category1
@pytest.mark.ipus(1)
def test_default(self):
self.run_command("python3 dynamic_sparse_fc.py",
working_path,
[r"(\w+.\w+) items/sec (\w+.\w+) TFLOPS/sec"])
@pytest.mark.category1
@pytest.mark.ipus(1)
def test_16x16_blocks(self):
self.run_command("python3 dynamic_sparse_fc.py --block-size 16 --batch-size=1 --input-size=160 --output-size=160",
working_path,
[r"(\w+.\w+) items/sec (\w+.\w+) TFLOPS/sec"])
@pytest.mark.category1
@pytest.mark.ipus(1)
def test_default_fp16(self):
self.run_command("python3 dynamic_sparse_fc.py --data-type fp16",
working_path,
[r"(\w+.\w+) items/sec (\w+.\w+) TFLOPS/sec"])
@pytest.mark.category1
@pytest.mark.ipus(1)
def test_all_args(self):
self.run_command("python3 dynamic_sparse_fc.py --input-size 512 --output-size 1024 --batch-size 16 --batches-per-step 10 --density 0.2",
working_path,
[r"(\w+.\w+) items/sec (\w+.\w+) TFLOPS/sec"])
@pytest.mark.category1
@pytest.mark.ipus(1)
def test_train(self):
self.run_command("python3 dynamic_sparse_fc.py --mode train",
working_path,
[r"(\w+.\w+) items/sec (\w+.\w+) TFLOPS/sec"])
@pytest.mark.category1
@pytest.mark.ipus(1)
def test_train_real_data(self):
self.run_command("python3 dynamic_sparse_fc.py --mode train --use-generated-data",
working_path,
[r"(\w+.\w+) items/sec (\w+.\w+) TFLOPS/sec"]) | 0.581422 | 0.474875 |
from vitamins.geometry import Vec3, Orientation
from vitamins import math
class Location(Vec3):
"""Objects that have a location."""
modified: bool = False
@property
def position(self) -> Vec3:
return Vec3(self.x, self.y, self.z)
@position.setter
def position(self, value: Vec3):
self.x, self.y, self.z = value
self.modified = True
class MovingLocation(Location):
"""Location that has a velocity."""
def __init__(self, position: Vec3, velocity: Vec3):
super().__init__(position)
self.velocity = velocity
@property
def speed(self):
return self.velocity.length()
@property
def direction(self):
return self.velocity.normalized()
def relative_velocity(self, other: Vec3) -> Vec3:
if hasattr(other, "velocity"):
return self.velocity - other.velocity
else:
return self.velocity
def speed_toward(self, other) -> float:
"""Closing speed (positive=approaching, negative=away)."""
return self.relative_velocity(other).dot(self.to(other).normalized())
class OrientedObject(Location):
"""GameObjects that also have velocity, angular velocity, and orientation."""
def __init__(
self,
position: Vec3 = 0,
velocity: Vec3 = 0,
angular_velocity: Vec3 = 0,
orientation: Orientation = None,
):
super().__init__(position)
self.velocity = Vec3(velocity)
self.angular_velocity = Vec3(angular_velocity)
if orientation is None:
orientation = Orientation(Vec3())
self.orientation = orientation
@property
def up(self)->Vec3:
return self.orientation.up
@property
def down(self)->Vec3:
return -self.orientation.up
@property
def left(self)->Vec3:
return -self.orientation.right
@property
def right(self)->Vec3:
return self.orientation.right
@property
def forward(self)->Vec3:
return self.orientation.forward
@property
def backward(self)->Vec3:
return -self.orientation.forward
@property
def yaw(self)->float:
return self.orientation.yaw
@property
def pitch(self)->float:
return self.orientation.pitch
@property
def roll(self)->float:
return self.orientation.roll
@property
def yaw_rate(self)->float:
return self.angular_velocity.dot(self.orientation.up)
@property
def pitch_rate(self)->float:
return self.angular_velocity.dot(-self.orientation.right)
@property
def roll_rate(self)->float:
return self.angular_velocity.dot(-self.orientation.forward)
def yaw_to(self, other: Vec3)->float:
"""Returns the yaw angle from the object's forward vector to the given location
(projected onto the object's horizontal plane).
"""
ovec = self.to(other)
ox = ovec.dot(self.left)
oy = ovec.dot(self.forward)
return -math.atan2(ox, oy) | vitamins/match/base.py |
from vitamins.geometry import Vec3, Orientation
from vitamins import math
class Location(Vec3):
"""Objects that have a location."""
modified: bool = False
@property
def position(self) -> Vec3:
return Vec3(self.x, self.y, self.z)
@position.setter
def position(self, value: Vec3):
self.x, self.y, self.z = value
self.modified = True
class MovingLocation(Location):
"""Location that has a velocity."""
def __init__(self, position: Vec3, velocity: Vec3):
super().__init__(position)
self.velocity = velocity
@property
def speed(self):
return self.velocity.length()
@property
def direction(self):
return self.velocity.normalized()
def relative_velocity(self, other: Vec3) -> Vec3:
if hasattr(other, "velocity"):
return self.velocity - other.velocity
else:
return self.velocity
def speed_toward(self, other) -> float:
"""Closing speed (positive=approaching, negative=away)."""
return self.relative_velocity(other).dot(self.to(other).normalized())
class OrientedObject(Location):
"""GameObjects that also have velocity, angular velocity, and orientation."""
def __init__(
self,
position: Vec3 = 0,
velocity: Vec3 = 0,
angular_velocity: Vec3 = 0,
orientation: Orientation = None,
):
super().__init__(position)
self.velocity = Vec3(velocity)
self.angular_velocity = Vec3(angular_velocity)
if orientation is None:
orientation = Orientation(Vec3())
self.orientation = orientation
@property
def up(self)->Vec3:
return self.orientation.up
@property
def down(self)->Vec3:
return -self.orientation.up
@property
def left(self)->Vec3:
return -self.orientation.right
@property
def right(self)->Vec3:
return self.orientation.right
@property
def forward(self)->Vec3:
return self.orientation.forward
@property
def backward(self)->Vec3:
return -self.orientation.forward
@property
def yaw(self)->float:
return self.orientation.yaw
@property
def pitch(self)->float:
return self.orientation.pitch
@property
def roll(self)->float:
return self.orientation.roll
@property
def yaw_rate(self)->float:
return self.angular_velocity.dot(self.orientation.up)
@property
def pitch_rate(self)->float:
return self.angular_velocity.dot(-self.orientation.right)
@property
def roll_rate(self)->float:
return self.angular_velocity.dot(-self.orientation.forward)
def yaw_to(self, other: Vec3)->float:
"""Returns the yaw angle from the object's forward vector to the given location
(projected onto the object's horizontal plane).
"""
ovec = self.to(other)
ox = ovec.dot(self.left)
oy = ovec.dot(self.forward)
return -math.atan2(ox, oy) | 0.970409 | 0.62223 |
import channels
from entity_pb2 import Entity
from entity_pb2 import Player
from world_pb2 import World
from browserquest_broadcast_pb2 import SpawnRequest
from browserquest_broadcast_pb2 import ListRequest
from browserquest_broadcast_pb2 import MoveRequest
from browserquest_broadcast_pb2 import AttackRequest
from browserquest_broadcast_pb2 import KillRequest
from browserquest_broadcast_pb2 import DespawnRequest
from browserquest_broadcast_pb2 import PopulationRequest
from browserquest_broadcast_pb2 import DestroyRequest
from event_service_pb2 import EventService
from browserquest_pb2 import BrowserQuest_Stub
from world_service_pb2 import WorldService_Stub
from entity_service_pb2 import EntityService_Stub
class BrowserQuestEventService(EventService):
def PlayerLogined(self, controller, event, callback):
entity_service = EntityService_Stub(channels.entity_channel)
player = Player()
player.id = event.player_id
player = entity_service.GetPlayer(controller, player)
def EntityJoinWorld(self, controller, event, callback):
entity_service = EntityService_Stub(channels.entity_channel)
entity = Entity()
entity.id = event.entity_id
entity = entity_service.GetEntity(controller, entity)
def PopulationUpdate(self, controller, event, callback):
world_service = WorldService_Stub(channels.world_channel)
browserquest_stub = BrowserQuest_Stub(channels.browserquest_channel)
world = World()
world.id = event.world_id
id_list = world_service.GetWorldPlayerList(controller, world)
population = PopulationRequest()
population.world = event.world_id
population.total = event.population
controller.player_ids = id_list.ids
browserquest_stub.population(controller, population)
def EntityGroupChanged(self, controller, event, callback):
entity_service = EntityService_Stub(channels.entity_channel)
browserquest_stub = BrowserQuest_Stub(channels.browserquest_channel)
world_service = WorldService_Stub(channels.world_channel)
entity = Entity()
entity.id = event.entity_id
entity = entity_service.GetEntity(controller, entity)
list_request = ListRequest()
id_list = world_service.GetRelevantEntityList(controller, entity)
list_request.entity_ids.extend(id_list.ids)
controller.player_ids = [entity.id]
browserquest_stub.list(controller, list_request)
spawn = SpawnRequest()
spawn.entity_id = entity.id
spawn.kind = entity.kind
spawn.x = entity.x
spawn.y = entity.y
spawn.name = entity.name
spawn.orientation = 1
spawn.armor = entity.armor
spawn.weapon = entity.weapon
id_list = world_service.GetAdjacentPlayerList(controller, entity)
controller.player_ids = id_list.ids
browserquest_stub.spawn(controller, spawn)
destroy = DestroyRequest()
destroy.entity_id = entity.id
id_list = world_service.GetRecentlyLeftGroupPlayerList(controller, entity)
controller.player_ids = id_list.ids
browserquest_stub.destroy(controller, destroy)
def EntityMove(self, controller, event, callback):
browserquest_stub = BrowserQuest_Stub(channels.browserquest_channel)
world_service = WorldService_Stub(channels.world_channel)
move_request = MoveRequest()
move_request.entity_id = event.entity_id
move_request.entity_x = event.x
move_request.entity_y = event.y
entity = Entity()
entity.id = event.entity_id
id_list = world_service.GetAdjacentPlayerList(controller, entity)
controller.player_ids = id_list.ids
browserquest_stub.move(controller, move_request)
def Attack(self, controller, event, callback):
browserquest_stub = BrowserQuest_Stub(channels.browserquest_channel)
world_service = WorldService_Stub(channels.world_channel)
attack_request = AttackRequest()
attack_request.attacker_id = event.attack_id
attack_request.target_id = event.target_id
entity = Entity()
entity.id = event.attack_id
id_list = world_service.GetAdjacentPlayerList(controller, entity)
controller.player_ids = id_list.ids
browserquest_stub.attack(controller, attack_request)
def Damage(self, controller, event, callback):
pass
def Kill(self, controller, event, callback):
world_service = WorldService_Stub(channels.world_channel)
entity_service = EntityService_Stub(channels.entity_channel)
browserquest_stub = BrowserQuest_Stub(channels.browserquest_channel)
killed_entity = Entity()
killed_entity.id = event.killed_id
killed_entity = entity_service.GetEntity(controller, killed_entity)
kill_request = KillRequest()
kill_request.mob_kind = killed_entity.kind
controller.player_ids = [event.killer_id]
browserquest_stub.kill(controller, kill_request)
despawn_request = DespawnRequest()
despawn_request.entity_id = event.killed_id
id_list = world_service.GetAdjacentPlayerList(controller, killed_entity)
controller.player_ids = id_list.ids
browserquest_stub.despawn(controller, despawn_request) | session_server/services/browserquest_event.py | import channels
from entity_pb2 import Entity
from entity_pb2 import Player
from world_pb2 import World
from browserquest_broadcast_pb2 import SpawnRequest
from browserquest_broadcast_pb2 import ListRequest
from browserquest_broadcast_pb2 import MoveRequest
from browserquest_broadcast_pb2 import AttackRequest
from browserquest_broadcast_pb2 import KillRequest
from browserquest_broadcast_pb2 import DespawnRequest
from browserquest_broadcast_pb2 import PopulationRequest
from browserquest_broadcast_pb2 import DestroyRequest
from event_service_pb2 import EventService
from browserquest_pb2 import BrowserQuest_Stub
from world_service_pb2 import WorldService_Stub
from entity_service_pb2 import EntityService_Stub
class BrowserQuestEventService(EventService):
def PlayerLogined(self, controller, event, callback):
entity_service = EntityService_Stub(channels.entity_channel)
player = Player()
player.id = event.player_id
player = entity_service.GetPlayer(controller, player)
def EntityJoinWorld(self, controller, event, callback):
entity_service = EntityService_Stub(channels.entity_channel)
entity = Entity()
entity.id = event.entity_id
entity = entity_service.GetEntity(controller, entity)
def PopulationUpdate(self, controller, event, callback):
world_service = WorldService_Stub(channels.world_channel)
browserquest_stub = BrowserQuest_Stub(channels.browserquest_channel)
world = World()
world.id = event.world_id
id_list = world_service.GetWorldPlayerList(controller, world)
population = PopulationRequest()
population.world = event.world_id
population.total = event.population
controller.player_ids = id_list.ids
browserquest_stub.population(controller, population)
def EntityGroupChanged(self, controller, event, callback):
entity_service = EntityService_Stub(channels.entity_channel)
browserquest_stub = BrowserQuest_Stub(channels.browserquest_channel)
world_service = WorldService_Stub(channels.world_channel)
entity = Entity()
entity.id = event.entity_id
entity = entity_service.GetEntity(controller, entity)
list_request = ListRequest()
id_list = world_service.GetRelevantEntityList(controller, entity)
list_request.entity_ids.extend(id_list.ids)
controller.player_ids = [entity.id]
browserquest_stub.list(controller, list_request)
spawn = SpawnRequest()
spawn.entity_id = entity.id
spawn.kind = entity.kind
spawn.x = entity.x
spawn.y = entity.y
spawn.name = entity.name
spawn.orientation = 1
spawn.armor = entity.armor
spawn.weapon = entity.weapon
id_list = world_service.GetAdjacentPlayerList(controller, entity)
controller.player_ids = id_list.ids
browserquest_stub.spawn(controller, spawn)
destroy = DestroyRequest()
destroy.entity_id = entity.id
id_list = world_service.GetRecentlyLeftGroupPlayerList(controller, entity)
controller.player_ids = id_list.ids
browserquest_stub.destroy(controller, destroy)
def EntityMove(self, controller, event, callback):
browserquest_stub = BrowserQuest_Stub(channels.browserquest_channel)
world_service = WorldService_Stub(channels.world_channel)
move_request = MoveRequest()
move_request.entity_id = event.entity_id
move_request.entity_x = event.x
move_request.entity_y = event.y
entity = Entity()
entity.id = event.entity_id
id_list = world_service.GetAdjacentPlayerList(controller, entity)
controller.player_ids = id_list.ids
browserquest_stub.move(controller, move_request)
def Attack(self, controller, event, callback):
browserquest_stub = BrowserQuest_Stub(channels.browserquest_channel)
world_service = WorldService_Stub(channels.world_channel)
attack_request = AttackRequest()
attack_request.attacker_id = event.attack_id
attack_request.target_id = event.target_id
entity = Entity()
entity.id = event.attack_id
id_list = world_service.GetAdjacentPlayerList(controller, entity)
controller.player_ids = id_list.ids
browserquest_stub.attack(controller, attack_request)
def Damage(self, controller, event, callback):
pass
def Kill(self, controller, event, callback):
world_service = WorldService_Stub(channels.world_channel)
entity_service = EntityService_Stub(channels.entity_channel)
browserquest_stub = BrowserQuest_Stub(channels.browserquest_channel)
killed_entity = Entity()
killed_entity.id = event.killed_id
killed_entity = entity_service.GetEntity(controller, killed_entity)
kill_request = KillRequest()
kill_request.mob_kind = killed_entity.kind
controller.player_ids = [event.killer_id]
browserquest_stub.kill(controller, kill_request)
despawn_request = DespawnRequest()
despawn_request.entity_id = event.killed_id
id_list = world_service.GetAdjacentPlayerList(controller, killed_entity)
controller.player_ids = id_list.ids
browserquest_stub.despawn(controller, despawn_request) | 0.429549 | 0.135461 |
import pandas as pd
import requests
import re
import datetime
import json
from pandas import Series
from iex.utils import (param_bool,
parse_date,
validate_date_format,
validate_range_set,
validate_output_format,
timestamp_to_datetime,
timestamp_to_isoformat)
from iex.constants import (BASE_URL,
CHART_RANGES,
RANGES,
DATE_FIELDS)
class Batch:
"""
The Batch object is designed to fetch data
from multiple stocks.
"""
def __init__(self, symbols, date_format='timestamp', output_format='dataframe'):
"""
Args:
symbols - a list of symbols.
output_format - dataframe (pandas) or json
convert_dates - Converts dates
"""
self.symbols = symbols
self.symbols_list = ','.join(symbols)
self.date_format = validate_date_format(date_format)
self.output_format = validate_output_format(output_format)
def _get(self, _type, params={}):
request_url = BASE_URL + '/stock/market/batch'
params.update({'symbols': self.symbols_list,
'types': _type})
response = requests.get(request_url, params=params)
# Check the response
if response.status_code != 200:
raise Exception(f"{response.status_code}: {response.content.decode('utf-8')}")
if self.output_format == 'json':
return response.json()
result = response.json()
if _type in ['delayed_quote',
'price']:
for symbol, v in result.items():
v.update({'symbol': symbol})
result = pd.DataFrame.from_dict([v for k, v in result.items()])
# Symbol --> List
elif _type in ['peers']:
for symbol, v in result.items():
v.update({'symbol': symbol})
result = pd.DataFrame.from_dict([v for k, v in result.items()])
# Expand nested columns
result = result.set_index('symbol') \
.apply(lambda x: x.apply(pd.Series).stack()) \
.reset_index() \
.drop('level_1', 1)
# Nested result
elif _type in ['company',
'quote',
'stats']:
for symbol, item in result.items():
item.update({'symbol': symbol})
result = pd.DataFrame.from_dict([v[_type] for k, v in result.items()])
# Nested multi-line
elif _type in ['earnings', 'financials']:
result_set = []
for symbol, rows in result.items():
for row in rows[_type][_type]:
row.update({'symbol': symbol})
result_set.append(row)
result = pd.DataFrame.from_dict(result_set)
# Nested result list
elif _type in ['book', 'chart']:
result_set = []
for symbol, rowset in result.items():
for row in rowset[_type]:
row.update({'symbol': symbol})
result_set.append(row)
result = pd.DataFrame.from_dict(result_set)
# Convert columns with unix timestamps
if self.date_format:
date_field_conv = [x for x in result.columns if x in DATE_FIELDS]
if date_field_conv:
if self.date_format == 'datetime':
date_apply_func = timestamp_to_datetime
elif self.date_format == 'isoformat':
date_apply_func = timestamp_to_isoformat
result[date_field_conv] = result[date_field_conv].applymap(date_apply_func)
# Move symbol to first column
cols = ['symbol'] + [x for x in result.columns if x != 'symbol']
result = result.reindex(cols, axis=1)
return result
def book(self):
return self._get("book")
def chart(self, range):
if range not in CHART_RANGES:
err_msg = f"Invalid range: '{range}'. Valid ranges are {', '.join(CHART_RANGES)}"
raise ValueError(err_msg)
return self._get("chart", params={'range': range})
def company(self):
return self._get("company")
def delayed_quote(self):
return self._get("delayed_quote")
def dividends(self, range):
if range not in DIVIDEND_RANGES:
err_msg = f"Invalid range: '{range}'. Valid ranges are {', '.join(DIVIDEND_RANGES)}"
raise ValueError(err_msg)
def earnings(self):
return self._get('earnings')
def financials(self):
return self._get('financials')
def stats(self):
return self._get('stats')
def peers(self):
return self._get('peers')
def price(self):
return self._get("price")
def quote(self, displayPercent=False):
displayPercent = param_bool(displayPercent)
return self._get("quote", params={"displayPercent": displayPercent})
def __repr__(self):
return f"<Batch: {len(self.symbols)} symbols>" | iex/batch.py | import pandas as pd
import requests
import re
import datetime
import json
from pandas import Series
from iex.utils import (param_bool,
parse_date,
validate_date_format,
validate_range_set,
validate_output_format,
timestamp_to_datetime,
timestamp_to_isoformat)
from iex.constants import (BASE_URL,
CHART_RANGES,
RANGES,
DATE_FIELDS)
class Batch:
"""
The Batch object is designed to fetch data
from multiple stocks.
"""
def __init__(self, symbols, date_format='timestamp', output_format='dataframe'):
"""
Args:
symbols - a list of symbols.
output_format - dataframe (pandas) or json
convert_dates - Converts dates
"""
self.symbols = symbols
self.symbols_list = ','.join(symbols)
self.date_format = validate_date_format(date_format)
self.output_format = validate_output_format(output_format)
def _get(self, _type, params={}):
request_url = BASE_URL + '/stock/market/batch'
params.update({'symbols': self.symbols_list,
'types': _type})
response = requests.get(request_url, params=params)
# Check the response
if response.status_code != 200:
raise Exception(f"{response.status_code}: {response.content.decode('utf-8')}")
if self.output_format == 'json':
return response.json()
result = response.json()
if _type in ['delayed_quote',
'price']:
for symbol, v in result.items():
v.update({'symbol': symbol})
result = pd.DataFrame.from_dict([v for k, v in result.items()])
# Symbol --> List
elif _type in ['peers']:
for symbol, v in result.items():
v.update({'symbol': symbol})
result = pd.DataFrame.from_dict([v for k, v in result.items()])
# Expand nested columns
result = result.set_index('symbol') \
.apply(lambda x: x.apply(pd.Series).stack()) \
.reset_index() \
.drop('level_1', 1)
# Nested result
elif _type in ['company',
'quote',
'stats']:
for symbol, item in result.items():
item.update({'symbol': symbol})
result = pd.DataFrame.from_dict([v[_type] for k, v in result.items()])
# Nested multi-line
elif _type in ['earnings', 'financials']:
result_set = []
for symbol, rows in result.items():
for row in rows[_type][_type]:
row.update({'symbol': symbol})
result_set.append(row)
result = pd.DataFrame.from_dict(result_set)
# Nested result list
elif _type in ['book', 'chart']:
result_set = []
for symbol, rowset in result.items():
for row in rowset[_type]:
row.update({'symbol': symbol})
result_set.append(row)
result = pd.DataFrame.from_dict(result_set)
# Convert columns with unix timestamps
if self.date_format:
date_field_conv = [x for x in result.columns if x in DATE_FIELDS]
if date_field_conv:
if self.date_format == 'datetime':
date_apply_func = timestamp_to_datetime
elif self.date_format == 'isoformat':
date_apply_func = timestamp_to_isoformat
result[date_field_conv] = result[date_field_conv].applymap(date_apply_func)
# Move symbol to first column
cols = ['symbol'] + [x for x in result.columns if x != 'symbol']
result = result.reindex(cols, axis=1)
return result
def book(self):
return self._get("book")
def chart(self, range):
if range not in CHART_RANGES:
err_msg = f"Invalid range: '{range}'. Valid ranges are {', '.join(CHART_RANGES)}"
raise ValueError(err_msg)
return self._get("chart", params={'range': range})
def company(self):
return self._get("company")
def delayed_quote(self):
return self._get("delayed_quote")
def dividends(self, range):
if range not in DIVIDEND_RANGES:
err_msg = f"Invalid range: '{range}'. Valid ranges are {', '.join(DIVIDEND_RANGES)}"
raise ValueError(err_msg)
def earnings(self):
return self._get('earnings')
def financials(self):
return self._get('financials')
def stats(self):
return self._get('stats')
def peers(self):
return self._get('peers')
def price(self):
return self._get("price")
def quote(self, displayPercent=False):
displayPercent = param_bool(displayPercent)
return self._get("quote", params={"displayPercent": displayPercent})
def __repr__(self):
return f"<Batch: {len(self.symbols)} symbols>" | 0.555918 | 0.259186 |
from __future__ import unicode_literals
from django.utils.encoding import python_2_unicode_compatible
from django.db import models, IntegrityError, DatabaseError, transaction
from django.db.models import Q
from django.urls import reverse
from django.utils import timezone
try:
from version_utils.rpm import labelCompare
except ImportError:
from rpm import labelCompare
from tagging.fields import TagField
from packages.models import Package, PackageUpdate
from domains.models import Domain
from repos.models import Repository
from operatingsystems.models import OS
from arch.models import MachineArchitecture
from patchman.signals import info_message, error_message
from repos.utils import find_best_repo
from hosts.utils import update_rdns, remove_reports
@python_2_unicode_compatible
class Host(models.Model):
hostname = models.CharField(max_length=255, unique=True)
ipaddress = models.GenericIPAddressField()
reversedns = models.CharField(max_length=255, blank=True, null=True)
check_dns = models.BooleanField(default=True)
os = models.ForeignKey(OS, on_delete=models.CASCADE)
kernel = models.CharField(max_length=255)
arch = models.ForeignKey(MachineArchitecture, on_delete=models.CASCADE)
domain = models.ForeignKey(Domain, on_delete=models.CASCADE)
lastreport = models.DateTimeField()
packages = models.ManyToManyField(Package, blank=True)
repos = models.ManyToManyField(Repository, blank=True, through='HostRepo')
updates = models.ManyToManyField(PackageUpdate, blank=True)
reboot_required = models.BooleanField(default=False)
host_repos_only = models.BooleanField(default=True)
tags = TagField()
updated_at = models.DateTimeField(default=timezone.now)
class Meta(object):
verbose_name = 'Host'
verbose_name_plural = 'Hosts'
ordering = ('hostname',)
def __str__(self):
return self.hostname
def show(self):
""" Show info about this host
"""
text = '{0!s}:\n'.format(self)
text += 'IP address : {0!s}\n'.format(self.ipaddress)
text += 'Reverse DNS : {0!s}\n'.format(self.reversedns)
text += 'Domain : {0!s}\n'.format(self.domain)
text += 'OS : {0!s}\n'.format(self.os)
text += 'Kernel : {0!s}\n'.format(self.kernel)
text += 'Architecture : {0!s}\n'.format(self.arch)
text += 'Last report : {0!s}\n'.format(self.lastreport)
text += 'Packages : {0!s}\n'.format(self.get_num_packages())
text += 'Repos : {0!s}\n'.format(self.get_num_repos())
text += 'Updates : {0!s}\n'.format(self.get_num_updates())
text += 'Tags : {0!s}\n'.format(self.tags)
text += 'Needs reboot : {0!s}\n'.format(self.reboot_required)
text += 'Updated at : {0!s}\n'.format(self.updated_at)
text += 'Host repos : {0!s}\n'.format(self.host_repos_only)
info_message.send(sender=None, text=text)
def get_absolute_url(self):
return reverse('hosts:host_detail', args=[self.hostname])
def get_num_security_updates(self):
return self.updates.filter(security=True).count()
def get_num_bugfix_updates(self):
return self.updates.filter(security=False).count()
def get_num_updates(self):
return self.updates.count()
def get_num_packages(self):
return self.packages.count()
def get_num_repos(self):
return self.repos.count()
def check_rdns(self):
if self.check_dns:
update_rdns(self)
if self.hostname.lower() == self.reversedns.lower():
info_message.send(sender=None, text='Reverse DNS matches')
else:
text = 'Reverse DNS mismatch found: '
text += '{0!s} != {1!s}'.format(self.hostname, self.reversedns)
info_message.send(sender=None, text=text)
else:
info_message.send(sender=None,
text='Reverse DNS check disabled')
def clean_reports(self, timestamp):
remove_reports(self, timestamp)
def get_host_repo_packages(self):
if self.host_repos_only:
hostrepos_q = Q(mirror__repo__in=self.repos.all(),
mirror__enabled=True, mirror__repo__enabled=True,
mirror__repo__hostrepo__enabled=True)
else:
hostrepos_q = \
Q(mirror__repo__osgroup__os__host=self,
mirror__repo__arch=self.arch, mirror__enabled=True,
mirror__repo__enabled=True) | \
Q(mirror__repo__in=self.repos.all(),
mirror__enabled=True, mirror__repo__enabled=True)
return Package.objects.select_related().filter(hostrepos_q).distinct()
def process_update(self, package, highest_package):
if self.host_repos_only:
host_repos = Q(repo__host=self)
else:
host_repos = \
Q(repo__osgroup__os__host=self, repo__arch=self.arch) | \
Q(repo__host=self)
mirrors = highest_package.mirror_set.filter(host_repos)
security = False
# If any of the containing repos are security,
# mark the update as security
for mirror in mirrors:
if mirror.repo.security:
security = True
try:
updates = PackageUpdate.objects.all()
with transaction.atomic():
update, c = updates.get_or_create(
oldpackage=package,
newpackage=highest_package,
security=security)
except IntegrityError as e:
error_message.send(sender=None, text=e)
update = updates.get(oldpackage=package,
newpackage=highest_package,
security=security)
except DatabaseError as e:
error_message.send(sender=None, text=e)
try:
with transaction.atomic():
self.updates.add(update)
info_message.send(sender=None, text='{0!s}'.format(update))
return update.id
except IntegrityError as e:
error_message.send(sender=None, text=e)
except DatabaseError as e:
error_message.send(sender=None, text=e)
def find_updates(self):
kernels_q = Q(name__name='kernel') | Q(name__name='kernel-devel') | \
Q(name__name='kernel-pae') | Q(name__name='kernel-pae-devel') | \
Q(name__name='kernel-xen') | Q(name__name='kernel-xen-devel') | \
Q(name__name='kernel-headers') | Q(name__name='kernel-default')
repo_packages = self.get_host_repo_packages()
host_packages = self.packages.exclude(kernels_q).distinct()
kernel_packages = self.packages.filter(kernels_q)
if self.host_repos_only:
update_ids = self.find_host_repo_updates(host_packages,
repo_packages)
else:
update_ids = self.find_osgroup_repo_updates(host_packages,
repo_packages)
kernel_update_ids = self.find_kernel_updates(kernel_packages,
repo_packages)
for ku_id in kernel_update_ids:
update_ids.append(ku_id)
for update in self.updates.all():
if update.id not in update_ids:
self.updates.remove(update)
def find_host_repo_updates(self, host_packages, repo_packages):
update_ids = []
hostrepos_q = Q(repo__mirror__enabled=True,
repo__mirror__repo__enabled=True, host=self)
hostrepos = HostRepo.objects.select_related().filter(hostrepos_q)
for package in host_packages:
highest_package = package
best_repo = find_best_repo(package, hostrepos)
priority = None
if best_repo is not None:
priority = best_repo.priority
# find the packages that are potential updates
pu_q = Q(name=package.name, arch=package.arch,
packagetype=package.packagetype)
potential_updates = repo_packages.filter(pu_q)
for potential_update in potential_updates:
if highest_package.compare_version(potential_update) == -1 \
and package.compare_version(potential_update) == -1:
if priority is not None:
# proceed only if the package is from a repo with a
# priority and that priority is >= the repo priority
pu_best_repo = find_best_repo(potential_update,
hostrepos)
pu_priority = pu_best_repo.priority
if pu_priority >= priority:
highest_package = potential_update
else:
highest_package = potential_update
if highest_package != package:
uid = self.process_update(package, highest_package)
if uid is not None:
update_ids.append(uid)
return update_ids
def find_osgroup_repo_updates(self, host_packages, repo_packages):
update_ids = []
for package in host_packages:
highest_package = package
# find the packages that are potential updates
pu_q = Q(name=package.name, arch=package.arch,
packagetype=package.packagetype)
potential_updates = repo_packages.filter(pu_q)
for potential_update in potential_updates:
if highest_package.compare_version(potential_update) == -1 \
and package.compare_version(potential_update) == -1:
highest_package = potential_update
if highest_package != package:
uid = self.process_update(package, highest_package)
if uid is not None:
update_ids.append(uid)
return update_ids
def check_if_reboot_required(self, host_highest):
to_strip = ['xen', '-xen', 'PAE', '-pae', '-default', 'vanilla', '-pv']
kernel = self.kernel
for s in to_strip:
if kernel.endswith(s):
kernel = kernel[:-len(s)]
ver, rel = kernel.rsplit('-')
kernel_ver = ('', str(ver), str(rel))
host_highest_ver = ('', host_highest.version, host_highest.release)
if labelCompare(kernel_ver, host_highest_ver) == -1:
self.reboot_required = True
else:
self.reboot_required = False
def find_kernel_updates(self, kernel_packages, repo_packages):
update_ids = []
for package in kernel_packages:
host_highest = package
repo_highest = package
pk_q = Q(name=package.name)
potential_updates = repo_packages.filter(pk_q)
for pu in potential_updates:
if package.compare_version(pu) == -1 \
and repo_highest.compare_version(pu) == -1:
repo_highest = pu
host_packages = self.packages.filter(pk_q)
for hp in host_packages:
if package.compare_version(hp) == -1 and \
host_highest.compare_version(hp) == -1:
host_highest = hp
if host_highest.compare_version(repo_highest) == -1:
uid = self.process_update(host_highest, repo_highest)
if uid is not None:
update_ids.append(uid)
self.check_if_reboot_required(host_highest)
try:
with transaction.atomic():
self.save()
except DatabaseError as e:
error_message.send(sender=None, text=e)
return update_ids
@python_2_unicode_compatible
class HostRepo(models.Model):
host = models.ForeignKey(Host, on_delete=models.CASCADE)
repo = models.ForeignKey(Repository, on_delete=models.CASCADE)
enabled = models.BooleanField(default=True)
priority = models.IntegerField(default=0)
class Meta(object):
unique_together = ('host', 'repo')
def __str__(self):
return '{0!s}-{1!s}'.format(self.host, self.repo) | gopatch/hosts/models.py |
from __future__ import unicode_literals
from django.utils.encoding import python_2_unicode_compatible
from django.db import models, IntegrityError, DatabaseError, transaction
from django.db.models import Q
from django.urls import reverse
from django.utils import timezone
try:
from version_utils.rpm import labelCompare
except ImportError:
from rpm import labelCompare
from tagging.fields import TagField
from packages.models import Package, PackageUpdate
from domains.models import Domain
from repos.models import Repository
from operatingsystems.models import OS
from arch.models import MachineArchitecture
from patchman.signals import info_message, error_message
from repos.utils import find_best_repo
from hosts.utils import update_rdns, remove_reports
@python_2_unicode_compatible
class Host(models.Model):
hostname = models.CharField(max_length=255, unique=True)
ipaddress = models.GenericIPAddressField()
reversedns = models.CharField(max_length=255, blank=True, null=True)
check_dns = models.BooleanField(default=True)
os = models.ForeignKey(OS, on_delete=models.CASCADE)
kernel = models.CharField(max_length=255)
arch = models.ForeignKey(MachineArchitecture, on_delete=models.CASCADE)
domain = models.ForeignKey(Domain, on_delete=models.CASCADE)
lastreport = models.DateTimeField()
packages = models.ManyToManyField(Package, blank=True)
repos = models.ManyToManyField(Repository, blank=True, through='HostRepo')
updates = models.ManyToManyField(PackageUpdate, blank=True)
reboot_required = models.BooleanField(default=False)
host_repos_only = models.BooleanField(default=True)
tags = TagField()
updated_at = models.DateTimeField(default=timezone.now)
class Meta(object):
verbose_name = 'Host'
verbose_name_plural = 'Hosts'
ordering = ('hostname',)
def __str__(self):
return self.hostname
def show(self):
""" Show info about this host
"""
text = '{0!s}:\n'.format(self)
text += 'IP address : {0!s}\n'.format(self.ipaddress)
text += 'Reverse DNS : {0!s}\n'.format(self.reversedns)
text += 'Domain : {0!s}\n'.format(self.domain)
text += 'OS : {0!s}\n'.format(self.os)
text += 'Kernel : {0!s}\n'.format(self.kernel)
text += 'Architecture : {0!s}\n'.format(self.arch)
text += 'Last report : {0!s}\n'.format(self.lastreport)
text += 'Packages : {0!s}\n'.format(self.get_num_packages())
text += 'Repos : {0!s}\n'.format(self.get_num_repos())
text += 'Updates : {0!s}\n'.format(self.get_num_updates())
text += 'Tags : {0!s}\n'.format(self.tags)
text += 'Needs reboot : {0!s}\n'.format(self.reboot_required)
text += 'Updated at : {0!s}\n'.format(self.updated_at)
text += 'Host repos : {0!s}\n'.format(self.host_repos_only)
info_message.send(sender=None, text=text)
def get_absolute_url(self):
return reverse('hosts:host_detail', args=[self.hostname])
def get_num_security_updates(self):
return self.updates.filter(security=True).count()
def get_num_bugfix_updates(self):
return self.updates.filter(security=False).count()
def get_num_updates(self):
return self.updates.count()
def get_num_packages(self):
return self.packages.count()
def get_num_repos(self):
return self.repos.count()
def check_rdns(self):
if self.check_dns:
update_rdns(self)
if self.hostname.lower() == self.reversedns.lower():
info_message.send(sender=None, text='Reverse DNS matches')
else:
text = 'Reverse DNS mismatch found: '
text += '{0!s} != {1!s}'.format(self.hostname, self.reversedns)
info_message.send(sender=None, text=text)
else:
info_message.send(sender=None,
text='Reverse DNS check disabled')
def clean_reports(self, timestamp):
remove_reports(self, timestamp)
def get_host_repo_packages(self):
if self.host_repos_only:
hostrepos_q = Q(mirror__repo__in=self.repos.all(),
mirror__enabled=True, mirror__repo__enabled=True,
mirror__repo__hostrepo__enabled=True)
else:
hostrepos_q = \
Q(mirror__repo__osgroup__os__host=self,
mirror__repo__arch=self.arch, mirror__enabled=True,
mirror__repo__enabled=True) | \
Q(mirror__repo__in=self.repos.all(),
mirror__enabled=True, mirror__repo__enabled=True)
return Package.objects.select_related().filter(hostrepos_q).distinct()
def process_update(self, package, highest_package):
if self.host_repos_only:
host_repos = Q(repo__host=self)
else:
host_repos = \
Q(repo__osgroup__os__host=self, repo__arch=self.arch) | \
Q(repo__host=self)
mirrors = highest_package.mirror_set.filter(host_repos)
security = False
# If any of the containing repos are security,
# mark the update as security
for mirror in mirrors:
if mirror.repo.security:
security = True
try:
updates = PackageUpdate.objects.all()
with transaction.atomic():
update, c = updates.get_or_create(
oldpackage=package,
newpackage=highest_package,
security=security)
except IntegrityError as e:
error_message.send(sender=None, text=e)
update = updates.get(oldpackage=package,
newpackage=highest_package,
security=security)
except DatabaseError as e:
error_message.send(sender=None, text=e)
try:
with transaction.atomic():
self.updates.add(update)
info_message.send(sender=None, text='{0!s}'.format(update))
return update.id
except IntegrityError as e:
error_message.send(sender=None, text=e)
except DatabaseError as e:
error_message.send(sender=None, text=e)
def find_updates(self):
kernels_q = Q(name__name='kernel') | Q(name__name='kernel-devel') | \
Q(name__name='kernel-pae') | Q(name__name='kernel-pae-devel') | \
Q(name__name='kernel-xen') | Q(name__name='kernel-xen-devel') | \
Q(name__name='kernel-headers') | Q(name__name='kernel-default')
repo_packages = self.get_host_repo_packages()
host_packages = self.packages.exclude(kernels_q).distinct()
kernel_packages = self.packages.filter(kernels_q)
if self.host_repos_only:
update_ids = self.find_host_repo_updates(host_packages,
repo_packages)
else:
update_ids = self.find_osgroup_repo_updates(host_packages,
repo_packages)
kernel_update_ids = self.find_kernel_updates(kernel_packages,
repo_packages)
for ku_id in kernel_update_ids:
update_ids.append(ku_id)
for update in self.updates.all():
if update.id not in update_ids:
self.updates.remove(update)
def find_host_repo_updates(self, host_packages, repo_packages):
update_ids = []
hostrepos_q = Q(repo__mirror__enabled=True,
repo__mirror__repo__enabled=True, host=self)
hostrepos = HostRepo.objects.select_related().filter(hostrepos_q)
for package in host_packages:
highest_package = package
best_repo = find_best_repo(package, hostrepos)
priority = None
if best_repo is not None:
priority = best_repo.priority
# find the packages that are potential updates
pu_q = Q(name=package.name, arch=package.arch,
packagetype=package.packagetype)
potential_updates = repo_packages.filter(pu_q)
for potential_update in potential_updates:
if highest_package.compare_version(potential_update) == -1 \
and package.compare_version(potential_update) == -1:
if priority is not None:
# proceed only if the package is from a repo with a
# priority and that priority is >= the repo priority
pu_best_repo = find_best_repo(potential_update,
hostrepos)
pu_priority = pu_best_repo.priority
if pu_priority >= priority:
highest_package = potential_update
else:
highest_package = potential_update
if highest_package != package:
uid = self.process_update(package, highest_package)
if uid is not None:
update_ids.append(uid)
return update_ids
def find_osgroup_repo_updates(self, host_packages, repo_packages):
update_ids = []
for package in host_packages:
highest_package = package
# find the packages that are potential updates
pu_q = Q(name=package.name, arch=package.arch,
packagetype=package.packagetype)
potential_updates = repo_packages.filter(pu_q)
for potential_update in potential_updates:
if highest_package.compare_version(potential_update) == -1 \
and package.compare_version(potential_update) == -1:
highest_package = potential_update
if highest_package != package:
uid = self.process_update(package, highest_package)
if uid is not None:
update_ids.append(uid)
return update_ids
def check_if_reboot_required(self, host_highest):
to_strip = ['xen', '-xen', 'PAE', '-pae', '-default', 'vanilla', '-pv']
kernel = self.kernel
for s in to_strip:
if kernel.endswith(s):
kernel = kernel[:-len(s)]
ver, rel = kernel.rsplit('-')
kernel_ver = ('', str(ver), str(rel))
host_highest_ver = ('', host_highest.version, host_highest.release)
if labelCompare(kernel_ver, host_highest_ver) == -1:
self.reboot_required = True
else:
self.reboot_required = False
def find_kernel_updates(self, kernel_packages, repo_packages):
update_ids = []
for package in kernel_packages:
host_highest = package
repo_highest = package
pk_q = Q(name=package.name)
potential_updates = repo_packages.filter(pk_q)
for pu in potential_updates:
if package.compare_version(pu) == -1 \
and repo_highest.compare_version(pu) == -1:
repo_highest = pu
host_packages = self.packages.filter(pk_q)
for hp in host_packages:
if package.compare_version(hp) == -1 and \
host_highest.compare_version(hp) == -1:
host_highest = hp
if host_highest.compare_version(repo_highest) == -1:
uid = self.process_update(host_highest, repo_highest)
if uid is not None:
update_ids.append(uid)
self.check_if_reboot_required(host_highest)
try:
with transaction.atomic():
self.save()
except DatabaseError as e:
error_message.send(sender=None, text=e)
return update_ids
@python_2_unicode_compatible
class HostRepo(models.Model):
host = models.ForeignKey(Host, on_delete=models.CASCADE)
repo = models.ForeignKey(Repository, on_delete=models.CASCADE)
enabled = models.BooleanField(default=True)
priority = models.IntegerField(default=0)
class Meta(object):
unique_together = ('host', 'repo')
def __str__(self):
return '{0!s}-{1!s}'.format(self.host, self.repo) | 0.47098 | 0.089018 |
import math
import torch
import torch.nn as nn
from torch.nn import TransformerEncoder, TransformerEncoderLayer, Linear, TransformerDecoder, TransformerDecoderLayer
from torch.nn.modules.normalization import LayerNorm
from .model import Transformer_EncoderDecoder_Seq2Seq
from quaesita.PositionalEncoding import PositionalEncoding
torch.manual_seed(0)
class VanillaTransformerGenerator(nn.Module):
""" Implements Vanilla Trasnformer Generator.
The original Transformer Encoder-Decoder Model. The training process however differes
in our work. Refer utils.utils.* for training procedure. This work is derived from pytorch
implementation of Transformer Encoder-Decoder class. This is multi-step regression model.
Arguments:
model_params(dictionary): Refer example below -
seq2seq_model_params = { 'd_model': 512, 'nhead': 8,'dropout': 0.1,'num_of_enc_layers': 6,'num_of_dec_layers': 6,'input_sequence_length': 10,'forecasting_step': 2}
"""
def __init__(self, model_params):
super(VanillaTransformerGenerator, self).__init__()
self.model = Transformer_EncoderDecoder_Seq2Seq(**model_params)
def forward(self, src, tgt, tgt_mask):
output = model(src, tgt, tgt_mask)
return self.model
class SequenceCritic(nn.Module):
""" Implements Critic also can be referred as Discriminator.
Four Layer Multi Layer perceptron critic similar to original WGAN paper. https://arxiv.org/abs/1701.07875
Arguments:
model_params(dictionary): model dimensions as model parameters.
model_params = { 'd_model' : 512, 'activation_fn' : 'ReLU'/'LeakyReLU'/ 'tanh' / 'Swish' }
"""
def __init__(self, model_params):
super(SequenceCritic, self).__init__()
critic_model = nn.Sequential(
nn.Linear(1, model_params['d_model']),
nn.Tanh(),
# nn.LeakyReLU(0.2, inplace=True),
nn.Linear(model_params['d_model'], model_params['d_model'] * 2),
nn.Tanh(),
# nn.LeakyReLU(0.2, inplace=True),
nn.Linear(model_params['d_model'] * 2, 1),
nn.Tanh(),
# nn.Sigmoid(),
)
self.critic_model = critic_model
def forward(self, x):
output = self.critic_model(x)
return output | quaesita/transformerGANs.py | import math
import torch
import torch.nn as nn
from torch.nn import TransformerEncoder, TransformerEncoderLayer, Linear, TransformerDecoder, TransformerDecoderLayer
from torch.nn.modules.normalization import LayerNorm
from .model import Transformer_EncoderDecoder_Seq2Seq
from quaesita.PositionalEncoding import PositionalEncoding
torch.manual_seed(0)
class VanillaTransformerGenerator(nn.Module):
""" Implements Vanilla Trasnformer Generator.
The original Transformer Encoder-Decoder Model. The training process however differes
in our work. Refer utils.utils.* for training procedure. This work is derived from pytorch
implementation of Transformer Encoder-Decoder class. This is multi-step regression model.
Arguments:
model_params(dictionary): Refer example below -
seq2seq_model_params = { 'd_model': 512, 'nhead': 8,'dropout': 0.1,'num_of_enc_layers': 6,'num_of_dec_layers': 6,'input_sequence_length': 10,'forecasting_step': 2}
"""
def __init__(self, model_params):
super(VanillaTransformerGenerator, self).__init__()
self.model = Transformer_EncoderDecoder_Seq2Seq(**model_params)
def forward(self, src, tgt, tgt_mask):
output = model(src, tgt, tgt_mask)
return self.model
class SequenceCritic(nn.Module):
""" Implements Critic also can be referred as Discriminator.
Four Layer Multi Layer perceptron critic similar to original WGAN paper. https://arxiv.org/abs/1701.07875
Arguments:
model_params(dictionary): model dimensions as model parameters.
model_params = { 'd_model' : 512, 'activation_fn' : 'ReLU'/'LeakyReLU'/ 'tanh' / 'Swish' }
"""
def __init__(self, model_params):
super(SequenceCritic, self).__init__()
critic_model = nn.Sequential(
nn.Linear(1, model_params['d_model']),
nn.Tanh(),
# nn.LeakyReLU(0.2, inplace=True),
nn.Linear(model_params['d_model'], model_params['d_model'] * 2),
nn.Tanh(),
# nn.LeakyReLU(0.2, inplace=True),
nn.Linear(model_params['d_model'] * 2, 1),
nn.Tanh(),
# nn.Sigmoid(),
)
self.critic_model = critic_model
def forward(self, x):
output = self.critic_model(x)
return output | 0.934604 | 0.39129 |
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
('sites', '0002_alter_domain_unique'),
]
operations = [
migrations.CreateModel(
name='Attachment',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(help_text='Enter file name', max_length=200)),
('fpath', models.FileField(upload_to='uploads/%Y/%m/%d/')),
('date', models.DateTimeField(verbose_name='date published')),
],
),
migrations.CreateModel(
name='Author',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(help_text='Enter author name', max_length=200)),
('email', models.EmailField(help_text='Enter author email', max_length=200)),
('bio', models.CharField(help_text='Enter author bio', max_length=200)),
],
),
migrations.CreateModel(
name='Category',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(help_text='Enter Category name', max_length=200)),
('description', models.CharField(help_text='Enter Category description', max_length=200)),
],
options={
'verbose_name_plural': 'categories',
},
),
migrations.CreateModel(
name='Tag',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(help_text='Enter Tag name', max_length=200)),
('description', models.CharField(help_text='Enter Tag description', max_length=200)),
],
),
migrations.CreateModel(
name='Siteinfo',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(help_text='Enter site name', max_length=200)),
('title', models.CharField(help_text='Enter site title', max_length=200)),
('tagline', models.CharField(help_text='Enter site tagline', max_length=200)),
('description', models.CharField(help_text='Enter site description', max_length=200)),
('copyright', models.CharField(blank=True, help_text='Enter site copyright', max_length=200, null=True)),
('footer', models.CharField(blank=True, help_text='Enter site copyright footer', max_length=200, null=True)),
('domains', models.ManyToManyField(to='sites.Site')),
('owner', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='site_cms.Author')),
],
),
migrations.CreateModel(
name='Content',
fields=[
('id', models.UUIDField(default=uuid.uuid4, help_text='Unique ID for post', primary_key=True, serialize=False)),
('title', models.CharField(help_text='Enter taxonomy name', max_length=200)),
('ctype', models.IntegerField(choices=[(1, 'Blog'), (2, 'Page')], verbose_name='Content type')),
('body', models.TextField(help_text='Enter content here')),
('contentstatus', models.IntegerField(choices=[(1, 'Draft'), (2, 'Published')], verbose_name='Content status')),
('slug', models.SlugField(blank=True, help_text='Enter slug', max_length=250)),
('publishdate', models.DateTimeField(verbose_name='Publish date')),
('description', models.CharField(help_text='Enter taxonomy name', max_length=200)),
('image', models.ImageField(blank=True, null=True, upload_to='pageimage/%Y/%m/%d/')),
('attachments', models.ManyToManyField(blank=True, to='site_cms.Attachment')),
('author', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='site_cms.Author')),
('categories', models.ManyToManyField(blank=True, to='site_cms.Category')),
('siteinfo', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='site_cms.Siteinfo')),
('tags', models.ManyToManyField(blank=True, to='site_cms.Tag')),
],
options={
'ordering': ['-publishdate'],
},
),
] | site_cms/migrations/0001_initial.py |
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
('sites', '0002_alter_domain_unique'),
]
operations = [
migrations.CreateModel(
name='Attachment',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(help_text='Enter file name', max_length=200)),
('fpath', models.FileField(upload_to='uploads/%Y/%m/%d/')),
('date', models.DateTimeField(verbose_name='date published')),
],
),
migrations.CreateModel(
name='Author',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(help_text='Enter author name', max_length=200)),
('email', models.EmailField(help_text='Enter author email', max_length=200)),
('bio', models.CharField(help_text='Enter author bio', max_length=200)),
],
),
migrations.CreateModel(
name='Category',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(help_text='Enter Category name', max_length=200)),
('description', models.CharField(help_text='Enter Category description', max_length=200)),
],
options={
'verbose_name_plural': 'categories',
},
),
migrations.CreateModel(
name='Tag',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(help_text='Enter Tag name', max_length=200)),
('description', models.CharField(help_text='Enter Tag description', max_length=200)),
],
),
migrations.CreateModel(
name='Siteinfo',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(help_text='Enter site name', max_length=200)),
('title', models.CharField(help_text='Enter site title', max_length=200)),
('tagline', models.CharField(help_text='Enter site tagline', max_length=200)),
('description', models.CharField(help_text='Enter site description', max_length=200)),
('copyright', models.CharField(blank=True, help_text='Enter site copyright', max_length=200, null=True)),
('footer', models.CharField(blank=True, help_text='Enter site copyright footer', max_length=200, null=True)),
('domains', models.ManyToManyField(to='sites.Site')),
('owner', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='site_cms.Author')),
],
),
migrations.CreateModel(
name='Content',
fields=[
('id', models.UUIDField(default=uuid.uuid4, help_text='Unique ID for post', primary_key=True, serialize=False)),
('title', models.CharField(help_text='Enter taxonomy name', max_length=200)),
('ctype', models.IntegerField(choices=[(1, 'Blog'), (2, 'Page')], verbose_name='Content type')),
('body', models.TextField(help_text='Enter content here')),
('contentstatus', models.IntegerField(choices=[(1, 'Draft'), (2, 'Published')], verbose_name='Content status')),
('slug', models.SlugField(blank=True, help_text='Enter slug', max_length=250)),
('publishdate', models.DateTimeField(verbose_name='Publish date')),
('description', models.CharField(help_text='Enter taxonomy name', max_length=200)),
('image', models.ImageField(blank=True, null=True, upload_to='pageimage/%Y/%m/%d/')),
('attachments', models.ManyToManyField(blank=True, to='site_cms.Attachment')),
('author', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='site_cms.Author')),
('categories', models.ManyToManyField(blank=True, to='site_cms.Category')),
('siteinfo', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='site_cms.Siteinfo')),
('tags', models.ManyToManyField(blank=True, to='site_cms.Tag')),
],
options={
'ordering': ['-publishdate'],
},
),
] | 0.428951 | 0.118487 |
import os
from aim.engine.configs import *
def get_experiment_path(repo_path: str, experiment_name: str) -> str:
return os.path.join(repo_path, experiment_name)
def get_experiment_run_path(repo_path: str, experiment_name: str,
run_hash: str) -> str:
path = os.path.join(get_experiment_path(repo_path, experiment_name),
run_hash)
return path
def get_run_objects_dir_path(repo_path: str, experiment_name: str,
run_hash: str) -> str:
"""Returns path of `objects` directory of a run"""
path = os.path.join(repo_path,
experiment_name,
run_hash,
AIM_OBJECTS_DIR_NAME)
return path
def get_run_objects_meta_file_path(repo_path: str, experiment_name: str,
run_hash: str) -> str:
"""Returns path of `meta.json` file of a run"""
path = os.path.join(get_run_objects_dir_path(repo_path, experiment_name,
run_hash),
AIM_COMMIT_META_FILE_NAME)
return path
def cat_to_dir(cat):
"""
Finds file directory by it's category
"""
if cat[0] == 'metrics':
return AIM_METRICS_DIR_NAME
elif cat[0] == 'metric_groups':
return AIM_METRIC_GR_DIR_NAME
elif cat[0] == 'media':
if cat[1] == 'images':
return os.path.join(AIM_MEDIA_DIR_NAME, AIM_IMAGES_DIR_NAME)
elif cat[0] == 'misclassification':
return AIM_ANNOT_DIR_NAME
elif cat[0] == 'segmentation':
return AIM_SEG_DIR_NAME
elif cat[0] == 'models':
return AIM_MODELS_DIR_NAME
elif cat[0] == 'correlation':
return AIM_CORR_DIR_NAME
elif cat[0] == 'hyperparameters':
return AIM_PARAMS_DIR_NAME
elif cat[0] == 'map':
return AIM_MAP_DIR_NAME
elif cat[0] == 'stats':
return AIM_STATS_DIR_NAME
elif cat[0] == 'text':
return AIM_TEXT_DIR_NAME | aim/engine/repo/utils.py | import os
from aim.engine.configs import *
def get_experiment_path(repo_path: str, experiment_name: str) -> str:
return os.path.join(repo_path, experiment_name)
def get_experiment_run_path(repo_path: str, experiment_name: str,
run_hash: str) -> str:
path = os.path.join(get_experiment_path(repo_path, experiment_name),
run_hash)
return path
def get_run_objects_dir_path(repo_path: str, experiment_name: str,
run_hash: str) -> str:
"""Returns path of `objects` directory of a run"""
path = os.path.join(repo_path,
experiment_name,
run_hash,
AIM_OBJECTS_DIR_NAME)
return path
def get_run_objects_meta_file_path(repo_path: str, experiment_name: str,
run_hash: str) -> str:
"""Returns path of `meta.json` file of a run"""
path = os.path.join(get_run_objects_dir_path(repo_path, experiment_name,
run_hash),
AIM_COMMIT_META_FILE_NAME)
return path
def cat_to_dir(cat):
"""
Finds file directory by it's category
"""
if cat[0] == 'metrics':
return AIM_METRICS_DIR_NAME
elif cat[0] == 'metric_groups':
return AIM_METRIC_GR_DIR_NAME
elif cat[0] == 'media':
if cat[1] == 'images':
return os.path.join(AIM_MEDIA_DIR_NAME, AIM_IMAGES_DIR_NAME)
elif cat[0] == 'misclassification':
return AIM_ANNOT_DIR_NAME
elif cat[0] == 'segmentation':
return AIM_SEG_DIR_NAME
elif cat[0] == 'models':
return AIM_MODELS_DIR_NAME
elif cat[0] == 'correlation':
return AIM_CORR_DIR_NAME
elif cat[0] == 'hyperparameters':
return AIM_PARAMS_DIR_NAME
elif cat[0] == 'map':
return AIM_MAP_DIR_NAME
elif cat[0] == 'stats':
return AIM_STATS_DIR_NAME
elif cat[0] == 'text':
return AIM_TEXT_DIR_NAME | 0.533641 | 0.198316 |
import logging
import re
import subprocess
from dataclasses import dataclass
from enum import Enum
from pathlib import Path
from typing import Sequence
from datargs import arg, parse
class PdfEngines(Enum):
pdfroff = "pdfroff"
wkhtmltopdf = "wkhtmltopdf"
weasyprint = "weasyprint"
prince = "prince"
class OutputTypes(Enum):
pdf = "pdf"
html = "html"
LOGGER = logging.getLogger("convert_markdown.py")
THIS_DIRECTORY: Path = Path(__file__).parent
CONTENT_DIRECTORY: str = "content"
DEFAULT_CSS_FILE_PATH: Path = Path(THIS_DIRECTORY, "css/pandoc.css")
DEFAULT_DATA_DIRECTORY: Path = Path(THIS_DIRECTORY, "pandoc")
ERROR_CSS_INVALID: str = (
"Invalid CSS file. {} is not a valid file. Using default path {}."
)
PDF_ENGINE_MEMBERS = [member.value for member in PdfEngines]
HELP_PDF_ENGINE = [
"PDF rendering engine to use if --type is pdf.",
"Supported PDF rendering engines: {}".format(", ".join(PDF_ENGINE_MEMBERS)),
]
HELP_CSS_FILE = "Path to the css file to use for rendering. Default: {}".format(
DEFAULT_CSS_FILE_PATH
)
@dataclass
class Args:
files: Sequence[Path] = arg(
positional=True, help="A list of paths to markdown files."
)
output_directory: Path = arg(
default=Path(), help="Path to the output directory.", aliases=["-o"]
)
pdf_engine: PdfEngines = arg(
default=PdfEngines.weasyprint, help="\n".join(HELP_PDF_ENGINE), aliases=["-p"]
)
output_type: OutputTypes = arg(
default=OutputTypes.html,
help="Type of file to output, either html or pdf.",
aliases=["-t"],
)
css: Path = arg(default=DEFAULT_CSS_FILE_PATH, help=HELP_CSS_FILE, aliases=["-c"])
pandoc_data_directory: Path = arg(
default=DEFAULT_DATA_DIRECTORY,
help="Path to a data directory to use for pandoc.",
aliases=["-d"],
)
filters: Sequence[str] = arg(
default=(),
aliases=["-f"],
help="List of pandoc filters to run on each content file.",
)
def path_to_title(filepath: str) -> str:
title: str = Path(filepath).stem
title = re.sub(r"^\d*\.", "", title)
title = re.sub(r"[\-_\/\\]", " ", title)
return title
def get_output_path(args: Args, filepath: Path) -> Path:
"""Calculates and return the desired output file path."""
directory_name: str = filepath.parent.name
filename: str = filepath.stem
filename += ".{}".format(args.output_type.value)
return Path(args.output_directory, directory_name, filename)
def convert_markdown(args: Args, path: str) -> None:
"""Builds and runs a pandoc command to convert the input markdown document
`path` to the desired output format."""
title: str = path_to_title(path)
pandoc_command = [
"pandoc",
path.absolute().as_posix(),
"--self-contained",
"--css",
args.css.absolute().as_posix(),
"--metadata",
"pagetitle='{}'".format(title),
"--data-dir",
args.pandoc_data_directory.absolute().as_posix(),
]
if args.output_type == OutputTypes.pdf:
pandoc_command += ["--pdf-engine", args.pdf_engine]
if args.filters:
pandoc_command += ["--filter", *args.filters]
output_path: Path = get_output_path(args, path)
pandoc_command += ["--output", output_path.absolute().as_posix()]
# To use pandoc's built-in syntax highlighter. The theme still needs some work.
# PANDOC_DIRECTORY: Path = Path(THIS_DIRECTORY, "pandoc")
# pandoc_command += [
# "--syntax-definition",
# Path(PANDOC_DIRECTORY, "gd-script.xml").absolute().as_posix(),
# "--highlight-style",
# Path(PANDOC_DIRECTORY, "gdscript.theme").absolute().as_posix()
# ]
if not output_path.parent.exists():
output_path.parent.mkdir(parents=True)
out = subprocess.run(pandoc_command, capture_output=True, cwd=path.parent)
if out.returncode != 0:
print(out.stderr.decode())
raise Exception(out.stderr.decode())
def main():
args: Args = parse(Args)
for filepath in args.files:
convert_markdown(args, filepath)
if __name__ == "__main__":
main() | programs/scons/convert_markdown.py | import logging
import re
import subprocess
from dataclasses import dataclass
from enum import Enum
from pathlib import Path
from typing import Sequence
from datargs import arg, parse
class PdfEngines(Enum):
pdfroff = "pdfroff"
wkhtmltopdf = "wkhtmltopdf"
weasyprint = "weasyprint"
prince = "prince"
class OutputTypes(Enum):
pdf = "pdf"
html = "html"
LOGGER = logging.getLogger("convert_markdown.py")
THIS_DIRECTORY: Path = Path(__file__).parent
CONTENT_DIRECTORY: str = "content"
DEFAULT_CSS_FILE_PATH: Path = Path(THIS_DIRECTORY, "css/pandoc.css")
DEFAULT_DATA_DIRECTORY: Path = Path(THIS_DIRECTORY, "pandoc")
ERROR_CSS_INVALID: str = (
"Invalid CSS file. {} is not a valid file. Using default path {}."
)
PDF_ENGINE_MEMBERS = [member.value for member in PdfEngines]
HELP_PDF_ENGINE = [
"PDF rendering engine to use if --type is pdf.",
"Supported PDF rendering engines: {}".format(", ".join(PDF_ENGINE_MEMBERS)),
]
HELP_CSS_FILE = "Path to the css file to use for rendering. Default: {}".format(
DEFAULT_CSS_FILE_PATH
)
@dataclass
class Args:
files: Sequence[Path] = arg(
positional=True, help="A list of paths to markdown files."
)
output_directory: Path = arg(
default=Path(), help="Path to the output directory.", aliases=["-o"]
)
pdf_engine: PdfEngines = arg(
default=PdfEngines.weasyprint, help="\n".join(HELP_PDF_ENGINE), aliases=["-p"]
)
output_type: OutputTypes = arg(
default=OutputTypes.html,
help="Type of file to output, either html or pdf.",
aliases=["-t"],
)
css: Path = arg(default=DEFAULT_CSS_FILE_PATH, help=HELP_CSS_FILE, aliases=["-c"])
pandoc_data_directory: Path = arg(
default=DEFAULT_DATA_DIRECTORY,
help="Path to a data directory to use for pandoc.",
aliases=["-d"],
)
filters: Sequence[str] = arg(
default=(),
aliases=["-f"],
help="List of pandoc filters to run on each content file.",
)
def path_to_title(filepath: str) -> str:
title: str = Path(filepath).stem
title = re.sub(r"^\d*\.", "", title)
title = re.sub(r"[\-_\/\\]", " ", title)
return title
def get_output_path(args: Args, filepath: Path) -> Path:
"""Calculates and return the desired output file path."""
directory_name: str = filepath.parent.name
filename: str = filepath.stem
filename += ".{}".format(args.output_type.value)
return Path(args.output_directory, directory_name, filename)
def convert_markdown(args: Args, path: str) -> None:
"""Builds and runs a pandoc command to convert the input markdown document
`path` to the desired output format."""
title: str = path_to_title(path)
pandoc_command = [
"pandoc",
path.absolute().as_posix(),
"--self-contained",
"--css",
args.css.absolute().as_posix(),
"--metadata",
"pagetitle='{}'".format(title),
"--data-dir",
args.pandoc_data_directory.absolute().as_posix(),
]
if args.output_type == OutputTypes.pdf:
pandoc_command += ["--pdf-engine", args.pdf_engine]
if args.filters:
pandoc_command += ["--filter", *args.filters]
output_path: Path = get_output_path(args, path)
pandoc_command += ["--output", output_path.absolute().as_posix()]
# To use pandoc's built-in syntax highlighter. The theme still needs some work.
# PANDOC_DIRECTORY: Path = Path(THIS_DIRECTORY, "pandoc")
# pandoc_command += [
# "--syntax-definition",
# Path(PANDOC_DIRECTORY, "gd-script.xml").absolute().as_posix(),
# "--highlight-style",
# Path(PANDOC_DIRECTORY, "gdscript.theme").absolute().as_posix()
# ]
if not output_path.parent.exists():
output_path.parent.mkdir(parents=True)
out = subprocess.run(pandoc_command, capture_output=True, cwd=path.parent)
if out.returncode != 0:
print(out.stderr.decode())
raise Exception(out.stderr.decode())
def main():
args: Args = parse(Args)
for filepath in args.files:
convert_markdown(args, filepath)
if __name__ == "__main__":
main() | 0.753467 | 0.194081 |
from django.conf.urls import url, include
from django.contrib import admin
from django.contrib.auth.views import logout
from django.views.generic import TemplateView
from . import views
from django.conf import settings
from django.conf.urls.static import static
import accounts
handler400 = 'imglnx.views.handler400'
handler403 = 'imglnx.views.handler403'
handler404 = 'imglnx.views.handler404'
handler500 = 'imglnx.views.handler500'
urlpatterns = [
url(r'^$', TemplateView.as_view(template_name='home.html'), name='home'),
url(r'^kewlbeans/', admin.site.urls, name='admin'),
url(r'^blog/', include('blog.urls')),
url(r'^account/', include('accounts.urls')),
#url(r'^(?P<filename>[a-zA-Z0-9]+)$', views.ShareView.as_view(), name='share-image'),
url(r'^api/', include('api.urls'), name='api'),
url(r'^latest/?$', views.LatestImagesView.as_view(), name='latest-images'),
# album stuff
# url(r'^album/new/?$', views.NewAlbumView.as_view(), name='newalbum'),
url(r'^album/(?P<album_id>[a-zA-Z0-9]+)/?$', accounts.views.ViewAlbumView.as_view(), name='view_album'),
# auth urls here, because they're just redirects
url(r'^auth/login/?$', accounts.views.LoginUser.as_view(), name='login'),
url(r'^auth/register/?$', accounts.views.RegisterUser.as_view(), name='register'),
#url(r'^auth/forgot/?$', accounts.views.forgot_user.as_view(), name='forgot'),
#url(r'^auth/forgot/reset/?$', accounts.views.forgot_user_reset.as_view(), name='forgot-reset'),
url(r'^auth/logout/?$', logout, {'next_page': '/'}, name='logout'),
# pages
url(r'^page/faq/?$', TemplateView.as_view(template_name='faq.html'), name='faq'),
url(r'^page/about/?$', TemplateView.as_view(template_name='about.html'), name='about'),
url(r'^page/donate/?$', TemplateView.as_view(template_name='donate.html'), name='donate'),
url(r'^page/contact/?$', views.ContactView.as_view(), name='contact'),
url(r'^page/contact/thank-you/?$', TemplateView.as_view(template_name='misc/contact-thank-you.html'), name='contact-thanks'),
url(r'^page/changelog/?$', TemplateView.as_view(template_name='changelog.html'), name='changelog'),
url(r'^deleted-account/?$', TemplateView.as_view(template_name='misc/deleted-account.html'), name='deleted-account-thanks'),
# actions
url(r'^upload/?$', views.uploader, name='image-upload'),
url(r'^upload/url/?$', views.url_uploader, name='url-image-upload'),
url(r'^captcha/', include('captcha.urls')),
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += static(settings.ARCHIVES_URL, document_root=settings.ARCHIVES_ROOT)
urlpatterns += static(settings.THUMBNAIL_URL, document_root=settings.THUMBNAIL_ROOT) | imglnx/urls.py | from django.conf.urls import url, include
from django.contrib import admin
from django.contrib.auth.views import logout
from django.views.generic import TemplateView
from . import views
from django.conf import settings
from django.conf.urls.static import static
import accounts
handler400 = 'imglnx.views.handler400'
handler403 = 'imglnx.views.handler403'
handler404 = 'imglnx.views.handler404'
handler500 = 'imglnx.views.handler500'
urlpatterns = [
url(r'^$', TemplateView.as_view(template_name='home.html'), name='home'),
url(r'^kewlbeans/', admin.site.urls, name='admin'),
url(r'^blog/', include('blog.urls')),
url(r'^account/', include('accounts.urls')),
#url(r'^(?P<filename>[a-zA-Z0-9]+)$', views.ShareView.as_view(), name='share-image'),
url(r'^api/', include('api.urls'), name='api'),
url(r'^latest/?$', views.LatestImagesView.as_view(), name='latest-images'),
# album stuff
# url(r'^album/new/?$', views.NewAlbumView.as_view(), name='newalbum'),
url(r'^album/(?P<album_id>[a-zA-Z0-9]+)/?$', accounts.views.ViewAlbumView.as_view(), name='view_album'),
# auth urls here, because they're just redirects
url(r'^auth/login/?$', accounts.views.LoginUser.as_view(), name='login'),
url(r'^auth/register/?$', accounts.views.RegisterUser.as_view(), name='register'),
#url(r'^auth/forgot/?$', accounts.views.forgot_user.as_view(), name='forgot'),
#url(r'^auth/forgot/reset/?$', accounts.views.forgot_user_reset.as_view(), name='forgot-reset'),
url(r'^auth/logout/?$', logout, {'next_page': '/'}, name='logout'),
# pages
url(r'^page/faq/?$', TemplateView.as_view(template_name='faq.html'), name='faq'),
url(r'^page/about/?$', TemplateView.as_view(template_name='about.html'), name='about'),
url(r'^page/donate/?$', TemplateView.as_view(template_name='donate.html'), name='donate'),
url(r'^page/contact/?$', views.ContactView.as_view(), name='contact'),
url(r'^page/contact/thank-you/?$', TemplateView.as_view(template_name='misc/contact-thank-you.html'), name='contact-thanks'),
url(r'^page/changelog/?$', TemplateView.as_view(template_name='changelog.html'), name='changelog'),
url(r'^deleted-account/?$', TemplateView.as_view(template_name='misc/deleted-account.html'), name='deleted-account-thanks'),
# actions
url(r'^upload/?$', views.uploader, name='image-upload'),
url(r'^upload/url/?$', views.url_uploader, name='url-image-upload'),
url(r'^captcha/', include('captcha.urls')),
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += static(settings.ARCHIVES_URL, document_root=settings.ARCHIVES_ROOT)
urlpatterns += static(settings.THUMBNAIL_URL, document_root=settings.THUMBNAIL_ROOT) | 0.182863 | 0.045628 |
import os
import json
with open('/etc/config.json') as config_file:
config = json.load(config_file)
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = config['SECRET_KEY']
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['*']
#CSRF_COOKIE_SECURE = True
#SESSION_COOKIE_SECURE = True
# Application definition
INSTALLED_APPS = [
'foodieshoot.apps.FoodieshootConfig',
'users.apps.UsersConfig',
'api.apps.ApiConfig',
'rest_framework',
'rest_framework.authtoken',
'rest_auth',
'crispy_forms',
'django_cleanup',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
#Google sign in
# 'social_django',
#'allauth',
#'allauth.account',
#'allauth.socialaccount',
#'allauth.socialaccount.providers.google',
#Allow use of single codebase with different databases
#'django.contrib.sites',
]
#Tell django to use the first site/db as a default site
#SITE_ID = 1
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication', # <-- And here
],
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.AllowAny',
]
}
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'foodieshoot_api.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'foodieshoot_api.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
CRISPY_TEMPLATE_PACK = 'bootstrap4'
STATIC_ROOT = os.path.join(BASE_DIR,'static')
STATIC_URL = '/static/'
STATICFILES_DIR = [
os.path.join(BASE_DIR,'static/'),
os.path.join(BASE_DIR,'foodieshoot/static/'),
os.path.join(BASE_DIR,'users/static/'),
]
MEDIA_ROOT = os.path.join(BASE_DIR,'media')
MEDIA_URL = '/media/'
LOGIN_REDIRECT_URL = 'fs-home'
LOGIN_URL = 'fs-signin'
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_USE_SSL = False
EMAIL_USE_TLS = True
EMAIL_PORT = 587
EMAIL_HOST_USER = config.get('EMAIL_USER')
EMAIL_HOST_PASSWORD = config.get('EMAIL_PASS')
#Add django allauth backend
#AUTHENTICATION_BACKENDS = (
# 'social_core.backends.google.GoogleOAuth2',
#Needed to login by username in Django admin, regardless of 'allauth'
# 'django.contrib.auth.backends.ModelBackend',
#'allauth' specific authentication methods, such as login by e-mail
# 'allauth.account.auth_backends.AuthenticationBackend'
#) | Backend/foodieshoot_api/foodieshoot_api/settings.py | import os
import json
with open('/etc/config.json') as config_file:
config = json.load(config_file)
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = config['SECRET_KEY']
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['*']
#CSRF_COOKIE_SECURE = True
#SESSION_COOKIE_SECURE = True
# Application definition
INSTALLED_APPS = [
'foodieshoot.apps.FoodieshootConfig',
'users.apps.UsersConfig',
'api.apps.ApiConfig',
'rest_framework',
'rest_framework.authtoken',
'rest_auth',
'crispy_forms',
'django_cleanup',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
#Google sign in
# 'social_django',
#'allauth',
#'allauth.account',
#'allauth.socialaccount',
#'allauth.socialaccount.providers.google',
#Allow use of single codebase with different databases
#'django.contrib.sites',
]
#Tell django to use the first site/db as a default site
#SITE_ID = 1
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication', # <-- And here
],
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.AllowAny',
]
}
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'foodieshoot_api.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'foodieshoot_api.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
CRISPY_TEMPLATE_PACK = 'bootstrap4'
STATIC_ROOT = os.path.join(BASE_DIR,'static')
STATIC_URL = '/static/'
STATICFILES_DIR = [
os.path.join(BASE_DIR,'static/'),
os.path.join(BASE_DIR,'foodieshoot/static/'),
os.path.join(BASE_DIR,'users/static/'),
]
MEDIA_ROOT = os.path.join(BASE_DIR,'media')
MEDIA_URL = '/media/'
LOGIN_REDIRECT_URL = 'fs-home'
LOGIN_URL = 'fs-signin'
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_USE_SSL = False
EMAIL_USE_TLS = True
EMAIL_PORT = 587
EMAIL_HOST_USER = config.get('EMAIL_USER')
EMAIL_HOST_PASSWORD = config.get('EMAIL_PASS')
#Add django allauth backend
#AUTHENTICATION_BACKENDS = (
# 'social_core.backends.google.GoogleOAuth2',
#Needed to login by username in Django admin, regardless of 'allauth'
# 'django.contrib.auth.backends.ModelBackend',
#'allauth' specific authentication methods, such as login by e-mail
# 'allauth.account.auth_backends.AuthenticationBackend'
#) | 0.293404 | 0.077274 |
response = {
"result": {
"result": {
"order0": {
"ID": "35943",
"TITLE": "7-я Кожуховская ул., 4К1: 104%, 3.6, эт. 12/16, 10.5 -> 16.3 (от собственника)",
"HONORIFIC": None,
"NAME": None,
"SECOND_NAME": None,
"LAST_NAME": None,
"COMPANY_TITLE": None,
"COMPANY_ID": None,
"CONTACT_ID": None,
"IS_RETURN_CUSTOMER": "N",
"BIRTHDATE": "",
"SOURCE_ID": None,
"SOURCE_DESCRIPTION": None,
"STATUS_ID": "3",
"STATUS_DESCRIPTION": None,
"POST": None,
"COMMENTS": None,
"CURRENCY_ID": "RUB",
"OPPORTUNITY": "3607999.00",
"IS_MANUAL_OPPORTUNITY": "N",
"HAS_PHONE": "N",
"HAS_EMAIL": "N",
"HAS_IMOL": "N",
"ASSIGNED_BY_ID": "19",
"CREATED_BY_ID": "1",
"MODIFY_BY_ID": "19",
"DATE_CREATE": "2022-05-21T12:00:12+03:00",
"DATE_MODIFY": "2022-05-22T13:11:57+03:00",
"DATE_CLOSED": "",
"STATUS_SEMANTIC_ID": "P",
"OPENED": "N",
"ORIGINATOR_ID": None,
"ORIGIN_ID": None,
"MOVED_BY_ID": "19",
"MOVED_TIME": "2022-05-22T13:11:57+03:00",
"ADDRESS": None,
"ADDRESS_2": None,
"ADDRESS_CITY": None,
"ADDRESS_POSTAL_CODE": None,
"ADDRESS_REGION": None,
"ADDRESS_PROVINCE": None,
"ADDRESS_COUNTRY": None,
"ADDRESS_COUNTRY_CODE": None,
"ADDRESS_LOC_ADDR_ID": None,
"UTM_SOURCE": None,
"UTM_MEDIUM": None,
"UTM_CAMPAIGN": None,
"UTM_CONTENT": None,
"UTM_TERM": None,
}
},
"result_error": [],
"result_total": [],
"result_next": [],
"result_time": {
"order0": {
"start": 1653240482.052486,
"finish": 1653240482.083635,
"duration": 0.03114914894104004,
"processing": 0.031054973602294922,
"date_start": "2022-05-22T20:28:02+03:00",
"date_finish": "2022-05-22T20:28:02+03:00",
"operating": 1.7768540382385254,
}
},
},
"time": {
"start": 1653240482.013116,
"finish": 1653240482.083662,
"duration": 0.07054615020751953,
"processing": 0.03124380111694336,
"date_start": "2022-05-22T20:28:02+03:00",
"date_finish": "2022-05-22T20:28:02+03:00",
"operating": 1.7768540382385254,
},
} | tests/real_responses/call_single_success.py | response = {
"result": {
"result": {
"order0": {
"ID": "35943",
"TITLE": "7-я Кожуховская ул., 4К1: 104%, 3.6, эт. 12/16, 10.5 -> 16.3 (от собственника)",
"HONORIFIC": None,
"NAME": None,
"SECOND_NAME": None,
"LAST_NAME": None,
"COMPANY_TITLE": None,
"COMPANY_ID": None,
"CONTACT_ID": None,
"IS_RETURN_CUSTOMER": "N",
"BIRTHDATE": "",
"SOURCE_ID": None,
"SOURCE_DESCRIPTION": None,
"STATUS_ID": "3",
"STATUS_DESCRIPTION": None,
"POST": None,
"COMMENTS": None,
"CURRENCY_ID": "RUB",
"OPPORTUNITY": "3607999.00",
"IS_MANUAL_OPPORTUNITY": "N",
"HAS_PHONE": "N",
"HAS_EMAIL": "N",
"HAS_IMOL": "N",
"ASSIGNED_BY_ID": "19",
"CREATED_BY_ID": "1",
"MODIFY_BY_ID": "19",
"DATE_CREATE": "2022-05-21T12:00:12+03:00",
"DATE_MODIFY": "2022-05-22T13:11:57+03:00",
"DATE_CLOSED": "",
"STATUS_SEMANTIC_ID": "P",
"OPENED": "N",
"ORIGINATOR_ID": None,
"ORIGIN_ID": None,
"MOVED_BY_ID": "19",
"MOVED_TIME": "2022-05-22T13:11:57+03:00",
"ADDRESS": None,
"ADDRESS_2": None,
"ADDRESS_CITY": None,
"ADDRESS_POSTAL_CODE": None,
"ADDRESS_REGION": None,
"ADDRESS_PROVINCE": None,
"ADDRESS_COUNTRY": None,
"ADDRESS_COUNTRY_CODE": None,
"ADDRESS_LOC_ADDR_ID": None,
"UTM_SOURCE": None,
"UTM_MEDIUM": None,
"UTM_CAMPAIGN": None,
"UTM_CONTENT": None,
"UTM_TERM": None,
}
},
"result_error": [],
"result_total": [],
"result_next": [],
"result_time": {
"order0": {
"start": 1653240482.052486,
"finish": 1653240482.083635,
"duration": 0.03114914894104004,
"processing": 0.031054973602294922,
"date_start": "2022-05-22T20:28:02+03:00",
"date_finish": "2022-05-22T20:28:02+03:00",
"operating": 1.7768540382385254,
}
},
},
"time": {
"start": 1653240482.013116,
"finish": 1653240482.083662,
"duration": 0.07054615020751953,
"processing": 0.03124380111694336,
"date_start": "2022-05-22T20:28:02+03:00",
"date_finish": "2022-05-22T20:28:02+03:00",
"operating": 1.7768540382385254,
},
} | 0.363873 | 0.308906 |
from django.db.models.query import QuerySet
from wagtail.wagtailsearch.backends.elasticsearch import ElasticsearchSearchBackend, ElasticsearchSearchQuery
from wagtail.wagtailsearch.index import class_is_indexed
class CustomElasticsearchSearchQuery(ElasticsearchSearchQuery):
def __init__(self, queryset, query_string, fields=None, operator=None, order_by_relevance=True,
extra_raw_filters=None):
super(CustomElasticsearchSearchQuery, self).__init__(queryset, query_string, fields, operator, order_by_relevance)
self.extra_raw_filters = extra_raw_filters
def get_filters(self):
filters = []
# Filter by content type
filters.append({
'prefix': {
'content_type': self.queryset.model.indexed_get_content_type()
}
})
# Apply filters from queryset
queryset_filters = self._get_filters_from_queryset()
if queryset_filters:
filters.append(queryset_filters)
if self.extra_raw_filters:
filters.extend(self.extra_raw_filters)
return filters
class CustomElasticsearchSearchBackend(ElasticsearchSearchBackend):
query_class = CustomElasticsearchSearchQuery
def __init__(self, params):
super(CustomElasticsearchSearchBackend, self).__init__(params)
def search(self, query_string, model_or_queryset, fields=None, filters=None,
prefetch_related=None, operator=None, order_by_relevance=True, extra_raw_filters=None):
# Find model/queryset
if isinstance(model_or_queryset, QuerySet):
model = model_or_queryset.model
queryset = model_or_queryset
else:
model = model_or_queryset
queryset = model_or_queryset.objects.all()
# Model must be a class that is in the index
if not class_is_indexed(model):
return []
# Check that theres still a query string after the clean up
if query_string == "":
return []
# Apply filters to queryset
if filters:
queryset = queryset.filter(**filters)
# Prefetch related
if prefetch_related:
for prefetch in prefetch_related:
queryset = queryset.prefetch_related(prefetch)
# Check operator
if operator is not None:
operator = operator.lower()
if operator not in ['or', 'and']:
raise ValueError("operator must be either 'or' or 'and'")
# Search
search_query = self.query_class(
queryset, query_string, fields=fields, operator=operator,
order_by_relevance=order_by_relevance, extra_raw_filters=extra_raw_filters
)
return self.results_class(self, search_query) | search/custom_elasticsearch.py | from django.db.models.query import QuerySet
from wagtail.wagtailsearch.backends.elasticsearch import ElasticsearchSearchBackend, ElasticsearchSearchQuery
from wagtail.wagtailsearch.index import class_is_indexed
class CustomElasticsearchSearchQuery(ElasticsearchSearchQuery):
def __init__(self, queryset, query_string, fields=None, operator=None, order_by_relevance=True,
extra_raw_filters=None):
super(CustomElasticsearchSearchQuery, self).__init__(queryset, query_string, fields, operator, order_by_relevance)
self.extra_raw_filters = extra_raw_filters
def get_filters(self):
filters = []
# Filter by content type
filters.append({
'prefix': {
'content_type': self.queryset.model.indexed_get_content_type()
}
})
# Apply filters from queryset
queryset_filters = self._get_filters_from_queryset()
if queryset_filters:
filters.append(queryset_filters)
if self.extra_raw_filters:
filters.extend(self.extra_raw_filters)
return filters
class CustomElasticsearchSearchBackend(ElasticsearchSearchBackend):
query_class = CustomElasticsearchSearchQuery
def __init__(self, params):
super(CustomElasticsearchSearchBackend, self).__init__(params)
def search(self, query_string, model_or_queryset, fields=None, filters=None,
prefetch_related=None, operator=None, order_by_relevance=True, extra_raw_filters=None):
# Find model/queryset
if isinstance(model_or_queryset, QuerySet):
model = model_or_queryset.model
queryset = model_or_queryset
else:
model = model_or_queryset
queryset = model_or_queryset.objects.all()
# Model must be a class that is in the index
if not class_is_indexed(model):
return []
# Check that theres still a query string after the clean up
if query_string == "":
return []
# Apply filters to queryset
if filters:
queryset = queryset.filter(**filters)
# Prefetch related
if prefetch_related:
for prefetch in prefetch_related:
queryset = queryset.prefetch_related(prefetch)
# Check operator
if operator is not None:
operator = operator.lower()
if operator not in ['or', 'and']:
raise ValueError("operator must be either 'or' or 'and'")
# Search
search_query = self.query_class(
queryset, query_string, fields=fields, operator=operator,
order_by_relevance=order_by_relevance, extra_raw_filters=extra_raw_filters
)
return self.results_class(self, search_query) | 0.756447 | 0.159381 |
from __future__ import print_function
import os
import ast
from . import utils
def get_toplevel_imports(module):
"""Get the imports at the top-level of the given Python module.
:param module: An actual module; not the name.
:returns list: The absolute names of everything imported,
"""
path = utils.get_source_path(module)
if path is None:
return []
return parse_imports(
open(path).read(),
getattr(module, '__package__'),
getattr(module, '__name__'),
path=path,
)
def parse_imports(source, package=None, module=None, path=None, toplevel=True):
"""Get the imports at the top-level of the given Python module.
:param str source: Python source code.
:param str package: The ``__package__`` this source is from.
:param str module: The ``__name__`` this source is from.
:param bool toplevel: Walk the full AST, or only look at the top-level?
:returns list: The names of everything imported; absolute if package
and module are provided.
"""
names = []
try:
# Discard all trailing whitespace to avoid syntax errors due to
# too much white in the last line.
mod_ast = ast.parse(source.rstrip())
except (TypeError, SyntaxError) as e:
print('# %s: %s in %s: %s' % (__name__, e.__class__.__name__, path, e))
return []
for node in ast.walk(mod_ast) if not toplevel else mod_ast.body:
if isinstance(node, ast.Import):
names.extend(alias.name for alias in node.names)
elif isinstance(node, ast.ImportFrom):
base = '.' * node.level + (node.module or '')
names.append(base)
if node.module:
base += '.'
names.extend(base + alias.name for alias in node.names)
if package is not None and module is not None:
names = [utils.resolve_relative_name(package, module, name) for name in names]
return names
def path_is_in_directories(path, directories):
"""Is the given path within the given directory?
:param str path: The path to test.
:param str directory: The directory to test if the path is in.
:returns bool:
"""
a = [x for x in os.path.abspath(path)[1:].split('/') if x]
bs = [[y for y in os.path.abspath(x)[1:].split('/') if y] for x in directories]
return any(a[:len(b)] == b for b in bs) | metatools/imports/discovery.py | from __future__ import print_function
import os
import ast
from . import utils
def get_toplevel_imports(module):
"""Get the imports at the top-level of the given Python module.
:param module: An actual module; not the name.
:returns list: The absolute names of everything imported,
"""
path = utils.get_source_path(module)
if path is None:
return []
return parse_imports(
open(path).read(),
getattr(module, '__package__'),
getattr(module, '__name__'),
path=path,
)
def parse_imports(source, package=None, module=None, path=None, toplevel=True):
"""Get the imports at the top-level of the given Python module.
:param str source: Python source code.
:param str package: The ``__package__`` this source is from.
:param str module: The ``__name__`` this source is from.
:param bool toplevel: Walk the full AST, or only look at the top-level?
:returns list: The names of everything imported; absolute if package
and module are provided.
"""
names = []
try:
# Discard all trailing whitespace to avoid syntax errors due to
# too much white in the last line.
mod_ast = ast.parse(source.rstrip())
except (TypeError, SyntaxError) as e:
print('# %s: %s in %s: %s' % (__name__, e.__class__.__name__, path, e))
return []
for node in ast.walk(mod_ast) if not toplevel else mod_ast.body:
if isinstance(node, ast.Import):
names.extend(alias.name for alias in node.names)
elif isinstance(node, ast.ImportFrom):
base = '.' * node.level + (node.module or '')
names.append(base)
if node.module:
base += '.'
names.extend(base + alias.name for alias in node.names)
if package is not None and module is not None:
names = [utils.resolve_relative_name(package, module, name) for name in names]
return names
def path_is_in_directories(path, directories):
"""Is the given path within the given directory?
:param str path: The path to test.
:param str directory: The directory to test if the path is in.
:returns bool:
"""
a = [x for x in os.path.abspath(path)[1:].split('/') if x]
bs = [[y for y in os.path.abspath(x)[1:].split('/') if y] for x in directories]
return any(a[:len(b)] == b for b in bs) | 0.622115 | 0.238961 |
import logging
import tunnel_ctl_service.linode_util as linode_util
import paramiko
log = logging.getLogger("module:" + __name__)
# ssh commands
# databases
is_mysql_installed = "dpkg-query -f '${Status} @@ ${binary:Package}\n' -W | grep -v '^deinstall ok config-files @@ ' | grep '^.* @@ mysql-server$' > /dev/null"
install_mysql = "DEBIAN_FRONTEND=noninteractive apt-get install -y mysql-server"
uninstall_mysql = "DEBIAN_FRONTEND=noninteractive apt-get remove -y mysql-server"
def install_database(d):
database = d.installation.database if d.installation else None
if database == None:
# removing all databases
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(d.ip_address, username = "root", password = d.server.login.password)
# getting installation info
if exec_ssh_rc(ssh, is_mysql_installed) == 0:
# mysql is installed
log.info("linode %i: uninstalling MySQL server" % d.linode_id)
exec_ssh_rc(ssh, uninstall_mysql)
else:
log.info("linode %i: MySQL server is not installed, cannot remove" % d.linode_id)
ssh.close()
elif database.provider == "mysql":
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(d.ip_address, username = "root", password = d.server.login.password)
# getting installation info
if exec_ssh_rc(ssh, is_mysql_installed) != 0:
# no mysql installed
log.info("linode %i: installing MySQL server" % d.linode_id)
exec_ssh_rc(ssh, install_mysql)
# setting up root password
exec_ssh_rc(ssh, "mysqladmin -u root password %s" % database.password)
else:
log.info("linode %i: MySQL server is already installed" % d.linode_id)
ssh.close()
else:
raise RuntimeError("unsupported database: %s, cannot handle" % database.provider)
def handle_path_change(config, key, old_value, new_value):
install_database(config)
linode_util.register_path_change("installation.database", handle_path_change)
def exec_ssh_rc(ssh, cmd):
stdin, stdout, stderr = ssh.exec_command(cmd)
return stdout.channel.recv_exit_status() | tunnel_ctl_service/modules/debian_mysql.py |
import logging
import tunnel_ctl_service.linode_util as linode_util
import paramiko
log = logging.getLogger("module:" + __name__)
# ssh commands
# databases
is_mysql_installed = "dpkg-query -f '${Status} @@ ${binary:Package}\n' -W | grep -v '^deinstall ok config-files @@ ' | grep '^.* @@ mysql-server$' > /dev/null"
install_mysql = "DEBIAN_FRONTEND=noninteractive apt-get install -y mysql-server"
uninstall_mysql = "DEBIAN_FRONTEND=noninteractive apt-get remove -y mysql-server"
def install_database(d):
database = d.installation.database if d.installation else None
if database == None:
# removing all databases
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(d.ip_address, username = "root", password = d.server.login.password)
# getting installation info
if exec_ssh_rc(ssh, is_mysql_installed) == 0:
# mysql is installed
log.info("linode %i: uninstalling MySQL server" % d.linode_id)
exec_ssh_rc(ssh, uninstall_mysql)
else:
log.info("linode %i: MySQL server is not installed, cannot remove" % d.linode_id)
ssh.close()
elif database.provider == "mysql":
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(d.ip_address, username = "root", password = d.server.login.password)
# getting installation info
if exec_ssh_rc(ssh, is_mysql_installed) != 0:
# no mysql installed
log.info("linode %i: installing MySQL server" % d.linode_id)
exec_ssh_rc(ssh, install_mysql)
# setting up root password
exec_ssh_rc(ssh, "mysqladmin -u root password %s" % database.password)
else:
log.info("linode %i: MySQL server is already installed" % d.linode_id)
ssh.close()
else:
raise RuntimeError("unsupported database: %s, cannot handle" % database.provider)
def handle_path_change(config, key, old_value, new_value):
install_database(config)
linode_util.register_path_change("installation.database", handle_path_change)
def exec_ssh_rc(ssh, cmd):
stdin, stdout, stderr = ssh.exec_command(cmd)
return stdout.channel.recv_exit_status() | 0.205814 | 0.048406 |
import re
import random
from apiclient.discovery import build
from apiclient.errors import HttpError
def youtube_search(q):
# TODO: insert developer key
youtube = build("youtube", "v3", developerKey="")
# call the search.list method
search_response = youtube.search().list(
q=q,
part="id,snippet",
maxResults=5,
videoDuration="short",
type="video",
safeSearch="moderate"
).execute()
ret = []
for search_result in search_response.get("items", []):
# only fetch videos
if search_result["id"]["kind"] != "youtube#video":
continue
# append to videos
ret.append((search_result["snippet"]["title"], search_result["id"]["videoId"]))
return ret
# parameters
label_file = "resources/labels.txt"
# videos to download
to_download = 500
# load labels
with open(label_file) as f:
# regular exploression from removing ID from the beginning
strip_id = re.compile(r"^n\d+ ")
# extract all labels (remove ID from beginning, trip new line character and split words)
labels = [x for l in f.readlines() for x in strip_id.sub("", l).strip().split(", ")]
# run until download is full
download_list = []
while len(download_list) < to_download:
# make query
query_terms = random.choice(labels)
if 0.5 < random.random(): # use two labels half the time
query_terms += " " + random.choice(labels)
# run query
try:
videos = youtube_search(query_terms)
except HttpError, e:
print "An HTTP error %d occurred:\n%s" % (e.resp.status, e.content)
break
# select two files to download
for (title, video_id) in videos[0:2]:
# print "Download: %s" % title
download_list.append("http://youtube.com/watch?v=%s" % video_id)
# print download list
for download in download_list:
print download
# to download, use something like `youtube-dl` | find_videos.py | import re
import random
from apiclient.discovery import build
from apiclient.errors import HttpError
def youtube_search(q):
# TODO: insert developer key
youtube = build("youtube", "v3", developerKey="")
# call the search.list method
search_response = youtube.search().list(
q=q,
part="id,snippet",
maxResults=5,
videoDuration="short",
type="video",
safeSearch="moderate"
).execute()
ret = []
for search_result in search_response.get("items", []):
# only fetch videos
if search_result["id"]["kind"] != "youtube#video":
continue
# append to videos
ret.append((search_result["snippet"]["title"], search_result["id"]["videoId"]))
return ret
# parameters
label_file = "resources/labels.txt"
# videos to download
to_download = 500
# load labels
with open(label_file) as f:
# regular exploression from removing ID from the beginning
strip_id = re.compile(r"^n\d+ ")
# extract all labels (remove ID from beginning, trip new line character and split words)
labels = [x for l in f.readlines() for x in strip_id.sub("", l).strip().split(", ")]
# run until download is full
download_list = []
while len(download_list) < to_download:
# make query
query_terms = random.choice(labels)
if 0.5 < random.random(): # use two labels half the time
query_terms += " " + random.choice(labels)
# run query
try:
videos = youtube_search(query_terms)
except HttpError, e:
print "An HTTP error %d occurred:\n%s" % (e.resp.status, e.content)
break
# select two files to download
for (title, video_id) in videos[0:2]:
# print "Download: %s" % title
download_list.append("http://youtube.com/watch?v=%s" % video_id)
# print download list
for download in download_list:
print download
# to download, use something like `youtube-dl` | 0.134264 | 0.201283 |
import sys
from glados.es.ws2es.es_util import DefaultMappings
from glados.es.ws2es.denormalization import DenormalizationHandler
from glados.es.ws2es.util import SummableDict
from glados.es.ws2es.denormalization.assay_handler import AssayDenormalizationHandler
from glados.es.ws2es.denormalization.compound_handler import CompoundDenormalizationHandler
from glados.es.ws2es.denormalization.compound_record_handler import CompoundRecordDenormalizationHandler
from glados.es.ws2es.denormalization.document_handler import DocumentDenormalizationHandler
from glados.es.ws2es.denormalization.organism_handler import OrganismDenormalizationHandler
from glados.es.ws2es.denormalization.source_handler import SourceDenormalizationHandler
from glados.es.ws2es.denormalization.target_component_handler import TargetComponentDenormalizationHandler
from glados.es.ws2es.denormalization.target_handler import TargetDenormalizationHandler
from glados.es.ws2es.denormalization.protein_class_handler import ProteinClassDenormalizationHandler
from glados.es.ws2es.progress_bar_handler import get_new_progressbar
class ActivityDenormalizationHandler(DenormalizationHandler):
RESOURCE = DenormalizationHandler.AVAILABLE_RESOURCES.ACTIVITY
def __init__(self, complete_from_activity: bool=False, assay_dh: AssayDenormalizationHandler=None,
compound_dh: CompoundDenormalizationHandler=None, organism_dh: OrganismDenormalizationHandler=None,
source_dh: SourceDenormalizationHandler=None, target_dh: TargetDenormalizationHandler=None,
target_component_dh: TargetComponentDenormalizationHandler=None,
compound_record_dh: CompoundRecordDenormalizationHandler=None,
document_dh: DocumentDenormalizationHandler=None):
super().__init__(complete_from_activity or
assay_dh is not None or
compound_dh is not None or
organism_dh is not None or
source_dh is not None or
target_dh is not None or
target_component_dh is not None or
compound_record_dh is not None or
document_dh is not None)
self.assay_dh = assay_dh
self.compound_dh = compound_dh
self.organism_dh = organism_dh
self.source_dh = source_dh
self.target_dh = target_dh
self.target_component_dh = target_component_dh
self.compound_record_dh = compound_record_dh
self.document_dh = document_dh
self.assay_dict = {}
self.compound_dict = {}
self.document_dict = {}
self.target_dict = {}
self.compound_2_assay = {}
self.assay_2_compound = {}
def handle_doc(self, doc: dict, total_docs: int, index: int, first: bool, last: bool):
self.collect_data(doc, self.assay_dict, 'assay_chembl_id', [
self.DENORMALIZATION_CONFIGURATIONS[self.AVAILABLE_RESOURCES.ACTIVITY],
self.DENORMALIZATION_CONFIGURATIONS[self.AVAILABLE_RESOURCES.DOCUMENT],
self.DENORMALIZATION_CONFIGURATIONS[self.AVAILABLE_RESOURCES.MOLECULE],
self.DENORMALIZATION_CONFIGURATIONS[self.AVAILABLE_RESOURCES.TARGET],
]
)
self.collect_data(doc, self.document_dict, 'document_chembl_id', [
self.DENORMALIZATION_CONFIGURATIONS[self.AVAILABLE_RESOURCES.ACTIVITY],
self.DENORMALIZATION_CONFIGURATIONS[self.AVAILABLE_RESOURCES.ASSAY],
self.DENORMALIZATION_CONFIGURATIONS[self.AVAILABLE_RESOURCES.MOLECULE],
self.DENORMALIZATION_CONFIGURATIONS[self.AVAILABLE_RESOURCES.TARGET],
]
)
self.collect_data(doc, self.compound_dict, 'molecule_chembl_id', [
self.DENORMALIZATION_CONFIGURATIONS[self.AVAILABLE_RESOURCES.ACTIVITY],
self.DENORMALIZATION_CONFIGURATIONS[self.AVAILABLE_RESOURCES.ASSAY],
self.DENORMALIZATION_CONFIGURATIONS[self.AVAILABLE_RESOURCES.DOCUMENT],
self.DENORMALIZATION_CONFIGURATIONS[self.AVAILABLE_RESOURCES.TARGET],
]
)
self.collect_data(doc, self.target_dict, 'target_chembl_id', [
self.DENORMALIZATION_CONFIGURATIONS[self.AVAILABLE_RESOURCES.ACTIVITY],
self.DENORMALIZATION_CONFIGURATIONS[self.AVAILABLE_RESOURCES.ASSAY],
self.DENORMALIZATION_CONFIGURATIONS[self.AVAILABLE_RESOURCES.DOCUMENT],
self.DENORMALIZATION_CONFIGURATIONS[self.AVAILABLE_RESOURCES.MOLECULE],
]
)
if doc['molecule_chembl_id'] not in self.compound_2_assay:
self.compound_2_assay[doc['molecule_chembl_id']] = set()
self.compound_2_assay[doc['molecule_chembl_id']].add(doc['assay_chembl_id'])
if doc['assay_chembl_id'] not in self.assay_2_compound:
self.assay_2_compound[doc['assay_chembl_id']] = set()
self.assay_2_compound[doc['assay_chembl_id']].add(doc['molecule_chembl_id'])
def save_denormalization(self):
self.submit_docs_collected_data(self.assay_dict,
DenormalizationHandler.AVAILABLE_RESOURCES.ASSAY)
self.submit_docs_collected_data(self.compound_dict,
DenormalizationHandler.AVAILABLE_RESOURCES.MOLECULE)
self.submit_docs_collected_data(self.document_dict,
DenormalizationHandler.AVAILABLE_RESOURCES.DOCUMENT)
self.submit_docs_collected_data(self.target_dict,
DenormalizationHandler.AVAILABLE_RESOURCES.TARGET)
def get_custom_mappings_for_complete_data(self):
mappings = SummableDict()
mappings += AssayDenormalizationHandler.ACTIVITY_DATA_MAPPING
mappings += CompoundDenormalizationHandler.ACTIVITY_DATA_MAPPING
mappings += SourceDenormalizationHandler.METADATA_MAPPING
mappings += OrganismDenormalizationHandler.METADATA_MAPPING
mappings += CompoundRecordDenormalizationHandler.ACTIVITY_DATA_MAPPING
mappings += TargetDenormalizationHandler.ACTIVITY_DATA_MAPPING
mappings += ProteinClassDenormalizationHandler.METADATA_MAPPING
mappings += DocumentDenormalizationHandler.FIELDS_FOR_ACTIVITY_MAPPING
mappings += {
'properties':
{
'_metadata':
{
'properties':
{
'activity_generated':
{
'properties':
{
'short_data_validity_comment': DefaultMappings.KEYWORD
}
}
}
}
}
}
return mappings
def get_doc_for_complete_data(self, doc: dict):
update_doc_md = {}
assay_data = None
if self.assay_dh and doc['assay_chembl_id'] in self.assay_dh.assay_activity_data:
assay_data = self.assay_dh.assay_activity_data[doc['assay_chembl_id']]
if assay_data is not None:
update_doc_md['assay_data'] = assay_data
compound_data = None
if self.compound_dh and doc['molecule_chembl_id'] in self.compound_dh.molecule_activity_data:
compound_data = self.compound_dh.molecule_activity_data[doc['molecule_chembl_id']]
if compound_data is not None:
update_doc_md['parent_molecule_data'] = compound_data
compound_record_data = None
if self.compound_record_dh and \
doc['record_id'] in self.compound_record_dh.compound_record_activity_data:
compound_record_data = self.compound_record_dh.compound_record_activity_data[doc['record_id']]
if compound_record_data is not None:
if 'parent_molecule_data' not in update_doc_md:
update_doc_md['parent_molecule_data'] = {}
update_doc_md['parent_molecule_data']['compound_key'] = compound_record_data['compound_key']
source = None
if self.source_dh and doc['src_id'] in self.source_dh.sources_by_id:
source = self.source_dh.sources_by_id[doc['src_id']]
if source is not None:
update_doc_md['source'] = source
organism_taxonomy = None
try:
if doc['target_tax_id']:
tax_id = int(doc['target_tax_id'])
if self.organism_dh and tax_id in self.organism_dh.organism_by_id:
organism_taxonomy = self.organism_dh.organism_by_id[tax_id]
if organism_taxonomy is not None:
update_doc_md['organism_taxonomy'] = organism_taxonomy
except:
print('ERROR: taxonomy id is not a number {0}'.format(doc['target_tax_id']), file=sys.stderr)
protein_classification = None
if self.target_component_dh:
protein_classification = self.target_component_dh.get_protein_classifications(doc['target_chembl_id'])
if protein_classification is not None:
update_doc_md['protein_classification'] = protein_classification
target_data = None
if self.target_dh:
target_data = self.target_dh.target_2_target_type.get(doc['target_chembl_id'], None)
if target_data:
update_doc_md['target_data'] = target_data
document_data = None
if self.document_dh and doc.get('document_chembl_id', None) in self.document_dh.docs_for_activity_by_chembl_id:
document_data = self.document_dh.docs_for_activity_by_chembl_id[doc['document_chembl_id']]
if document_data is not None:
update_doc_md['document_data'] = document_data
return {
'_metadata': update_doc_md
}
def complete_compound(self):
pb = get_new_progressbar('compound-completion', len(self.compound_2_assay))
for i, molecule_chembl_id in enumerate(self.compound_2_assay):
if molecule_chembl_id not in self.compound_dict:
self.compound_dict[molecule_chembl_id] = {}
self.compound_dict[molecule_chembl_id]['related_cell_lines'] = {
'count': 0,
'all_chembl_ids': set()
}
self.compound_dict[molecule_chembl_id]['related_tissues'] = {
'count': 0,
'all_chembl_ids': set()
}
for assay in self.compound_2_assay.get(molecule_chembl_id, []):
cell_n_tissue = self.assay_dh.assay_2_cell_n_tissue.get(assay, {})
cell_id = cell_n_tissue.get('cell_chembl_id', None)
tissue_id = cell_n_tissue.get('tissue_chembl_id', None)
if cell_id and \
cell_id not in self.compound_dict[molecule_chembl_id]['related_cell_lines']['all_chembl_ids']:
self.compound_dict[molecule_chembl_id]['related_cell_lines']['count'] += 1
self.compound_dict[molecule_chembl_id]['related_cell_lines']['all_chembl_ids'].add(cell_id)
if tissue_id and \
tissue_id not in self.compound_dict[molecule_chembl_id]['related_tissues']['all_chembl_ids']:
self.compound_dict[molecule_chembl_id]['related_tissues']['count'] += 1
self.compound_dict[molecule_chembl_id]['related_tissues']['all_chembl_ids'].add(tissue_id)
pb.update(i)
pb.finish() | src/glados/es/ws2es/denormalization/activity_handler.py | import sys
from glados.es.ws2es.es_util import DefaultMappings
from glados.es.ws2es.denormalization import DenormalizationHandler
from glados.es.ws2es.util import SummableDict
from glados.es.ws2es.denormalization.assay_handler import AssayDenormalizationHandler
from glados.es.ws2es.denormalization.compound_handler import CompoundDenormalizationHandler
from glados.es.ws2es.denormalization.compound_record_handler import CompoundRecordDenormalizationHandler
from glados.es.ws2es.denormalization.document_handler import DocumentDenormalizationHandler
from glados.es.ws2es.denormalization.organism_handler import OrganismDenormalizationHandler
from glados.es.ws2es.denormalization.source_handler import SourceDenormalizationHandler
from glados.es.ws2es.denormalization.target_component_handler import TargetComponentDenormalizationHandler
from glados.es.ws2es.denormalization.target_handler import TargetDenormalizationHandler
from glados.es.ws2es.denormalization.protein_class_handler import ProteinClassDenormalizationHandler
from glados.es.ws2es.progress_bar_handler import get_new_progressbar
class ActivityDenormalizationHandler(DenormalizationHandler):
RESOURCE = DenormalizationHandler.AVAILABLE_RESOURCES.ACTIVITY
def __init__(self, complete_from_activity: bool=False, assay_dh: AssayDenormalizationHandler=None,
compound_dh: CompoundDenormalizationHandler=None, organism_dh: OrganismDenormalizationHandler=None,
source_dh: SourceDenormalizationHandler=None, target_dh: TargetDenormalizationHandler=None,
target_component_dh: TargetComponentDenormalizationHandler=None,
compound_record_dh: CompoundRecordDenormalizationHandler=None,
document_dh: DocumentDenormalizationHandler=None):
super().__init__(complete_from_activity or
assay_dh is not None or
compound_dh is not None or
organism_dh is not None or
source_dh is not None or
target_dh is not None or
target_component_dh is not None or
compound_record_dh is not None or
document_dh is not None)
self.assay_dh = assay_dh
self.compound_dh = compound_dh
self.organism_dh = organism_dh
self.source_dh = source_dh
self.target_dh = target_dh
self.target_component_dh = target_component_dh
self.compound_record_dh = compound_record_dh
self.document_dh = document_dh
self.assay_dict = {}
self.compound_dict = {}
self.document_dict = {}
self.target_dict = {}
self.compound_2_assay = {}
self.assay_2_compound = {}
def handle_doc(self, doc: dict, total_docs: int, index: int, first: bool, last: bool):
self.collect_data(doc, self.assay_dict, 'assay_chembl_id', [
self.DENORMALIZATION_CONFIGURATIONS[self.AVAILABLE_RESOURCES.ACTIVITY],
self.DENORMALIZATION_CONFIGURATIONS[self.AVAILABLE_RESOURCES.DOCUMENT],
self.DENORMALIZATION_CONFIGURATIONS[self.AVAILABLE_RESOURCES.MOLECULE],
self.DENORMALIZATION_CONFIGURATIONS[self.AVAILABLE_RESOURCES.TARGET],
]
)
self.collect_data(doc, self.document_dict, 'document_chembl_id', [
self.DENORMALIZATION_CONFIGURATIONS[self.AVAILABLE_RESOURCES.ACTIVITY],
self.DENORMALIZATION_CONFIGURATIONS[self.AVAILABLE_RESOURCES.ASSAY],
self.DENORMALIZATION_CONFIGURATIONS[self.AVAILABLE_RESOURCES.MOLECULE],
self.DENORMALIZATION_CONFIGURATIONS[self.AVAILABLE_RESOURCES.TARGET],
]
)
self.collect_data(doc, self.compound_dict, 'molecule_chembl_id', [
self.DENORMALIZATION_CONFIGURATIONS[self.AVAILABLE_RESOURCES.ACTIVITY],
self.DENORMALIZATION_CONFIGURATIONS[self.AVAILABLE_RESOURCES.ASSAY],
self.DENORMALIZATION_CONFIGURATIONS[self.AVAILABLE_RESOURCES.DOCUMENT],
self.DENORMALIZATION_CONFIGURATIONS[self.AVAILABLE_RESOURCES.TARGET],
]
)
self.collect_data(doc, self.target_dict, 'target_chembl_id', [
self.DENORMALIZATION_CONFIGURATIONS[self.AVAILABLE_RESOURCES.ACTIVITY],
self.DENORMALIZATION_CONFIGURATIONS[self.AVAILABLE_RESOURCES.ASSAY],
self.DENORMALIZATION_CONFIGURATIONS[self.AVAILABLE_RESOURCES.DOCUMENT],
self.DENORMALIZATION_CONFIGURATIONS[self.AVAILABLE_RESOURCES.MOLECULE],
]
)
if doc['molecule_chembl_id'] not in self.compound_2_assay:
self.compound_2_assay[doc['molecule_chembl_id']] = set()
self.compound_2_assay[doc['molecule_chembl_id']].add(doc['assay_chembl_id'])
if doc['assay_chembl_id'] not in self.assay_2_compound:
self.assay_2_compound[doc['assay_chembl_id']] = set()
self.assay_2_compound[doc['assay_chembl_id']].add(doc['molecule_chembl_id'])
def save_denormalization(self):
self.submit_docs_collected_data(self.assay_dict,
DenormalizationHandler.AVAILABLE_RESOURCES.ASSAY)
self.submit_docs_collected_data(self.compound_dict,
DenormalizationHandler.AVAILABLE_RESOURCES.MOLECULE)
self.submit_docs_collected_data(self.document_dict,
DenormalizationHandler.AVAILABLE_RESOURCES.DOCUMENT)
self.submit_docs_collected_data(self.target_dict,
DenormalizationHandler.AVAILABLE_RESOURCES.TARGET)
def get_custom_mappings_for_complete_data(self):
mappings = SummableDict()
mappings += AssayDenormalizationHandler.ACTIVITY_DATA_MAPPING
mappings += CompoundDenormalizationHandler.ACTIVITY_DATA_MAPPING
mappings += SourceDenormalizationHandler.METADATA_MAPPING
mappings += OrganismDenormalizationHandler.METADATA_MAPPING
mappings += CompoundRecordDenormalizationHandler.ACTIVITY_DATA_MAPPING
mappings += TargetDenormalizationHandler.ACTIVITY_DATA_MAPPING
mappings += ProteinClassDenormalizationHandler.METADATA_MAPPING
mappings += DocumentDenormalizationHandler.FIELDS_FOR_ACTIVITY_MAPPING
mappings += {
'properties':
{
'_metadata':
{
'properties':
{
'activity_generated':
{
'properties':
{
'short_data_validity_comment': DefaultMappings.KEYWORD
}
}
}
}
}
}
return mappings
def get_doc_for_complete_data(self, doc: dict):
update_doc_md = {}
assay_data = None
if self.assay_dh and doc['assay_chembl_id'] in self.assay_dh.assay_activity_data:
assay_data = self.assay_dh.assay_activity_data[doc['assay_chembl_id']]
if assay_data is not None:
update_doc_md['assay_data'] = assay_data
compound_data = None
if self.compound_dh and doc['molecule_chembl_id'] in self.compound_dh.molecule_activity_data:
compound_data = self.compound_dh.molecule_activity_data[doc['molecule_chembl_id']]
if compound_data is not None:
update_doc_md['parent_molecule_data'] = compound_data
compound_record_data = None
if self.compound_record_dh and \
doc['record_id'] in self.compound_record_dh.compound_record_activity_data:
compound_record_data = self.compound_record_dh.compound_record_activity_data[doc['record_id']]
if compound_record_data is not None:
if 'parent_molecule_data' not in update_doc_md:
update_doc_md['parent_molecule_data'] = {}
update_doc_md['parent_molecule_data']['compound_key'] = compound_record_data['compound_key']
source = None
if self.source_dh and doc['src_id'] in self.source_dh.sources_by_id:
source = self.source_dh.sources_by_id[doc['src_id']]
if source is not None:
update_doc_md['source'] = source
organism_taxonomy = None
try:
if doc['target_tax_id']:
tax_id = int(doc['target_tax_id'])
if self.organism_dh and tax_id in self.organism_dh.organism_by_id:
organism_taxonomy = self.organism_dh.organism_by_id[tax_id]
if organism_taxonomy is not None:
update_doc_md['organism_taxonomy'] = organism_taxonomy
except:
print('ERROR: taxonomy id is not a number {0}'.format(doc['target_tax_id']), file=sys.stderr)
protein_classification = None
if self.target_component_dh:
protein_classification = self.target_component_dh.get_protein_classifications(doc['target_chembl_id'])
if protein_classification is not None:
update_doc_md['protein_classification'] = protein_classification
target_data = None
if self.target_dh:
target_data = self.target_dh.target_2_target_type.get(doc['target_chembl_id'], None)
if target_data:
update_doc_md['target_data'] = target_data
document_data = None
if self.document_dh and doc.get('document_chembl_id', None) in self.document_dh.docs_for_activity_by_chembl_id:
document_data = self.document_dh.docs_for_activity_by_chembl_id[doc['document_chembl_id']]
if document_data is not None:
update_doc_md['document_data'] = document_data
return {
'_metadata': update_doc_md
}
def complete_compound(self):
pb = get_new_progressbar('compound-completion', len(self.compound_2_assay))
for i, molecule_chembl_id in enumerate(self.compound_2_assay):
if molecule_chembl_id not in self.compound_dict:
self.compound_dict[molecule_chembl_id] = {}
self.compound_dict[molecule_chembl_id]['related_cell_lines'] = {
'count': 0,
'all_chembl_ids': set()
}
self.compound_dict[molecule_chembl_id]['related_tissues'] = {
'count': 0,
'all_chembl_ids': set()
}
for assay in self.compound_2_assay.get(molecule_chembl_id, []):
cell_n_tissue = self.assay_dh.assay_2_cell_n_tissue.get(assay, {})
cell_id = cell_n_tissue.get('cell_chembl_id', None)
tissue_id = cell_n_tissue.get('tissue_chembl_id', None)
if cell_id and \
cell_id not in self.compound_dict[molecule_chembl_id]['related_cell_lines']['all_chembl_ids']:
self.compound_dict[molecule_chembl_id]['related_cell_lines']['count'] += 1
self.compound_dict[molecule_chembl_id]['related_cell_lines']['all_chembl_ids'].add(cell_id)
if tissue_id and \
tissue_id not in self.compound_dict[molecule_chembl_id]['related_tissues']['all_chembl_ids']:
self.compound_dict[molecule_chembl_id]['related_tissues']['count'] += 1
self.compound_dict[molecule_chembl_id]['related_tissues']['all_chembl_ids'].add(tissue_id)
pb.update(i)
pb.finish() | 0.38341 | 0.122786 |
from random import randint
import json
class Pykemon(object):
pykemon = [
[100, 'Pydiot', 'Pydiot','images/pydiot.png', 'Pydiot is an avian Pykamon with large wings, sharp talons, and a short, hooked beak'],
[90, 'Pytata', 'Pytata', 'images/pytata.png', 'Pytata is cautious in the extreme. Even while it is asleep, it constantly listens by moving its ears around.'],
[80, 'Pyliwag', 'Pyliwag', 'images/pyliwag.png', 'Pyliwag resembles a blue, spherical tadpole. It has large eyes and pink lips.'],
[70, 'Pyrasect', 'Pyrasect', 'images/pyrasect.png','Pyrasect is known to infest large trees en masse and drain nutrients from the lower trunk and roots.'],
[60, 'Pyduck', 'Pyduck', 'images/pyduck.png','Pyduck is a yellow Pykamon that resembles a duck or bipedal platypus'],
[50, 'Pygglipuff', 'Pygglipuff', 'images/pygglipuff.png','When this Pykamon sings, it never pauses to breathe.'],
[40, 'Pykachu', 'Pykachu', 'images/pykachu.png','This Pykamon has electricity-storing pouches on its cheeks. These appear to become electrically charged during the night while Pykachu sleeps.'],
[30, 'Pyrigon', 'Pyrigon', 'images/pyrigon.png','Pyrigon is capable of reverting itself entirely back to program data and entering cyberspace.'],
[20, 'Pyrodactyl', 'Pyrodactyl', 'images/pyrodactyl.png','Pyrodactyl is a Pykamon from the age of dinosaurs'],
[10, 'Pytwo', 'Pytwo', 'images/pytwo.png','Pytwo is a Pykamon created by genetic manipulation'],
[0, 'FLAG', 'FLAG','images/flag.png', 'PCTF{XXXXX}']
]
def __init__(self, name=None, hp=None):
pykemon = Pykemon.pykemon
if not name:
i = randint(0,10)
else:
count = 0
for p in pykemon:
if name in p:
i = count
count += 1
self.name = pykemon[i][1]
self.nickname = pykemon[i][2]
self.sprite = pykemon[i][3]
self.description = pykemon[i][4]
self.hp = hp
if not hp:
self.hp = randint(1,100)
self.rarity = pykemon[i][0]
self.pid = self.name + str(self.hp)
class Room(object):
def __init__(self):
self.rid = 0
self.pykemon_count = randint(5,15)
self.pykemon = []
if not self.pykemon_count:
return
while len(self.pykemon) < self.pykemon_count:
p = Pykemon()
self.pykemon.append(p.__dict__)
return
class Map(object):
def __init__(self):
self.size = 10 | PlaidCTF/2017/pykemon/pykemon.py | from random import randint
import json
class Pykemon(object):
pykemon = [
[100, 'Pydiot', 'Pydiot','images/pydiot.png', 'Pydiot is an avian Pykamon with large wings, sharp talons, and a short, hooked beak'],
[90, 'Pytata', 'Pytata', 'images/pytata.png', 'Pytata is cautious in the extreme. Even while it is asleep, it constantly listens by moving its ears around.'],
[80, 'Pyliwag', 'Pyliwag', 'images/pyliwag.png', 'Pyliwag resembles a blue, spherical tadpole. It has large eyes and pink lips.'],
[70, 'Pyrasect', 'Pyrasect', 'images/pyrasect.png','Pyrasect is known to infest large trees en masse and drain nutrients from the lower trunk and roots.'],
[60, 'Pyduck', 'Pyduck', 'images/pyduck.png','Pyduck is a yellow Pykamon that resembles a duck or bipedal platypus'],
[50, 'Pygglipuff', 'Pygglipuff', 'images/pygglipuff.png','When this Pykamon sings, it never pauses to breathe.'],
[40, 'Pykachu', 'Pykachu', 'images/pykachu.png','This Pykamon has electricity-storing pouches on its cheeks. These appear to become electrically charged during the night while Pykachu sleeps.'],
[30, 'Pyrigon', 'Pyrigon', 'images/pyrigon.png','Pyrigon is capable of reverting itself entirely back to program data and entering cyberspace.'],
[20, 'Pyrodactyl', 'Pyrodactyl', 'images/pyrodactyl.png','Pyrodactyl is a Pykamon from the age of dinosaurs'],
[10, 'Pytwo', 'Pytwo', 'images/pytwo.png','Pytwo is a Pykamon created by genetic manipulation'],
[0, 'FLAG', 'FLAG','images/flag.png', 'PCTF{XXXXX}']
]
def __init__(self, name=None, hp=None):
pykemon = Pykemon.pykemon
if not name:
i = randint(0,10)
else:
count = 0
for p in pykemon:
if name in p:
i = count
count += 1
self.name = pykemon[i][1]
self.nickname = pykemon[i][2]
self.sprite = pykemon[i][3]
self.description = pykemon[i][4]
self.hp = hp
if not hp:
self.hp = randint(1,100)
self.rarity = pykemon[i][0]
self.pid = self.name + str(self.hp)
class Room(object):
def __init__(self):
self.rid = 0
self.pykemon_count = randint(5,15)
self.pykemon = []
if not self.pykemon_count:
return
while len(self.pykemon) < self.pykemon_count:
p = Pykemon()
self.pykemon.append(p.__dict__)
return
class Map(object):
def __init__(self):
self.size = 10 | 0.321886 | 0.501709 |
import json
import tempfile
import subprocess
from os import path
from pprint import pformat
from unittest import TestCase
from pathlib import Path
from ..util import setup_temp_dir, SAMPLES_DIR, TEMP_DIR
from gltflib import GLTF
# If set to True, for any models that fail to pass the equality check, this will automatically launch kdiff3 to compare
# the original model to the roundtrip model (execution will be paused while kdiff3 is open).
DEBUG = False
class TestRoundtrip(TestCase):
"""
Performs round-trip equality tests for all models in the glTF-Sample-Models repository.
This test class loads each model (including all variants: glTF, glTF-Binary, glTF-Embedded, etc.) from the original
glTF-Sample-Models repository, then performs the following steps:
1. Export the model (without any changes) to a temporary location
2. Load the exported copy
3. Ensure that the parsed model from the exported copy is equal to the parsed model from the original sample
This ensures that all fields were parsed correctly and that no fields are missing.
"""
@classmethod
def setUpClass(cls):
print()
print('Running round-trip tests:')
print()
setup_temp_dir()
def setUp(self):
self.maxDiff = None
def _get_model_index(self):
with open(path.join(SAMPLES_DIR, 'model-index.json')) as f:
return json.load(f)
def test_roundtrip(self):
"""Ensures all sample models remain unchanged after loading, saving, and loading again via the library"""
# Read the model-index.json file to get a listing of all sample models
for info in self._get_model_index():
model_name = info['name']
variants = info['variants']
# Test each available variant of the model (glTF, glTF-Binary, glTF-Embedded, and glTF-Draco)
for variant in variants:
basename = variants[variant]
original_filename = path.join(SAMPLES_DIR, model_name, variant, basename)
abspath = path.abspath(original_filename)
# Print the absolute path of the current variant we're testing
print(abspath)
# Parse the original model
original_model = GLTF.load(original_filename)
# Export a copy of the parsed model to a temporary location
output_filename = path.join(TEMP_DIR, model_name, variant, basename)
original_model.export(output_filename)
# Parse the exported copy
roundtrip_model = GLTF.load(output_filename)
# In debug mode, open a diff viewer if the original model is not equivalent to the roundtrip version
if DEBUG and original_model.model != roundtrip_model.model:
self._launch_diff_viewer(original_filename, variant, original_model, roundtrip_model)
# Fail the test if the original model doesn't match the roundtrip model
self.assertEqual(original_model.model, roundtrip_model.model)
def _launch_diff_viewer(self, filename: str, variant: str, model_1: GLTF, model_2: GLTF):
"""Helper method to open a diff viewer if the models don't match"""
p = Path(filename)
basename = p.stem
ext = p.suffix
v1 = pformat(model_1.model.to_dict())
v2 = pformat(model_2.model.to_dict())
with tempfile.NamedTemporaryFile(mode='w+', prefix=f"{basename}_{variant}_original_", suffix=ext) as f1:
f1.write(v1)
f1.flush()
with tempfile.NamedTemporaryFile(mode='w+', prefix=f"{basename}_{variant}_roundtrip_", suffix=ext) as f2:
f2.write(v2)
f2.flush()
subprocess.run(['kdiff3', f1.name, f2.name]) | tests/e2e/test_roundtrip.py | import json
import tempfile
import subprocess
from os import path
from pprint import pformat
from unittest import TestCase
from pathlib import Path
from ..util import setup_temp_dir, SAMPLES_DIR, TEMP_DIR
from gltflib import GLTF
# If set to True, for any models that fail to pass the equality check, this will automatically launch kdiff3 to compare
# the original model to the roundtrip model (execution will be paused while kdiff3 is open).
DEBUG = False
class TestRoundtrip(TestCase):
"""
Performs round-trip equality tests for all models in the glTF-Sample-Models repository.
This test class loads each model (including all variants: glTF, glTF-Binary, glTF-Embedded, etc.) from the original
glTF-Sample-Models repository, then performs the following steps:
1. Export the model (without any changes) to a temporary location
2. Load the exported copy
3. Ensure that the parsed model from the exported copy is equal to the parsed model from the original sample
This ensures that all fields were parsed correctly and that no fields are missing.
"""
@classmethod
def setUpClass(cls):
print()
print('Running round-trip tests:')
print()
setup_temp_dir()
def setUp(self):
self.maxDiff = None
def _get_model_index(self):
with open(path.join(SAMPLES_DIR, 'model-index.json')) as f:
return json.load(f)
def test_roundtrip(self):
"""Ensures all sample models remain unchanged after loading, saving, and loading again via the library"""
# Read the model-index.json file to get a listing of all sample models
for info in self._get_model_index():
model_name = info['name']
variants = info['variants']
# Test each available variant of the model (glTF, glTF-Binary, glTF-Embedded, and glTF-Draco)
for variant in variants:
basename = variants[variant]
original_filename = path.join(SAMPLES_DIR, model_name, variant, basename)
abspath = path.abspath(original_filename)
# Print the absolute path of the current variant we're testing
print(abspath)
# Parse the original model
original_model = GLTF.load(original_filename)
# Export a copy of the parsed model to a temporary location
output_filename = path.join(TEMP_DIR, model_name, variant, basename)
original_model.export(output_filename)
# Parse the exported copy
roundtrip_model = GLTF.load(output_filename)
# In debug mode, open a diff viewer if the original model is not equivalent to the roundtrip version
if DEBUG and original_model.model != roundtrip_model.model:
self._launch_diff_viewer(original_filename, variant, original_model, roundtrip_model)
# Fail the test if the original model doesn't match the roundtrip model
self.assertEqual(original_model.model, roundtrip_model.model)
def _launch_diff_viewer(self, filename: str, variant: str, model_1: GLTF, model_2: GLTF):
"""Helper method to open a diff viewer if the models don't match"""
p = Path(filename)
basename = p.stem
ext = p.suffix
v1 = pformat(model_1.model.to_dict())
v2 = pformat(model_2.model.to_dict())
with tempfile.NamedTemporaryFile(mode='w+', prefix=f"{basename}_{variant}_original_", suffix=ext) as f1:
f1.write(v1)
f1.flush()
with tempfile.NamedTemporaryFile(mode='w+', prefix=f"{basename}_{variant}_roundtrip_", suffix=ext) as f2:
f2.write(v2)
f2.flush()
subprocess.run(['kdiff3', f1.name, f2.name]) | 0.642881 | 0.480601 |
import numpy as np
from numpy import zeros_like
from scipy.linalg import svd
s0 = np.array([[1, 0], [0, 1]])
s1 = np.array([[0, 1], [1, 0]])
s2 = np.array([[0, -1j], [1j, 0]])
s3 = np.array([[1, 0], [0, -1]])
s0T = s0.T
s1T = s1.T
s2T = s2.T
s3T = s3.T
pauli_dict = {0: s0, 1: s1, 2: s2, 3: s3}
def pauli_mat(nbasis, i):
"""
nbasis: size of the matrix. should be multiple of 2.
i: index of pauli dictionary.
"""
N = nbasis // 2
assert (N * 2 == nbasis)
M = np.ones((N, N), dtype='complex')
spm = pauli_dict[i]
return np.block([[M * spm[0, 0], M * spm[0, 1]],
[M * spm[1, 0], M * spm[1, 1]]])
def pauli_decomp(M):
""" Given a 2*2 matrix, get the I, x, y, z component.
:param M: 2*2 matrix
:returns: (I, x, y, z) are four scalars.
:rtype: same as dtype of M
"""
return (np.trace(s0.dot(M)) / 2, np.trace(s1.dot(M)) / 2,
np.trace(s2.dot(M)) / 2, np.trace(s3.dot(M)) / 2)
def pauli_decomp2(M):
""" Given a 2*2 matrix, get the I, x, y, z component. (method2)
:param M: 2*2 matrix
:returns: (I, x, y, z) are four scalars.
:rtype: same as dtype of M
"""
return (np.sum(M * s0T) / 2, np.sum(M * s1T) / 2, np.sum(M * s2T) / 2,
np.sum(M * s3T) / 2)
def pauli_sigma_norm(M):
MI, Mx, My, Mz = pauli_decomp2(M)
return np.linalg.norm([Mx, My, Mz])
def pauli_block_I(M, norb):
"""
I compoenent of a matrix, see pauli_block
"""
ret = zeros_like(M)
tmp = (M[::2, ::2] + M[1::2, 1::2]) / 2
ret[::2, ::2] = ret[1::2, 1::2] = tmp
return ret
def pauli_block_x(M, norb):
"""
x compoenent of a matrix, see pauli_block
"""
ret = zeros_like(M)
tmp = (M[::2, 1::2] + M[1::2, ::2]) / 2
ret[::2, 1::2] = ret[1::2, ::2] = tmp
return ret
def pauli_block_y(M, norb):
"""
y compoenent of a matrix, see pauli_block
"""
ret = zeros_like(M)
tmp = (M[::2, 1::2] * (-1j) + M[1::2, ::2] * (1j)) / 2
ret[::2, 1::2] = tmp * (-1j)
ret[1::2, ::2] = tmp * 1j
return tmp, ret
def pauli_block_z(M, norb):
""" z compoenent of a matrix, see pauli_block
:param M:
:param norb:
:returns:
:rtype:
"""
ret = zeros_like(M)
tmp = (M[::2, ::2] - M[1::2, 1::2]) / 2
ret[::2, ::2] = tmp
ret[1::2, 1::2] = -tmp
return tmp, ret
def pauli_block(M, idim):
""" Get the I, x, y, z component of a matrix.
:param M: The input matrix, aranged in four blocks:
[[upup, updn], [dnup, dndn]]. let norb be number of orbitals in
each block. (so M has dim 2norb1*2norb2)
:param idim: 0, 1,2, 3 for I , x, y, z.
:returns: the idim(th) component of M
:rtype: a matrix with shape of M.shape//2
"""
# ret = zeros_like(M)
if idim == 0:
tmp = (M[::2, ::2] + M[1::2, 1::2]) / 2.0
elif idim == 1:
tmp = (M[::2, 1::2] + M[1::2, ::2]) / 2.0
elif idim == 2:
# Note that this is not element wise product with sigma_y but dot product
# sigma_y=[[0, -1j],[1j, 0]]
tmp = (M[::2, 1::2] * (1.0j) + M[1::2, ::2] * (-1.0j)) / 2.0
elif idim == 3:
tmp = (M[::2, ::2] - M[1::2, 1::2]) / 2.0
else:
raise NotImplementedError()
return tmp
def pauli_block_all(M):
MI = (M[::2, ::2] + M[1::2, 1::2]) / 2.0
Mx = (M[::2, 1::2] + M[1::2, ::2]) / 2.0
# Note that this is not element wise product with sigma_y but dot product
My = (M[::2, 1::2] - M[1::2, ::2]) * 0.5j
Mz = (M[::2, ::2] - M[1::2, 1::2]) / 2.0
return MI, Mx, My, Mz
def op_norm(M):
return max(svd(M)[1])
def pauli_block_sigma_norm(M):
"""
M= MI * I + \vec{P} dot \vec{sigma}
= MI*I + p * \vec{e} dot \vec{sigma}
where p is the norm of P.
"""
MI, Mx, My, Mz = pauli_block_all(M)
ex, ey, ez = np.trace(Mx), np.trace(My), np.trace(Mz)
#ex,ey,ez = op_norm(Mx), op_norm(My), op_norm(Mz)
evec = np.array((ex, ey, ez))
evec = evec / np.linalg.norm(evec)
return Mx * evec[0] + My * evec[1] + Mz * evec[2] | TB2J/pauli.py | import numpy as np
from numpy import zeros_like
from scipy.linalg import svd
s0 = np.array([[1, 0], [0, 1]])
s1 = np.array([[0, 1], [1, 0]])
s2 = np.array([[0, -1j], [1j, 0]])
s3 = np.array([[1, 0], [0, -1]])
s0T = s0.T
s1T = s1.T
s2T = s2.T
s3T = s3.T
pauli_dict = {0: s0, 1: s1, 2: s2, 3: s3}
def pauli_mat(nbasis, i):
"""
nbasis: size of the matrix. should be multiple of 2.
i: index of pauli dictionary.
"""
N = nbasis // 2
assert (N * 2 == nbasis)
M = np.ones((N, N), dtype='complex')
spm = pauli_dict[i]
return np.block([[M * spm[0, 0], M * spm[0, 1]],
[M * spm[1, 0], M * spm[1, 1]]])
def pauli_decomp(M):
""" Given a 2*2 matrix, get the I, x, y, z component.
:param M: 2*2 matrix
:returns: (I, x, y, z) are four scalars.
:rtype: same as dtype of M
"""
return (np.trace(s0.dot(M)) / 2, np.trace(s1.dot(M)) / 2,
np.trace(s2.dot(M)) / 2, np.trace(s3.dot(M)) / 2)
def pauli_decomp2(M):
""" Given a 2*2 matrix, get the I, x, y, z component. (method2)
:param M: 2*2 matrix
:returns: (I, x, y, z) are four scalars.
:rtype: same as dtype of M
"""
return (np.sum(M * s0T) / 2, np.sum(M * s1T) / 2, np.sum(M * s2T) / 2,
np.sum(M * s3T) / 2)
def pauli_sigma_norm(M):
MI, Mx, My, Mz = pauli_decomp2(M)
return np.linalg.norm([Mx, My, Mz])
def pauli_block_I(M, norb):
"""
I compoenent of a matrix, see pauli_block
"""
ret = zeros_like(M)
tmp = (M[::2, ::2] + M[1::2, 1::2]) / 2
ret[::2, ::2] = ret[1::2, 1::2] = tmp
return ret
def pauli_block_x(M, norb):
"""
x compoenent of a matrix, see pauli_block
"""
ret = zeros_like(M)
tmp = (M[::2, 1::2] + M[1::2, ::2]) / 2
ret[::2, 1::2] = ret[1::2, ::2] = tmp
return ret
def pauli_block_y(M, norb):
"""
y compoenent of a matrix, see pauli_block
"""
ret = zeros_like(M)
tmp = (M[::2, 1::2] * (-1j) + M[1::2, ::2] * (1j)) / 2
ret[::2, 1::2] = tmp * (-1j)
ret[1::2, ::2] = tmp * 1j
return tmp, ret
def pauli_block_z(M, norb):
""" z compoenent of a matrix, see pauli_block
:param M:
:param norb:
:returns:
:rtype:
"""
ret = zeros_like(M)
tmp = (M[::2, ::2] - M[1::2, 1::2]) / 2
ret[::2, ::2] = tmp
ret[1::2, 1::2] = -tmp
return tmp, ret
def pauli_block(M, idim):
""" Get the I, x, y, z component of a matrix.
:param M: The input matrix, aranged in four blocks:
[[upup, updn], [dnup, dndn]]. let norb be number of orbitals in
each block. (so M has dim 2norb1*2norb2)
:param idim: 0, 1,2, 3 for I , x, y, z.
:returns: the idim(th) component of M
:rtype: a matrix with shape of M.shape//2
"""
# ret = zeros_like(M)
if idim == 0:
tmp = (M[::2, ::2] + M[1::2, 1::2]) / 2.0
elif idim == 1:
tmp = (M[::2, 1::2] + M[1::2, ::2]) / 2.0
elif idim == 2:
# Note that this is not element wise product with sigma_y but dot product
# sigma_y=[[0, -1j],[1j, 0]]
tmp = (M[::2, 1::2] * (1.0j) + M[1::2, ::2] * (-1.0j)) / 2.0
elif idim == 3:
tmp = (M[::2, ::2] - M[1::2, 1::2]) / 2.0
else:
raise NotImplementedError()
return tmp
def pauli_block_all(M):
MI = (M[::2, ::2] + M[1::2, 1::2]) / 2.0
Mx = (M[::2, 1::2] + M[1::2, ::2]) / 2.0
# Note that this is not element wise product with sigma_y but dot product
My = (M[::2, 1::2] - M[1::2, ::2]) * 0.5j
Mz = (M[::2, ::2] - M[1::2, 1::2]) / 2.0
return MI, Mx, My, Mz
def op_norm(M):
return max(svd(M)[1])
def pauli_block_sigma_norm(M):
"""
M= MI * I + \vec{P} dot \vec{sigma}
= MI*I + p * \vec{e} dot \vec{sigma}
where p is the norm of P.
"""
MI, Mx, My, Mz = pauli_block_all(M)
ex, ey, ez = np.trace(Mx), np.trace(My), np.trace(Mz)
#ex,ey,ez = op_norm(Mx), op_norm(My), op_norm(Mz)
evec = np.array((ex, ey, ez))
evec = evec / np.linalg.norm(evec)
return Mx * evec[0] + My * evec[1] + Mz * evec[2] | 0.706089 | 0.691621 |
from copy import deepcopy
from optax import sgd
from .._base.test_case import TestCase
from .._core.stochastic_transition_model import StochasticTransitionModel
from ..utils import get_transition_batch
from ..regularizers import EntropyRegularizer
from ._model_updater import ModelUpdater
class TestModelUpdater(TestCase):
def setUp(self):
self.transition_discrete = get_transition_batch(self.env_discrete, random_seed=42)
self.transition_boxspace = get_transition_batch(self.env_boxspace, random_seed=42)
def test_update_type1(self):
env = self.env_discrete
func_p = self.func_p_type1
transition_batch = self.transition_discrete
p = StochasticTransitionModel(func_p, env, random_seed=11)
updater = ModelUpdater(p, optimizer=sgd(1.0))
params = deepcopy(p.params)
function_state = deepcopy(p.function_state)
updater.update(transition_batch)
self.assertPytreeNotEqual(params, p.params)
self.assertPytreeNotEqual(function_state, p.function_state)
def test_update_type2(self):
env = self.env_discrete
func_p = self.func_p_type2
transition_batch = self.transition_discrete
p = StochasticTransitionModel(func_p, env, random_seed=11)
updater = ModelUpdater(p, optimizer=sgd(1.0))
params = deepcopy(p.params)
function_state = deepcopy(p.function_state)
updater.update(transition_batch)
self.assertPytreeNotEqual(params, p.params)
self.assertPytreeNotEqual(function_state, p.function_state)
def test_policyreg(self):
env = self.env_discrete
func_p = self.func_p_type1
transition_batch = self.transition_discrete
p = StochasticTransitionModel(func_p, env, random_seed=11)
params_init = deepcopy(p.params)
function_state_init = deepcopy(p.function_state)
# first update without policy regularizer
updater = ModelUpdater(p, optimizer=sgd(1.0))
updater.update(transition_batch)
params_without_reg = deepcopy(p.params)
function_state_without_reg = deepcopy(p.function_state)
self.assertPytreeNotEqual(params_without_reg, params_init)
self.assertPytreeNotEqual(function_state_without_reg, function_state_init)
# reset weights
p = StochasticTransitionModel(func_p, env, random_seed=11)
self.assertPytreeAlmostEqual(params_init, p.params)
self.assertPytreeAlmostEqual(function_state_init, p.function_state)
# then update with policy regularizer
reg = EntropyRegularizer(p, beta=1.0)
updater = ModelUpdater(p, optimizer=sgd(1.0), regularizer=reg)
updater.update(transition_batch)
params_with_reg = deepcopy(p.params)
function_state_with_reg = deepcopy(p.function_state)
self.assertPytreeNotEqual(params_with_reg, params_init)
self.assertPytreeNotEqual(params_with_reg, params_without_reg) # <---- important
self.assertPytreeNotEqual(function_state_with_reg, function_state_init)
self.assertPytreeAlmostEqual(function_state_with_reg, function_state_without_reg) # same! | coax/model_updaters/_model_updater_test.py | from copy import deepcopy
from optax import sgd
from .._base.test_case import TestCase
from .._core.stochastic_transition_model import StochasticTransitionModel
from ..utils import get_transition_batch
from ..regularizers import EntropyRegularizer
from ._model_updater import ModelUpdater
class TestModelUpdater(TestCase):
def setUp(self):
self.transition_discrete = get_transition_batch(self.env_discrete, random_seed=42)
self.transition_boxspace = get_transition_batch(self.env_boxspace, random_seed=42)
def test_update_type1(self):
env = self.env_discrete
func_p = self.func_p_type1
transition_batch = self.transition_discrete
p = StochasticTransitionModel(func_p, env, random_seed=11)
updater = ModelUpdater(p, optimizer=sgd(1.0))
params = deepcopy(p.params)
function_state = deepcopy(p.function_state)
updater.update(transition_batch)
self.assertPytreeNotEqual(params, p.params)
self.assertPytreeNotEqual(function_state, p.function_state)
def test_update_type2(self):
env = self.env_discrete
func_p = self.func_p_type2
transition_batch = self.transition_discrete
p = StochasticTransitionModel(func_p, env, random_seed=11)
updater = ModelUpdater(p, optimizer=sgd(1.0))
params = deepcopy(p.params)
function_state = deepcopy(p.function_state)
updater.update(transition_batch)
self.assertPytreeNotEqual(params, p.params)
self.assertPytreeNotEqual(function_state, p.function_state)
def test_policyreg(self):
env = self.env_discrete
func_p = self.func_p_type1
transition_batch = self.transition_discrete
p = StochasticTransitionModel(func_p, env, random_seed=11)
params_init = deepcopy(p.params)
function_state_init = deepcopy(p.function_state)
# first update without policy regularizer
updater = ModelUpdater(p, optimizer=sgd(1.0))
updater.update(transition_batch)
params_without_reg = deepcopy(p.params)
function_state_without_reg = deepcopy(p.function_state)
self.assertPytreeNotEqual(params_without_reg, params_init)
self.assertPytreeNotEqual(function_state_without_reg, function_state_init)
# reset weights
p = StochasticTransitionModel(func_p, env, random_seed=11)
self.assertPytreeAlmostEqual(params_init, p.params)
self.assertPytreeAlmostEqual(function_state_init, p.function_state)
# then update with policy regularizer
reg = EntropyRegularizer(p, beta=1.0)
updater = ModelUpdater(p, optimizer=sgd(1.0), regularizer=reg)
updater.update(transition_batch)
params_with_reg = deepcopy(p.params)
function_state_with_reg = deepcopy(p.function_state)
self.assertPytreeNotEqual(params_with_reg, params_init)
self.assertPytreeNotEqual(params_with_reg, params_without_reg) # <---- important
self.assertPytreeNotEqual(function_state_with_reg, function_state_init)
self.assertPytreeAlmostEqual(function_state_with_reg, function_state_without_reg) # same! | 0.715126 | 0.488893 |
import os
import numpy as np
import torch
from .cityscapes.data_loader import load_partition_data_cityscapes
from .coco.segmentation.data_loader import load_partition_data_coco_segmentation
from .pascal_voc_augmented.data_loader import load_partition_data_pascal_voc
import logging
def load(args):
return load_synthetic_data(args)
def combine_batches(batches):
full_x = torch.from_numpy(np.asarray([])).float()
full_y = torch.from_numpy(np.asarray([])).long()
for (batched_x, batched_y) in batches:
full_x = torch.cat((full_x, batched_x), 0)
full_y = torch.cat((full_y, batched_y), 0)
return [(full_x, full_y)]
def load_synthetic_data(args):
dataset_name = str(args.dataset).lower()
# check if the centralized training is enabled
centralized = True if (args.client_num_in_total == 1 and args.training_type != "cross_silo") else False
# check if the full-batch training is enabled
args_batch_size = args.batch_size
if args.batch_size <= 0:
full_batch = True
args.batch_size = 128 # temporary batch size
else:
full_batch = False
if dataset_name == "cityscapes":
# load cityscapes dataset
(
train_data_num,
test_data_num,
train_data_global,
test_data_global,
data_local_num_dict,
train_data_local_dict,
test_data_local_dict,
class_num,
) = load_partition_data_cityscapes(
dataset=dataset_name,
data_dir=args.data_cache_dir,
partition_method=None,
partition_alpha=None,
client_number=args.client_num_in_total,
batch_size=args.batch_size,
)
elif dataset_name in ["coco_segmentation", "coco"]:
# load coco dataset
(
train_data_num,
test_data_num,
train_data_global,
test_data_global,
data_local_num_dict,
train_data_local_dict,
test_data_local_dict,
class_num,
) = load_partition_data_coco_segmentation(
dataset=dataset_name,
data_dir=args.data_cache_dir,
partition_method=None,
partition_alpha=None,
client_number=args.client_num_in_total,
batch_size=args.batch_size,
)
elif dataset_name in ["pascal_voc", "pascal_voc_augmented"]:
# load pascal voc dataset
(
train_data_num,
test_data_num,
train_data_global,
test_data_global,
data_local_num_dict,
train_data_local_dict,
test_data_local_dict,
class_num,
) = load_partition_data_pascal_voc(
dataset=dataset_name,
data_dir=args.data_cache_dir,
partition_method=None,
partition_alpha=None,
client_number=args.client_num_in_total,
batch_size=args.batch_size,
)
else:
raise ValueError("dataset %s is not supported" % dataset_name)
if centralized:
train_data_local_num_dict = {
0: sum(user_train_data_num for user_train_data_num in train_data_local_num_dict.values())
}
train_data_local_dict = {
0: [batch for cid in sorted(train_data_local_dict.keys()) for batch in train_data_local_dict[cid]]
}
test_data_local_dict = {
0: [batch for cid in sorted(test_data_local_dict.keys()) for batch in test_data_local_dict[cid]]
}
args.client_num_in_total = 1
if full_batch:
train_data_global = combine_batches(train_data_global)
test_data_global = combine_batches(test_data_global)
train_data_local_dict = {
cid: combine_batches(train_data_local_dict[cid]) for cid in train_data_local_dict.keys()
}
test_data_local_dict = {cid: combine_batches(test_data_local_dict[cid]) for cid in test_data_local_dict.keys()}
args.batch_size = args_batch_size
dataset = [
train_data_num,
test_data_num,
train_data_global,
test_data_global,
train_data_local_num_dict,
train_data_local_dict,
test_data_local_dict,
class_num,
]
return dataset, class_num | app/fedcv/object_detection/data/data_loader.py | import os
import numpy as np
import torch
from .cityscapes.data_loader import load_partition_data_cityscapes
from .coco.segmentation.data_loader import load_partition_data_coco_segmentation
from .pascal_voc_augmented.data_loader import load_partition_data_pascal_voc
import logging
def load(args):
return load_synthetic_data(args)
def combine_batches(batches):
full_x = torch.from_numpy(np.asarray([])).float()
full_y = torch.from_numpy(np.asarray([])).long()
for (batched_x, batched_y) in batches:
full_x = torch.cat((full_x, batched_x), 0)
full_y = torch.cat((full_y, batched_y), 0)
return [(full_x, full_y)]
def load_synthetic_data(args):
dataset_name = str(args.dataset).lower()
# check if the centralized training is enabled
centralized = True if (args.client_num_in_total == 1 and args.training_type != "cross_silo") else False
# check if the full-batch training is enabled
args_batch_size = args.batch_size
if args.batch_size <= 0:
full_batch = True
args.batch_size = 128 # temporary batch size
else:
full_batch = False
if dataset_name == "cityscapes":
# load cityscapes dataset
(
train_data_num,
test_data_num,
train_data_global,
test_data_global,
data_local_num_dict,
train_data_local_dict,
test_data_local_dict,
class_num,
) = load_partition_data_cityscapes(
dataset=dataset_name,
data_dir=args.data_cache_dir,
partition_method=None,
partition_alpha=None,
client_number=args.client_num_in_total,
batch_size=args.batch_size,
)
elif dataset_name in ["coco_segmentation", "coco"]:
# load coco dataset
(
train_data_num,
test_data_num,
train_data_global,
test_data_global,
data_local_num_dict,
train_data_local_dict,
test_data_local_dict,
class_num,
) = load_partition_data_coco_segmentation(
dataset=dataset_name,
data_dir=args.data_cache_dir,
partition_method=None,
partition_alpha=None,
client_number=args.client_num_in_total,
batch_size=args.batch_size,
)
elif dataset_name in ["pascal_voc", "pascal_voc_augmented"]:
# load pascal voc dataset
(
train_data_num,
test_data_num,
train_data_global,
test_data_global,
data_local_num_dict,
train_data_local_dict,
test_data_local_dict,
class_num,
) = load_partition_data_pascal_voc(
dataset=dataset_name,
data_dir=args.data_cache_dir,
partition_method=None,
partition_alpha=None,
client_number=args.client_num_in_total,
batch_size=args.batch_size,
)
else:
raise ValueError("dataset %s is not supported" % dataset_name)
if centralized:
train_data_local_num_dict = {
0: sum(user_train_data_num for user_train_data_num in train_data_local_num_dict.values())
}
train_data_local_dict = {
0: [batch for cid in sorted(train_data_local_dict.keys()) for batch in train_data_local_dict[cid]]
}
test_data_local_dict = {
0: [batch for cid in sorted(test_data_local_dict.keys()) for batch in test_data_local_dict[cid]]
}
args.client_num_in_total = 1
if full_batch:
train_data_global = combine_batches(train_data_global)
test_data_global = combine_batches(test_data_global)
train_data_local_dict = {
cid: combine_batches(train_data_local_dict[cid]) for cid in train_data_local_dict.keys()
}
test_data_local_dict = {cid: combine_batches(test_data_local_dict[cid]) for cid in test_data_local_dict.keys()}
args.batch_size = args_batch_size
dataset = [
train_data_num,
test_data_num,
train_data_global,
test_data_global,
train_data_local_num_dict,
train_data_local_dict,
test_data_local_dict,
class_num,
]
return dataset, class_num | 0.496338 | 0.341473 |
import torch
import torch.nn as nn
import torch.nn.functional as F
# CTR的LR模型
# 主要是用 用户ID和物品ID,将他们进行onehot
class LR(nn.Module):
"""
user_id, movie_id进行embedding的MLP网络模型
user共6040个,movie共3883个
"""
def __init__(self):
super(LR, self).__init__()
# self.user_id_embed = nn.Embedding(6040, 128)
# self.movie_id_embed = nn.Embedding(3883, 128)
# self.dropout = nn.Dropout(0.3)
self.fc = nn.Linear(9923, 1) # usr_id 和 movie_id onehot后的长度
self.sig = nn.Sigmoid()
# https://zhuanlan.zhihu.com/p/59800597
self.criterion = nn.BCELoss(reduction="mean")
def forward(self, x):
device = x.device.type
batch_data = None
for id in x.cpu().numpy():
us, mv = torch.zeros(6040), torch.zeros(3883)
us[int(id[0])], mv[int(id[1])] = 1, 1
data = torch.cat((us, mv), axis=-1).unsqueeze(dim=0)
if batch_data is None:
batch_data = data
else:
batch_data = torch.cat((batch_data, data), axis=0)
x = batch_data.to(device)
# x = x.float()
# user_embed = self.user_id_embed(x[:, 0].long()) # 必须是long类型
# movie_embed = self.movie_id_embed(x[:, 1].long())
# x = torch.cat((user_embed, movie_embed), axis=-1)
# 可以在这里进行onehot,节省时间
logit = self.fc(x)
output = self.sig(logit)
return torch.cat((1 - output, output), dim=-1)
def cal_loss(self, pred, target):
"""Calculate loss"""
# 这里的pred指sigmoid后的值,即 1/(1+exp(-z))
return self.criterion(pred[:, 1].squeeze(dim=-1), target.float())
class LR_Test(nn.Module):
def __init__(self, features=41, output=5):
super().__init__()
self.features = features
self.output = output
self.fc = nn.Linear(features, self.output)
# 手动全连接层
self.w = nn.Parameter(torch.randn((features, output), requires_grad=True))
# self.register_parameter('w', self.w)
self.b = nn.Parameter(torch.randn((1, output), requires_grad=True))
# self.register_parameter('b', self.b)
print('查看模型参数:', self._parameters, end='\n')
def forward(self, x):
# x = self.fc(x)
x = torch.matmul(x, self.w) + self.b
return torch.sigmoid(x)
if __name__ == '__main__':
x = torch.randn(4, 12)
model = LR_Test(12, 1)
print(model(x)) | models/fedavg/movielens/lr.py | import torch
import torch.nn as nn
import torch.nn.functional as F
# CTR的LR模型
# 主要是用 用户ID和物品ID,将他们进行onehot
class LR(nn.Module):
"""
user_id, movie_id进行embedding的MLP网络模型
user共6040个,movie共3883个
"""
def __init__(self):
super(LR, self).__init__()
# self.user_id_embed = nn.Embedding(6040, 128)
# self.movie_id_embed = nn.Embedding(3883, 128)
# self.dropout = nn.Dropout(0.3)
self.fc = nn.Linear(9923, 1) # usr_id 和 movie_id onehot后的长度
self.sig = nn.Sigmoid()
# https://zhuanlan.zhihu.com/p/59800597
self.criterion = nn.BCELoss(reduction="mean")
def forward(self, x):
device = x.device.type
batch_data = None
for id in x.cpu().numpy():
us, mv = torch.zeros(6040), torch.zeros(3883)
us[int(id[0])], mv[int(id[1])] = 1, 1
data = torch.cat((us, mv), axis=-1).unsqueeze(dim=0)
if batch_data is None:
batch_data = data
else:
batch_data = torch.cat((batch_data, data), axis=0)
x = batch_data.to(device)
# x = x.float()
# user_embed = self.user_id_embed(x[:, 0].long()) # 必须是long类型
# movie_embed = self.movie_id_embed(x[:, 1].long())
# x = torch.cat((user_embed, movie_embed), axis=-1)
# 可以在这里进行onehot,节省时间
logit = self.fc(x)
output = self.sig(logit)
return torch.cat((1 - output, output), dim=-1)
def cal_loss(self, pred, target):
"""Calculate loss"""
# 这里的pred指sigmoid后的值,即 1/(1+exp(-z))
return self.criterion(pred[:, 1].squeeze(dim=-1), target.float())
class LR_Test(nn.Module):
def __init__(self, features=41, output=5):
super().__init__()
self.features = features
self.output = output
self.fc = nn.Linear(features, self.output)
# 手动全连接层
self.w = nn.Parameter(torch.randn((features, output), requires_grad=True))
# self.register_parameter('w', self.w)
self.b = nn.Parameter(torch.randn((1, output), requires_grad=True))
# self.register_parameter('b', self.b)
print('查看模型参数:', self._parameters, end='\n')
def forward(self, x):
# x = self.fc(x)
x = torch.matmul(x, self.w) + self.b
return torch.sigmoid(x)
if __name__ == '__main__':
x = torch.randn(4, 12)
model = LR_Test(12, 1)
print(model(x)) | 0.828072 | 0.485051 |
from itertools import cycle
from string import capwords
from fabric.colors import red, green, blue, magenta, white, yellow
class ColorRow(dict):
"""
Ordered collection of column values.
"""
def __init__(self, table, **kwargs):
super(ColorRow, self).__init__(self)
self.table = table
for column in self.table.columns:
self[column] = kwargs.get(column)
def __str__(self):
"""
Generate a formatted and colored string for this row.
"""
def format_cell(color, item):
column, value = item
width = self.table.column_widths[column]
return color(" {0}".format(value).ljust(1 + width))
# get items in column order
items = [(column, self[column]) for column in self.table.columns]
# format cells with color and length
colors_and_items = zip(cycle(self.table.colors), items)
cells = [format_cell(color, item) for color, item in colors_and_items]
return " ".join(cells)
class ColorTable(object):
"""
Simple row/column table.
"""
DEFAULT_COLORS = [red, green, blue, magenta, white, yellow]
def __init__(self, *columns, **kwargs):
"""
Create a table with fixed columns.
:param columns: *args style list of column names
:param kwargs: additional options, including `sort_key` and `colors`
"""
self.columns = columns
self.sort_key = kwargs.get("sort_key")
self.colors = kwargs.get("colors", ColorTable.DEFAULT_COLORS)
header_cells = dict([(column, capwords(column)) for column in self.columns])
self.header = ColorRow(self, **header_cells)
# initialize column widths based on header
self.column_widths = dict([(column, len(self.header[column])) for column in self.columns])
self.rows = []
@property
def separator(self):
"""
Generate a separator row using current column widths.
"""
cells = dict([(column, "-" * self.column_widths[column]) for column in self.columns])
return ColorRow(self, **cells)
def add(self, **kwargs):
row = ColorRow(self, **kwargs)
# update column widths
for column in self.columns:
self.column_widths[column] = max(self.column_widths[column], len(row[column]))
self.rows.append(row)
def __str__(self):
"""
Generate a colored table.
"""
rows = sorted(self.rows, key=self.sort_key) if self.sort_key else self.rows
return "\n".join(map(str, [self.header, self.separator] + rows))
if __name__ == '__main__':
table = ColorTable("first", "last", sort_key=lambda row: (row["last"], row["first"]))
table.add(first="George", last="Washington")
table.add(first="John", last="Adams")
table.add(first="Thomas", last="Jefferson")
print table | gusset/colortable.py | from itertools import cycle
from string import capwords
from fabric.colors import red, green, blue, magenta, white, yellow
class ColorRow(dict):
"""
Ordered collection of column values.
"""
def __init__(self, table, **kwargs):
super(ColorRow, self).__init__(self)
self.table = table
for column in self.table.columns:
self[column] = kwargs.get(column)
def __str__(self):
"""
Generate a formatted and colored string for this row.
"""
def format_cell(color, item):
column, value = item
width = self.table.column_widths[column]
return color(" {0}".format(value).ljust(1 + width))
# get items in column order
items = [(column, self[column]) for column in self.table.columns]
# format cells with color and length
colors_and_items = zip(cycle(self.table.colors), items)
cells = [format_cell(color, item) for color, item in colors_and_items]
return " ".join(cells)
class ColorTable(object):
"""
Simple row/column table.
"""
DEFAULT_COLORS = [red, green, blue, magenta, white, yellow]
def __init__(self, *columns, **kwargs):
"""
Create a table with fixed columns.
:param columns: *args style list of column names
:param kwargs: additional options, including `sort_key` and `colors`
"""
self.columns = columns
self.sort_key = kwargs.get("sort_key")
self.colors = kwargs.get("colors", ColorTable.DEFAULT_COLORS)
header_cells = dict([(column, capwords(column)) for column in self.columns])
self.header = ColorRow(self, **header_cells)
# initialize column widths based on header
self.column_widths = dict([(column, len(self.header[column])) for column in self.columns])
self.rows = []
@property
def separator(self):
"""
Generate a separator row using current column widths.
"""
cells = dict([(column, "-" * self.column_widths[column]) for column in self.columns])
return ColorRow(self, **cells)
def add(self, **kwargs):
row = ColorRow(self, **kwargs)
# update column widths
for column in self.columns:
self.column_widths[column] = max(self.column_widths[column], len(row[column]))
self.rows.append(row)
def __str__(self):
"""
Generate a colored table.
"""
rows = sorted(self.rows, key=self.sort_key) if self.sort_key else self.rows
return "\n".join(map(str, [self.header, self.separator] + rows))
if __name__ == '__main__':
table = ColorTable("first", "last", sort_key=lambda row: (row["last"], row["first"]))
table.add(first="George", last="Washington")
table.add(first="John", last="Adams")
table.add(first="Thomas", last="Jefferson")
print table | 0.888233 | 0.440529 |
import json
import torch
import pandas as pd
import numpy as np
from pathlib import Path
from itertools import repeat
from collections import OrderedDict
from PIL import Image
from scipy.special import softmax
def stat_cuda(msg):
print('--', msg)
print('allocated: %dM, max allocated: %dM, cached: %dM, max cached: %dM' % (
torch.cuda.memory_allocated() / 1024 / 1024,
torch.cuda.max_memory_allocated() / 1024 / 1024,
torch.cuda.memory_cached() / 1024 / 1024,
torch.cuda.max_memory_cached() / 1024 / 1024
))
def ensure_dir(dirname):
dirname = Path(dirname)
if not dirname.is_dir():
dirname.mkdir(parents=True, exist_ok=False)
def read_json(fname):
fname = Path(fname)
with fname.open('rt') as handle:
return json.load(handle, object_hook=OrderedDict)
def write_json(content, fname):
fname = Path(fname)
with fname.open('wt') as handle:
json.dump(content, handle, indent=4, sort_keys=False)
def inf_loop(data_loader):
""" wrapper function for endless data loader. """
for loader in repeat(data_loader):
yield from loader
def save_image(np_arr, file_path):
img = Image.fromarray(np_arr)
img.save(file_path)
class MetricTracker:
def __init__(self, *keys, writer=None):
self.writer = writer
self._data = pd.DataFrame(index=keys, columns=['total', 'counts', 'average'])
self.reset()
def reset(self):
for col in self._data.columns:
self._data[col].values[:] = 0
def update(self, key, value, n=1):
if self.writer is not None:
self.writer.add_scalar(key, value)
self._data.total[key] += value * n
self._data.counts[key] += n
self._data.average[key] = self._data.total[key] / self._data.counts[key]
def avg(self, key):
return self._data.average[key]
def result(self):
return dict(self._data.average)
class CityscapesMetricTracker:
class_names = [
"road",
"sidewalk",
"building",
"wall",
"fence",
"pole",
"traffic_light",
"traffic_sight",
"vegetation",
"terrain",
"sky",
"person",
"rider",
"car",
"truck",
"bus",
"train",
"motorcycle",
"bicycle"
]
num_classes = len(class_names)
def __init__(self, writer=None, ignore_index=255):
self.writer = writer
class_iou = list(map(lambda x: "class_iou_"+x, self.class_names))
self._data = pd.DataFrame(index=class_iou, columns=['total', 'counts', 'average'])
self.ignore_index = ignore_index
self.conf = np.zeros((self.num_classes, self.num_classes)) # 19class + 1 ignore class
self.reset()
def reset(self):
self.conf = np.zeros((self.num_classes, self.num_classes))
def update(self, outputs, labels):
labels[labels == self.ignore_index] = self.num_classes
outputs = torch.argmax(outputs, dim=1)
conf = self.confusion_for_batch(outputs.view(-1), labels.view(-1))
self.conf = self.conf + conf
def get_iou(self):
if not np.any(self.conf):
return 1.
tp = np.diag(self.conf)
iou_pc = tp / (np.sum(self.conf, 0) + np.sum(self.conf, 1) - tp)
return np.nanmean(iou_pc)
def confusion_for_batch(self, output, target):
pred = output.flatten().detach().cpu().numpy()
target = target.flatten().detach().cpu().numpy()
mask = (target >= 0) & (target < self.num_classes)
hist = np.bincount(
self.num_classes * target[mask].astype(int) +
pred[mask], minlength=self.num_classes ** 2).reshape(self.num_classes, self.num_classes)
return hist
class EarlyStopTracker:
def __init__(self, mode='last', criterion='min', threshold=0.0001, threshold_mode='rel'):
"""
:param mode: str - either 'last' or 'best'
"""
self.mode = mode
if self.mode != 'last' and self.mode != 'best':
raise ValueError('Unsupported type of mode. Expect either "last" or "best" but got: ' + str(self.mode))
self.criterion = criterion
if self.criterion != 'min' and self.criterion != 'max':
raise ValueError('Unsupported type of mode. Expect either "min" or "max" but got: ' + str(self.criterion))
self.threshold = threshold
self.threshold_mode = threshold_mode
self.last = None
self.best = None
self.last_update_success = True
def is_better(self, old_value, new_value):
if old_value is None:
return True
elif self.criterion == 'min':
if self.threshold_mode == 'rel':
threshold_old_value = old_value*(1-self.threshold)
else:
threshold_old_value = old_value - self.threshold
if new_value < threshold_old_value:
return True
return False
else: # max
if self.threshold_mode == 'rel':
threshold_old_value = old_value*(1+self.threshold)
else:
threshold_old_value = old_value + self.threshold
if new_value > threshold_old_value:
return True
return False
def update(self, new_value):
if self.mode == 'best':
old_value = self.best
else:
old_value = self.last
if self.is_better(old_value, new_value):
if self.mode == 'best':
self.best = new_value
self.last = new_value
self.last_update_success = True
return True
else:
self.last = new_value
self.last_update_success = False
return False
def reset(self):
self.last = None
self.best = None
self.last_update_success = True
class ImportanceFilterTracker:
def __init__(self, writer):
self.writer = writer
self.importance_dict = dict()
self.counter = dict()
self.temperature = 1
self.scale_factor = 1e5
def update_importance_list(self, added_gates):
for name, gate_layer in added_gates.items():
self.importance_dict[name] = np.zeros(gate_layer.num_features)
self.counter[name] = 0.
def update(self, new_importance_dict):
for name, vector in new_importance_dict.items():
self.importance_dict[name] += vector
self.counter[name] += 1
def average(self):
result = dict()
for name, vector in self.importance_dict.items():
mean_vector = vector / self.counter[name] * self.scale_factor
sum_importance = np.sum(mean_vector)
result[name] = mean_vector / sum_importance
return result | utils/util.py | import json
import torch
import pandas as pd
import numpy as np
from pathlib import Path
from itertools import repeat
from collections import OrderedDict
from PIL import Image
from scipy.special import softmax
def stat_cuda(msg):
print('--', msg)
print('allocated: %dM, max allocated: %dM, cached: %dM, max cached: %dM' % (
torch.cuda.memory_allocated() / 1024 / 1024,
torch.cuda.max_memory_allocated() / 1024 / 1024,
torch.cuda.memory_cached() / 1024 / 1024,
torch.cuda.max_memory_cached() / 1024 / 1024
))
def ensure_dir(dirname):
dirname = Path(dirname)
if not dirname.is_dir():
dirname.mkdir(parents=True, exist_ok=False)
def read_json(fname):
fname = Path(fname)
with fname.open('rt') as handle:
return json.load(handle, object_hook=OrderedDict)
def write_json(content, fname):
fname = Path(fname)
with fname.open('wt') as handle:
json.dump(content, handle, indent=4, sort_keys=False)
def inf_loop(data_loader):
""" wrapper function for endless data loader. """
for loader in repeat(data_loader):
yield from loader
def save_image(np_arr, file_path):
img = Image.fromarray(np_arr)
img.save(file_path)
class MetricTracker:
def __init__(self, *keys, writer=None):
self.writer = writer
self._data = pd.DataFrame(index=keys, columns=['total', 'counts', 'average'])
self.reset()
def reset(self):
for col in self._data.columns:
self._data[col].values[:] = 0
def update(self, key, value, n=1):
if self.writer is not None:
self.writer.add_scalar(key, value)
self._data.total[key] += value * n
self._data.counts[key] += n
self._data.average[key] = self._data.total[key] / self._data.counts[key]
def avg(self, key):
return self._data.average[key]
def result(self):
return dict(self._data.average)
class CityscapesMetricTracker:
class_names = [
"road",
"sidewalk",
"building",
"wall",
"fence",
"pole",
"traffic_light",
"traffic_sight",
"vegetation",
"terrain",
"sky",
"person",
"rider",
"car",
"truck",
"bus",
"train",
"motorcycle",
"bicycle"
]
num_classes = len(class_names)
def __init__(self, writer=None, ignore_index=255):
self.writer = writer
class_iou = list(map(lambda x: "class_iou_"+x, self.class_names))
self._data = pd.DataFrame(index=class_iou, columns=['total', 'counts', 'average'])
self.ignore_index = ignore_index
self.conf = np.zeros((self.num_classes, self.num_classes)) # 19class + 1 ignore class
self.reset()
def reset(self):
self.conf = np.zeros((self.num_classes, self.num_classes))
def update(self, outputs, labels):
labels[labels == self.ignore_index] = self.num_classes
outputs = torch.argmax(outputs, dim=1)
conf = self.confusion_for_batch(outputs.view(-1), labels.view(-1))
self.conf = self.conf + conf
def get_iou(self):
if not np.any(self.conf):
return 1.
tp = np.diag(self.conf)
iou_pc = tp / (np.sum(self.conf, 0) + np.sum(self.conf, 1) - tp)
return np.nanmean(iou_pc)
def confusion_for_batch(self, output, target):
pred = output.flatten().detach().cpu().numpy()
target = target.flatten().detach().cpu().numpy()
mask = (target >= 0) & (target < self.num_classes)
hist = np.bincount(
self.num_classes * target[mask].astype(int) +
pred[mask], minlength=self.num_classes ** 2).reshape(self.num_classes, self.num_classes)
return hist
class EarlyStopTracker:
def __init__(self, mode='last', criterion='min', threshold=0.0001, threshold_mode='rel'):
"""
:param mode: str - either 'last' or 'best'
"""
self.mode = mode
if self.mode != 'last' and self.mode != 'best':
raise ValueError('Unsupported type of mode. Expect either "last" or "best" but got: ' + str(self.mode))
self.criterion = criterion
if self.criterion != 'min' and self.criterion != 'max':
raise ValueError('Unsupported type of mode. Expect either "min" or "max" but got: ' + str(self.criterion))
self.threshold = threshold
self.threshold_mode = threshold_mode
self.last = None
self.best = None
self.last_update_success = True
def is_better(self, old_value, new_value):
if old_value is None:
return True
elif self.criterion == 'min':
if self.threshold_mode == 'rel':
threshold_old_value = old_value*(1-self.threshold)
else:
threshold_old_value = old_value - self.threshold
if new_value < threshold_old_value:
return True
return False
else: # max
if self.threshold_mode == 'rel':
threshold_old_value = old_value*(1+self.threshold)
else:
threshold_old_value = old_value + self.threshold
if new_value > threshold_old_value:
return True
return False
def update(self, new_value):
if self.mode == 'best':
old_value = self.best
else:
old_value = self.last
if self.is_better(old_value, new_value):
if self.mode == 'best':
self.best = new_value
self.last = new_value
self.last_update_success = True
return True
else:
self.last = new_value
self.last_update_success = False
return False
def reset(self):
self.last = None
self.best = None
self.last_update_success = True
class ImportanceFilterTracker:
def __init__(self, writer):
self.writer = writer
self.importance_dict = dict()
self.counter = dict()
self.temperature = 1
self.scale_factor = 1e5
def update_importance_list(self, added_gates):
for name, gate_layer in added_gates.items():
self.importance_dict[name] = np.zeros(gate_layer.num_features)
self.counter[name] = 0.
def update(self, new_importance_dict):
for name, vector in new_importance_dict.items():
self.importance_dict[name] += vector
self.counter[name] += 1
def average(self):
result = dict()
for name, vector in self.importance_dict.items():
mean_vector = vector / self.counter[name] * self.scale_factor
sum_importance = np.sum(mean_vector)
result[name] = mean_vector / sum_importance
return result | 0.610105 | 0.155431 |
import datetime
import logging
from enum import IntEnum
from functools import wraps
from flask import g, request, jsonify
from plugins.ethpassthrough.database.models import db_session, Project
class ApiError(IntEnum):
MISSING_API_KEY = 1
MISSING_PROJECT_ID = 2
PROJECT_NOT_EXIST = 3
PROJECT_EXPIRED = 4
API_TOKENS_EXCEEDED = 5
MISSING_PAYMENT = 6
API_KEY_DISABLED = 7
def missing_keys():
response = jsonify({
'message': "API_KEY header missing or project-id missing",
'error': ApiError.MISSING_KEYS
})
return response, 401
def project_not_exists():
response = jsonify({
'message': "Bad API_KEY or project-id does not exist",
'error': ApiError.PROJECT_NOT_EXIST
})
return response, 401
def project_expired():
response = jsonify({
'message': "Project has expired",
'error': ApiError.PROJECT_EXPIRED
})
return response, 401
def api_tokens_exceeded():
response = jsonify({
'message': "API calls exceeded!",
'error': ApiError.API_TOKENS_EXCEEDED
})
return response, 401
def api_key_disabled():
response = jsonify({
'message': "API key is disabled",
'error': ApiError.API_KEY_DISABLED
})
return response, 401
def api_error_msg(msg: str, code: ApiError):
response = jsonify({
'message': msg,
'error': code
})
return response, 401
def authenticate(f):
@wraps(f)
def wrapper(*args, **kwargs):
logging.debug('%s %s', request.headers.get('Api-Key'), request.view_args['project_id'])
if 'Api-Key' not in request.headers:
return api_error_msg('Missing Api-Key header', ApiError.MISSING_API_KEY)
if 'project_id' not in request.view_args:
return api_error_msg('Missing project-id in url', ApiError.MISSING_PROJECT_ID)
project_id = request.view_args['project_id']
api_key = request.headers.get('Api-Key')
with db_session:
project = Project.get(name=project_id, api_key=api_key)
if project is None:
return project_not_exists()
if not project.expires:
return api_error_msg('Payment not received yet. Please submit payment or wait until payment confirms',
ApiError.MISSING_PAYMENT)
if datetime.datetime.now() > project.expires or not project.active:
return api_error_msg('Project has expired. Please request a new project and api key',
ApiError.PROJECT_EXPIRED)
if project.used_api_tokens >= project.api_token_count:
return api_tokens_exceeded()
if not project.active:
return api_key_disabled()
g.project = project
return f(*args, **kwargs)
return wrapper | plugins/ethpassthrough/middleware.py |
import datetime
import logging
from enum import IntEnum
from functools import wraps
from flask import g, request, jsonify
from plugins.ethpassthrough.database.models import db_session, Project
class ApiError(IntEnum):
MISSING_API_KEY = 1
MISSING_PROJECT_ID = 2
PROJECT_NOT_EXIST = 3
PROJECT_EXPIRED = 4
API_TOKENS_EXCEEDED = 5
MISSING_PAYMENT = 6
API_KEY_DISABLED = 7
def missing_keys():
response = jsonify({
'message': "API_KEY header missing or project-id missing",
'error': ApiError.MISSING_KEYS
})
return response, 401
def project_not_exists():
response = jsonify({
'message': "Bad API_KEY or project-id does not exist",
'error': ApiError.PROJECT_NOT_EXIST
})
return response, 401
def project_expired():
response = jsonify({
'message': "Project has expired",
'error': ApiError.PROJECT_EXPIRED
})
return response, 401
def api_tokens_exceeded():
response = jsonify({
'message': "API calls exceeded!",
'error': ApiError.API_TOKENS_EXCEEDED
})
return response, 401
def api_key_disabled():
response = jsonify({
'message': "API key is disabled",
'error': ApiError.API_KEY_DISABLED
})
return response, 401
def api_error_msg(msg: str, code: ApiError):
response = jsonify({
'message': msg,
'error': code
})
return response, 401
def authenticate(f):
@wraps(f)
def wrapper(*args, **kwargs):
logging.debug('%s %s', request.headers.get('Api-Key'), request.view_args['project_id'])
if 'Api-Key' not in request.headers:
return api_error_msg('Missing Api-Key header', ApiError.MISSING_API_KEY)
if 'project_id' not in request.view_args:
return api_error_msg('Missing project-id in url', ApiError.MISSING_PROJECT_ID)
project_id = request.view_args['project_id']
api_key = request.headers.get('Api-Key')
with db_session:
project = Project.get(name=project_id, api_key=api_key)
if project is None:
return project_not_exists()
if not project.expires:
return api_error_msg('Payment not received yet. Please submit payment or wait until payment confirms',
ApiError.MISSING_PAYMENT)
if datetime.datetime.now() > project.expires or not project.active:
return api_error_msg('Project has expired. Please request a new project and api key',
ApiError.PROJECT_EXPIRED)
if project.used_api_tokens >= project.api_token_count:
return api_tokens_exceeded()
if not project.active:
return api_key_disabled()
g.project = project
return f(*args, **kwargs)
return wrapper | 0.293607 | 0.038035 |
import cv2
import torch
import random
import torch.utils.data
import torch.optim.lr_scheduler as lr_scheduler
import numpy as np
import scipy.io as scio
import os
import time
from PIL import Image
import model as model
import anchor as anchor
from tqdm import tqdm
import random_erasing
import logging
from ptflops import get_model_complexity_info
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
fx = 475.065948
fy = 475.065857
u0 = 315.944855
v0 = 245.287079
validIndex_train = np.load('./data/hands2017/validIndex.npy')
TrainImgFrames = len(validIndex_train) # 957032
TestImgFrames = 295510
validIndex_test = np.arange(TestImgFrames)
keypointsNumber = 21
cropWidth = 176
cropHeight = 176
batch_size = 32
xy_thres = 100
depth_thres = 150
depth_pixel_ratio = cropHeight / 2 / depth_thres
learning_rate = 0.00035
Weight_Decay = 1e-4
nepoch = 17
downsample = 16
RandCropShift = 5
RandshiftDepth = 1
RandRotate = 180
RandScale = (1.0, 0.5)
randomseed = 12345
random.seed(randomseed)
np.random.seed(randomseed)
torch.manual_seed(randomseed)
save_dir = './result/HANDS2017'
try:
os.makedirs(save_dir)
except OSError:
pass
trainingImageDir = '/home/dejian/Dataset/hands2017/images/'
train_center_file = './data/hands2017/hands2017_center_train.mat'
train_keypoint_file = './data/hands2017/hands2017_keypointsUVD_train.mat'
testingImageDir = '/home/dejian/Dataset/hands2017/frame/images/'
test_center_file = './data/hands2017/hands2017_center_test.mat'
test_keypoint_file = './data/hands2017/hands2017_keypointsUVD_test.mat'
MEAN = np.load('./data/hands2017/hands2017_mean.npy')
STD = np.load('./data/hands2017/hands2017_std.npy')
model_dir = './model/hands2017_resnet50.pth'
result_file = 'result_HANDS2017.txt'
def pixel2world(x, fx, fy, ux, uy):
x[:, :, 0] = (x[:, :, 0] - ux) * x[:, :, 2] / fx
x[:, :, 1] = (x[:, :, 1] - uy) * x[:, :, 2] / fy
return x
def world2pixel(x, fx, fy, ux, uy):
x[:, :, 0] = x[:, :, 0] * fx / x[:, :, 2] + ux
x[:, :, 1] = x[:, :, 1] * fy / x[:, :, 2] + uy
return x
# train
keypointsUVD_train = scio.loadmat(train_keypoint_file)['keypoints3D'].astype(np.float32)
center_train = scio.loadmat(train_center_file)['centre_pixel'].astype(np.float)
centre_train_world = pixel2world(center_train.copy(), fx, fy, u0, v0)
centerlefttop_train = centre_train_world.copy()
centerlefttop_train[:,0,0] = centerlefttop_train[:,0,0]-xy_thres
centerlefttop_train[:,0,1] = centerlefttop_train[:,0,1]+xy_thres
centerrightbottom_train = centre_train_world.copy()
centerrightbottom_train[:,0,0] = centerrightbottom_train[:,0,0]+xy_thres
centerrightbottom_train[:,0,1] = centerrightbottom_train[:,0,1]-xy_thres
train_lefttop_pixel = world2pixel(centerlefttop_train, fx, fy, u0, v0)
train_rightbottom_pixel = world2pixel(centerrightbottom_train, fx, fy, u0, v0)
# test
keypointsUVD_test = np.zeros((TestImgFrames,keypointsNumber,3),dtype=np.float32)
center_test = scio.loadmat(test_center_file)['centre_pixel'].astype(np.float)
centre_test_world = pixel2world(center_test.copy(), fx, fy, u0, v0)
centerlefttop_test = centre_test_world.copy()
centerlefttop_test[:,0,0] = centerlefttop_test[:,0,0]-xy_thres
centerlefttop_test[:,0,1] = centerlefttop_test[:,0,1]+xy_thres
centerrightbottom_test = centre_test_world.copy()
centerrightbottom_test[:,0,0] = centerrightbottom_test[:,0,0]+xy_thres
centerrightbottom_test[:,0,1] = centerrightbottom_test[:,0,1]-xy_thres
test_lefttop_pixel = world2pixel(centerlefttop_test, fx, fy, u0, v0)
test_rightbottom_pixel = world2pixel(centerrightbottom_test, fx, fy, u0, v0)
def transform(img, label, matrix):
'''
img: [H, W] label, [N,2]
'''
img_out = cv2.warpAffine(img,matrix,(cropWidth,cropHeight))
label_out = np.ones((keypointsNumber, 3))
label_out[:,:2] = label[:,:2].copy()
label_out = np.matmul(matrix, label_out.transpose())
label_out = label_out.transpose()
return img_out, label_out
def dataPreprocess(index, img, keypointsUVD, center, mean, std, lefttop_pixel, rightbottom_pixel, xy_thres=100, depth_thres=150, augment=False):
imageOutputs = np.ones((cropHeight, cropWidth, 1), dtype='float32')
labelOutputs = np.ones((keypointsNumber, 3), dtype = 'float32')
if augment:
RandomOffset_1 = np.random.randint(-1*RandCropShift,RandCropShift)
RandomOffset_2 = np.random.randint(-1*RandCropShift,RandCropShift)
RandomOffset_3 = np.random.randint(-1*RandCropShift,RandCropShift)
RandomOffset_4 = np.random.randint(-1*RandCropShift,RandCropShift)
RandomOffsetDepth = np.random.normal(0, RandshiftDepth, cropHeight*cropWidth).reshape(cropHeight,cropWidth)
RandomOffsetDepth[np.where(RandomOffsetDepth < RandshiftDepth)] = 0
RandomRotate = np.random.randint(-1*RandRotate,RandRotate)
RandomScale = np.random.rand()*RandScale[0]+RandScale[1]
matrix = cv2.getRotationMatrix2D((cropWidth/2,cropHeight/2),RandomRotate,RandomScale)
else:
RandomOffset_1, RandomOffset_2, RandomOffset_3, RandomOffset_4 = 0, 0, 0, 0
RandomRotate = 0
RandomScale = 1
RandomOffsetDepth = 0
matrix = cv2.getRotationMatrix2D((cropWidth/2,cropHeight/2),RandomRotate,RandomScale)
new_Xmin = max(lefttop_pixel[index,0,0], 0)
new_Ymin = max(rightbottom_pixel[index,0,1], 0)
new_Xmax = min(rightbottom_pixel[index,0,0], img.shape[1] - 1)
new_Ymax = min(lefttop_pixel[index,0,1], img.shape[0] - 1)
imCrop = img.copy()[int(new_Ymin):int(new_Ymax), int(new_Xmin):int(new_Xmax)]
imgResize = cv2.resize(imCrop, (cropWidth, cropHeight), interpolation=cv2.INTER_NEAREST)
imgResize = np.asarray(imgResize,dtype = 'float32')
imgResize[np.where(imgResize >= center[index][0][2] + depth_thres)] = center[index][0][2]
imgResize[np.where(imgResize <= center[index][0][2] - depth_thres)] = center[index][0][2]
imgResize = (imgResize - center[index][0][2])
imgResize = (imgResize - mean) / std
## label
label_xy = np.ones((keypointsNumber, 2), dtype = 'float32')
label_xy[:,0] = (keypointsUVD[index,:,0].copy() - new_Xmin)*cropWidth/(new_Xmax - new_Xmin)
label_xy[:,1] = (keypointsUVD[index,:,1].copy() - new_Ymin)*cropHeight/(new_Ymax - new_Ymin)
if augment:
imgResize, label_xy = transform(imgResize, label_xy, matrix) ## rotation, scale
imageOutputs[:,:,0] = imgResize
labelOutputs[:,1] = label_xy[:,0]
labelOutputs[:,0] = label_xy[:,1]
# labelOutputs[:,2] = (keypointsUVD[index,:,2] - center[index][0][2]) # Z
labelOutputs[:,2] = (keypointsUVD[index,:,2] - center[index][0][2])*depth_pixel_ratio
imageOutputs = np.asarray(imageOutputs)
imageNCHWOut = imageOutputs.transpose(2, 0, 1) # [H, W, C] --->>> [C, H, W]
imageNCHWOut = np.asarray(imageNCHWOut)
labelOutputs = np.asarray(labelOutputs)
data, label = torch.from_numpy(imageNCHWOut), torch.from_numpy(labelOutputs)
return data, label
###################### Pytorch dataloader #################
class my_dataloader(torch.utils.data.Dataset):
def __init__(self, ImgDir, center, lefttop_pixel, rightbottom_pixel, keypointsUVD, validIndex, augment=False):
self.ImgDir = ImgDir
self.mean = MEAN
self.std = STD
self.center = center
self.lefttop_pixel = lefttop_pixel
self.rightbottom_pixel = rightbottom_pixel
self.keypointsUVD = keypointsUVD
self.xy_thres = xy_thres
self.depth_thres = depth_thres
self.validIndex = validIndex
self.augment = augment
self.randomErase = random_erasing.RandomErasing(probability = 0.5, sl = 0.02, sh = 0.4, r1 = 0.3, mean=[0])
def __getitem__(self, index):
index = self.validIndex[index]
depth = Image.open(self.ImgDir + 'image_D%.8d'%(index+1) + '.png')
depth = np.array(depth)
data, label = dataPreprocess(index, depth, self.keypointsUVD, self.center, self.mean, self.std, \
self.lefttop_pixel, self.rightbottom_pixel, self.xy_thres, self.depth_thres, self.augment)
if self.augment:
data = self.randomErase(data)
return data, label
def __len__(self):
return len(self.center)
train_image_datasets = my_dataloader(trainingImageDir, center_train, train_lefttop_pixel, train_rightbottom_pixel, keypointsUVD_train, validIndex_train, augment=True)
train_dataloaders = torch.utils.data.DataLoader(train_image_datasets, batch_size = batch_size, shuffle = True, num_workers = 8)
test_image_datasets = my_dataloader(testingImageDir, center_test, test_lefttop_pixel, test_rightbottom_pixel, keypointsUVD_test, validIndex_test, augment=False)
test_dataloaders = torch.utils.data.DataLoader(test_image_datasets, batch_size = batch_size, shuffle = False, num_workers = 8)
def train():
net = model.A2J_model(num_classes=keypointsNumber, backbone='resnet50')
net = net.cuda()
post_precess = anchor.A2JProcess(cropHeight, keypointsNumber, downsample)
criterion = anchor.A2JLoss(cropHeight, keypointsNumber, downsample)
optimizer = torch.optim.Adam(net.parameters(), lr=learning_rate, weight_decay=Weight_Decay)
scheduler = lr_scheduler.StepLR(optimizer, step_size=7, gamma=0.2)
logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%Y/%m/%d %H:%M:%S', \
filename=os.path.join(save_dir, 'train.log'), level=logging.INFO)
logging.info('======================================================')
macs, params = get_model_complexity_info(net, (1,cropHeight,cropWidth),as_strings=True,print_per_layer_stat=False)
logging.info('macs=%s, params=%s'%(macs, params))
for epoch in range(nepoch):
net = net.train()
train_loss_add = 0.0
Cls_loss_add = 0.0
Reg_loss_add = 0.0
timer = time.time()
# Training loop
for i, (img, label) in enumerate(train_dataloaders):
torch.cuda.synchronize()
img, label = img.cuda(), label.cuda()
heads = net(img)
optimizer.zero_grad()
Cls_loss, Reg_loss = criterion(heads, label)
loss = Cls_loss + Reg_loss
loss.backward()
optimizer.step()
torch.cuda.synchronize()
train_loss_add = train_loss_add + (loss.item())*len(img)
Cls_loss_add = Cls_loss_add + (Cls_loss.item())*len(img)
Reg_loss_add = Reg_loss_add + (Reg_loss.item())*len(img)
# printing loss info
if i%10 == 0:
print('epoch: ',epoch, ' step: ', i, 'Cls_loss ',Cls_loss.item(), 'Reg_loss ',Reg_loss.item(), ' total loss ',loss.item())
scheduler.step(epoch)
# time taken
torch.cuda.synchronize()
timer = time.time() - timer
timer = timer / TrainImgFrames
print('==> time to learn 1 sample = %f (ms)' %(timer*1000))
train_loss_add = train_loss_add / TrainImgFrames
Cls_loss_add = Cls_loss_add / TrainImgFrames
Reg_loss_add = Reg_loss_add / TrainImgFrames
print('mean train_loss_add of 1 sample: %f, #train_indexes = %d' %(train_loss_add, TrainImgFrames))
print('mean Cls_loss_add of 1 sample: %f, #train_indexes = %d' %(Cls_loss_add, TrainImgFrames))
print('mean Reg_loss_add of 1 sample: %f, #train_indexes = %d' %(Reg_loss_add, TrainImgFrames))
saveNamePrefix = '%s/net_%d_wetD_' % (save_dir, epoch)
torch.save(net.state_dict(), saveNamePrefix + '.pth')
# log
logging.info('Epoch#%d: total loss=%.4f, Cls_loss=%.4f, Reg_loss=%.4f, lr = %.6f'
%(epoch, train_loss_add, Cls_loss_add, Reg_loss_add, scheduler.get_lr()[0]))
def test():
net = model.A2J_model(num_classes=keypointsNumber, backbone='resnet50')
net.load_state_dict(torch.load(model_dir))
net = net.cuda()
net.eval()
post_precess = anchor.A2JProcess(cropHeight, keypointsNumber, downsample)
output = torch.FloatTensor()
torch.cuda.synchronize()
for i, (img, label) in tqdm(enumerate(test_dataloaders)):
with torch.no_grad():
img, label = img.cuda(), label.cuda()
heads = net(img)
pred_keypoints = post_precess(heads)
output = torch.cat([output,pred_keypoints.data.cpu()], 0)
torch.cuda.synchronize()
result = output.cpu().data.numpy()
writeTxt(result, center_test)
def errorCompute(result, target, center):
assert np.shape(result)==np.shape(target), "source has different shape with target"
resultUVD_ = result.copy()
target_ = target.copy()
resultUVD_[:, :, 0] = result[:,:,1]
resultUVD_[:, :, 1] = result[:,:,0]
resultUVD = resultUVD_ # [x, y, z]
center_pixel = center.copy()
centre_world = pixel2world(center.copy(), fx, fy, u0, v0)
centerlefttop = centre_world.copy()
centerlefttop[:,0,0] = centerlefttop[:,0,0]-xy_thres
centerlefttop[:,0,1] = centerlefttop[:,0,1]+xy_thres
centerrightbottom = centre_world.copy()
centerrightbottom[:,0,0] = centerrightbottom[:,0,0]+xy_thres
centerrightbottom[:,0,1] = centerrightbottom[:,0,1]-xy_thres
lefttop_pixel = world2pixel(centerlefttop, fx, fy, u0, v0)
rightbottom_pixel = world2pixel(centerrightbottom, fx, fy, u0, v0)
for i in range(len(result)):
Xmin = max(lefttop_pixel[i,0,0], 0)
Ymin = max(rightbottom_pixel[i,0,1], 0)
Xmax = min(rightbottom_pixel[i,0,0], 320*2 - 1)
Ymax = min(lefttop_pixel[i,0,1], 240*2 - 1)
resultUVD[i,:,0] = resultUVD_[i,:,0]*(Xmax-Xmin)/cropWidth + Xmin # x
resultUVD[i,:,1] = resultUVD_[i,:,1]*(Ymax-Ymin)/cropHeight + Ymin # y
resultUVD[i,:,2] = result[i,:,2] / depth_pixel_ratio + center[i][0][2]
labels = pixel2world(target_, fx, fy, u0, v0)
resultXYD = pixel2world(resultUVD.copy(), fx, fy, u0, v0)
errors = np.sqrt(np.sum((labels - resultXYD) ** 2, axis=2))
return np.mean(errors)
def writeTxt(result, center):
resultUVD_ = result.copy()
resultUVD_[:, :, 0] = result[:,:,1]
resultUVD_[:, :, 1] = result[:,:,0]
resultUVD = resultUVD_ # [x, y, z]
center_pixel = center.copy()
centre_world = pixel2world(center.copy(), fx, fy, u0, v0)
centerlefttop = centre_world.copy()
centerlefttop[:,0,0] = centerlefttop[:,0,0]-xy_thres
centerlefttop[:,0,1] = centerlefttop[:,0,1]+xy_thres
centerrightbottom = centre_world.copy()
centerrightbottom[:,0,0] = centerrightbottom[:,0,0]+xy_thres
centerrightbottom[:,0,1] = centerrightbottom[:,0,1]-xy_thres
lefttop_pixel = world2pixel(centerlefttop, fx, fy, u0, v0)
rightbottom_pixel = world2pixel(centerrightbottom, fx, fy, u0, v0)
for i in range(len(result)):
Xmin = max(lefttop_pixel[i,0,0], 0)
Ymin = max(rightbottom_pixel[i,0,1], 0)
Xmax = min(rightbottom_pixel[i,0,0], 320*2 - 1)
Ymax = min(lefttop_pixel[i,0,1], 240*2 - 1)
resultUVD[i,:,0] = resultUVD_[i,:,0]*(Xmax-Xmin)/cropWidth + Xmin # x
resultUVD[i,:,1] = resultUVD_[i,:,1]*(Ymax-Ymin)/cropHeight + Ymin # y
resultUVD[i,:,2] = result[i,:,2] / depth_pixel_ratio + center[i][0][2]
resultXYD = pixel2world(resultUVD.copy(), fx, fy, u0, v0)
resultReshape = resultXYD.reshape(len(resultXYD), -1)
with open(os.path.join(save_dir, result_file), 'w') as f:
for i in tqdm(range(len(resultReshape))):
f.write('frame/images/' + 'image_D%.8d'%(i+1) + '.png' + '\t')
for j in range(keypointsNumber*3):
f.write(str(resultReshape[i, j])+'\t')
f.write('\n')
f.close()
if __name__ == '__main__':
# train()
test() | src/hands2017.py | import cv2
import torch
import random
import torch.utils.data
import torch.optim.lr_scheduler as lr_scheduler
import numpy as np
import scipy.io as scio
import os
import time
from PIL import Image
import model as model
import anchor as anchor
from tqdm import tqdm
import random_erasing
import logging
from ptflops import get_model_complexity_info
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
fx = 475.065948
fy = 475.065857
u0 = 315.944855
v0 = 245.287079
validIndex_train = np.load('./data/hands2017/validIndex.npy')
TrainImgFrames = len(validIndex_train) # 957032
TestImgFrames = 295510
validIndex_test = np.arange(TestImgFrames)
keypointsNumber = 21
cropWidth = 176
cropHeight = 176
batch_size = 32
xy_thres = 100
depth_thres = 150
depth_pixel_ratio = cropHeight / 2 / depth_thres
learning_rate = 0.00035
Weight_Decay = 1e-4
nepoch = 17
downsample = 16
RandCropShift = 5
RandshiftDepth = 1
RandRotate = 180
RandScale = (1.0, 0.5)
randomseed = 12345
random.seed(randomseed)
np.random.seed(randomseed)
torch.manual_seed(randomseed)
save_dir = './result/HANDS2017'
try:
os.makedirs(save_dir)
except OSError:
pass
trainingImageDir = '/home/dejian/Dataset/hands2017/images/'
train_center_file = './data/hands2017/hands2017_center_train.mat'
train_keypoint_file = './data/hands2017/hands2017_keypointsUVD_train.mat'
testingImageDir = '/home/dejian/Dataset/hands2017/frame/images/'
test_center_file = './data/hands2017/hands2017_center_test.mat'
test_keypoint_file = './data/hands2017/hands2017_keypointsUVD_test.mat'
MEAN = np.load('./data/hands2017/hands2017_mean.npy')
STD = np.load('./data/hands2017/hands2017_std.npy')
model_dir = './model/hands2017_resnet50.pth'
result_file = 'result_HANDS2017.txt'
def pixel2world(x, fx, fy, ux, uy):
x[:, :, 0] = (x[:, :, 0] - ux) * x[:, :, 2] / fx
x[:, :, 1] = (x[:, :, 1] - uy) * x[:, :, 2] / fy
return x
def world2pixel(x, fx, fy, ux, uy):
x[:, :, 0] = x[:, :, 0] * fx / x[:, :, 2] + ux
x[:, :, 1] = x[:, :, 1] * fy / x[:, :, 2] + uy
return x
# train
keypointsUVD_train = scio.loadmat(train_keypoint_file)['keypoints3D'].astype(np.float32)
center_train = scio.loadmat(train_center_file)['centre_pixel'].astype(np.float)
centre_train_world = pixel2world(center_train.copy(), fx, fy, u0, v0)
centerlefttop_train = centre_train_world.copy()
centerlefttop_train[:,0,0] = centerlefttop_train[:,0,0]-xy_thres
centerlefttop_train[:,0,1] = centerlefttop_train[:,0,1]+xy_thres
centerrightbottom_train = centre_train_world.copy()
centerrightbottom_train[:,0,0] = centerrightbottom_train[:,0,0]+xy_thres
centerrightbottom_train[:,0,1] = centerrightbottom_train[:,0,1]-xy_thres
train_lefttop_pixel = world2pixel(centerlefttop_train, fx, fy, u0, v0)
train_rightbottom_pixel = world2pixel(centerrightbottom_train, fx, fy, u0, v0)
# test
keypointsUVD_test = np.zeros((TestImgFrames,keypointsNumber,3),dtype=np.float32)
center_test = scio.loadmat(test_center_file)['centre_pixel'].astype(np.float)
centre_test_world = pixel2world(center_test.copy(), fx, fy, u0, v0)
centerlefttop_test = centre_test_world.copy()
centerlefttop_test[:,0,0] = centerlefttop_test[:,0,0]-xy_thres
centerlefttop_test[:,0,1] = centerlefttop_test[:,0,1]+xy_thres
centerrightbottom_test = centre_test_world.copy()
centerrightbottom_test[:,0,0] = centerrightbottom_test[:,0,0]+xy_thres
centerrightbottom_test[:,0,1] = centerrightbottom_test[:,0,1]-xy_thres
test_lefttop_pixel = world2pixel(centerlefttop_test, fx, fy, u0, v0)
test_rightbottom_pixel = world2pixel(centerrightbottom_test, fx, fy, u0, v0)
def transform(img, label, matrix):
'''
img: [H, W] label, [N,2]
'''
img_out = cv2.warpAffine(img,matrix,(cropWidth,cropHeight))
label_out = np.ones((keypointsNumber, 3))
label_out[:,:2] = label[:,:2].copy()
label_out = np.matmul(matrix, label_out.transpose())
label_out = label_out.transpose()
return img_out, label_out
def dataPreprocess(index, img, keypointsUVD, center, mean, std, lefttop_pixel, rightbottom_pixel, xy_thres=100, depth_thres=150, augment=False):
imageOutputs = np.ones((cropHeight, cropWidth, 1), dtype='float32')
labelOutputs = np.ones((keypointsNumber, 3), dtype = 'float32')
if augment:
RandomOffset_1 = np.random.randint(-1*RandCropShift,RandCropShift)
RandomOffset_2 = np.random.randint(-1*RandCropShift,RandCropShift)
RandomOffset_3 = np.random.randint(-1*RandCropShift,RandCropShift)
RandomOffset_4 = np.random.randint(-1*RandCropShift,RandCropShift)
RandomOffsetDepth = np.random.normal(0, RandshiftDepth, cropHeight*cropWidth).reshape(cropHeight,cropWidth)
RandomOffsetDepth[np.where(RandomOffsetDepth < RandshiftDepth)] = 0
RandomRotate = np.random.randint(-1*RandRotate,RandRotate)
RandomScale = np.random.rand()*RandScale[0]+RandScale[1]
matrix = cv2.getRotationMatrix2D((cropWidth/2,cropHeight/2),RandomRotate,RandomScale)
else:
RandomOffset_1, RandomOffset_2, RandomOffset_3, RandomOffset_4 = 0, 0, 0, 0
RandomRotate = 0
RandomScale = 1
RandomOffsetDepth = 0
matrix = cv2.getRotationMatrix2D((cropWidth/2,cropHeight/2),RandomRotate,RandomScale)
new_Xmin = max(lefttop_pixel[index,0,0], 0)
new_Ymin = max(rightbottom_pixel[index,0,1], 0)
new_Xmax = min(rightbottom_pixel[index,0,0], img.shape[1] - 1)
new_Ymax = min(lefttop_pixel[index,0,1], img.shape[0] - 1)
imCrop = img.copy()[int(new_Ymin):int(new_Ymax), int(new_Xmin):int(new_Xmax)]
imgResize = cv2.resize(imCrop, (cropWidth, cropHeight), interpolation=cv2.INTER_NEAREST)
imgResize = np.asarray(imgResize,dtype = 'float32')
imgResize[np.where(imgResize >= center[index][0][2] + depth_thres)] = center[index][0][2]
imgResize[np.where(imgResize <= center[index][0][2] - depth_thres)] = center[index][0][2]
imgResize = (imgResize - center[index][0][2])
imgResize = (imgResize - mean) / std
## label
label_xy = np.ones((keypointsNumber, 2), dtype = 'float32')
label_xy[:,0] = (keypointsUVD[index,:,0].copy() - new_Xmin)*cropWidth/(new_Xmax - new_Xmin)
label_xy[:,1] = (keypointsUVD[index,:,1].copy() - new_Ymin)*cropHeight/(new_Ymax - new_Ymin)
if augment:
imgResize, label_xy = transform(imgResize, label_xy, matrix) ## rotation, scale
imageOutputs[:,:,0] = imgResize
labelOutputs[:,1] = label_xy[:,0]
labelOutputs[:,0] = label_xy[:,1]
# labelOutputs[:,2] = (keypointsUVD[index,:,2] - center[index][0][2]) # Z
labelOutputs[:,2] = (keypointsUVD[index,:,2] - center[index][0][2])*depth_pixel_ratio
imageOutputs = np.asarray(imageOutputs)
imageNCHWOut = imageOutputs.transpose(2, 0, 1) # [H, W, C] --->>> [C, H, W]
imageNCHWOut = np.asarray(imageNCHWOut)
labelOutputs = np.asarray(labelOutputs)
data, label = torch.from_numpy(imageNCHWOut), torch.from_numpy(labelOutputs)
return data, label
###################### Pytorch dataloader #################
class my_dataloader(torch.utils.data.Dataset):
def __init__(self, ImgDir, center, lefttop_pixel, rightbottom_pixel, keypointsUVD, validIndex, augment=False):
self.ImgDir = ImgDir
self.mean = MEAN
self.std = STD
self.center = center
self.lefttop_pixel = lefttop_pixel
self.rightbottom_pixel = rightbottom_pixel
self.keypointsUVD = keypointsUVD
self.xy_thres = xy_thres
self.depth_thres = depth_thres
self.validIndex = validIndex
self.augment = augment
self.randomErase = random_erasing.RandomErasing(probability = 0.5, sl = 0.02, sh = 0.4, r1 = 0.3, mean=[0])
def __getitem__(self, index):
index = self.validIndex[index]
depth = Image.open(self.ImgDir + 'image_D%.8d'%(index+1) + '.png')
depth = np.array(depth)
data, label = dataPreprocess(index, depth, self.keypointsUVD, self.center, self.mean, self.std, \
self.lefttop_pixel, self.rightbottom_pixel, self.xy_thres, self.depth_thres, self.augment)
if self.augment:
data = self.randomErase(data)
return data, label
def __len__(self):
return len(self.center)
train_image_datasets = my_dataloader(trainingImageDir, center_train, train_lefttop_pixel, train_rightbottom_pixel, keypointsUVD_train, validIndex_train, augment=True)
train_dataloaders = torch.utils.data.DataLoader(train_image_datasets, batch_size = batch_size, shuffle = True, num_workers = 8)
test_image_datasets = my_dataloader(testingImageDir, center_test, test_lefttop_pixel, test_rightbottom_pixel, keypointsUVD_test, validIndex_test, augment=False)
test_dataloaders = torch.utils.data.DataLoader(test_image_datasets, batch_size = batch_size, shuffle = False, num_workers = 8)
def train():
net = model.A2J_model(num_classes=keypointsNumber, backbone='resnet50')
net = net.cuda()
post_precess = anchor.A2JProcess(cropHeight, keypointsNumber, downsample)
criterion = anchor.A2JLoss(cropHeight, keypointsNumber, downsample)
optimizer = torch.optim.Adam(net.parameters(), lr=learning_rate, weight_decay=Weight_Decay)
scheduler = lr_scheduler.StepLR(optimizer, step_size=7, gamma=0.2)
logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%Y/%m/%d %H:%M:%S', \
filename=os.path.join(save_dir, 'train.log'), level=logging.INFO)
logging.info('======================================================')
macs, params = get_model_complexity_info(net, (1,cropHeight,cropWidth),as_strings=True,print_per_layer_stat=False)
logging.info('macs=%s, params=%s'%(macs, params))
for epoch in range(nepoch):
net = net.train()
train_loss_add = 0.0
Cls_loss_add = 0.0
Reg_loss_add = 0.0
timer = time.time()
# Training loop
for i, (img, label) in enumerate(train_dataloaders):
torch.cuda.synchronize()
img, label = img.cuda(), label.cuda()
heads = net(img)
optimizer.zero_grad()
Cls_loss, Reg_loss = criterion(heads, label)
loss = Cls_loss + Reg_loss
loss.backward()
optimizer.step()
torch.cuda.synchronize()
train_loss_add = train_loss_add + (loss.item())*len(img)
Cls_loss_add = Cls_loss_add + (Cls_loss.item())*len(img)
Reg_loss_add = Reg_loss_add + (Reg_loss.item())*len(img)
# printing loss info
if i%10 == 0:
print('epoch: ',epoch, ' step: ', i, 'Cls_loss ',Cls_loss.item(), 'Reg_loss ',Reg_loss.item(), ' total loss ',loss.item())
scheduler.step(epoch)
# time taken
torch.cuda.synchronize()
timer = time.time() - timer
timer = timer / TrainImgFrames
print('==> time to learn 1 sample = %f (ms)' %(timer*1000))
train_loss_add = train_loss_add / TrainImgFrames
Cls_loss_add = Cls_loss_add / TrainImgFrames
Reg_loss_add = Reg_loss_add / TrainImgFrames
print('mean train_loss_add of 1 sample: %f, #train_indexes = %d' %(train_loss_add, TrainImgFrames))
print('mean Cls_loss_add of 1 sample: %f, #train_indexes = %d' %(Cls_loss_add, TrainImgFrames))
print('mean Reg_loss_add of 1 sample: %f, #train_indexes = %d' %(Reg_loss_add, TrainImgFrames))
saveNamePrefix = '%s/net_%d_wetD_' % (save_dir, epoch)
torch.save(net.state_dict(), saveNamePrefix + '.pth')
# log
logging.info('Epoch#%d: total loss=%.4f, Cls_loss=%.4f, Reg_loss=%.4f, lr = %.6f'
%(epoch, train_loss_add, Cls_loss_add, Reg_loss_add, scheduler.get_lr()[0]))
def test():
net = model.A2J_model(num_classes=keypointsNumber, backbone='resnet50')
net.load_state_dict(torch.load(model_dir))
net = net.cuda()
net.eval()
post_precess = anchor.A2JProcess(cropHeight, keypointsNumber, downsample)
output = torch.FloatTensor()
torch.cuda.synchronize()
for i, (img, label) in tqdm(enumerate(test_dataloaders)):
with torch.no_grad():
img, label = img.cuda(), label.cuda()
heads = net(img)
pred_keypoints = post_precess(heads)
output = torch.cat([output,pred_keypoints.data.cpu()], 0)
torch.cuda.synchronize()
result = output.cpu().data.numpy()
writeTxt(result, center_test)
def errorCompute(result, target, center):
assert np.shape(result)==np.shape(target), "source has different shape with target"
resultUVD_ = result.copy()
target_ = target.copy()
resultUVD_[:, :, 0] = result[:,:,1]
resultUVD_[:, :, 1] = result[:,:,0]
resultUVD = resultUVD_ # [x, y, z]
center_pixel = center.copy()
centre_world = pixel2world(center.copy(), fx, fy, u0, v0)
centerlefttop = centre_world.copy()
centerlefttop[:,0,0] = centerlefttop[:,0,0]-xy_thres
centerlefttop[:,0,1] = centerlefttop[:,0,1]+xy_thres
centerrightbottom = centre_world.copy()
centerrightbottom[:,0,0] = centerrightbottom[:,0,0]+xy_thres
centerrightbottom[:,0,1] = centerrightbottom[:,0,1]-xy_thres
lefttop_pixel = world2pixel(centerlefttop, fx, fy, u0, v0)
rightbottom_pixel = world2pixel(centerrightbottom, fx, fy, u0, v0)
for i in range(len(result)):
Xmin = max(lefttop_pixel[i,0,0], 0)
Ymin = max(rightbottom_pixel[i,0,1], 0)
Xmax = min(rightbottom_pixel[i,0,0], 320*2 - 1)
Ymax = min(lefttop_pixel[i,0,1], 240*2 - 1)
resultUVD[i,:,0] = resultUVD_[i,:,0]*(Xmax-Xmin)/cropWidth + Xmin # x
resultUVD[i,:,1] = resultUVD_[i,:,1]*(Ymax-Ymin)/cropHeight + Ymin # y
resultUVD[i,:,2] = result[i,:,2] / depth_pixel_ratio + center[i][0][2]
labels = pixel2world(target_, fx, fy, u0, v0)
resultXYD = pixel2world(resultUVD.copy(), fx, fy, u0, v0)
errors = np.sqrt(np.sum((labels - resultXYD) ** 2, axis=2))
return np.mean(errors)
def writeTxt(result, center):
resultUVD_ = result.copy()
resultUVD_[:, :, 0] = result[:,:,1]
resultUVD_[:, :, 1] = result[:,:,0]
resultUVD = resultUVD_ # [x, y, z]
center_pixel = center.copy()
centre_world = pixel2world(center.copy(), fx, fy, u0, v0)
centerlefttop = centre_world.copy()
centerlefttop[:,0,0] = centerlefttop[:,0,0]-xy_thres
centerlefttop[:,0,1] = centerlefttop[:,0,1]+xy_thres
centerrightbottom = centre_world.copy()
centerrightbottom[:,0,0] = centerrightbottom[:,0,0]+xy_thres
centerrightbottom[:,0,1] = centerrightbottom[:,0,1]-xy_thres
lefttop_pixel = world2pixel(centerlefttop, fx, fy, u0, v0)
rightbottom_pixel = world2pixel(centerrightbottom, fx, fy, u0, v0)
for i in range(len(result)):
Xmin = max(lefttop_pixel[i,0,0], 0)
Ymin = max(rightbottom_pixel[i,0,1], 0)
Xmax = min(rightbottom_pixel[i,0,0], 320*2 - 1)
Ymax = min(lefttop_pixel[i,0,1], 240*2 - 1)
resultUVD[i,:,0] = resultUVD_[i,:,0]*(Xmax-Xmin)/cropWidth + Xmin # x
resultUVD[i,:,1] = resultUVD_[i,:,1]*(Ymax-Ymin)/cropHeight + Ymin # y
resultUVD[i,:,2] = result[i,:,2] / depth_pixel_ratio + center[i][0][2]
resultXYD = pixel2world(resultUVD.copy(), fx, fy, u0, v0)
resultReshape = resultXYD.reshape(len(resultXYD), -1)
with open(os.path.join(save_dir, result_file), 'w') as f:
for i in tqdm(range(len(resultReshape))):
f.write('frame/images/' + 'image_D%.8d'%(i+1) + '.png' + '\t')
for j in range(keypointsNumber*3):
f.write(str(resultReshape[i, j])+'\t')
f.write('\n')
f.close()
if __name__ == '__main__':
# train()
test() | 0.24599 | 0.155527 |
from keras.layers import Input, Dense, Flatten, Reshape
from keras.layers.advanced_activations import LeakyReLU
from keras.layers.convolutional import Conv2D
from keras.models import Model
from keras.optimizers import Adam
from ast import literal_eval
from face_swap.PixelShuffler import PixelShuffler
def conv(filters, kernel_size=5, strides=2):
def block(x):
x = Conv2D(filters, kernel_size=kernel_size,
strides=strides, padding='same')(x)
x = LeakyReLU(0.1)(x)
return x
return block
# deconvolution block used in the decoder
def upscale(filters, kernel_size=3):
def block(x):
x = Conv2D(filters * 4, kernel_size=kernel_size,
padding='same')(x)
x = LeakyReLU(0.1)(x)
x = PixelShuffler()(x)
return x
return block
def Encoder(input_shape, hidden_dim, init_filters=128, num_conv_blocks=4):
model_input = Input(shape=input_shape)
x = model_input
for i in range(num_conv_blocks):
x = conv(init_filters * (2 ** i))(x)
x = Dense(hidden_dim)(Flatten()(x))
x = Dense(4 * 4 * hidden_dim)(x)
x = Reshape((4, 4, hidden_dim))(x)
x = upscale(hidden_dim//2)(x)
return Model(model_input, x)
def Decoder(input_shape, init_filters=256, num_deconv_blocks=3):
model_input = Input(shape=input_shape)
x = model_input
for i in range(num_deconv_blocks):
x = upscale(init_filters // (2 ** i))(x)
x = Conv2D(3, kernel_size=5, padding='same', activation='sigmoid')(x)
return Model(model_input, x)
def get_autoencoders(cfg):
models_path = cfg.get('models_path', None)
IMAGE_SHAPE = literal_eval(cfg.get('img_shape'))
ENCODER_DIM = cfg.get('encoder_dim')
DECODER_INPUT_SHAPE = literal_eval(cfg.get('decoder_input_shape'))
encoder_init_filters = cfg.get('encoder_init_filters')
encoder_nb_conv_blocks = cfg.get('encoder_nb_conv_blocks')
decoder_init_filters = cfg.get('decoder_init_filters')
decoder_nb_conv_blocks = cfg.get('decoder_nb_conv_blocks')
optimizer = Adam(lr=5e-5, beta_1=0.5, beta_2=0.999)
encoder = Encoder(IMAGE_SHAPE, ENCODER_DIM,
init_filters=encoder_init_filters,
num_conv_blocks=encoder_nb_conv_blocks)
decoder_a = Decoder(DECODER_INPUT_SHAPE,
init_filters=decoder_init_filters,
num_deconv_blocks=decoder_nb_conv_blocks)
decoder_b = Decoder(DECODER_INPUT_SHAPE,
init_filters=decoder_init_filters,
num_deconv_blocks=decoder_nb_conv_blocks)
x = Input(shape=IMAGE_SHAPE)
autoencoder_a = Model(x, decoder_a(encoder(x)))
autoencoder_b = Model(x, decoder_b(encoder(x)))
autoencoder_a.compile(optimizer=optimizer, loss='mean_absolute_error')
autoencoder_b.compile(optimizer=optimizer, loss='mean_absolute_error')
if models_path:
print("Loading Autoencoder Models...")
encoder.load_weights(models_path + '/encoder.h5')
decoder_a.load_weights(models_path + '/decoder_A.h5')
decoder_b.load_weights(models_path + '/decoder_B.h5')
print("Autoencoder Models Loaded")
return autoencoder_a, autoencoder_b | face_swap/autoencoder.py | from keras.layers import Input, Dense, Flatten, Reshape
from keras.layers.advanced_activations import LeakyReLU
from keras.layers.convolutional import Conv2D
from keras.models import Model
from keras.optimizers import Adam
from ast import literal_eval
from face_swap.PixelShuffler import PixelShuffler
def conv(filters, kernel_size=5, strides=2):
def block(x):
x = Conv2D(filters, kernel_size=kernel_size,
strides=strides, padding='same')(x)
x = LeakyReLU(0.1)(x)
return x
return block
# deconvolution block used in the decoder
def upscale(filters, kernel_size=3):
def block(x):
x = Conv2D(filters * 4, kernel_size=kernel_size,
padding='same')(x)
x = LeakyReLU(0.1)(x)
x = PixelShuffler()(x)
return x
return block
def Encoder(input_shape, hidden_dim, init_filters=128, num_conv_blocks=4):
model_input = Input(shape=input_shape)
x = model_input
for i in range(num_conv_blocks):
x = conv(init_filters * (2 ** i))(x)
x = Dense(hidden_dim)(Flatten()(x))
x = Dense(4 * 4 * hidden_dim)(x)
x = Reshape((4, 4, hidden_dim))(x)
x = upscale(hidden_dim//2)(x)
return Model(model_input, x)
def Decoder(input_shape, init_filters=256, num_deconv_blocks=3):
model_input = Input(shape=input_shape)
x = model_input
for i in range(num_deconv_blocks):
x = upscale(init_filters // (2 ** i))(x)
x = Conv2D(3, kernel_size=5, padding='same', activation='sigmoid')(x)
return Model(model_input, x)
def get_autoencoders(cfg):
models_path = cfg.get('models_path', None)
IMAGE_SHAPE = literal_eval(cfg.get('img_shape'))
ENCODER_DIM = cfg.get('encoder_dim')
DECODER_INPUT_SHAPE = literal_eval(cfg.get('decoder_input_shape'))
encoder_init_filters = cfg.get('encoder_init_filters')
encoder_nb_conv_blocks = cfg.get('encoder_nb_conv_blocks')
decoder_init_filters = cfg.get('decoder_init_filters')
decoder_nb_conv_blocks = cfg.get('decoder_nb_conv_blocks')
optimizer = Adam(lr=5e-5, beta_1=0.5, beta_2=0.999)
encoder = Encoder(IMAGE_SHAPE, ENCODER_DIM,
init_filters=encoder_init_filters,
num_conv_blocks=encoder_nb_conv_blocks)
decoder_a = Decoder(DECODER_INPUT_SHAPE,
init_filters=decoder_init_filters,
num_deconv_blocks=decoder_nb_conv_blocks)
decoder_b = Decoder(DECODER_INPUT_SHAPE,
init_filters=decoder_init_filters,
num_deconv_blocks=decoder_nb_conv_blocks)
x = Input(shape=IMAGE_SHAPE)
autoencoder_a = Model(x, decoder_a(encoder(x)))
autoencoder_b = Model(x, decoder_b(encoder(x)))
autoencoder_a.compile(optimizer=optimizer, loss='mean_absolute_error')
autoencoder_b.compile(optimizer=optimizer, loss='mean_absolute_error')
if models_path:
print("Loading Autoencoder Models...")
encoder.load_weights(models_path + '/encoder.h5')
decoder_a.load_weights(models_path + '/decoder_A.h5')
decoder_b.load_weights(models_path + '/decoder_B.h5')
print("Autoencoder Models Loaded")
return autoencoder_a, autoencoder_b | 0.945425 | 0.534187 |
import nltk
from pyvi.pyvi import ViTokenizer
import re
import ast
with open('text/acronym.txt', 'r') as f:
acronym = ast.literal_eval(str(f.read()))
def int_to_vn(num):
d = {0: 'không', 1: 'một', 2: 'hai', 3: 'ba', 4: 'bốn', 5: 'năm', 6: 'sáu', 7: 'bảy', 8: 'tám', 9: 'chín', 10: 'mười'}
if num <= 10: return d[num]
if num//1000000000 > 0:
if num % 1000000000 == 0: return int_to_vn(num // 1000000000) + " tỷ"
if num%1000000000 < 10:
return int_to_vn(num//1000000000) + " tỷ không triệu không nghìn không trăm linh "+int_to_vn(num % 1000000000)
if num % 1000000000 < 100:
return int_to_vn(num // 1000000000) + " tỷ không triệu không nghìn không trăm " + int_to_vn(num % 1000000000)
if num % 1000000000 < 1000:
return int_to_vn(num // 1000000000) + " tỷ không triệu không nghìn " + int_to_vn(num % 1000000000)
if num % 1000000000 < 1000000:
return int_to_vn(num // 1000000000) + " tỷ không triệu " + int_to_vn(num % 1000000000)
if num % 1000000000 != 0:
return int_to_vn(num // 1000000000) + " tỷ " + int_to_vn(num % 1000000000)
if num//1000000 > 0:
if num % 1000000 == 0: return int_to_vn(num // 1000000) + " triệu"
if num%1000000 < 10:
return int_to_vn(num//1000000) + " triệu không nghìn không trăm linh "+int_to_vn(num % 1000000)
if num % 1000000 < 100:
return int_to_vn(num // 1000000) + " triệu không nghìn không trăm " + int_to_vn(num % 1000000)
if num % 1000000 < 1000:
return int_to_vn(num // 1000000) + " triệu không nghìn " + int_to_vn(num % 1000000)
if num % 1000000 != 0:
return int_to_vn(num // 1000000) + " triệu " + int_to_vn(num % 1000000)
if num // 1000 > 0:
if num % 1000 == 0: return int_to_vn(num//1000) + " nghìn"
if num%1000 <10:
return int_to_vn(num//1000) + " nghìn không trăm linh "+int_to_vn(num%1000)
if num%1000 <100:
return int_to_vn(num//1000) + " nghìn không trăm "+int_to_vn(num%1000)
if num%1000 != 0:
return int_to_vn(num//1000) + " nghìn "+int_to_vn(num%1000)
if num // 100 > 0:
if num%100 == 0:
return int_to_vn(num // 100) + " trăm"
if num%100 <10:
return int_to_vn(num//100) + " trăm linh " + int_to_vn(num%100)
if num%100 != 0:
return int_to_vn(num//100) + " trăm " + int_to_vn(num%100)
if num // 10 > 0 and num >= 20:
if num%10 != 0:
if num%10 == 5:
return int_to_vn(num//10) + ' mươi lăm'
if num%10 == 1:
return int_to_vn(num//10) + ' mươi mốt'
if num%10 == 4:
return int_to_vn(num//10) + ' mươi tư'
return int_to_vn(num // 10) + ' mươi ' + int_to_vn(num % 10)
return int_to_vn(num//10) + ' mươi'
if num // 10 > 0:
if num == 15:
return 'mười lăm'
return "mười "+ d[num%10]
def _hour(m):
out = m.group(0)
out = out.replace(',', '').replace('.', '').strip().split(':')
check = False
if len(out) == 3:
if int(out[2].strip()) > 0:
check = True
out = out[0] + ' giờ ' + out[1] + ' phút ' + out[2] + ' giây '
else:
out = m.group(0)
out = out.replace(':', ' giờ ')
out = out.replace('00 giờ', '0 giờ')
if check is not True:
out = out.replace('00 phút', '')
out = out.replace('00 giây', '')
out = out.replace('00', '')
return out
def _size(m):
return m.group(0).replace('x', ' nhân ')
def _old(m):
return m.group(0).replace('u', 'u ')
def _g(m):
print('output ', m.group(0))
return m.group(0).replace('g', ' giờ ')
def _hour_minute(m):
out = m.group(0)
end = ''
print('step 2 ', out)
if out[-1]==':':
end = ', '
elif out[-1]=='-':
end = ' đến '
elif out[-1]=='–':
end = ' đến '
out = out[:-1].strip()
out = out.replace('h:', ' giờ ')
out = out.replace('g:', ' giờ ')
out = re.sub(re.compile(r"[0-9]g"), _g, out)
out = out.replace('h', ' giờ ')
out = out.replace(':', ' giờ ')
if out[-1].isdigit():
out = out + ' phút '
elif out[-1] == 'p':
out = out[:-1] + ' phút '
out = out.replace('00 giờ', '0 giờ')
out = out.replace('00 phút', '')
out = out.replace('00', '')
out = out.replace(' 0', ' ')
out = out.replace('-', ' đến ')
out = out.replace('–', ' đến ')
return out + end
def _hour_minute1(m):
print('input ', m.group(0))
output = re.sub(re.compile(r"([0-9]|[0-2][0-9])((\ g\ )|(\ g)|(\ g)|(\ g:\ )|(\ g:)|(g:\ )|(g:)|g)((([0-9]|[0-6][0-9])(p|))|)(:|\.|,|-| -|–| –|\ )"), _hour_minute, m.group(0))
return output
def _bignum(m):
return m.group(0).replace('.', '')
def _float(m):
x = m.group(0).replace('.', '')
x = x.split(',')
output = x[0] + ' phẩy '
if len(x[1]) > 2:
output += ' '.join(list(x[1]))
else: output += x[1]
return output
def _thounsand(m):
return m.group(0).replace('k', ' nghìn').replace('-', ' đến ')
def _m(m):
return m.group(0).replace('m', ' mét ')
def _v(m):
return m.group(0).replace('v', ' vol')
def _weight(m):
return m.group(0).replace('g', ' gam ')
def _volume(m):
return m.group(0).replace('l', ' lít ')
def _ward(m):
return m.group(0).replace('.', ' ').replace(' p ', ' phường ')
def _district(m):
return m.group(0).replace('.', ' ').replace(' q ', ' quận ')
def _city(m):
return m.group(0).replace(' tp.', ' thành phố ').replace(' t.p', ' thành phố ').replace(' tx.', ' thị xã ').replace(' tt.', ' thị trấn ')
def _money(m):
return m.group(0).replace('đ', ' đồng ')
def _split(m):
out = ''
text = m.group(0)
for idx, char in enumerate(text):
if not char.isdigit():
out += char
else:
if char == '0' or len(text[idx:])>2:
out += ' ' + ' '.join(list(text[idx:]))
else:
out += ' ' + text[idx:]
break
return out
def _split2(m): #OnePlus Nord N10 D12345
out1, out2 = '', ''
text = m.group(0).strip()
for idx, char in enumerate(text):
if not char.isdigit():
out1 += char
else:
if char == '0' or len(text[idx:])>2:
out2 += ' ' + ' '.join(list(text[idx:])) #ABC 0123
else:
out2 += ' ' + text[idx:] #ABC 1 2 3
break
if out1 not in ['VOV', 'VOH', 'VTV', 'HTV']:
out1 = ' '.join(list(out1))
return ' '+out1+' '+out2+' '
def _split3(m):
result = ''
for w in list(m.group(0).strip()):
if w.isdigit():
result += ' ' + int_to_vn(int(w))
else: result += ' ' + w
return result + ' '
def _split4(m):
text = m.group()
for i in text:
if not i.isdigit() and i != ' ':
text = text.replace(i, ' ' + i)
break
return text
def _uper(m):
return m.group(0).replace(m.group(0), ' '.join(list(m.group(0))))
def _phone(m):
out = m.group(0).replace('.', '')
return ' '.join(list(out))
def _phone2(m):
out = m.group(0).replace('.', '').strip()
for x in out.split(' '):
if x.isdigit():
out = out.replace(x, ' '.join(list(x)))
return ' '+out+' '
def _no(m):
out = m.group(0).split('.')
return out[0]+' '+int_to_vn(int(out[1]))
def _num(m):
text = str(m.group(0)).split(' ')
result = ''
for id, x in enumerate(text):
if x.isdigit():
if id > 0 and text[id-1] in ['thứ', 'tháng'] and int(x)==4:
result += 'tư '
else:
result+= str(int(x)) + ' '
else: result+=x+' '
return result
def _no(m):
out = m.group(0).split('.')
return out[0]+' '+int_to_vn(int(out[1]))
def _link(m):
out = m.group(0)
out = out.replace('/', ' siệt ' )
out = out.replace('.', ' chấm ')
out = out.replace(':', ' hai chấm ')
out = out.replace('-', ' gạch giữa ')
out = out.replace('vn', 'v n')
out = out.replace('org', 'o r g')
return out
def _mail(m):
out = m.group(0)
out = out.replace('/', ' siệt ')
out = out.replace('.', ' chấm ')
out = out.replace('@', ', a còng, ')
out = out.replace(':', ' hai chấm ')
out = out.replace('olli-ai', 'olli ây ai')
out = out.replace('gmail', 'gờ mail')
return out
def _license_plate(m):
out = ''
for char in m.group(0):
if char.isdigit():
out+=char+' '
else: out+=char
return out
def _roman_num(word):
num = 0
p = False
for x in list(word)[::-1]:
if x == 'i':
if p:
p = False
num -= 1
else: num += 1
elif x == 'v':
num += 5
p = True
elif x == 'x':
num += 10
p = True
return str(num)
def _roman_numerals(m):
out = ''
#print(m.group(0))
compiles = re.compile(r'(x|i|v)+')
for w in nltk.word_tokenize(m.group(0)):
if compiles.match(w) is not None:
out += _roman_num(w) + ' '
else:
out += w + ' '
return out
def _dot(m):
return m.group(0).replace('.', '')
def _dot2(m):
return m.group(0).replace('.', ' ')
def _dot3(m):
x = m.group(0).split('.')
output = x[0] + ' chấm ' + ' '.join(list(x[1]))
return output
def _dot4(m):
return m.group(0).replace('.', ' chấm ')
def _measure(m):
input = m.group(0)
input = input.replace('km2', ' ki lô mét vuông')
input = input.replace('m2', ' mét vuông')
input = input.replace('m3/s', ' mét khối trên giây')
input = input.replace('m3', ' mét khối')
input = input.replace('km/h', ' ki lô mét trên giờ')
input = input.replace('m/s', ' mét trên giây')
input = input.replace('°c', ' độ xê')
input = input.replace('°f', ' độ ép')
input = input.replace('ml', ' mi li lít')
input = input.replace('mg', ' mi li gam')
input = input.replace('cm', ' xen ti mét')
input = input.replace('nm', ' na nô mét')
input = input.replace('mm', ' mi li mét')
input = input.replace('ms', ' mi li giây')
input = input.replace('m³', ' mét khối')
input = input.replace('mw', ' mê ga oát')
input = input.replace('kwh', ' ki lô oát giờ')
input = input.replace('km²', ' ki lô mét vuông')
input = input.replace('km', ' ki lô mét')
input = input.replace('đ/kg', 'đồng trên kí')
input = input.replace('đồng/kg', 'đồng trên kí')
input = input.replace('đồng/km', 'đồng trên kí lô mét')
input = input.replace('kg', ' ki lô gam')
input = input.replace('kw', ' ki lô oát')
input = input.replace('độ c', 'độ xê')
input = input.replace('$', ' đô_la')
input = input.replace('%', ' phần_trăm')
input = input.replace('m²', ' mét vuông')
input = input.replace('mhz', ' mê ga hét')
input = input.replace('khz', ' ki lô hét')
input = input.replace('hz', ' hẹt')
input = input.replace('gb', ' ghi ga bai')
input = input.replace('µm', ' mi rô mét')
input = input.replace('ft', ' feet')
input = input.replace('mmhg', ' mi li mét thủy ngân')
input = input.replace('ha', ' héc ta')
input = input.replace('mah', ' mi li am pe giờ')
input = input.replace('vnđ', ' việt_nam_đồng')
input = input.replace('vnd', ' việt_nam_đồng')
input = input.replace('ndt', ' nhân_dân_tệ')
input = input.replace('€', ' ơ_rô')
input = input.replace('£', 'bản_anh')
return input
def _interval(m):
out = m.group(0).replace('-', ' đến ngày ')
return out
def _ddmmyy(m):
text = m.group(0)
out = ''
if len(text.split('/'))==3:
date = text.split('/')
elif len(text.split('-'))==3:
date = text.split('-')
elif len(text.split('.'))==3:
date = text.split('.')
if int(date[1]) == 4:
out = int_to_vn(int(date[0])) + ' tháng tư năm '+ int_to_vn(int(date[2]))
else:
out = int_to_vn(int(date[0])) + ' tháng ' + int_to_vn(int(date[1])) + ' năm ' + int_to_vn(int(date[2]))
return out + ' '
def _mmyy(m):
text = m.group(0).strip()
end = ''
if text[-1] in ',.?!':
en = text[-1]
text = text[:-1]
out = ''
if len(text.split(' '))>1:
date = text.split(' ')[1]
else: date = text
if len(date.split('/'))==2:
date = date.split('/')
elif len(date.split('-'))==2:
date = date.split('-')
elif len(date.split('.'))==2:
date = date.split('.')
if int(date[0]) == 4:
out = ' tháng tư năm '+ int_to_vn(int(date[1]))
else:
out = ' tháng ' + int_to_vn(int(date[0])) + ' năm ' + int_to_vn(int(date[1]))
return out+end+' '
def _ddmm(m):
text = m.group(0).strip()
end = ''
if text[-1] in ',.?!':
end = text[-1]
text = text[:-1]
out = ''
if len(text.split('/')) == 2:
date = text.split('/')
elif len(text.split('-')) == 2:
date = text.split('-')
elif len(text.split('.')) == 2:
date = text.split('.')
out += ' ' + int_to_vn(int(date[0])) + ' tháng ' + (int_to_vn(int(date[1])) if int(date[1]) != 4 else "tư")
return out+end+' '
def _ddmm1(m):
out = m.group(0).strip()
out = re.sub(re.compile(r'([1-9]|[0-3][0-9])(/|-|\.)((0[1-9]|1[0-2])|[1-9])'), _ddmm, out)
return out
def _days(m):
out = m.group(0)
out = out.replace('-', ' đến ')
out = re.sub(re.compile(r'([0-3][0-9]|[1-9])(/|-|\.)((0[1-9]|1[0-2])|[1-9])(/|-|\.)[1-2][0-9][0-9][0-9]'), _ddmmyy, out)
out = re.sub(re.compile(r'([1-9]|[0-3][0-9])(/|-|\.)((0[1-9]|1[0-2])|[1-9])'), _ddmm, out)
return out+ ' '
def _phay(m):
return m.group(0)+','
def _3G(m):
out = m.group(0)
out = re.sub(re.compile(r'[a-z0-9\+]+'), _phay, out)
return out.replace('3g', 'ba gờ').replace('4g', 'bốn gờ').replace('5g', 'năm gờ')
def _duration(m):
text = m.group(0).split('-')
return text[0]+' đến ngày '+text[1]
def _vi(m):
out = m.group(0)
v = {'/':'trên', 't':'tê', 'g':'giê', 'q':'quy', 'đ':'đê', 'c':'xê', 'p':'pê', 'k':'ca', 'h':'hắc', 'v':'vê', 'b':'bê',}
result = ' '
for c in out:
if c in v:
result += v[c]+' '
return result
def _TW(m):
out = m.group(0)
out = out.replace('-', '')
out = re.sub(re.compile('(/[tgqđcpkhvb][tgqđcpkhvb]+)'), _vi, out)
return out.replace('/', ' trên ')
def _am(m):
out = m.group(0)
out = out.replace('-', 'âm ')
return out
def _name(m):
out = m.group(0)
out = out.replace('m4u', 'em pho du').replace('365', '3 6 5')
return out
def _am_pm(m):
out = m.group(0)
out = out.replace('am', 'sáng')
if out[-2:] == "pm":
h = int(out[:2].strip())
if (h > 12 and h < 18) or (h >= 1 and h < 6):
out = out.replace('pm', 'chiều')
elif (h >= 18 and h < 22) or (h >= 6 and h < 10):
out = out.replace('pm', 'tối')
elif (h >= 22 and h <= 24) or (h >= 10 and h <= 12):
out = out.replace('pm', 'khuya')
return out
def _noun(m):
out = m.group(0)
out = out.replace('\'s', ' is ')
out = out.replace('\'re', ' are ')
return out
def _self(m):
return m.group(0).replace('\'', '')
def _upper(m):
out = m.group(0).strip()
end = ''
if out[-1] in [',','.','?','!', ';', ':']:
end = out[-1]
out = out[:-1].strip()
if out in acronym:
return ' '+acronym[out]+end+' '
out = ' '.join(list(out))
return ' '+out+end+' '
def _space(m):
out = m.group(0)
out = out.replace('-', ' , ')
return out
def _nay(m):
out = m.group(0)
out = out.replace('(', '').replace(')','')
return out
def _AI(m):
out = m.group(0)
out = out.replace('AI', 'ây ai')
return out
def _hyphen(m):
out = m.group(0)
return out.replace(' ', '')
def _fourth(m):
out = m.group(0)
return out.replace('4', ' tư ')
def _part(m):
out = m.group(0)
return out.replace('p', 'phần ')
_alphabet = 'aăâbcdđeêghiklmnoôơpqrstuưvxyfjwz' \
'áắấéếíóốớúứý' \
'àằầèềìòồờùừỳ' \
'ảẳẩẻểỉỏổởủửỷ' \
'ãẵẫẽễĩõỗỡũữỹ' \
'ạặậẹệịọộợụựỵ '
def processSent(sent):
'''
Thể thao 24/7 Hôm nay là 24/7 Địa chỉ là 24/7 24/7/2017 7/2017
24,7 24.700.000 24$ 24% 24x7 24h 23h7 24m 24g 24kg 24ha 24m2 24m3 U19 ()
:param input:
:return:
'''
# Acronym & vocab & number
_characters = '!,.?'
input = re.sub(re.compile(r"(^|\ )(AI)(,|;|:|\?|!|\.|\ |$)"), _AI, sent)
input = re.sub(re.compile(r'(\ )[A-Z]+[0-9]+(\ |\.|,|/|-)'), _split2, ' ' + input + ' ')
input = ' '+ re.sub(re.compile(r"(^|\ )(AI|SE|IS|IPA|US|UK|KRQE|FBI|UAV|UAE|USS|DSCA|AM|CISM|AIoT|COC|TAC|5K|FCA|HoSE|TNHH MTV|ĐĐ.Thích)(,|\.|\?|!|;|:|\ |$)"), _upper, input+' ').lower() + ' '
input = re.sub(re.compile(r"(bks |biển kiểm soát |biển số )[0-9][0-9][a-z][1-9]\ [0-9]+"),_license_plate, input)
input = re.sub(re.compile(r'từ ([0-9]|[0-3][0-9])/([0-9]|[0-1][0-9])((/([1-2][0-9][0-9][0-9]))|)((\ -\ )|(-\ )|(\ -)|(-))([0-9]|[0-3][0-9])/([0-9]|[0-1][0-9])((/([1-2][0-9][0-9][0-9]))|)'), _interval, input)
input = re.sub(re.compile(r'(hôm nay|sáng nay|tối nay|sớm nay|chiều nay|trưa nay|ngày mai|mai)\ (\(([1-9]|[0-3][0-9])(/|-|\.)((0[1-9]|1[0-2])|[1-9])\))'), _nay, input)
input = re.sub(re.compile(r'(nhóm|nhạc|minh vương|dương)(\ )(m4u|365|565)'), _name, input)
input = re.sub(re.compile(r"(he|she|it|you|we|they)\'(s|re)"), _noun, input)
input = re.sub(re.compile(r"\ [a-z]+\'s"), _self, ' '+ input)
input = re.sub(re.compile(r"\(p[0-9]+\)"), _part, input)
input = re.sub(re.compile(r'(quận |thứ |hạng )4(\.|,|\?|!|\ |$)'), _fourth, input)
input = input.replace('i\'m', 'i m')
input = input.replace('i\'d', 'i d')
input = input.replace('p!nk', 'pink')
input = input.replace('*', '')
input = input.replace(';', '.')
input = input.replace('?.', '?') #fix bug split sentence
input = input.replace('!.', '!') #fix bug split sentence
input = input.replace('“', '')
input = input.replace('”', '')
input = input.replace('\"', '')
input = input.replace('\'s', '')
input = input.replace('\'', '')
input = input.replace(')', ',')
input = input.replace('(', ', ')
input = input.replace('″', '')
input = input.replace('’', '')
input = input.replace('‘', '')
input = input.replace('#', '')
input = input.replace('[', '')
input = input.replace(']', '')
#input = input.replace(',...', ', vân vân. ')
input = input.replace('...', '. ')
#input = input.replace(',…', ', vân vân. ')
input = input.replace('…', '. ')
input = input.replace('=', ' bằng ')
input = re.sub(re.compile(r'(,)(\ |,)+'), ', ', input)
input = re.sub(re.compile(r'[0-9][0-9\ ]*(mỗi|từng|chục|trăm|tỷ|nghìn|ngàn|triệu|đồng|đơn vị|đơn vị là|một|hai|ba|bốn|năm|sáu|bảy|tám|chín|mười|mươi|lăm|mốt|\ )*(mm|khz|m3/s|đ/kg|£|mah|€|đồng/kg|đồng/km|kg|ha|mmhg|vnđ|ndt|vnd|µm|ft|m/s|km/h|gb|hz|mhz|m²|độ c|\$|%|km²|km|m³|ms|kwh|mw|mg|cm|°f|°c|m2|km2|m3|ml|l|kw|mm|nm)[/\ ,.?!-]'), _measure, input+' ')
input = re.sub(re.compile(r'(quyết định|nghị định|thông tư|văn bản|nghị định|số)(\ )([0-9][0-9/]*[tgqđcpkhvb][tgqđcpkhvb\-]*)'), _TW, input)
input = re.sub(re.compile(r'(^|\ )\-[0-9]+'), _am, input)
input = re.sub(re.compile(r'(\ )[a-zđ]+[0-9]+(\ |\.|,|/|-)'), _split, ' ' + input + ' ')
input = re.sub(re.compile(r'(www.|http://|https://|)[a-z0-9\.\-]+@(gmail|yahoo|outlook|olli-ai)(\.com|\.vn|\.edu)+'), _mail, input)
input = re.sub(re.compile(r'(www.|http://|https://|)[a-z0-9\.\-]+(\.com|\.vn|\.edu|\.org|\.net)+'), _link, input)
input = re.sub(re.compile(r"(thế kỉ|thứ|giải|hạng|bsck|quý|khóa|khoá|khoa|tầng|chương|mục|phần|nhóm|đại hội|tk|đệ|thế chiến|cấp|kỳ|kì|kỷ)\ [ivx]+[\ .,/-]"),_roman_numerals, input)
input = re.sub(re.compile(r'[1-9][0-9\ ]*x((\ |)*[1-9][0-9]*)[\ .,-/]'), _size, input+' ')
#print('in ', input)
input = re.sub(re.compile(r"(lúc|từ|khoảng|đến|tới|vào|hồi)\ ([1-9]|[0-2][0-9])((\ :\ )|(\ :)|(:\ )|:)(([0-6][0-9]|[1-9])|)((((\ :\ )|(\ :)|(:\ )|:)([0-6][0-9]|[1-9])){1,2})(\ |\.|,|-||–| –|)"), _hour, input + ' ')
#print('out ', input)
input = re.sub(re.compile(r"([0-9]|[0-2][0-9])((\ h\ )|(h\ )|(\ h)|(\ h:\ )|(\ h:)|(h:\ )|(h:)|h)((([0-9]|[0-6][0-9])(p|))|)(:|\.|,|-| -|–| –|\ )"), _hour_minute, input.strip()+' ')
input = re.sub(re.compile(r"([0-9]|[0-2][0-9])((\ :\ )|(\ :)|(:\ )|:)([0-9]|[0-6][0-9])(p|)(:|\.|,|-| -|–| –|\ )"), _hour_minute, input.strip()+' ')
#print(input)
input = re.sub(re.compile(r"(lúc|từ|đến|tới|vào|hồi)\ ([0-9]|[0-2][0-9])((\ g\ )|(\ g)|(\ g)|g)(\.|,|-| -|–| –|\ )"), _hour_minute1, input+' ')
#print(input)
input = re.sub(re.compile(r"([0-9]|[0-2][0-9])((\ g\ )|(\ g)|(\ g)|g)((([0-9]|[0-6][0-9])(p|)))(\.|,|-| -|–| –|\ )"), _hour_minute, input+' ')
print(input)
input = re.sub(re.compile(r"([0-9]|[0-2][0-9])((\ g:\ )|(\ g:)|(\ g:)|g:)((([0-9]|[0-6][0-9])(p|))|)(:|\.|,|-| -|–| –|\ )"), _hour_minute, input+' ')
#print(input)
input = re.sub(re.compile(r"(khoảng\ )([0-9]|[0-2][0-9])((\ g\ )|(\ g)|(g\ )|(\ g:\ )|(\ g:)|(g:\ )|(g:)|g)((([0-9]|[0-6][0-9])(p|))|)(\ )(một lần|mỗi ngày|hàng ngày|cùng ngày|ngày|trưa|tối|sáng|rạng sáng|buổi)"), _hour_minute1, input+' ')
input = re.sub(re.compile(r'[0-9][0-9\ ]*k[/\ .,-]'), _thounsand, input)
input = re.sub(re.compile(r'\ ((p(\ )[0-9]{1,2})|(p\.(\ )*([0-9]{1,2}|[a-zđ]{1,})))'), _ward, ' ' + input)
input = re.sub(re.compile(r'\ ((q(\ )[0-9]{1,2})|(q\.(\ )*([0-9]{1,2}|[a-zđ]{1,})))'), _district, ' ' + input)
input = re.sub(re.compile(r'\ (tp\.|t\.p\ |tp\. |tt\.|tx\.|tt\. |tx\. )[đâơôa-z]'), _city, ' '+ input)
input = re.sub(re.compile(r'\ [1-9][0-9][0-9]\.([0-9][0-9][0-9]\.)*[0-9][0-9][0-9]\ '), _bignum, ' '+input)
input = re.sub(re.compile(r'[0-9][0-9\ ]+đ[/\ .,-]'), _money, input+' ')
input = re.sub(re.compile(r'\ ([a-z0-9\+]+|dung lượng|tài khoản|gói cước|sim|lưu lượng|đăng ký|nạp tiền|gia hạn|mạng|dịch vụ|sử dụng|truy cập|kết nối)\ (là |)(3|4|5)g[\ \.,-?!]'), _3G, ' ' + input + ' ')
input = re.sub(re.compile(r'[0-9][0-9\ ]*g[/\ .,-]'), _weight, input + ' ')
input = re.sub(re.compile(r'[0-9][0-9\ ]*l[/\ .,-]'), _volume, input + ' ')
input = re.sub(re.compile(r'[0-9][0-9\ ]*m[\ .,-]'), _m, input + ' ')
input = re.sub(re.compile(r'[0-9][0-9\ ]*v[\ .,-]'), _v, input + ' ')
input = re.sub(re.compile(r'((no|vol)\.)(\ |)[0-9]{1,2}'), _no, input)
input = re.sub(re.compile(r'(ngày|đêm|tối|sáng|trưa|chiều|từ)\ (([1-9]|[0-3][0-9]))((\ |)(-|và|đến|tới)(\ |))(((([0-3][0-9]|[1-9])(/|\.)((0[1-9]|1[0-2])|[1-9])(/|\.)[1-2][0-9][0-9][0-9]))|(([1-9]|[0-3][0-9])(/|\.|-)(0[1-9]|1[0-2]|[1-9])))'),_days, input + ' ')
input = re.sub(re.compile(r'từ ([1-9]|[0-3][0-9])(/|\.)((0[1-9]|1[0-2])|[1-9])(\ |,|;|\.)'), _ddmm1, input)
# 8/9/2018, 8-9-2018, 8.9.2018
input = re.sub(re.compile(r'([0-3][0-9]|[1-9])/((0[1-9]|1[0-2])|[1-9])/[1-2][0-9][0-9][0-9]'), _ddmmyy, input)
input = re.sub(re.compile(r'([0-3][0-9]|[1-9])\.((0[1-9]|1[0-2])|[1-9])\.[1-2][0-9][0-9][0-9]'), _ddmmyy, input)
input = re.sub(re.compile(r'([0-3][0-9]|[1-9])-((0[1-9]|1[0-2])|[1-9])-[1-2][0-9][0-9][0-9]'), _ddmmyy, input)
# # 9.2018, 9-2018, 9/2018, ngày 7-9, 14-9, 21-8
input = re.sub(re.compile(r'tháng\ ((0[1-9]|1[0-2])|[1-9])(/|\.|-)[1-2][0-9][0-9][0-9]'), _mmyy, input + ' ')
input = re.sub(re.compile(r'\ ((0[1-9]|1[0-2])|[1-9])(/|\.|-)[1-2][0-9][0-9][0-9](\ |\.|,)'), _mmyy, input + ' ')
input = re.sub(re.compile(r'(([0-9]|[0-2][0-9])(\ giờ)((\ ([0-9]|[0-6][0-9]) phút)|\ ([0-9]|[0-6][0-9])|)((\ ([0-9]|[0-6][0-9]) giây)|))(\ )(am|pm)'), _am_pm, input)
input = input.replace(':', ', ')
out =''
words = ViTokenizer.tokenize(input)
words = words.replace(' & ', '&')
words = re.sub(re.compile(r'[0-9](\ )*\-(\ )*[0-9]'), _hyphen, words)
words = words.replace(' .', '.')
words = words.replace('thứ hai', 'thứ_hai')
words = words.replace('thứ ba', 'thứ_ba')
words = words.replace('thứ tư', 'thứ_tư')
words = words.replace('thứ năm', 'thứ_năm')
words = words.replace('thứ sáu', 'thứ_sáu')
words = words.replace('thứ bảy', 'thứ_bảy')
words = words.replace('thứ 2 ', 'thứ_hai ')
words = words.replace('thứ 3 ', 'thứ_ba ')
words = words.replace('thứ 4 ', 'thứ_tư ')
words = words.replace('thứ 5 ', 'thứ_năm ')
words = words.replace('thứ 6 ', 'thứ_sáu ')
words = words.replace('thứ 7 ', 'thứ_bảy ')
words = words.replace('chủ nhật', 'chủ_nhật')
words = words.replace('số nhà', 'số_nhà')
words = words.replace('giổ tổ', 'giổ_tổ')
dates = ['thứ_hai','thứ_ba','thứ_tư','thứ_năm','thứ_sáu','thứ_bảy','chủ_nhật', 'thứ_2', 'thứ_3', 'thứ_4', 'thứ_5', 'thứ_6', 'giổ_tổ', 'mùng',
'ngày', 'tháng', 'sáng', 'trưa', 'chiều','tối', 'qua', 'mai', 'đêm', 'vào', 'khủng_bố', 'sự_kiện',
'khuya', 'hôm', 'quốc_khánh', 'lễ', 'thiếu_nhi', 'việt_nam', 'nay', 'đến', 'phiên', 'hôm_nay', 'ngày_mai']
spec_day = ['2/9','8/3', '3/2', '20/11', '30/4', '1/5', '10/3', '27/7', '22/12']
address = ['địa_chỉ', 'hẻm', 'số_nhà', 'ngõ', 'đường']
for id, word in enumerate(words.split(' ')):
if word in spec_day or (id > 0 and (words.split(' ')[id - 1] in dates) and word[0].isdigit()):
end = ''
if word[-1] == '.' or word[-1] ==',':
end = word[-1]
word = word[:-1]
word = re.sub(re.compile(r'([1-9]|[0-3][0-9])-([1-9]|[0-3][0-9])(/|\.)((0[1-9]|1[0-2])|[1-9])'), _duration, word)
word = re.sub(re.compile(r'([1-9]|[0-3][0-9])(/|-|\.)((0[1-9]|1[0-2])|[1-9])'), _ddmm, word)
out += word.strip() + end + ' '
elif len(word.split('/')) > 1:
for id1, w in enumerate(word.split('/')):
if w.isdigit():
if id1 != len(word.split('/')) - 1 and words.split(' ')[id - 1] in address:
out += int_to_vn(int(w)) + ' siệt '
elif id1 != len(word.split('/')) - 1 and words.split(' ')[id - 1] not in address:
out += int_to_vn(int(w)) + ' trên '
else:
out += int_to_vn(int(w)) + ' '
else:
if id1 != len(word.split('/')) - 1:
out += w + ' trên '
else:
out += w + ' '
elif len(word) >2 and len(word.split('-')) == 2 and word.split('-')[0][0].isdigit() and word.split('-')[1][0].isdigit():
if id - 1 >= 0 and words.split(' ')[id - 1] in ['từ', 'khoảng', 'tầm' , 'ngày']:
word = word.replace('-', ' đến ')
out += word+' '
else:
word = re.sub(re.compile(r'[0-9][0-9\.]*\,[0-9]+'), _float, ' ' + word + ' ')
word = word.strip()
end = ''
if len(word) > 0 and word[-1] in _characters and word not in ['mr.']:
end = word[-1]
word = word[:-1]
if word in acronym:
word = acronym[word]
out += word + end + ' '
tokens = ViTokenizer.tokenize(out.strip())
tokens = tokens.replace('_', ' ')
tokens = tokens.replace('/', ' ')
tokens = tokens.replace('\\', ' ')
tokens = tokens.replace(', ,', ' , ')
tokens = tokens.replace('&', ' và ')
tokens = tokens.replace('+', ' cộng ')
tokens = tokens.replace('giờ 00', ' giờ ')
tokens = re.sub(re.compile(r'[0-9]+-[0-9]+'), _space, tokens)
tokens = tokens.replace(' - ', ' , ')
tokens = tokens.replace('-', ' ')
tokens = tokens.replace(' –', ' ')
tokens = tokens.replace('– ', ' ')
tokens = re.sub(re.compile(r'\ [0-9][0-9\.]*\,[0-9]+'), _float, ' ' + tokens + ' ')
tokens = re.sub(re.compile(r'[0-9]+(\.[0-9]{3})+[\ \.,?!]'), _dot, tokens+' ')
tokens = re.sub(re.compile(r'[0-9]+(\.)0[0-9]*'), _dot3, tokens)
tokens = re.sub(re.compile(r'[0-9]+((\.)[0-9]+)+'), _dot4, tokens)
tokens = re.sub(re.compile(r"\ (tổng đài|liên hệ|số điện thoại)(\ )*(1800|1900|0)[0-9\.\ ]+"), _phone2, tokens)
tokens = re.sub(re.compile(r"(\ )*(ngày|tháng|số|thứ)(\ )*([0-9]+)"), _num, tokens)
tokens = re.sub(re.compile(r"\ (0|\+8)[0-9\.]{8,9}"), _phone, tokens)
tokens = re.sub(re.compile(r"\ [0-9]+[a-zđ\-]+(\ |\.|,)"), _split4, tokens)
tokens = re.sub(re.compile(r'[a-zđ](\.[a-zđ])+'), _dot2, tokens)
result = ''
for token in tokens.split(' '):
if token.isdigit():
result += int_to_vn(int(token))+ ' '
elif token in _characters:
result = result[:-1] + token + ' '
elif token in acronym:
result += acronym[token] + ' '
elif token != '':
result += token + ' '
result = re.sub(re.compile(r'\ ([bcdđghklmnpqrstvxfjwz0-9]{2,})+[\ \.,?!]'), _split3, ' ' + result + ' ')
result = re.sub(re.compile(r'\ ([aeoyiu]+[0-9]+)([bcdđghklmnpqrstvxfjwz]+|)[\ \.,?!]'), _split3, ' ' + result + ' ')
result = result.replace('_',' ').strip()
result = ' '.join([x for x in result.split(' ') if x != ''])
if len(result) >= 1 and result[-1] not in _characters:
result = result + '.'
return result.strip()
#print(processSent("biện pháp 5K trốn tìm Đen, MTV, cty TNHH MTV olli"))
stop_word = [
'và', 'sau_khi', 'khi', 'bởi', 'vì_sao', 'điều_này', 'cho_rằng',
'rằng', 'nếu', 'vì', 'lúc_này', 'khi_đó', 'nên', 'cũng_như', 'mà', 'tại_sao',
'lúc', 'vậy', 'tại_sao', 'một_cách', 'đến_nỗi', 'bởi_vì',
'do_đó', 'do', 'sau_đó', 'đó_là', 'thế_nhưng', 'tại', 'thì', 'hoặc', 'với',
'tất_nhiên', 'đương_nhiên', 'thay_vì', 'vì_vậy', 'giả_sử', 'giá_như', 'nhưng',
'may_mà', 'thế_mà', 'tuy', 'rằng', 'mặc_dù', 'hễ', 'hèn_chi', 'so_với',
'huống_chi', 'huống_hồ', 'vả_lại', 'họa_chăng', 'kẻo', 'kẻo_mà', 'kẻo_nữa',
'hèn_chi', 'hèn_gì', 'thảo_nào', 'để', 'giả_sử', 'ví_như', 'dường_như', 'dẫu', 'tuy',
'ví_như', 'tuy_rằng', 'thế_mà', 'mà', 'vậy_mà', 'thế_mà', 'dẫu', 'thì', 'huống_hồ', 'biết_đâu', 'quả nhiên',
'bởi_vậy', 'thành_thử', 'còn_như', 'kẻo_lại', 'vậy_mà',
'thế_thì', 'huống_là', 'hay_là', 'miễn_là', 'dù', 'như_vậy', 'đến_khi', 'cho_đến', 'đến_nỗi',
'trong_khi', 'trong_lúc', 'thảo_nào', 'trong', 'dẫn_đến', 'bao_gồm', 'sau_đó',
]
def pretokenize(doc):
doc = doc.replace('sau khi', 'sau_khi')
doc = doc.replace('tại sao', 'tại_sao')
doc = doc.replace('so với', 'so_với')
doc = doc.replace('bởi vậy', 'bởi_vậy')
doc = doc.replace('thành thử', 'thành_thử')
doc = doc.replace('còn như', 'còn_như')
doc = doc.replace('kẻo lại', 'kẻo_lại')
doc = doc.replace('vậy mà', 'vậy_mà')
doc = doc.replace('huống là', 'huống_là')
doc = doc.replace('hay là', 'hay_là')
doc = doc.replace('miễn là', 'miễn_là')
doc = doc.replace('cho đến', 'cho_đến')
doc = doc.replace('đến khi', 'đến_khi')
doc = doc.replace('đến nổi', 'đến_nổi')
doc = doc.replace('trong khi', 'trong_khi')
doc = doc.replace('trong lúc', 'trong_lúc')
doc = doc.replace('dẫn đến', 'dẫn_đến')
doc = doc.replace('cho rằng', 'cho_rằng')
doc = doc.replace('một cách', 'một_cách')
doc = doc.replace('điều này', 'điều_này')
doc = doc.replace('cũng như', 'cũng_như')
doc = doc.replace('sau đó', 'sau_đó')
return doc
def split(doc):
max_len=35
sent_list = nltk.sent_tokenize(doc)
out_list = []
for sent in sent_list:
if len(sent.split(' ')) <= max_len:
out_list.append(sent)
else:
clause = re.split(", |\?|!|,|\.", sent)
for seq in clause:
word_list = seq.split(' ')
if len(word_list)<=max_len:
out_list.append(seq)
else:
chk = ViTokenizer.tokenize(seq)
chk = pretokenize(chk).split()
start = 0
for index, token in enumerate(chk):
if token in stop_word and index != len(chk)-1:
out_list.append(' '.join(chk[start:index]).replace('_', ' '))
start = index
elif index == len(chk)-1:
out_list.append(' '.join(chk[start:index+1]).replace('_', ' '))
return out_list
def split1(doc):
max_len=35
sent_list = nltk.sent_tokenize(doc)
out_list = []
for sent in sent_list:
sent = sent.strip()
if len(sent.split(' ')) <= max_len:
out_list.append(sent)
else:
p_list = []
clause = re.split(", |\?|!|,", sent)
for seq in clause:
word_list = seq.strip().split(' ')
if len(word_list)<=max_len:
p_list.append(seq)
else:
chk = ViTokenizer.tokenize(seq)
chk = pretokenize(chk).split()
start = 0
for index, token in enumerate(chk):
if token in stop_word and index != len(chk)-1:
p_list.append(' '.join(chk[start:index]).replace('_', ' '))
start = index
elif index == len(chk)-1:
p_list.append(' '.join(chk[start:index+1]).replace('_', ' '))
p_list = [x.strip() for x in p_list if x != '']
part = partition(p_list)
text_split = sent.split(' ')
text_split = [x.strip() for x in text_split if x != '']
id = 0
for i in part:
out_list.append(' '.join(text_split[id:(id+i)]))
id +=i
return out_list | text_normalization.py | import nltk
from pyvi.pyvi import ViTokenizer
import re
import ast
with open('text/acronym.txt', 'r') as f:
acronym = ast.literal_eval(str(f.read()))
def int_to_vn(num):
d = {0: 'không', 1: 'một', 2: 'hai', 3: 'ba', 4: 'bốn', 5: 'năm', 6: 'sáu', 7: 'bảy', 8: 'tám', 9: 'chín', 10: 'mười'}
if num <= 10: return d[num]
if num//1000000000 > 0:
if num % 1000000000 == 0: return int_to_vn(num // 1000000000) + " tỷ"
if num%1000000000 < 10:
return int_to_vn(num//1000000000) + " tỷ không triệu không nghìn không trăm linh "+int_to_vn(num % 1000000000)
if num % 1000000000 < 100:
return int_to_vn(num // 1000000000) + " tỷ không triệu không nghìn không trăm " + int_to_vn(num % 1000000000)
if num % 1000000000 < 1000:
return int_to_vn(num // 1000000000) + " tỷ không triệu không nghìn " + int_to_vn(num % 1000000000)
if num % 1000000000 < 1000000:
return int_to_vn(num // 1000000000) + " tỷ không triệu " + int_to_vn(num % 1000000000)
if num % 1000000000 != 0:
return int_to_vn(num // 1000000000) + " tỷ " + int_to_vn(num % 1000000000)
if num//1000000 > 0:
if num % 1000000 == 0: return int_to_vn(num // 1000000) + " triệu"
if num%1000000 < 10:
return int_to_vn(num//1000000) + " triệu không nghìn không trăm linh "+int_to_vn(num % 1000000)
if num % 1000000 < 100:
return int_to_vn(num // 1000000) + " triệu không nghìn không trăm " + int_to_vn(num % 1000000)
if num % 1000000 < 1000:
return int_to_vn(num // 1000000) + " triệu không nghìn " + int_to_vn(num % 1000000)
if num % 1000000 != 0:
return int_to_vn(num // 1000000) + " triệu " + int_to_vn(num % 1000000)
if num // 1000 > 0:
if num % 1000 == 0: return int_to_vn(num//1000) + " nghìn"
if num%1000 <10:
return int_to_vn(num//1000) + " nghìn không trăm linh "+int_to_vn(num%1000)
if num%1000 <100:
return int_to_vn(num//1000) + " nghìn không trăm "+int_to_vn(num%1000)
if num%1000 != 0:
return int_to_vn(num//1000) + " nghìn "+int_to_vn(num%1000)
if num // 100 > 0:
if num%100 == 0:
return int_to_vn(num // 100) + " trăm"
if num%100 <10:
return int_to_vn(num//100) + " trăm linh " + int_to_vn(num%100)
if num%100 != 0:
return int_to_vn(num//100) + " trăm " + int_to_vn(num%100)
if num // 10 > 0 and num >= 20:
if num%10 != 0:
if num%10 == 5:
return int_to_vn(num//10) + ' mươi lăm'
if num%10 == 1:
return int_to_vn(num//10) + ' mươi mốt'
if num%10 == 4:
return int_to_vn(num//10) + ' mươi tư'
return int_to_vn(num // 10) + ' mươi ' + int_to_vn(num % 10)
return int_to_vn(num//10) + ' mươi'
if num // 10 > 0:
if num == 15:
return 'mười lăm'
return "mười "+ d[num%10]
def _hour(m):
out = m.group(0)
out = out.replace(',', '').replace('.', '').strip().split(':')
check = False
if len(out) == 3:
if int(out[2].strip()) > 0:
check = True
out = out[0] + ' giờ ' + out[1] + ' phút ' + out[2] + ' giây '
else:
out = m.group(0)
out = out.replace(':', ' giờ ')
out = out.replace('00 giờ', '0 giờ')
if check is not True:
out = out.replace('00 phút', '')
out = out.replace('00 giây', '')
out = out.replace('00', '')
return out
def _size(m):
return m.group(0).replace('x', ' nhân ')
def _old(m):
return m.group(0).replace('u', 'u ')
def _g(m):
print('output ', m.group(0))
return m.group(0).replace('g', ' giờ ')
def _hour_minute(m):
out = m.group(0)
end = ''
print('step 2 ', out)
if out[-1]==':':
end = ', '
elif out[-1]=='-':
end = ' đến '
elif out[-1]=='–':
end = ' đến '
out = out[:-1].strip()
out = out.replace('h:', ' giờ ')
out = out.replace('g:', ' giờ ')
out = re.sub(re.compile(r"[0-9]g"), _g, out)
out = out.replace('h', ' giờ ')
out = out.replace(':', ' giờ ')
if out[-1].isdigit():
out = out + ' phút '
elif out[-1] == 'p':
out = out[:-1] + ' phút '
out = out.replace('00 giờ', '0 giờ')
out = out.replace('00 phút', '')
out = out.replace('00', '')
out = out.replace(' 0', ' ')
out = out.replace('-', ' đến ')
out = out.replace('–', ' đến ')
return out + end
def _hour_minute1(m):
print('input ', m.group(0))
output = re.sub(re.compile(r"([0-9]|[0-2][0-9])((\ g\ )|(\ g)|(\ g)|(\ g:\ )|(\ g:)|(g:\ )|(g:)|g)((([0-9]|[0-6][0-9])(p|))|)(:|\.|,|-| -|–| –|\ )"), _hour_minute, m.group(0))
return output
def _bignum(m):
return m.group(0).replace('.', '')
def _float(m):
x = m.group(0).replace('.', '')
x = x.split(',')
output = x[0] + ' phẩy '
if len(x[1]) > 2:
output += ' '.join(list(x[1]))
else: output += x[1]
return output
def _thounsand(m):
return m.group(0).replace('k', ' nghìn').replace('-', ' đến ')
def _m(m):
return m.group(0).replace('m', ' mét ')
def _v(m):
return m.group(0).replace('v', ' vol')
def _weight(m):
return m.group(0).replace('g', ' gam ')
def _volume(m):
return m.group(0).replace('l', ' lít ')
def _ward(m):
return m.group(0).replace('.', ' ').replace(' p ', ' phường ')
def _district(m):
return m.group(0).replace('.', ' ').replace(' q ', ' quận ')
def _city(m):
return m.group(0).replace(' tp.', ' thành phố ').replace(' t.p', ' thành phố ').replace(' tx.', ' thị xã ').replace(' tt.', ' thị trấn ')
def _money(m):
return m.group(0).replace('đ', ' đồng ')
def _split(m):
out = ''
text = m.group(0)
for idx, char in enumerate(text):
if not char.isdigit():
out += char
else:
if char == '0' or len(text[idx:])>2:
out += ' ' + ' '.join(list(text[idx:]))
else:
out += ' ' + text[idx:]
break
return out
def _split2(m): #OnePlus Nord N10 D12345
out1, out2 = '', ''
text = m.group(0).strip()
for idx, char in enumerate(text):
if not char.isdigit():
out1 += char
else:
if char == '0' or len(text[idx:])>2:
out2 += ' ' + ' '.join(list(text[idx:])) #ABC 0123
else:
out2 += ' ' + text[idx:] #ABC 1 2 3
break
if out1 not in ['VOV', 'VOH', 'VTV', 'HTV']:
out1 = ' '.join(list(out1))
return ' '+out1+' '+out2+' '
def _split3(m):
result = ''
for w in list(m.group(0).strip()):
if w.isdigit():
result += ' ' + int_to_vn(int(w))
else: result += ' ' + w
return result + ' '
def _split4(m):
text = m.group()
for i in text:
if not i.isdigit() and i != ' ':
text = text.replace(i, ' ' + i)
break
return text
def _uper(m):
return m.group(0).replace(m.group(0), ' '.join(list(m.group(0))))
def _phone(m):
out = m.group(0).replace('.', '')
return ' '.join(list(out))
def _phone2(m):
out = m.group(0).replace('.', '').strip()
for x in out.split(' '):
if x.isdigit():
out = out.replace(x, ' '.join(list(x)))
return ' '+out+' '
def _no(m):
out = m.group(0).split('.')
return out[0]+' '+int_to_vn(int(out[1]))
def _num(m):
text = str(m.group(0)).split(' ')
result = ''
for id, x in enumerate(text):
if x.isdigit():
if id > 0 and text[id-1] in ['thứ', 'tháng'] and int(x)==4:
result += 'tư '
else:
result+= str(int(x)) + ' '
else: result+=x+' '
return result
def _no(m):
out = m.group(0).split('.')
return out[0]+' '+int_to_vn(int(out[1]))
def _link(m):
out = m.group(0)
out = out.replace('/', ' siệt ' )
out = out.replace('.', ' chấm ')
out = out.replace(':', ' hai chấm ')
out = out.replace('-', ' gạch giữa ')
out = out.replace('vn', 'v n')
out = out.replace('org', 'o r g')
return out
def _mail(m):
out = m.group(0)
out = out.replace('/', ' siệt ')
out = out.replace('.', ' chấm ')
out = out.replace('@', ', a còng, ')
out = out.replace(':', ' hai chấm ')
out = out.replace('olli-ai', 'olli ây ai')
out = out.replace('gmail', 'gờ mail')
return out
def _license_plate(m):
out = ''
for char in m.group(0):
if char.isdigit():
out+=char+' '
else: out+=char
return out
def _roman_num(word):
num = 0
p = False
for x in list(word)[::-1]:
if x == 'i':
if p:
p = False
num -= 1
else: num += 1
elif x == 'v':
num += 5
p = True
elif x == 'x':
num += 10
p = True
return str(num)
def _roman_numerals(m):
out = ''
#print(m.group(0))
compiles = re.compile(r'(x|i|v)+')
for w in nltk.word_tokenize(m.group(0)):
if compiles.match(w) is not None:
out += _roman_num(w) + ' '
else:
out += w + ' '
return out
def _dot(m):
return m.group(0).replace('.', '')
def _dot2(m):
return m.group(0).replace('.', ' ')
def _dot3(m):
x = m.group(0).split('.')
output = x[0] + ' chấm ' + ' '.join(list(x[1]))
return output
def _dot4(m):
return m.group(0).replace('.', ' chấm ')
def _measure(m):
input = m.group(0)
input = input.replace('km2', ' ki lô mét vuông')
input = input.replace('m2', ' mét vuông')
input = input.replace('m3/s', ' mét khối trên giây')
input = input.replace('m3', ' mét khối')
input = input.replace('km/h', ' ki lô mét trên giờ')
input = input.replace('m/s', ' mét trên giây')
input = input.replace('°c', ' độ xê')
input = input.replace('°f', ' độ ép')
input = input.replace('ml', ' mi li lít')
input = input.replace('mg', ' mi li gam')
input = input.replace('cm', ' xen ti mét')
input = input.replace('nm', ' na nô mét')
input = input.replace('mm', ' mi li mét')
input = input.replace('ms', ' mi li giây')
input = input.replace('m³', ' mét khối')
input = input.replace('mw', ' mê ga oát')
input = input.replace('kwh', ' ki lô oát giờ')
input = input.replace('km²', ' ki lô mét vuông')
input = input.replace('km', ' ki lô mét')
input = input.replace('đ/kg', 'đồng trên kí')
input = input.replace('đồng/kg', 'đồng trên kí')
input = input.replace('đồng/km', 'đồng trên kí lô mét')
input = input.replace('kg', ' ki lô gam')
input = input.replace('kw', ' ki lô oát')
input = input.replace('độ c', 'độ xê')
input = input.replace('$', ' đô_la')
input = input.replace('%', ' phần_trăm')
input = input.replace('m²', ' mét vuông')
input = input.replace('mhz', ' mê ga hét')
input = input.replace('khz', ' ki lô hét')
input = input.replace('hz', ' hẹt')
input = input.replace('gb', ' ghi ga bai')
input = input.replace('µm', ' mi rô mét')
input = input.replace('ft', ' feet')
input = input.replace('mmhg', ' mi li mét thủy ngân')
input = input.replace('ha', ' héc ta')
input = input.replace('mah', ' mi li am pe giờ')
input = input.replace('vnđ', ' việt_nam_đồng')
input = input.replace('vnd', ' việt_nam_đồng')
input = input.replace('ndt', ' nhân_dân_tệ')
input = input.replace('€', ' ơ_rô')
input = input.replace('£', 'bản_anh')
return input
def _interval(m):
out = m.group(0).replace('-', ' đến ngày ')
return out
def _ddmmyy(m):
text = m.group(0)
out = ''
if len(text.split('/'))==3:
date = text.split('/')
elif len(text.split('-'))==3:
date = text.split('-')
elif len(text.split('.'))==3:
date = text.split('.')
if int(date[1]) == 4:
out = int_to_vn(int(date[0])) + ' tháng tư năm '+ int_to_vn(int(date[2]))
else:
out = int_to_vn(int(date[0])) + ' tháng ' + int_to_vn(int(date[1])) + ' năm ' + int_to_vn(int(date[2]))
return out + ' '
def _mmyy(m):
text = m.group(0).strip()
end = ''
if text[-1] in ',.?!':
en = text[-1]
text = text[:-1]
out = ''
if len(text.split(' '))>1:
date = text.split(' ')[1]
else: date = text
if len(date.split('/'))==2:
date = date.split('/')
elif len(date.split('-'))==2:
date = date.split('-')
elif len(date.split('.'))==2:
date = date.split('.')
if int(date[0]) == 4:
out = ' tháng tư năm '+ int_to_vn(int(date[1]))
else:
out = ' tháng ' + int_to_vn(int(date[0])) + ' năm ' + int_to_vn(int(date[1]))
return out+end+' '
def _ddmm(m):
text = m.group(0).strip()
end = ''
if text[-1] in ',.?!':
end = text[-1]
text = text[:-1]
out = ''
if len(text.split('/')) == 2:
date = text.split('/')
elif len(text.split('-')) == 2:
date = text.split('-')
elif len(text.split('.')) == 2:
date = text.split('.')
out += ' ' + int_to_vn(int(date[0])) + ' tháng ' + (int_to_vn(int(date[1])) if int(date[1]) != 4 else "tư")
return out+end+' '
def _ddmm1(m):
out = m.group(0).strip()
out = re.sub(re.compile(r'([1-9]|[0-3][0-9])(/|-|\.)((0[1-9]|1[0-2])|[1-9])'), _ddmm, out)
return out
def _days(m):
out = m.group(0)
out = out.replace('-', ' đến ')
out = re.sub(re.compile(r'([0-3][0-9]|[1-9])(/|-|\.)((0[1-9]|1[0-2])|[1-9])(/|-|\.)[1-2][0-9][0-9][0-9]'), _ddmmyy, out)
out = re.sub(re.compile(r'([1-9]|[0-3][0-9])(/|-|\.)((0[1-9]|1[0-2])|[1-9])'), _ddmm, out)
return out+ ' '
def _phay(m):
return m.group(0)+','
def _3G(m):
out = m.group(0)
out = re.sub(re.compile(r'[a-z0-9\+]+'), _phay, out)
return out.replace('3g', 'ba gờ').replace('4g', 'bốn gờ').replace('5g', 'năm gờ')
def _duration(m):
text = m.group(0).split('-')
return text[0]+' đến ngày '+text[1]
def _vi(m):
out = m.group(0)
v = {'/':'trên', 't':'tê', 'g':'giê', 'q':'quy', 'đ':'đê', 'c':'xê', 'p':'pê', 'k':'ca', 'h':'hắc', 'v':'vê', 'b':'bê',}
result = ' '
for c in out:
if c in v:
result += v[c]+' '
return result
def _TW(m):
out = m.group(0)
out = out.replace('-', '')
out = re.sub(re.compile('(/[tgqđcpkhvb][tgqđcpkhvb]+)'), _vi, out)
return out.replace('/', ' trên ')
def _am(m):
out = m.group(0)
out = out.replace('-', 'âm ')
return out
def _name(m):
out = m.group(0)
out = out.replace('m4u', 'em pho du').replace('365', '3 6 5')
return out
def _am_pm(m):
out = m.group(0)
out = out.replace('am', 'sáng')
if out[-2:] == "pm":
h = int(out[:2].strip())
if (h > 12 and h < 18) or (h >= 1 and h < 6):
out = out.replace('pm', 'chiều')
elif (h >= 18 and h < 22) or (h >= 6 and h < 10):
out = out.replace('pm', 'tối')
elif (h >= 22 and h <= 24) or (h >= 10 and h <= 12):
out = out.replace('pm', 'khuya')
return out
def _noun(m):
out = m.group(0)
out = out.replace('\'s', ' is ')
out = out.replace('\'re', ' are ')
return out
def _self(m):
return m.group(0).replace('\'', '')
def _upper(m):
out = m.group(0).strip()
end = ''
if out[-1] in [',','.','?','!', ';', ':']:
end = out[-1]
out = out[:-1].strip()
if out in acronym:
return ' '+acronym[out]+end+' '
out = ' '.join(list(out))
return ' '+out+end+' '
def _space(m):
out = m.group(0)
out = out.replace('-', ' , ')
return out
def _nay(m):
out = m.group(0)
out = out.replace('(', '').replace(')','')
return out
def _AI(m):
out = m.group(0)
out = out.replace('AI', 'ây ai')
return out
def _hyphen(m):
out = m.group(0)
return out.replace(' ', '')
def _fourth(m):
out = m.group(0)
return out.replace('4', ' tư ')
def _part(m):
out = m.group(0)
return out.replace('p', 'phần ')
_alphabet = 'aăâbcdđeêghiklmnoôơpqrstuưvxyfjwz' \
'áắấéếíóốớúứý' \
'àằầèềìòồờùừỳ' \
'ảẳẩẻểỉỏổởủửỷ' \
'ãẵẫẽễĩõỗỡũữỹ' \
'ạặậẹệịọộợụựỵ '
def processSent(sent):
'''
Thể thao 24/7 Hôm nay là 24/7 Địa chỉ là 24/7 24/7/2017 7/2017
24,7 24.700.000 24$ 24% 24x7 24h 23h7 24m 24g 24kg 24ha 24m2 24m3 U19 ()
:param input:
:return:
'''
# Acronym & vocab & number
_characters = '!,.?'
input = re.sub(re.compile(r"(^|\ )(AI)(,|;|:|\?|!|\.|\ |$)"), _AI, sent)
input = re.sub(re.compile(r'(\ )[A-Z]+[0-9]+(\ |\.|,|/|-)'), _split2, ' ' + input + ' ')
input = ' '+ re.sub(re.compile(r"(^|\ )(AI|SE|IS|IPA|US|UK|KRQE|FBI|UAV|UAE|USS|DSCA|AM|CISM|AIoT|COC|TAC|5K|FCA|HoSE|TNHH MTV|ĐĐ.Thích)(,|\.|\?|!|;|:|\ |$)"), _upper, input+' ').lower() + ' '
input = re.sub(re.compile(r"(bks |biển kiểm soát |biển số )[0-9][0-9][a-z][1-9]\ [0-9]+"),_license_plate, input)
input = re.sub(re.compile(r'từ ([0-9]|[0-3][0-9])/([0-9]|[0-1][0-9])((/([1-2][0-9][0-9][0-9]))|)((\ -\ )|(-\ )|(\ -)|(-))([0-9]|[0-3][0-9])/([0-9]|[0-1][0-9])((/([1-2][0-9][0-9][0-9]))|)'), _interval, input)
input = re.sub(re.compile(r'(hôm nay|sáng nay|tối nay|sớm nay|chiều nay|trưa nay|ngày mai|mai)\ (\(([1-9]|[0-3][0-9])(/|-|\.)((0[1-9]|1[0-2])|[1-9])\))'), _nay, input)
input = re.sub(re.compile(r'(nhóm|nhạc|minh vương|dương)(\ )(m4u|365|565)'), _name, input)
input = re.sub(re.compile(r"(he|she|it|you|we|they)\'(s|re)"), _noun, input)
input = re.sub(re.compile(r"\ [a-z]+\'s"), _self, ' '+ input)
input = re.sub(re.compile(r"\(p[0-9]+\)"), _part, input)
input = re.sub(re.compile(r'(quận |thứ |hạng )4(\.|,|\?|!|\ |$)'), _fourth, input)
input = input.replace('i\'m', 'i m')
input = input.replace('i\'d', 'i d')
input = input.replace('p!nk', 'pink')
input = input.replace('*', '')
input = input.replace(';', '.')
input = input.replace('?.', '?') #fix bug split sentence
input = input.replace('!.', '!') #fix bug split sentence
input = input.replace('“', '')
input = input.replace('”', '')
input = input.replace('\"', '')
input = input.replace('\'s', '')
input = input.replace('\'', '')
input = input.replace(')', ',')
input = input.replace('(', ', ')
input = input.replace('″', '')
input = input.replace('’', '')
input = input.replace('‘', '')
input = input.replace('#', '')
input = input.replace('[', '')
input = input.replace(']', '')
#input = input.replace(',...', ', vân vân. ')
input = input.replace('...', '. ')
#input = input.replace(',…', ', vân vân. ')
input = input.replace('…', '. ')
input = input.replace('=', ' bằng ')
input = re.sub(re.compile(r'(,)(\ |,)+'), ', ', input)
input = re.sub(re.compile(r'[0-9][0-9\ ]*(mỗi|từng|chục|trăm|tỷ|nghìn|ngàn|triệu|đồng|đơn vị|đơn vị là|một|hai|ba|bốn|năm|sáu|bảy|tám|chín|mười|mươi|lăm|mốt|\ )*(mm|khz|m3/s|đ/kg|£|mah|€|đồng/kg|đồng/km|kg|ha|mmhg|vnđ|ndt|vnd|µm|ft|m/s|km/h|gb|hz|mhz|m²|độ c|\$|%|km²|km|m³|ms|kwh|mw|mg|cm|°f|°c|m2|km2|m3|ml|l|kw|mm|nm)[/\ ,.?!-]'), _measure, input+' ')
input = re.sub(re.compile(r'(quyết định|nghị định|thông tư|văn bản|nghị định|số)(\ )([0-9][0-9/]*[tgqđcpkhvb][tgqđcpkhvb\-]*)'), _TW, input)
input = re.sub(re.compile(r'(^|\ )\-[0-9]+'), _am, input)
input = re.sub(re.compile(r'(\ )[a-zđ]+[0-9]+(\ |\.|,|/|-)'), _split, ' ' + input + ' ')
input = re.sub(re.compile(r'(www.|http://|https://|)[a-z0-9\.\-]+@(gmail|yahoo|outlook|olli-ai)(\.com|\.vn|\.edu)+'), _mail, input)
input = re.sub(re.compile(r'(www.|http://|https://|)[a-z0-9\.\-]+(\.com|\.vn|\.edu|\.org|\.net)+'), _link, input)
input = re.sub(re.compile(r"(thế kỉ|thứ|giải|hạng|bsck|quý|khóa|khoá|khoa|tầng|chương|mục|phần|nhóm|đại hội|tk|đệ|thế chiến|cấp|kỳ|kì|kỷ)\ [ivx]+[\ .,/-]"),_roman_numerals, input)
input = re.sub(re.compile(r'[1-9][0-9\ ]*x((\ |)*[1-9][0-9]*)[\ .,-/]'), _size, input+' ')
#print('in ', input)
input = re.sub(re.compile(r"(lúc|từ|khoảng|đến|tới|vào|hồi)\ ([1-9]|[0-2][0-9])((\ :\ )|(\ :)|(:\ )|:)(([0-6][0-9]|[1-9])|)((((\ :\ )|(\ :)|(:\ )|:)([0-6][0-9]|[1-9])){1,2})(\ |\.|,|-||–| –|)"), _hour, input + ' ')
#print('out ', input)
input = re.sub(re.compile(r"([0-9]|[0-2][0-9])((\ h\ )|(h\ )|(\ h)|(\ h:\ )|(\ h:)|(h:\ )|(h:)|h)((([0-9]|[0-6][0-9])(p|))|)(:|\.|,|-| -|–| –|\ )"), _hour_minute, input.strip()+' ')
input = re.sub(re.compile(r"([0-9]|[0-2][0-9])((\ :\ )|(\ :)|(:\ )|:)([0-9]|[0-6][0-9])(p|)(:|\.|,|-| -|–| –|\ )"), _hour_minute, input.strip()+' ')
#print(input)
input = re.sub(re.compile(r"(lúc|từ|đến|tới|vào|hồi)\ ([0-9]|[0-2][0-9])((\ g\ )|(\ g)|(\ g)|g)(\.|,|-| -|–| –|\ )"), _hour_minute1, input+' ')
#print(input)
input = re.sub(re.compile(r"([0-9]|[0-2][0-9])((\ g\ )|(\ g)|(\ g)|g)((([0-9]|[0-6][0-9])(p|)))(\.|,|-| -|–| –|\ )"), _hour_minute, input+' ')
print(input)
input = re.sub(re.compile(r"([0-9]|[0-2][0-9])((\ g:\ )|(\ g:)|(\ g:)|g:)((([0-9]|[0-6][0-9])(p|))|)(:|\.|,|-| -|–| –|\ )"), _hour_minute, input+' ')
#print(input)
input = re.sub(re.compile(r"(khoảng\ )([0-9]|[0-2][0-9])((\ g\ )|(\ g)|(g\ )|(\ g:\ )|(\ g:)|(g:\ )|(g:)|g)((([0-9]|[0-6][0-9])(p|))|)(\ )(một lần|mỗi ngày|hàng ngày|cùng ngày|ngày|trưa|tối|sáng|rạng sáng|buổi)"), _hour_minute1, input+' ')
input = re.sub(re.compile(r'[0-9][0-9\ ]*k[/\ .,-]'), _thounsand, input)
input = re.sub(re.compile(r'\ ((p(\ )[0-9]{1,2})|(p\.(\ )*([0-9]{1,2}|[a-zđ]{1,})))'), _ward, ' ' + input)
input = re.sub(re.compile(r'\ ((q(\ )[0-9]{1,2})|(q\.(\ )*([0-9]{1,2}|[a-zđ]{1,})))'), _district, ' ' + input)
input = re.sub(re.compile(r'\ (tp\.|t\.p\ |tp\. |tt\.|tx\.|tt\. |tx\. )[đâơôa-z]'), _city, ' '+ input)
input = re.sub(re.compile(r'\ [1-9][0-9][0-9]\.([0-9][0-9][0-9]\.)*[0-9][0-9][0-9]\ '), _bignum, ' '+input)
input = re.sub(re.compile(r'[0-9][0-9\ ]+đ[/\ .,-]'), _money, input+' ')
input = re.sub(re.compile(r'\ ([a-z0-9\+]+|dung lượng|tài khoản|gói cước|sim|lưu lượng|đăng ký|nạp tiền|gia hạn|mạng|dịch vụ|sử dụng|truy cập|kết nối)\ (là |)(3|4|5)g[\ \.,-?!]'), _3G, ' ' + input + ' ')
input = re.sub(re.compile(r'[0-9][0-9\ ]*g[/\ .,-]'), _weight, input + ' ')
input = re.sub(re.compile(r'[0-9][0-9\ ]*l[/\ .,-]'), _volume, input + ' ')
input = re.sub(re.compile(r'[0-9][0-9\ ]*m[\ .,-]'), _m, input + ' ')
input = re.sub(re.compile(r'[0-9][0-9\ ]*v[\ .,-]'), _v, input + ' ')
input = re.sub(re.compile(r'((no|vol)\.)(\ |)[0-9]{1,2}'), _no, input)
input = re.sub(re.compile(r'(ngày|đêm|tối|sáng|trưa|chiều|từ)\ (([1-9]|[0-3][0-9]))((\ |)(-|và|đến|tới)(\ |))(((([0-3][0-9]|[1-9])(/|\.)((0[1-9]|1[0-2])|[1-9])(/|\.)[1-2][0-9][0-9][0-9]))|(([1-9]|[0-3][0-9])(/|\.|-)(0[1-9]|1[0-2]|[1-9])))'),_days, input + ' ')
input = re.sub(re.compile(r'từ ([1-9]|[0-3][0-9])(/|\.)((0[1-9]|1[0-2])|[1-9])(\ |,|;|\.)'), _ddmm1, input)
# 8/9/2018, 8-9-2018, 8.9.2018
input = re.sub(re.compile(r'([0-3][0-9]|[1-9])/((0[1-9]|1[0-2])|[1-9])/[1-2][0-9][0-9][0-9]'), _ddmmyy, input)
input = re.sub(re.compile(r'([0-3][0-9]|[1-9])\.((0[1-9]|1[0-2])|[1-9])\.[1-2][0-9][0-9][0-9]'), _ddmmyy, input)
input = re.sub(re.compile(r'([0-3][0-9]|[1-9])-((0[1-9]|1[0-2])|[1-9])-[1-2][0-9][0-9][0-9]'), _ddmmyy, input)
# # 9.2018, 9-2018, 9/2018, ngày 7-9, 14-9, 21-8
input = re.sub(re.compile(r'tháng\ ((0[1-9]|1[0-2])|[1-9])(/|\.|-)[1-2][0-9][0-9][0-9]'), _mmyy, input + ' ')
input = re.sub(re.compile(r'\ ((0[1-9]|1[0-2])|[1-9])(/|\.|-)[1-2][0-9][0-9][0-9](\ |\.|,)'), _mmyy, input + ' ')
input = re.sub(re.compile(r'(([0-9]|[0-2][0-9])(\ giờ)((\ ([0-9]|[0-6][0-9]) phút)|\ ([0-9]|[0-6][0-9])|)((\ ([0-9]|[0-6][0-9]) giây)|))(\ )(am|pm)'), _am_pm, input)
input = input.replace(':', ', ')
out =''
words = ViTokenizer.tokenize(input)
words = words.replace(' & ', '&')
words = re.sub(re.compile(r'[0-9](\ )*\-(\ )*[0-9]'), _hyphen, words)
words = words.replace(' .', '.')
words = words.replace('thứ hai', 'thứ_hai')
words = words.replace('thứ ba', 'thứ_ba')
words = words.replace('thứ tư', 'thứ_tư')
words = words.replace('thứ năm', 'thứ_năm')
words = words.replace('thứ sáu', 'thứ_sáu')
words = words.replace('thứ bảy', 'thứ_bảy')
words = words.replace('thứ 2 ', 'thứ_hai ')
words = words.replace('thứ 3 ', 'thứ_ba ')
words = words.replace('thứ 4 ', 'thứ_tư ')
words = words.replace('thứ 5 ', 'thứ_năm ')
words = words.replace('thứ 6 ', 'thứ_sáu ')
words = words.replace('thứ 7 ', 'thứ_bảy ')
words = words.replace('chủ nhật', 'chủ_nhật')
words = words.replace('số nhà', 'số_nhà')
words = words.replace('giổ tổ', 'giổ_tổ')
dates = ['thứ_hai','thứ_ba','thứ_tư','thứ_năm','thứ_sáu','thứ_bảy','chủ_nhật', 'thứ_2', 'thứ_3', 'thứ_4', 'thứ_5', 'thứ_6', 'giổ_tổ', 'mùng',
'ngày', 'tháng', 'sáng', 'trưa', 'chiều','tối', 'qua', 'mai', 'đêm', 'vào', 'khủng_bố', 'sự_kiện',
'khuya', 'hôm', 'quốc_khánh', 'lễ', 'thiếu_nhi', 'việt_nam', 'nay', 'đến', 'phiên', 'hôm_nay', 'ngày_mai']
spec_day = ['2/9','8/3', '3/2', '20/11', '30/4', '1/5', '10/3', '27/7', '22/12']
address = ['địa_chỉ', 'hẻm', 'số_nhà', 'ngõ', 'đường']
for id, word in enumerate(words.split(' ')):
if word in spec_day or (id > 0 and (words.split(' ')[id - 1] in dates) and word[0].isdigit()):
end = ''
if word[-1] == '.' or word[-1] ==',':
end = word[-1]
word = word[:-1]
word = re.sub(re.compile(r'([1-9]|[0-3][0-9])-([1-9]|[0-3][0-9])(/|\.)((0[1-9]|1[0-2])|[1-9])'), _duration, word)
word = re.sub(re.compile(r'([1-9]|[0-3][0-9])(/|-|\.)((0[1-9]|1[0-2])|[1-9])'), _ddmm, word)
out += word.strip() + end + ' '
elif len(word.split('/')) > 1:
for id1, w in enumerate(word.split('/')):
if w.isdigit():
if id1 != len(word.split('/')) - 1 and words.split(' ')[id - 1] in address:
out += int_to_vn(int(w)) + ' siệt '
elif id1 != len(word.split('/')) - 1 and words.split(' ')[id - 1] not in address:
out += int_to_vn(int(w)) + ' trên '
else:
out += int_to_vn(int(w)) + ' '
else:
if id1 != len(word.split('/')) - 1:
out += w + ' trên '
else:
out += w + ' '
elif len(word) >2 and len(word.split('-')) == 2 and word.split('-')[0][0].isdigit() and word.split('-')[1][0].isdigit():
if id - 1 >= 0 and words.split(' ')[id - 1] in ['từ', 'khoảng', 'tầm' , 'ngày']:
word = word.replace('-', ' đến ')
out += word+' '
else:
word = re.sub(re.compile(r'[0-9][0-9\.]*\,[0-9]+'), _float, ' ' + word + ' ')
word = word.strip()
end = ''
if len(word) > 0 and word[-1] in _characters and word not in ['mr.']:
end = word[-1]
word = word[:-1]
if word in acronym:
word = acronym[word]
out += word + end + ' '
tokens = ViTokenizer.tokenize(out.strip())
tokens = tokens.replace('_', ' ')
tokens = tokens.replace('/', ' ')
tokens = tokens.replace('\\', ' ')
tokens = tokens.replace(', ,', ' , ')
tokens = tokens.replace('&', ' và ')
tokens = tokens.replace('+', ' cộng ')
tokens = tokens.replace('giờ 00', ' giờ ')
tokens = re.sub(re.compile(r'[0-9]+-[0-9]+'), _space, tokens)
tokens = tokens.replace(' - ', ' , ')
tokens = tokens.replace('-', ' ')
tokens = tokens.replace(' –', ' ')
tokens = tokens.replace('– ', ' ')
tokens = re.sub(re.compile(r'\ [0-9][0-9\.]*\,[0-9]+'), _float, ' ' + tokens + ' ')
tokens = re.sub(re.compile(r'[0-9]+(\.[0-9]{3})+[\ \.,?!]'), _dot, tokens+' ')
tokens = re.sub(re.compile(r'[0-9]+(\.)0[0-9]*'), _dot3, tokens)
tokens = re.sub(re.compile(r'[0-9]+((\.)[0-9]+)+'), _dot4, tokens)
tokens = re.sub(re.compile(r"\ (tổng đài|liên hệ|số điện thoại)(\ )*(1800|1900|0)[0-9\.\ ]+"), _phone2, tokens)
tokens = re.sub(re.compile(r"(\ )*(ngày|tháng|số|thứ)(\ )*([0-9]+)"), _num, tokens)
tokens = re.sub(re.compile(r"\ (0|\+8)[0-9\.]{8,9}"), _phone, tokens)
tokens = re.sub(re.compile(r"\ [0-9]+[a-zđ\-]+(\ |\.|,)"), _split4, tokens)
tokens = re.sub(re.compile(r'[a-zđ](\.[a-zđ])+'), _dot2, tokens)
result = ''
for token in tokens.split(' '):
if token.isdigit():
result += int_to_vn(int(token))+ ' '
elif token in _characters:
result = result[:-1] + token + ' '
elif token in acronym:
result += acronym[token] + ' '
elif token != '':
result += token + ' '
result = re.sub(re.compile(r'\ ([bcdđghklmnpqrstvxfjwz0-9]{2,})+[\ \.,?!]'), _split3, ' ' + result + ' ')
result = re.sub(re.compile(r'\ ([aeoyiu]+[0-9]+)([bcdđghklmnpqrstvxfjwz]+|)[\ \.,?!]'), _split3, ' ' + result + ' ')
result = result.replace('_',' ').strip()
result = ' '.join([x for x in result.split(' ') if x != ''])
if len(result) >= 1 and result[-1] not in _characters:
result = result + '.'
return result.strip()
#print(processSent("biện pháp 5K trốn tìm Đen, MTV, cty TNHH MTV olli"))
stop_word = [
'và', 'sau_khi', 'khi', 'bởi', 'vì_sao', 'điều_này', 'cho_rằng',
'rằng', 'nếu', 'vì', 'lúc_này', 'khi_đó', 'nên', 'cũng_như', 'mà', 'tại_sao',
'lúc', 'vậy', 'tại_sao', 'một_cách', 'đến_nỗi', 'bởi_vì',
'do_đó', 'do', 'sau_đó', 'đó_là', 'thế_nhưng', 'tại', 'thì', 'hoặc', 'với',
'tất_nhiên', 'đương_nhiên', 'thay_vì', 'vì_vậy', 'giả_sử', 'giá_như', 'nhưng',
'may_mà', 'thế_mà', 'tuy', 'rằng', 'mặc_dù', 'hễ', 'hèn_chi', 'so_với',
'huống_chi', 'huống_hồ', 'vả_lại', 'họa_chăng', 'kẻo', 'kẻo_mà', 'kẻo_nữa',
'hèn_chi', 'hèn_gì', 'thảo_nào', 'để', 'giả_sử', 'ví_như', 'dường_như', 'dẫu', 'tuy',
'ví_như', 'tuy_rằng', 'thế_mà', 'mà', 'vậy_mà', 'thế_mà', 'dẫu', 'thì', 'huống_hồ', 'biết_đâu', 'quả nhiên',
'bởi_vậy', 'thành_thử', 'còn_như', 'kẻo_lại', 'vậy_mà',
'thế_thì', 'huống_là', 'hay_là', 'miễn_là', 'dù', 'như_vậy', 'đến_khi', 'cho_đến', 'đến_nỗi',
'trong_khi', 'trong_lúc', 'thảo_nào', 'trong', 'dẫn_đến', 'bao_gồm', 'sau_đó',
]
def pretokenize(doc):
doc = doc.replace('sau khi', 'sau_khi')
doc = doc.replace('tại sao', 'tại_sao')
doc = doc.replace('so với', 'so_với')
doc = doc.replace('bởi vậy', 'bởi_vậy')
doc = doc.replace('thành thử', 'thành_thử')
doc = doc.replace('còn như', 'còn_như')
doc = doc.replace('kẻo lại', 'kẻo_lại')
doc = doc.replace('vậy mà', 'vậy_mà')
doc = doc.replace('huống là', 'huống_là')
doc = doc.replace('hay là', 'hay_là')
doc = doc.replace('miễn là', 'miễn_là')
doc = doc.replace('cho đến', 'cho_đến')
doc = doc.replace('đến khi', 'đến_khi')
doc = doc.replace('đến nổi', 'đến_nổi')
doc = doc.replace('trong khi', 'trong_khi')
doc = doc.replace('trong lúc', 'trong_lúc')
doc = doc.replace('dẫn đến', 'dẫn_đến')
doc = doc.replace('cho rằng', 'cho_rằng')
doc = doc.replace('một cách', 'một_cách')
doc = doc.replace('điều này', 'điều_này')
doc = doc.replace('cũng như', 'cũng_như')
doc = doc.replace('sau đó', 'sau_đó')
return doc
def split(doc):
max_len=35
sent_list = nltk.sent_tokenize(doc)
out_list = []
for sent in sent_list:
if len(sent.split(' ')) <= max_len:
out_list.append(sent)
else:
clause = re.split(", |\?|!|,|\.", sent)
for seq in clause:
word_list = seq.split(' ')
if len(word_list)<=max_len:
out_list.append(seq)
else:
chk = ViTokenizer.tokenize(seq)
chk = pretokenize(chk).split()
start = 0
for index, token in enumerate(chk):
if token in stop_word and index != len(chk)-1:
out_list.append(' '.join(chk[start:index]).replace('_', ' '))
start = index
elif index == len(chk)-1:
out_list.append(' '.join(chk[start:index+1]).replace('_', ' '))
return out_list
def split1(doc):
max_len=35
sent_list = nltk.sent_tokenize(doc)
out_list = []
for sent in sent_list:
sent = sent.strip()
if len(sent.split(' ')) <= max_len:
out_list.append(sent)
else:
p_list = []
clause = re.split(", |\?|!|,", sent)
for seq in clause:
word_list = seq.strip().split(' ')
if len(word_list)<=max_len:
p_list.append(seq)
else:
chk = ViTokenizer.tokenize(seq)
chk = pretokenize(chk).split()
start = 0
for index, token in enumerate(chk):
if token in stop_word and index != len(chk)-1:
p_list.append(' '.join(chk[start:index]).replace('_', ' '))
start = index
elif index == len(chk)-1:
p_list.append(' '.join(chk[start:index+1]).replace('_', ' '))
p_list = [x.strip() for x in p_list if x != '']
part = partition(p_list)
text_split = sent.split(' ')
text_split = [x.strip() for x in text_split if x != '']
id = 0
for i in part:
out_list.append(' '.join(text_split[id:(id+i)]))
id +=i
return out_list | 0.130092 | 0.349283 |
from pathlib import Path
from collections import Counter, defaultdict
INPUTFILE = "input.txt"
SAMPLE_INPUT = """
16
10
15
5
1
11
7
19
6
12
4
"""
SAMPLE_INPUT2 = """
28
33
18
42
31
14
46
20
48
47
24
23
49
45
19
38
39
11
1
32
25
35
8
17
7
9
4
2
34
10
3
"""
# Utility functions
def load_input(infile):
return filter_blank_lines(Path(infile).open())
def filter_blank_lines(lines):
return [line.strip() for line in lines if line.strip()]
# Solution
def solve(lines):
"""Solve the problem."""
jolts = [0] + [int(line) for line in lines]
jolts.sort()
jolts.append(max(jolts) + 3)
c = Counter([b-a for a, b in zip(jolts[:-1], jolts[1:])])
return c[1] * c[3]
def solve2(lines):
"""Solve the problem."""
jolts = [0] + [int(line) for line in lines]
jolts.sort()
count = defaultdict(int)
count[max(jolts)] = 1
for jolt in reversed(jolts):
count[jolt] += count[jolt + 1] + count[jolt + 2] + count[jolt + 3]
return count[0]
# PART 1
def example1():
lines = filter_blank_lines(SAMPLE_INPUT.split("\n"))
result = solve(lines)
expected = 35
print(f"'sample-input' -> {result} (expected {expected})")
assert result == expected
lines = filter_blank_lines(SAMPLE_INPUT2.split("\n"))
result = solve(lines)
expected = 220
print(f"'sample-input2' -> {result} (expected {expected})")
assert result == expected
print("= " * 32)
def part1(lines):
result = solve(lines)
print(f"result is {result}")
print("= " * 32)
# PART 2
def example2():
lines = filter_blank_lines(SAMPLE_INPUT.split("\n"))
result = solve2(lines)
expected = 8
print(f"'sample-input' -> {result} (expected {expected})")
assert result == expected
lines = filter_blank_lines(SAMPLE_INPUT2.split("\n"))
result = solve2(lines)
expected = 19208
print(f"'sample-input2' -> {result} (expected {expected})")
assert result == expected
print("= " * 32)
def part2(lines):
result = solve2(lines)
print(f"result is {result}")
print("= " * 32)
if __name__ == "__main__":
example1()
lines = load_input(INPUTFILE)
part1(lines)
example2()
part2(lines) | day10/day10.py | from pathlib import Path
from collections import Counter, defaultdict
INPUTFILE = "input.txt"
SAMPLE_INPUT = """
16
10
15
5
1
11
7
19
6
12
4
"""
SAMPLE_INPUT2 = """
28
33
18
42
31
14
46
20
48
47
24
23
49
45
19
38
39
11
1
32
25
35
8
17
7
9
4
2
34
10
3
"""
# Utility functions
def load_input(infile):
return filter_blank_lines(Path(infile).open())
def filter_blank_lines(lines):
return [line.strip() for line in lines if line.strip()]
# Solution
def solve(lines):
"""Solve the problem."""
jolts = [0] + [int(line) for line in lines]
jolts.sort()
jolts.append(max(jolts) + 3)
c = Counter([b-a for a, b in zip(jolts[:-1], jolts[1:])])
return c[1] * c[3]
def solve2(lines):
"""Solve the problem."""
jolts = [0] + [int(line) for line in lines]
jolts.sort()
count = defaultdict(int)
count[max(jolts)] = 1
for jolt in reversed(jolts):
count[jolt] += count[jolt + 1] + count[jolt + 2] + count[jolt + 3]
return count[0]
# PART 1
def example1():
lines = filter_blank_lines(SAMPLE_INPUT.split("\n"))
result = solve(lines)
expected = 35
print(f"'sample-input' -> {result} (expected {expected})")
assert result == expected
lines = filter_blank_lines(SAMPLE_INPUT2.split("\n"))
result = solve(lines)
expected = 220
print(f"'sample-input2' -> {result} (expected {expected})")
assert result == expected
print("= " * 32)
def part1(lines):
result = solve(lines)
print(f"result is {result}")
print("= " * 32)
# PART 2
def example2():
lines = filter_blank_lines(SAMPLE_INPUT.split("\n"))
result = solve2(lines)
expected = 8
print(f"'sample-input' -> {result} (expected {expected})")
assert result == expected
lines = filter_blank_lines(SAMPLE_INPUT2.split("\n"))
result = solve2(lines)
expected = 19208
print(f"'sample-input2' -> {result} (expected {expected})")
assert result == expected
print("= " * 32)
def part2(lines):
result = solve2(lines)
print(f"result is {result}")
print("= " * 32)
if __name__ == "__main__":
example1()
lines = load_input(INPUTFILE)
part1(lines)
example2()
part2(lines) | 0.780035 | 0.430686 |
import argparse
import unittest
from unittest import mock
import tensorflow as tf
import numpy as np
import shared.utils as utils
from Inception_V3 import custom_baseline
from Inception_V3.custom_baseline import build_custom_model
class TestCustomInceptionV3Model(unittest.TestCase):
@classmethod
def setUpClass(cls):
args = argparse.Namespace()
args.nb_classes = 3
cls.args = args
@mock.patch('Inception_V3.custom_baseline.Inceptionv3')
def test_InceptionV3_is_created(self, mock_IV3):
build_custom_model(self.args, utils.INPUT_SHAPE)
# check input_tensor shape is set up right
mock_IV3.assert_called_with(self.args.nb_classes, input_shape=utils.INPUT_SHAPE)
@mock.patch('Inception_V3.custom_baseline.Inceptionv3')
def test_InceptionV3_is_compiled(self, mock_IV3):
build_custom_model(self.args, utils.INPUT_SHAPE)
self.assertTrue(mock_IV3.return_value.compile.called)
@mock.patch('Inception_V3.custom_baseline.Activation')
@mock.patch('Inception_V3.custom_baseline.BatchNormalization')
@mock.patch('Inception_V3.custom_baseline.Conv2D')
def test_conv2d_bn_uses_necessary_layers_with_proper_arguments(self, m_conv2d, m_batch_norm, m_activation):
x = np.random.rand(100, 200, 3)
filters = 12
kernel_size = (3, 3)
padding = 'valid'
strides = (2, 1)
name = '01'
output = custom_baseline.conv2d_bn(x, filters, kernel_size, padding, strides, name)
# check conv2d is working as intended
m_conv2d.assert_called_once_with(
filters, kernel_size, strides=strides, padding=padding, use_bias=False, name='01_conv'
)
m_conv2d.return_value.assert_called_once_with(x)
m_conv2d_output = m_conv2d.return_value.return_value
# check batchnorm is working as intended
m_batch_norm.assert_called_once_with(scale=False, name='01_bn')
m_batch_norm.return_value.assert_called_once_with(m_conv2d_output)
m_batch_norm_output = m_batch_norm.return_value.return_value
# check relu activation
m_activation.assert_called_once_with('relu', name='01')
m_activation.return_value.assert_called_once_with(m_batch_norm_output)
# check the output tensor is the relu activation output
self.assertEqual(m_activation.return_value.return_value, output)
def test_custom_inceptionv3_raises_valueError_when_either_input_tensor_or_shape_are_not_provided(self):
with self.assertRaises(ValueError) as ve:
custom_baseline.Inceptionv3(self.args.nb_classes)
@mock.patch('Inception_V3.custom_baseline.Model')
@mock.patch('Inception_V3.custom_baseline.Dense')
def test_custom_inceptionv3_has_dense_layer(self, m_dense, m_model):
custom_baseline.Inceptionv3(self.args.nb_classes, input_shape=utils.INPUT_SHAPE)
m_dense.assert_called_once_with(self.args.nb_classes, activation='softmax')
@mock.patch('Inception_V3.custom_baseline.Flatten')
@mock.patch('Inception_V3.custom_baseline.GlobalAveragePooling2D')
@mock.patch('Inception_V3.custom_baseline.concatenate')
@mock.patch('Inception_V3.custom_baseline.MaxPooling2D')
@mock.patch('Inception_V3.custom_baseline.AveragePooling2D')
@mock.patch('Inception_V3.custom_baseline.conv2d_bn')
@mock.patch('Inception_V3.custom_baseline.Dense')
@mock.patch('Inception_V3.custom_baseline.Input')
@mock.patch('Inception_V3.custom_baseline.Model')
def test_model_is_created_with_appropriate_inputs_and_outputs(
self, m_model, m_input, m_dense, _conv2d_bn, _avg, _max, _concat, _glob_avg, _flat
):
model = custom_baseline.Inceptionv3(self.args.nb_classes, input_shape=utils.INPUT_SHAPE)
# input tensor is setup correctly
m_input.assert_called_once_with(shape=utils.INPUT_SHAPE)
input = m_input.return_value
# output tensor is from dense layer
output = m_dense.return_value.return_value
# check model is created correctly
m_model.assert_called_once_with(inputs=input, outputs=output)
self.assertEqual(m_model.return_value, model)
if __name__ == '__main__':
unittest.main() | Plant_Disease_Detection_Benchmark_models/tests/test_inceptionv3_custom_baseline.py | import argparse
import unittest
from unittest import mock
import tensorflow as tf
import numpy as np
import shared.utils as utils
from Inception_V3 import custom_baseline
from Inception_V3.custom_baseline import build_custom_model
class TestCustomInceptionV3Model(unittest.TestCase):
@classmethod
def setUpClass(cls):
args = argparse.Namespace()
args.nb_classes = 3
cls.args = args
@mock.patch('Inception_V3.custom_baseline.Inceptionv3')
def test_InceptionV3_is_created(self, mock_IV3):
build_custom_model(self.args, utils.INPUT_SHAPE)
# check input_tensor shape is set up right
mock_IV3.assert_called_with(self.args.nb_classes, input_shape=utils.INPUT_SHAPE)
@mock.patch('Inception_V3.custom_baseline.Inceptionv3')
def test_InceptionV3_is_compiled(self, mock_IV3):
build_custom_model(self.args, utils.INPUT_SHAPE)
self.assertTrue(mock_IV3.return_value.compile.called)
@mock.patch('Inception_V3.custom_baseline.Activation')
@mock.patch('Inception_V3.custom_baseline.BatchNormalization')
@mock.patch('Inception_V3.custom_baseline.Conv2D')
def test_conv2d_bn_uses_necessary_layers_with_proper_arguments(self, m_conv2d, m_batch_norm, m_activation):
x = np.random.rand(100, 200, 3)
filters = 12
kernel_size = (3, 3)
padding = 'valid'
strides = (2, 1)
name = '01'
output = custom_baseline.conv2d_bn(x, filters, kernel_size, padding, strides, name)
# check conv2d is working as intended
m_conv2d.assert_called_once_with(
filters, kernel_size, strides=strides, padding=padding, use_bias=False, name='01_conv'
)
m_conv2d.return_value.assert_called_once_with(x)
m_conv2d_output = m_conv2d.return_value.return_value
# check batchnorm is working as intended
m_batch_norm.assert_called_once_with(scale=False, name='01_bn')
m_batch_norm.return_value.assert_called_once_with(m_conv2d_output)
m_batch_norm_output = m_batch_norm.return_value.return_value
# check relu activation
m_activation.assert_called_once_with('relu', name='01')
m_activation.return_value.assert_called_once_with(m_batch_norm_output)
# check the output tensor is the relu activation output
self.assertEqual(m_activation.return_value.return_value, output)
def test_custom_inceptionv3_raises_valueError_when_either_input_tensor_or_shape_are_not_provided(self):
with self.assertRaises(ValueError) as ve:
custom_baseline.Inceptionv3(self.args.nb_classes)
@mock.patch('Inception_V3.custom_baseline.Model')
@mock.patch('Inception_V3.custom_baseline.Dense')
def test_custom_inceptionv3_has_dense_layer(self, m_dense, m_model):
custom_baseline.Inceptionv3(self.args.nb_classes, input_shape=utils.INPUT_SHAPE)
m_dense.assert_called_once_with(self.args.nb_classes, activation='softmax')
@mock.patch('Inception_V3.custom_baseline.Flatten')
@mock.patch('Inception_V3.custom_baseline.GlobalAveragePooling2D')
@mock.patch('Inception_V3.custom_baseline.concatenate')
@mock.patch('Inception_V3.custom_baseline.MaxPooling2D')
@mock.patch('Inception_V3.custom_baseline.AveragePooling2D')
@mock.patch('Inception_V3.custom_baseline.conv2d_bn')
@mock.patch('Inception_V3.custom_baseline.Dense')
@mock.patch('Inception_V3.custom_baseline.Input')
@mock.patch('Inception_V3.custom_baseline.Model')
def test_model_is_created_with_appropriate_inputs_and_outputs(
self, m_model, m_input, m_dense, _conv2d_bn, _avg, _max, _concat, _glob_avg, _flat
):
model = custom_baseline.Inceptionv3(self.args.nb_classes, input_shape=utils.INPUT_SHAPE)
# input tensor is setup correctly
m_input.assert_called_once_with(shape=utils.INPUT_SHAPE)
input = m_input.return_value
# output tensor is from dense layer
output = m_dense.return_value.return_value
# check model is created correctly
m_model.assert_called_once_with(inputs=input, outputs=output)
self.assertEqual(m_model.return_value, model)
if __name__ == '__main__':
unittest.main() | 0.850624 | 0.591841 |
import subprocess
import csv
import os
import shutil
import unittest
class TestPlotScript(unittest.TestCase):
RESULTS_DIR = "plot-results"
REMYCC_NAME = os.path.join(os.environ["srcdir"], "RemyCC-2014-100x.dna")
PLOT_SCRIPT = os.path.join(os.environ["srcdir"], "../scripts/plot.py")
ORIGINALS_DIR = os.path.join(os.environ["srcdir"], "../scripts/originals")
SENDERRUNNER = os.path.abspath("../src/sender-runner")
def test_scripts(self):
# Run as command line, not as Python import, to check command line interface
subprocess.check_output([self.PLOT_SCRIPT, self.REMYCC_NAME, "-n=10", "-O", self.RESULTS_DIR,
"--originals", self.ORIGINALS_DIR, "--sender-runner", self.SENDERRUNNER, "--newlines"])
# Check data matches what was expected
EXPECTED_DATA = [
[0.1 , -3.652, 1.259, 15.58, 1.258, 16.08],
[0.215443469003, -1.098, 1.078, 2.305, 1.074, 2.307],
[0.464158883361, -0.493, 0.952, 1.339, 0.948, 1.337],
[1.0 , -0.444, 0.808, 1.097, 0.805, 1.099],
[2.15443469003 , -0.559, 0.876, 1.283, 0.865, 1.283],
[4.64158883361 , -0.586, 0.812, 1.219, 0.811, 1.218],
[10.0 , -0.533, 0.715, 1.038, 0.719, 1.038],
[21.5443469003 , -0.672, 0.640, 1.021, 0.640, 1.020],
[46.4158883361 , -1.119, 0.463, 1.000, 0.457, 1.000],
[100.0 , -2.233, 0.212, 1.000, 0.212, 1.000],
]
result_file = open(os.path.join(self.RESULTS_DIR, "data", "data-" + os.path.basename(self.REMYCC_NAME) + ".csv"))
result_csv = csv.reader(result_file)
for expected_row, actual_row_str in zip(EXPECTED_DATA, result_csv):
actual_row = [float(x) for x in actual_row_str]
expected_link_ppt = expected_row.pop(0)
actual_link_ppt = actual_row.pop(0)
self.assertAlmostEqual(expected_link_ppt, actual_link_ppt)
expected_norm_score = expected_row.pop(0)
actual_norm_score = actual_row.pop(0)
self.assertAlmostEqual(expected_norm_score, actual_norm_score, delta=0.5)
for expected, actual in zip(expected_row, actual_row):
self.assertLess(abs((actual - expected)/expected), 0.2, msg="{} is not within 20% of {}".format(actual, expected))
self.assertEqual(actual > 0, expected > 0)
# clean up
os.unlink("last")
shutil.rmtree(self.RESULTS_DIR)
if __name__ == '__main__':
unittest.main() | tests/run-plot-script.py |
import subprocess
import csv
import os
import shutil
import unittest
class TestPlotScript(unittest.TestCase):
RESULTS_DIR = "plot-results"
REMYCC_NAME = os.path.join(os.environ["srcdir"], "RemyCC-2014-100x.dna")
PLOT_SCRIPT = os.path.join(os.environ["srcdir"], "../scripts/plot.py")
ORIGINALS_DIR = os.path.join(os.environ["srcdir"], "../scripts/originals")
SENDERRUNNER = os.path.abspath("../src/sender-runner")
def test_scripts(self):
# Run as command line, not as Python import, to check command line interface
subprocess.check_output([self.PLOT_SCRIPT, self.REMYCC_NAME, "-n=10", "-O", self.RESULTS_DIR,
"--originals", self.ORIGINALS_DIR, "--sender-runner", self.SENDERRUNNER, "--newlines"])
# Check data matches what was expected
EXPECTED_DATA = [
[0.1 , -3.652, 1.259, 15.58, 1.258, 16.08],
[0.215443469003, -1.098, 1.078, 2.305, 1.074, 2.307],
[0.464158883361, -0.493, 0.952, 1.339, 0.948, 1.337],
[1.0 , -0.444, 0.808, 1.097, 0.805, 1.099],
[2.15443469003 , -0.559, 0.876, 1.283, 0.865, 1.283],
[4.64158883361 , -0.586, 0.812, 1.219, 0.811, 1.218],
[10.0 , -0.533, 0.715, 1.038, 0.719, 1.038],
[21.5443469003 , -0.672, 0.640, 1.021, 0.640, 1.020],
[46.4158883361 , -1.119, 0.463, 1.000, 0.457, 1.000],
[100.0 , -2.233, 0.212, 1.000, 0.212, 1.000],
]
result_file = open(os.path.join(self.RESULTS_DIR, "data", "data-" + os.path.basename(self.REMYCC_NAME) + ".csv"))
result_csv = csv.reader(result_file)
for expected_row, actual_row_str in zip(EXPECTED_DATA, result_csv):
actual_row = [float(x) for x in actual_row_str]
expected_link_ppt = expected_row.pop(0)
actual_link_ppt = actual_row.pop(0)
self.assertAlmostEqual(expected_link_ppt, actual_link_ppt)
expected_norm_score = expected_row.pop(0)
actual_norm_score = actual_row.pop(0)
self.assertAlmostEqual(expected_norm_score, actual_norm_score, delta=0.5)
for expected, actual in zip(expected_row, actual_row):
self.assertLess(abs((actual - expected)/expected), 0.2, msg="{} is not within 20% of {}".format(actual, expected))
self.assertEqual(actual > 0, expected > 0)
# clean up
os.unlink("last")
shutil.rmtree(self.RESULTS_DIR)
if __name__ == '__main__':
unittest.main() | 0.489259 | 0.353428 |
import json
from pathlib import Path
import pickle
BASE_DIR = Path("./Training/SImple_Resturant")
USER_DATABASE = BASE_DIR / "users-information.json"
FOOD_DATABASE = BASE_DIR / "food_menu.json"
class UsersInfo:
__instance = None
def __init__(self):
self.users = dict()
self.keys = ['password', 'phone', 'address', 'level', 'past_buy']
@classmethod
def __new__(cls, *args, **kwargs):
if cls.__instance == None:
cls.__instance = super().__new__(*args, **kwargs)
return cls.__instance
def add_user(self, username, user_info):
if self.data_validation(user_info):
load_file = self.read_users_info
load_file[username] = user_info
with open(USER_DATABASE, "r+") as user_file:
json.dump(load_file, user_file)
return True
@property
def read_users_info(self):
try:
with open(USER_DATABASE, "r") as user_file:
return json.load(user_file)
except:
return dict()
def data_validation(self, info):
for i in info:
if i not in self.keys:
return False
return True
def check_user(self, username, password):
load_file = self.read_users_info
if username in load_file:
if load_file[username]["password"] == password:
return load_file[username]["level"]
return False
def change_info(self, username,prop, new_val):
load_file = self.read_users_info
if prop != "past_buy":
load_file[username][prop] = new_val
else:
load_file[username][prop] += new_val
with open(USER_DATABASE, "w") as user_file:
json.dump(load_file, user_file)
return True
def read_user_info(self, user):
load_file = self.read_users_info
return load_file[user]
class Foods:
def add_to_menu(self,name, food_info):
load_file = self.read_menu
with open(FOOD_DATABASE, "w") as food_file:
load_file[name] = food_info
json.dump(load_file, food_file)
return True
@property
def read_menu(self):
with open(FOOD_DATABASE, "r") as food_file:
return json.load(food_file)
def remove(self, name):
load_file = self.read_menu
try: load_file.remove(name)
except: return False
with open(Foods, "w") as food_file:
json.dump(load_file, food_file)
return True
def increase(self, name, qty):
load_file = self.read_menu
load_file[name][0] += qty
with open(FOOD_DATABASE, "w") as food_file:
json.dump(load_file, food_file)
return True
def change_price(self, name, price):
load_file = self.read_menu
load_file[name][1] += price
with open(FOOD_DATABASE, "w") as food_file:
json.dump(load_file, food_file)
return True
def decrease(self, cart):
load_file = self.read_menu
total_price = 0
for k,v in cart:
load_file[k][0] -= v
total_price += load_file[k][1] * v
with open(FOOD_DATABASE, "w") as food_file:
json.dump(load_file, food_file)
return total_price
if __name__ == '__main__':
obj1 = UsersInfo()
obj2 = UsersInfo()
print(obj1)
print(obj2) | SImple_Resturant/model.py | import json
from pathlib import Path
import pickle
BASE_DIR = Path("./Training/SImple_Resturant")
USER_DATABASE = BASE_DIR / "users-information.json"
FOOD_DATABASE = BASE_DIR / "food_menu.json"
class UsersInfo:
__instance = None
def __init__(self):
self.users = dict()
self.keys = ['password', 'phone', 'address', 'level', 'past_buy']
@classmethod
def __new__(cls, *args, **kwargs):
if cls.__instance == None:
cls.__instance = super().__new__(*args, **kwargs)
return cls.__instance
def add_user(self, username, user_info):
if self.data_validation(user_info):
load_file = self.read_users_info
load_file[username] = user_info
with open(USER_DATABASE, "r+") as user_file:
json.dump(load_file, user_file)
return True
@property
def read_users_info(self):
try:
with open(USER_DATABASE, "r") as user_file:
return json.load(user_file)
except:
return dict()
def data_validation(self, info):
for i in info:
if i not in self.keys:
return False
return True
def check_user(self, username, password):
load_file = self.read_users_info
if username in load_file:
if load_file[username]["password"] == password:
return load_file[username]["level"]
return False
def change_info(self, username,prop, new_val):
load_file = self.read_users_info
if prop != "past_buy":
load_file[username][prop] = new_val
else:
load_file[username][prop] += new_val
with open(USER_DATABASE, "w") as user_file:
json.dump(load_file, user_file)
return True
def read_user_info(self, user):
load_file = self.read_users_info
return load_file[user]
class Foods:
def add_to_menu(self,name, food_info):
load_file = self.read_menu
with open(FOOD_DATABASE, "w") as food_file:
load_file[name] = food_info
json.dump(load_file, food_file)
return True
@property
def read_menu(self):
with open(FOOD_DATABASE, "r") as food_file:
return json.load(food_file)
def remove(self, name):
load_file = self.read_menu
try: load_file.remove(name)
except: return False
with open(Foods, "w") as food_file:
json.dump(load_file, food_file)
return True
def increase(self, name, qty):
load_file = self.read_menu
load_file[name][0] += qty
with open(FOOD_DATABASE, "w") as food_file:
json.dump(load_file, food_file)
return True
def change_price(self, name, price):
load_file = self.read_menu
load_file[name][1] += price
with open(FOOD_DATABASE, "w") as food_file:
json.dump(load_file, food_file)
return True
def decrease(self, cart):
load_file = self.read_menu
total_price = 0
for k,v in cart:
load_file[k][0] -= v
total_price += load_file[k][1] * v
with open(FOOD_DATABASE, "w") as food_file:
json.dump(load_file, food_file)
return total_price
if __name__ == '__main__':
obj1 = UsersInfo()
obj2 = UsersInfo()
print(obj1)
print(obj2) | 0.255251 | 0.080105 |
import requests
from hashlib import md5
from allauth.socialaccount.providers.base import ProviderAccount
from allauth.socialaccount.providers.core.oauth2.provider import OAuth2Provider
class MailRuAccount(ProviderAccount):
def get_profile_url(self):
return self.account.extra_data.get('link')
def get_avatar_url(self):
ret = None
if self.account.extra_data.get('has_pic'):
pic_big_url = self.account.extra_data.get('pic_big')
pic_small_url = self.account.extra_data.get('pic_small')
if pic_big_url:
return pic_big_url
elif pic_small_url:
return pic_small_url
else:
return ret
def to_str(self):
dflt = super(MailRuAccount, self).to_str()
return self.account.extra_data.get('name', dflt)
class MailRuProvider(OAuth2Provider):
id = 'mailru'
name = 'Mail.RU'
account_class = MailRuAccount
access_token_url = 'https://connect.mail.ru/oauth/token'
authorize_url = 'https://connect.mail.ru/oauth/authorize'
profile_url = 'http://www.appsmail.ru/platform/api'
def complete_login(self, request, app, token, **kwargs):
uid = kwargs['response']['x_mailru_vid']
data = {
'method': 'users.getInfo',
'app_id': app.client_id,
'secure': '1',
'uids': uid
}
param_list = sorted(list(item + '=' + data[item] for item in data))
data['sig'] = md5(
(''.join(param_list) + app.secret).encode('utf-8')
).hexdigest()
response = requests.get(self.get_profile_url(request), params=data)
extra_data = response.json()[0]
return self.sociallogin_from_response(request, extra_data)
def extract_uid(self, data):
return data['uid']
def extract_common_fields(self, data):
return dict(email=data.get('email'),
last_name=data.get('last_name'),
username=data.get('nick'),
first_name=data.get('first_name'))
provider_classes = [MailRuProvider] | allauth/socialaccount/providers/dev_sites/mailru/provider.py | import requests
from hashlib import md5
from allauth.socialaccount.providers.base import ProviderAccount
from allauth.socialaccount.providers.core.oauth2.provider import OAuth2Provider
class MailRuAccount(ProviderAccount):
def get_profile_url(self):
return self.account.extra_data.get('link')
def get_avatar_url(self):
ret = None
if self.account.extra_data.get('has_pic'):
pic_big_url = self.account.extra_data.get('pic_big')
pic_small_url = self.account.extra_data.get('pic_small')
if pic_big_url:
return pic_big_url
elif pic_small_url:
return pic_small_url
else:
return ret
def to_str(self):
dflt = super(MailRuAccount, self).to_str()
return self.account.extra_data.get('name', dflt)
class MailRuProvider(OAuth2Provider):
id = 'mailru'
name = 'Mail.RU'
account_class = MailRuAccount
access_token_url = 'https://connect.mail.ru/oauth/token'
authorize_url = 'https://connect.mail.ru/oauth/authorize'
profile_url = 'http://www.appsmail.ru/platform/api'
def complete_login(self, request, app, token, **kwargs):
uid = kwargs['response']['x_mailru_vid']
data = {
'method': 'users.getInfo',
'app_id': app.client_id,
'secure': '1',
'uids': uid
}
param_list = sorted(list(item + '=' + data[item] for item in data))
data['sig'] = md5(
(''.join(param_list) + app.secret).encode('utf-8')
).hexdigest()
response = requests.get(self.get_profile_url(request), params=data)
extra_data = response.json()[0]
return self.sociallogin_from_response(request, extra_data)
def extract_uid(self, data):
return data['uid']
def extract_common_fields(self, data):
return dict(email=data.get('email'),
last_name=data.get('last_name'),
username=data.get('nick'),
first_name=data.get('first_name'))
provider_classes = [MailRuProvider] | 0.284974 | 0.136407 |
import unittest
import filecmp
import time
from threading import Event
from rx import *
from TorrentPython.DownloadManager import DownloadManager
from TorrentPython.MetaInfo import MetaInfo
from TorrentPython.RoutingTable import RoutingTable
from TorrentPython.TorrentUtils import TorrentUtils
SAMPLE_TORRENT_PATH = '../Resources/sample.torrent'
ROUTING_TABLE_PATH = '../Resources/routing_table.py'
class DownloadManagerTest(unittest.TestCase):
def setUp(self):
self.client_id = TorrentUtils.getPeerID()
self.metainfo = MetaInfo.create_from_torrent(SAMPLE_TORRENT_PATH)
self.info = self.metainfo.get_info()
self.dest = 'D:/sandbox/'
# self.routing_table = RoutingTable.load(ROUTING_TABLE_PATH)
self.routing_table = None
self.answer = 'D:/sandbox2/'
def tearDown(self):
pass
@unittest.skip("clear")
def test_new(self):
testObj = DownloadManager.start(self.client_id, self.metainfo, self.dest, self.routing_table)
testObj.stop()
del testObj
@unittest.skip("wait")
def test_on_off(self):
test_obj = DownloadManager.start(self.client_id, self.metainfo, self.dest, self.routing_table)
self.assertIsNotNone(test_obj)
test_obj.subscribe(lambda msg: print(msg))
test_obj.on()
time.sleep(10)
# test_obj.off()
test_obj.stop()
del test_obj
# @unittest.skip("wait")
def test_download(self):
testObj = DownloadManager.start(self.client_id, self.metainfo, self.dest, self.routing_table)
self.assertIsNotNone(testObj)
endEvent = Event()
class DownloadManagerObserver(Observer):
def __init__(self, event):
self.endEvent = event
def on_next(self, msg):
print(msg)
if msg.bitfield_ext.get_percent() == 100:
endEvent.set()
def on_completed(self):
print('on_completed')
def on_error(self, e):
print('on_error')
testObj.subscribe(DownloadManagerObserver(endEvent))
testObj.on()
endEvent.wait()
# self.assertTrue(
# filecmp.cmp(self.dest + self.info.get_name().decode(),
# self.answer + self.info.get_name().decode()))
testObj.stop()
del testObj
if __name__ == '__main__':
unittest.main() | TorrentPython/unittest/DownloadManager_test.py | import unittest
import filecmp
import time
from threading import Event
from rx import *
from TorrentPython.DownloadManager import DownloadManager
from TorrentPython.MetaInfo import MetaInfo
from TorrentPython.RoutingTable import RoutingTable
from TorrentPython.TorrentUtils import TorrentUtils
SAMPLE_TORRENT_PATH = '../Resources/sample.torrent'
ROUTING_TABLE_PATH = '../Resources/routing_table.py'
class DownloadManagerTest(unittest.TestCase):
def setUp(self):
self.client_id = TorrentUtils.getPeerID()
self.metainfo = MetaInfo.create_from_torrent(SAMPLE_TORRENT_PATH)
self.info = self.metainfo.get_info()
self.dest = 'D:/sandbox/'
# self.routing_table = RoutingTable.load(ROUTING_TABLE_PATH)
self.routing_table = None
self.answer = 'D:/sandbox2/'
def tearDown(self):
pass
@unittest.skip("clear")
def test_new(self):
testObj = DownloadManager.start(self.client_id, self.metainfo, self.dest, self.routing_table)
testObj.stop()
del testObj
@unittest.skip("wait")
def test_on_off(self):
test_obj = DownloadManager.start(self.client_id, self.metainfo, self.dest, self.routing_table)
self.assertIsNotNone(test_obj)
test_obj.subscribe(lambda msg: print(msg))
test_obj.on()
time.sleep(10)
# test_obj.off()
test_obj.stop()
del test_obj
# @unittest.skip("wait")
def test_download(self):
testObj = DownloadManager.start(self.client_id, self.metainfo, self.dest, self.routing_table)
self.assertIsNotNone(testObj)
endEvent = Event()
class DownloadManagerObserver(Observer):
def __init__(self, event):
self.endEvent = event
def on_next(self, msg):
print(msg)
if msg.bitfield_ext.get_percent() == 100:
endEvent.set()
def on_completed(self):
print('on_completed')
def on_error(self, e):
print('on_error')
testObj.subscribe(DownloadManagerObserver(endEvent))
testObj.on()
endEvent.wait()
# self.assertTrue(
# filecmp.cmp(self.dest + self.info.get_name().decode(),
# self.answer + self.info.get_name().decode()))
testObj.stop()
del testObj
if __name__ == '__main__':
unittest.main() | 0.338624 | 0.202148 |
class LDA_original:
@staticmethod
def _convergence_(new, old, epsilon = 1.0e-3):
'''
Check convergence.
'''
delta = abs(new - old)
return np.all(delta) < epsilon
@staticmethod
def _normalization_col(x):
'''
Normalize a matrix.
Each element is divided by the corresponding column sum.
'''
return x/np.sum(x,0)
@staticmethod
def _accumulate_Phi(beta, Phi, doc):
'''
This function accumulates the effect of Phi_new from all documents after e step.
beta is V*k matrix.
Phi is N_d * k matrix.
Return updated beta.
'''
row_index = list(doc.keys())
word_count = list(doc.values())
for i in range(len(row_index)):
beta[row_index[i],:] = word_count[i] * Phi[i,:]
return beta
def __init__(self, k, max_em_iter=50, max_alpha_iter=50, max_Estep_iter=50):
self._k = k
self._max_em_iter = max_em_iter
self._max_alpha_iter = max_alpha_iter
self._max_Estep_iter = max_Estep_iter
def initializaiton(self, V):
'''
Initialize alpha and beta.
alpha is a k-dim vector. beta is V*k matrix.
'''
k = self._k
alpha = np.random.uniform(size = k)
alpha_new = alpha/np.sum(alpha)
beta = np.random.dirichlet(alpha_new, V)
return alpha_new, beta
def Estep(self, doc, alpha, beta, N_d):
'''
E step for a document, which calculate the posterior parameters.
beta_old and alpha-old is coming from previous iteration.
Return Phi and gamma of a document.
'''
k = self._k
max_iter = self._max_Estep_iter
gamma_old = [alpha[i] + N_d/k for i in range(k)]
row_index = list(doc.keys())
word_count = np.array(list(doc.values()))
for i in range(max_iter):
# Update Phi
Phi = np.zeros((N_d, k))
for i in range(N_d):
for j in range(k):
Phi[i,j] = beta[row_index[i],j] * np.exp(digamma(gamma_old[j]))
Phi[i,:] = Phi[i,:]/np.sum(Phi[i,:])
#Update gamma
Phi_sum = np.zeros(k)
for j in range(k):
z = 0
for i in range(N_d):
z += Phi[i,j] * word_count[i]
Phi_sum[j] = z
gamma_new = alpha + Phi_sum
# Converge or not
if (i>0) & self._convergence_(gamma_new, gamma_old):
break
else:
gamma_old = gamma_new.copy()
return gamma_new, Phi
def newton_raphson(self, alpha_old, gamma_matrix):
'''
This function uses New Raphson method to update alpha in the M step.
alpha_old is a k-dim vector.
gamma_matrix is a M * k matrix which stores all gamma from M documents.
Return updated alpha.
'''
k = self._k
max_iter = self._max_alpha_iter
M = gamma_matrix.shape[0]
pg = np.sum(digamma(gamma_matrix), 0) - np.sum(digamma(np.sum(gamma_matrix, 1)))
alpha_new = alpha_old.copy()
for t in range(max_iter):
alpha_sum = np.sum(alpha_old)
g = M * (digamma(alpha_sum) - digamma(alpha_old)) + pg
h = -M * polygamma(1, alpha_old)
z = M * polygamma(1, alpha_sum)
c = np.sum(g/h)/(z**(-1.0) + np.sum(h**(-1.0)))
delta = (g-c)/h
alpha_new -= delta
if np.any(alpha_new) < 0:
alpha_new = self.newton_raphson(alpha_old/10, gamma_matrix)
return alpha_new
if (t > 1) & self._convergence_(delta, np.zeros((1,k))):
break
else:
alpha_old = alpha_new.copy()
return alpha_new
def fit(self, doc, vocabulary):
'''
Latent Dirichlet Allocation Model.
doc is a set of documents, each document is a dictionary.
vocabulary contains the words in all documents.
Return updated alpha and beta.
'''
k = self._k
max_iter = self._max_em_iter
N_d = [len(d) for d in doc] # Get the length of each document.
V = len(vocabulary) # Get the length of vocabulary
M = len(doc) # Get the document number.
# Initialize alpha, beta and the statistics od gamma
alpha_new, beta_new = self.initializaiton(V)
gamma_matrix = np.zeros((M, k))
for iter in range(max_iter):
beta_old = beta_new.copy()
alpha_old = alpha_new.copy()
# E step
for i in range(M):
gamma, Phi = self.Estep(doc[i], alpha_old, beta_old, N_d[i])
beta_new = self._accumulate_Phi(beta_new, Phi, doc[i])
gamma_matrix[i,:] = gamma
# M step
alpha_new = self.newton_raphson(alpha_old, gamma_matrix)
beta_new = self._normalization_col(beta_new)
# check convergence
if self._convergence_(alpha_new, alpha_old) & self._convergence_(np.sum(beta_new,0), np.sum(beta_old,0)):
break
return alpha_new, beta_new | LDA_withoutOPT.py | class LDA_original:
@staticmethod
def _convergence_(new, old, epsilon = 1.0e-3):
'''
Check convergence.
'''
delta = abs(new - old)
return np.all(delta) < epsilon
@staticmethod
def _normalization_col(x):
'''
Normalize a matrix.
Each element is divided by the corresponding column sum.
'''
return x/np.sum(x,0)
@staticmethod
def _accumulate_Phi(beta, Phi, doc):
'''
This function accumulates the effect of Phi_new from all documents after e step.
beta is V*k matrix.
Phi is N_d * k matrix.
Return updated beta.
'''
row_index = list(doc.keys())
word_count = list(doc.values())
for i in range(len(row_index)):
beta[row_index[i],:] = word_count[i] * Phi[i,:]
return beta
def __init__(self, k, max_em_iter=50, max_alpha_iter=50, max_Estep_iter=50):
self._k = k
self._max_em_iter = max_em_iter
self._max_alpha_iter = max_alpha_iter
self._max_Estep_iter = max_Estep_iter
def initializaiton(self, V):
'''
Initialize alpha and beta.
alpha is a k-dim vector. beta is V*k matrix.
'''
k = self._k
alpha = np.random.uniform(size = k)
alpha_new = alpha/np.sum(alpha)
beta = np.random.dirichlet(alpha_new, V)
return alpha_new, beta
def Estep(self, doc, alpha, beta, N_d):
'''
E step for a document, which calculate the posterior parameters.
beta_old and alpha-old is coming from previous iteration.
Return Phi and gamma of a document.
'''
k = self._k
max_iter = self._max_Estep_iter
gamma_old = [alpha[i] + N_d/k for i in range(k)]
row_index = list(doc.keys())
word_count = np.array(list(doc.values()))
for i in range(max_iter):
# Update Phi
Phi = np.zeros((N_d, k))
for i in range(N_d):
for j in range(k):
Phi[i,j] = beta[row_index[i],j] * np.exp(digamma(gamma_old[j]))
Phi[i,:] = Phi[i,:]/np.sum(Phi[i,:])
#Update gamma
Phi_sum = np.zeros(k)
for j in range(k):
z = 0
for i in range(N_d):
z += Phi[i,j] * word_count[i]
Phi_sum[j] = z
gamma_new = alpha + Phi_sum
# Converge or not
if (i>0) & self._convergence_(gamma_new, gamma_old):
break
else:
gamma_old = gamma_new.copy()
return gamma_new, Phi
def newton_raphson(self, alpha_old, gamma_matrix):
'''
This function uses New Raphson method to update alpha in the M step.
alpha_old is a k-dim vector.
gamma_matrix is a M * k matrix which stores all gamma from M documents.
Return updated alpha.
'''
k = self._k
max_iter = self._max_alpha_iter
M = gamma_matrix.shape[0]
pg = np.sum(digamma(gamma_matrix), 0) - np.sum(digamma(np.sum(gamma_matrix, 1)))
alpha_new = alpha_old.copy()
for t in range(max_iter):
alpha_sum = np.sum(alpha_old)
g = M * (digamma(alpha_sum) - digamma(alpha_old)) + pg
h = -M * polygamma(1, alpha_old)
z = M * polygamma(1, alpha_sum)
c = np.sum(g/h)/(z**(-1.0) + np.sum(h**(-1.0)))
delta = (g-c)/h
alpha_new -= delta
if np.any(alpha_new) < 0:
alpha_new = self.newton_raphson(alpha_old/10, gamma_matrix)
return alpha_new
if (t > 1) & self._convergence_(delta, np.zeros((1,k))):
break
else:
alpha_old = alpha_new.copy()
return alpha_new
def fit(self, doc, vocabulary):
'''
Latent Dirichlet Allocation Model.
doc is a set of documents, each document is a dictionary.
vocabulary contains the words in all documents.
Return updated alpha and beta.
'''
k = self._k
max_iter = self._max_em_iter
N_d = [len(d) for d in doc] # Get the length of each document.
V = len(vocabulary) # Get the length of vocabulary
M = len(doc) # Get the document number.
# Initialize alpha, beta and the statistics od gamma
alpha_new, beta_new = self.initializaiton(V)
gamma_matrix = np.zeros((M, k))
for iter in range(max_iter):
beta_old = beta_new.copy()
alpha_old = alpha_new.copy()
# E step
for i in range(M):
gamma, Phi = self.Estep(doc[i], alpha_old, beta_old, N_d[i])
beta_new = self._accumulate_Phi(beta_new, Phi, doc[i])
gamma_matrix[i,:] = gamma
# M step
alpha_new = self.newton_raphson(alpha_old, gamma_matrix)
beta_new = self._normalization_col(beta_new)
# check convergence
if self._convergence_(alpha_new, alpha_old) & self._convergence_(np.sum(beta_new,0), np.sum(beta_old,0)):
break
return alpha_new, beta_new | 0.801042 | 0.545286 |
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
from google.protobuf import descriptor_pb2
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
import PortEnumsProto_pb2 as PortEnumsProto__pb2
DESCRIPTOR = _descriptor.FileDescriptor(
name='PortProto.proto',
package='net',
syntax='proto3',
serialized_pb=_b('\n\x0fPortProto.proto\x12\x03net\x1a\x14PortEnumsProto.proto\"\xdb\x01\n\tPortProto\x12\x13\n\x0bport_number\x18\x01 \x01(\t\x12\x12\n\nis_enabled\x18\x02 \x01(\x08\x12\'\n\x04type\x18\x03 \x01(\x0e\x32\x19.net.device.PortTypeProto\x12\x12\n\nport_speed\x18\x04 \x01(\x03\x12\x34\n\x0b\x61nnotations\x18\x05 \x03(\x0b\x32\x1f.net.PortProto.AnnotationsEntry\x1a\x32\n\x10\x41nnotationsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\x42!\n\x1forg.onosproject.grpc.net.modelsb\x06proto3')
,
dependencies=[PortEnumsProto__pb2.DESCRIPTOR,])
_PORTPROTO_ANNOTATIONSENTRY = _descriptor.Descriptor(
name='AnnotationsEntry',
full_name='net.PortProto.AnnotationsEntry',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='key', full_name='net.PortProto.AnnotationsEntry.key', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='value', full_name='net.PortProto.AnnotationsEntry.value', index=1,
number=2, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=_descriptor._ParseOptions(descriptor_pb2.MessageOptions(), _b('8\001')),
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=216,
serialized_end=266,
)
_PORTPROTO = _descriptor.Descriptor(
name='PortProto',
full_name='net.PortProto',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='port_number', full_name='net.PortProto.port_number', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='is_enabled', full_name='net.PortProto.is_enabled', index=1,
number=2, type=8, cpp_type=7, label=1,
has_default_value=False, default_value=False,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='type', full_name='net.PortProto.type', index=2,
number=3, type=14, cpp_type=8, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='port_speed', full_name='net.PortProto.port_speed', index=3,
number=4, type=3, cpp_type=2, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='annotations', full_name='net.PortProto.annotations', index=4,
number=5, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[_PORTPROTO_ANNOTATIONSENTRY, ],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=47,
serialized_end=266,
)
_PORTPROTO_ANNOTATIONSENTRY.containing_type = _PORTPROTO
_PORTPROTO.fields_by_name['type'].enum_type = PortEnumsProto__pb2._PORTTYPEPROTO
_PORTPROTO.fields_by_name['annotations'].message_type = _PORTPROTO_ANNOTATIONSENTRY
DESCRIPTOR.message_types_by_name['PortProto'] = _PORTPROTO
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
PortProto = _reflection.GeneratedProtocolMessageType('PortProto', (_message.Message,), dict(
AnnotationsEntry = _reflection.GeneratedProtocolMessageType('AnnotationsEntry', (_message.Message,), dict(
DESCRIPTOR = _PORTPROTO_ANNOTATIONSENTRY,
__module__ = 'PortProto_pb2'
# @@protoc_insertion_point(class_scope:net.PortProto.AnnotationsEntry)
))
,
DESCRIPTOR = _PORTPROTO,
__module__ = 'PortProto_pb2'
# @@protoc_insertion_point(class_scope:net.PortProto)
))
_sym_db.RegisterMessage(PortProto)
_sym_db.RegisterMessage(PortProto.AnnotationsEntry)
DESCRIPTOR.has_options = True
DESCRIPTOR._options = _descriptor._ParseOptions(descriptor_pb2.FileOptions(), _b('\n\037org.onosproject.grpc.net.models'))
_PORTPROTO_ANNOTATIONSENTRY.has_options = True
_PORTPROTO_ANNOTATIONSENTRY._options = _descriptor._ParseOptions(descriptor_pb2.MessageOptions(), _b('8\001'))
# @@protoc_insertion_point(module_scope) | src/onos_grpc_demo/proto/PortProto_pb2.py |
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
from google.protobuf import descriptor_pb2
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
import PortEnumsProto_pb2 as PortEnumsProto__pb2
DESCRIPTOR = _descriptor.FileDescriptor(
name='PortProto.proto',
package='net',
syntax='proto3',
serialized_pb=_b('\n\x0fPortProto.proto\x12\x03net\x1a\x14PortEnumsProto.proto\"\xdb\x01\n\tPortProto\x12\x13\n\x0bport_number\x18\x01 \x01(\t\x12\x12\n\nis_enabled\x18\x02 \x01(\x08\x12\'\n\x04type\x18\x03 \x01(\x0e\x32\x19.net.device.PortTypeProto\x12\x12\n\nport_speed\x18\x04 \x01(\x03\x12\x34\n\x0b\x61nnotations\x18\x05 \x03(\x0b\x32\x1f.net.PortProto.AnnotationsEntry\x1a\x32\n\x10\x41nnotationsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\x42!\n\x1forg.onosproject.grpc.net.modelsb\x06proto3')
,
dependencies=[PortEnumsProto__pb2.DESCRIPTOR,])
_PORTPROTO_ANNOTATIONSENTRY = _descriptor.Descriptor(
name='AnnotationsEntry',
full_name='net.PortProto.AnnotationsEntry',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='key', full_name='net.PortProto.AnnotationsEntry.key', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='value', full_name='net.PortProto.AnnotationsEntry.value', index=1,
number=2, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=_descriptor._ParseOptions(descriptor_pb2.MessageOptions(), _b('8\001')),
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=216,
serialized_end=266,
)
_PORTPROTO = _descriptor.Descriptor(
name='PortProto',
full_name='net.PortProto',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='port_number', full_name='net.PortProto.port_number', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='is_enabled', full_name='net.PortProto.is_enabled', index=1,
number=2, type=8, cpp_type=7, label=1,
has_default_value=False, default_value=False,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='type', full_name='net.PortProto.type', index=2,
number=3, type=14, cpp_type=8, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='port_speed', full_name='net.PortProto.port_speed', index=3,
number=4, type=3, cpp_type=2, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
_descriptor.FieldDescriptor(
name='annotations', full_name='net.PortProto.annotations', index=4,
number=5, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[_PORTPROTO_ANNOTATIONSENTRY, ],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=47,
serialized_end=266,
)
_PORTPROTO_ANNOTATIONSENTRY.containing_type = _PORTPROTO
_PORTPROTO.fields_by_name['type'].enum_type = PortEnumsProto__pb2._PORTTYPEPROTO
_PORTPROTO.fields_by_name['annotations'].message_type = _PORTPROTO_ANNOTATIONSENTRY
DESCRIPTOR.message_types_by_name['PortProto'] = _PORTPROTO
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
PortProto = _reflection.GeneratedProtocolMessageType('PortProto', (_message.Message,), dict(
AnnotationsEntry = _reflection.GeneratedProtocolMessageType('AnnotationsEntry', (_message.Message,), dict(
DESCRIPTOR = _PORTPROTO_ANNOTATIONSENTRY,
__module__ = 'PortProto_pb2'
# @@protoc_insertion_point(class_scope:net.PortProto.AnnotationsEntry)
))
,
DESCRIPTOR = _PORTPROTO,
__module__ = 'PortProto_pb2'
# @@protoc_insertion_point(class_scope:net.PortProto)
))
_sym_db.RegisterMessage(PortProto)
_sym_db.RegisterMessage(PortProto.AnnotationsEntry)
DESCRIPTOR.has_options = True
DESCRIPTOR._options = _descriptor._ParseOptions(descriptor_pb2.FileOptions(), _b('\n\037org.onosproject.grpc.net.models'))
_PORTPROTO_ANNOTATIONSENTRY.has_options = True
_PORTPROTO_ANNOTATIONSENTRY._options = _descriptor._ParseOptions(descriptor_pb2.MessageOptions(), _b('8\001'))
# @@protoc_insertion_point(module_scope) | 0.211254 | 0.08438 |
from collections import OrderedDict
from django.views.generic import TemplateView
from django.contrib.postgres.fields.jsonb import KeyTextTransform
from django.db.models import (
Case, When, F, Count, Sum, FloatField, Avg, Min, Max, Q
)
from django.db.models.functions import Cast
from rest_framework.views import APIView
from rest_framework.response import Response
from bims.api_views.search_version_2 import SearchVersion2
from bims.models import LocationSite
from sass.models import (
SiteVisitTaxon,
SiteVisitBiotopeTaxon,
SassEcologicalCategory,
SassEcologicalCondition
)
class SassDashboardMultipleSitesView(TemplateView):
template_name = 'sass_dashboard_multiple_sites.html'
class SassDashboardMultipleSitesApiView(APIView):
site_visit_taxa = SiteVisitTaxon.objects.none()
location_sites = LocationSite.objects.none()
def get_sass_score_chart_data(self):
summary = self.site_visit_taxa.annotate(
date=F('site_visit__site_visit_date'),
site_code=Case(
When(site_visit__location_site__site_code__isnull=False,
then='site_visit__location_site__site_code'),
default='site_visit__location_site__name'
),
sass_id=F('site_visit__id'),
site_id=F('site_visit__location_site__id'),
).values('site_code', 'date', 'site_id', 'sass_id').annotate(
count=Count('sass_taxon'),
sass_score=Sum(Case(
When(
condition=Q(site_visit__sass_version=5,
sass_taxon__sass_5_score__isnull=False),
then='sass_taxon__sass_5_score'),
default='sass_taxon__score'
)),
).annotate(
aspt=Cast(F('sass_score'), FloatField()) / Cast(F('count'),
FloatField()),
).order_by('-date')
chart_data = {
'sass_ids': [],
'site_id': [],
'site_code': [],
'sass_score': [],
'aspt_score': [],
'taxa_count': [],
'date': [],
'aspt_average': [],
'taxa_number_average': [],
'sass_score_average': [],
'number_assessments': [],
}
site_codes = []
for data in summary:
# Get the latest data
if data['site_code'] in site_codes:
continue
site_codes.append(data['site_code'])
chart_data['site_code'].append(
data['site_code']
)
chart_data['sass_ids'].append(
data['sass_id']
)
chart_data['site_id'].append(
data['site_id']
)
chart_data['sass_score'].append(
data['sass_score']
)
chart_data['aspt_score'].append(
round(data['aspt'], 2)
)
chart_data['taxa_count'].append(
data['count']
)
chart_data['date'].append(
data['date'].strftime('%d-%m-%Y')
)
chart_data['number_assessments'].append(
len(summary.filter(site=data['site_id']))
)
averages = summary.filter(site=data['site_id']).aggregate(
taxa_number_average=Avg('count'),
sass_score_average=Avg('sass_score'),
aspt_average=Avg('aspt'),
taxa_number_min=Min('count'),
sass_score_min=Min('sass_score'),
aspt_min=Min('aspt'),
taxa_number_max=Max('count'),
sass_score_max=Max('sass_score'),
aspt_max=Max('aspt')
)
chart_data['taxa_number_average'].append({
'avg': averages['taxa_number_average'],
'min': averages['taxa_number_min'],
'max': averages['taxa_number_max'],
})
chart_data['sass_score_average'].append({
'avg': averages['sass_score_average'],
'min': averages['sass_score_min'],
'max': averages['sass_score_max'],
})
chart_data['aspt_average'].append({
'avg': averages['aspt_average'],
'min': averages['aspt_min'],
'max': averages['aspt_max'],
})
return chart_data
def get_taxa_per_biotope_data(self):
latest_site_visits = self.site_visit_taxa.order_by(
'site',
'-site_visit__site_visit_date'
).distinct('site').values('site_visit')
sass_taxon_data = (
self.site_visit_taxa.filter(
site_visit__in=latest_site_visits
).annotate(
site_code=Case(
When(site_visit__location_site__site_code__isnull=False,
then='site_visit__location_site__site_code'),
default='site_visit__location_site__name'
),
taxon_name=Case(
When(
condition=Q(site_visit__sass_version=5,
sass_taxon__taxon_sass_5__isnull=False),
then='sass_taxon__taxon_sass_5'),
default='sass_taxon__taxon_sass_4'
),
sass_score=Case(
When(
condition=Q(site_visit__sass_version=5,
sass_taxon__sass_5_score__isnull=False),
then='sass_taxon__sass_5_score'),
default='sass_taxon__score'
),
site_id=F('site_visit__location_site__id'),
canonical_name=F('taxonomy__canonical_name'),
abundance=F('taxon_abundance__abc'),
score=F('sass_score'),
group_name=F('taxonomy__taxongroup__name'),
display_order=Case(
When(
condition=Q(
site_visit__sass_version=5,
sass_taxon__display_order_sass_5__isnull=False),
then='sass_taxon__display_order_sass_5'),
default='sass_taxon__display_order_sass_4'
),
).values(
'site_id',
'site_code',
'sass_taxon_id',
'canonical_name',
'abundance',
'taxon_name',
'score',
'group_name',
'display_order'
)
.order_by('display_order')
)
biotope_data = (
SiteVisitBiotopeTaxon.objects.filter(
sass_taxon__in=self.site_visit_taxa.values_list('sass_taxon'),
site_visit__in=latest_site_visits
).annotate(
canonical_name=F('taxon__canonical_name'),
abundance=F('taxon_abundance__abc'),
biotope_name=F('biotope__name'),
site_id=F('site_visit__location_site__id'),
).values(
'site_id',
'biotope_name',
'sass_taxon_id',
'canonical_name',
'abundance')
)
sass_taxon_data_dict = OrderedDict()
for taxon_data in list(sass_taxon_data):
name = '{name}-{sass_taxon_id}'.format(
name=taxon_data['canonical_name'],
sass_taxon_id=taxon_data['sass_taxon_id']
)
site_id = taxon_data['site_id']
if name not in sass_taxon_data_dict:
sass_taxon_data_dict[name] = taxon_data
sass_taxon_data_dict[name]['site_abundance'] = {}
sass_taxon_data_dict[name]['site_abundance'][site_id] = (
taxon_data['abundance']
)
try:
sass_taxon_data_dict[name].pop('site_id')
sass_taxon_data_dict[name].pop('abundance')
sass_taxon_data_dict[name].pop('site_code')
except KeyError:
pass
for biotope in biotope_data:
key = '{name}-{sass_taxon_id}'.format(
name=biotope['canonical_name'],
sass_taxon_id=biotope['sass_taxon_id']
)
site_id = str(biotope['site_id'])
if key in sass_taxon_data_dict:
if 'biotope_data' not in sass_taxon_data_dict[key]:
sass_taxon_data_dict[key]['biotope_data'] = {}
if site_id not in sass_taxon_data_dict[key]['biotope_data']:
sass_taxon_data_dict[key]['biotope_data'][site_id] = {}
sass_taxon_data_dict[key][
'biotope_data'][site_id][biotope['biotope_name']] = (
biotope['abundance']
)
return sass_taxon_data_dict
def get_biotope_ratings_chart_data(self, sass_ids=None):
data = {}
biotope_ratings = self.site_visit_taxa.filter(
site_visit_id__in=sass_ids,
site_visit__sass_biotope_fraction__sass_biotope__biotope_form=1
).annotate(
site_code=Case(
When(site_visit__location_site__site_code__isnull=False,
then='site_visit__location_site__site_code'),
default='site_visit__location_site__name'
),
date=F('site_visit__site_visit_date'),
rate=F('site_visit__sass_biotope_fraction__rate__rate'),
biotope_name=F(
'site_visit__sass_biotope_fraction__sass_biotope__name')
).values(
'date', 'rate', 'biotope_name', 'site_id', 'site_code').order_by(
'-site_visit__site_visit_date',
'site_visit__sass_biotope_fraction__sass_biotope__display_order'
).distinct()
biotope_labels = []
for rating_data in biotope_ratings:
date = rating_data['date'].strftime('%d-%m-%Y')
site_id = rating_data['site_id']
if site_id not in data:
data[site_id] = {}
rate = rating_data['rate']
biotope = rating_data['biotope_name'].encode('utf-8')
if not rate:
rate = 0
data[site_id]['date'] = date
data[site_id]['site_code'] = rating_data['site_code']
data[site_id][biotope] = rate
if biotope not in biotope_labels:
biotope_labels.append(biotope)
return {
'rating_data': data,
'biotope_labels': biotope_labels
}
def get_ecological_chart_data(self):
chart_data = {}
unique_ecoregions = []
all_chart_data = []
eco_geo_data = (self.location_sites.annotate(
geo_class=KeyTextTransform(
'value', KeyTextTransform(
'geo_class',
KeyTextTransform(
'service_registry_values',
KeyTextTransform(
'eco_geo_group',
KeyTextTransform(
'context_group_values',
'location_context'))))),
eco_region=KeyTextTransform(
'value', KeyTextTransform(
'eco_region',
KeyTextTransform(
'service_registry_values',
KeyTextTransform(
'eco_geo_group',
KeyTextTransform(
'context_group_values',
'location_context')))))
).values('geo_class', 'eco_region', 'id')).distinct()
unique_eco_geo = {}
max_charts = 4
for eco_geo in eco_geo_data:
eco_region = eco_geo['eco_region']
geo_class = eco_geo['geo_class']
if not eco_region or not geo_class:
continue
tuple_key = (eco_region, geo_class)
if tuple_key not in unique_eco_geo:
unique_eco_geo[tuple_key] = []
unique_eco_geo[tuple_key].append(eco_geo['id'])
index = 0
for eco_geo, site_ids in unique_eco_geo.iteritems():
if index >= max_charts:
unique_ecoregions.append({
'eco_regions': eco_geo,
'site_ids': site_ids
})
continue
index += 1
eco_region = eco_geo[0]
geo_class = eco_geo[1]
ecological_conditions = SassEcologicalCondition.objects.filter(
ecoregion_level_1__icontains=eco_region,
geomorphological_zone__icontains=geo_class
)
if not ecological_conditions:
# check Combined data
geo_class = 'combined'
ecological_conditions = (
SassEcologicalCondition.objects.filter(
ecoregion_level_1__icontains=eco_region,
geomorphological_zone__icontains=geo_class
))
ecological_conditions = ecological_conditions.annotate(
ec_name=F('ecological_category__name'),
ec_category=F(
'ecological_category__category'),
color=F('ecological_category__colour'),
sass=F('sass_score_precentile'),
aspt=F('aspt_score_precentile'),
).values(
'ec_name',
'ec_category',
'color',
'sass',
'aspt'
).order_by('ecological_category__order')
chart_data = list(ecological_conditions)
if chart_data:
lowest_category = SassEcologicalCategory.objects.filter(
Q(category__icontains='e') |
Q(category__icontains='f')
)
if lowest_category.exists():
lowest_category = lowest_category[0]
chart_data.append({
'ec_name': lowest_category.name,
'ec_category': 'E/F',
'color': lowest_category.colour,
'sass': 0,
'aspt': 0.0
})
all_chart_data.append({
'chart_data': chart_data,
'site_data': {
'site_ids': site_ids,
'eco_region': eco_region,
'geo_class': geo_class
}
})
return all_chart_data, unique_ecoregions
def get(self, request):
filters = request.GET
search = SearchVersion2(filters)
collection_records = search.process_search()
self.site_visit_taxa = SiteVisitTaxon.objects.filter(
id__in=collection_records
)
sass_score_chart_data = self.get_sass_score_chart_data()
taxa_per_biotope_data = self.get_taxa_per_biotope_data()
biotope_ratings_chart_data = self.get_biotope_ratings_chart_data(
sass_ids=sass_score_chart_data['sass_ids']
)
self.location_sites = LocationSite.objects.filter(
id__in=collection_records.values('site').distinct()
)
coordinates = []
ecological_chart_data, unique_ecoregions = (
self.get_ecological_chart_data()
)
for location_site in self.location_sites:
coordinates.append({
'x': location_site.get_centroid().x,
'y': location_site.get_centroid().y
})
return Response({
'sass_score_chart_data': sass_score_chart_data,
'taxa_per_biotope_data': taxa_per_biotope_data,
'biotope_ratings_chart_data': biotope_ratings_chart_data,
'ecological_chart_data': ecological_chart_data,
'unique_ecoregions': unique_ecoregions,
'coordinates': coordinates,
'data_sources': list(
self.site_visit_taxa.exclude(
site_visit__data_source__isnull=True
).values_list(
'site_visit__data_source__name',
flat=True
).distinct())
}) | sass/views/sass_dashboard_multiple.py | from collections import OrderedDict
from django.views.generic import TemplateView
from django.contrib.postgres.fields.jsonb import KeyTextTransform
from django.db.models import (
Case, When, F, Count, Sum, FloatField, Avg, Min, Max, Q
)
from django.db.models.functions import Cast
from rest_framework.views import APIView
from rest_framework.response import Response
from bims.api_views.search_version_2 import SearchVersion2
from bims.models import LocationSite
from sass.models import (
SiteVisitTaxon,
SiteVisitBiotopeTaxon,
SassEcologicalCategory,
SassEcologicalCondition
)
class SassDashboardMultipleSitesView(TemplateView):
template_name = 'sass_dashboard_multiple_sites.html'
class SassDashboardMultipleSitesApiView(APIView):
site_visit_taxa = SiteVisitTaxon.objects.none()
location_sites = LocationSite.objects.none()
def get_sass_score_chart_data(self):
summary = self.site_visit_taxa.annotate(
date=F('site_visit__site_visit_date'),
site_code=Case(
When(site_visit__location_site__site_code__isnull=False,
then='site_visit__location_site__site_code'),
default='site_visit__location_site__name'
),
sass_id=F('site_visit__id'),
site_id=F('site_visit__location_site__id'),
).values('site_code', 'date', 'site_id', 'sass_id').annotate(
count=Count('sass_taxon'),
sass_score=Sum(Case(
When(
condition=Q(site_visit__sass_version=5,
sass_taxon__sass_5_score__isnull=False),
then='sass_taxon__sass_5_score'),
default='sass_taxon__score'
)),
).annotate(
aspt=Cast(F('sass_score'), FloatField()) / Cast(F('count'),
FloatField()),
).order_by('-date')
chart_data = {
'sass_ids': [],
'site_id': [],
'site_code': [],
'sass_score': [],
'aspt_score': [],
'taxa_count': [],
'date': [],
'aspt_average': [],
'taxa_number_average': [],
'sass_score_average': [],
'number_assessments': [],
}
site_codes = []
for data in summary:
# Get the latest data
if data['site_code'] in site_codes:
continue
site_codes.append(data['site_code'])
chart_data['site_code'].append(
data['site_code']
)
chart_data['sass_ids'].append(
data['sass_id']
)
chart_data['site_id'].append(
data['site_id']
)
chart_data['sass_score'].append(
data['sass_score']
)
chart_data['aspt_score'].append(
round(data['aspt'], 2)
)
chart_data['taxa_count'].append(
data['count']
)
chart_data['date'].append(
data['date'].strftime('%d-%m-%Y')
)
chart_data['number_assessments'].append(
len(summary.filter(site=data['site_id']))
)
averages = summary.filter(site=data['site_id']).aggregate(
taxa_number_average=Avg('count'),
sass_score_average=Avg('sass_score'),
aspt_average=Avg('aspt'),
taxa_number_min=Min('count'),
sass_score_min=Min('sass_score'),
aspt_min=Min('aspt'),
taxa_number_max=Max('count'),
sass_score_max=Max('sass_score'),
aspt_max=Max('aspt')
)
chart_data['taxa_number_average'].append({
'avg': averages['taxa_number_average'],
'min': averages['taxa_number_min'],
'max': averages['taxa_number_max'],
})
chart_data['sass_score_average'].append({
'avg': averages['sass_score_average'],
'min': averages['sass_score_min'],
'max': averages['sass_score_max'],
})
chart_data['aspt_average'].append({
'avg': averages['aspt_average'],
'min': averages['aspt_min'],
'max': averages['aspt_max'],
})
return chart_data
def get_taxa_per_biotope_data(self):
latest_site_visits = self.site_visit_taxa.order_by(
'site',
'-site_visit__site_visit_date'
).distinct('site').values('site_visit')
sass_taxon_data = (
self.site_visit_taxa.filter(
site_visit__in=latest_site_visits
).annotate(
site_code=Case(
When(site_visit__location_site__site_code__isnull=False,
then='site_visit__location_site__site_code'),
default='site_visit__location_site__name'
),
taxon_name=Case(
When(
condition=Q(site_visit__sass_version=5,
sass_taxon__taxon_sass_5__isnull=False),
then='sass_taxon__taxon_sass_5'),
default='sass_taxon__taxon_sass_4'
),
sass_score=Case(
When(
condition=Q(site_visit__sass_version=5,
sass_taxon__sass_5_score__isnull=False),
then='sass_taxon__sass_5_score'),
default='sass_taxon__score'
),
site_id=F('site_visit__location_site__id'),
canonical_name=F('taxonomy__canonical_name'),
abundance=F('taxon_abundance__abc'),
score=F('sass_score'),
group_name=F('taxonomy__taxongroup__name'),
display_order=Case(
When(
condition=Q(
site_visit__sass_version=5,
sass_taxon__display_order_sass_5__isnull=False),
then='sass_taxon__display_order_sass_5'),
default='sass_taxon__display_order_sass_4'
),
).values(
'site_id',
'site_code',
'sass_taxon_id',
'canonical_name',
'abundance',
'taxon_name',
'score',
'group_name',
'display_order'
)
.order_by('display_order')
)
biotope_data = (
SiteVisitBiotopeTaxon.objects.filter(
sass_taxon__in=self.site_visit_taxa.values_list('sass_taxon'),
site_visit__in=latest_site_visits
).annotate(
canonical_name=F('taxon__canonical_name'),
abundance=F('taxon_abundance__abc'),
biotope_name=F('biotope__name'),
site_id=F('site_visit__location_site__id'),
).values(
'site_id',
'biotope_name',
'sass_taxon_id',
'canonical_name',
'abundance')
)
sass_taxon_data_dict = OrderedDict()
for taxon_data in list(sass_taxon_data):
name = '{name}-{sass_taxon_id}'.format(
name=taxon_data['canonical_name'],
sass_taxon_id=taxon_data['sass_taxon_id']
)
site_id = taxon_data['site_id']
if name not in sass_taxon_data_dict:
sass_taxon_data_dict[name] = taxon_data
sass_taxon_data_dict[name]['site_abundance'] = {}
sass_taxon_data_dict[name]['site_abundance'][site_id] = (
taxon_data['abundance']
)
try:
sass_taxon_data_dict[name].pop('site_id')
sass_taxon_data_dict[name].pop('abundance')
sass_taxon_data_dict[name].pop('site_code')
except KeyError:
pass
for biotope in biotope_data:
key = '{name}-{sass_taxon_id}'.format(
name=biotope['canonical_name'],
sass_taxon_id=biotope['sass_taxon_id']
)
site_id = str(biotope['site_id'])
if key in sass_taxon_data_dict:
if 'biotope_data' not in sass_taxon_data_dict[key]:
sass_taxon_data_dict[key]['biotope_data'] = {}
if site_id not in sass_taxon_data_dict[key]['biotope_data']:
sass_taxon_data_dict[key]['biotope_data'][site_id] = {}
sass_taxon_data_dict[key][
'biotope_data'][site_id][biotope['biotope_name']] = (
biotope['abundance']
)
return sass_taxon_data_dict
def get_biotope_ratings_chart_data(self, sass_ids=None):
data = {}
biotope_ratings = self.site_visit_taxa.filter(
site_visit_id__in=sass_ids,
site_visit__sass_biotope_fraction__sass_biotope__biotope_form=1
).annotate(
site_code=Case(
When(site_visit__location_site__site_code__isnull=False,
then='site_visit__location_site__site_code'),
default='site_visit__location_site__name'
),
date=F('site_visit__site_visit_date'),
rate=F('site_visit__sass_biotope_fraction__rate__rate'),
biotope_name=F(
'site_visit__sass_biotope_fraction__sass_biotope__name')
).values(
'date', 'rate', 'biotope_name', 'site_id', 'site_code').order_by(
'-site_visit__site_visit_date',
'site_visit__sass_biotope_fraction__sass_biotope__display_order'
).distinct()
biotope_labels = []
for rating_data in biotope_ratings:
date = rating_data['date'].strftime('%d-%m-%Y')
site_id = rating_data['site_id']
if site_id not in data:
data[site_id] = {}
rate = rating_data['rate']
biotope = rating_data['biotope_name'].encode('utf-8')
if not rate:
rate = 0
data[site_id]['date'] = date
data[site_id]['site_code'] = rating_data['site_code']
data[site_id][biotope] = rate
if biotope not in biotope_labels:
biotope_labels.append(biotope)
return {
'rating_data': data,
'biotope_labels': biotope_labels
}
def get_ecological_chart_data(self):
chart_data = {}
unique_ecoregions = []
all_chart_data = []
eco_geo_data = (self.location_sites.annotate(
geo_class=KeyTextTransform(
'value', KeyTextTransform(
'geo_class',
KeyTextTransform(
'service_registry_values',
KeyTextTransform(
'eco_geo_group',
KeyTextTransform(
'context_group_values',
'location_context'))))),
eco_region=KeyTextTransform(
'value', KeyTextTransform(
'eco_region',
KeyTextTransform(
'service_registry_values',
KeyTextTransform(
'eco_geo_group',
KeyTextTransform(
'context_group_values',
'location_context')))))
).values('geo_class', 'eco_region', 'id')).distinct()
unique_eco_geo = {}
max_charts = 4
for eco_geo in eco_geo_data:
eco_region = eco_geo['eco_region']
geo_class = eco_geo['geo_class']
if not eco_region or not geo_class:
continue
tuple_key = (eco_region, geo_class)
if tuple_key not in unique_eco_geo:
unique_eco_geo[tuple_key] = []
unique_eco_geo[tuple_key].append(eco_geo['id'])
index = 0
for eco_geo, site_ids in unique_eco_geo.iteritems():
if index >= max_charts:
unique_ecoregions.append({
'eco_regions': eco_geo,
'site_ids': site_ids
})
continue
index += 1
eco_region = eco_geo[0]
geo_class = eco_geo[1]
ecological_conditions = SassEcologicalCondition.objects.filter(
ecoregion_level_1__icontains=eco_region,
geomorphological_zone__icontains=geo_class
)
if not ecological_conditions:
# check Combined data
geo_class = 'combined'
ecological_conditions = (
SassEcologicalCondition.objects.filter(
ecoregion_level_1__icontains=eco_region,
geomorphological_zone__icontains=geo_class
))
ecological_conditions = ecological_conditions.annotate(
ec_name=F('ecological_category__name'),
ec_category=F(
'ecological_category__category'),
color=F('ecological_category__colour'),
sass=F('sass_score_precentile'),
aspt=F('aspt_score_precentile'),
).values(
'ec_name',
'ec_category',
'color',
'sass',
'aspt'
).order_by('ecological_category__order')
chart_data = list(ecological_conditions)
if chart_data:
lowest_category = SassEcologicalCategory.objects.filter(
Q(category__icontains='e') |
Q(category__icontains='f')
)
if lowest_category.exists():
lowest_category = lowest_category[0]
chart_data.append({
'ec_name': lowest_category.name,
'ec_category': 'E/F',
'color': lowest_category.colour,
'sass': 0,
'aspt': 0.0
})
all_chart_data.append({
'chart_data': chart_data,
'site_data': {
'site_ids': site_ids,
'eco_region': eco_region,
'geo_class': geo_class
}
})
return all_chart_data, unique_ecoregions
def get(self, request):
filters = request.GET
search = SearchVersion2(filters)
collection_records = search.process_search()
self.site_visit_taxa = SiteVisitTaxon.objects.filter(
id__in=collection_records
)
sass_score_chart_data = self.get_sass_score_chart_data()
taxa_per_biotope_data = self.get_taxa_per_biotope_data()
biotope_ratings_chart_data = self.get_biotope_ratings_chart_data(
sass_ids=sass_score_chart_data['sass_ids']
)
self.location_sites = LocationSite.objects.filter(
id__in=collection_records.values('site').distinct()
)
coordinates = []
ecological_chart_data, unique_ecoregions = (
self.get_ecological_chart_data()
)
for location_site in self.location_sites:
coordinates.append({
'x': location_site.get_centroid().x,
'y': location_site.get_centroid().y
})
return Response({
'sass_score_chart_data': sass_score_chart_data,
'taxa_per_biotope_data': taxa_per_biotope_data,
'biotope_ratings_chart_data': biotope_ratings_chart_data,
'ecological_chart_data': ecological_chart_data,
'unique_ecoregions': unique_ecoregions,
'coordinates': coordinates,
'data_sources': list(
self.site_visit_taxa.exclude(
site_visit__data_source__isnull=True
).values_list(
'site_visit__data_source__name',
flat=True
).distinct())
}) | 0.384565 | 0.173726 |
import django_tables2
from django.template.loader import get_template
from django.utils.html import format_html, mark_safe
from django_tables2.utils import Accessor
import help_text
from core.tables import CobwebBaseTable
from projects.models import Claim, Nomination, Project
class ProjectTable(CobwebBaseTable):
"""django_tables2.Table object for lists of projects."""
class Meta(CobwebBaseTable.Meta):
model = Project
fields = ('title', 'unclaimed_nominations',
'claimed_nominations', 'held_nominations')
empty_text = "No projects."
title = django_tables2.LinkColumn(
viewname='project',
kwargs={'slug': Accessor('slug')},
)
unclaimed_nominations = django_tables2.Column(
verbose_name=mark_safe('Unclaimed ')
+ get_template('help_text/more_info.html')
.render(context={'help_text': help_text.N_UNCLAIMED}),
attrs={'cell': {'class': 'text-center'}},
)
claimed_nominations = django_tables2.Column(
verbose_name=mark_safe('Claimed ')
+ get_template('help_text/more_info.html')
.render(context={'help_text': help_text.N_CLAIMED}),
attrs={'cell': {'class': 'text-center'}},
)
held_nominations = django_tables2.Column(
verbose_name=mark_safe('Held ')
+ get_template('help_text/more_info.html')
.render(context={'help_text': help_text.N_HELD}),
attrs={'cell': {'class': 'text-center'}},
)
def render_unclaimed_nominations(self, value):
if value == 0:
return ''
else:
return format_html('<span class="badge-unclaimed">{}</span>',
value)
def render_claimed_nominations(self, value):
if value == 0:
return ''
else:
return format_html('<span class="badge-claimed">{}</span>',
value)
def render_held_nominations(self, value):
if value == 0:
return ''
else:
return format_html('<span class="badge-held">{}</span>',
value)
class UserProjectsTable(ProjectTable):
"""django_tables2.Table object for lists of projects."""
class Meta(ProjectTable.Meta):
fields = ('title', 'n_unclaimed',
'n_claimed', 'n_held')
exclude = ['unclaimed_nominations', 'claimed_nominations',
'held_nominations']
title = django_tables2.LinkColumn(
viewname='project',
kwargs={'slug': Accessor('slug')},
)
n_unclaimed = django_tables2.Column(
verbose_name=mark_safe('Unclaimed ')
+ get_template('help_text/more_info.html')
.render(context={'help_text': help_text.N_UNCLAIMED}),
attrs={'cell': {'class': 'text-center'}},
)
n_claimed = django_tables2.Column(
verbose_name=mark_safe('Claimed ')
+ get_template('help_text/more_info.html')
.render(context={'help_text': help_text.N_CLAIMED}),
attrs={'cell': {'class': 'text-center'}},
)
n_held = django_tables2.Column(
verbose_name=mark_safe('Held ')
+ get_template('help_text/more_info.html')
.render(context={'help_text': help_text.N_HELD}),
attrs={'cell': {'class': 'text-center'}},
)
def render_n_unclaimed(self, value):
if value == 0:
return ''
else:
return format_html('<span class="badge-unclaimed">{}</span>',
value)
def render_n_claimed(self, value):
if value == 0:
return ''
else:
return format_html('<span class="badge-claimed">{}</span>',
value)
def render_n_held(self, value):
if value == 0:
return ''
else:
return format_html('<span class="badge-held">{}</span>',
value)
class NominationColumn(django_tables2.LinkColumn):
def text(self, record):
return record.name + "\nHi!"
def render_link(self, uri, record, value, attrs=None):
return super().render_link(uri, record, value, attrs=None)
class NominationTable(CobwebBaseTable):
"""django_tables2.Table object for lists of nominations."""
class Meta(CobwebBaseTable.Meta):
model = Nomination
fields = ('url', 'project', 'status') # , 'claim_link')
# exclude = ('project',)
empty_text = "No nominations."
url = django_tables2.LinkColumn(
viewname='nomination_update',
kwargs={'project_slug': Accessor('project_slug'),
'url': Accessor('url')},
verbose_name='Nomination',
)
project = django_tables2.LinkColumn(
viewname='nomination_update',
kwargs={'project_slug': Accessor('project_slug'),
'url': Accessor('resource.url')},
verbose_name='In project',
)
status = django_tables2.TemplateColumn(
'<span class="badge-{{record.status}}">{{record.status|capfirst}}</span>',
attrs={'cell': {'class': 'text-center'}},
)
# claim_link = django_tables2.LinkColumn(
# viewname='nomination_update',
# kwargs={'project_slug': Accessor('project_slug'),
# 'url': Accessor('url')},
# text='[claim]', verbose_name='', orderable=False,
# )
class NominationIndexTable(django_tables2.Table):
"""django_tables2.Table object for lists of nominations."""
class Meta(CobwebBaseTable.Meta):
model = Nomination
fields = ('project', 'resource.url', 'title', 'creator', 'language',
'description', 'status', 'tags', 'claims')
claims = django_tables2.Column(verbose_name="Claiming organizations")
def value_claims(self, record):
return ', '.join([c.organization.slug for c in record.claims.all()])
def render_claims(self, record):
return self.value_claims(record)
class ClaimTable(CobwebBaseTable):
"""django_tables2.Table object for lists of claims."""
class Meta(CobwebBaseTable.Meta):
model = Claim
fields = ('has_holding', 'nomination', 'organization', 'link')
empty_text = "No Claims."
nomination = django_tables2.LinkColumn(viewname='nomination',
kwargs={'pk': Accessor('pk')})
organization = django_tables2.LinkColumn(viewname='organization',
kwargs={'slug': Accessor('organization.slug')})
link = django_tables2.TemplateColumn(
'<a href={{record.get_absolute_url}} class="linklet">[details]</a>',
verbose_name='',
orderable=False,
)
has_holding = django_tables2.TemplateColumn("""
{% if record.has_holding %}
<span class="badge-held">Held</span>
{% else %}
<span class="badge-claimed">Claimed</span>
{% endif %}
""", verbose_name="Claim type", orderable=True) | projects/tables.py | import django_tables2
from django.template.loader import get_template
from django.utils.html import format_html, mark_safe
from django_tables2.utils import Accessor
import help_text
from core.tables import CobwebBaseTable
from projects.models import Claim, Nomination, Project
class ProjectTable(CobwebBaseTable):
"""django_tables2.Table object for lists of projects."""
class Meta(CobwebBaseTable.Meta):
model = Project
fields = ('title', 'unclaimed_nominations',
'claimed_nominations', 'held_nominations')
empty_text = "No projects."
title = django_tables2.LinkColumn(
viewname='project',
kwargs={'slug': Accessor('slug')},
)
unclaimed_nominations = django_tables2.Column(
verbose_name=mark_safe('Unclaimed ')
+ get_template('help_text/more_info.html')
.render(context={'help_text': help_text.N_UNCLAIMED}),
attrs={'cell': {'class': 'text-center'}},
)
claimed_nominations = django_tables2.Column(
verbose_name=mark_safe('Claimed ')
+ get_template('help_text/more_info.html')
.render(context={'help_text': help_text.N_CLAIMED}),
attrs={'cell': {'class': 'text-center'}},
)
held_nominations = django_tables2.Column(
verbose_name=mark_safe('Held ')
+ get_template('help_text/more_info.html')
.render(context={'help_text': help_text.N_HELD}),
attrs={'cell': {'class': 'text-center'}},
)
def render_unclaimed_nominations(self, value):
if value == 0:
return ''
else:
return format_html('<span class="badge-unclaimed">{}</span>',
value)
def render_claimed_nominations(self, value):
if value == 0:
return ''
else:
return format_html('<span class="badge-claimed">{}</span>',
value)
def render_held_nominations(self, value):
if value == 0:
return ''
else:
return format_html('<span class="badge-held">{}</span>',
value)
class UserProjectsTable(ProjectTable):
"""django_tables2.Table object for lists of projects."""
class Meta(ProjectTable.Meta):
fields = ('title', 'n_unclaimed',
'n_claimed', 'n_held')
exclude = ['unclaimed_nominations', 'claimed_nominations',
'held_nominations']
title = django_tables2.LinkColumn(
viewname='project',
kwargs={'slug': Accessor('slug')},
)
n_unclaimed = django_tables2.Column(
verbose_name=mark_safe('Unclaimed ')
+ get_template('help_text/more_info.html')
.render(context={'help_text': help_text.N_UNCLAIMED}),
attrs={'cell': {'class': 'text-center'}},
)
n_claimed = django_tables2.Column(
verbose_name=mark_safe('Claimed ')
+ get_template('help_text/more_info.html')
.render(context={'help_text': help_text.N_CLAIMED}),
attrs={'cell': {'class': 'text-center'}},
)
n_held = django_tables2.Column(
verbose_name=mark_safe('Held ')
+ get_template('help_text/more_info.html')
.render(context={'help_text': help_text.N_HELD}),
attrs={'cell': {'class': 'text-center'}},
)
def render_n_unclaimed(self, value):
if value == 0:
return ''
else:
return format_html('<span class="badge-unclaimed">{}</span>',
value)
def render_n_claimed(self, value):
if value == 0:
return ''
else:
return format_html('<span class="badge-claimed">{}</span>',
value)
def render_n_held(self, value):
if value == 0:
return ''
else:
return format_html('<span class="badge-held">{}</span>',
value)
class NominationColumn(django_tables2.LinkColumn):
def text(self, record):
return record.name + "\nHi!"
def render_link(self, uri, record, value, attrs=None):
return super().render_link(uri, record, value, attrs=None)
class NominationTable(CobwebBaseTable):
"""django_tables2.Table object for lists of nominations."""
class Meta(CobwebBaseTable.Meta):
model = Nomination
fields = ('url', 'project', 'status') # , 'claim_link')
# exclude = ('project',)
empty_text = "No nominations."
url = django_tables2.LinkColumn(
viewname='nomination_update',
kwargs={'project_slug': Accessor('project_slug'),
'url': Accessor('url')},
verbose_name='Nomination',
)
project = django_tables2.LinkColumn(
viewname='nomination_update',
kwargs={'project_slug': Accessor('project_slug'),
'url': Accessor('resource.url')},
verbose_name='In project',
)
status = django_tables2.TemplateColumn(
'<span class="badge-{{record.status}}">{{record.status|capfirst}}</span>',
attrs={'cell': {'class': 'text-center'}},
)
# claim_link = django_tables2.LinkColumn(
# viewname='nomination_update',
# kwargs={'project_slug': Accessor('project_slug'),
# 'url': Accessor('url')},
# text='[claim]', verbose_name='', orderable=False,
# )
class NominationIndexTable(django_tables2.Table):
"""django_tables2.Table object for lists of nominations."""
class Meta(CobwebBaseTable.Meta):
model = Nomination
fields = ('project', 'resource.url', 'title', 'creator', 'language',
'description', 'status', 'tags', 'claims')
claims = django_tables2.Column(verbose_name="Claiming organizations")
def value_claims(self, record):
return ', '.join([c.organization.slug for c in record.claims.all()])
def render_claims(self, record):
return self.value_claims(record)
class ClaimTable(CobwebBaseTable):
"""django_tables2.Table object for lists of claims."""
class Meta(CobwebBaseTable.Meta):
model = Claim
fields = ('has_holding', 'nomination', 'organization', 'link')
empty_text = "No Claims."
nomination = django_tables2.LinkColumn(viewname='nomination',
kwargs={'pk': Accessor('pk')})
organization = django_tables2.LinkColumn(viewname='organization',
kwargs={'slug': Accessor('organization.slug')})
link = django_tables2.TemplateColumn(
'<a href={{record.get_absolute_url}} class="linklet">[details]</a>',
verbose_name='',
orderable=False,
)
has_holding = django_tables2.TemplateColumn("""
{% if record.has_holding %}
<span class="badge-held">Held</span>
{% else %}
<span class="badge-claimed">Claimed</span>
{% endif %}
""", verbose_name="Claim type", orderable=True) | 0.494141 | 0.089216 |
import pprint
import carla
import time
import numpy as np
import sys
try:
import pygame
from pygame.locals import KMOD_CTRL
from pygame.locals import KMOD_SHIFT
from pygame.locals import K_0
from pygame.locals import K_9
from pygame.locals import K_BACKQUOTE
from pygame.locals import K_BACKSPACE
from pygame.locals import K_COMMA
from pygame.locals import K_DOWN
from pygame.locals import K_ESCAPE
from pygame.locals import K_F1
from pygame.locals import K_LEFT
from pygame.locals import K_PERIOD
from pygame.locals import K_RIGHT
from pygame.locals import K_SLASH
from pygame.locals import K_SPACE
from pygame.locals import K_TAB
from pygame.locals import K_UP
from pygame.locals import K_a
from pygame.locals import K_b
from pygame.locals import K_c
from pygame.locals import K_d
from pygame.locals import K_g
from pygame.locals import K_h
from pygame.locals import K_i
from pygame.locals import K_l
from pygame.locals import K_m
from pygame.locals import K_n
from pygame.locals import K_p
from pygame.locals import K_q
from pygame.locals import K_r
from pygame.locals import K_s
from pygame.locals import K_v
from pygame.locals import K_w
from pygame.locals import K_x
from pygame.locals import K_z
from pygame.locals import K_MINUS
from pygame.locals import K_EQUALS
except ImportError:
raise RuntimeError('cannot import pygame, make sure pygame package is installed')
class KeyboardControl(object):
"""Class that handles keyboard input."""
def __init__(self):
self._control = carla.VehicleControl()
self._lights = carla.VehicleLightState.NONE
self._steer_cache = 0.0
def parse_events(self, clock) -> bool:
for event in pygame.event.get():
self._parse_vehicle_keys(pygame.key.get_pressed(), clock.get_time())
if event.type == pygame.QUIT:
return True
return False
def get_control(self):
return self._control
def _parse_vehicle_keys(self, keys, milliseconds):
if keys[K_UP] or keys[K_w]:
self._control.throttle = min(self._control.throttle + 0.01, 1)
else:
self._control.throttle = 0.0
if keys[K_DOWN] or keys[K_s]:
self._control.brake = min(self._control.brake + 0.2, 1)
else:
self._control.brake = 0
steer_increment = 5e-4 * milliseconds
if keys[K_LEFT] or keys[K_a]:
if self._steer_cache > 0:
self._steer_cache = 0
else:
self._steer_cache -= steer_increment
elif keys[K_RIGHT] or keys[K_d]:
if self._steer_cache < 0:
self._steer_cache = 0
else:
self._steer_cache += steer_increment
else:
self._steer_cache = 0.0
self._steer_cache = min(0.7, max(-0.7, self._steer_cache))
self._control.steer = round(self._steer_cache, 1)
self._control.hand_brake = keys[K_SPACE]
@staticmethod
def _is_quit_shortcut(key):
return (key == K_ESCAPE) or (key == K_q and pygame.key.get_mods() & KMOD_CTRL)
def main():
from gym_carla.envs.carla_pid_env import CarlaPidEnv
# parameters for the gym_carla environment
params = {
# carla connection parameters+
'host': 'localhost',
'port': 2000, # connection port
'town': 'Town01', # which town to simulate
'traffic_manager_port': 8000,
# simulation parameters
'verbose': False,
'vehicles': 25, # number of vehicles in the simulation
'walkers': 0, # number of walkers in the simulation
'obs_size': 288, # sensor width and height
'max_past_step': 1, # the number of past steps to draw
'dt': 0.025, # time interval between two frames
'reward_weights': [0.3, 0.3, 0.3],
'continuous_speed_range': [0.0, 6.0], # continuous acceleration range
'continuous_steer_range': [-1.0, 1.0], # continuous steering angle range
'ego_vehicle_filter': 'vehicle.lincoln*', # filter for defining ego vehicle
'max_time_episode': 1000, # maximum timesteps per episode
"normalized_input": True,
'max_waypt': 12, # maximum number of waypoints
'd_behind': 12, # distance behind the ego vehicle (meter)
'out_lane_thres': 4.0, # threshold for out of lane
'desired_speed': 6, # desired speed (m/s)
'speed_reduction_at_intersection': 0.75,
'max_ego_spawn_times': 200, # maximum times to spawn ego vehicle
}
env = CarlaPidEnv(params)
env.reset()
pygame.init()
pygame.font.init()
try:
display = pygame.display.set_mode(
(288, 288),
pygame.HWSURFACE | pygame.DOUBLEBUF)
display.fill((0, 0, 0))
pygame.display.flip()
controller = KeyboardControl()
clock = pygame.time.Clock()
steps = 0
total_return = 0
while True:
clock.tick_busy_loop(60)
stop = controller.parse_events(clock)
if stop:
break
# target speed, steer
control = controller.get_control()
action = [control.throttle - control.brake - 0.5, control.steer]
start = time.time()
obs, r, done, info = env.step(action)
speed_mag = np.linalg.norm(obs["speed"])
fps = 1 / (time.time() - start)
sys.stdout.write("\r")
sys.stdout.write(f"[{fps:.1f} fps] HLC={obs['hlc']} throttle={action[0]:.3f}, steer={action[1]:.3f}, "
f"speed={speed_mag:.2f} rew={r:.2f}, "
f"lateral_distance={info['lateral_dis']:.4f},"
f"delta_yaw={info['delta_yaw']:.4f}, average_delta_yaw={info['average_delta_yaw']:.4f}, "
f"r_yaw={info['rewards']['r_yaw']:.3f}, r_steer={info['rewards']['r_steer']:.3f}")
sys.stdout.flush()
steps += 1
total_return += r
if done:
print(f"\nTotal steps={steps}, return={total_return:.3f}, collision={info['colision']}, "
f"collision_actor={info['colision_actor']}, out_of_lane={info['out_of_lane']}")
obs = env.reset()
steps = 0
finally:
pygame.quit()
env.reset()
if __name__ == "__main__":
main() | test_carla_manual.py | import pprint
import carla
import time
import numpy as np
import sys
try:
import pygame
from pygame.locals import KMOD_CTRL
from pygame.locals import KMOD_SHIFT
from pygame.locals import K_0
from pygame.locals import K_9
from pygame.locals import K_BACKQUOTE
from pygame.locals import K_BACKSPACE
from pygame.locals import K_COMMA
from pygame.locals import K_DOWN
from pygame.locals import K_ESCAPE
from pygame.locals import K_F1
from pygame.locals import K_LEFT
from pygame.locals import K_PERIOD
from pygame.locals import K_RIGHT
from pygame.locals import K_SLASH
from pygame.locals import K_SPACE
from pygame.locals import K_TAB
from pygame.locals import K_UP
from pygame.locals import K_a
from pygame.locals import K_b
from pygame.locals import K_c
from pygame.locals import K_d
from pygame.locals import K_g
from pygame.locals import K_h
from pygame.locals import K_i
from pygame.locals import K_l
from pygame.locals import K_m
from pygame.locals import K_n
from pygame.locals import K_p
from pygame.locals import K_q
from pygame.locals import K_r
from pygame.locals import K_s
from pygame.locals import K_v
from pygame.locals import K_w
from pygame.locals import K_x
from pygame.locals import K_z
from pygame.locals import K_MINUS
from pygame.locals import K_EQUALS
except ImportError:
raise RuntimeError('cannot import pygame, make sure pygame package is installed')
class KeyboardControl(object):
"""Class that handles keyboard input."""
def __init__(self):
self._control = carla.VehicleControl()
self._lights = carla.VehicleLightState.NONE
self._steer_cache = 0.0
def parse_events(self, clock) -> bool:
for event in pygame.event.get():
self._parse_vehicle_keys(pygame.key.get_pressed(), clock.get_time())
if event.type == pygame.QUIT:
return True
return False
def get_control(self):
return self._control
def _parse_vehicle_keys(self, keys, milliseconds):
if keys[K_UP] or keys[K_w]:
self._control.throttle = min(self._control.throttle + 0.01, 1)
else:
self._control.throttle = 0.0
if keys[K_DOWN] or keys[K_s]:
self._control.brake = min(self._control.brake + 0.2, 1)
else:
self._control.brake = 0
steer_increment = 5e-4 * milliseconds
if keys[K_LEFT] or keys[K_a]:
if self._steer_cache > 0:
self._steer_cache = 0
else:
self._steer_cache -= steer_increment
elif keys[K_RIGHT] or keys[K_d]:
if self._steer_cache < 0:
self._steer_cache = 0
else:
self._steer_cache += steer_increment
else:
self._steer_cache = 0.0
self._steer_cache = min(0.7, max(-0.7, self._steer_cache))
self._control.steer = round(self._steer_cache, 1)
self._control.hand_brake = keys[K_SPACE]
@staticmethod
def _is_quit_shortcut(key):
return (key == K_ESCAPE) or (key == K_q and pygame.key.get_mods() & KMOD_CTRL)
def main():
from gym_carla.envs.carla_pid_env import CarlaPidEnv
# parameters for the gym_carla environment
params = {
# carla connection parameters+
'host': 'localhost',
'port': 2000, # connection port
'town': 'Town01', # which town to simulate
'traffic_manager_port': 8000,
# simulation parameters
'verbose': False,
'vehicles': 25, # number of vehicles in the simulation
'walkers': 0, # number of walkers in the simulation
'obs_size': 288, # sensor width and height
'max_past_step': 1, # the number of past steps to draw
'dt': 0.025, # time interval between two frames
'reward_weights': [0.3, 0.3, 0.3],
'continuous_speed_range': [0.0, 6.0], # continuous acceleration range
'continuous_steer_range': [-1.0, 1.0], # continuous steering angle range
'ego_vehicle_filter': 'vehicle.lincoln*', # filter for defining ego vehicle
'max_time_episode': 1000, # maximum timesteps per episode
"normalized_input": True,
'max_waypt': 12, # maximum number of waypoints
'd_behind': 12, # distance behind the ego vehicle (meter)
'out_lane_thres': 4.0, # threshold for out of lane
'desired_speed': 6, # desired speed (m/s)
'speed_reduction_at_intersection': 0.75,
'max_ego_spawn_times': 200, # maximum times to spawn ego vehicle
}
env = CarlaPidEnv(params)
env.reset()
pygame.init()
pygame.font.init()
try:
display = pygame.display.set_mode(
(288, 288),
pygame.HWSURFACE | pygame.DOUBLEBUF)
display.fill((0, 0, 0))
pygame.display.flip()
controller = KeyboardControl()
clock = pygame.time.Clock()
steps = 0
total_return = 0
while True:
clock.tick_busy_loop(60)
stop = controller.parse_events(clock)
if stop:
break
# target speed, steer
control = controller.get_control()
action = [control.throttle - control.brake - 0.5, control.steer]
start = time.time()
obs, r, done, info = env.step(action)
speed_mag = np.linalg.norm(obs["speed"])
fps = 1 / (time.time() - start)
sys.stdout.write("\r")
sys.stdout.write(f"[{fps:.1f} fps] HLC={obs['hlc']} throttle={action[0]:.3f}, steer={action[1]:.3f}, "
f"speed={speed_mag:.2f} rew={r:.2f}, "
f"lateral_distance={info['lateral_dis']:.4f},"
f"delta_yaw={info['delta_yaw']:.4f}, average_delta_yaw={info['average_delta_yaw']:.4f}, "
f"r_yaw={info['rewards']['r_yaw']:.3f}, r_steer={info['rewards']['r_steer']:.3f}")
sys.stdout.flush()
steps += 1
total_return += r
if done:
print(f"\nTotal steps={steps}, return={total_return:.3f}, collision={info['colision']}, "
f"collision_actor={info['colision_actor']}, out_of_lane={info['out_of_lane']}")
obs = env.reset()
steps = 0
finally:
pygame.quit()
env.reset()
if __name__ == "__main__":
main() | 0.479991 | 0.142739 |
from pathlib import Path
import cv2
import numpy as np
import torch
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms
import augmenter
from perception.utils.helpers import get_segmentation_tensor
from perception.utils.segmentation_labels import DEFAULT_CLASSES
class MultiTaskDataset(Dataset):
"""Dataset of folder with rgb, segmentation and depth subfolders"""
def __init__(self, root_folder: str, transform=None, semantic_classes=DEFAULT_CLASSES, max_n_instances=None,
augment_strategy=None):
self.root_folder = Path(root_folder)
self.transform = transform
self.semantic_classes = semantic_classes
self.rgb_folder = self.root_folder / "rgb"
self.semantic_folder = self.root_folder / "segmentation"
self.depth_folder = self.root_folder / "depth"
self.rgb_imgs = [x for x in self.rgb_folder.iterdir()]
self.semantic_imgs = [x for x in self.semantic_folder.iterdir()]
self.depth_imgs = [x for x in self.depth_folder.iterdir()]
self.rgb_imgs.sort()
self.semantic_imgs.sort()
self.depth_imgs.sort()
self.rgb_imgs = self.rgb_imgs[:max_n_instances]
self.semantic_imgs = self.semantic_imgs[:max_n_instances]
self.depth_imgs = self.depth_imgs[:max_n_instances]
assert len(self.rgb_imgs) == len(self.depth_imgs)
assert len(self.rgb_imgs) == len(self.semantic_imgs)
self.num_imgs = len(self.rgb_imgs)
print("Len of dataset is:", self.num_imgs)
print("augment with", augment_strategy)
if augment_strategy is not None and augment_strategy != "None":
self.augmenter = getattr(augmenter, augment_strategy)
else:
self.augmenter = None
self.batch_read_number = 819200
def __len__(self):
return self.num_imgs
def __getitem__(self, idx):
def transpose(img, normalize: bool):
img = img.transpose(2, 0, 1)
return img / 255 if normalize else img
def read_rgb(img_path):
return cv2.cvtColor(cv2.imread(img_path), cv2.COLOR_BGR2RGB)
rgb_target = read_rgb(str(self.rgb_imgs[idx]))
if self.augmenter:
rgb_input = self.augmenter(self.batch_read_number).augment_image(rgb_target)
else:
rgb_input = rgb_target
rgb_input = transpose(rgb_input, normalize=True)
rgb_target = transpose(rgb_target, normalize=True)
semantic_img = transpose(
get_segmentation_tensor(read_rgb(str(self.semantic_imgs[idx])), classes=self.semantic_classes),
normalize=False)
depth_img = np.array([cv2.imread(str(self.depth_imgs[idx]), cv2.IMREAD_GRAYSCALE)]) / 255
self.batch_read_number += 1
return rgb_input, rgb_target, semantic_img, depth_img
class SegmentationDataset(Dataset):
"""Dataset of folder with rgb, segmentation subfolders"""
def __init__(self, root_folder: str, transform=None, semantic_classes=DEFAULT_CLASSES, max_n_instances=None,
augment_strategy=None):
self.root_folder = Path(root_folder)
self.transform = transform
self.semantic_classes = semantic_classes
self.rgb_folder = self.root_folder / "rgb"
self.semantic_folder = self.root_folder / "segmentation"
self.rgb_imgs = [x for x in self.rgb_folder.iterdir()]
self.semantic_imgs = [x for x in self.semantic_folder.iterdir()]
self.rgb_imgs.sort()
self.semantic_imgs.sort()
self.rgb_imgs = self.rgb_imgs[:max_n_instances]
self.semantic_imgs = self.semantic_imgs[:max_n_instances]
assert len(self.rgb_imgs) == len(self.semantic_imgs)
self.num_imgs = len(self.rgb_imgs)
print("Len of dataset is:", self.num_imgs)
print("augment with", augment_strategy)
if augment_strategy is not None and augment_strategy != "None":
self.augmenter = getattr(augmenter, augment_strategy)
else:
self.augmenter = None
self.batch_read_number = 819200
self.to_tensor = transforms.Compose([
transforms.ToTensor()
])
self.to_tensor_and_normalize = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
])
def __len__(self):
return self.num_imgs
def __getitem__(self, idx):
def read_rgb(img_path):
return cv2.cvtColor(cv2.imread(img_path), cv2.COLOR_BGR2RGB)
rgb_target = read_rgb(str(self.rgb_imgs[idx]))
if self.augmenter:
rgb_input = self.augmenter(self.batch_read_number).augment_image(rgb_target)
else:
rgb_input = rgb_target
rgb_raw = rgb_input.transpose(2, 0, 1)
rgb_input = self.to_tensor_and_normalize(rgb_input)
rgb_target = self.to_tensor_and_normalize(rgb_target)
semantic_img = self.to_tensor(get_segmentation_tensor(read_rgb(str(self.semantic_imgs[idx])),
classes=self.semantic_classes))
self.batch_read_number += 1
return rgb_input, rgb_target, semantic_img, rgb_raw, str(self.semantic_imgs[idx])
class DepthDataset(Dataset):
"""Dataset of folder with rgb and depth subfolders"""
def __init__(self, root_folder: str, transform=None, max_n_instances=None, augment_strategy=None,
use_transform=None):
self.root_folder = Path(root_folder)
self.transform = transform
self.rgb_folder = self.root_folder / "rgb"
self.depth_folder = self.root_folder / "depth"
self.rgb_imgs = [x for x in self.rgb_folder.iterdir()]
self.depth_imgs = [x for x in self.depth_folder.iterdir()]
self.rgb_imgs.sort()
self.depth_imgs.sort()
self.rgb_imgs = self.rgb_imgs[:max_n_instances]
self.depth_imgs = self.depth_imgs[:max_n_instances]
assert len(self.rgb_imgs) == len(self.depth_imgs)
self.num_imgs = len(self.rgb_imgs)
print("Len of dataset is:", self.num_imgs)
print("augment with", augment_strategy)
if augment_strategy is not None and augment_strategy != "None":
self.augmenter = getattr(augmenter, augment_strategy)
else:
self.augmenter = None
self.batch_read_number = 819200
if use_transform is None:
print("DepthDataset: Using normal transform")
self.transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
])
elif use_transform == "midas_small":
print("DepthDataset: Using small midas transform")
midas_transforms = torch.hub.load("intel-isl/MiDaS", "transforms")
self.transform = midas_transforms.small_transform
else:
print("DepthDataset: Using big midas transform")
midas_transforms = torch.hub.load("intel-isl/MiDaS", "transforms")
self.transform = midas_transforms.default_transform
self.to_tensor = transforms.Compose([
transforms.ToTensor()
])
# TODO bruk midas sine egne transforms - de reshaper til 384 x 384
def __len__(self):
return self.num_imgs
def __getitem__(self, idx):
def read_rgb(img_path):
return cv2.cvtColor(cv2.imread(img_path), cv2.COLOR_BGR2RGB)
rgb_target = read_rgb(str(self.rgb_imgs[idx]))
if self.augmenter:
rgb_input = self.augmenter(self.batch_read_number).augment_image(rgb_target)
else:
rgb_input = rgb_target
rgb_raw = rgb_input.transpose(2, 0, 1)
rgb_input = self.transform(rgb_input)
rgb_target = self.transform(rgb_target)
depth_img = (np.array([cv2.imread(str(self.depth_imgs[idx]), cv2.IMREAD_GRAYSCALE)]) / 255)
self.batch_read_number += 1
return rgb_input, rgb_target, depth_img, rgb_raw, str(self.depth_imgs[idx])
class ComparisonDataset(Dataset):
"""Dataset of folder with rgb, segmentation and depth subfolders"""
def __init__(self, root_folder: str, segmentation_models, depth_models,
semantic_classes=DEFAULT_CLASSES, transform=None, max_n_instances=None):
self.root_folder = Path(root_folder)
self.transform = transform
self.semantic_classes = semantic_classes
self.rgb_folder = self.root_folder / "rgb"
self.semantic_folder = self.root_folder / "segmentation"
self.depth_folder = self.root_folder / "depth"
self.rgb_imgs = [x for x in self.rgb_folder.iterdir()]
self.semantic_imgs = [x for x in self.semantic_folder.iterdir()]
self.depth_imgs = [x for x in self.depth_folder.iterdir()]
self.rgb_imgs.sort()
self.semantic_imgs.sort()
self.depth_imgs.sort()
self.rgb_imgs = self.rgb_imgs[:max_n_instances]
self.semantic_imgs = self.semantic_imgs[:max_n_instances]
self.depth_imgs = self.depth_imgs[:max_n_instances]
assert len(self.rgb_imgs) == len(self.depth_imgs)
assert len(self.rgb_imgs) == len(self.semantic_imgs)
self.num_imgs = len(self.rgb_imgs)
print("Len of dataset is:", self.num_imgs)
# same setup but for variable number of prediction models
self.segmentation_model_imgs = {}
for model in segmentation_models:
self.segmentation_model_imgs[model[0]] = [x for x in model[1].iterdir()]
self.segmentation_model_imgs[model[0]].sort()
self.segmentation_model_imgs[model[0]] = self.segmentation_model_imgs[model[0]][:max_n_instances]
assert len(self.segmentation_model_imgs[model[0]]) == self.num_imgs
self.depth_model_imgs = {}
for model in depth_models:
self.depth_model_imgs[model[0]] = [x for x in model[1].iterdir()]
self.depth_model_imgs[model[0]].sort()
self.depth_model_imgs[model[0]] = self.depth_model_imgs[model[0]][:max_n_instances]
assert len(self.depth_model_imgs[model[0]]) == self.num_imgs
self.depth_model_invert = {}
for model in depth_models:
self.depth_model_invert[model[0]] = model[2]
def __len__(self):
return self.num_imgs
def __getitem__(self, idx):
def transpose(img, normalize: bool):
img = img.transpose(2, 0, 1)
return img / 255 if normalize else img
def read_rgb(img_path):
return cv2.cvtColor(cv2.imread(img_path), cv2.COLOR_BGR2RGB)
rgb_img = read_rgb(str(self.rgb_imgs[idx]))
semantic_img = transpose(
get_segmentation_tensor(read_rgb(str(self.semantic_imgs[idx])), classes=self.semantic_classes),
normalize=False)
depth_img = np.array([cv2.imread(str(self.depth_imgs[idx]), cv2.IMREAD_GRAYSCALE)]) / 255
semantic_model_preds = {}
for model_name in self.segmentation_model_imgs:
semantic_model_preds[model_name] = transpose(
get_segmentation_tensor(read_rgb(str(self.segmentation_model_imgs[model_name][idx])),
classes=self.semantic_classes), normalize=False)
depth_model_preds = {}
for model_name in self.depth_model_imgs:
# some models treat white as close and black as far away, invert some models so that they are "aligned"
if self.depth_model_invert[model_name]:
depth_model_preds[model_name] = (255 - np.array([cv2.imread(str(self.depth_model_imgs[model_name][idx])
, cv2.IMREAD_GRAYSCALE)])) / 255
else:
depth_model_preds[model_name] = np.array([cv2.imread(str(self.depth_model_imgs[model_name][idx])
, cv2.IMREAD_GRAYSCALE)]) / 255
return rgb_img, semantic_img, depth_img, semantic_model_preds, depth_model_preds
if __name__ == '__main__':
dataset = MultiTaskDataset("data/perception/prepped_256x288_mtl", semantic_classes=DEFAULT_CLASSES)
dataloader = DataLoader(dataset, batch_size=2, shuffle=True, num_workers=0,
pin_memory=True)
for i, data in enumerate(dataloader):
rgb, semantic, depth = data
print(semantic.shape) | perception/custom_datasets.py | from pathlib import Path
import cv2
import numpy as np
import torch
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms
import augmenter
from perception.utils.helpers import get_segmentation_tensor
from perception.utils.segmentation_labels import DEFAULT_CLASSES
class MultiTaskDataset(Dataset):
"""Dataset of folder with rgb, segmentation and depth subfolders"""
def __init__(self, root_folder: str, transform=None, semantic_classes=DEFAULT_CLASSES, max_n_instances=None,
augment_strategy=None):
self.root_folder = Path(root_folder)
self.transform = transform
self.semantic_classes = semantic_classes
self.rgb_folder = self.root_folder / "rgb"
self.semantic_folder = self.root_folder / "segmentation"
self.depth_folder = self.root_folder / "depth"
self.rgb_imgs = [x for x in self.rgb_folder.iterdir()]
self.semantic_imgs = [x for x in self.semantic_folder.iterdir()]
self.depth_imgs = [x for x in self.depth_folder.iterdir()]
self.rgb_imgs.sort()
self.semantic_imgs.sort()
self.depth_imgs.sort()
self.rgb_imgs = self.rgb_imgs[:max_n_instances]
self.semantic_imgs = self.semantic_imgs[:max_n_instances]
self.depth_imgs = self.depth_imgs[:max_n_instances]
assert len(self.rgb_imgs) == len(self.depth_imgs)
assert len(self.rgb_imgs) == len(self.semantic_imgs)
self.num_imgs = len(self.rgb_imgs)
print("Len of dataset is:", self.num_imgs)
print("augment with", augment_strategy)
if augment_strategy is not None and augment_strategy != "None":
self.augmenter = getattr(augmenter, augment_strategy)
else:
self.augmenter = None
self.batch_read_number = 819200
def __len__(self):
return self.num_imgs
def __getitem__(self, idx):
def transpose(img, normalize: bool):
img = img.transpose(2, 0, 1)
return img / 255 if normalize else img
def read_rgb(img_path):
return cv2.cvtColor(cv2.imread(img_path), cv2.COLOR_BGR2RGB)
rgb_target = read_rgb(str(self.rgb_imgs[idx]))
if self.augmenter:
rgb_input = self.augmenter(self.batch_read_number).augment_image(rgb_target)
else:
rgb_input = rgb_target
rgb_input = transpose(rgb_input, normalize=True)
rgb_target = transpose(rgb_target, normalize=True)
semantic_img = transpose(
get_segmentation_tensor(read_rgb(str(self.semantic_imgs[idx])), classes=self.semantic_classes),
normalize=False)
depth_img = np.array([cv2.imread(str(self.depth_imgs[idx]), cv2.IMREAD_GRAYSCALE)]) / 255
self.batch_read_number += 1
return rgb_input, rgb_target, semantic_img, depth_img
class SegmentationDataset(Dataset):
"""Dataset of folder with rgb, segmentation subfolders"""
def __init__(self, root_folder: str, transform=None, semantic_classes=DEFAULT_CLASSES, max_n_instances=None,
augment_strategy=None):
self.root_folder = Path(root_folder)
self.transform = transform
self.semantic_classes = semantic_classes
self.rgb_folder = self.root_folder / "rgb"
self.semantic_folder = self.root_folder / "segmentation"
self.rgb_imgs = [x for x in self.rgb_folder.iterdir()]
self.semantic_imgs = [x for x in self.semantic_folder.iterdir()]
self.rgb_imgs.sort()
self.semantic_imgs.sort()
self.rgb_imgs = self.rgb_imgs[:max_n_instances]
self.semantic_imgs = self.semantic_imgs[:max_n_instances]
assert len(self.rgb_imgs) == len(self.semantic_imgs)
self.num_imgs = len(self.rgb_imgs)
print("Len of dataset is:", self.num_imgs)
print("augment with", augment_strategy)
if augment_strategy is not None and augment_strategy != "None":
self.augmenter = getattr(augmenter, augment_strategy)
else:
self.augmenter = None
self.batch_read_number = 819200
self.to_tensor = transforms.Compose([
transforms.ToTensor()
])
self.to_tensor_and_normalize = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
])
def __len__(self):
return self.num_imgs
def __getitem__(self, idx):
def read_rgb(img_path):
return cv2.cvtColor(cv2.imread(img_path), cv2.COLOR_BGR2RGB)
rgb_target = read_rgb(str(self.rgb_imgs[idx]))
if self.augmenter:
rgb_input = self.augmenter(self.batch_read_number).augment_image(rgb_target)
else:
rgb_input = rgb_target
rgb_raw = rgb_input.transpose(2, 0, 1)
rgb_input = self.to_tensor_and_normalize(rgb_input)
rgb_target = self.to_tensor_and_normalize(rgb_target)
semantic_img = self.to_tensor(get_segmentation_tensor(read_rgb(str(self.semantic_imgs[idx])),
classes=self.semantic_classes))
self.batch_read_number += 1
return rgb_input, rgb_target, semantic_img, rgb_raw, str(self.semantic_imgs[idx])
class DepthDataset(Dataset):
"""Dataset of folder with rgb and depth subfolders"""
def __init__(self, root_folder: str, transform=None, max_n_instances=None, augment_strategy=None,
use_transform=None):
self.root_folder = Path(root_folder)
self.transform = transform
self.rgb_folder = self.root_folder / "rgb"
self.depth_folder = self.root_folder / "depth"
self.rgb_imgs = [x for x in self.rgb_folder.iterdir()]
self.depth_imgs = [x for x in self.depth_folder.iterdir()]
self.rgb_imgs.sort()
self.depth_imgs.sort()
self.rgb_imgs = self.rgb_imgs[:max_n_instances]
self.depth_imgs = self.depth_imgs[:max_n_instances]
assert len(self.rgb_imgs) == len(self.depth_imgs)
self.num_imgs = len(self.rgb_imgs)
print("Len of dataset is:", self.num_imgs)
print("augment with", augment_strategy)
if augment_strategy is not None and augment_strategy != "None":
self.augmenter = getattr(augmenter, augment_strategy)
else:
self.augmenter = None
self.batch_read_number = 819200
if use_transform is None:
print("DepthDataset: Using normal transform")
self.transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
])
elif use_transform == "midas_small":
print("DepthDataset: Using small midas transform")
midas_transforms = torch.hub.load("intel-isl/MiDaS", "transforms")
self.transform = midas_transforms.small_transform
else:
print("DepthDataset: Using big midas transform")
midas_transforms = torch.hub.load("intel-isl/MiDaS", "transforms")
self.transform = midas_transforms.default_transform
self.to_tensor = transforms.Compose([
transforms.ToTensor()
])
# TODO bruk midas sine egne transforms - de reshaper til 384 x 384
def __len__(self):
return self.num_imgs
def __getitem__(self, idx):
def read_rgb(img_path):
return cv2.cvtColor(cv2.imread(img_path), cv2.COLOR_BGR2RGB)
rgb_target = read_rgb(str(self.rgb_imgs[idx]))
if self.augmenter:
rgb_input = self.augmenter(self.batch_read_number).augment_image(rgb_target)
else:
rgb_input = rgb_target
rgb_raw = rgb_input.transpose(2, 0, 1)
rgb_input = self.transform(rgb_input)
rgb_target = self.transform(rgb_target)
depth_img = (np.array([cv2.imread(str(self.depth_imgs[idx]), cv2.IMREAD_GRAYSCALE)]) / 255)
self.batch_read_number += 1
return rgb_input, rgb_target, depth_img, rgb_raw, str(self.depth_imgs[idx])
class ComparisonDataset(Dataset):
"""Dataset of folder with rgb, segmentation and depth subfolders"""
def __init__(self, root_folder: str, segmentation_models, depth_models,
semantic_classes=DEFAULT_CLASSES, transform=None, max_n_instances=None):
self.root_folder = Path(root_folder)
self.transform = transform
self.semantic_classes = semantic_classes
self.rgb_folder = self.root_folder / "rgb"
self.semantic_folder = self.root_folder / "segmentation"
self.depth_folder = self.root_folder / "depth"
self.rgb_imgs = [x for x in self.rgb_folder.iterdir()]
self.semantic_imgs = [x for x in self.semantic_folder.iterdir()]
self.depth_imgs = [x for x in self.depth_folder.iterdir()]
self.rgb_imgs.sort()
self.semantic_imgs.sort()
self.depth_imgs.sort()
self.rgb_imgs = self.rgb_imgs[:max_n_instances]
self.semantic_imgs = self.semantic_imgs[:max_n_instances]
self.depth_imgs = self.depth_imgs[:max_n_instances]
assert len(self.rgb_imgs) == len(self.depth_imgs)
assert len(self.rgb_imgs) == len(self.semantic_imgs)
self.num_imgs = len(self.rgb_imgs)
print("Len of dataset is:", self.num_imgs)
# same setup but for variable number of prediction models
self.segmentation_model_imgs = {}
for model in segmentation_models:
self.segmentation_model_imgs[model[0]] = [x for x in model[1].iterdir()]
self.segmentation_model_imgs[model[0]].sort()
self.segmentation_model_imgs[model[0]] = self.segmentation_model_imgs[model[0]][:max_n_instances]
assert len(self.segmentation_model_imgs[model[0]]) == self.num_imgs
self.depth_model_imgs = {}
for model in depth_models:
self.depth_model_imgs[model[0]] = [x for x in model[1].iterdir()]
self.depth_model_imgs[model[0]].sort()
self.depth_model_imgs[model[0]] = self.depth_model_imgs[model[0]][:max_n_instances]
assert len(self.depth_model_imgs[model[0]]) == self.num_imgs
self.depth_model_invert = {}
for model in depth_models:
self.depth_model_invert[model[0]] = model[2]
def __len__(self):
return self.num_imgs
def __getitem__(self, idx):
def transpose(img, normalize: bool):
img = img.transpose(2, 0, 1)
return img / 255 if normalize else img
def read_rgb(img_path):
return cv2.cvtColor(cv2.imread(img_path), cv2.COLOR_BGR2RGB)
rgb_img = read_rgb(str(self.rgb_imgs[idx]))
semantic_img = transpose(
get_segmentation_tensor(read_rgb(str(self.semantic_imgs[idx])), classes=self.semantic_classes),
normalize=False)
depth_img = np.array([cv2.imread(str(self.depth_imgs[idx]), cv2.IMREAD_GRAYSCALE)]) / 255
semantic_model_preds = {}
for model_name in self.segmentation_model_imgs:
semantic_model_preds[model_name] = transpose(
get_segmentation_tensor(read_rgb(str(self.segmentation_model_imgs[model_name][idx])),
classes=self.semantic_classes), normalize=False)
depth_model_preds = {}
for model_name in self.depth_model_imgs:
# some models treat white as close and black as far away, invert some models so that they are "aligned"
if self.depth_model_invert[model_name]:
depth_model_preds[model_name] = (255 - np.array([cv2.imread(str(self.depth_model_imgs[model_name][idx])
, cv2.IMREAD_GRAYSCALE)])) / 255
else:
depth_model_preds[model_name] = np.array([cv2.imread(str(self.depth_model_imgs[model_name][idx])
, cv2.IMREAD_GRAYSCALE)]) / 255
return rgb_img, semantic_img, depth_img, semantic_model_preds, depth_model_preds
if __name__ == '__main__':
dataset = MultiTaskDataset("data/perception/prepped_256x288_mtl", semantic_classes=DEFAULT_CLASSES)
dataloader = DataLoader(dataset, batch_size=2, shuffle=True, num_workers=0,
pin_memory=True)
for i, data in enumerate(dataloader):
rgb, semantic, depth = data
print(semantic.shape) | 0.858793 | 0.497925 |
from datetime import datetime, timedelta
from airflow.decorators import dag, task
import os, sys
sys.path.append('/opt/airflow/')
from dags.connectors.sf import sf
from dags.utils.vaults_at_risk.setup import _setup
from dags.utils.vaults_at_risk.urns import _fetch_urns
from dags.utils.vaults_at_risk.rates import _fetch_rates
from dags.utils.vaults_at_risk.mats import _fetch_mats
from dags.utils.vaults_at_risk.pips import _fetch_pips
from dags.utils.vaults_at_risk.prices import _fetch_prices
from dags.utils.vaults_at_risk.proc import _proc
# [START default_args]
# These args will get passed on to each operator
# You can override them on a per-task basis during operator initialization
default_args = {
"owner": "airflow",
"email": ["<EMAIL>", "<EMAIL>"],
"email_on_failure": True,
"retries": 0,
"retry_delay": timedelta(minutes=1),
}
# [END default_args]
# [START instantiate_dag]
@dag(
default_args=default_args,
schedule_interval='*/5 * * * *',
start_date=datetime(2022, 4, 5, 10),
max_active_runs=1,
catchup=False,
)
def prod_vaults_at_risk():
@task(multiple_outputs=True)
def setup():
start_block, last_scanned_block, latest_timestamp = _setup()
return dict(
start_block=start_block,
last_scanned_block=last_scanned_block,
latest_timestamp=latest_timestamp.__str__()[:19]
)
@task()
def urns(task_dependency, setup):
_fetch_urns(sf, setup['start_block'], setup['last_scanned_block'])
return
@task()
def rates(task_dependency, setup):
_fetch_rates(sf, setup['start_block'], setup['last_scanned_block'])
return
@task()
def mats(task_dependency, setup):
_fetch_mats(sf, setup['start_block'], setup['last_scanned_block'])
return
@task()
def pips(task_dependency, setup):
_fetch_pips(sf, setup['start_block'], setup['last_scanned_block'])
return
@task()
def prices(task_dependency, setup):
_fetch_prices(sf, setup['start_block'], setup['last_scanned_block'])
return
@task()
def proc(task_dependency, setup):
_proc(sf, setup['last_scanned_block'], setup['latest_timestamp'])
@task()
def outro(task_dependency, setup):
sf.execute(f"""
UPDATE MAKER.RISK.VAULTS
SET last_scanned_block = {setup['last_scanned_block']}
WHERE ID = 1;
""")
return
setup = setup()
u = urns(setup, setup)
r = rates(setup, setup)
m = mats(setup, setup)
pips = pips(setup, setup)
prices = prices(pips, setup)
proc = proc([setup, u, r, m, pips, prices], setup)
outro(proc, setup)
prod_vaults_at_risk = prod_vaults_at_risk() | dags/prod_vaults_at_risk.py | from datetime import datetime, timedelta
from airflow.decorators import dag, task
import os, sys
sys.path.append('/opt/airflow/')
from dags.connectors.sf import sf
from dags.utils.vaults_at_risk.setup import _setup
from dags.utils.vaults_at_risk.urns import _fetch_urns
from dags.utils.vaults_at_risk.rates import _fetch_rates
from dags.utils.vaults_at_risk.mats import _fetch_mats
from dags.utils.vaults_at_risk.pips import _fetch_pips
from dags.utils.vaults_at_risk.prices import _fetch_prices
from dags.utils.vaults_at_risk.proc import _proc
# [START default_args]
# These args will get passed on to each operator
# You can override them on a per-task basis during operator initialization
default_args = {
"owner": "airflow",
"email": ["<EMAIL>", "<EMAIL>"],
"email_on_failure": True,
"retries": 0,
"retry_delay": timedelta(minutes=1),
}
# [END default_args]
# [START instantiate_dag]
@dag(
default_args=default_args,
schedule_interval='*/5 * * * *',
start_date=datetime(2022, 4, 5, 10),
max_active_runs=1,
catchup=False,
)
def prod_vaults_at_risk():
@task(multiple_outputs=True)
def setup():
start_block, last_scanned_block, latest_timestamp = _setup()
return dict(
start_block=start_block,
last_scanned_block=last_scanned_block,
latest_timestamp=latest_timestamp.__str__()[:19]
)
@task()
def urns(task_dependency, setup):
_fetch_urns(sf, setup['start_block'], setup['last_scanned_block'])
return
@task()
def rates(task_dependency, setup):
_fetch_rates(sf, setup['start_block'], setup['last_scanned_block'])
return
@task()
def mats(task_dependency, setup):
_fetch_mats(sf, setup['start_block'], setup['last_scanned_block'])
return
@task()
def pips(task_dependency, setup):
_fetch_pips(sf, setup['start_block'], setup['last_scanned_block'])
return
@task()
def prices(task_dependency, setup):
_fetch_prices(sf, setup['start_block'], setup['last_scanned_block'])
return
@task()
def proc(task_dependency, setup):
_proc(sf, setup['last_scanned_block'], setup['latest_timestamp'])
@task()
def outro(task_dependency, setup):
sf.execute(f"""
UPDATE MAKER.RISK.VAULTS
SET last_scanned_block = {setup['last_scanned_block']}
WHERE ID = 1;
""")
return
setup = setup()
u = urns(setup, setup)
r = rates(setup, setup)
m = mats(setup, setup)
pips = pips(setup, setup)
prices = prices(pips, setup)
proc = proc([setup, u, r, m, pips, prices], setup)
outro(proc, setup)
prod_vaults_at_risk = prod_vaults_at_risk() | 0.348756 | 0.329607 |
import argparse
import torch
from torch.utils.data.dataloader import DataLoader
from tqdm import tqdm
from data_modules.dataset_factory import DatasetFactory
from data_modules.image_dataset_data_module import ImageDatasetDataModule
from metrics.cw import silverman_rule_of_thumb
def parse_program_args() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser()
parser.add_argument('--dataset', required=True, help='mnist | fmnist | celeba')
parser.add_argument('--batch_size', type=int, required=True, help='count of samples to be compared')
parser.add_argument('--dataroot', default='../data', help='path to dataset')
parser.add_argument('--workers', type=int, default=16, help='number of data loading workers')
return parser
def compute_mean_and_stddev_for_dataset(dataloader: DataLoader) -> tuple[torch.Tensor, torch.Tensor]:
sum_x = torch.FloatTensor([0.0])
sum_x2 = torch.FloatTensor([0.0])
elements_count = 0
for batch in tqdm(dataloader):
flattened_batch = torch.flatten(batch)
sum_x += flattened_batch.sum()
sum_x2 += flattened_batch.square().sum()
elements_count += flattened_batch.size(0)
mean = sum_x / elements_count
stddev = torch.sqrt(sum_x2/elements_count - mean**2)
return mean, stddev
def run():
parser = parse_program_args()
hparams = parser.parse_args()
dataset_factory = DatasetFactory(hparams.dataset, hparams.dataroot)
data_module = ImageDatasetDataModule(dataset_factory, hparams.batch_size, hparams.batch_size, hparams.workers)
data_module.setup()
dataloader = data_module.train_dataloader(shuffle=True, drop_last=True)
mean, stddev = compute_mean_and_stddev_for_dataset(dataloader)
gamma = silverman_rule_of_thumb(stddev, hparams.batch_size)
print('Mean: ', mean.item())
print('StdDev: ', stddev.item())
print('Silverman rule of thumb: ', gamma.item())
if __name__ == '__main__':
run()
# MNIST mean: 0.1307, stddev: 0.3081
# FMNIST mean: 0.2860, stddev: 0.3530
# CELEBA mean: 0.4328, stddev: 0.2774
# (1.06*STDDEV*N^(-1/5))**2 | src/compute_cw_dataset_statistics.py | import argparse
import torch
from torch.utils.data.dataloader import DataLoader
from tqdm import tqdm
from data_modules.dataset_factory import DatasetFactory
from data_modules.image_dataset_data_module import ImageDatasetDataModule
from metrics.cw import silverman_rule_of_thumb
def parse_program_args() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser()
parser.add_argument('--dataset', required=True, help='mnist | fmnist | celeba')
parser.add_argument('--batch_size', type=int, required=True, help='count of samples to be compared')
parser.add_argument('--dataroot', default='../data', help='path to dataset')
parser.add_argument('--workers', type=int, default=16, help='number of data loading workers')
return parser
def compute_mean_and_stddev_for_dataset(dataloader: DataLoader) -> tuple[torch.Tensor, torch.Tensor]:
sum_x = torch.FloatTensor([0.0])
sum_x2 = torch.FloatTensor([0.0])
elements_count = 0
for batch in tqdm(dataloader):
flattened_batch = torch.flatten(batch)
sum_x += flattened_batch.sum()
sum_x2 += flattened_batch.square().sum()
elements_count += flattened_batch.size(0)
mean = sum_x / elements_count
stddev = torch.sqrt(sum_x2/elements_count - mean**2)
return mean, stddev
def run():
parser = parse_program_args()
hparams = parser.parse_args()
dataset_factory = DatasetFactory(hparams.dataset, hparams.dataroot)
data_module = ImageDatasetDataModule(dataset_factory, hparams.batch_size, hparams.batch_size, hparams.workers)
data_module.setup()
dataloader = data_module.train_dataloader(shuffle=True, drop_last=True)
mean, stddev = compute_mean_and_stddev_for_dataset(dataloader)
gamma = silverman_rule_of_thumb(stddev, hparams.batch_size)
print('Mean: ', mean.item())
print('StdDev: ', stddev.item())
print('Silverman rule of thumb: ', gamma.item())
if __name__ == '__main__':
run()
# MNIST mean: 0.1307, stddev: 0.3081
# FMNIST mean: 0.2860, stddev: 0.3530
# CELEBA mean: 0.4328, stddev: 0.2774
# (1.06*STDDEV*N^(-1/5))**2 | 0.678753 | 0.256855 |