repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
zf020114/CHPDet
src/DOTA_devkit/datapipeline_Visualization.py
import mmcv import numpy as np from mmcv import Config import cv2 from mmdet.datasets import build_dataloader, build_dataset import numpy as np import matplotlib.pyplot as plt import os from DOTA import DOTA import dota_utils as util import pylab pylab.rcParams['figure.figsize'] = (10.0, 10.0) import math from matplotlib.collections import PatchCollection from dota_poly2rbox import rbox2poly_single from matplotlib.patches import Polygon, Circle def showAnns( img,rboxes): plt.imshow(img) plt.axis('off') ax = plt.gca() ax.set_autoscale_on(False) polygons = [] color = [] circles = [] r = 5 for rbox in rboxes: c = (np.random.random((1, 3)) * 0.6 + 0.4).tolist()[0] pts = rbox2poly_single(rbox) poly = [(pts[0], pts[1]), (pts[2], pts[3]), (pts[4], pts[5]), (pts[6], pts[7])] polygons.append(Polygon(poly)) color.append(c) point = poly[0] circle = Circle((point[0], point[1]), r) circles.append(circle) p = PatchCollection(polygons, facecolors=color, linewidths=0, alpha=0.4) ax.add_collection(p) p = PatchCollection(polygons, facecolors='none', edgecolors=color, linewidths=2) ax.add_collection(p) p = PatchCollection(circles, facecolors='red') ax.add_collection(p) plt.imshow(img) plt.show() def run_datatloader(cfg): """ 可视化数据增强后的效果,同时也可以确认训练样本是否正确 Args: cfg: 配置 Returns: """ # Build dataset dataset = build_dataset(cfg.data.train) # prepare data loaders data_loader = build_dataloader( dataset, imgs_per_gpu=1, workers_per_gpu=cfg.data.workers_per_gpu, dist= False, shuffle=False) # rootdir=os.path.dirname(os.path.dirname(dataset.img_prefix)) # example = DOTA(rootdir) # imgids = example.getImgIds() # len(imgids) # imgid=imgids[0] for i, data_batch in enumerate(data_loader): img_batch =data_batch['img'].data gt_label = data_batch['gt_labels'].data gt_box = data_batch['gt_bboxes'].data for batch_i in range(len(img_batch)): img = img_batch[batch_i] mean_value = np.array(cfg.img_norm_cfg['mean']) std_value = np.array(cfg.img_norm_cfg['std']) img_hwc = np.transpose(np.squeeze(img.numpy()), [1, 2, 0]) img = (img_hwc * std_value) + mean_value img = np.array(img, np.uint8) img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR) # img_numpy_float = mmcv.imdenormalize(img_hwc, mean_value, std_value) img_numpy_uint8 = np.array(img, np.uint8) label = gt_label[batch_i] boxes = gt_box[batch_i][0].cpu().numpy() showAnns( img,boxes) # mmcv.imshow(img_numpy_uint8, 'img', 0) if __name__ == '__main__': cfg = Config.fromfile('/home/zf/2020HJJ/train_worm/s2anet_r101_fpn_3x_hrsc2016.py') run_datatloader(cfg)
zf020114/CHPDet
src/compute_angle_acc_rate.py
<filename>src/compute_angle_acc_rate.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jun 15 15:39:49 2020 @author: zf """ from __future__ import absolute_import from __future__ import print_function from __future__ import division import os, sys import cv2 import numpy as np import shutil import sys sys.path.append('/home/zf/0tools') from DataFunction import get_file_paths_recursive,read_rotate_xml,rotate_rect2cv,rotate_rect2cv_np # from r_nms_cpu import nms_rotate_cpus from All_Class_NAME_LABEL import NAME_LABEL_MAP_HRSC, NAME_LABEL_MAP_USnavy_20 #sys.path.append('/media/zf/E/Dataset/DOTA_devkit') sys.path.append('/home/zf/s2anet_rep/DOTA_devkit') from dota15 import data_v15_evl_1 def nms_rotate_cpu(boxes, scores, iou_threshold, max_output_size): keep = []#保留框的结果集合 order = scores.argsort()[::-1]#对检测结果得分进行降序排序 num = boxes.shape[0]#获取检测框的个数 suppressed = np.zeros((num), dtype=np.int) angle_det = np.zeros((num)) for _i in range(num): if len(keep) >= max_output_size:#若当前保留框集合中的个数大于max_output_size时,直接返回 break i = order[_i] if suppressed[i] == 1:#对于抑制的检测框直接跳过 continue keep.append(i)#保留当前框的索引 # (midx,midy),(width,height), angle) r1 = ((boxes[i, 0], boxes[i, 1]), (boxes[i, 2], boxes[i, 3]), boxes[i, 4]) # r1 = ((boxes[i, 1], boxes[i, 0]), (boxes[i, 3], boxes[i, 2]), boxes[i, 4]) #根据box信息组合成opencv中的旋转bbox # print("r1:{}".format(r1)) area_r1 = boxes[i, 2] * boxes[i, 3]#计算当前检测框的面积 for _j in range(_i + 1, num):#对剩余的而进行遍历 j = order[_j] if suppressed[i] == 1: continue r2 = ((boxes[j, 0], boxes[j, 1]), (boxes[j, 2], boxes[j, 3]), boxes[j, 4]) area_r2 = boxes[j, 2] * boxes[j, 3] inter = 0.0 int_pts = cv2.rotatedRectangleIntersection(r1, r2)[1]#求两个旋转矩形的交集,并返回相交的点集合 if int_pts is not None: order_pts = cv2.convexHull(int_pts, returnPoints=True)#求点集的凸边形 int_area = cv2.contourArea(order_pts)#计算当前点集合组成的凸边形的面积 inter = int_area * 1.0 / (area_r1 + area_r2 - int_area + 0.0000001) if inter >= iou_threshold:#对大于设定阈值的检测框进行滤除 suppressed[j] = 1 angle_det[j]=np.abs( r1 [2]-r2[2]) return np.array(keep, np.int64),angle_det def get_label_name_map(NAME_LABEL_MAP): reverse_dict = {} for name, label in NAME_LABEL_MAP.items(): reverse_dict[label] = name return reverse_dict def eval_rotatexml(GT_xml_dir, det_xml_dir, NAME_LABEL_MAP, file_ext='.xml', ovthresh=0.5): # GT_xml_path 是需要转换为txt的xml文件 # txt_dir_h是将要写入的xml转换为txt的文件路径 # annopath 是GT的txt文件 # 读取原图路径 LABEl_NAME_MAP = get_label_name_map(NAME_LABEL_MAP) file_paths = get_file_paths_recursive(GT_xml_dir, '.xml') num_det_all=[] num_tp_all=[] num_gt_all=[] for count, xml_path in enumerate(file_paths): img_size,gsd,imagesource,gtbox_label,extra=read_rotate_xml(xml_path,NAME_LABEL_MAP) # num_gt = np.ones((len(gtbox_label))) num_det = np.zeros((len(gtbox_label))) num_tp = np.zeros((len(gtbox_label))) det_xml=xml_path.replace(GT_xml_dir,det_xml_dir) try: img_size,gsd,imagesource,detbox_label,extra=read_rotate_xml(det_xml,NAME_LABEL_MAP) except : continue if len(detbox_label)>0: for i,box in enumerate( gtbox_label): gt_cvrbox=rotate_rect2cv_np(box) gt_center=np.array([box[0],box[1]]) gt_centers=np.repeat(gt_center[None], len(detbox_label), axis=0) det_centers=np.array(detbox_label)[:,0:2] diff=det_centers-gt_centers dist=np.sqrt(np.square(diff[:,0])+np.square(diff[:,1]),) index=np.argmin(dist) det_gt_box=detbox_label[index] det_cvrbox=rotate_rect2cv_np(det_gt_box) r1 = ((gt_cvrbox[0], gt_cvrbox[1]), (gt_cvrbox[2], gt_cvrbox[3]), gt_cvrbox[4]) area_r1 = gt_cvrbox[2] * gt_cvrbox[3]#计算当前检测框的面积 r2 = ((det_cvrbox[0], det_cvrbox[1]), (det_cvrbox[ 2], det_cvrbox[3]), det_cvrbox[4]) area_r2 = det_cvrbox[2] * det_cvrbox[3] inter = 0.0 int_pts = cv2.rotatedRectangleIntersection(r1, r2)[1]#求两个旋转矩形的交集,并返回相交的点集合 if int_pts is not None: order_pts = cv2.convexHull(int_pts, returnPoints=True)#求点集的凸边形 int_area = cv2.contourArea(order_pts)#计算当前点集合组成的凸边形的面积 inter = int_area * 1.0 / (area_r1 + area_r2 - int_area + 0.0000001) if inter >= ovthresh:#对大于设定阈值的检测框进行滤除 num_det[i]=1 # angle_diff=np.min([np.abs(gtbox_label[i][4]-detbox_label[int(index)][4]), # np.abs(gtbox_label[i][4]-detbox_label[int(index)][4]+np.pi*2), # np.abs(gtbox_label[i][4]-detbox_label[int(index)][4]-np.pi*2), # np.abs(gtbox_label[i][4]-detbox_label[int(index)][4]+np.pi), # np.abs(gtbox_label[i][4]-detbox_label[int(index)][4]-np.pi)]) angle_diff=np.min([np.abs(gtbox_label[i][4]-detbox_label[int(index)][4]), np.abs(gtbox_label[i][4]-detbox_label[int(index)][4]+np.pi*2), np.abs(gtbox_label[i][4]-detbox_label[int(index)][4]-np.pi*2)]) if angle_diff<np.pi/18: num_tp[i]=1 else: print('xmlpath {}'.format(xml_path)) print('gt index {}'.format(i)) print('det index {}'.format(index)) num_det=num_det.tolist() num_tp=num_tp.tolist() # num_gt=num_gt.tolist() # assert(len(angle_det)==len(gtbox_label)) print(len(num_det)) num_det_all+=num_det num_tp_all+=num_tp print(len(num_det_all)) num_det_all=np.array(num_det_all) mean_det=np.mean(num_det_all) num_tp_all=np.array(num_tp_all) mean_tp=np.mean(num_tp_all) print('Mean of det is {}'.format(mean_det)) print('Mean of gt is {}'.format(mean_tp)) print('bow acc rate {}'.format(mean_tp/mean_det)) if __name__ == '__main__': #这是手动计算同样一个rotatebox旋转5度iou #和不同的检测算法角度预测精度的程序,实验结果表明没有明显的优势 GT_xml_dir = '/home/zf/Dataset/USnavy_test_gt/train/rotatexml' # det_xml_dir = '/home/zf/Dataset/USnavy_test_gt/CHE_Hourglass512' det_xml_dir = '/home/zf/Dataset/USnavy_test_gt/6center_DLA1024_rotatexml_merge' # det_xml_dir = '/home/zf/Dataset/USnavy_test_gt/5s2a_show_rotatexml_merge' NAME_LABEL_MAP = NAME_LABEL_MAP_USnavy_20 eval_rotatexml(GT_xml_dir, det_xml_dir, NAME_LABEL_MAP, ovthresh=0.5)
zf020114/CHPDet
src/lib/models/networks/orn/demo.py
<filename>src/lib/models/networks/orn/demo.py import torch import math import numbers import random import argparse import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.utils.data import Dataset from PIL import Image, ImageOps from tqdm import tqdm from torchvision import datasets, transforms from functions import rotation_invariant_encoding from modules.ORConv import ORConv2d # Training settings parser = argparse.ArgumentParser(description='ORN.PyTorch MNIST Example') parser.add_argument('--batch-size', type=int, default=128, metavar='N', help='input batch size for training (default: 128)') parser.add_argument('--test-batch-size', type=int, default=1000, metavar='N', help='input batch size for testing (default: 1000)') parser.add_argument('--epochs', type=int, default=200, metavar='N', help='number of epochs to train (default: 200)') parser.add_argument('--no-cuda', action='store_true', default=False, help='disables CUDA training') parser.add_argument('--seed', type=int, default=1234, metavar='S', help='random seed (default: 1234)') parser.add_argument('--log-interval', type=int, default=20, metavar='N', help='how many batches to wait before logging training status') parser.add_argument('--use-arf', action='store_true', default=False, help='upgrading to ORN') parser.add_argument('--orientation', type=int, default=8, metavar='O', help='nOrientation for ARFs (default: 8)') class toyDataset(Dataset): def __init__(self, num_samples = 10000): super(toyDataset, self).__init__() self.num_samples = num_samples def __len__(self): return self.num_samples def __getitem__(self, index): assert index < len(self), 'index range error' image = torch.randn(1, 32, 32) label = torch.randint(0,10,(1,)).item() return image, label args = parser.parse_args() args.cuda = not args.no_cuda and torch.cuda.is_available() torch.manual_seed(args.seed) if args.cuda: torch.cuda.manual_seed(args.seed) train_loader = torch.utils.data.DataLoader(toyDataset(10000), batch_size=args.batch_size, shuffle=True) test_loader = torch.utils.data.DataLoader(toyDataset(100), batch_size=args.batch_size, shuffle=False) class Net(nn.Module): def __init__(self, use_arf=False, nOrientation=8): super(Net, self).__init__() self.use_arf = use_arf self.nOrientation = nOrientation if use_arf: self.conv1 = ORConv2d(1, 10, arf_config=(1,nOrientation), kernel_size=3) self.conv2 = ORConv2d(10, 20, arf_config=nOrientation,kernel_size=3) self.conv3 = ORConv2d(20, 40, arf_config=nOrientation,kernel_size=3, stride=1, padding=1) self.conv4 = ORConv2d(40, 80, arf_config=nOrientation,kernel_size=3) else: self.conv1 = nn.Conv2d(1, 80, kernel_size=3) self.conv2 = nn.Conv2d(80, 160, kernel_size=3) self.conv3 = nn.Conv2d(160, 320, kernel_size=3, stride=1, padding=1) self.conv4 = nn.Conv2d(320, 640, kernel_size=3) self.fc1 = nn.Linear(640, 1024) self.fc2 = nn.Linear(1024, 10) def forward(self, x): x = F.max_pool2d(F.relu(self.conv1(x)), 2) x = F.max_pool2d(F.relu(self.conv2(x)), 2) x = F.max_pool2d(F.relu(self.conv3(x)), 2) x = F.relu(self.conv4(x)) if self.use_arf: x = rotation_invariant_encoding(x, self.nOrientation) x = x.view(-1, 640) x = F.relu(self.fc1(x)) x = F.dropout(x, training=self.training) x = self.fc2(x) return F.log_softmax(x, dim=1) model = Net(args.use_arf, args.orientation) print(model) if args.cuda: model.cuda() optimizer = optim.Adadelta(model.parameters()) best_test_acc = 0. def train(epoch): model.train() for batch_idx, (data, target) in enumerate(tqdm(train_loader)): if args.cuda: data, target = data.cuda(), target.cuda() optimizer.zero_grad() output = model(data) loss = F.nll_loss(output, target) loss.backward() optimizer.step() # if batch_idx % args.log_interval == 0: print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format( epoch, batch_idx * len(data), len(train_loader.dataset), 100. * batch_idx / len(train_loader), loss.item())) def test(epoch): global best_test_acc model.eval() test_loss = 0 correct = 0 for data, target in tqdm(test_loader): with torch.no_grad(): if args.cuda: data, target = data.cuda(), target.cuda() output = model(data) test_loss += F.nll_loss(output, target).item() pred = output.data.max(1)[1] # get the index of the max log-probability correct += pred.eq(target.data).cpu().sum() test_loss = test_loss test_loss /= len(test_loader) # loss function already averages over batch size test_acc = 100. * correct / len(test_loader.dataset) if test_acc > best_test_acc: best_test_acc = test_acc print('best test accuracy: {:.2f}%'.format(best_test_acc)) print('\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.2f}%)\n'.format( test_loss, correct, len(test_loader.dataset), test_acc)) for epoch in range(1, args.epochs + 1): train(epoch) test(epoch) print('best test accuracy: {:.2f}%'.format(best_test_acc))
zf020114/CHPDet
src/DOTA_devkit/HRSC2DOTA.py
<reponame>zf020114/CHPDet<filename>src/DOTA_devkit/HRSC2DOTA.py import json import os import os.path as osp import numpy as np import xmltodict from dota_poly2rbox import rbox2poly_single def parse_ann_info(objects): bboxes, labels, bboxes_ignore, labels_ignore = [], [], [], [] # only one annotation if type(objects) != list: objects = [objects] for obj in objects: if obj['difficult'] == '0': bbox = float(obj['mbox_cx']), float(obj['mbox_cy']), float( obj['mbox_w']), float(obj['mbox_h']), float(obj['mbox_ang']) label = 'ship' bboxes.append(bbox) labels.append(label) elif obj['difficult'] == '1': bbox = float(obj['mbox_cx']), float(obj['mbox_cy']), float( obj['mbox_w']), float(obj['mbox_h']), float(obj['mbox_ang']) label = 'ship' bboxes_ignore.append(bbox) labels_ignore.append(label) return bboxes, labels, bboxes_ignore, labels_ignore def ann_to_txt(ann): out_str = '' for bbox, label in zip(ann['bboxes'], ann['labels']): poly = rbox2poly_single(bbox) str_line = '{} {} {} {} {} {} {} {} {} {}\n'.format( poly[0], poly[1], poly[2], poly[3], poly[4], poly[5], poly[6], poly[7], label, '0') out_str += str_line for bbox, label in zip(ann['bboxes_ignore'], ann['labels_ignore']): poly = rbox2poly_single(bbox) str_line = '{} {} {} {} {} {} {} {} {} {}\n'.format( poly[0], poly[1], poly[2], poly[3], poly[4], poly[5], poly[6], poly[7], label, '1') out_str += str_line return out_str def generate_txt_labels(root_path): img_path = osp.join(root_path, 'AllImages') label_path = osp.join(root_path, 'Annotations') label_txt_path = osp.join(root_path, 'labelTxt') if not osp.exists(label_txt_path): os.mkdir(label_txt_path) img_names = [osp.splitext(img_name.strip())[0] for img_name in os.listdir(img_path)] for img_name in img_names: label = osp.join(label_path, img_name+'.xml') label_txt = osp.join(label_txt_path, img_name+'.txt') f_label = open(label) data_dict = xmltodict.parse(f_label.read()) data_dict = data_dict['HRSC_Image'] f_label.close() label_txt_str = '' # with annotations if data_dict['HRSC_Objects']: objects = data_dict['HRSC_Objects']['HRSC_Object'] bboxes, labels, bboxes_ignore, labels_ignore = parse_ann_info( objects) ann = dict( bboxes=bboxes, labels=labels, bboxes_ignore=bboxes_ignore, labels_ignore=labels_ignore) label_txt_str = ann_to_txt(ann) with open(label_txt,'w') as f_txt: f_txt.write(label_txt_str) if __name__ == '__main__': generate_txt_labels('/project/jmhan/data/HRSC2016/Train') generate_txt_labels('/project/jmhan/data/HRSC2016/Test') print('done!')
zf020114/CHPDet
src/eval_xml.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jun 15 23:00:51 2020 @author: zf """ # import pycocotools.coco as coco # from pycocotools.coco import COCO import os import shutil from tqdm import tqdm import skimage.io as io import matplotlib.pyplot as plt import cv2 from PIL import Image, ImageDraw import numpy as np from scipy import stats as st import sys sys.path.append('/home/zf/0tools') from py_cpu_nms import py_cpu_nms from r_nms_cpu import nms_rotate_cpu from DataFunction import write_rotate_xml, read_rotate_xml, rotate_rect2cv_np from All_Class_NAME_LABEL import NAME_LABEL_MAP_DOTA10 from Rotatexml2DotaTxT import eval_rotatexml def get_label_name_map(NAME_LABEL_MAP): reverse_dict = {} for name, label in NAME_LABEL_MAP.items(): reverse_dict[label] = name return reverse_dict def get_file_paths_recursive(folder=None, file_ext=None): """ Get the absolute path of all files in given folder recursively :param folder: :param file_ext: :return: """ file_list = [] if folder is None: return file_list file_list = [os.path.join(folder, f) for f in sorted(os.listdir(folder)) if f.endswith(file_ext)] return file_list def id2name(coco): classes=dict() for cls in coco.dataset['categories']: classes[cls['id']]=cls['name'] return classes def show_rotate_box(src_img,rotateboxes,name=None): cx, cy, w,h,Angle=rotateboxes[:,0], rotateboxes[:,1], rotateboxes[:,2], rotateboxes[:,3], rotateboxes[:,4] p_rotate=[] for i in range(rotateboxes.shape[0]): RotateMatrix=np.array([ [np.cos(Angle[i]),-np.sin(Angle[i])], [np.sin(Angle[i]),np.cos(Angle[i])]]) rhead,r1,r2,r3,r4=np.transpose([0,-h/2]),np.transpose([-w[i]/2,-h[i]/2]),np.transpose([w[i]/2,-h[i]/2]),np.transpose([w[i]/2,h[i]/2]),np.transpose([-w[i]/2,h[i]/2]) rhead=np.transpose(np.dot(RotateMatrix, rhead))+[cx[i],cy[i]] p1=np.transpose(np.dot(RotateMatrix, r1))+[cx[i],cy[i]] p2=np.transpose(np.dot(RotateMatrix, r2))+[cx[i],cy[i]] p3=np.transpose(np.dot(RotateMatrix, r3))+[cx[i],cy[i]] p4=np.transpose(np.dot(RotateMatrix, r4))+[cx[i],cy[i]] p_rotate_=np.int32(np.vstack((p1,p2,p3,p4))) p_rotate.append(p_rotate_) cv2.polylines(src_img,np.array(p_rotate),True,(0,255,255)) # if name==None: # cv2.imwrite('1.jpg',src_img) # else: # cv2.imwrite('{}.jpg'.format(name),src_img) cv2.imshow('rotate_box',src_img.astype('uint8')) cv2.waitKey(0) cv2.destroyAllWindows() def py_cpu_label_nms(dets, thresh, max_output_size,LABEL_NAME_MAP,NAME_LONG_MAP,std_scale): """Pure Python NMS baseline.""" x1 = dets[:, 0] y1 = dets[:, 1] x2 = dets[:, 2] y2 = dets[:, 3] scores = dets[:, 6] label = dets[:, 5] areas = (x2 - x1 + 1) * (y2 - y1 + 1) order = scores.argsort()[::-1] keep = [] while order.size > 0: if len(keep) >= max_output_size: break i = order[0] keep.append(i) xx1 = np.maximum(x1[i], x1[order[1:]]) yy1 = np.maximum(y1[i], y1[order[1:]]) xx2 = np.minimum(x2[i], x2[order[1:]]) yy2 = np.minimum(y2[i], y2[order[1:]]) w = np.maximum(0.0, xx2 - xx1 + 1) h = np.maximum(0.0, yy2 - yy1 + 1) inter = w * h ovr = inter / (areas[i] + areas[order[1:]] - inter) # find the overlap bbox inds1 = np.where(ovr > thresh)[0]+1 # inds1=np.concatenate(inds1,np.expand_dims(i, 0)) inds1=np.concatenate((order[inds1],np.expand_dims(i, 0)),axis=0) #get label index label_refine = label[inds1] #get accture length h_acc=y2[inds1]-y1[inds1] #initial long_label and p long_label=np.zeros_like(label_refine) p=np.zeros_like(label_refine) for j in range(label_refine.size): long_label[j]=NAME_LONG_MAP[LABEL_NAME_MAP[label_refine[j]]] p[j]=2* st.norm.cdf(-(np.abs(h_acc[j] - long_label[j]*2) / (std_scale*2*long_label[j]))) label_refine = label[inds1] inds_other=np.where(label_refine == 24)[0] if inds_other.size>0 and inds_other.size != long_label.size: p[inds_other]=1-np.max(p) scores[inds1]=scores[inds1]*p inds = np.where(ovr <= thresh)[0] order = order[inds + 1] order = scores.argsort()[::-1] keep = [] while order.size > 0: if len(keep) >= max_output_size: break i = order[0] keep.append(i) xx1 = np.maximum(x1[i], x1[order[1:]]) yy1 = np.maximum(y1[i], y1[order[1:]]) xx2 = np.minimum(x2[i], x2[order[1:]]) yy2 = np.minimum(y2[i], y2[order[1:]]) w = np.maximum(0.0, xx2 - xx1 + 1) h = np.maximum(0.0, yy2 - yy1 + 1) inter = w * h ovr = inter / (areas[i] + areas[order[1:]] - inter) inds = np.where(ovr <= thresh)[0] order = order[inds + 1] return np.array(keep, np.int64),scores def merge_rotatexml(xmldir, merge_xmldir, NAME_LABEL_MAP,NAME_LONG_MAP, std_scale, score_threshold): LABEL_NAME_MAP = get_label_name_map(NAME_LABEL_MAP) if not os.path.exists(merge_xmldir): os.mkdir(merge_xmldir) imgs_path=get_file_paths_recursive(xmldir, '.xml') name_det={} for num,img_path in enumerate(imgs_path,0): str_num=img_path.replace('.xml','').strip().split('__') img_name=str_num[0] scale=np.float(str_num[1]) ww_=np.int(str_num[2]) hh_=np.int(str_num[3]) img_size,gsd,imagesource,gtbox,extra=read_rotate_xml(img_path,NAME_LABEL_MAP) gtbox=np.array(gtbox) if len(gtbox)>0: gtbox[:,6]=extra inx=gtbox[:,6]>score_threshold rotateboxes=gtbox[inx] gtbox[:, 0]=(gtbox[:, 0]+ww_)/scale gtbox[:, 1]=(gtbox[:, 1]+hh_)/scale gtbox[:, 2]/=scale gtbox[:, 3]/=scale if not img_name in name_det : name_det[img_name]= gtbox else: name_det[img_name]= np.vstack((name_det[img_name],gtbox)) # else: # print(' ') # # #将所有检测结果综合起来 #正框mns for img_name, rotateboxes in name_det.items(): if std_scale==0: print('no nms') else: inx, scores = py_cpu_label_nms( dets=np.array(rotateboxes, np.float32), thresh=nms_threshold, max_output_size=500, LABEL_NAME_MAP=LABEL_NAME_MAP_USnavy_20, NAME_LONG_MAP=NAME_LONG_MAP_USnavy, std_scale=std_scale) rotateboxes = rotateboxes[inx] # result[:, 4]=scores[inx] # inx=result[:, 4]>score_threshold_2 # result=result[inx] cvrboxes=[] for box in rotateboxes: cvrboxes.append(rotate_rect2cv_np(box)) cvrboxes = np.array(cvrboxes) if len(cvrboxes)>0:##斜框NMS keep = nms_rotate_cpu(cvrboxes, rotateboxes[:, 6], rnms_threshold, 4000) #这里可以改 rotateboxes=rotateboxes[keep] # keep=[]#去掉过 尺寸异常的目标 # for i in range(rotateboxes.shape[0]): # box=rotateboxes[i,:] # actual_long=box[3]*scale # standad_long = NAME_LONG_MAP[LABEL_NAME_MAP[box[5]]] # STD_long = NAME_LONG_MAP[LABEL_NAME_MAP[box[5]]] # STD_long *= std_scale # if np.abs(actual_long-standad_long)/standad_long < STD_long *1.2 and box[2]>16: # keep.append(i) # else: # print('{} hh:{} ww:{}'.format(img_name,hh_,ww_)) # print('{} th label {} is wrong,long is {} normal long is {} width is {}'.format(i+1,LABEl_NAME_MAP[box[5]],actual_long,standad_long,box[3])) # rotateboxes=rotateboxes[keep] #保存检测结果 为比赛格式 # image_dir,image_name=os.path.split(img_path) # gt_box=rotateboxes[:,0:5] # label=rotateboxes[:,6] write_rotate_xml(merge_xmldir,'{}.jpg'.format(img_name),[1024 ,1024,3],0.5,'USnavy',rotateboxes,LABEL_NAME_MAP,rotateboxes[:,6])#size,gsd,imagesource if __name__ == '__main__': #Store annotations and train2014/val2014/... in this folder xmldir ='/home/zf/Dataset/DOTA_800_aug/val_det_xml1024' #the path you want to save your results for coco to voc merge_xmldir = '/home/zf/Dataset/DOTA_800_aug/val_det_merge_xml1024' nms_threshold=0.9#0.8 rnms_threshold=0.15#0.1 score_threshold=0.02 std_scale=0 IOU_thresh=0.5 NAME_LABEL_MAP = NAME_LABEL_MAP_DOTA10 NAME_LONG_MAP = NAME_LABEL_MAP_DOTA10 merge_rotatexml(xmldir, merge_xmldir, NAME_LABEL_MAP, NAME_LONG_MAP, std_scale, score_threshold) txt_dir_h = '/home/zf/Dataset/DOTA_800_aug/val_det_merge_xmltxt' annopath = '/media/zf/F/Dataset_ori/Dota/val/labelTxt/' file_ext = '.xml' flag = 'test' eval_rotatexml(merge_xmldir, txt_dir_h, annopath, NAME_LABEL_MAP, file_ext, flag, IOU_thresh)
zf020114/CHPDet
src/inference.py
<filename>src/inference.py import sys sys.path.insert(0, '/home/zf/CenterNet') from lib.detectors.detector_factory import detector_factory from opts import opts import glob import numpy as np from utils.post_process import multi_pose_post_process try: from external.nms import soft_nms_39 except: print('NMS not imported! If you need it,' ' do \n cd $CenterNet_ROOT/src/lib/external \n make') MODEL_PATH = '../models/multi_pose_dla__52_1024*1024.pth' TASK = 'multi_pose' # or 'ctdet' for human pose estimation opt = opts().init('{} --load_model {}'.format(TASK, MODEL_PATH).split(' ')) opt.debug = max(opt.debug, 1) opt.vis_thresh=0.2 detector = detector_factory[opt.task](opt) time_stats = ['tot', 'load', 'pre', 'net', 'dec', 'post', 'merge'] img_path='../images' imgs = glob.glob(img_path+"/*.jpg") for i, img in enumerate(imgs): ret = detector.run(img) time_str = '' for stat in time_stats: time_str = time_str + '{} {:.3f}s |'.format(stat, ret[stat]) print(time_str)
zf020114/CHPDet
src/5eval_json.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jun 15 23:00:51 2020 @author: zf """ # import pycocotools.coco as coco from pycocotools.coco import COCO import os import shutil from tqdm import tqdm import skimage.io as io import matplotlib.pyplot as plt import cv2 from PIL import Image, ImageDraw import numpy as np import sys sys.path.append('/home/zf/0tools') from py_cpu_nms import py_cpu_nms, py_cpu_label_nms from r_nms_cpu import nms_rotate_cpu from DataFunction import write_rotate_xml from Rotatexml2DotaTxT import eval_rotatexml def get_label_name_map(NAME_LABEL_MAP): reverse_dict = {} for name, label in NAME_LABEL_MAP.items(): reverse_dict[label] = name return reverse_dict def id2name(coco): classes=dict() for cls in coco.dataset['categories']: classes[cls['id']]=cls['name'] return classes def show_rotate_box(src_img,rotateboxes,name=None): cx, cy, w,h,Angle=rotateboxes[:,0], rotateboxes[:,1], rotateboxes[:,2], rotateboxes[:,3], rotateboxes[:,4] p_rotate=[] for i in range(rotateboxes.shape[0]): RotateMatrix=np.array([ [np.cos(Angle[i]),-np.sin(Angle[i])], [np.sin(Angle[i]),np.cos(Angle[i])]]) rhead,r1,r2,r3,r4=np.transpose([0,-h/2]),np.transpose([-w[i]/2,-h[i]/2]),np.transpose([w[i]/2,-h[i]/2]),np.transpose([w[i]/2,h[i]/2]),np.transpose([-w[i]/2,h[i]/2]) rhead=np.transpose(np.dot(RotateMatrix, rhead))+[cx[i],cy[i]] p1=np.transpose(np.dot(RotateMatrix, r1))+[cx[i],cy[i]] p2=np.transpose(np.dot(RotateMatrix, r2))+[cx[i],cy[i]] p3=np.transpose(np.dot(RotateMatrix, r3))+[cx[i],cy[i]] p4=np.transpose(np.dot(RotateMatrix, r4))+[cx[i],cy[i]] p_rotate_=np.int32(np.vstack((p1,p2,p3,p4))) p_rotate.append(p_rotate_) cv2.polylines(src_img,np.array(p_rotate),True,(0,255,255)) # if name==None: # cv2.imwrite('1.jpg',src_img) # else: # cv2.imwrite('{}.jpg'.format(name),src_img) cv2.imshow('rotate_box',src_img.astype('uint8')) cv2.waitKey(0) cv2.destroyAllWindows() def result2rotatebox_cvbox(src_img,result): cx, cy, w,h=(result[:,0]+result[:,2])/2 ,(result[:,1]+result[:,3])/2 ,(result[:,2]-result[:,0]) ,(result[:,3]-result[:,1]) head=result[:,5:7]#头部坐标 center=np.vstack((cx,cy)).T#中心坐标 det=head-center Angle=np.zeros_like(cx) for i in range(det.shape[0]): if det[i,0]==0: if det[i,1]>0: Angle[i]=np.pi/2 else: Angle[i]=-np.pi/2 elif det[i,0]<0: Angle[i]=np.arctan(det[i,1]/det[i,0])+np.pi*3/2 else: Angle[i]=np.arctan(det[i,1]/det[i,0])+np.pi/2 rotateboxes=np.vstack((cx, cy, w,h,Angle,result[:,7],result[:,4])).T center_head=np.sqrt(det[:,0]*det[:,0]+det[:,1]*det[:,1]) # ratio_h_head=np.array(([2*center_head/h, h/center_head/2])).min(axis=0) # rotateboxes[:,6]*=ratio_h_head*ratio_h_head #这里可以将超过范围的点去掉 # keep=center_head>h/3 # rotateboxes=rotateboxes[keep] # show_rotate_box(src_img,rotateboxes) # 在opencv中,坐标系原点在左上角,相对于x轴,逆时针旋转角度为负,顺时针旋转角度为正。所以,θ∈(-90度,0]。 #rotatexml start normal y shunp_cv p_cv=[] cvboxes=np.zeros_like(rotateboxes) for i in range(rotateboxes.shape[0]): angle_cv=rotateboxes[i,4]/np.pi*180 if angle_cv>0: angle_cv=angle_cv cv_h=rotateboxes[i,3] cv_w=rotateboxes[i,2] else: angle_cv=angle_cv+90 cv_h=rotateboxes[i,2] cv_w=rotateboxes[i,3] cvboxes[i,:]=[rotateboxes[i,0],rotateboxes[i,1],cv_w,cv_h,angle_cv,result[i,7],result[i,4]] return cvboxes,rotateboxes def showimg_kepoint(coco,dataset,img,classes,cls_id,show=True): global dataDir annIds = coco.getAnnIds(imgIds=img['id'], catIds=cls_id, iscrowd=None) anns = coco.loadAnns(annIds) objs = [] result_=np.zeros((0,8)) for ann in anns: class_name=classes[ann['category_id']] bbox=ann['bbox'] xmin = int(bbox[0]) ymin = int(bbox[1]) xmax = int(bbox[2] + bbox[0]) ymax = int(bbox[3] + bbox[1]) obj = [class_name, xmin, ymin, xmax, ymax] objs.append(obj) keypoints=ann['keypoints'] keypoint=keypoints[0:2] score=ann['score'] if score>score_threshold: res_array=np.array([xmin,ymin,xmax,ymax,score,keypoint[0],keypoint[1],NAME_LABEL_MAP[class_name]]).T result_=np.vstack((result_,res_array)) return result_ def merge_json2rotatexml(gtFile, annFile, merge_xmldir, NAME_LABEL_MAP, NAME_LONG_MAP, NAME_STD_MAP, std_scale, score_threshold): classes_names = [] for name, label in NAME_LABEL_MAP.items(): classes_names.append(name) if not os.path.exists(merge_xmldir): os.mkdir(merge_xmldir) LABEl_NAME_MAP = get_label_name_map(NAME_LABEL_MAP) #COCO API for initializing annotated data coco = COCO(gtFile) coco_res=coco.loadRes(annFile) classes = id2name(coco) print(classes) classes_ids = coco.getCatIds(catNms=classes_names) print(classes_ids) #Get ID number of this class img_ids=coco.getImgIds() print('len of dataset:{}'.format(len(img_ids))) img_name_ori='' result=np.zeros((0,8)) name_det={} for imgId in tqdm(img_ids): img = coco_res.loadImgs(imgId)[0] # Img_fullname='%s/%s/%s'%(dataDir,dataset,img['file_name']) filename = img['file_name'] str_num=filename.replace('.jpg','').strip().split('__') img_name=str_num[0] scale=np.float(str_num[1]) ww_=np.int(str_num[2]) hh_=np.int(str_num[3]) result_=showimg_kepoint(coco_res, 'val2017', img, classes,classes_ids,show=True) inx=result_[:, 4]>score_threshold result_=result_[inx] cvboxes,rotateboxes=result2rotatebox_cvbox(img,result_) # img=cv2.imread(Img_fullname) # show_rotate_box(img,rotateboxes) result_[:, 0]=(result_[:, 0]+ww_)/scale result_[:, 2]=(result_[:, 2]+ww_)/scale result_[:, 5]=(result_[:, 5]+ww_)/scale result_[:, 1]=(result_[:, 1]+hh_)/scale result_[:, 3]=(result_[:, 3]+hh_)/scale result_[:, 6]=(result_[:, 6]+hh_)/scale if not img_name in name_det : name_det[img_name]= result_ else: name_det[img_name]= np.vstack((name_det[img_name],result_)) # # #将所有检测结果综合起来 #正框mns for img_name, result in name_det.items(): if std_scale==0: inx = py_cpu_nms(dets=np.array(result, np.float32),thresh=nms_threshold,max_output_size=500) result=result[inx] else: inx ,scores= py_cpu_label_nms(dets=np.array(result, np.float32),thresh=nms_threshold,max_output_size=500, LABEL_NAME_MAP=LABEL_NAME_MAP, NAME_LONG_MAP=NAME_LONG_MAP,std_scale=std_scale) result=result[inx] result[:, 4]=scores[inx] cvrboxes,rotateboxes=result2rotatebox_cvbox(img,result) #斜框NMS if cvrboxes.size>0: keep = nms_rotate_cpu(cvrboxes,cvrboxes[:,6],rnms_threshold, 200) #这里可以改 rotateboxes=rotateboxes[keep] # #去掉过小的目标 # keep=[] # for i in range(rotateboxes.shape[0]): # box=rotateboxes[i,:] # actual_long=box[3]*scale # standad_long=NAME_LONG_MAP[LABEl_NAME_MAP[box[5]]] # STD_long=NAME_STD_MAP[LABEl_NAME_MAP[box[5]]] # if np.abs(actual_long-standad_long)/standad_long < STD_long *1.2 and box[2]>16: # keep.append(i) # else: # print('{} hh:{} ww:{}'.format(img_name,hh_,ww_)) # print('{} th label {} is wrong,long is {} normal long is {} width is {}'.format(i+1,LABEl_NAME_MAP[box[5]],actual_long,standad_long,box[3])) # rotateboxes=rotateboxes[keep] #保存检测结果 为比赛格式 # image_dir,image_name=os.path.split(img_path) # gt_box=rotateboxes[:,0:5] # label=rotateboxes[:,6] write_rotate_xml(merge_xmldir, '{}.jpg'.format(img_name), [1024, 1024, 3], 0.5, 'USnavy', rotateboxes, LABEl_NAME_MAP, rotateboxes[:, 6]) #size,gsd,imagesource if __name__ == '__main__': #Store annotations and train2014/val2014/... in this folder # annFile = '/media/zf/F/Dataset/USnavy_test_gt/json文件/resultsDLA_512_1_10.json' #0.9 0.15 0.05 map82.30 加上去掉过小的目标后是82。55 加上1.3约束82。80 # annFile = '/media/zf/E/CenterNet/exp/multi_pose/dla_USnavy512_RGuass1_12raduis_arf/results.json'#map 81.34 # annFile = '/media/zf/E/CenterNet/exp/multi_pose/dla_USnavy512_RGuass_scale1/results.json' #0.8 0.1 0.1 map 80.88 # annFile = '/media/zf/F/Dataset/USnavy_test_gt/json文件/dla_1x.json'#map80.39 80.52 # annFile = '/media/zf/F/Dataset/USnavy_test_gt/json文件/dla_USnavy512_RGuass1_12raduis.json'#map 80.59 # annFile = '/media/zf/F/Dataset/USnavy_test_gt/json文件/dla_USnavy512_RGuass1_12raduis_arf.json'#map #map81.37 82.10 # annFile = '/media/zf/E/CenterNet/exp/multi_pose/dla_USnavy512_DLA1x_FL/results.json'#map #map81.36 # annFile = '/media/zf/F/Dataset/USnavy_test_gt/json文件/dla_USnavy512_RGuass_scale1.json'#map 80.86 # annFile = '/media/zf/F/Dataset/USnavy_test_gt/json文件/results_Hourglass_512.json'#map 82.46 82.42 # annFile = "/media/zf/F/Dataset/USnavy_test_gt/json文件/CHP_DLA_34_ARF_RGUSS_roatate.json"# 0.9 0.15 0.03 0 83.09 # annFile = "/media/zf/E/Dataset/USnavy_test_gt/json文件/dla_USnavy512_guass.json" #map: 0.8661307458688858 # annFile = "/media/zf/E/Dataset/USnavy_test_gt/json文件/FGSD_DLA34_ARF_Rguass_20.json"#map: 0.861307352764251 # annFile = "/media/zf/F/Dataset/USnavy_test_gt/json文件/dla_USnavy512_RGuass1_12raduis_addconv_20.json"#map: 0.8307403617505426 map: 0.8357533770407948 # annFile = "/media/zf/E/Dataset/USnavy_test_gt/json文件/dla_1x_USnavy.json"#map: 0.8838930423970701 # annFile = "/media/zf/Z/0/hg_3x_Usnavy_512/results.json"#这是20类的HG104 map: 0.8508702824464331 # annFile ="/media/zf/E/CenterNet/exp/multi_pose/hg_3x_Usnavy_512/results.json"#map: 0.8508702824464331 # annFile = "/media/zf/E/CenterNet/exp/multi_pose/dla_USnavy512_RGuass1_12raduis_arf_20_FL/results.json" #map: 0.8437783437896875 # annFile="/media/zf/F/Dataset/USnavy_test_gt/json文件/dla_USnavy512_addconv_20.json"#map: 0.8265993090632107 # annFile = "/media/zf/F/Dataset/USnavy_test_gt/json文件/dla_USnavy512_20.json"#map: 0.8296416651842302 annFile = "/media/zf/Z/0/hg_arf_3x_Usnavy_512.json" gtFile='/media/zf/E/Dataset/US_Navy_train_square/annotations/person_keypoints_val2017.json' #the path you want to save your results for coco to voc merge_xmldir = '/media/zf/E/Dataset/US_Navy_train_square/FGSDxml' txt_dir_h = '/media/zf/E/Dataset/US_Navy_train_square/eval/0/' annopath = '/media/zf/E/Dataset/US_Navy_train_square/eval/GT20_TxT/' #GT_angle0_TxT#GT20_TxT nms_threshold=0.9#0.8 rnms_threshold=0.15#0.1 score_threshold=0.05 std_scale=0 NAME_LABEL_MAP ={ '航母': 1, '黄蜂级': 2, '塔瓦拉级': 3, '奥斯汀级': 4, '惠特贝岛级': 5, '圣安东尼奥级': 6, '新港级': 7, '提康德罗加级': 8, '阿利·伯克级': 9, '佩里级': 10, '刘易斯和克拉克级': 11, '供应级': 12, '凯泽级': 13, '霍普级': 14, '仁慈级': 15, '自由级': 16, '独立级': 17, '复仇者级': 18, '潜艇':19, '其他':20 } NAME_LONG_MAP = { '航母': 330, '黄蜂级': 253, '塔瓦拉级': 253, '奥斯汀级': 173, '惠特贝岛级': 185, '圣安东尼奥级': 208, '新港级': 168, '提康德罗加级': 172, '阿利·伯克级': 154, '佩里级': 135, '刘易斯和克拉克级': 210, '供应级': 229, '凯泽级': 206, '霍普级': 290, '仁慈级': 272, '自由级': 120, '独立级': 127, '复仇者级': 68, '潜艇':140, '其他':200 } normal=0.10 NAME_STD_MAP = { '航母': 0.1, '黄蜂级': normal, '塔瓦拉级': normal, '奥斯汀级': normal, '惠特贝岛级': normal, '圣安东尼奥级': normal, '新港级': normal, '提康德罗加级': normal, '阿利·伯克级': normal, '佩里级': normal+0.01, '刘易斯和克拉克级': normal, '供应级': normal-0.01, '凯泽级': normal-0.01, '霍普级': normal, '仁慈级': normal, '自由级': normal*2, '独立级': normal*2, '复仇者级': normal*2, '潜艇':0.75, '其他':1 } def get_label_name_map(NAME_LABEL_MAP): reverse_dict = {} for name, label in NAME_LABEL_MAP.items(): reverse_dict[label] = name return reverse_dict LABEL_NAME_MAP=get_label_name_map(NAME_LABEL_MAP) merge_json2rotatexml(gtFile,annFile, merge_xmldir, NAME_LABEL_MAP, NAME_LONG_MAP, NAME_STD_MAP, std_scale, score_threshold) eval_rotatexml(merge_xmldir, txt_dir_h, annopath, NAME_LABEL_MAP=NAME_LABEL_MAP, file_ext='.xml', flag='test', ovthresh=0.5)
zf020114/CHPDet
src/eval_json_CenR.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jun 15 23:00:51 2020 @author: zf """ # import pycocotools.coco as coco from pycocotools.coco import COCO import os import shutil from tqdm import tqdm import skimage.io as io import matplotlib.pyplot as plt import cv2 from PIL import Image, ImageDraw import numpy as np import sys sys.path.append('/home/zf/0tools') from py_cpu_nms import py_cpu_nms, py_cpu_label_nms from r_nms_cpu import nms_rotate_cpu from DataFunction import write_rotate_xml from All_Class_NAME_LABEL import NAME_LABEL_MAP_USnavy_20,NAME_LONG_MAP_USnavy,NAME_STD_MAP_USnavy,LABEL_NAME_MAP_USnavy_20 from Rotatexml2DotaTxT import eval_rotatexml def get_label_name_map(NAME_LABEL_MAP): reverse_dict = {} for name, label in NAME_LABEL_MAP.items(): reverse_dict[label] = name return reverse_dict def id2name(coco): classes=dict() for cls in coco.dataset['categories']: classes[cls['id']]=cls['name'] return classes def show_rotate_box(src_img,rotateboxes,name=None): cx, cy, w,h,Angle=rotateboxes[:,0], rotateboxes[:,1], rotateboxes[:,2], rotateboxes[:,3], rotateboxes[:,4] p_rotate=[] for i in range(rotateboxes.shape[0]): RotateMatrix=np.array([ [np.cos(Angle[i]),-np.sin(Angle[i])], [np.sin(Angle[i]),np.cos(Angle[i])]]) rhead,r1,r2,r3,r4=np.transpose([0,-h/2]),np.transpose([-w[i]/2,-h[i]/2]),np.transpose([w[i]/2,-h[i]/2]),np.transpose([w[i]/2,h[i]/2]),np.transpose([-w[i]/2,h[i]/2]) rhead=np.transpose(np.dot(RotateMatrix, rhead))+[cx[i],cy[i]] p1=np.transpose(np.dot(RotateMatrix, r1))+[cx[i],cy[i]] p2=np.transpose(np.dot(RotateMatrix, r2))+[cx[i],cy[i]] p3=np.transpose(np.dot(RotateMatrix, r3))+[cx[i],cy[i]] p4=np.transpose(np.dot(RotateMatrix, r4))+[cx[i],cy[i]] p_rotate_=np.int32(np.vstack((p1,p2,p3,p4))) p_rotate.append(p_rotate_) cv2.polylines(src_img,np.array(p_rotate),True,(0,255,255)) cv2.imshow('rotate_box',src_img.astype('uint8')) cv2.waitKey(0) cv2.destroyAllWindows() def result2rotatebox_cvbox(coco,dataset,img,classes,cls_id,show=True): annIds = coco.getAnnIds(imgIds=img['id'], catIds=cls_id, iscrowd=None) anns = coco.loadAnns(annIds) result_=np.zeros((0,7)) for ann in anns: class_name=classes[ann['category_id']] bbox=ann['bbox'] xmin = int(bbox[0]) ymin = int(bbox[1]) xmax = int(bbox[2] + bbox[0]) ymax = int(bbox[3] + bbox[1]) ang=bbox[4] score=ann['score'] if score>score_threshold: res_array=np.array([xmin,ymin,xmax,ymax,ang,score,NAME_LABEL_MAP[class_name]]).T result_=np.vstack((result_,res_array)) result = result_ cx, cy, w,h=(result[:,0]+result[:,2])/2 ,(result[:,1]+result[:,3])/2 ,(result[:,2]-result[:,0]) ,(result[:,3]-result[:,1]) ang=result[:,4]/180*np.pi center=np.vstack((cx,cy)).T#中心坐标 rotateboxes=np.vstack((cx, cy, w,h,ang,result[:,6],result[:,5])).T p_cv=[] cvboxes=np.zeros_like(rotateboxes) for i in range(rotateboxes.shape[0]): angle_cv=rotateboxes[i,4]/np.pi*180 if angle_cv>0: angle_cv=angle_cv cv_h=rotateboxes[i,3] cv_w=rotateboxes[i,2] else: angle_cv=angle_cv+90 cv_h=rotateboxes[i,2] cv_w=rotateboxes[i,3] cvboxes[i,:]=[rotateboxes[i,0],rotateboxes[i,1],cv_w,cv_h,angle_cv,result[i,6],result[i,5]] return cvboxes,rotateboxes def merge_json2rotatexml(gtFile, annFile, merge_xmldir, NAME_LABEL_MAP, NAME_LONG_MAP, NAME_STD_MAP, std_scale, score_threshold): classes_names = [] for name, label in NAME_LABEL_MAP.items(): classes_names.append(name) if not os.path.exists(merge_xmldir): os.mkdir(merge_xmldir) LABEl_NAME_MAP = get_label_name_map(NAME_LABEL_MAP) #COCO API for initializing annotated data coco = COCO(gtFile) # coco_o=COCO(gtFile) coco_res=coco.loadRes(annFile) #show all classes in coco classes = id2name(coco) print(classes) classes_ids = coco.getCatIds(catNms=classes_names) print(classes_ids) #Get ID number of this class img_ids=coco.getImgIds() print('len of dataset:{}'.format(len(img_ids))) # imgIds=img_ids[0:10] img_name_ori='' result=np.zeros((0,8)) name_det={} for imgId in tqdm(img_ids): img = coco_res.loadImgs(imgId)[0] # Img_fullname='%s/%s/%s'%(dataDir,dataset,img['file_name']) filename = img['file_name'] str_num=filename.replace('.jpg','').strip().split('__') img_name=str_num[0] scale=np.float(str_num[1]) ww_=np.int(str_num[2]) hh_=np.int(str_num[3]) cvboxes,rotateboxes=result2rotatebox_cvbox(coco_res, 'val2017', img, classes,classes_ids,show=True) xml_dir='/home/zf/CenterNet/exp/ctdet/CenR_usnavy512_dla_2x/rotatexml' write_rotate_xml(xml_dir, img["file_name"], [1024, 1024, 3], 0.5, 'USnavy', rotateboxes, LABEl_NAME_MAP, rotateboxes[:,6]) #size,gsd,imagesource # img_dir='/home/zf/CenterNet/data/coco/val2017' # src_img=cv2.imread(os.path.join(img_dir,img["file_name"])) # show_rotate_box(src_img,rotateboxes) # result_[:, 0:4]=(result_[:, 0:4]+ww_)/scale # if not img_name in name_det : # name_det[img_name]= result_ # else: # name_det[img_name]= np.vstack((name_det[img_name],result_)) # # # # #将所有检测结果综合起来 #正框mns # for img_name, result in name_det.items(): # # if std_scale==0: # # inx = py_cpu_nms(dets=np.array(result, np.float32),thresh=nms_threshold,max_output_size=500) # # result=result[inx] # # else: # # inx ,scores= py_cpu_label_nms(dets=np.array(result, np.float32),thresh=nms_threshold,max_output_size=500, # # LABEL_NAME_MAP=LABEL_NAME_MAP_USnavy_20, # # NAME_LONG_MAP=NAME_LONG_MAP_USnavy,std_scale=std_scale) # # result=result[inx] # # result[:, 4]=scores[inx] # cvrboxes,rotateboxes=result2rotatebox_cvbox(img,result) # #斜框NMS # if cvrboxes.size>0: # keep = nms_rotate_cpu(cvrboxes,cvrboxes[:,6],rnms_threshold, 200) #这里可以改 # rotateboxes=rotateboxes[keep] # # #去掉过小的目标 # # keep=[] # # for i in range(rotateboxes.shape[0]): # # box=rotateboxes[i,:] # # actual_long=box[3]*scale # # standad_long=NAME_LONG_MAP[LABEl_NAME_MAP[box[5]]] # # STD_long=NAME_STD_MAP[LABEl_NAME_MAP[box[5]]] # # if np.abs(actual_long-standad_long)/standad_long < STD_long *1.2 and box[2]>16: # # keep.append(i) # # else: # # print('{} hh:{} ww:{}'.format(img_name,hh_,ww_)) # # print('{} th label {} is wrong,long is {} normal long is {} width is {}'.format(i+1,LABEl_NAME_MAP[box[5]],actual_long,standad_long,box[3])) # # rotateboxes=rotateboxes[keep] # #保存检测结果 为比赛格式 # # image_dir,image_name=os.path.split(img_path) # # gt_box=rotateboxes[:,0:5] # # label=rotateboxes[:,6] # write_rotate_xml(merge_xmldir, '{}.jpg'.format(img_name), # [1024, 1024, 3], 0.5, 'USnavy', rotateboxes, # LABEl_NAME_MAP, rotateboxes[:, # 6]) #size,gsd,imagesource if __name__ == '__main__': #Store annotations and train2014/val2014/... in this folder annFile = '/home/zf/CenterNet/exp/ctdet/CenR_usnavy512_dla_2x/results.json' gtFile='/home/zf/Dataset/US_Navy_train_square/annotations/person_keypoints_val2017.json' #the path you want to save your results for coco to voc merge_xmldir = '/home/zf/Dataset/USnavy_test_gt/CenR_DLA34' txt_dir_h = '/media/zf/E/Dataset/US_Navy_train_square/eval/0/' annopath = '/media/zf/E/Dataset/US_Navy_train_square/eval/GT20_TxT/' #GT_angle0_TxT#GT20_TxT nms_threshold=0.9#0.8 rnms_threshold=0.15#0.1 score_threshold=0.1 std_scale=0.4 score_threshold_2=0.05 NAME_LABEL_MAP = NAME_LABEL_MAP_USnavy_20 NAME_LONG_MAP = NAME_LONG_MAP_USnavy NAME_STD_MAP = NAME_STD_MAP_USnavy merge_json2rotatexml(gtFile,annFile, merge_xmldir, NAME_LABEL_MAP, NAME_LONG_MAP, NAME_STD_MAP, std_scale, score_threshold) eval_rotatexml(merge_xmldir, txt_dir_h, annopath, NAME_LABEL_MAP=NAME_LABEL_MAP, file_ext='.xml', flag='test')
grafixoner/ownphotos
api/autoalbum.py
from api.models import Photo from api.models import Person from api.models import AlbumAuto from api.models import LongRunningJob from datetime import datetime, timedelta from itertools import groupby import os import shutil import numpy as np import ipdb from django_rq import job from tqdm import tqdm import rq from api.util import logger import pytz @job def regenerate_event_titles(user): job_id = rq.get_current_job().id if LongRunningJob.objects.filter(job_id=job_id).exists(): lrj = LongRunningJob.objects.get(job_id=job_id) lrj.started_at = datetime.now().replace(tzinfo=pytz.utc) lrj.save() else: lrj = LongRunningJob.objects.create( started_by=user, job_id=job_id, queued_at=datetime.now().replace(tzinfo=pytz.utc), started_at=datetime.now().replace(tzinfo=pytz.utc), job_type=LongRunningJob.JOB_GENERATE_AUTO_ALBUM_TITLES) lrj.save() try: aus = AlbumAuto.objects.filter(owner=user).prefetch_related('photos') target_count = len(aus) for idx,au in enumerate(aus): logger.info('job {}: {}'.format(job_id,idx)) au._autotitle() au.save() lrj.result = { 'progress': { "current": idx + 1, "target": target_count } } lrj.save() status = True message = 'success' res = {'status': status, 'message': message} lrj.finished = True lrj.finished_at = datetime.now().replace(tzinfo=pytz.utc) lrj.save() logger.info('job {}: updated lrj entry to db'.format(job_id)) except: lrj.failed = True lrj.finished = True lrj.finished_at = datetime.now().replace(tzinfo=pytz.utc) lrj.save() return 1 @job def generate_event_albums(user): job_id = rq.get_current_job().id if LongRunningJob.objects.filter(job_id=job_id).exists(): lrj = LongRunningJob.objects.get(job_id=job_id) lrj.started_at = datetime.now().replace(tzinfo=pytz.utc) lrj.save() else: lrj = LongRunningJob.objects.create( started_by=user, job_id=job_id, queued_at=datetime.now().replace(tzinfo=pytz.utc), started_at=datetime.now().replace(tzinfo=pytz.utc), job_type=LongRunningJob.JOB_GENERATE_AUTO_ALBUMS) lrj.save() try: photos = Photo.objects.filter(deleted=False).filter(owner=user).only('exif_timestamp') photos_with_timestamp = [(photo.exif_timestamp, photo) for photo in photos if photo.exif_timestamp] timestamps = [ photo.exif_timestamp for photo in photos if photo.exif_timestamp ] def group(photos_with_timestamp, dt=timedelta(hours=6)): photos_with_timestamp = sorted( photos_with_timestamp, key=lambda x: x[0]) groups = [] for idx,photo in enumerate(photos_with_timestamp): if len(groups) == 0: groups.append([]) groups[-1].append(photo[1]) else: if photo[0] - groups[-1][-1].exif_timestamp < dt: groups[-1].append(photo[1]) else: groups.append([]) groups[-1].append(photo[1]) logger.info('job {}: {}'.format(job_id,idx)) return groups groups = group(photos_with_timestamp, dt=timedelta(days=1, hours=12)) logger.info('job {}: made groups'.format(job_id)) album_locations = [] target_count = len(groups) date_format = "%Y:%m:%d %H:%M:%S" for idx, group in enumerate(groups): key = group[0].exif_timestamp logger.info('job {}: processing auto album with date: '.format(job_id) + key.strftime(date_format)) items = group if len(group) >= 2: qs = AlbumAuto.objects.filter(timestamp=key).filter(owner=user) if qs.count() == 0: album = AlbumAuto(created_on=datetime.utcnow().replace(tzinfo=pytz.utc), owner=user) album.timestamp = key album.save() locs = [] for item in items: album.photos.add(item) item.save() if item.exif_gps_lat and item.exif_gps_lon: locs.append([item.exif_gps_lat, item.exif_gps_lon]) if len(locs) > 0: album_location = np.mean(np.array(locs), 0) album_locations.append(album_location) album.gps_lat = album_location[0] album.gps_lon = album_location[1] else: album_locations.append([]) album._autotitle() album.save() logger.info('job {}: generated auto album {}'.format(job_id,album.id)) lrj.result = { 'progress': { "current": idx + 1, "target": target_count } } lrj.save() status = True message = 'success' res = {'status': status, 'message': message} lrj.finished = True lrj.finished_at = datetime.now().replace(tzinfo=pytz.utc) lrj.save() except: lrj.failed = True lrj.finished = True lrj.finished_at = datetime.now().replace(tzinfo=pytz.utc) lrj.save() return 1
GusSMoraes/shopee-case-study
casestudy.py
""" Sales Management Author: <NAME> License: MIT Status: 0.0.1 """ import os os.system("cls") class colors: GREEN = '\033[0;32m' RED = '\033[0;31m' BLUE = '\033[0;36m' END = '\033[m' # Add a sale def add(list, sellers): global id id += 1 sales = { "ID": id, "Seller Name": input('\nSeller Name: '), "Customer Name": input('Customer Name: '), "Date of Sale": input('Date of Sale: '), "Sale Item Name": input('Sale Item Name: '), "Sale Value": float(input('Sale Value: ')) } name = sales["Seller Name"] found = exist_seller(name, sellers) if found: list.append(sales) print(colors.GREEN + '\nSale successfully registered!' + colors.END) sales_list(list) else: print(colors.RED + '\nUnregistered seller!' + colors.END) id -= 1 sales_list(list) def exist_seller(name, sellers): for i in range(len(sellers)): if name == sellers[i]: found = True break else: found = False return found # Edit a sale def change(list, sellers): if len(list) > 0: change_id = int(input('\nEnter the sales ID to edit: ')) for i in range(len(list)): if list[i]['ID'] == change_id: if exist_sale(change_id, list): while True: print(colors.BLUE + '\n--- Edit Sales ---\n' + colors.END) print('[1] Seller Name') print('[2] Customer Name') print('[3] Date of Sale') print('[4] Sale Item Name') print('[5] Sale Value') option = int(input('\nEnter the corresponding option: ')) if option == 1: name = input("\nEnter the new sellers name: ") found = exist_seller(name, sellers) if found: list[i]['Seller Name'] = name print(colors.GREEN + "\nThe sellers name has been changed!" + colors.END) else: print(colors.RED + "\nUnregistered seller!" + colors.END) break elif option == 2: list[i]['Customer Name'] = input("\nEnter the new customers name: ") print(colors.GREEN + "\nThe customers name has been changed!" + colors.END) break elif option == 3: list[i]['Date of Sale'] = input("\nEnter the new date of sale: ") print(colors.GREEN + "\nThe date of sale has been changed!" + colors.END) break elif option == 4: list[i]['Sale Item Name'] = input("\nEnter the new sales item name: ") print(colors.GREEN + "\nThe sales item name has been changed!" + colors.END) break elif option == 5: list[i]['Sale Value'] = float(input("\nEnter the new sales value: ")) print(colors.GREEN + "\nThe sales value has been changed!" + colors.END) break else: print(colors.RED + '\nInvalid option! Try again!' + colors.END) sales_list(list) break else: print(colors.RED + "\nNo registered sale with this ID!" + colors.END) else: print(colors.RED + "\nNo registered sale!" + colors.END) # Check for a sale def exist_sale(id, list): if len(list) > 0: for sales in list: if sales['ID'] == id: return True return False # Remove a sale def remove(list): if len(list) > 0: del_id = int(input("\nEnter the sales ID to remove: ")) if exist_sale(del_id, list): for i in range(len(list)): if list[i]['ID'] == del_id: del list[i] print(colors.GREEN + "\nSale removed!" + colors.END) sales_list(list) break else: print(colors.RED + "\nNo registered sale with this ID!" + colors.END) else: print(colors.RED + "\nNo registered sale!" + colors.END) # Order the sales based on value def order(e): return e['Sale Value'] # Show the sales list def sales_list(list): print(colors.BLUE + "\n--- Sales List ---\n" + colors.END) list.sort(reverse=True, key=order) if len(list) > 0: for sales in list: print("ID: {}".format(sales['ID']), "Seller Name: {}".format(sales['Seller Name']), "Customer Name: {}".format(sales['Customer Name']), "Date of Sale: {}".format(sales['Date of Sale']), "Sale Item Name: {}".format(sales['Sale Item Name']), "Sale Value: {}".format(sales['Sale Value']), sep=' ') else: print(colors.RED + "No registered sale!" + colors.END) # Show the sellers list def sellers_list(list): print(colors.BLUE + "\n--- Sellers List---\n" + colors.END) for i in range(0, len(list)): print(list[i]) def clear(): input(colors.GREEN + "\nPress Enter to continue..." + colors.END) os.system("cls") id = 0 # Main def main(): list = [] sellers = ['Gustavo', 'Leonardo', 'Alice', 'Laura', 'Isabella'] while True: print(colors.BLUE + '\n--- Sales Management ---\n' + colors.END) print('[1] Register sale') print('[2] Change sale') print('[3] Remove sale') print('[4] Sales list') print('[5] Sellers list') print('[6] Exit') option = int(input('\nEnter the corresponding option: ')) if option == 1: add(list, sellers) elif option == 2: change(list, sellers) elif option == 3: remove(list) elif option == 4: sales_list(list) elif option == 5: sellers_list(sellers) elif option == 6: print(colors.GREEN + '\nEnd of program! Come back soon!' + colors.END) break else: print(colors.RED + '\nInvalid option! Try again!' + colors.END) print('\n------------------------------') clear() if __name__ == "__main__": main()
hetdev/hackerrank-solutions
py_set_difference_operation.py
<reponame>hetdev/hackerrank-solutions<gh_stars>0 n_1, students_list_1 = input(), list(input().split(" ")) n_2, students_list_2 = input(), list(input().split(" ")) answer_list = list(map(lambda s: s not in students_list_2, students_list_1)) print(sum(answer_list))
hetdev/hackerrank-solutions
any_or_all.py
n, n_list = list(input()), list(input().split(" ")) n_positive = (all(list(map(lambda v: False if int(v) < 0 else True, n_list)))) and ( any(list(map(lambda v: True if v == v[::-1] else False, n_list))) ) print(n_positive)
hetdev/hackerrank-solutions
ginorts.py
n = list(input()) lowers = [] uppers = [] nums_odd = [] nums_even = [] nums_zeros = [] for word in n: if word.islower(): lowers.append(word) elif word.isupper(): uppers.append(word) else: if int(word) % 2 == 0: nums_even.append(str(word)) elif int(word) == 0: nums_zeros.append(str(word)) else: nums_odd.append(str(word)) str_answer = "".join( sorted(lowers) + sorted(uppers) + sorted(nums_odd) + sorted(nums_zeros) + sorted(nums_even) ) print(str_answer)
hetdev/hackerrank-solutions
py_introduction_to_sets.py
<filename>py_introduction_to_sets.py def average(array): # your code goes here set_a = set(array) return sum(set_a) / len(set_a)
hetdev/hackerrank-solutions
itertools_permutations.py
from itertools import permutations inputt = input().split() for prod in sorted(list(permutations(inputt[0], int(inputt[1])))): print("".join(prod))
hetdev/hackerrank-solutions
itertools_combinations_with_replacement.py
<reponame>hetdev/hackerrank-solutions<gh_stars>0 from itertools import combinations, combinations_with_replacement word, size = input().split() words_list = list(combinations_with_replacement(sorted(word), int(size))) for word_l in words_list: print("".join(word_l))
hetdev/hackerrank-solutions
py_check_strict_superset.py
set_a = set(input().split()) num_sets = int(input()) i = 0 resp = [] while i < num_sets: set_b = set(input().split()) resp.append( len(set_b.intersection(set_a)) == len(set_b) and len(set_a) > len(set_b) ) i += 1 print(all(resp))
hetdev/hackerrank-solutions
py_check_subset.py
<gh_stars>0 num_cases = int(input()) i = 0 while i < num_cases: num_set_a = int(input()) set_a = set(input().split()) # print(set_a) num_set_b = int(input()) set_b = set(input().split()) print(len(set_a.intersection(set_b)) == num_set_a) i += 1
hetdev/hackerrank-solutions
itertools_product.py
<gh_stars>0 from itertools import product a = [int(i) for i in (input().split())] b = [int(i) for i in (input().split())] srt = "" for prod in tuple(product(a, b)): srt += f"{prod} " print(srt)
hetdev/hackerrank-solutions
py_set_symmetric_difference.py
n_1, students_list_1 = input(), set(input().split(" ")) n_2, students_list_2 = input(), set(input().split(" ")) print(len(students_list_1.symmetric_difference(students_list_2)))
ShayanRiyaz/BitUGrading
Teacher/DigitalHistory/Assignments_To_Be_Graded/123456789/Week_Two/Now_Try_This/5.py
# Please note that if you uncomment and press multiple times, the program will keep appending to the file. def cap_four(name): new_name = name[0].upper() + name[1:3] + name[3].upper() + name[4:] return new_name # Check answer = cap_four('macdonald') print(answer)
ShayanRiyaz/BitUGrading
Teacher/BitGrading.py
<reponame>ShayanRiyaz/BitUGrading<gh_stars>0 import numpy as np import pandas as pd import os import shutil import ast import subprocess def get_student_ids(move_dir,change_dir = True): ''' This function will read inside the provided move_dir directory and will list out all the folders inside. We are assuming the folder inside has all the studentids. :params: move_dir : The given directory where the student ids are location Change_dir : Boolean to change the directory we are currently in (default is True) :returns: list of folder names (string) inside the directory ''' if not os.path.exists(move_dir): return 'Wrong Path' if change_dir == True: os.chdir(move_dir) current_dir = os.path.abspath(os.getcwd()) x = [files for files in os.listdir(current_dir) if os.path.isdir(os.path.join(current_dir, files))] unwanted = [] for i in x: if '.' in i: unwanted.append(i) else: pass return [ele for ele in x if ele not in unwanted] else: current_dir = os.path.join(move_dir) x = [files for files in os.listdir(current_dir) if os.path.isdir(os.path.join(current_dir, files))] unwanted = [] for i in x: if '.' in i: unwanted.append(i) else: pass return [ele for ele in x if ele not in unwanted] def make_grade_sheet(student_ids): """ Makes a dataframe with respect to the number of student Ids and the number of questions. Requires an integer input of the number of questions. :params: student_ids : list of student ids inside the working directory :returns: grade_sheet : a dataframe made using pandas num_questions : the number of questions inputted by the user. """ num_questions = int(input('Input the number of questions in this assignment: ')) # Input the number of questions cols = ['ID'] # Student Ids for i in range(1,num_questions+1): cols.append(f'Q{i}') print('Initializaing the Points Tally for the Students') grade_sheet = pd.DataFrame() # Pandas dataframe for i in cols: grade_sheet[i] = 0.0 print('This is your grade sheet with all the Student Ids') grade_sheet['ID'] = student_ids grade_sheet[cols[1:]] = 0.0 print(grade_sheet) return grade_sheet,num_questions def week(student_id,week): ''' Searches for the number of folders inside the designated student id folder. We are assuming all folders inside are weeks. :returns: new path with the respective week folder ''' print(f'\nYou are in the {week} Directory') return os.path.join(student_id,week) def homework_or_NTT(student_week_path,ASSIGNMENT_TYPE): ''' Uses the provided path and joins it with the type of assignment provided if it exists :params: student_week_path : path that connects the student id folder and it's subdirectory assignment : name of the folder we want to add to our path. :returns: new path with the assignment folder joined ''' if not os.path.exists(os.path.join(student_week_path,ASSIGNMENT_TYPE)): return 'No Folder Found' return os.path.join(student_week_path,ASSIGNMENT_TYPE) def get_python_list(file_path): """ Find all the .py files in the directory and append them to a raw_files list. :params: file_path = the path to the folder where the to-be read folders are. :returns: raw_files : list of all files ending with '.py' in the read folder. """ python_files = [] for file in os.listdir(file_path): if file.endswith(".py"): python_files.append(file) print('\nThese are all the .py files inside the folder: \n') for i in python_files: print(i) return python_files def make_answer_key(num_questions): ''' This question provides the user the opportunity to set up all the answer keys by answer with 'Y' or to set up the answer key manually when grading the questions with 'N'. If 'Y' we will further be asked the following for every question. - Does the question have subparts? - What is the type of answer i.e integer (int), decimal (float), string (str), list (list), tuple (tuple) :params: num_questions : The number of question to create answer keys for :returns: if make_answer_keys == 'N' : None if make_answer_keys == 'Y' : A dynamic list of lists with the number of columns for every question depending on the number of subparts. ''' correct_answer = [] per_question_answers = [] make_answer_keys = input(' Would you like to set up the Correct Answers for the Questions right now\n or would you prefer setting them up manually?\n Pleae answer with Y or N respectively [Y/N]: ') while make_answer_keys != 'Y' and make_answer_keys != 'N': make_answer_keys = input(' Would you like to set up the Correct Answers for the Questions right now\n or would you prefer setting them up manually?\n Pleae answer with Y or N respectively [Y/N]: ') if make_answer_keys == 'Y': print('\n If there is a question you want to grade manually please enter "NaN"') print(f' There are {num_questions} Questions in this assignment,\n you will be asked to enter the answers for the sub parts depending on the question') for i in range(1,num_questions+1): while True: try: sub_parts = int(input(f' Please enter the number of subparts for Q{i}: ')) except ValueError: print("Sorry, I didn't understand that.") #better try again... Return to the start of the loop continue else: break for j in range(1,sub_parts+1): while True: try: answer = input(f' Enter the answer for Q{i} part {j}: ') answer_type = input('Is this answer is : \ninteger (int), \ndecimal (float), \nstring (str), \nlist (list), \ntuple (tuple): ') if answer_type == 'int': per_question_answers.append(int(answer)) elif answer_type == 'float': per_question_answers.append(float(answer)) elif answer_type == 'str': per_question_answers.append(str(answer)) elif answer_type == 'list': per_question_answers.append(ast.literal_eval(answer)) elif answer_type == 'tuple': per_question_answers.append(eval(answer)) elif answer_type != 'tuple' and answer_type != 'list' and answer_type != 'str' and answer_type == 'float' and answer_type == 'int': print('Incorrect input') return except ValueError: print("Sorry, I didn't understand that.") #better try again... Return to the start of the loop continue else: break correct_answer.append(per_question_answers) per_question_answers = [] elif make_answer_keys == 'N': print(' You will be manually entering the answers below for each question') return correct_answer,make_answer_keys ####################################### If Auto Grading ##################################################################### def grade_question(Question,student_ids,Grading_Sheet,answer,correct_answer): ''' This function selects the designated question number, and the first student id in the studen_ids and modifies the grades for the selected in the dataframe. :params: Question : student_ids : Grading_Sheet : answer : correct_answer : :returns: Grading sheet for the student being graded - Updated with the present score ''' if len(answer) != len(grading_sh for a in range(0,len(answer)): if answer[a] != correct_answer[a]: print(f'{answer[a]} is incorrect, correct answer is {correct_answer[a]}') Grading_Sheet.loc[Grading_Sheet.ID == student_ids[0],f'{Question}'] += 0 elif answer[a] == correct_answer[a]: print(f'{answer[a]} is correct') Grading_Sheet.loc[Grading_Sheet.ID == student_ids[0],f'{Question}'] += (1/len(answer)) return Grading_Sheet.loc[Grading_Sheet.ID == student_ids[0]] ####################################### If Manual Grading ##################################################################### def mannual_answer_key(question_num,correct_answer_key= None): if question_num == 1: correct_answer_key = [] per_question_answers = [] for i in range(question_num,question_num+1): while True: try: sub_parts = int(input(f' Please enter the number of subparts for Q{question_num}: ')) except ValueError: print("Sorry, I didn't understand that.") #better try again... Return to the start of the loop continue else: break for j in range(1,sub_parts+1): while True: try: answer = input(f' Enter the answer for Q{question_num} part {j}: ') answer_type = input('Is this answer is : \ninteger (int), \ndecimal (float), \nstring (str), \nlist (list), \ntuple (tuple): ') if answer_type == 'int': per_question_answers.append(int(answer)) elif answer_type == 'float': per_question_answers.append(float(answer)) elif answer_type == 'str': per_question_answers.append(str(answer)) elif answer_type == 'list': per_question_answers.append(ast.literal_eval(answer)) elif answer_type == 'tuple': per_question_answers.append(eval(answer)) elif answer_type != 'tuple' and answer_type != 'list' and answer_type != 'str' and answer_type == 'float' and answer_type == 'int': print('Incorrect input') return except ValueError: print("Sorry, I didn't understand that.") #better try again... Return to the start of the loop continue else: break correct_answer_key.append(per_question_answers) per_question_answers = [] return correct_answer_key,question_num def manual_grade_question(q,correct_answer_key,Grading_Sheet,student_ids,student_answers = None): #for j in range(len(manually_graded_questions)): #output = subprocess.check_output(['python', f'{manually_graded_questions[j]}.py']) # executes the file and saves the output #answers = output.decode('utf-8') # deletes an empty element at the end print(f"\nThis is the answer for Q{q} vs What the student answered: \n") if student_answers: for ans in range(len(correct_answer_key)): if len(correct_answer_key) == len(student_answers): print(f"The correct answer is {correct_answer_key[ans]} : The student answered {student_answers[ans]}") else: print('length not equal') break for i in correct_answer_key: r_or_w = input(f"Is this answer : '{i}' correct?") if r_or_w == 'Y': Grading_Sheet.loc[Grading_Sheet.ID == student_ids[0],f'Q{q}'] += (1/len(correct_answer_key)) print(Grading_Sheet.loc[Grading_Sheet.ID == student_ids[0]]) elif r_or_w == 'N': Grading_Sheet.loc[Grading_Sheet.ID == student_ids[0],f'Q{q}'] += 0 return Grading_Sheet ###################################### Steps after grading #################################################################### def move_graded_student(Graded_folder,student_ids): ''' Moves the folder graded student_id to the Grade folder. One the folder has been moved the student id is removed from the student_ids list. :params: Graded_folder: Name of the graded folder where the student id folder will be moved. student_ids : The student Id folder to be moved. Assumed to be the first :returns: if remaining student_ids == 0 : returns message that we are done grading else : returns the count of remaining students. ''' os.chdir('../../../') print(os.path.abspath(os.getcwd())) if not os.path.exists(f'../{Graded_folder}'): os.mkdir(f'../{Graded_folder}') print('Successfully Created Directory, Lets get started') else: print('Directory Already Exists') shutil.move(f'{student_ids[0]}',f'../{Graded_folder}') student_ids.pop(0) if len(student_ids) == 0: x = "You are Done Grading!" os.chdir('../../') return len(student_ids) else: print(f"Number of Students Left: {len(student_ids)}") print(f"Ids Left: {student_ids}") os.chdir('../../') return len(student_ids) ##### FUNCTIONS IN TESTING PHASE ############### def questions_to_manually_grade(correct_answer_key): manually_grade_questions = [] for i in range(0,len(correct_answer_key)): if correct_answer_key[i][0][0] == 'NA': manually_grade_questions.append([i+1][0]) #print("This is NA You'll have to grade the question manually") correct_answer_key.pop([i][0]) #answer.pop(i-1) else: pass return correct_answer_key,manually_grade_questions
ShayanRiyaz/BitUGrading
Teacher/DigitalHistory/Assignments_To_Be_Graded/123456789/Week_Two/Now_Try_This/3.py
<filename>Teacher/DigitalHistory/Assignments_To_Be_Graded/123456789/Week_Two/Now_Try_This/3.py # Please note that if you uncomment and press multiple times, the program will keep appending to the file. t = (1,2,3) # An example print(type(t))
ShayanRiyaz/BitUGrading
Teacher/DigitalHistory/Assignments_To_Be_Graded/123456789/Week_Two/Now_Try_This/2.py
<filename>Teacher/DigitalHistory/Assignments_To_Be_Graded/123456789/Week_Two/Now_Try_This/2.py<gh_stars>0 # Please note that if you uncomment and press multiple times, the program will keep appending to the file. answer1 = [0]*3 print(answer1)# Please note that if you uncomment and press multiple times, the program will keep appending to the file. list3 = [1,2,[3,4,'hello']] list3[2][2] = 'goodbye' list3# Please note that if you uncomment and press multiple times, the program will keep appending to the file. list4 = [5,3,4,6,1] answer2 = sorted(list4) print(answer2)
ShayanRiyaz/BitUGrading
Teacher/DigitalHistory/Assignments_To_Be_Graded/123456789/Week_Two/Now_Try_This/6.py
# Please note that if you uncomment and press multiple times, the program will keep appending to the file. x = 5 y = 0 try: z = x/y except ZeroDivisionError: print("Can't divide by Zero!") finally: print('All Done!')
ShayanRiyaz/BitUGrading
Teacher/DigitalHistory/Assignments_To_Be_Graded/016993270/Week_Two/Now_Try_This/1.py
# Please note that if you uncomment and press multiple times, the program will keep appending to the file. s = 'Amsterdam' # Print out 'e' using indexing answer1 = s[2] print(answer1)# Please note that if you uncomment and press multiple times, the program will keep appending to the file. s ='Amsterdam' # Reverse the string using slicing answer2 = s[1] print(answer2)# Please note that if you uncomment and press multiple times, the program will keep appending to the file. answer3 = s[::-1] print(answer3)
ShayanRiyaz/BitUGrading
Teacher/DigitalHistory/Assignments_To_Be_Graded/123456789/Week_Two/Now_Try_This/4.py
# Please note that if you uncomment and press multiple times, the program will keep appending to the file. d = {'simple_key':'hello'} answer1 = d['simple_key'] print(answer1)# Please note that if you uncomment and press multiple times, the program will keep appending to the file. d = {'k1':{'k2':'hello'}} answer2 = d['k1']['k2'] print(answer2)# Please note that if you uncomment and press multiple times, the program will keep appending to the file. d = {'k1':[{'nest_key':['this is deep',['hello']]}]} answer3 = d['k1'][0]['nest_key'][1][0] print(answer3)# Please note that if you uncomment and press multiple times, the program will keep appending to the file. d = {'k1':[1,2,{'k2':['this is tricky',{'tough':[1,2,['hello']]}]}]} answer4 = d['k1'][2]['k2'][1]['tough'][2][0] print(answer4)
ShayanRiyaz/BitUGrading
Teacher/BitGrader.py
<reponame>ShayanRiyaz/BitUGrading<filename>Teacher/BitGrader.py import BitGrading import pandas as pd import numpy as np import os import ast import shutil import subprocess grading_done = False initialize = False DIRECTORY = 'DigitalHistory/Assignments_To_Be_Graded' while not grading_done: while not initialize: student_ids = BitGrading.get_student_ids(DIRECTORY,change_dir=False) print(f"These are all the student Id's in our Directory : {student_ids}\n") print(f"These are the Weeks inside {student_ids[0]}: {os.listdir(f'DigitalHistory/Assignments_To_Be_Graded/{student_ids[0]}')}") WEEK_NUM = 'Week_Two'#input('Enter the name of the folder you want to grade: ') print(f"\nThese are the Assignment Types inside {student_ids[0]}: {os.listdir(f'DigitalHistory/Assignments_To_Be_Graded/{student_ids[0]}/{WEEK_NUM}')}") ASSIGNMENT_TYPE = 'Now_Try_This'#input('Enter the name of the assignment type you want to grade: ') Grading_Sheet,num_questions = BitGrading.make_grade_sheet(student_ids) manual = 'Y' correct_answer_key = [["e","m","m"],['[0,0,0]',"[1, 2, [3, 4, 'goodbye']]",'[1, 3, 4, 5, 6]]'], [["<type 'tuple'>"]],[["hello"],["hello"],["hello"],["hello"]],[["MacDonald"]], [["NA"]]] #correct_answer_key,manual = BitGrading.make_answer_key(num_questions) initialize = True if manual == 'Y': print(correct_answer_key) manual_grading_check = False student_ids = BitGrading.get_student_ids(DIRECTORY,change_dir=True) week_path = BitGrading.week(student_ids[0],WEEK_NUM) file_path = BitGrading.homework_or_NTT(week_path,ASSIGNMENT_TYPE) assignment_list = BitGrading.get_python_list(file_path) print(f'Currently Grading {student_ids[0]} -> {WEEK_NUM} - > {ASSIGNMENT_TYPE} Section.') os.chdir(file_path) correct_answer_key,manually_graded_questions = BitGrading.questions_to_manually_grade(correct_answer_key) for man_grade in range(0,len(assignment_list)): if assignment_list[man_grade] == f'{man_grade}.py': assignment_list.pop(man_grade) for i in range(0,len(assignment_list)-1): print('SANITY CHECK----------------------------------------1') output = subprocess.check_output(['python', f'{i+1}.py']) # executes the file and saves the output answers = output.decode('utf-8').split('\n')[:-1] # deletes an empty element at the end print(f'The Student Answered: {answers}\n') if manual == 'N': correct_answer_key,question = BitGrading.mannual_answer_key(1) print(f'\n The correct answer key for {question} is {correct_answer_key}') BitGrading.grade_question(f'Q{i+1}',student_ids,Grading_Sheet,answers,correct_answer_key[i],) print(f'\n{Grading_Sheet.loc[Grading_Sheet.ID == student_ids[0]]}') else: BitGrading.grade_question(f'Q{i+1}',student_ids,Grading_Sheet,answers,correct_answer_key[i],) Grading_Sheet.loc[Grading_Sheet.ID == student_ids[0]] BitGrading.manual_grade_question(manually_graded_questions,Grading_Sheet,student_ids) print('SANITY CHECK----------------------------------------2') GRADED_FOLDER = 'Assignments_Graded' remaining_students = BitGrading.move_graded_student(GRADED_FOLDER,student_ids) if remaining_students == 0: print('SANITY CHECK----------------------------------------3') Grading_Sheet['Total_Score'] = Grading_Sheet.iloc[:, 1:].sum(axis=1) export_file_path = f'{WEEK_NUM}_Grades' Grading_Sheet.to_csv (export_file_path, index = True, header=True) grading_done = True
PhilMcDaniel/python-crash-course
2_variables_and_data_types.py
#simple print with var message = "hello world!" print(message) #print same after changing var message = "hola globa" print(message) #string manip and formatting name = "<NAME>" print(name.title()) print(name.upper()) print(name.lower()) first_name = "john" last_name = "doe" full_name = f"{first_name} {last_name}" print(full_name) print(f"Hello, {full_name.title()}!") print("\tPython") print("Python\n\tPythonLine2") langs = ' python ' print(langs) print(langs.rstrip()) print(langs.lstrip()) print(langs.strip()) #integer/decimal stuff print(3+2) print(3/2) print(3-2) print(3**2) print(2+3*4) print((2+3)*4) print(.2+.22) large_num = 10_000_000 print(large_num) x,y,z = 1,2,3 print(f"x={x} y={y} z={z}") #constant in caps CONSTANT = 333 print (CONSTANT)
PhilMcDaniel/python-crash-course
8_pizza.py
def make_pizza(size,*toppings): """summarize the pizza""" print(f"\nMaking a {size}-inch pizza with the following toppings") for topping in toppings: print(f" - {topping}")
PhilMcDaniel/python-crash-course
5_if_statements.py
<reponame>PhilMcDaniel/python-crash-course cars = ["audi","bmw","subaru","toyota"] print(cars) for car in cars: if car == "bmw": print(car.upper()) else: print(car.title()) #set value car = 'bmw' #compare value car =='bmw' print(car == 'bmw') #equality check is case-sensitive car = 'Audi' print(car =='audi') toppings = "mushrooms" print(toppings) if toppings != "anchovies": print("hold the anchovies") else: print ("bring on the anchovies") #numerical comparisons age = 18 print(age == 18) answer = 25 if answer != 42: print("the answer is incorrect") age = 19 print (age <= 21) print (age > 21) #multiple conditions w/ and age_0 = 22 age_1 = 18 print (age_0 >= 21 and age_1 >= 21) age_1 = 23 print (age_0 >= 21 and age_1 >= 21) #multiple conditions w/ or age_0 = 22 age_1 = 18 print (age_0 >= 21 or age_1 >= 21) age_0 = 18 age_1 = 18 print (age_0 >= 21 or age_1 >= 21) #checking values in a list toppings = ['mushrooms','onions','pineapple'] print ('mushrooms' in toppings) print ('pepperoni' in toppings) #checking value not in a list banned_users = ['andrew','carolina','david'] user = 'marie' if user not in banned_users: print (f"{user.title()}, you are allowed to post a response") #boolean game_active = True can_edit = False #multiple actions age = 19 if age >=18: print("You are old enough to vote") print("Have you registered to vote yet?") #if else age = 17 if age >= 18: print("You are old enough to vote yet") else: print("Sorry, you are too young to vote") #if elif else age = 12 if age < 4: print("Your admission cost is $0") elif age < 18: print("Your admission cost is $25") else: print("Your admission cost is $40") age = 12 if age < 4: price = 0 elif age < 18: price = 25 elif age < 65: price = 40 else: price = 20 print(f"Your admission cost is ${price}.") #testing multiple conditions toppings = ["mushrooms","extra cheese"] #not using if elif because it would short circuit on single hit if "mushrooms" in toppings: print("Adding mushrooms") if 'pepperoni' in toppings: print("Adding pepperoni") if 'extra cheese' in toppings: print("adding extra cheese") print("\nFinished making your pizza") #if/else with loop toppings = ['mushrooms','green peppers','extra cheese'] #print(toppings) for topping in toppings: if topping == 'green peppers': print("sorry, we are out of green peppers") else: print(f"adding {topping}.") print("\nFinished making your pizza") #checking for non empty list toppings = [] if toppings: for topping in toppings: print(f"adding {topping}") else: print("are you sure you want a plain pizza?") a_toppings = ["mushrooms","olives","green peppers","pepperoni","pineapple","extra cheese"] r_toppings = ["mushrooms","french fries","extra cheese"] for r_topping in r_toppings: if r_topping in a_toppings: print(f"adding {r_topping}") else: print(f"Sorry, we don't have {r_topping}") print("\nFinished making your pizza")
PhilMcDaniel/python-crash-course
4_working_with_lists.py
<gh_stars>0 magicians = ['alice','david','carolina'] #print each entry in list for magician in magicians: print(magician) #for loop with formatted text for magician in magicians: print(f"{magician.title()}, that was a great trick!") print(f"I can't wait to see your next trick, {magician.title()}.\n") print("Thank you everyone, that was a great show") #numerical loops #loop ends when max value is hit. Need to +1 to ensure 1-5 are all printed for value in range(1,6): print(value) numbers = list(range(1,6)) print (numbers) #skip numbers, use third param in range() even_numb = list(range(0,11,2)) print(even_numb) #first 10 square numbers square_numb = [] for num in range(1,11): num = num**2 square_numb.append(num) #square_numb.append(num**2) print(square_numb) digits = [1,2,3,4,5,6,7,8,9,0] min_d = min(digits) print(min_d) max_d = max(digits) print(max_d) sum_d = sum(digits) print(sum_d) #single line to create first 10 squares squares = [value**2 for value in range(1,11)] print(squares) #slicing list players = ['charles','martina','michael','florence','eli'] print (players[0:3]) print (players[1:4]) #start at beginning and give me 4 print (players[:4]) #start at two and give me rest of list print(players[2:]) #last three in list print(players[-3:]) #looping through a slice print("Here are the first three players in my team:") for player in players[:3]: print (player) #copying lists my_foods = ['pizza','ice cream','pasta','cake'] print(my_foods) your_foods = my_foods[:] print (your_foods) my_foods.append('tacos') your_foods.append('celery') print(my_foods) print(your_foods) #tuples = immutable list. uses () instead of [] dimensions = (200,50) print(dimensions[0]) print(dimensions[1]) #tuple with single value needs trailing comma dimensions = (30,) print(dimensions[0]) #loop over tuple dimensions = (200,50,10,1,0,99) for dimension in dimensions: print (dimension) dimensions = (200,50,10)
PhilMcDaniel/python-crash-course
3_lists.py
#list ex bikes = ['trek','giant','cannondale','redline'] print (bikes) #print first value in list print(bikes[0]) print(bikes[0].title()) print(bikes[1]) print(bikes[3]) #-1 position is last, -2 second from last print(bikes[-1]) print(bikes[-2]) #formatted example print(f"My first bike was a {bikes[0].title()}.") #change value of first object in list motos = ['honda','yamaha','suzuki'] print(motos[0]) motos[0]= 'ducati' print(motos[0]) #append adds to end of list motos = ['honda','yamaha','suzuki'] motos.append("ducati") print (motos) #can initialize empty list and add later motos = [] print(motos) motos.append('honda') motos.append('yamaha') motos.append('suzuki') print(motos) #insert() lets you add to list at location of your choosing motos = ['honda','yamaha','suzuki'] motos.insert(0,'ducati') print(motos) #remove from list using del del motos[0] print (motos) #pop removes from end of list, but can be accessed pop_motos = motos.pop() print(motos) print(pop_motos) #can pop from any position with index value passed pop_motos = motos.pop(1) print(pop_motos) #removing based on value motos = ['honda','yamaha','suzuki','ducati'] print(motos) motos.remove('ducati') print(motos) #organizing a list cars = ['bmw','audi','toyota','subaru'] print(cars) cars.sort() print(cars) #reverse order, does not sort alphabetically cars.sort(reverse=True) print(cars) #length of list print(len(cars))
PhilMcDaniel/python-crash-course
7_user_input_and_while_loops.py
<reponame>PhilMcDaniel/python-crash-course # input() has a single prompt parameter. Pauses execution and waits for input message = input("Tell me something about yourself and I will tell it back to you") print(message) name = input("Please enter your name: ") print(f"\nHello, {name}") # multi-line prompt prompt = "If you tell us who you are, we can personalize the messages you see." prompt += "\nWhat is your first name? " name = input(prompt) print("\nHello, {name}") # input response is always a string, until it isnt age = input("How old are you? ") print(age) # This would throw an error # age>21 # convert input to int print(int(age) > 21) height = input("How tall are you in inches? ") height = int(height) print(height) if height >= 48: print("\nYou're tall enough to ride!") else: print("You'll be able to ride when you get taller") # modulo = remainder of division num % denom # when 0 returned, then the numbers are divisible 4 % 3 6 % 2 number = input("Enter a number and I'll tell you if it's even or odd: ") number = int(number) if number % 2 == 0: print(f"\nThe number {number} is even") else: print(f"\nThe number {number} is odd") # while loops current_number = 1 while current_number <= 5: print(current_number) current_number += 1 prompt = "\nTell me something, and I will repeat it back to you:" prompt += "\nEnter 'quit' to end the program" message = "" while message != "quit": message = input(prompt) # This is added so that the word quit is not printed out when it is the message value from input if message != "quit": print(message) # using a flag to accomplish the same thing prompt = "\nTell me something, and I will repeat it back to you:" prompt += "\nEnter 'quit' to end the program" active = True while active: message = input(prompt) if message == "quit": active = False else: print(message) # using break to exit prompt = "\nEnter a city that you have visted:" prompt += "\n(Enter 'quit' to finish.)" while True: city = input(prompt) if city == "quit": break else: print(f"I'd love to go to {city.title()}!") # using continue to go back to beginning of loop logic current_number = 0 while current_number < 10: current_number += 1 if current_number % 2 ==0: continue print(current_number) x = 1 while x <= 5: print(x) x+=1 #while loops with lists and dicts unconfirmed_users = ['alice','brian','candace'] confirmed_users = [] #verify each user until all are confirmed while unconfirmed_users: current_user = unconfirmed_users.pop() print(f"Verifying user: {current_user.title()}") confirmed_users.append(current_user) #display confirmed users print("\nThe following users have been confirmed:") for user in confirmed_users: print(user.title()) #removing specific values from list pets = ['dog','cat','dog','goldfish','cat','rabbit','cat'] print(pets) while 'cat' in pets: pets.remove('cat') print(pets) #filling a dictionary responses = {} polling_active = True while polling_active: name = input("\nWhat is your name:") response = input("Which mountaing would you like to climb? ") #store responses[name] = response repeat = input("Would you like to let another user respond? (yes/no)") if repeat == 'no': polling_active = False print("\n--- Poll Results ---") for name, response in responses.items(): print(f"{name} would like to climb {response}.")
PhilMcDaniel/python-crash-course
9_classes.py
<gh_stars>0 #capital for classes #function inside a class is called a method #class is set of instructions to call a specific instance class Dog: """A simple attempt to model a dog""" #__init__ is special method that python runs automatically when we create new instance of class #self is needed and must come first def __init__(self,name,age): """initialize name and age attributes""" #any variable with self. is available to entire class and any instance #variables that are accessable through instances are called attributes self.name = name self.age = age def sit(self): """simulate dog sitting after command""" print(f"{self.name} is now sitting") def roll_over(self): """simulate rolling over after command""" print(f"{self.name} rolled over!") #instance of Dog class #instance.attribute for accessing values of attributes my_dog = Dog('willie',6) print(f"My dog's name is {my_dog.name}") print(f"My dog is {my_dog.age} years old") #call a method from the instance of Dog my_dog my_dog.sit() my_dog.roll_over() #creating multing instances my_dog = Dog('willie',6) your_dog = Dog('Lucy',3) print(f"My dog's name is {my_dog.name}") print(f"My dog is {my_dog.age} years old") print(f"\nYour dog's name is {your_dog.name}") print(f"Your dog is {your_dog.age} years old") #Working with classes and instances class Car: """A simple attempt to represent a car""" def __init__(self,make,model,year): self.make = make self.model = model self.year = year def get_descriptive_name(self): """Return a neatly formatted name.""" long_name = f"{self.year} {self.make} {self.model}" return long_name.title() my_car = Car('toyota','camry','2015') print(my_car.get_descriptive_name()) #setting default value for an attribute class Car: """A simple attempt to represent a car""" def __init__(self,make,model,year): self.make = make self.model = model self.year = year self.odometer_reading = 0 def get_descriptive_name(self): """Return a neatly formatted name.""" long_name = f"{self.year} {self.make} {self.model}" return long_name.title() def read_odometer(self): """Print a statement showing car mileage""" print(f"This car has {self.odometer_reading} miles on it.") my_car = Car('toyota','camry','2015') print(my_car.get_descriptive_name()) my_car.read_odometer() #modifying attribute values #direct modification my_car.odometer_reading = 23 my_car.read_odometer() #modify via method class Car: """A simple attempt to represent a car""" def __init__(self,make,model,year): self.make = make self.model = model self.year = year self.odometer_reading = 0 def get_descriptive_name(self): """Return a neatly formatted name.""" long_name = f"{self.year} {self.make} {self.model}" return long_name.title() def read_odometer(self): """Print a statement showing car mileage""" print(f"This car has {self.odometer_reading} miles on it.") def update_odometer(self,mileage): """Set the odometer to given value. Reject if there is an attempt to decrease""" if mileage >= self.odometer_reading: self.odometer_reading = mileage else: print("You can't roll back the odometer") my_car = Car('toyota','camry','2015') print(my_car.get_descriptive_name()) my_car.read_odometer() my_car.update_odometer(24) my_car.read_odometer() my_car.update_odometer(10) #incrementing an attribute via method class Car: """A simple attempt to represent a car""" def __init__(self,make,model,year): self.make = make self.model = model self.year = year self.odometer_reading = 0 def get_descriptive_name(self): """Return a neatly formatted name.""" long_name = f"{self.year} {self.make} {self.model}" return long_name.title() def read_odometer(self): """Print a statement showing car mileage""" print(f"This car has {self.odometer_reading} miles on it.") def update_odometer(self,mileage): """Set the odometer to given value. Reject if there is an attempt to decrease""" if mileage >= self.odometer_reading: self.odometer_reading = mileage else: print("You can't roll back the odometer") def increment_odometer(self,miles): """add given amount to odometer reading""" self.odometer_reading += miles my_car = Car('toyota','camry','2015') print(my_car.get_descriptive_name()) my_car.read_odometer() my_car.update_odometer(1500) my_car.read_odometer() my_car.increment_odometer(200) my_car.read_odometer() #inheritance #when a class inherits from another, it takes the attributes and methods from the parent class. can define new attributes or methods class Car: """Simple representation of a car""" def __init__(self,make,model,year): self.make = make self.model = model self.year = year self.odometer_reading = 0 def get_descriptive_name(self): """Return a neatly formatted name.""" long_name = f"{self.year} {self.make} {self.model}" return long_name.title() def read_odometer(self): """Print a statement showing car mileage""" print(f"This car has {self.odometer_reading} miles on it.") def update_odometer(self,mileage): """Set the odometer to given value. Reject if there is an attempt to decrease""" if mileage >= self.odometer_reading: self.odometer_reading = mileage else: print("You can't roll back the odometer") def increment_odometer(self,miles): """add given amount to odometer reading""" self.odometer_reading += miles #inherited class class ElectricCar(Car): """Represents aspects of a car, specific to electric cars""" def __init__(self,make,model,year): """initialize attributes from parent""" #super() function reaches to parent class super().__init__(make,model,year) my_tesla = ElectricCar('tesla','model s','2019') print(my_tesla.get_descriptive_name()) #extend child class with new method and attributes class ElectricCar(Car): """Represents aspects of a car, specific to electric cars""" def __init__(self,make,model,year): """initialize attributes from parent""" #super() function reaches to parent class super().__init__(make,model,year) self.battery_size = 75 def describe_battery_size(self): """print a statement describing the battery""" print(f"The battery size is {self.battery_size}") my_tesla = ElectricCar('tesla','model s','2019') print(my_tesla.get_descriptive_name()) my_tesla.describe_battery_size() #override method from parent class # define method in child class with same name as in parent class class ElectricCar(Car): #assume the "Car" class had a method for this and we wanted to override it for ElectricCar def fill_gas_tank(self): print("This car doesn't need a gas tank") #instances as attributes #useful for breaking large classes into smaller ones that work together class Battery: """simple model of battery for an electric car""" def __init__(self,battery_size=75): self.battery_size = battery_size def describe_battery(self): """print a statement describing the battery""" print(f"This car's battery size is: {self.battery_size}") def get_range(self): """print a statement about the battery's range""" if self.battery_size == 75: range = 260 elif self.battery_size == 100: range = 315 print(f"This car can go about {range} miles") my_battery = Battery() my_battery.describe_battery() class ElectricCar(Car): """Represents aspects of a car, specific to electric cars""" def __init__(self,make,model,year): """initialize attributes from parent""" super().__init__(make,model,year) #reference the battery class and create new attribute for child class self.battery = Battery() my_tesla = ElectricCar('tesla','model s','2019') print(my_tesla.get_descriptive_name()) my_tesla.battery.describe_battery() my_tesla.battery.get_range() #importing classes #from file/module import class as alias #from file/module import class1, class2, classn ... #from file/modeule (will need to use dot notation to access specific classes) #can do nested importing of dependent classses #python standard lib from random import randint randint(1,6) from random import choice players = ['charles','martina','michael','florence','eli'] first=choice(players) print(first) #styling classes #class names in CamelCase #always include docstring """ class expl """ #import from standard lib first, leave blank line, import custom modules
PhilMcDaniel/python-crash-course
6_dictionaries.py
#dictionary is group of key-value pairs alien_0 = {'color':'green','points':'5'} print(alien_0['color']) print(alien_0['points']) new_points = alien_0['points'] print(f"You just earned {new_points} points.") #adding values to dictionary alien_0['x_position'] = 0 alien_0['y_position'] = 25 print(alien_0) #start with empty dictionary alien_0 = {} print(alien_0) alien_0['color'] = 'green' alien_0['points'] = 5 print(alien_0) #change value print(alien_0['color']) alien_0['color'] = 'yellow' print(alien_0['color']) alien_0 = {'x_position':0,'y_position':25,'speed':'medium'} print(alien_0) #move to right #alien_0['speed'] = 'fast' if alien_0['speed'] == 'slow': x_increment = 1 elif alien_0['speed'] == 'medium': x_increment = 2 else: x_increment = 3 alien_0['x_position'] = alien_0['x_position'] + x_increment print(f"New position: {alien_0['x_position']}") #removing values print(alien_0) del alien_0['speed'] print(alien_0) fav_lang = { 'jen':'python' ,'sarah':'c' ,'edward':'ruby' ,'phil':'python' } print(fav_lang) lang = fav_lang['sarah'].title() print(f"Sarah's favorite language is {lang}") #using get() to provide defaults alien_0 = {'color':'green','speed':'slow'} # The below fails because that key does not exist # print(alien_0['points'] print(alien_0.get('points','No points value assigned')) #looping through dictionary user_0 = { 'username':'efermi' ,'first':'enrico' ,'last':'fermi' } print(user_0) for key,value in user_0.items(): print(f"\nKey: {key}") print(f"Value: {value}") fav_lang = { 'jen':'python' ,'sarah':'c' ,'edward':'ruby' ,'phil':'python' } for name,language in fav_lang.items(): print(f"{name.title()}'s favorite language is {language}.") #loop through only keys (use keys() method) for name in fav_lang.keys(): print(name.title()) friends = ['phil','sarah'] for name in fav_lang.keys(): print(f"Hi, {name.title()}.") if name in friends: language = fav_lang[name].title() print(f"\t{name.title()}, I see you love {language}") if 'erin' not in fav_lang.keys(): print("Erin, please take our poll") #looping through dictionary in a specific order fav_lang = { 'jen':'python' ,'sarah':'c' ,'edward':'ruby' ,'phil':'python' } for name in sorted(fav_lang.keys()): print(f"{name.title()}, thank you for taking our poll!") print("The following languages have been mentioned:") for lang in fav_lang.values(): print({lang.title()}) #using set() to de-dupe #"python" was listed twice for lang in set(fav_lang.values()): print({lang.title()}) #nesting alien_0 = {'color':'green','points':5} alien_1 = {'color':'yellow','points':10} alien_2 = {'color':'red','points':15} aliens = [alien_0,alien_1,alien_2] for alien in aliens: print(alien) #using loop to create multiple dictionary values aliens=[] for alien_number in range(30): new_alien = {'color':'green','points':5,'speed':'slow'} aliens.append(new_alien) #display first 5 for alien in aliens[:5]: print(alien) print("...") print(f"Total number of aliens: {len(aliens)}") #modify 3 rows to change a value for alien in aliens[:3]: if alien['color'] == 'green': alien['color'] = 'yellow' alien['speed'] = 'medium' alien['points'] = 10 for alien in aliens[:5]: print(alien) print("...") print(f"Total number of aliens: {len(aliens)}") #list in dictionary pizza={ 'crust':'thick' ,'toppings':['mushroom','extra cheese'] } print(f"You ordered a {pizza['crust']}-crust pizza" " with the following toppings:") for topping in pizza['toppings']: print(topping) fav_lang = { 'jen':['python','ruby'] ,'sarah':['c'] ,'edward':['ruby','go'] ,'phil':['python','haskell'] } for name,lang in fav_lang.items(): print(f"\n{name.title()}'s favorite languages are:") for lang in lang: print(f"\t{lang.title()}") #dictionary in a dictionary users = { 'aeinstein': { 'first':'albert' ,'last':'einsein' ,'location':'princeton' } ,'mcurie': { 'first':'marie' ,'last':'curie' ,'location':'paris' } } for username,user_info in users.items(): print(f"\nUsername: {username}") full_name = f"{user_info['first']} {user_info['last']}" location = user_info['location'] print(f"\tFull name: {full_name.title()}") print(f"\tLocation: {location.title()}")
PhilMcDaniel/python-crash-course
10_files_and_exceptions.py
<filename>10_files_and_exceptions.py with open('10_pi_digits.txt') as file_object: contents = file_object.read() print(contents) #reading file like this ends up with extra blank string at end of file print(contents.rstrip()) #read line by line file_name = '10_pi_digits.txt' with open(file_name) as file: for line in file: #need to strip newline characters stored at end of each line print(line.rstrip()) #read file into list of lines with open(file_name) as file: lines = file.readlines() print(lines) for line in lines: print(line.rstrip()) #working with file contents pi_string = '' for line in lines: pi_string += line.strip() print(pi_string) len(pi_string) #large files (1 mil digits) file_name = '10_pi_million_digits.txt' with open(file_name) as file: lines = file.readlines() print(lines) pi_string='' for line in lines: pi_string+=line.strip() len(pi_string) #first 50 chars print(pi_string[:50]) #is your birthday containted in pi birthday = input("enter your birthday, mmddyy: ") if birthday in pi_string: print('your birthday appears in the first million digits of pi!') else: print('sorry your birthday is not in the first million digits of pi') #writing to an empty file #2nd parm(r=read,w=write,append=a,r+=readwrite) read is the default filename ='10_programming.txt' with open(filename,'w') as file: file.write('I love programming') #multiple lines filename ='10_programming.txt' with open(filename,'w') as file: #need to include \n or these will both be on the same line file.write('I love programming\n') file.write('I love creating new games\n') #appending with open(filename,'a') as file: file.write('I love finding meaning in large datasets\n') file.write('I love creating apps that can run in a browser\n') #exceptions print(5/0) try: print(5/0) #catching specific error for divide by 0 except ZeroDivisionError: print('you cant divide by zero') #if try code works, except code does not run. print('give me two numbers and Ill divide them') print('enter q to quit') while True: first_num = input('\nFirst number: ') if first_num == 'q': break second_num = input('Second number: ') if second_num =='q': break #try/catch for divide by zero try: answer = int(first_num)/int(second_num) except ZeroDivisionError: print('you cant divide by zero!') #else runs with success of try block else: print(answer) #handling FileNotFoundError exception filename = 'alice.txt' try: with open(filename,encoding='utf-8') as f: contents = f.read() except FileNotFoundError: print(f'sorry the file {filename} not exist') title = 'Alice In Wonderland' title.split(' ') #wordcount filename = '10_alice.txt' try: with open(filename,'r',encoding='utf-8') as f: contents = f.read() except: print('file does not exist') else: words = contents.split(" ") num_words = len(words) print(f"{filename} has around {num_words} words") #working with multiple files def count_words(filename): """count the approximate number of words in a file.""" try: with open(filename,'r',encoding='utf-8') as f: contents = f.read() except: print('file does not exist') else: words = contents.split(" ") num_words = len(words) print(f"{filename} has around {num_words} words") filename = '10_alice.txt' count_words(filename) filenames = ['10_alice.txt','10_siddhartha.txt','10_moby_dick.txt','10_little_women.txt'] for file in filenames: count_words(file) #storing data #json is a good option for storing data import json numbers = [2,3,5,7,11,13] filename = '10_numbers.json' with open(filename,'w') as f: json.dump(numbers,f) with open(filename,'r') as f: numbers=json.load(f) print(numbers) #saving and reading user-generated data username = input('What is your name?') #store data from input filename = '10_username.json' with open(filename,'w') as f: json.dump(username,f) print(f"We'll remember you when you come back, {username}") #load data that was stored with open(filename) as f: username = json.load(f) print(f'welcome back, {username}') #load stored data if exists, else prompt for value filename = '10_username.json' try: with open(filename,'r') as f: username = json.load(f) except FileNotFoundError: username = input('What is your name?') with open(filename,'w') as f: json.dump(username,f) print(f"we'll remember you when you comeback, {username}") #refactor by puting in function def greet_user(): """greet the user by name""" filename = '10_username.json' try: with open(filename,'r') as f: username = json.load(f) except FileNotFoundError: username = input('What is your name?') with open(filename,'w') as f: json.dump(username,f) print("we'll remember you when you come back, {username}") else: print(f'welcome back {username}') greet_user() def get_stored_username(): """Get stored username, if available""" filename = '10_username.json' try: with open(filename,'r') as f: username = json.load(f) except FileNotFoundError: return None else: return username def greet_user(): """greet the user by name""" username = get_stored_username() if username: print(f"welcome back {username}") else: username = input('Whats your name?') filename = '10_username.json' with open(filename,'w') as f: json.dump(filename,f) print(f"we'll remember you {username}") greet_user() #all pieces inside functions def get_stored_username(): """Get stored username, if available""" filename = '10_username.json' try: with open(filename,'r') as f: username = json.load(f) except FileNotFoundError: return None else: return username def get_new_username(): """prompt for a new username""" username = input("What is your name?") filename = '10_username.json' with open(filename,'w') as f: json.dump(username,f) return username def greet_user(): """greet the user by name""" username = get_stored_username() if username: print(f"welcome back {username}") else: username = get_new_username() print(f"we'll remember you when you come back {username}") greet_user()
PhilMcDaniel/python-crash-course
8_functions.py
#simple example def greet_user(): #docstring for automating documentation. Triple quotes """Display a simple greeting.""" print("Hello!") greet_user() #pass information to function def greet_user(username): #docstring for automating documentation. Triple quotes """Display a simple greeting.""" print(f"Hello, {username.title()}") greet_user('Bob') #positional arguments def describe_pet(animal_type,pet_name): """Diplay information about a pet""" print(f"\nI have a {animal_type}.") print(f"My {animal_type}'s name is {pet_name.title()}") describe_pet('hamster','harry') describe_pet('dog','doge') #this example shows that order of arugments matters describe_pet('harry','hamster') #this example shows the explicit use describe_pet(animal_type='hamster',pet_name='harold') describe_pet(pet_name='doge',animal_type='dogo') #default values def describe_pet(pet_name,animal_type='dog'): """Diplay information about a pet""" print(f"\nI have a {animal_type}.") print(f"My {animal_type}'s name is {pet_name.title()}") describe_pet('Max') describe_pet(pet_name='peter',animal_type='plant') #avoiding argument errors def describe_pet(pet_name,animal_type): """Diplay information about a pet""" print(f"\nI have a {animal_type}.") print(f"My {animal_type}'s name is {pet_name.title()}") describe_pet() #returning simple value def get_formatted_name(first,last): """Return a full name, neatly formatted.""" full_name = f"{first} {last}" return full_name.title() musician = get_formatted_name('jimi','hendrix') print(musician) #optional argument def get_formatted_name(first,last,middle=''): """Return a full name, neatly formatted.""" if middle: full_name = f"{first} {middle} {last}" else: full_name = f"{first} {last}" return full_name.title() musician = get_formatted_name('john','hooker','lee') print(musician) musician = get_formatted_name('jimi','hendrix') print(musician) #returning dictionary def build_person(first_name,last_name,age=None): """Return a dictionary of information about a person.""" person = {'first': first_name,'last':last_name} if age: person['age'] = age return person musician = build_person('jimi','hendrix') print(musician) musician = build_person('jimi','hendrix',age=27) print(musician) #using function with while loop def get_formatted_name(first,last,middle=''): """Return a full name, neatly formatted.""" if middle: full_name = f"{first} {middle} {last}" else: full_name = f"{first} {last}" return full_name.title() while True: print(f"\nPlease tell me your name:") print("(enter 'q' at any time to quit)") f_name = input("First name: ") if f_name =='q': break l_name = input("Last name: ") if l_name == 'q': break formatted_name = get_formatted_name(f_name,l_name) print(f"\nHello, {formatted_name}") #passing a list def greet_users(names): """print a simple greeting to each user in a list""" for name in names: msg = f"Hello {name.title()}" print(msg) usernames = ['hannah','ty','margot'] greet_users(usernames) #modifying a list using a function unprinted_designs = ['phone case','robot pendant','dodecahedron'] completed_models = [] def print_models(unprinted_designs,completed_models): """ Simulate printing each design until none are left. Move to completed_models after printing. """ while unprinted_designs: current_design = unprinted_designs.pop() print(f"Printing model {current_design}") completed_models.append(current_design) def show_completed_models(completed_models): """Show all models that were printed""" for completed_model in completed_models: print(completed_model) print_models(unprinted_designs,completed_models) show_completed_models(completed_models) #preventing a function from modifying a list #[:] makes a copy of the list to send to the function funtion_name(list_name[:]) print_models(unprinted_designs[:],completed_models) #passing arbitrary number of arguments to function #* is the keyword def make_pizza(*toppings): """Summarize what we are about to make""" print("\nMaking a pizza with the following toppings:") for topping in toppings: print(f"- {topping}") make_pizza('pepperoni') make_pizza('sausage','cheese','mushroom','greenpeppers') #mixing positional and arbitrary number of args def make_pizza(size,*toppings): """Summarize what we are about to make""" print(f"\nMaking a {size}-inch pizza with the following toppings:") for topping in toppings: print(f"- {topping}") make_pizza(16,'pepperoni') make_pizza(12,'sausage','cheese','mushroom','greenpeppers') #arbitrary keyword arguments def make_pizza(*toppings): """Print the list of toppings that have been requested.""" print(toppings) #result is a tuple make_pizza('pepperoni') make_pizza('sausage','cheese','mushroom','greenpeppers') def make_pizza(*toppings): """Print the list of toppings that have been requested.""" print("\nMaking pizza with the following toppings:") for topping in toppings: print(f" - {topping}") make_pizza('pepperoni') make_pizza('sausage','cheese','mushroom','greenpeppers') #mixing positional and arbitrary # arbitrary needs to be last param # often see *args as generic name for arbitrary positional arguments def make_pizza(size,*toppings): """summarize the pizza""" print(f"\nMaking a {size}-inch pizza with the following toppings") for topping in toppings: print(f" - {topping}") make_pizza(12,'pepperoni') make_pizza(16,'pepperoni','cheese','green pep') #using arbitrary keyword arguments #**kwargs used for non-specific keyword arguments # double asterisk causes python to create empty dict and fill with arguments passed def build_profile(first,last, **user_info): """Build a dict containing everything we know about user""" user_info['first_name'] = first user_info['last_name'] = last return user_info user_profile = build_profile('albert','einstein',location='princeton',field='physics') print(user_profile) #storing functions in modules #module_name.function_name() import pizza pizza.make_pizza(16,'pepperoni') pizza.make_pizza(16,'mushrooms','green peppers','extra cheese') #import specific function #from module_name import function_name #from module_name import function_name_0,function_name_1,function_name2 #use "as" to alias function #from module_name import function_name as fn from pizza import make_pizza as mp mp(16,'pepperoni') mp(16,'mushrooms','green peppers','extra cheese') #us "as" to alias module #import module_name as mn import pizza as p #import all functions ni a module from pizza import * #from module_name import * #styling functions #functions should have descriptive names #add comment to explain what the function does #don't use space when assigning default values
ParkvilleData/MetaGenePipe
scripts/query_ena.py
import json import pandas as pd import os import urllib.request from bs4 import BeautifulSoup import argparse import sys import logging parser = argparse.ArgumentParser(description='A script to query the European Nucleotide Archive (ENA) website to create a CSV file with information for each read sequence file.') parser.add_argument("csv", help="The input CSV file. It requires a column for the ENA_PROJECT with the project accesion numbers. \ It also expects columns for METAGENOMICS_ANALYSES and METAGENOMICS_SAMPLES if the ENA_PROJECT is missing.") parser.add_argument("cache", help="The path to a directory to cache the downloads of the ENA report files.") parser.add_argument("-o","--output", help="The output CSV file for the individual read files. Each read file is a separate row in the table.") args = parser.parse_args() def human_readable_file_size(size): """ Returns a human readable file size string for a size in bytes. Adapted from https://stackoverflow.com/a/25613067) """ from math import log2 _suffixes = ['bytes', 'KB', 'MB', 'GB', 'TB', 'PB'] # determine binary order in steps of size 10 # (coerce to int, // still returns a float) order = int(log2(size) / 10) if size else 0 # format file size # (.4g results in rounded numbers for exact matches and max 3 decimals, # should never resort to exponent values) return '{:.4g} {}'.format(size / (1 << (order * 10)), _suffixes[order]) def cached_download( url, local_path ): """ Downloads a file if a local file does not already exist. Args: url: The url of the file to download. local_path: The local path of where the file should be. If this file isn't there or the file size is zero then this function downloads it to this location. Raises: Exception: Raises an exception if it cannot download the file. """ if not os.path.isfile( local_path ) or os.path.getsize(local_path) == 0: try: print(f"Downloading {url} to {local_path}") urllib.request.urlretrieve(url, local_path) except: raise Exception(f"Error downloading {url}") if not os.path.isfile( local_path ): raise Exception(f"Error reading {local_path}") def download_ena_report( accession, result_type, cache_dir ): """ Downloads a TSV file report from the European Nucleotide Archive (ENA) website if it is not already cached. If the file already is cached then it is not downloaded again. Args: accession: The accession id for the query. It can be a project accession id or a sample accession id. result_type: The type of report we are seeking (e.g. 'analysis' or 'read_run'). cache_dir: The path to the directory where the downloaded files are stored. Returns: The local path to the ENA file report. Raises: Exception: Raises an exception if it cannot download the file. """ path = f"{cache_dir}/{accession}.{result_type}.tsv" tsv_url = f"https://www.ebi.ac.uk/ena/data/warehouse/filereport?accession={accession}&result={result_type}" cached_download( tsv_url, path ) return path def ena_report_df( accession, result_type, cache_dir ): """ Same as 'download_ena_report' but this function opens the TSV file as a Pandas dataframe. """ path = download_ena_report( accession, result_type, cache_dir ) return pd.read_csv( path, sep='\t' ) df = pd.read_csv(args.csv, encoding="ISO-8859-1") data = [] projects_count = len(df.index) for index,row in df.iterrows(): project_accession = row['ENA_PROJECT'] print(f"Project {index} of {projects_count}: {project_accession}") # Download 'analysis' data for project to get the sample accession ids print(project_accession, "analysis" ) try: analysis_df = ena_report_df( project_accession, "analysis", args.cache ) except: # Sometimes the ENA_PROJECT element in the CSV files for this project for some reason. # If this is the case, we can try the METAGENOMICS_SAMPLES element instead. # However, since the first column (i.e. ENA_PROJECT) is missing, we get the 'METAGENOMICS_SAMPLES' value from the 'METAGENOMICS_ANALYSES' column. project_accession = row['METAGENOMICS_ANALYSES'] try: analysis_df = ena_report_df( project_accession, "analysis", args.cache ) except: logging.warning(f"WARNING: Cannot read row: {row}") continue sample_accessions = analysis_df['sample_accession'].unique() # Occasionally the 'analysls' table for the ENA project accession number is empty. # Usually when this happens, the project accession ID can be used as the 'sample' accession id to download the 'read_run' table if len(sample_accessions) == 0 or str(sample_accessions) == "[nan]": sample_accessions = [project_accession] print('sample_accessions:', sample_accessions) for sample_accession in sample_accessions: read_run_df = ena_report_df( sample_accession, "read_run", args.cache ) print(read_run_df) #assert len(read_run_df.index) > 0 if len(read_run_df.index) == 0: logging.warning(f"WARNING: No reads found for {project_accession}") for _, sample_row in read_run_df.iterrows(): if pd.isna(sample_row)['fastq_ftp']: logging.warning(f"WARNING: No FASTQ files found for {project_accession}") continue fastq_bytes_list = str(sample_row['fastq_bytes']).split(";") fastq_md5_list = str(sample_row['fastq_md5']).split(";") fastq_ftp_list = str(sample_row['fastq_ftp']).split(";") fastq_aspera_list = str(sample_row['fastq_aspera']).split(";") #fastq_galaxy_list = str(sample_row['fastq_galaxy']).split(";") for file_index, (fastq_bytes, fastq_md5, fastq_ftp, fastq_aspera) in enumerate(zip(fastq_bytes_list, fastq_md5_list, fastq_ftp_list, fastq_aspera_list)): #Cast to float first in case there are decimal points in the string for bytes. See https://stackoverflow.com/a/8948303 fastq_bytes = int(float(fastq_bytes)) data.append( [project_accession, sample_row['sample_accession'], file_index, fastq_bytes, human_readable_file_size(fastq_bytes), fastq_md5, fastq_ftp, fastq_aspera] ) ftp_df = pd.DataFrame( data, columns=["project_accession", "sample_accession", "file_index", "fastq_bytes", "fastq_bytes_human_readable", "fastq_md5", "fastq_ftp", "fastq_aspera"]) print(ftp_df) output_path = args.output if not output_path: csv_filename, _ = os.path.splitext(args.csv) output_path = csv_filename + "-FASTQ.csv" ftp_df.to_csv( output_path ) total_bytes = ftp_df['fastq_bytes'].sum() print(human_readable_file_size(total_bytes))
ParkvilleData/MetaGenePipe
scripts/xml_parser-v4.py
import xml.etree.ElementTree as ET import sys import re import argparse import pandas as pd import shelve parser = argparse.ArgumentParser() parser.add_argument('xmls', help="The XML files to search for the hits.", nargs='+') parser.add_argument('--outfile', help="The name of the output file. Default: OTU.tsv", default="OTU.tsv") args = parser.parse_args() tax = shelve.open('/data/gpfs/projects/punim0639/databases/metaGenePipe/taxon/taxonomic_lineages.db') df = pd.DataFrame() sample_names = [] for xml in args.xmls: sample_name = xml.split("/")[-1].split(".")[0] sample_names.append(sample_name) root = ET.parse(xml).getroot() for hit in root.findall("./BlastOutput_iterations/Iteration/Iteration_hits/Hit"): hit_text = hit.find("Hit_id").text code = hit_text.split(":")[0] df = df.append( {'code':code, "sample_name":sample_name}, ignore_index=True) print(f"Writing to {args.outfile}") with open(args.outfile, "w") as f: columns = ["Name", "Kegg Code", "Lineage"] + sample_names print("\t".join(columns), file=f) codes = sorted(df.code.unique()) for code in codes: if code in tax.keys(): lineage = tax[code] name = lineage.split(";")[-1] name = name[ len(code)+2:].strip() else: lineage = "unknown" name = "Unknown" f.write( "\t".join( [name, code, lineage] ) ) for sample_name in sample_names: filtered = df[ (df.sample_name == sample_name) & (df.code == code) ] count = len(filtered.index) f.write( f"\t{count}" ) f.write("\n")
ParkvilleData/MetaGenePipe
scripts/inputArgMaker.v.1.0.3.py
<reponame>ParkvilleData/MetaGenePipe<gh_stars>0 # -*- coding: utf-8 -*- """ inputMaker.py 05/03/2020 - <NAME>, <NAME> Description: This script will take in a number of parameters and will create an input file that can be used for the HPGAP WDL workflow Example: $ python ./scripts/inputMaker.py -f fasta -d /data/cephfs/punim1165/bshaban/hpgap_dev/fastqFiles/ -o input.txt -p true -pl PL -ph 33 usage: inputArgMaker.py [-h] -o OUTPUTFILE [-f FORMAT] -d DIRECTORY -p PAIREDEND -ph PHRED -pl PL [-debug] Todo: * You have to also use ``sphinx.ext.todo`` extension * Throw error if no files in directory or if they are not gzipped or fastq * check size order in PE mode """ import sys import glob import os import re import pprint import textwrap import argparse import gzip from itertools import islice from collections import OrderedDict def main(): parser = argparse.ArgumentParser() parser.add_argument('-o', '--outputfile', type=str, required=True, help='You must add a name for the output file') parser.add_argument('-f', '--format', type=str, help='What format are your files?') parser.add_argument('-d', '--directory', type=str, required=True, help='You need to add a path to the sample files') parser.add_argument('-p', '--pairedend', required=False, type=str, help='Are your samples paired end? YES/NO') parser.add_argument('-ph', '--phred', required=False, type=str, help='Phred score type i.e. 33?') parser.add_argument('-ml', '--minlength', required=True, type=str, help='Minimum length of reads after trimming') parser.add_argument('-pl', '--platform', required=True, type=str, help='PL flag?') parser.add_argument('-lb', '--library', required=True, type=str, help='BAM Header LB') parser.add_argument('-sm', '--sample', required=True, type=str, help='BAM Header SM') parser.add_argument('--debug', action="store_true", help='Do you want to turn on Debug Mode?') args = parser.parse_args() #if debug is set to true run if args.debug: printArgvs(args, sys) #return file list and size from read files function fileListRaw = readFiles_glob(args.directory) if args.debug: print("Raw File List") input_file = open(args.outputfile, 'w') #if paired end send file list off for PE processing # better way of doing this? # replace with a regular expression to pattern match YES if args.pairedend in ('True', 'true', 'TRUE', 'Yes', 'yes', 'y', 'Y', 't', 'T'): print("You are running paired end version\n") fileList = paired_end_files(fileListRaw, args) pairedEndKeys = return_list_base_names(fileListRaw, True) for keys in pairedEndKeys: input_file.write(keys + "\t" + fileList[keys]['flag'] + '\t' + args.minlength + '\t' + args.phred + '\t' + args.platform + '\t' + fileList[keys]['size'] + '\t' + args.library + '\t' + fileList[keys]['id'] + '\t' + args.sample + '\t' + fileList[keys]['id'] + '\t' + fileList[keys]['forward'] + '\t' + fileList[keys]['reverse'] + '\n') else: fileList=fileListRaw for files in fileList: sample, size, identity = str(files[1]), str(files[0]), str(files[2]) baseName = return_sample_name(sample) input_file.write(baseName + "\t" + "SE" + '\t' + args.minlength + '\t' + args.phred + '\t' + args.platform + '\t' + size + '\t' + args.library + '\t' + identity + '\t' + args.sample + '\t' + identity + '\t' + sample + '\n') input_file.close() print("Creation of input file complete!") if args.debug: printDictionary(fileList) ######################### Functions ################################# def paired_end_files(fileList, args): """ paired_end_files Is executed if the paired end parameter is set to true Reads in folder, takes basename of files as sample name Args: fileList (tuple): The first first parameter: A list of files debug: Do you want to debug or not? Returns: Dictionary: Contains SampleName, file size and forwrd and reverse reads """ #remove paired ending of sample name and remove non-unique uniqueSampleNames = return_list_base_names(fileList, True) #go through fileList and if match append to dictionary sampleDictionary = {} for uniqueSamples in uniqueSampleNames: #intiate keys sampleDictionary[uniqueSamples] = {} for fileLine in fileList: if uniqueSamples in fileLine[1]: if 'r1' in fileLine[1]: sampleDictionary[uniqueSamples]['forward'], sampleDictionary[uniqueSamples]['size'], sampleDictionary[uniqueSamples]['flag'], sampleDictionary[uniqueSamples]['id'] = fileLine[1], str(fileLine[0]), "PE", str(fileLine[2]) elif 'r2' in fileLine[1]: sampleDictionary[uniqueSamples]['reverse'] = fileLine[1] #sort by file size result = OrderedDict(sorted(sampleDictionary.items(), key=lambda i: int(i[1]['size']))) return result def return_list_base_names(fileList, uniq): """ return_list_of_base_names Returns a list of base names from raw list of files Args: fileList: raw list of files and paths uniq: If you want the files to be unique Returns: string: returns list of basenames without _r1 or _r2 """ sampleNames = [] for lines in fileList: tempString = return_sample_name(str(lines[1])) sampleNames.append(tempString) samples = [] for s in sampleNames: samples.append(s.split('_')[0]) if uniq: result = list(dict.fromkeys(samples)) else: result = uniqueSampleNames return result def return_sample_name(path): """ return_sample_name Returns sample names from a path Args: param1 (string): Path of the sample file Returns: string: returns the sample name? with or without _r1 or _r2 """ basename = os.path.basename(path) samplename = basename.split('.') return samplename[0] def readFiles_glob(directory): """ readFiles_glob Returns list of files Args: param1 (string): Path of the directory which contains the fasta files Returns: list: returns list of files """ try: os.path.isdir(directory) pairs = [] types = ('*.gz', '*.fastq') for fs in types: for name in sorted(glob.glob(os.path.join(directory + fs ))): file_size = os.path.getsize(name) #get id from first line in forward read if 'gz' in name: with gzip.open(name, 'rb') as f: for l in islice(f, 0, None): try: first_line = re.search("@(.+?)C001", "l {}".format(l)).group(1) f.close() except AttributeError: print("not found\n") break elif 'fastq' in name: with open(name, 'r') as inf: fline = inf.readline() first_line = re.search("@(.+?)C001", "fline {}".format(fline)).group(1) pairs.append((file_size, name, first_line)) #sort files by size then reverse - probably better way to do this pairs.sort(key=lambda s: s[0], reverse=True) return pairs except: print(directory + ' does not exist\n') def printDictionary(dictionary): """ print Dictionary Prints contents of dictionary for debug purposes Args: param1 (Dictionary): Dictionary of questionable content Returns: NA: print out dictionary contents """ print("\nDictionary contents below") pp = pprint.PrettyPrinter(indent=4) pp.pprint(dictionary) def printArgvs(args, sys): """ printArgvs Prints out arguments from command line i.e. get opts Args: args (list): arguments from command line sys (object?): options passed in from command line Returns: str: Prints the number of arguments and the arguments themselves """ # ... for testing of get options print("\nDebugging info START\n") print('Number of arguments:', len(sys.argv), 'arguments.') print('Argument List:', str(sys.argv)) print('Opts string:', str(args)) print("\nDebugging info END\n") ###### Main call ########## if __name__ == "__main__": main()
ParkvilleData/MetaGenePipe
setup.py
############### download metagenepipe databases ###################### # -*- coding: utf-8 -*- """ download_databases.py Description: Download hmmer, blast and swissprot databases Requirements: Args: packages: os sys pathlib usage: python download_databases.py --blast mito --hmmer_kegg prokaryote --swissprot y --singularity y/n Todo: Author: <NAME> Date: 27/04/2022 """ import sys import os import argparse from pathlib import Path import urllib.request as urllib import gzip import shutil import ftplib import glob from datetime import datetime def main(): """ Main(): Parses command line parameters and calls download functions function Parameters ____________ None Returns ____________ downloads blast, koalafam or swissprot database """ parser = argparse.ArgumentParser() parser.add_argument('-b', '--blast', type=str, help='Download blast nt database: options: nr, nt, pdbaa') parser.add_argument('-k', '--hmmer_kegg', type=str, help='Download KoalaFam hmmer profiles') parser.add_argument('-s', '--sprott', type=str, help='Download Swissprot db and convert to diamond db') parser.add_argument('-c', '--cromwell', type=str, help='Download cromwell jar') parser.add_argument('-i', '--singularity', type=str, help='Download Singularity container') args = parser.parse_args() #Download singularity container ############################### try: if args.singularity: print("Ensure singularity is installed and in your path") os.system("singularity pull --arch amd64 library://bshaban/metagenepipe/metagenepipe.simg:v2") args.singularity = glob.glob('*.sif')[0] print(args.singularity) except Exception as err: print(err) #Download cromwell ############################### try: if args.cromwell: print("Download cromwell") os.system("LOCATION=$(curl -s https://api.github.com/repos/broadinstitute/cromwell/releases/latest | grep \"browser_download_url\" | grep \"cromwell-\" | awk '{ print $2 }' | sed 's/,$//' | sed 's/\"//g' ) ; curl -L -o cromwell-latest.jar $LOCATION") except Exception as err: print(err) ### download blast database ########################### try: if args.blast: download_blast(args.blast, args.singularity) except Exception as err: print(err) ### download koala_fam ###################### try: if args.hmmer_kegg: download_koalafam(args.singularity, args.hmmer_kegg) except Exception as err: print(err) ### download swissprot database ############################### try: if args.sprott: download_swissprot(args.singularity) except Exception as err: print(err) """ download_blast(): Downloads blast database Parameters ____________ singularity: location of singularity file blast: name of blast database to download database to download Actions ___________ downloads blast database """ def download_blast(blast, singularity): print("downloading blast database") FTP_HOST = "ftp.ncbi.nlm.nih.gov" FTP_USER = "anonymous" ftp = ftplib.FTP(FTP_HOST, FTP_USER) ftp.encoding = "utf-8" ftp.cwd('blast/db') print("{:20} {}".format("File Name", "File Size")) for file_name in ftp.nlst(): if file_name.startswith(blast) and file_name.endswith('.gz'): print("https://" + FTP_HOST + "/blast/db/" + file_name) download_file("https://" + FTP_HOST + "/blast/db/" + file_name) ## Create directory Path("blast").mkdir(parents=True, exist_ok=True) ## move file to kegg directory shutil.move(file_name, "blast/"+file_name) ## unzip file os.system("tar -xvf ./blast/* -C ./blast/") """ download_koalafam(): downloads koalafam profiles and merges according to prokaryotes/ eukaryotes Parameters ____________ singularity: Location of singularity container karyote: Either eukaryote or prokaryote Returns ____________ merged hmmer profiles in kegg directory """ def download_koalafam(singularity, karyote): print("download KoalaFam hmmer profiles") print("8 Gb of Storage required") koalafam_download = "https://www.genome.jp/ftp/db/kofam/profiles.tar.gz" pwd = os.getcwd() existing_file = os.path.exists(pwd + "/profiles.tar.gz") ## if file exsts switch if existing_file: print("File already exists") zipped_koalafam = "profiles.tar.gz" else: zipped_koalafam = download_file(koalafam_download) ## unzipfile zip_command = "tar -xvf " + zipped_koalafam os.system(zip_command) ## remove zipped file print("Removing zipped file") os.remove("profiles.tar.gz") ## sed start of hal file print("update hal file to correct location of hmmer profiles") os.system("sed 's/K/profiles\/K/' " + "profiles/" + karyote + ".hal > profiles/prok.hal") ##cat hmmer files together print("Merging " + str(karyote) + ".hal hmmer profiles") os.system("xargs cat < profiles/prok.hal > kegg/kegg_all.hmm") """ download_swissprot(): downloads swissprot database and creates diamond database Parameters ____________ singularity: location of singularity image Returns ____________ Swissprot database in diamond format """ def download_swissprot(singularity): print("downloading swissprot database") swissprot_location = "ftp://ftp.ebi.ac.uk/pub/databases/uniprot/knowledgebase/uniprot_sprot.fasta.gz" ## download file zipped_swiss = download_file(swissprot_location) ## unzipfile with gzip.open(zipped_swiss, 'rb') as f_in: with open("uniprot_sprot.fasta", 'wb') as f_out: shutil.copyfileobj(f_in, f_out) ## remove zipped file print("Removing zipped file") os.remove(zipped_swiss) ## use singularity to create diamond database singularity_string = "singularity run -B $PWD:$PWD " + singularity + " diamond makedb --in uniprot_sprot.fasta -d swissprot" os.system(singularity_string) ## remove fasta file os.remove("uniprot_sprot.fasta") ## move file to kegg directory shutil.move("swissprot.dmnd", "kegg/swissprot.dmnd") """ download_file(): Downloads file and provides status bar Parameters ____________ url: url for file to download Returns ____________ Downloaded file """ def download_file(url): file_name = url.split('/')[-1] u = urllib.urlopen(url) f = open(file_name, 'wb') meta = u.info() ## Koalafam doesn't have the file size in the file header ## Figure out a better way to do this if u.headers['Content-length']: file_size = int(u.headers['Content-length']) print("Downloading: %s Bytes: %s" % (file_name, file_size)) else: file_size = int("1395864371") file_size_dl = 0 block_sz = 8192 while True: buffer = u.read(block_sz) if not buffer: break file_size_dl += len(buffer) f.write(buffer) status = r"%10d [%3.2f%%]" % (file_size_dl, file_size_dl * 100. / file_size) status = status + chr(8)*(len(status)+1) print(status) f.close() return(file_name) # some utility functions that we gonna need def get_size_format(n, suffix="B"): # converts bytes to scaled format (e.g KB, MB, etc.) for unit in ["", "K", "M", "G", "T", "P"]: if n < 1024: return f"{n:.2f}{unit}{suffix}" n /= 1024 def get_datetime_format(date_time): # convert to datetime object date_time = datetime.strptime(date_time, "%Y%m%d%H%M%S") # convert to human readable date time string return date_time.strftime("%Y/%m/%d %H:%M:%S") ###### Main call ########## if __name__ == "__main__": main()
ParkvilleData/MetaGenePipe
scripts/xml_parser-v3.py
<reponame>ParkvilleData/MetaGenePipe<filename>scripts/xml_parser-v3.py import xml.etree.ElementTree as ET import sys import json import re import argparse import pandas as pd def search( node, query, parent_lineage=[] ): code = node["name"].split()[0] # Append this node to the lineage my_linage = list(parent_lineage) + [node["name"]] if code == query: return my_linage # if it doesn't have the code, then search children if "children" in node: for child in node["children"]: result = search( child, query, my_linage ) if result != False: return result # if no children then return false return False parser = argparse.ArgumentParser() parser.add_argument('lineage', help="The KEGG linage file.") parser.add_argument('xmls', help="The XML files to search for the hits.", nargs='+') parser.add_argument('--outfile', help="The name of the output file. Default: OTU.tsv", default="OTU.tsv") args = parser.parse_args() with open(args.lineage) as f: tax = json.load(f) df = pd.DataFrame() sample_names = [] for xml in args.xmls: sample_name = xml.split(".")[0] sample_names.append(sample_name) root = ET.parse(xml).getroot() for hit in root.findall("./BlastOutput_iterations/Iteration/Iteration_hits/Hit"): hit_text = hit.find("Hit_id").text code = hit_text.split(":")[0] df = df.append( {'code':code, "sample_name":sample_name}, ignore_index=True) print(f"Writing to {args.outfile}") with open(args.outfile, "w") as f: columns = ["Name", "Kegg Code", "Lineage"] + sample_names print("\t".join(columns), file=f) codes = sorted(df.code.unique()) for code in codes: lineage = search( tax, code ) lineage.pop(0) # Get rid of root lineage_text = "; ".join(lineage) name = lineage[-1] name = name[ len(code):].strip() f.write( "\t".join( [name, code, lineage_text] ) ) for sample_name in sample_names: filtered = df[ (df.sample_name == sample_name) & (df.code == code) ] count = len(filtered.index) f.write( f"\t{count}" ) f.write("\n")
ParkvilleData/MetaGenePipe
scripts/inputMaker.py
# -*- coding: utf-8 -*- """ inputMaker.py 05/03/2020 - <NAME>, <NAME> Description: This script will take in a number of parameters and will create an input file that can be used for the HPGAP WDL workflow Example: $ python ./scripts/inputMaker.py -f fasta -d /data/cephfs/punim1165/bshaban/hpgap_dev/fastqFiles/ -o input.txt -p true Help: -h|--help: Prints help message -o|--outputfile: Name of the output (input) file -f|--format: Format of sample files e.g. fasta -p|--pairedend: Paired end samples e.g. true or false -d|--directory: Directory of sample files -b|--debug: Runs debug functions Todo: * Get paired end option working * Add metadata from the data.yml * add helpful help message i.e usage * You have to also use ``sphinx.ext.todo`` extension * Convert to use argparse instead of getopts """ import getopt, sys import glob import os import re import pprint import textwrap def main(): try: opts, args = getopt.getopt(sys.argv[1:], "ho:f:p:d:b:v", ["help", "outputfile=", "format=", "pairedend=", "directory=", "debug="]) except getopt.GetoptError as err: # print help information and exit: print("******************************************************************************************") usage() print("******************************************************************************************\n") print(err) # will print something like "option -a not recognized" print("\n") sys.exit(2) #sets default parameters debug = True outputfile = False inputFormat = False pairedend = False directory = False optsArray = [outputfile, inputFormat, pairedend, directory] if len(opts) !=0: for o, a in opts: if o == "-v": verbose = True elif o in ("-h", "--help"): usage() sys.exit() elif o in ("-o", "--outputfile"): outputfile = a elif o in ("-f", "--format"): inputFormat = a elif o in ("-p", "--pairedend"): pairedend = a elif o in ("-d", "--directory"): directory = a elif o in ("-b", "--debug"): debug = a else: assert False, "unhandled option" #if debug is set to true run verbose if debug: commandLine = sys.argv printArgvs(commandLine, opts) #return file list and size from read files function fileListRaw = readFiles_glob(directory) #if paired end send file list off for PE processing if pairedend: fileList = paired_end_files(fileListRaw, debug) else: fileList=convert(fileListRaw) if debug: printDictionary(fileList) #open file for printing input_file = open(outputfile, 'w') #print files to file in order of large to small for files in fileList: writing_string = str(files[1]) sampleName = return_sample_name(writing_string) input_file.write(sampleName + '\t' + writing_string + '\n') input_file.close() else: usage() #not used def isEmpty(variable, option): try: if variable != None: return variable else: print(option + "Is empty") usage() sys.exit(2) except ValueError: pass def Convert(lst): res_dct = {lst[i]: lst[i + 1] for i in range(0, len(lst), 2)} return res_dct def paired_end_files(fileList, debug): """ paired_end_files Is executed if the paired end parameter is set to true Reads in folder, takes basename of files as sample name Args: fileList (tuple): The first first parameter: A list of files debug: Do you want to debug or not? Returns: Dictionary: Contains SampleName, file size and forwrd and reverse reads """ sampleNameList = [] for lines in fileList: tempString = return_sample_name(str(lines[1])) sampleNameList.append(tempString) #remove paired ending of sample name and remove non-unique uniqueSampleNames = [] for sampleNames in sampleNameList: uniqueSampleNames.append(sampleNames.split('_')[0]) #creates a dictionary adding sample names #creates list with unique sample names uniqueSampleNames = list(dict.fromkeys(uniqueSampleNames)) print("The number of unique sample names are " + str(len(uniqueSampleNames))) #go through fileList and if match append to dictionary sampleDictionary = {} for uniqueSamples in uniqueSampleNames: #intiate keys #print(uniqueSamples) sampleDictionary[uniqueSamples] = {} for fileLine in fileList: if uniqueSamples in fileLine[1]: if 'r1' in fileLine[1]: #print(uniqueSamples + '\t' + fileLine[1] + '\t' + str(fileLine[0])) sampleDictionary[uniqueSamples]['forward'] = fileLine[1] sampleDictionary[uniqueSamples]['size'] = str(fileLine[0]) elif 'r2' in fileLine[1]: #print(uniqueSamples + '\t' + fileLine[1] + '\t' + str(fileLine[0])) sampleDictionary[uniqueSamples]['reverse'] = fileLine[1] sampleDictionary[uniqueSamples]['size'] = str(fileLine[0]) if debug: printDictionary(sampleDictionary) return sampleDictionary def return_sample_name(path): """ return_sample_name Returns sample names from a path Args: param1 (string): Path of the sample file Returns: string: returns the sample name? with or without _r1 or _r2 """ basename = os.path.basename(path) samplename = basename.split('.') return samplename[0] def get_file_size(file_path): """ get_file_size Returns file size Args: param1 (string): Path of the sample file Returns: int: returns the size of the file in bytes """ size = os.path.getsize(file_path) return size def readFiles_glob(directory): """ readFiles_glob Returns list of files Args: param1 (string): Path of the directory which contains the fasta files Returns: list: returns list of files """ if os.path.isdir(directory): pairs = [] for name in sorted(glob.glob(os.path.join(directory + '*.gz'))): file_size = get_file_size(name) pairs.append((file_size, name)) #sort files by size then reverse - probably better way to do this pairs.sort(key=lambda s: s[0]) pairs.reverse() return pairs else: print(directory + ' does not exist\n') def printDictionary(dictionary): """ print Dictionary Prints contents of dictionary for debug purposes Args: param1 (Dictionary): Dictionary of questionable content Returns: NA: print out dictionary contents """ print("\nDictionary contents below") for key in dictionary: print (key) for value in dictionary[key]: print(key,':',dictionary[key]) def printArgvs(commandLine, opts): """ printArgvs Prints out arguments from command line i.e. get opts Args: sys.argv (list): arguments from command line opts (object?): options passed in from command line Returns: str: Prints the number of arguments and the arguments themselves """ # ... for testing of get options print("\nDebugging info START\n") print('Number of arguments:', len(commandLine), 'arguments.') print('Argument List:', str(sys.argv)) print('Opts string:', str(opts)) print("\nDebugging info END\n") def usage(): print textwrap.dedent("""Description: This script will take in a number of parameters and will create an input file that can be used for the HPGAP WDL workflow Example: $ python ./scripts/inputMaker.py -f fasta -d /data/cephfs/punim1165/bshaban/hpgap_dev/fastqFiles/ -o input.txt -p true Help: -h|--help: Prints help message -o|--outputfile: Name of the output (input) file -f|--format: Format of sample files e.g. fasta -p|--pairedend: Paired end samples e.g. true or false -d|--directory: Directory of sample files -b|--debug: Runs debug functions""") ###### Main call ########## if __name__ == "__main__": main()
ParkvilleData/MetaGenePipe
scripts/rerunTaxon.py
import paramiko import pysftp from pathlib import Path from base64 import decodebytes from .mediaflux import get_asset_content from .mma import get_upload_success from .paths import get_output_dir_name from .mfclient import mfclient import xml_parser-v4 parser = argparse.ArgumentParser() parser.add_argument('xmls', help="The XML files to search for the hits.", nargs='+') parser.add_argument('--outfile', help="The name of the output file. Default: OTU.tsv", default="OTU.tsv") args = parser.parse_args() def taxon( destination, mma_token, mf_config ): """ Downloads the files necessary for the taxonomic classification task, reruns the task and reuploads back to Mediaflux """ download_taxon() rerun_taxon() upload_taxon() def download_taxon(destination, study_accession, mma_token, mf_config): upload_success = get_upload_success( mma_token ) if type(destination) == str: destination = Path(destination) keydata = b"""<KEY>"" key = paramiko.RSAKey(data=decodebytes(keydata)) cnopts = pysftp.CnOpts() cnopts.hostkeys.add('mediaflux.researchsoftware.unimelb.edu.au', 'ssh-rsa', key) username = "unimelb:"+mf_config['user'] with pysftp.Connection('mediaflux.researchsoftware.unimelb.edu.au', username=username, password=mf_config['password'], cnopts=cnopts) as sftp: for status in upload_success: study_accession = status['study'] batch = status['batch_index'] print(study_accession, batch) local_path = destination/f"{study_accession}_{batch}" local_path = local_path.resolve() # Check if folder already exists if local_path.is_dir(): continue local_path.mkdir(exist_ok=True, parents=True) output_dir_name = get_output_dir_name(study_accession, batch) remote_path = f'/Volumes/proj-6300_metagenomics_processed_verbruggenmdap-1128.4.295/metaGenPipe_outputs/{output_dir_name}/optimisation' print(f"Downloading {remote_path} to {local_path}") with sftp.cd(remote_path): sftp.get_r(".", str(local_path)) def rerun_taxon(xml_parser, diamondXML, destination): optim_directory = destination/"optimisation" singularity = "/data/projects/punim1293/singularity/metaGenPipe.20201119.simg" script = f"python3 {xml_parser} --outfile OTU.brite.tsv {diamondXML}" os.system(f'sbatch -J "rerunTaxon" -D {destination} -o {destination} -e ${err} -t 5000 -p "adhoc,snowy,physical" -q adhoc --account=punim1293 -n 1 -c 1 --mem=61440 \ --wrap "module load singularity/3.5.3; /usr/bin/time -v --output {optim_directory}/cromwell_xxxxxxxx_OTUtaxon.txt singularity run -B {singularity} /bin/bash ${script}; sh ${head_directory}/scripts/opt_shell.sh ${script} ${job_name} ${optim_directory} def upload_taxon():
ParkvilleData/MetaGenePipe
scripts/download_ena.py
<reponame>ParkvilleData/MetaGenePipe #!/usr/bin/env python3 import pandas as pd import argparse from pathlib import Path import hashlib import os import numpy as np import multiprocessing def str2bool(v): """ Converts a string to a boolean value for parsing in argparse. From https://stackoverflow.com/a/43357954 """ if isinstance(v, bool): return v if v.lower() in ('yes', 'true', 't', 'y', '1'): return True elif v.lower() in ('no', 'false', 'f', 'n', '0'): return False else: raise argparse.ArgumentTypeError('Boolean value expected.') parser = argparse.ArgumentParser(description="Downloads in parallel the read files in a CSV file using Aspear Connect.") parser.add_argument("csv", help="The CSV file for the read files (created through query_ena.py). \ It expects fields named: project_accession, sample_accession, file_index, fastq_bytes, fastq_bytes_human_readable, and fastq_aspera.") parser.add_argument("key", help="The SSH key to use with Aspera Connect.") parser.add_argument("--validate", type=str2bool, nargs='?', const=True, default=True, help="If true, then the script validates the MD5 checksum of the file if it is already downloaded. If there is a mismatch then the file is downloaded again.") args = parser.parse_args() def process_row(row): aspera = Path(row['fastq_aspera']) print(f"Processing: {row['project_accession']}, {row['sample_accession']}, {row['file_index']}, {aspera}") local_dir = Path(f"{row['project_accession']}/{row['sample_accession']}/{row['file_index']}") local_dir.mkdir(parents=True, exist_ok=True) local_path = local_dir / aspera.name # Check to see if the file need to be downloaded if local_path.is_file(): print(f"{local_path} already downloaded.") if args.validate: md5 = hashlib.md5(local_path).hexdigest() if md5 == row['fastq_md5']: return else: print("MD5 checksum is incorrect. Downloading again.") else: return print(f"Downloading {aspera} ({row['fastq_bytes_human_readable']})") cmd = f"ascp -QT -l 1000m -P33001 -i {args.key} era-fasp@{aspera} {local_path}" print(cmd) os.system(cmd) def process_dataframe(df): for index, row in df.iterrows(): process_row(row) df = pd.read_csv(args.csv) n_cores = multiprocessing.cpu_count() # Arrange dataframe into even partitions df = df.sort_values(by=['fastq_bytes']).reset_index(drop=True) df['partition'] = df.index % n_cores df = df.sort_values(by=['partition']).reset_index(drop=True) df_split = np.array_split(df, n_cores) # Process on multiple processors pool = multiprocessing.Pool(n_cores) pool.map(process_dataframe, df_split) # This is a hack to just run the process_dataframe in parallel on all the partitions.
ParkvilleData/MetaGenePipe
scripts/benchmark_assembly.py
<filename>scripts/benchmark_assembly.py<gh_stars>0 #!/usr/bin/env python3 import subprocess import itertools import os assemblers = { 'megahit': "../MEGAHIT-1.2.9-Linux-x86_64-static/bin/megahit", 'metaspades': "../SPAdes-3.14.1-Linux/bin/metaspades.py", 'idba': "idba_ud" } def run_benchmark(assembler, reads, threads): print("Running " + assembler + ": " + str(reads) + " reads, " + str(threads) + " threads...") if assembler != 'idba': output_detail = subprocess.run(["/usr/bin/time", "-v", assemblers[assembler], "-1", str(reads) + "K/R1.fastq", "-2", str(reads) + "K/R2.fastq", "-o", str(reads) + "K/" + assembler + "_" + str(threads) + "t", "-t", str(threads)], capture_output=True) elif assembler == 'idba': output_detail = subprocess.run(["/usr/bin/time", "-v", assemblers[assembler], "-r", str(reads) + "K/merged.fa", "-o", str(reads) + "K/" + assembler + "_" + str(threads) + "t", "--num_threads", str(threads)], capture_output=True) time_detail = 'assembler: ' + assembler + ': reads: ' + str(reads) + ': threads: ' + str(threads) + ': ' + output_detail.stderr.decode().split('ommand being ')[-1].replace('\n\t',': ') return time_detail all_params = list(itertools.product([24, 20, 16, 12, 8, 4, 2, 1], [250, 500, 1000, 2000, 5000, 10000], assemblers)) for (threads, reads, assembler) in all_params: filename = "./output/" + assembler + "_" + str(reads) + "K_" + str(threads) + "t.txt" # if the output file already exists, then continue if os.path.isfile(filename): print("File " + filename + " already exists, skipping") else: time_detail = run_benchmark(assembler, reads, threads) text_file = open(filename, "w") text_file.write(time_detail) text_file.close()
ParkvilleData/MetaGenePipe
scripts/megaGraph.py
import sys import glob import os import argparse import fnmatch def main(): parser = argparse.ArgumentParser() parser.add_argument('-d', '--directory', type=str, required=True, help='The directory containing megahit contig fasta files') parser.add_argument('-s', '--sampleName', type=str, help='Sample name for output') args = parser.parse_args() os.chdir(args.directory) #print(args.directory) files = glob.glob("k*[0-9].contigs.fa") #print(files) files.sort(key=lambda f: os.stat(f).st_size, reverse=False) for f in (files): #print(f) kmerSplit = f.split(".")[0] old_file_name = f new_file_name = args.sampleName + ".contigs." + kmerSplit + ".fa" os.rename(f, new_file_name) #redo glob after file rename files = glob.glob("*.contigs.*.fa") #find largest file size for file in (files): #print(file + " " + str(os.stat(file).st_size)) size=os.stat(file).st_size if(os.stat(file).st_size != 0): #print(file + " " + str(os.stat(file).st_size)) kmer = file.split(".")[2].replace("k", "") fastg = args.sampleName + '.' + kmer + '.fastg' fastg.replace(".contigs", "").replace(".final", "") os.system('megahit_core contig2fastg ' + kmer + ' ' + file + ' > ' + fastg) print(kmer) break ###### Main call ########## if __name__ == "__main__": main()
ParkvilleData/MetaGenePipe
scripts/taxonfile.py
<gh_stars>0 import shelve import json with open('/data/gpfs/projects/punim0639/databases/metaGenePipe/taxon/br08610.json') as f: tax = json.load(f) def get_lineage(tree, current = []): if "children" in tree: for child in tree["children"]: if isinstance(child, dict): yield from get_lineage(child, current+[tree["name"]]) elif isinstance(child, list): for i in child: yield from get_lineage(i, current+[tree["name"]]) else: code = tree["name"].split()[0] yield [code]+current+[tree["name"]] eukaryota = list(get_lineage(tax['children'][0])) bacteria = list(get_lineage(tax['children'][1])) archaea = list(get_lineage(tax['children'][2])) my_dict = {lineage[0]: "; ".join(lineage[1:]) for lineage in eukaryota+bacteria+archaea} myShelvedDict = shelve.open("/data/gpfs/projects/punim0639/databases/metaGenePipe/taxon/taxonomic_lineages.db") myShelvedDict.update(my_dict)
ParkvilleData/MetaGenePipe
scripts/hmm_parser-v1.py
#!/usr/bin/env python from collections import defaultdict import pandas as pd import numpy as np import sys import pprint from Bio import SearchIO import argparse def hmmer_to_df(hmmTbl, only_top_hit=False): """ Takes a table from HMMER 3 and converts it to a Pandas Dataframe Adapted from https://stackoverflow.com/a/62021471 """ attribs = [ 'id', 'evalue'] # can add in more columns hits = defaultdict(list) prev_hit_id = None ## open hmmTbl and extract hits with open(hmmTbl) as handle: for queryresult in SearchIO.parse(handle, 'hmmer3-tab'): for hit in queryresult.hits: # Only record the top hit if only_top_hit and hit.id == prev_hit_id: continue for attrib in attribs: hits[attrib].append(getattr(hit, attrib)) hits['KO'].append(queryresult.id) prev_hit_id = hit.id return pd.DataFrame.from_dict(hits) def main(): parser = argparse.ArgumentParser() parser.add_argument('brite', type=argparse.FileType('r'), help="The brite hierachy level file.") parser.add_argument('hmm_tbls', nargs='+', help='A list of tables from HMMER 3.') parser.add_argument('--consistent-pathways', action='store_true', help='Outputs all the pathways consistently across each output file even if they do not exist at that level.') parser.add_argument('--outprefix', help="The samplename prefix") args = parser.parse_args() levels = ["Level1", "Level2", "Level3"] # load brite database brite_df = pd.read_csv(args.brite, sep='\t') # Loop over the HMMER tables counts_df = [] for hmm_tbl in args.hmm_tbls: hmmer_df = hmmer_to_df( hmm_tbl, only_top_hit=False ) # Select ids for rows with minimum e value idx_evalue_min = hmmer_df.groupby('id')['evalue'].idxmin() # Filter hmmer dataframe with these indexes hmmer_min_e_df = hmmer_df.loc[idx_evalue_min] brite_filtered = brite_df[brite_df['KO'].isin(hmmer_min_e_df.KO)] for level in levels: my_counts_df = brite_filtered[level].value_counts().rename_axis('pathway').reset_index(name='counts') my_counts_df['level'] = level my_counts_df['hmm_tbl'] = hmm_tbl # Store in single dataframe counts_df = my_counts_df if len(counts_df) == 0 else pd.concat( [counts_df, my_counts_df ], ignore_index=True) # Output the counts into text files for level in levels: output_filepath = f"{level}.{args.outprefix}.counts.tsv" print(f"Writing to file {output_filepath}") with open(output_filepath, 'w') as f: # Get pathways for this level so that we can have consistency in the output files even when the counts are zero df_for_pathways = counts_df if args.consistent_pathways else counts_df[ counts_df.level == level ] pathways_for_level = sorted(df_for_pathways.pathway.unique()) headers = ["Pathway"] + args.hmm_tbls f.write( "\t".join(headers) ) f.write( "\n" ) for pathway in pathways_for_level: f.write(f"{pathway}") for hmm_tbl in args.hmm_tbls: filtered = counts_df[ (counts_df.pathway == pathway) & (counts_df.level == level) & (counts_df.hmm_tbl == hmm_tbl) ] count = filtered.counts.sum() f.write( f"\t{count}" ) f.write( "\n" ) if __name__ == "__main__": main()
jbaugh/pixel-palette
parse.py
import os, sys from PIL import Image import numpy # Converts a number to a 'hex chunk' which is a 0 padded hex nunber as a string def hex_chunk(num): s = str(hex(num)).replace('0x', '') if len(s) == 1: s = '0' + s return s # Converts a pixel: (r, g, b, a) to a hexcode: rrggbbaa def pixel_to_rgba(pixel): return hex_chunk(pixel[0]) + hex_chunk(pixel[1]) + hex_chunk(pixel[2]) + hex_chunk(pixel[3]) # Parses an image file and sums up the pixels being used # Output will be a dict with key: hexcode color and value: number of pixels in image with this color # # fpath is a filepath for the image # ignore_colors is an array of hexcode colors to be ignored (for example, if an image has ff00ffff [magenta] as a transparent color, this can be ignored) # ignore_insible is a boolean determinig if fully transparent pixels should be ignored (True) or counted (False) def sum_pixels(fpath, ignore_colors = [], ignore_invisible = True): pixels = {} with Image.open(fpath) as im: for i in range(1, im.size[0]): for j in range(1, im.size[1]): pixel = im.getpixel((i, j)) # If ignore_invisible is True, ignore pixels with alpha of 0 (i.e. invisible) if not ignore_invisible or pixel[3] != 0: hex_pixel = pixel_to_rgba(pixel) if hex_pixel not in ignore_colors: if hex_pixel in pixels: pixels[hex_pixel] += 1 else: pixels[hex_pixel] = 1 # Sort the pixels return {k: v for k, v in reversed(sorted(pixels.items(), key=lambda item: item[1]))} def print_pixels(pixels): for color in pixels: print(color + ':' + str(pixels[color])) # Input is a hexstring like: 0afe331a, and output is the color code: [10, 254, 51, 26] def hex_to_pixel(hex_code): color = [hex_code[i:i+2] for i in range(0, len(hex_code), 2)] return [int(color[0], 16), int(color[1], 16), int(color[2], 16), int(color[3], 16)] # Determines which color should be used when generating the palette image def get_color(colors, square_size, num_colors_col, x, y): # Get x/y index, using integer division, to see which 'square' it should be in xindex = x // square_size yindex = y // square_size color_index = xindex + (yindex * num_colors_col) if color_index >= len(colors): return [255, 255, 255, 255] else: return hex_to_pixel(colors[color_index]) # Generates a palette image # Each color in the source image will be represented by a square of size square_size, ordered by occurence count # i.e., the most common colors will appear starting from left to right, top to bottom def generate_image(pixels, square_size=16, num_colors_col = 10): image_size = square_size * num_colors_col colors = list(pixels) arr = [] for y in range(image_size): row = [] for x in range(image_size): row.append(get_color(colors, square_size, num_colors_col, x, y)) arr.append(row) array = numpy.array(arr, dtype=numpy.uint8) img = Image.fromarray(array) img.save('output/test.png') pixels = sum_pixels('samples/sprite1.png') print_pixels(pixels) generate_image(pixels)
musabalfarizi/Application-Python-Flask
app/tests.py
<reponame>musabalfarizi/Application-Python-Flask<filename>app/tests.py<gh_stars>1-10 # tests.py import flask_testing import unittest from flask import Flask from flask_testing import TestCase from app import create_app, db from app.models import Employee class TestBase(TestCase): def create_app(self): # pass in test configurations config_name = 'testing' app = create_app(config_name) app.config.update( SQLALCHEMY_DATABASE_URI='mysql+mysqlconnector://dt_admin:dt2016@localhost/dreamteam_test' ) return app def setUp(self): """ Will be called before every test """ db.create_all() # create test admin user admin = Employee(username="admin", password="<PASSWORD>", is_admin=True) # create test non-admin user employee = Employee(username="test_user", password="<PASSWORD>") # save users to database db.session.add(admin) db.session.add(employee) db.session.commit() def tearDown(self): """ Will be called after every test """ db.session.remove() db.drop_all() if __name__ == '__main__': unittest.main()
Abhi-thecoder/Split-Load-System
services/recvFile.py
<reponame>Abhi-thecoder/Split-Load-System import os import logging import enlighten SEPARATOR = "<SEPARATOR>" BUFFER_SIZE = 655350 FORMAT = '[%(asctime)-15s] {%(filename)s} {%(funcName)s} {%(lineno)d} %(message)s' logging.basicConfig(format=FORMAT, level=logging.WARNING) def recvFile(args): # logging.warning("Starting recvFile") # logging.warning(f"args : {args}") tcpSock = args[0] filename = args[1] filesize = args[2] recvFileProgress = args[3] factor = 1000000 oldFTell = 0 # filename, filesize = getFileDetails() # logging.warning(f"Before Receiving at: {tcpSock}") # logging.warning(f"filename: {filename}, filesize: {filesize}") # length=0 total = int(filesize/factor) # recvFileProgress = manager.counter(total= filesize, desc="Receiving File", unit="bytes", color="green") # recvFileProgress.update(incr=0) with open(filename, "wb") as f: # with alive_bar(filesize, manual = True) as bar: while (True): bytes_read = tcpSock.recv(BUFFER_SIZE) # length = length + len(bytes_read) # print("recv: ",length," | f.tell: ",f.tell()) f.write(bytes_read) if(bytes_read): # updateVal = int((f.tell() - oldFTell)/factor) updateVal = f.tell() - oldFTell recvFileProgress.update(incr = updateVal) oldFTell = f.tell() if f.tell() >= filesize: # logging.warning("File Received. Break") break # file_read = file_read + len(bytes_read) # bytes_read = tcpSock.recv(BUFFER_SIZE) # logging.warning("File Received") # logging.warning(f"Ending recvFile for {tcpSock}")
Abhi-thecoder/Split-Load-System
Test Scripts/SDL-1.6/SDL-1.6-test Script.py
<reponame>Abhi-thecoder/Split-Load-System<filename>Test Scripts/SDL-1.6/SDL-1.6-test Script.py import requests import socket import os import sys import json sys.path.append('../../') from services.getFileDetails import getFileDetails class MSG: master = None msg = None data = None def __init__(self, data, msg="", master=False): self.master = master self.msg = msg self.data = data def view(self): logging.warning(f"\n\nMaster: {self.master}\nMessage: {self.msg}\nData: {self.data}\n\n") def getJson(self): return {'master': self.master, 'msg': self.msg, 'data': self.data} def loadJson(self, rawData): decodedData = rawData.decode('ASCII') obj = json.loads(decodedData) #returns an object from a string representing a json object. self.master = obj['master'] self.msg = obj['msg'] self.data = obj['data'] def dumpJson(self): rawData = json.dumps(self.getJson()) #returns a string representing a json object from an object. return rawData.encode('ASCII') EXPECTED_SIZE = 323893 EXPECTED_NAME = "ChromeSetup0-323892.spld" s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(("8.8.8.8", 80)) clientList = [s.getsockname()[0], '192.168.1.2', '192.168.1.3','172.16.17.32'] url = 'https://dl.google.com/tag/s/appguid%3D%7B8A69D345-D564-463C-AFF1-A69D9E530F96%7D%26iid%3D%7B2A0BAEDD-4834-F37C-6BB6-2BD8AA910DF4%7D%26lang%3Den%26browser%3D4%26usagestats%3D1%26appname%3DGoogle%2520Chrome%26needsadmin%3Dprefers%26ap%3Dx64-stable-statsdef_1%26brand%3DCHBD%26installdataindex%3Dempty/update2/installers/ChromeSetup.exe' clientIpSegmentMap= {s.getsockname()[0]: '0-323892', '192.168.1.2': '323893-647785', '192.168.1.3': '647786-971678', '172.16.17.32': '971679-1295575'} distributionMsg = MSG( {"fileLink": url, "clientIpSegmentMap": clientIpSegmentMap, "filenameWithExt" : "ChromeSetup.exe"}, "Distribution message", False) responseTuple = getFileDetails(s.getsockname()[0],distributionMsg,s,False) if(responseTuple[0]==EXPECTED_NAME and responseTuple[1]==EXPECTED_SIZE): print("\n\nPassed!\nActual name: "+responseTuple[0]+" Expected name: "+EXPECTED_NAME+"\nActual FileSize: "+str(responseTuple[1])+" Expected FileSize: "+str(EXPECTED_SIZE)+"\nActual FileLink: "+url+" Expected FileLink: "+url) else: print("Test Failed")
Abhi-thecoder/Split-Load-System
services/recvFile - Copy.py
<reponame>Abhi-thecoder/Split-Load-System<filename>services/recvFile - Copy.py import os import logging SEPARATOR = "<SEPARATOR>" BUFFER_SIZE = 655350 FORMAT = '[%(asctime)-15s] {%(filename)s} {%(funcName)s} {%(lineno)d} %(message)s' logging.basicConfig(format=FORMAT, level=logging.WARNING) def recvFile(args): # logging.warning("Starting recvFile") # logging.warning(f"args : {args}") tcpSock = args[0] filename = args[1] filesize = args[2] # filename, filesize = getFileDetails() # logging.warning(f"Before Receiving at: {tcpSock}") # logging.warning(f"filename: {filename}, filesize: {filesize}") length=0 with open(filename, "wb") as f: with alive_bar(filesize, manual = True) as bar: while (True): bytes_read = tcpSock.recv(BUFFER_SIZE) # length = length + len(bytes_read) # print("recv: ",length," | f.tell: ",f.tell()) f.write(bytes_read) bar(perc=f.tell()/filesize, text='Receiving File') if f.tell() >= filesize: # logging.warning("File Received. Break") break # file_read = file_read + len(bytes_read) # bytes_read = tcpSock.recv(BUFFER_SIZE) # logging.warning("File Received") # logging.warning(f"Ending recvFile for {tcpSock}")
Abhi-thecoder/Split-Load-System
ui/ds2.py
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'ds2.ui' # # Created by: PyQt5 UI code generator 5.14.1 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_Form(object): def setupUi(self, Form): Form.setObjectName("Form") Form.resize(436, 418) icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap("icons/download.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) Form.setWindowIcon(icon) self.label = QtWidgets.QLabel(Form) self.label.setGeometry(QtCore.QRect(10, 10, 411, 31)) self.label.setMaximumSize(QtCore.QSize(16777215, 16777215)) self.label.setTextFormat(QtCore.Qt.AutoText) self.label.setObjectName("label") self.listView = QtWidgets.QListView(Form) self.listView.setGeometry(QtCore.QRect(60, 70, 321, 271)) self.listView.setObjectName("listView") self.Refresh = QtWidgets.QPushButton(Form) self.Refresh.setGeometry(QtCore.QRect(60, 360, 91, 41)) icon1 = QtGui.QIcon() icon1.addPixmap(QtGui.QPixmap("icons/refresh.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.Refresh.setIcon(icon1) self.Refresh.setIconSize(QtCore.QSize(35, 35)) self.Refresh.setCheckable(False) self.Refresh.setFlat(True) self.Refresh.setObjectName("pushButton") self.Next = QtWidgets.QPushButton(Form) self.Next.setGeometry(QtCore.QRect(310, 360, 81, 41)) icon2 = QtGui.QIcon() icon2.addPixmap(QtGui.QPixmap("icons/next.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.Next.setIcon(icon2) self.Next.setIconSize(QtCore.QSize(35, 35)) self.Next.setFlat(True) self.Next.setObjectName("pushButton_2") self.label_2 = QtWidgets.QLabel(Form) self.label_2.setGeometry(QtCore.QRect(50, 40, 81, 31)) self.label_2.setMaximumSize(QtCore.QSize(16777215, 16777215)) self.label_2.setTextFormat(QtCore.Qt.AutoText) self.label_2.setObjectName("label_2") self.retranslateUi(Form) QtCore.QMetaObject.connectSlotsByName(Form) def retranslateUi(self, Form): _translate = QtCore.QCoreApplication.translate Form.setWindowTitle(_translate("Form", "Client List")) self.label.setText(_translate("Form", "<html><head/><body><p align=\"center\"><span style=\" font-size:10pt; font-weight:600;\">Master</span></p></body></html>")) self.Refresh.setText(_translate("Form", "Refresh")) self.Next.setText(_translate("Form", "Next")) self.label_2.setText(_translate("Form", "<html><head/><body><p align=\"center\"><span style=\" font-size:9pt;\">Client List</span></p></body></html>"))
Abhi-thecoder/Split-Load-System
Test Scripts/MPF-1.11/MPF-1.10 Test Script.py
<reponame>Abhi-thecoder/Split-Load-System<gh_stars>1-10 import requests import socket import os import sys import json sys.path.append('../../') from services.merge import merge class MSG: master = None msg = None data = None def __init__(self, data, msg="", master=False): self.master = master self.msg = msg self.data = data def view(self): logging.warning(f"\n\nMaster: {self.master}\nMessage: {self.msg}\nData: {self.data}\n\n") def getJson(self): return {'master': self.master, 'msg': self.msg, 'data': self.data} def loadJson(self, rawData): decodedData = rawData.decode('ASCII') obj = json.loads(decodedData) #returns an object from a string representing a json object. self.master = obj['master'] self.msg = obj['msg'] self.data = obj['data'] def dumpJson(self): rawData = json.dumps(self.getJson()) #returns a string representing a json object from an object. return rawData.encode('ASCII') EXPECTED_NAME = "ChromeSetup.exe" s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(("8.8.8.8", 80)) clientList = [s.getsockname()[0], '192.168.1.2', '192.168.1.3','172.16.58.3'] url = 'https://dl.google.com/tag/s/appguid%3D%7B8A69D345-D564-463C-AFF1-A69D9E530F96%7D%26iid%3D%7B2A0BAEDD-4834-F37C-6BB6-2BD8AA910DF4%7D%26lang%3Den%26browser%3D4%26usagestats%3D1%26appname%3DGoogle%2520Chrome%26needsadmin%3Dprefers%26ap%3Dx64-stable-statsdef_1%26brand%3DCHBD%26installdataindex%3Dempty/update2/installers/ChromeSetup.exe' clientIpSegmentMap= {s.getsockname()[0]: '0-323892', '192.168.1.2': '323893-647785', '192.168.1.3': '647786-971678', '172.16.58.3': '971679-1295575'} distributionMsg = MSG( {"fileLink": url, "clientIpSegmentMap": clientIpSegmentMap, "filenameWithExt" : "ChromeSetup.exe"}, "Distribution message", False) os.system('curl -L -o ChromeSetup0-323892.spld --range 0-323892 ' + url) os.system('curl -L -o ChromeSetup323893-647785.spld --range 323893-647785 ' + url) os.system('curl -L -o ChromeSetup647786-971678.spld --range 647786-971678 ' + url) os.system('curl -L -o ChromeSetup971679-1295575.spld --range 971679-1295575 ' + url) responseTuple = merge(distributionMsg) try: size = os.path.getsize(EXPECTED_NAME) print("\n\nPassed!\nActual name: "+EXPECTED_NAME+" Expected name: "+EXPECTED_NAME) except Exception as e: print("Test Failed")
Abhi-thecoder/Split-Load-System
Test Scripts/SFP-1.10/tcps.py
<filename>Test Scripts/SFP-1.10/tcps.py import socket import sys import os import tqdm SERVER_HOST = "0.0.0.0" SERVER_PORT = 5001 BUFFER_SIZE = 4096 SEPARATOR = "<SEPARATOR>" s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((SERVER_HOST, SERVER_PORT)) s.listen(5) print(f"[*] Listening as {SERVER_HOST}:{SERVER_PORT}") client_socket, address = s.accept() print(f"[+] {address} is connected.") received = client_socket.recv(BUFFER_SIZE).decode() filename, filesize = received.split(SEPARATOR) filename = os.path.basename(filename) filesize = int(filesize) progress = tqdm.tqdm(range(filesize), f'Receiving {filename}', unit='B', unit_scale=True, unit_divisor=1024) with open(filename, "wb") as f: for _ in progress: bytes_read = client_socket.recv(BUFFER_SIZE) if not bytes_read: exit() f.write(bytes_read) progress.update(len(bytes_read)) client_socket.close() s.close() # print('Waiting for connection') # num=3 # abc = [] # bcd=[] # while(num!=0): # num = num-1 # connection, client_address = sock.accept() # abc.append(connection) # bcd.append(client_address) # print(client_address,connection) # print("abc")
Abhi-thecoder/Split-Load-System
ui/ds5.py
<filename>ui/ds5.py # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'ds5.ui' # # Created by: PyQt5 UI code generator 5.14.1 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_Form(object): def setupUi(self, Form): Form.setObjectName("Form") Form.resize(403, 300) icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap("icons/download.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) Form.setWindowIcon(icon) self.label = QtWidgets.QLabel(Form) self.label.setGeometry(QtCore.QRect(10, 70, 381, 51)) self.label.setTextFormat(QtCore.Qt.RichText) self.label.setScaledContents(False) self.label.setObjectName("label") self.label_2 = QtWidgets.QLabel(Form) self.label_2.setGeometry(QtCore.QRect(163, 140, 100, 91)) self.label_2.setTextFormat(QtCore.Qt.RichText) self.label_2.setPixmap(QtGui.QPixmap("icons/giphy.gif")) self.label_2.setObjectName("label_2") self.label_3 = QtWidgets.QLabel(Form) self.label_3.setGeometry(QtCore.QRect(10, 20, 381, 61)) self.label_3.setTextFormat(QtCore.Qt.RichText) self.label_3.setWordWrap(True) self.label_3.setObjectName("label_3") self.label_4 = QtWidgets.QLabel(Form) self.label_4.setGeometry(QtCore.QRect(14, 149, 371, 51)) self.label_4.setTextFormat(QtCore.Qt.RichText) self.label_4.setScaledContents(True) self.label_4.setObjectName("label_4") self.label_4.setWordWrap(True) self.retranslateUi(Form) QtCore.QMetaObject.connectSlotsByName(Form) def retranslateUi(self, Form): _translate = QtCore.QCoreApplication.translate Form.setWindowTitle(_translate("Form", "Download")) self.label.setText(_translate("Form", "<html><head/><body><p align=\"center\"><span style=\" font-size:12pt; font-weight:600;\">Downloading</span></p></body></html>")) self.label_3.setText(_translate("Form", "<html><head/><body><p>File Name : </p></body></html>")) self.label_4.setText(_translate("Form", "<html><head/><body><p>File Downloaded at : </p></body></html>")) self.label_2.setText(_translate("Downloading", "<html><head/><body><p align=\"center\"><br/></p></body></html>")) movie = QtGui.QMovie("icons/loading.gif") self.label_2.setMovie(movie) movie.start() self.label_2.setLayout(QtWidgets.QHBoxLayout()) def changeText(self, text:str, color:str='black'): _translate = QtCore.QCoreApplication.translate self.label.setText(_translate("Form", f"<html><head/><body><p align=\"center\"><span style=\" font-size:12pt; color:{color}; font-weight:600;\">{text}</span></p></body></html>")) def changeTextFilename(self, text:str): _translate = QtCore.QCoreApplication.translate self.label_3.setText(_translate("Form", f"<html><head/><body>{text}</body></html>")) def changeTextDownloadedAt(self, text:str): _translate = QtCore.QCoreApplication.translate self.label_4.setText(_translate("Form", f"<html><head/><body>{text}</body></html>"))
Abhi-thecoder/Split-Load-System
services/merge.py
<reponame>Abhi-thecoder/Split-Load-System import os def merge(distributionMsg): fileString = '' filenameWithExt = distributionMsg.data['filenameWithExt'] filename = filenameWithExt.split('.')[0] for segment in distributionMsg.data['clientIpSegmentMap'].values(): fileString = fileString + filename + segment + '.spld' + ' + ' fileString = fileString[:-2] distributionMsg.data['clientIpSegmentMap'].values() os.system(f'copy /b {fileString} {filenameWithExt}') print("Files merged") # if(os.system(f'copy /b {regexFile}* {filename}')): os.system(f'del {filename}*.spld')
Abhi-thecoder/Split-Load-System
services/divideFile.py
import requests import re import logging FORMAT = '[%(asctime)-15s] {%(filename)s} {%(funcName)s} {%(lineno)d} %(message)s' logging.basicConfig(format=FORMAT, level=logging.WARNING) def divideFile(url, clientList): #clientList = ['192.168.1.1', '192.168.1.2', '192.168.1.3','192.168.3.11'] #url = 'http://releases.ubuntu.com/19.10/ubuntu-19.10-desktop-amd64.iso' logging.warning(f'Please wait while segments are being calculated for {url}') head = requests.head(url, allow_redirects=True).headers # logging.warning(f'{head}') # contentDisposition = head.get('Content-Disposition') # filename = contentDisposition.split('filename=')[1] splitUrl = url.split('/') filename = splitUrl[len(splitUrl) - 1] size = int(head.get('Content-Length'))-1 start = 0 if size % len(clientList) == 0: individualSize = size / len(clientList) else: individualSize = size // len(clientList) individualSize = individualSize-1 end = individualSize count = 0 clientFileSection = {} for clientIp in clientList: clientFileSection[clientIp] = str(int(start)) + '-' + str(int(end)) if(count == 0): individualSize = individualSize+1 count = count+1 start = end + 1 end += individualSize if(len(clientList) != 1): clientFileSection[clientList[len(clientList)-1]] = str(int(end - 2*individualSize + 1)) + '-' + str(size) # logging.warning(f'{int(end - 2*individualSize + 1)}') # logging.warning('File Size = {}'.format(size)) logging.warning (clientFileSection) return (clientFileSection, filename, size+1)
Abhi-thecoder/Split-Load-System
services/startDownload.py
<reponame>Abhi-thecoder/Split-Load-System import os import logging import time def startDownload(segment, fileLink, filenameWithExt): # url = fileLink.split('/') fileName = filenameWithExt.split('.')[0] + str(segment) + '.spld' os.system('curl -s -L -o ' + '"' + fileName + '"' +' --range ' + segment + ' ' + '"' + fileLink +'"') # logging.warning(f"Downloading : {os.path.getsize(fileName)}") # os.system('curl -F 'file=fileName' http://localhost/')
Abhi-thecoder/Split-Load-System
services/portServices.py
import socket import struct,json def get_free_tcp_port(): tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM) tcp.bind(('', 0)) addr, port = tcp.getsockname() tcp.close() return port
Abhi-thecoder/Split-Load-System
Test Scripts/RCN-1.5/RCN-1.5 Test Script.py
<gh_stars>1-10 import requests import socket import os import sys sys.path.append('../../') from services.divideFile import divideFile EXPECTED_SEGMENT = "0-323892" EXPECTED_NAME = "ChromeSetup.exe" s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(("8.8.8.8", 80)) clientList = [s.getsockname()[0], '192.168.1.2', '192.168.1.3','192.168.3.11'] url = 'https://dl.google.com/tag/s/appguid%3D%7B8A69D345-D564-463C-AFF1-A69D9E530F96%7D%26iid%3D%7B2A0BAEDD-4834-F37C-6BB6-2BD8AA910DF4%7D%26lang%3Den%26browser%3D4%26usagestats%3D1%26appname%3DGoogle%2520Chrome%26needsadmin%3Dprefers%26ap%3Dx64-stable-statsdef_1%26brand%3DCHBD%26installdataindex%3Dempty/update2/installers/ChromeSetup.exe' responseTuple = divideFile(url,clientList) clientFileSection=responseTuple[0] filename = responseTuple[1] if(clientFileSection[s.getsockname()[0]]==EXPECTED_SEGMENT and filename==EXPECTED_NAME): print("\n\nPassed!\nActual Segment: "+clientFileSection[s.getsockname()[0]]+" Expected Segment: "+EXPECTED_SEGMENT+"\nActual Name: "+filename+" Expected Name: "+EXPECTED_NAME) else: print("Test Failed")
Abhi-thecoder/Split-Load-System
ui/ds.py
import ds1,ds1,ds3 from PyQt5 import QtCore, QtGui, QtWidgets ui1 = "abc" ui2="abc" ui3="abc" def abc(): ui1.label.setText("abc") if __name__ == "__main__": import sys app = QtWidgets.QApplication(sys.argv) Form = QtWidgets.QWidget() ui1 = ds1.Ui_Form() ui1.setupUi(Form) ui1.Master.clicked.connect(abc) ui1.Client.clicked.connect(abc) Form.show() sys.exit(app.exec_())
Abhi-thecoder/Split-Load-System
ui/ds3.py
<reponame>Abhi-thecoder/Split-Load-System<gh_stars>1-10 # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'ds3.ui' # # Created by: PyQt5 UI code generator 5.13.0 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_Form(object): def setupUi(self, Form): Form.setObjectName("Form") Form.resize(434, 452) self.label = QtWidgets.QLabel(Form) self.label.setGeometry(QtCore.QRect(20, 70, 71, 21)) self.label.setObjectName("label") self.label_2 = QtWidgets.QLabel(Form) self.label_2.setGeometry(QtCore.QRect(10, 0, 51, 31)) self.label_2.setMaximumSize(QtCore.QSize(16777215, 16777215)) self.label_2.setTextFormat(QtCore.Qt.AutoText) self.label_2.setObjectName("label_2") self.lineEdit = QtWidgets.QLineEdit(Form) self.lineEdit.setGeometry(QtCore.QRect(100, 70, 321, 21)) self.lineEdit.setObjectName("lineEdit") self.pushButton = QtWidgets.QPushButton(Form) self.pushButton.setGeometry(QtCore.QRect(100, 100, 91, 31)) self.pushButton.setObjectName("pushButton") self.retranslateUi(Form) QtCore.QMetaObject.connectSlotsByName(Form) def retranslateUi(self, Form): _translate = QtCore.QCoreApplication.translate Form.setWindowTitle(_translate("Form", "Form")) self.label.setText(_translate("Form", "Enter File Link")) self.label_2.setText(_translate("Form", "Master")) self.pushButton.setText(_translate("Form", "Start Download")) if __name__ == "__main__": import sys app = QtWidgets.QApplication(sys.argv) Form = QtWidgets.QWidget() ui = Ui_Form() ui.setupUi(Form) Form.show() sys.exit(app.exec_())
Abhi-thecoder/Split-Load-System
Test Scripts/FPS-1.12/FPS-1.12-TestScript.py
<reponame>Abhi-thecoder/Split-Load-System import requests import socket import os import sys import json sys.path.append('../../') from services.portServices import get_free_tcp_port response = get_free_tcp_port() if(response<=65536): print("Test Passed! Port: "+str(response)) else: print("Test Failed ")
Abhi-thecoder/Split-Load-System
Test Scripts/DFP-1.9/DFP-1.9-Test Script.py
import requests import socket import os import sys import json sys.path.append('../../') from services.startDownload import startDownload EXPECTED_SIZE = 323893 EXPECTED_NAME = "ChromeSetup0-323892.spld" SEGMENT = "0-323892" FILENAME_EXT="ChromeSetup.exe" url = 'https://dl.google.com/tag/s/appguid%3D%7B8A69D345-D564-463C-AFF1-A69D9E530F96%7D%26iid%3D%7B2A0BAEDD-4834-F37C-6BB6-2BD8AA910DF4%7D%26lang%3Den%26browser%3D4%26usagestats%3D1%26appname%3DGoogle%2520Chrome%26needsadmin%3Dprefers%26ap%3Dx64-stable-statsdef_1%26brand%3DCHBD%26installdataindex%3Dempty/update2/installers/ChromeSetup.exe' startDownload(SEGMENT,url,FILENAME_EXT) try: size = os.path.getsize(EXPECTED_NAME) if(size==EXPECTED_SIZE): print("\n\nPassed!\nActual name: "+EXPECTED_NAME+" Expected name: "+EXPECTED_NAME+"\nActual FileSize: "+str(size)+" Expected FileSize: "+str(EXPECTED_SIZE)) else: print("Test Failed") except Exception as e: print("Test Failed"+e)
Abhi-thecoder/Split-Load-System
services/sendFile.py
import os import logging from time import sleep from alive_progress import alive_bar import enlighten BUFFER_SIZE = 655350 SEPARATOR = "<SEPARATOR>" FORMAT = '[%(asctime)-15s] {%(filename)s} {%(funcName)s} {%(lineno)d} %(message)s' logging.basicConfig(format=FORMAT, level=logging.WARNING) def sendFile(args): # logging.warning("Starting sendFile") tcpSock = args[0] filename = args[1] filesize = args[2] sendFileProgress = args[3] factor = 1000000 oldFTell = 0 # logging.warning(f"\nSending: {filename} to {tcpSock}\n") # logging.warning(f"Filesize : {filesize}") while(True): try: f = open(filename, "rb") break except Exception as e: pass l=0 total = int(filesize/factor) byte_read=f.read(BUFFER_SIZE) if byte_read: l = len(byte_read) # print("\n\n") logging.warning(f"Sending File{tcpSock.getpeername()}|{tcpSock.getsockname()}") # sendFileProgress = manager.counter(total=filesize, desc=f"Sending File", unit="bytes", color="red") # sendFileProgress.update(incr=0) while(True): while(not byte_read and f.tell()<filesize): byte_read = f.read(BUFFER_SIZE) if(byte_read): tcpSock.sendall(byte_read) # updateVal = int((f.tell() - oldFTell)/factor) updateVal = f.tell() - oldFTell sendFileProgress.update(incr = updateVal) oldFTell = f.tell() l=l+len(byte_read) # logging.warning(f"{tcpSock.getsockname()[0]} : {tcpSock.getpeername()[0]} Length of file read: {len(byte_read)} | f.tell {f.tell()} , Total Length of file read: {l}") byte_read = None byte_read = f.read(BUFFER_SIZE) # if(byte_read): # logging.warning(f"{tcpSock.getsockname()[0]} : {tcpSock.getpeername()[0]} Length of file read after: {len(byte_read)}") # else: # logging.warning(f"No Byte read.") else: break # logging.warning(f"Ending sendFile for {tcpSock}") f.close()
Abhi-thecoder/Split-Load-System
ui/ds1.py
<gh_stars>1-10 # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'ds1.ui' # # Created by: PyQt5 UI code generator 5.14.1 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_Form(object): def setupUi(self, Form): Form.setObjectName("Form") Form.resize(311, 255) Form.setContextMenuPolicy(QtCore.Qt.PreventContextMenu) icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap("icons/download.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) Form.setWindowIcon(icon) self.Master = QtWidgets.QPushButton(Form) self.Master.setGeometry(QtCore.QRect(30, 180, 111, 31)) self.Master.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor)) self.Master.setToolTipDuration(2) self.Master.setAutoFillBackground(False) self.Master.setAutoDefault(True) self.Master.setFlat(False) self.Master.setObjectName("Master") self.Client = QtWidgets.QPushButton(Form) self.Client.setGeometry(QtCore.QRect(170, 180, 111, 31)) self.Client.setObjectName("Client") self.label = QtWidgets.QLabel(Form) self.label.setGeometry(QtCore.QRect(0, 140, 311, 20)) self.label.setContextMenuPolicy(QtCore.Qt.DefaultContextMenu) self.label.setObjectName("label") self.label_2 = QtWidgets.QLabel(Form) self.label_2.setGeometry(QtCore.QRect(0, 10, 311, 41)) self.label_2.setObjectName("label_2") self.label_3 = QtWidgets.QLabel(Form) self.label_3.setGeometry(QtCore.QRect(130, 50, 55, 51)) self.label_3.setText("") self.label_3.setPixmap(QtGui.QPixmap("icons/download.png")) self.label_3.setScaledContents(True) self.label_3.setObjectName("label_3") self.retranslateUi(Form) QtCore.QMetaObject.connectSlotsByName(Form) def retranslateUi(self, Form): _translate = QtCore.QCoreApplication.translate Form.setWindowTitle(_translate("Form", "SplitLoad")) self.Master.setToolTip(_translate("Form", "Start a new Download by providing Link")) self.Master.setText(_translate("Form", "Start Download")) self.Client.setText(_translate("Form", "Serve Download")) self.label.setText(_translate("Form", "<html><head/><body><p align=\"center\"><span style=\" font-size:10pt;\">Use this System to:</span></p></body></html>")) self.label_2.setText(_translate("Form", "<html><head/><body><p align=\"center\"><span style=\" font-size:12pt; font-weight:600;\">SplitLoad</span></p></body></html>"))
Abhi-thecoder/Split-Load-System
ui/ds4.py
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'ds4.ui' # # Created by: PyQt5 UI code generator 5.14.1 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_Form(object): def setupUi(self, Form): Form.setObjectName("Form") Form.resize(400, 300) icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap("icons/download.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) Form.setWindowIcon(icon) self.label = QtWidgets.QLabel(Form) self.label.setGeometry(QtCore.QRect(140, 20, 121, 16)) self.label.setObjectName("label") self.downloadLink = QtWidgets.QTextEdit(Form) self.downloadLink.setGeometry(QtCore.QRect(30, 50, 341, 41)) self.downloadLink.setObjectName("textEdit") self.Download = QtWidgets.QPushButton(Form) self.Download.setGeometry(QtCore.QRect(150, 110, 100, 28)) self.Download.setObjectName("pushButton") self.retranslateUi(Form) QtCore.QMetaObject.connectSlotsByName(Form) def retranslateUi(self, Form): _translate = QtCore.QCoreApplication.translate Form.setWindowTitle(_translate("Form", "Enter URL")) self.label.setText(_translate("Form", "Enter Download Link")) self.Download.setText(_translate("Form", "Download"))
Abhi-thecoder/Split-Load-System
Test Scripts/CTM-1.4/tcpc.py
<filename>Test Scripts/CTM-1.4/tcpc.py import socket import sys import os import tqdm SEPARATOR = "<SEPARATOR>" BUFFER_SIZE = 4096 host = "192.168.43.78" port = 5001 filename = "Dynamic Prog.pdf" filesize = os.path.getsize(filename) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print(f"[+] Connecting to {host}:{port}") s.connect((host, port)) print("[+] Connected.") s.sendall(f"{filename}{SEPARATOR}{filesize}".encode()) # progress = tqdm.tqdm(range(filesize), f'Sending {filename}', unit='B', unit_scale=True, unit_divisor=1024) with open(filename, "rb") as f: while True: bytes_read = f.read(BUFFER_SIZE) if not bytes_read: # file transmitting is done print("File Sent.") exit(0) s.sendall(bytes_read) # progress.update(len(bytes_read)) s.close()
Abhi-thecoder/Split-Load-System
SplitLoad.py
import threading import time import socket import struct import json import sys from services.portServices import get_free_tcp_port from services.divideFile import divideFile from services.startDownload import startDownload from services.getOwnIp import getOwnIp from services.sendFile import sendFile from services.recvFile import recvFile from services.getFileDetails import getFileDetails from services.merge import merge from ui import ds1 from ui import ds2 from ui import ds3 from ui import ds4 from ui import ds5 from PyQt5 import QtCore, QtGui, QtWidgets from datetime import datetime import logging from time import sleep from random import random import os import enlighten fileLink = "https://dl.google.com/tag/s/appguid%3D%7B8A69D345-D564-463C-AFF1-A69D9E530F96%7D%26iid%3D%7B2A0BAEDD-4834-F37C-6BB6-2BD8AA910DF4%7D%26lang%3Den%26browser%3D4%26usagestats%3D1%26appname%3DGoogle%2520Chrome%26needsadmin%3Dprefers%26ap%3Dx64-stable-statsdef_1%26brand%3DCHBD%26installdataindex%3Dempty/update2/installers/ChromeSetup.exe" appendLock = threading.Lock() segmentsFetched = False choice = -1 ui1 = "abc" ui2 = "abc" ui3 = "abc" ui4 = None ui5 = None Form = "abc" Form2 = None Form4 = None Form5 = None app = "abc" isMaster = False isBusy = False # Tell whether the this system is already busy in some download or not BUFSIZE = 655350 broadcastPort = 2100 tcpPort = 8888 clientsIp = [] # list to store clients tcpConnectionList = [] broadcastInterface = "192.168.43.255" broadcastListenInterface = "0.0.0.0" ipSockMap = {} ipThreadMap = {} ipPortMap = {} clientFileSection = {} clientIpSegmentMap = {} OWNPORT = get_free_tcp_port() OWNIP = getOwnIp() clientIpList=[] FORMAT = '[%(asctime)-15s] {%(filename)s} {%(funcName)s} {%(lineno)d} %(message)s' logging.basicConfig(format=FORMAT, level=logging.WARNING) class MSG: master = None msg = None data = None def __init__(self, data, msg="", master=False): self.master = master self.msg = msg self.data = data def view(self): logging.warning(f"\n\nMaster: {self.master}\nMessage: {self.msg}\nData: {self.data}\n\n") def getJson(self): return {'master': self.master, 'msg': self.msg, 'data': self.data} def loadJson(self, rawData): decodedData = rawData.decode('ASCII') obj = json.loads(decodedData) #returns an object from a string representing a json object. self.master = obj['master'] self.msg = obj['msg'] self.data = obj['data'] def dumpJson(self): rawData = json.dumps(self.getJson()) #returns a string representing a json object from an object. return rawData.encode('ASCII') distributionMsg = MSG({}) def listenClientTcpReq(arg): global clientIpList tcpSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) serverAddress = (OWNIP, tcpPort) tcpSock.bind(serverAddress) totalClients = len(clientIpList) tcpSock.listen(totalClients) while(len(ipSockMap.keys())<totalClients): connection, address = tcpSock.accept() #logging.warning(f'Accepted connection: {connection}') if address[0] not in ipSockMap: ipSockMap[address[0]]=connection #logging.warning(f'Connected to client(Inside listenClientTcpReq): {address[0]}, {address[1]}') #logging.warning(f"ipSockMap.keys(): {len(ipSockMap.keys())} totalClients: {totalClients}") if len(ipSockMap.keys())==totalClients: #logging.warning("All clients connected") break #logging.warning("Exiting listenClientTcpReq") def initiateDownload(args): segment = args[0] fileLink = args[1] filenameWithExt = args[2] startDownload(segment, fileLink, filenameWithExt) #logging.warning("Exiting initiateDownload") def listenBroadcast(arg): # client global clientIpList data = address = None manager = enlighten.get_manager() #logging.warning("listening broadcast started") sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.bind((broadcastListenInterface, broadcastPort)) res = MSG({}) #logging.warning('Listening for master at {}'.format(sock.getsockname())) data, address = sock.recvfrom(BUFSIZE) res.loadJson(data) sock.close() if res.msg == 'Add request': tcpSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) logging.warning("Announcement Received") logging.warning("Making connection with the Master at IP = {} and Port = {}".format( address[0], tcpPort)) tcpServerAddress = (address[0], tcpPort) tcpSock.connect(tcpServerAddress) rawData = tcpSock.recv(BUFSIZE) distributionMsg = MSG({}) distributionMsg.loadJson(rawData) #logging.warning("distribution message received ") clientDownloadStarted() distributionMsg.view() filenameWithExt = distributionMsg.data['filenameWithExt'] clientIpSegmentMap = distributionMsg.data['clientIpSegmentMap'] size = int(list(clientIpSegmentMap.values())[len(list(clientIpSegmentMap.values()))-1].split('-')[1]) + 1 setFilename(filenameWithExt, size) segment = clientIpSegmentMap[OWNIP] #logging.warning (segment) fileLink = distributionMsg.data['fileLink'] ipSockMap[address[0]] = tcpSock ipSockMap[OWNIP] = None clientIpList = distributionMsg.data['clientIpSegmentMap'].keys() listenClientTcpReqThread = threading.Thread(target=listenClientTcpReq, args = ("",)) listenClientTcpReqThread.start() recvFileThread = None sleep(random()*10) for client in clientIpList: if client not in ipSockMap: tcpServerAddress = (client, tcpPort) tcpSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) tcpSock.connect(tcpServerAddress) #logging.warning(f'Requested connection: {tcpSock}') ipSockMap[client]=tcpSock threads = [] progressBars = {} for client in ipSockMap: if(client != OWNIP): tcpSock = ipSockMap[client] filedetails = getFileDetails(OWNIP, distributionMsg, tcpSock) recvFileProgress = manager.counter(total= filedetails[1], desc="Receiving File", unit="bytes", color="green") progressBars[client] = (recvFileProgress,filedetails) for client in ipSockMap: if(client != OWNIP): tcpSock = ipSockMap[client] recvFileThread = threading.Thread(target=recvFile,args=((tcpSock, progressBars[client][1][0], progressBars[client][1][1], progressBars[client][0]),)) recvFileThread.start() threads.append(recvFileThread) # for x in ipSockMap: #logging.warning(x) startTime = time.time() initiateDownloadThread = threading.Thread( target=initiateDownload, args=((segment, fileLink, filenameWithExt),)) # Download Started initiateDownloadThread.start() threads.append(initiateDownloadThread) filename = filenameWithExt.split('.')[0] + str(segment) +'.spld' progressBars = {} for client in ipSockMap: if(client != OWNIP): tcpSock = ipSockMap[client] filedetails = getFileDetails(OWNIP, distributionMsg, tcpSock, flag = False) sendFileProgress = manager.counter(total=filedetails[1], desc=f"Sending File", unit="bytes", color="red") progressBars[client] = (sendFileProgress,filedetails) for ipSock in ipSockMap: client = ipSock if client != OWNIP: tcpSock = ipSockMap[client] sendFileThread = threading.Thread(target=sendFile,args=((tcpSock, progressBars[client][1][0], progressBars[client][1][1], progressBars[client][0]),)) sendFileThread.start() threads.append(sendFileThread) for thread in threads: thread.join() #logging.warning("Out of all Send and Recv Threads.") regexFile = filenameWithExt.split('.')[0] merge(distributionMsg) #logging.warning(f"Downloading time : {time.time() - startTime}") downloadComplete() # tcpSock.close() logging.warning("listening to master ended") def announceBroadcast(arg): global choice #logging.warning("announcing broadcast started") sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) while(True): res = MSG({}, "Add request", isMaster) sock.sendto(res.dumpJson(), (broadcastInterface, broadcastPort)) logging.warning("Announcing to Join.") time.sleep(1) # for i in clientsIp: #logging.warning(f"ip: {i}") #logging.warning("enter 1 for reannounce or 0 to end announcement") # refreshList() while(choice == -1): pass if(choice == 0): res.msg = 'Broadcast Ends' # sock.sendto(res.dumpJson(), (broadcastInterface, broadcastPort)) tcpSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) tcpServerAddress = (OWNIP, tcpPort) tcpSock.connect(tcpServerAddress) break choice = -1 sock.close() #logging.warning("announcing broadcast ended") def sendDistributionMsg(args): global segmentsFetched global distributionMsg connection = args[0] connection.sendall(distributionMsg.dumpJson()) #logging.warning("Exiting sendDistributionMsg") def listenTcp(arg): tcpSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) serverAddress = (OWNIP, tcpPort) tcpSock.bind(serverAddress) tcpSock.listen(10) while(True): connection, address = tcpSock.accept() if connection.getsockname()[0] == connection.getpeername()[0]: break tcpConnectionList.append((connection, address)) clientsIp.append(address[0]) ipSockMap[address[0]] = connection # refreshList() #logging.warning(f'Connected to : {address[0]} : {address[1]}') #logging.warning("Exiting listenTcp thread.") def Master(arg): startMasterScreen() global isMaster isMaster = True manager = enlighten.get_manager() listenTcpThread = threading.Thread(target=listenTcp, args = ("",)) listenTcpThread.start() announceBroadcastThread = threading.Thread( target=announceBroadcast, args=("",)) announceBroadcastThread.start() announceBroadcastThread.join() # while(announceBroadcastThread.is_alive()): # pass # if got all the clients, Time to distribute the file and send it to others # if not announceBroadcastThread.is_alive(): global segmentsFetched global distributionMsg clientsIp.append(OWNIP) clientIpSegmentMap, filenameWithExt, size = divideFile(fileLink, clientsIp) distributionMsg = MSG( {"fileLink": fileLink, "clientIpSegmentMap": clientIpSegmentMap, "filenameWithExt" : filenameWithExt}, "Distribution message", isMaster) #logging.warning("This is the distribution msg ") distributionMsg.view() setFilename(filenameWithExt, int(size)) for element in tcpConnectionList: sendDistributionMsgThread = threading.Thread(target = sendDistributionMsg, args = ((element[0],element[1]),)) sendDistributionMsgThread.start() segmentsFetched = True segment = clientIpSegmentMap[OWNIP] threads = [] progressBars = {} for client in ipSockMap: if(client != OWNIP): tcpSock = ipSockMap[client] filedetails = getFileDetails(OWNIP, distributionMsg, tcpSock) recvFileProgress = manager.counter(total= filedetails[1], desc="Receiving File", unit="bytes", color="green") progressBars[client] = (recvFileProgress,filedetails) # logging.warning(f"Client : {client}") for client in ipSockMap: if(client != OWNIP): tcpSock = ipSockMap[client] recvFileThread = threading.Thread(target=recvFile,args=((tcpSock, progressBars[client][1][0], progressBars[client][1][1], progressBars[client][0]),)) recvFileThread.start() threads.append(recvFileThread) startTime = time.time() initiateDownloadThread = threading.Thread(target=initiateDownload, args=( (segment, fileLink, filenameWithExt),)) # Download Started in Master initiateDownloadThread.start() threads.append(initiateDownloadThread) segment = clientIpSegmentMap[OWNIP] filename = filenameWithExt.split('.')[0] + str(segment) + '.spld' progressBars = {} for client in ipSockMap: if(client != OWNIP): tcpSock = ipSockMap[client] filedetails = getFileDetails(OWNIP, distributionMsg, tcpSock, flag = False) sendFileProgress = manager.counter(total=filedetails[1], desc=f"Sending File", unit="bytes", color="red") progressBars[client] = (sendFileProgress,filedetails) for ipSock in ipSockMap: client = ipSock if client != OWNIP: tcpSock = ipSockMap[client] sendFileThread = threading.Thread(target=sendFile,args=((tcpSock, progressBars[client][1][0], progressBars[client][1][1], progressBars[client][0]),)) sendFileThread.start() threads.append(sendFileThread) #logging.warning("recvFileThread joined") for thread in threads: thread.join() regexFile = filenameWithExt.split('.')[0] merge(distributionMsg) #logging.warning(f"Downloading time : {time.time() - startTime}") downloadComplete() #logging.warning("Exiting Master") def Client(): listenBroadcastThread = threading.Thread( target=listenBroadcast, args=("",)) listenBroadcastThread.start() Form.close() ui5.changeText("Waiting",'red') Form5.show() ui5.label_3.setVisible(False) ui5.label_4.setVisible(False) # listenBroadcastThread.join() def clientDownloadStarted(): ui5.changeText("Downloading") ui5.label_3.setVisible(True) def startMasterScreen(): global app global Form2 global Form def checkClientList(args): global clientsIp global choice #logging.warning("CheckClientList called") length = 0 while(choice != 0): # #logging.warning(f'{len(clientsIp)}') sleep(1) if(length != len(clientsIp)): length = len(clientsIp) #logging.warning("Refreshing List") refreshList() #logging.warning("Exiting checkClientList") def startMasterUtil(): #logging.warning("Master") masterThread = threading.Thread(target=Master, args=('',)) masterThread.start() checkClientListThread = threading.Thread(target=checkClientList, args=('',)) checkClientListThread.start() Form.close() Form2.show() refreshList() def reannounce(): global choice choice = 1 refreshList() def setFilename(filenameWithExt, size:int): sizeString = '' if ((size // 2**30) > 0): sizeString = ' GB' sizeString = '%.3f' %(size / 2**30) + sizeString elif ((size // 2**20) > 0): sizeString = ' MB' sizeString = '%.3f' %(size / 2**20) + sizeString else: sizeString = ' KB' sizeString = '%.3f' %(size / 2**10) + sizeString fileString = f"File Name : {filenameWithExt} ({sizeString})" ui5.changeTextFilename(fileString) def refreshList(): global clientsIp model = QtGui.QStandardItemModel() ui2.listView.setModel(model) for i in clientsIp: item = QtGui.QStandardItem(i) model.appendRow(item) def endAnnounceMent(): global choice global fileLink fileLink = str(ui4.downloadLink.toPlainText()) fileLink = fileLink.strip() choice = 0 Form4.close() Form5.show() ui5.label_4.setVisible(False) def urlPicker(): Form2.close() Form4.show() def downloadComplete(): ui5.changeText("Download Complete",'green') ui5.label_2.setVisible(False) path = os.path.dirname(os.path.abspath(__file__)) path = "File downloaded at : " + path ui5.label_4.setVisible(True) ui5.changeTextDownloadedAt(path) # # setDownloadedAt() if __name__ == "__main__": app = QtWidgets.QApplication(sys.argv) Form = QtWidgets.QWidget() ui1 = ds1.Ui_Form() ui1.setupUi(Form) Form2 = QtWidgets.QWidget() ui2 = ds2.Ui_Form() ui2.setupUi(Form2) Form4 = QtWidgets.QWidget() ui4 = ds4.Ui_Form() ui4.setupUi(Form4) Form5 = QtWidgets.QWidget() ui5 = ds5.Ui_Form() ui5.setupUi(Form5) ui1.Master.clicked.connect(startMasterUtil) ui1.Client.clicked.connect(Client) ui2.Refresh.clicked.connect(reannounce) ui2.Next.clicked.connect(urlPicker) ui4.Download.clicked.connect(endAnnounceMent) Form.show() sys.exit(app.exec_()) # while(True): # pass
Abhi-thecoder/Split-Load-System
services/getFileDetails.py
import logging FORMAT = '[%(asctime)-15s] {%(filename)s} {%(funcName)s} {%(lineno)d} %(message)s' logging.basicConfig(format=FORMAT, level=logging.WARNING) def getFileDetails(OWNIP,distributionMsg,socket,flag=True): laddr= socket.getsockname()[0] raddr = socket.getpeername()[0] if flag: addr = laddr if laddr!=OWNIP else raddr else: addr = laddr if laddr==OWNIP else raddr segment = distributionMsg.data["clientIpSegmentMap"][addr].split("-") fileSize = int(segment[1])-int(segment[0])+1 # logging.warning(f'{segment[1]} - {segment[0]} + 1 = {fileSize}') filenameWithExt = distributionMsg.data['filenameWithExt'] fileName = filenameWithExt.split('.')[0] + str(distributionMsg.data["clientIpSegmentMap"][addr])+".spld" return (fileName,fileSize)
Kolyamba-mamba/technology-partner-search-module
modules/helpers/dbHelper.py
import psycopg2 def create_connection(db_name, db_user, db_password, db_host, db_port): connection = None try: connection = psycopg2.connect( database=db_name, user=db_user, password=<PASSWORD>, host=db_host, port=db_port, ) print("Подключение к PostgreSQL установлено") except psycopg2.OperationalError as e: print(f"Ошибка '{e}' при подключении к БД") return connection def execute_query(connection, query): connection.autocommit = True cursor = connection.cursor() try: cursor.execute(query) # print("Запрос прошел успешно") except psycopg2.OperationalError as e: print(f"Ошибка '{e}' при выполнении запроса") def execute_query_with_params(connection, query, params): connection.autocommit = True cursor = connection.cursor() try: cursor.execute(query, params) # print("Запрос прошел успешно") except psycopg2.OperationalError as e: print(f"Ошибка '{e}' при выполнении запроса") def execute_select_all_query(connection, query): connection.autocommit = True cursor = connection.cursor() try: cursor.execute(query) # print("Запрос прошел успешно") return cursor.fetchall() except psycopg2.OperationalError as e: print(f"Ошибка '{e}' при выполнении запроса") def get_cursor_query(connection, query): cursor = connection.cursor() try: cursor.execute(query) # print("Запрос прошел успешно") return cursor except psycopg2.OperationalError as e: print(f"Ошибка '{e}' при выполнении запроса") def create_tables(connection): create_patents_table = """ CREATE TABLE IF NOT EXISTS patents ( id uuid NOT NULL PRIMARY KEY, publication_reference TEXT NOT NULL, main_classification_type TEXT NOT NULL, main_classification TEXT, title TEXT, inventors TEXT, abstract_path TEXT, description_path TEXT, claims_path TEXT, assignee TEXT ) """ create_sao_table = """ CREATE TABLE IF NOT EXISTS sao ( id uuid NOT NULL PRIMARY KEY, subject TEXT, action TEXT, object TEXT, patent_id uuid NOT NULL ) """ execute_query(connection, create_patents_table) execute_query(connection, create_sao_table)
Kolyamba-mamba/technology-partner-search-module
modules/dbActions/insertTables.py
<filename>modules/dbActions/insertTables.py import os import sys sys.path.append(os.path.abspath('../../mySite/mySite')) from modules.models.patent import Patent from modules.models.sao import Sao from modules.helpers.dbHelper import execute_query_with_params def insert_patent(connection, patent: Patent): insert_query = """ INSERT INTO patents ( id, publication_reference, main_classification_type, main_classification, title, inventors, abstract_path, description_path, claims_path, assignee) values (%s,%s,%s,%s,%s,%s,%s,%s,%s, %s) """ execute_query_with_params(connection, insert_query, list(patent.__dict__.values())) def insert_sao(connection, sao: Sao): insert_query = """ INSERT INTO sao ( id, subject, action, object, patent_id) values (%s,%s,%s,%s,%s) """ execute_query_with_params(connection, insert_query, list(sao.__dict__.values()))
Kolyamba-mamba/technology-partner-search-module
modules/parsers/patentParser.py
<gh_stars>1-10 from bs4 import BeautifulSoup as BS import uuid import multiprocessing import time import os import sys from modules.models.parsedPatent import ParsedPatent from modules.models.patent import Patent from modules.helpers.dbHelper import create_connection, create_tables from modules.dbActions.insertTables import insert_patent def save_to_file(path: str, patent_title: str, ext: str, data: str): if not os.path.isdir(path): os.makedirs(path) filePath = path + "/" + patent_title + ext try: with open(filePath, 'w', encoding="utf-8") as file: file.write(data.strip()) except EnvironmentError: print("Ошибка при записи в файл:" + filePath) return filePath def get_text_field(parent_name, field_name: str): field = parent_name.find(field_name) try: if field: text_field = field.text.strip() return text_field else: return None except AttributeError: print("Ошибка при обращении к полю" + field_name) return None def splitter(text: str): splitter = '<?xml version="1.0" encoding="UTF-8"?>' splitted = text.split(splitter) splitted = list(filter(lambda x: x != '', splitted)) return splitted def parse_XML(text): patent_reference = '' try: soup = BS(text, 'lxml') app_ref_tmp = soup.find("application-reference") if app_ref_tmp: application_reference = {'doc_number': get_text_field(app_ref_tmp, "doc-number"), 'country': get_text_field(app_ref_tmp, "country"), 'date': get_text_field(app_ref_tmp, "date")} else: application_reference = None pub_ref_tmp = soup.find("publication-reference") if pub_ref_tmp: publication_reference = {'doc-number': get_text_field(pub_ref_tmp, "doc-number"), 'country': get_text_field(pub_ref_tmp, "country"), 'date': get_text_field(pub_ref_tmp, "date"), 'kind': get_text_field(pub_ref_tmp, "kind")} patent_reference = publication_reference["country"] + publication_reference["doc-number"] \ + publication_reference["kind"] else: publication_reference = None invention_title = soup.find("invention-title") if invention_title: title = invention_title.text.strip() else: title = None inventors = [] applicants = soup.find("applicants") if applicants: for content in applicants.contents: if content != '\n': inventor = {'first-name': get_text_field(content, "first-name"), 'last-name': get_text_field(content, "last-name")} inventors.append(inventor) assignee_tmp = soup.find("assignee") assignee = None if assignee_tmp: assignee = get_text_field(assignee_tmp, "orgname") abstract_tmp = soup.find("abstract") if abstract_tmp: abstract = abstract_tmp.text else: abstract = None description_tmp = soup.find("description") if description_tmp: description = description_tmp.text else: description = None claims = [x.text for x in soup.findAll("claim-text")] classification_type = None main_classification = None # только ipc for classification in ("classification-ipc", "classification-ipcr", "classification-locarno"): tag = soup.find(classification) if tag: classification_type = classification if classification == "classification-ipcr": section_tag = tag.find("section") class_tag = tag.find("class") subclass_tag = tag.find("subclass") if section_tag and class_tag and subclass_tag: patent_section = section_tag.text.strip() patent_class = class_tag.text.strip() patent_subclass = subclass_tag.text.strip() main_classification = f"{patent_section} {patent_class} {patent_subclass}" break else: continue else: main_classification_tag = tag.find("main-classification") if main_classification_tag: main_classification = main_classification_tag.text.strip() break else: continue return ParsedPatent(application_reference, publication_reference, str(classification_type), str(main_classification), title, inventors, abstract, description, claims, assignee) except Exception: print("Ошибка при парсинге патента " + patent_reference) return None def save_patent(patent: ParsedPatent, path: str): result = {} filename = patent.publication_reference["country"] + patent.publication_reference["doc-number"] \ + patent.publication_reference["kind"] result['abstractPath'] = None result['descriptionPath'] = None result['claimsPath'] = None if patent.abstract: abstract_path = save_to_file(path + '/abstract', filename, '.txt', patent.abstract) result['abstractPath'] = abstract_path if patent.description: description_path = save_to_file(path + '/description', filename, '.txt', patent.description) result['descriptionPath'] = description_path if patent.claims: claims_path = save_to_file(path + '/claims', filename, '.txt', '\n'.join(patent.claims)) result['claimsPath'] = claims_path return result def map_patent(parsed_patent: ParsedPatent, paths): patent_reference = parsed_patent.publication_reference["country"] + parsed_patent.publication_reference[ "doc-number"] \ + parsed_patent.publication_reference["kind"] if parsed_patent.inventors and len(parsed_patent.inventors) > 0: inventors = ','.join(str(e['first-name']) + " " + str(e['last-name']) for e in parsed_patent.inventors) else: inventors = "" return Patent(str(uuid.uuid4()), patent_reference, parsed_patent.main_classification_type, parsed_patent.main_classification, parsed_patent.title, inventors, paths['abstractPath'], paths['descriptionPath'], paths['claimsPath'], parsed_patent.assignee) # Функция для обработки файлов def process_files(files, path): con = create_connection("diplom", "postgres", "postgres", "localhost", "5432") for file in files: start_time = time.time() with open(file) as f: xml = f.read() splitted_xml = splitter(xml) print(len(splitted_xml)) iter = 0 while iter < len(splitted_xml): parsed_patent = parse_XML(splitted_xml[iter]) if not parsed_patent: continue save_files = save_patent(parsed_patent, path) patent = map_patent(parsed_patent, save_files) insert_patent(con, patent) iter += 1 end_time = time.time() print(f"Finished processing {file}, time: {end_time-start_time}") con.close() def main(): total_time_start = time.time() parallel_processes_count = multiprocessing.cpu_count() - 2 path = 'C:/Users/mrkol/Documents' files = os.listdir(path + '/patents/unpack') names = list(map(lambda x: path + '/patents/unpack/' + x, files)) filenames_list = [] i = 0 con = create_connection("diplom", "postgres", "postgres", "localhost", "5432") create_tables(con) con.close() # Проверка существования while i < len(names): if os.path.isdir(names[i]): names += list(map(lambda x: f"{names[i]}/{x}", os.listdir(names[i]))) i += 1 filenames = [name for name in names if os.path.isfile(name)] for i in range(parallel_processes_count): start = i * len(filenames) / parallel_processes_count end = (i + 1) * len(filenames) / parallel_processes_count if i == parallel_processes_count: end = len(filenames) start = int(start) end = int(end) if len(filenames[start:end]) > 0: filenames_list.append(filenames[start:end]) filenames_list = filenames_list processes = [] for sublist in filenames_list: p = multiprocessing.Process(target=process_files, args=(sublist, path)) p.start() processes.append(p) for p in processes: p.join() total_time_end = time.time() print(f"\nDone in {total_time_end - total_time_start}") if __name__ == '__main__': main()
Kolyamba-mamba/technology-partner-search-module
modules/helpers/argParser.py
import argparse import os def parse_args(args): parser = argparse.ArgumentParser(description='Скачиватель патентов') parser.add_argument('-startDownloader', type=bool, dest='startDownloader', default=False, help='Запускать ли скачватель патентов') parser.add_argument('-startUnpacker', type=bool, dest='startUnpacker', default=False, help='Запускать ли распаковщик патентов') parser.add_argument('-path', type=str, dest='path', default='C:/Users/mrkol/Documents/patents/', help='Место сохранения') parser.add_argument('-saveUrl', type=bool, dest='saveUrl', default=False, help='Сохранять ли ссылки на файлы патентов') parser.add_argument('-urlsPath', type=str, dest='urlsPath', help='Путь к файлу с ссылками') parser.add_argument('-parsePatent', type=bool, dest='parsePatent', default=False, help='Запуск парсера патентов') parser.add_argument('-selectSao', type=bool, dest='selectSao', default=False, help='Запуск извлечения структур SAO') parser.add_argument('-createSaoLog', type=bool, dest='createSaoLog', default=False, help='Сохранение логов при извлечении SAO') parser.add_argument('-createW2VModel', type=bool, dest='cerateW2VModel', default=False, help='Создание модели Word2Vec') return parser.parse_args(args) def validate_args(args): if not args.saveUrl: if args.urlsPath is None or not os.path.isfile(args.urlsPath): print('Файла с ссылками не существует') return False else: return True if args.saveUrl: if args.urlsPath is not None: print('Вы не можете указывать путь к файлу с сылками, так как этот файл будет создан скриптом ') return False else: return True if args.startUnpacker: if os.path.isfile(args.path): return True else: return False else: return True
Kolyamba-mamba/technology-partner-search-module
modules/helpers/main.py
<reponame>Kolyamba-mamba/technology-partner-search-module import os import sys import modules.helpers.argParser as ap import modules.helpers.patentDownloader as pd import modules.helpers.unpacker as up import modules.parsers.patentParser as pp def main(): args = ap.parse_args(sys.argv[1:]) if not ap.validate_args(args): return if args.startDownloader: pd.main(args) if args.startUnpacker: up.main(args) if args.parsePatent: pp.main() if __name__ == '__main__': main()
Kolyamba-mamba/technology-partner-search-module
modules/models/sao.py
class Sao: """Класс sao (Subject-Action-Object)""" def __init__(self, id, subject, action, obj, patent_id): self.id = id self.subject = subject self.action = action self.object = obj self.patent_id = patent_id
Kolyamba-mamba/technology-partner-search-module
modules/dbActions/getTables.py
<gh_stars>1-10 import os import sys from modules.helpers.dbHelper import execute_select_all_query, get_cursor_query def get_count_table_rows(connection, table_name): query = f"SELECT COUNT(*) FROM {table_name}" count = execute_select_all_query(connection, query) return count def get_entities(connection, table_name): query = f"SELECT * FROM {table_name} ORDER BY id" ids = execute_select_all_query(connection, query) return ids def get_cursor(connection, table_name): query = f"SELECT * FROM {table_name}" cursor = get_cursor_query(connection, query) return cursor def get_entities_by_condition(connection, table_name, condition): query = f"SELECT * FROM {table_name} WHERE {condition} ORDER BY id" elements = execute_select_all_query(connection, query) return elements def get_abstract_and_descr_path(connection): query = f"SELECT abstract_path,description_path FROM patents" elements = execute_select_all_query(connection, query) return elements
Kolyamba-mamba/technology-partner-search-module
modules/helpers/saoSelector.py
import stanza import re import uuid from typing import List import os import sys from modules.models.patent import Patent from modules.models.sao import Sao from modules.dbActions.getTables import get_entities from modules.helpers.dbHelper import create_connection from modules.dbActions.insertTables import insert_sao from modules.helpers.logHelper import record_sao_log import psycopg2 def rem(text: str): pattern = r"\([\w\W][^\)\(]*\)" sub_regex = re.sub(pattern, "", text) if re.search(pattern, sub_regex): sub_regex = rem(sub_regex) return sub_regex def text_splitter(text: str): sentence_separators_regex = re.compile(r'[.|!|?|...|\n|;]') sentences = sentence_separators_regex.split(text) return sentences def sentence_splitter(sentence: str): words_separators_regex = re.compile(r'[\s|:|,|;|]') words = words_separators_regex.split(sentence) return words def split_description(text: str): titles = ["SUMMARY OF THE INVENTION", "SUMMARY", "DETAILED DESCRIPTION", "BRIEF SUMMARY OF THE INVENTION", "DETAILED DESCRIPTION OF THE INVENTION", "TECHNICAL FIELD", "FIELD OF THE INVENTION", "SUMMARY AND OBJECTS OF THE INVENTION", "BRIEF SUMMARY", "FIELD OF INVENTION"] result = [] splitter = re.compile(r'([^a-z0-9.]{2,}\n)') splitted_text = splitter.split(text) for i, t in enumerate(splitted_text): if t.strip().isupper() and t.strip() in titles and len(splitted_text) > i: result.append(splitted_text[i+1]) return " ".join(result) # Метод поиска предложений с запрещенными словами def find_forbidden_sentences(sentences: List[str]): forbidden_sentences = [] forbidden_words = ['comprise', 'comprises', 'comprised', 'comprising', 'include', 'includes', 'including', 'included', 'consist', 'consists', 'consisted', 'consisting', 'connect', 'connects', 'connected', 'connecting', 'fig', 'figs', 'contain', 'contains', 'contained', 'containing'] for sentence in sentences: if len(sentence) > 0: words = sentence_splitter(sentence) if len(words) > 3: for word in words: if word.lower() in forbidden_words or word.isnumeric(): forbidden_sentences.append(sentence) break else: forbidden_sentences.append(sentence) return forbidden_sentences # Метод обрезающий строку после ключевых слов def find_trim_sentence(sentences: List[str]): is_cropped = False trim_sentences = [] trim_sentence = "" words_of_cut_part = ['which', 'where', 'wherein'] for sentence in sentences: if len(sentence) > 0: words = sentence.split() for i, word in enumerate(words): if word in words_of_cut_part: trim_sentence = ' '.join(words[:i]) is_cropped = True break elif word == 'and': if i > 0: if words[i-1][-1] == ',': trim_sentence = ' '.join(words[:i]) is_cropped = True break elif word == 'such': if i < len(words)-1: if words[i+1] == 'as': trim_sentence = ' '.join(words[:i]) is_cropped = True break if is_cropped: trim_sentences.append(trim_sentence) else: trim_sentences.append(sentence) is_cropped = False return trim_sentences def get_sentences(text: str): sentences = text_splitter(text) trim_sentence = find_trim_sentence(sentences) forbidden_sentences = find_forbidden_sentences(trim_sentence) for sentence in forbidden_sentences: trim_sentence.remove(sentence) # trim_sentence = find_trim_sentence(sentences) return trim_sentence def get_sao(words, patent_id): object_deprel = ['iobj', 'obj', 'obl'] subject_deprel = ['nsubj', 'csubj', 'acl'] object_id = None subject_id = None action_text = None subject = None action = None obj = None for i, word in enumerate(words): if word.deprel == 'root' and word.upos == 'VERB': if i > 1 and words[i-1].deprel == 'aux': action_text = words[i-1].text + " " id_start = words[i-1].id if action_text: action_text += word.text id_end = word.id else: action_text = word.text id_start = word.id id_end = word.id action = (id_start, id_end, action_text) elif word.deprel in object_deprel and not object_id: object_id = word.id elif word.deprel in subject_deprel and not subject_id: subject_id = word.id if action and object_id and subject_id: if object_id < action[0]: obj = ' '.join(str(word.text) for word in words[:action[0]-1]) elif subject_id < action[0]: subject = ' '.join(str(word.text) for word in words[:action[0]-1]) if object_id > action[1]: obj = ' '.join(str(word.text) for word in words[action[1]:]) elif subject_id > action[1]: subject = ' '.join(str(word.text) for word in words[action[1]:]) if action and obj and subject: return Sao(str(uuid.uuid4()), subject, action[2], obj, patent_id) return None # Функция для извлечения sao def process_sao(text: str, patent_id: str, patent_name: str, is_description: bool): descr = text if is_description: text = split_description(text) text = rem(text) saos = [] sentences = get_sentences(text) nlp = stanza.Pipeline(lang='en', processors='tokenize,mwt,pos,lemma,depparse') con = create_connection("diplom", "postgres", "postgres", "localhost", "5432") for sentence in sentences: doc = nlp(sentence) if doc.sentences: sao = get_sao(doc.sentences[0].words, patent_id) if sao: saos.append(sao) try: insert_sao(con, sao) except psycopg2.errors.UniqueViolation as e: print(e) con.close() record_sao_log(patent_name, descr, sentences, saos, 'C:/Users/mrkol/Documents/myLog/saoLog.txt') def main(): stanza.download('en') con = create_connection("diplom", "postgres", "postgres", "localhost", "5432") patents = get_entities(con, "patents") for patent_tuple in patents: patent = Patent(*patent_tuple) if patent.abstract_path: if os.path.isfile(patent.abstract_path): with open(str(patent.abstract_path), 'r', encoding='utf8') as f: lines = f.read() process_sao(lines, patent.id, patent.publication_reference, False) if patent.description_path: if os.path.isfile(patent.description_path): with open(str(patent.description_path), 'r', encoding='utf8') as f: lines = f.read() process_sao(lines, patent.id, patent.publication_reference, True) con.close() if __name__ == '__main__': main()
Kolyamba-mamba/technology-partner-search-module
modules/analyzer/psComparator.py
import stanza import os import sys from gensim.models import Word2Vec from modules.helpers.dbHelper import create_connection from modules.dbActions.getTables import get_entities_by_condition from modules.models.sao import Sao # объединение списков def merge_list(lst1, lst2): for i in lst2: if i not in lst1: lst1.append(i) return lst1 # объединение списков def merge_list_and_count_weight(lst1, lst2): for i in lst2: if i not in lst1: lst1.append(i) else: index = lst1.index(i) if index >= 0: lst1[index] = (lst1[index][0] + i[0], lst1[index][1]) return lst1 # получение элементов с уникальным родителем def get_sao_with_unique_parent(lst): result = [] item_in_list = False for l in lst: for res in result: input_sao = Sao(*l[1]) result_sao = Sao(*res[1]) if input_sao.patent_id == result_sao.patent_id: item_in_list = True break if not item_in_list: result.append(l) item_in_list = False return result # ищем совпадения с синонимами объекта def find_synonym_match(model, connection, el, type): counter = 0 sao_with_object = [] try: synonyms = model.wv.most_similar(positive=str(el)) except: print("синоним не найден") return sao_with_object while counter < len(synonyms) and counter < 8 and synonyms[counter][1] > 0.6: counter += 1 saos = get_entities_by_condition(connection, 'sao', f'''lower({type}) like '%{synonyms[counter][0].lower()}%' ''') if len(saos) > 0: saos_with_weight = list(map(lambda x: (synonyms[counter][1], x), saos)) sao_with_object = merge_list(sao_with_object, saos_with_weight) return sao_with_object # получение action и object из запроса def get_ao(query): object_deprel = ['nmod', 'obj', 'obl'] action = [] obj = [] nlp = stanza.Pipeline(lang='en', processors='tokenize,mwt,pos,lemma,depparse') doc = nlp(query) if doc.sentences: for word in doc.sentences[0].words: if word.upos == 'VERB': action.append(word.text) elif word.deprel in object_deprel: obj.append(word.text) return action, obj # Функция поиска совпадающих с запросом sao def find_match(connection, query): # stanza.download('en') model = Word2Vec.load('C:\\Users\\mrkol\\OneDrive\\Рабочий стол\\Univers\\Диплом\\technology-partner-search-module\\modules\\analyzer\\myModel.model') sao_with_action = [] sao_with_object = [] action, obj = get_ao(query) for a in action: saos = get_entities_by_condition(connection, 'sao', f'''lower(action) = '{a.lower()}' ''') if len(saos) > 0: saos_with_weight = list(map(lambda x: (1, x), saos)) sao_with_action = merge_list(sao_with_action, saos_with_weight) synonym_sao = find_synonym_match(model, connection, a, 'action') sao_with_action = merge_list(sao_with_action, synonym_sao) for o in obj: saos = get_entities_by_condition(connection, 'sao', f'''lower(object) like '%{o.lower()}%' ''') if len(saos) > 0: saos_with_weight = list(map(lambda x: (1, x), saos)) sao_with_object = merge_list(sao_with_object, saos_with_weight) synonym_sao = find_synonym_match(model, connection, o, 'object') sao_with_action = merge_list(sao_with_action, synonym_sao) match_list = merge_list_and_count_weight(sao_with_action, sao_with_object) match_list.sort(key=lambda x: (x[0]), reverse=True) result = get_sao_with_unique_parent(match_list) return result def get_patents(query): results = [] connection = create_connection("diplom", "postgres", "postgres", "localhost", "5432") # save_text_db_to_txt(connection) # create_w2v_model('C:/Users/mrkol/Documents/myLog/dataset1.txt') matches = find_match(connection, query) for match in matches: patent = get_entities_by_condition(connection, "patents", f"id = '{match[1][4]}'")[0] result = (patent[0], patent[5], patent[4], patent[1], match[1][2] + " " + match[1][3], match[1][1], patent[9]) results.append(result) return results # model = Word2Vec.load('myModel.model') # query = input() get_patents("reducing capacity")# get_patents("reducing capacity")
Kolyamba-mamba/technology-partner-search-module
modules/models/parsedPatent.py
class ParsedPatent: """Класс патентных данных после парсинга""" def __init__(self, application_reference, publication_reference, main_classification_type, main_classification, title, inventors, abstract, description, claims, assignee): self.application_reference = application_reference self.publication_reference = publication_reference self.main_classification_type = main_classification_type self.main_classification = main_classification self.title = title self.inventors = inventors self.abstract = abstract self.description = description self.claims = claims self.assignee = assignee
Kolyamba-mamba/technology-partner-search-module
modules/helpers/logHelper.py
from typing import List import os import sys from modules.models.sao import Sao def record_sao_log(patent_number: str, description_text: str, sentences: List[str], saos: List[Sao], filePath: str): try: with open(filePath, 'a', encoding="utf-8") as file: file.write(patent_number + '\n') file.write(description_text + '\n\n') file.write('Отобранные для извлечения SAO предложения:\n') for sentence in sentences: file.write(sentence + '\n') file.write('\nSAO:\n') for sao in saos: file.write('Subject: ' + sao.subject + '\n') file.write('Action: ' + sao.action + '\n') file.write('Object: ' + sao.object + '\n\n') file.write('\n') except EnvironmentError: print("Ошибка при записи в файл:" + filePath)
Kolyamba-mamba/technology-partner-search-module
mySite/searchPartners/views.py
from django.shortcuts import render import os import sys sys.path.append(os.path.abspath('..')) from modules.analyzer.psComparator import get_patents from modules.helpers.dbHelper import create_connection from modules.dbActions.getTables import get_entities_by_condition def index(request): if request.method == "POST": query = request.POST.get("input_text") matches = get_patents(str(query)) #reducing capacity return render(request, 'searchPartners/homepage.html', {'partners': matches, 'input_text': query}) else: return render(request, 'searchPartners/homepage.html') def patent(request, id): abstr = "" descr = "" claims = "" con = create_connection("diplom", "postgres", "postgres", "localhost", "5432") patent = get_entities_by_condition(con, "patents", f"id = '{str(id)}'")[0] if patent[6]: if os.path.isfile(patent[6]): with open(str(patent[6]), 'r', encoding='utf8') as f: abstr = f.read() if patent[7]: if os.path.isfile(patent[7]): with open(str(patent[7]), 'r', encoding='utf8') as f: descr = f.read() if patent[8]: if os.path.isfile(patent[8]): with open(str(patent[8]), 'r', encoding='utf8') as f: claims = f.read() return render(request, 'searchPartners/patentpage.html', {'patent': patent, 'abstr': abstr, 'descr': descr, 'claims': claims})
Kolyamba-mamba/technology-partner-search-module
modules/helpers/unpacker.py
<filename>modules/helpers/unpacker.py import os from os import path import zipfile def unpacker(input_file, output_path): try: fantasy_zip = zipfile.ZipFile(input_file) fantasy_zip.extractall(output_path) fantasy_zip.close() except: print('Ошибка при распаковке архива') def main(args): print('Запущен распаковыватель') files = os.listdir(args.path) files = list(filter(lambda x: path.splitext(path.basename(x))[1] == '.zip', files)) for file in files: unpacker(args.path+file, args.path+'unpack/') print(f'''Распаковано {len(os.listdir(args.path+'unpack/'))} из {len(files)}''')
Kolyamba-mamba/technology-partner-search-module
mySite/searchPartners/urls.py
from django.conf.urls import url from django.urls import path from . import views urlpatterns = [ path('patent/<uuid:id>/', views.patent, name='patent'), url(r'^$', views.index, name='index') ]
Kolyamba-mamba/technology-partner-search-module
modules/helpers/patentDownloader.py
<filename>modules/helpers/patentDownloader.py import requests import os from bs4 import BeautifulSoup as BS def urls_saver(args, url): filename = args.path + 'urls.txt' for year in range(2010, 2021): year_url = url + str(year) + "/" req = requests.get(year_url) html = BS(req.content, 'html.parser') tr = html.findChildren('tr') tr.pop(0) if os.path.isfile(filename): mode = 'a' else: mode = 'w' with open(filename, mode) as urls: for td in tr: href = td.contents[0].text download_url = year_url + href urls.write(download_url + '\n') return filename def downloader(args, url): filename = url[url.rfind('/') + 1:] successPath = args.path + 'success.txt' errorPath = args.path + 'error.txt' if os.path.isfile(successPath): with open(successPath) as sp: success = sp.readlines() if url + '\n' in success: return try: r = requests.get(url, stream=True) print(f"Загрузка {url}") with open(args.path + filename, 'wb') as f: for chunk in r.iter_content(chunk_size=1024): if chunk: f.write(chunk) with open(successPath, 'a') as success_txt: success_txt.write(url + '\n') print(f"Загрузка {url} прошла успешно") except: with open(errorPath, 'a') as error_txt: error_txt.write(str(url) + '\n') print(f"Ошибка при загрузке {url}") def main(args): url = 'https://bulkdata.uspto.gov/data/patent/grant/redbook/fulltext/' if not os.path.isdir(args.path): os.makedirs(args.path) if args.saveUrl: file_url = urls_saver(args, url) else: file_url = args.urlsPath try: with open(file_url, 'r') as f: for line in f: downloader(args, line.rstrip('\n')) except: print('Error')
Kolyamba-mamba/technology-partner-search-module
modules/models/patent.py
<gh_stars>1-10 class Patent: """Класс патента""" def __init__(self, id, publication_reference, main_classification_type, main_classification, title, inventors, abstract_path, description_path, claims_path, assignee): self.id = id self.publication_reference = publication_reference self.main_classification_type = main_classification_type self.main_classification = main_classification self.title = title self.inventors = inventors self.abstract_path = abstract_path self.description_path = description_path self.claims_path = claims_path self.assignee = assignee
Kolyamba-mamba/technology-partner-search-module
modules/analyzer/w2v_module/word2vec.py
import nltk import os import re from nltk.corpus import stopwords from gensim.models import Word2Vec def prepare_dataset(dataset): stop_words = stopwords.words('english') # Очистка print("Привеодим к нижнему регистру") processed_article = dataset.lower() print("Удаляем все кроме слов") processed_article = re.sub(r'[^a-zA-Z\.]', ' ', processed_article) processed_article = processed_article.replace('fig', ' ') print("Удаляем лишние пробелы") processed_article = re.sub(r'\s+', ' ', processed_article) # Подготовка данных print("Разбиваем на предложения") all_sentences = nltk.sent_tokenize(processed_article) print("Разбиваем на слова") all_words = [nltk.word_tokenize(sent) for sent in all_sentences] # Удаление стоп слов print("Удаляем стоп слова") for i in range(len(all_words)): all_words[i] = [w for w in all_words[i] if w not in stop_words] return all_words def create_w2v_model(path): # nltk.download('punkt') # nltk.download('stopwords') if os.path.isfile(path): with open(str(path), 'r', encoding='utf8') as f: dataset = f.read() words = prepare_dataset(dataset) print("Обучение модели") model = Word2Vec(words, vector_size=50, window=5, min_count=2, workers=6, epochs=5) print("Сохранение модели") model.save('myModel.model')
Kolyamba-mamba/technology-partner-search-module
modules/analyzer/save_txt.py
<reponame>Kolyamba-mamba/technology-partner-search-module import os import sys sys.path.append(os.path.abspath('../../mySite/mySite')) from modules.dbActions.getTables import get_abstract_and_descr_path from modules.helpers.saoSelector import rem, split_description def save_text_db_to_txt(con, filename_base = 'C:/Users/mrkol/Documents/myLog/dataset.txt'): # Берем тексты патентов из БД paths = get_abstract_and_descr_path(con) # Сохраняем в файлы для обучения модели for i, el in enumerate(paths): try: with open(filename_base, 'a', encoding="utf-8") as file: if el[0]: if os.path.isfile(el[0]): with open(str(el[0]), 'r', encoding='utf8') as f: file.write(f.read()) if el[1]: if os.path.isfile(el[1]): with open(str(el[1]), 'r', encoding='utf8') as f: file.write(f.read()) except EnvironmentError: print("Ошибка при записи в файл:" + filename_base) return filename_base def save_text_db_to_txt2(con, filename_base = 'C:/Users/mrkol/Documents/myLog/dataset.txt'): # Берем тексты патентов из БД paths = get_abstract_and_descr_path(con) # Сохраняем в файлы для обучения модели for i, el in enumerate(paths): try: with open(filename_base, 'a', encoding="utf-8") as file: if el[0]: if os.path.isfile(el[0]): with open(str(el[0]), 'r', encoding='utf8') as f: text = f.read() text = rem(text) file.write(text) if el[1]: if os.path.isfile(el[1]): with open(str(el[1]), 'r', encoding='utf8') as f: text = f.read() text = split_description(text) text = rem(text) file.write(text) except EnvironmentError: print("Ошибка при записи в файл:" + filename_base) return filename_base
xtrp/studio-filters
main.py
from PIL import Image, ImageDraw from flask import Flask, Response from mss import mss import face_recognition, cv2, io, numpy SCREENSHOT_COORDS = (78,0,1200,800) # map but converts to list def map_to_list(func, iter_obj): return list(map(func, iter_obj)) def toBytes(image): imageByteArr = io.BytesIO() image.save(imageByteArr, format='JPEG') return imageByteArr.getvalue() def create_image(image, pil_image, dimensions_match_multiplier): def match_dimensions(e): return (e[0] * dimensions_match_multiplier, e[1] * dimensions_match_multiplier) # find facial features in all the faces in the image face_landmarks_list = face_recognition.face_landmarks(image) for face_landmarks in face_landmarks_list: draw_obj = ImageDraw.Draw(pil_image, 'RGBA') # match dimensions for all landmarks face_landmarks['left_eyebrow'] = map_to_list(match_dimensions, face_landmarks['left_eyebrow']) face_landmarks['right_eyebrow'] = map_to_list(match_dimensions, face_landmarks['right_eyebrow']) face_landmarks['top_lip'] = map_to_list(match_dimensions, face_landmarks['top_lip']) face_landmarks['bottom_lip'] = map_to_list(match_dimensions, face_landmarks['bottom_lip']) face_landmarks['left_eye'] = map_to_list(match_dimensions, face_landmarks['left_eye']) face_landmarks['right_eye'] = map_to_list(match_dimensions, face_landmarks['right_eye']) # eyebrows draw_obj.polygon(face_landmarks['left_eyebrow'], fill=(255, 255, 0, 127)) draw_obj.polygon(face_landmarks['right_eyebrow'], fill=(255, 255, 0, 127)) # lipstick draw_obj.polygon(face_landmarks['top_lip'], fill=(0, 0, 255, 127)) draw_obj.polygon(face_landmarks['bottom_lip'], fill=(0, 0, 255, 127)) # eyeliner draw_obj.line(face_landmarks['left_eye'] + [face_landmarks['left_eye'][0]], fill="#000", width=5) draw_obj.line(face_landmarks['right_eye'] + [face_landmarks['right_eye'][0]], fill="#000", width=5) # initialize mustache landmarks def mustache_from_lip(arr): for i, e in enumerate(arr): arr[i] = ((e[0], e[1] - SCREENSHOT_COORDS[3] * 0.01383399209 )) return arr mustache_landmarks = mustache_from_lip(face_landmarks['top_lip']) # mustache draw_obj.polygon(mustache_landmarks, fill=(255, 0, 0, 127)) return toBytes(pil_image) def getResizeDimensions(initialWidth, initialHeight, targetPixelCount): divisor = (initialWidth * initialHeight / targetPixelCount) ** .5 newWidth, newHeight = int(initialWidth // divisor), int(initialHeight // divisor) return newWidth, newHeight def screenshot_and_filter(screenshot_obj): global SCREENSHOT_COORDS screenshot_obj.get_pixels({ 'top': SCREENSHOT_COORDS[0], 'left': SCREENSHOT_COORDS[1], 'width': SCREENSHOT_COORDS[2], 'height': SCREENSHOT_COORDS[3] }) img = Image.frombytes('RGB', (screenshot_obj.width, screenshot_obj.height), screenshot_obj.image) image_to_filter_dimensions = getResizeDimensions(img.size[0], img.size[1], 100000) dimensions_match_multiplier = img.size[0] / image_to_filter_dimensions[0] image_to_filter = img.resize(image_to_filter_dimensions, Image.ANTIALIAS) image_to_filter = cv2.cvtColor(numpy.array(image_to_filter), cv2.COLOR_RGB2BGR) rVal = create_image(image_to_filter, img, dimensions_match_multiplier) return rVal app = Flask(__name__) def gen(): with mss() as screenshot_obj: while True: frame = screenshot_and_filter(screenshot_obj) if(frame): yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n') @app.route('/') def video_feed(): return Response(gen(), mimetype='multipart/x-mixed-replace; boundary=frame') if __name__ == '__main__': app.run(host='0.0.0.0', debug=True, port=5000)
Mahmoud-Khaled-Nasr/opencv-python-training
assets/classifier.py
<reponame>Mahmoud-Khaled-Nasr/opencv-python-training<gh_stars>1-10 from __future__ import absolute_import from __future__ import division from __future__ import print_function __version__ = '1.0.0' __author__ = '<NAME>' import os import cv2 import timeit import numpy as np import tensorflow as tf camera = cv2.VideoCapture(0) # Loads label file, strips off carriage return label_lines = [line.rstrip() for line in tf.gfile.GFile('retrained_labels.txt')] def grabVideoFeed(): '''Returns camera frame if available, otherwise None''' grabbed, frame = camera.read() return frame if grabbed else None def initialSetup(): '''Loads the retrained MobilNet model''' # INFO and WARNING MESSAGES are not printed os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' start_time = timeit.default_timer() # This takes 2-5 seconds to run # Unpersists graph from file with tf.gfile.FastGFile('retrained_graph.pb', 'rb') as f: graph_def = tf.GraphDef() graph_def.ParseFromString(f.read()) tf.import_graph_def(graph_def, name='') print('Took {} seconds to unpersist the graph'.format(timeit.default_timer() - start_time)) initialSetup() with tf.Session() as sess: start_time = timeit.default_timer() # Feed the image_data as input to the graph and get first prediction softmax_tensor = sess.graph.get_tensor_by_name('final_result:0') print('Took {} seconds to feed data to graph'.format(timeit.default_timer() - start_time)) while True: frame = grabVideoFeed() if frame is None: raise SystemError('Issue grabbing the frame') frame = cv2.resize(frame, (224, 224), interpolation=cv2.INTER_CUBIC) cv2.imshow('Main', frame) # adhere to TS graph input structure numpy_frame = np.asarray(frame) numpy_frame = cv2.normalize(numpy_frame.astype('float'), None, -0.5, 0.5, cv2.NORM_MINMAX) numpy_final = np.expand_dims(numpy_frame, axis=0) start_time = timeit.default_timer() # This takes 2-5 seconds as well predictions = sess.run(softmax_tensor, {'input:0': numpy_final}) print('Took {} seconds to perform prediction'.format(timeit.default_timer() - start_time)) start_time = timeit.default_timer() # Sort to show labels of first prediction in order of confidence top_k = predictions[0].argsort()[-len(predictions[0]):][::-1] print('Took {} seconds to sort the predictions'.format(timeit.default_timer() - start_time)) for node_id in top_k: human_string = label_lines[node_id] score = predictions[0][node_id] print('%s (score = %.5f)' % (human_string, score)) print('********* Session Ended *********') if cv2.waitKey(1) & 0xFF == ord('q'): sess.close() break camera.release() cv2.destroyAllWindows()
jsirois/pants
src/python/pants/testutil/rule_runner.py
# Copyright 2020 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import annotations import multiprocessing import os from contextlib import contextmanager from dataclasses import dataclass from io import StringIO from pathlib import Path, PurePath from tempfile import mkdtemp from types import CoroutineType, GeneratorType from typing import Any, Callable, Iterable, Iterator, Mapping, Sequence, Tuple, Type, TypeVar, cast from colors import blue, cyan, green, magenta, red, yellow from pants.base.build_root import BuildRoot from pants.base.deprecated import deprecated from pants.base.specs_parser import SpecsParser from pants.build_graph.build_configuration import BuildConfiguration from pants.build_graph.build_file_aliases import BuildFileAliases from pants.engine.addresses import Address from pants.engine.console import Console from pants.engine.environment import CompleteEnvironment from pants.engine.fs import PathGlobs, PathGlobsAndRoot, Snapshot, Workspace from pants.engine.goal import Goal from pants.engine.internals.native_engine import PyExecutor from pants.engine.internals.scheduler import SchedulerSession from pants.engine.internals.selectors import Get, Params from pants.engine.internals.session import SessionValues from pants.engine.process import InteractiveRunner from pants.engine.rules import QueryRule as QueryRule from pants.engine.rules import Rule from pants.engine.target import Target, WrappedTarget from pants.engine.unions import UnionMembership from pants.init.engine_initializer import EngineInitializer from pants.init.logging import initialize_stdio, stdio_destination from pants.option.global_options import ExecutionOptions, GlobalOptions from pants.option.options_bootstrapper import OptionsBootstrapper from pants.source import source_root from pants.testutil.option_util import create_options_bootstrapper from pants.util.collections import assert_single_element from pants.util.contextutil import temporary_dir, temporary_file from pants.util.dirutil import ( recursive_dirname, safe_file_dump, safe_mkdir, safe_mkdtemp, safe_open, ) from pants.util.ordered_set import FrozenOrderedSet # ----------------------------------------------------------------------------------------------- # `RuleRunner` # ----------------------------------------------------------------------------------------------- _O = TypeVar("_O") _EXECUTOR = PyExecutor( core_threads=multiprocessing.cpu_count(), max_threads=multiprocessing.cpu_count() * 4 ) @dataclass(frozen=True) class GoalRuleResult: exit_code: int stdout: str stderr: str @staticmethod def noop() -> GoalRuleResult: return GoalRuleResult(0, stdout="", stderr="") # This is not frozen because we need to update the `scheduler` when setting options. @dataclass class RuleRunner: build_root: str options_bootstrapper: OptionsBootstrapper build_config: BuildConfiguration scheduler: SchedulerSession def __init__( self, *, rules: Iterable | None = None, target_types: Iterable[type[Target]] | None = None, objects: dict[str, Any] | None = None, context_aware_object_factories: dict[str, Any] | None = None, isolated_local_store: bool = False, ca_certs_path: str | None = None, ) -> None: self.build_root = os.path.realpath(mkdtemp(suffix="_BUILD_ROOT")) safe_mkdir(self.build_root, clean=True) safe_mkdir(self.pants_workdir) BuildRoot().path = self.build_root # TODO: Redesign rule registration for tests to be more ergonomic and to make this less # special-cased. all_rules = ( *(rules or ()), *source_root.rules(), QueryRule(WrappedTarget, [Address]), QueryRule(UnionMembership, []), ) build_config_builder = BuildConfiguration.Builder() build_config_builder.register_aliases( BuildFileAliases( objects=objects, context_aware_object_factories=context_aware_object_factories ) ) build_config_builder.register_rules(all_rules) build_config_builder.register_target_types(target_types or ()) self.build_config = build_config_builder.create() self.environment = CompleteEnvironment({}) self.options_bootstrapper = create_options_bootstrapper() options = self.options_bootstrapper.full_options(self.build_config) global_options = self.options_bootstrapper.bootstrap_options.for_global_scope() local_store_dir = ( os.path.realpath(safe_mkdtemp()) if isolated_local_store else global_options.local_store_dir ) local_execution_root_dir = global_options.local_execution_root_dir named_caches_dir = global_options.named_caches_dir graph_session = EngineInitializer.setup_graph_extended( pants_ignore_patterns=GlobalOptions.compute_pants_ignore( self.build_root, global_options ), use_gitignore=False, local_store_dir=local_store_dir, local_execution_root_dir=local_execution_root_dir, named_caches_dir=named_caches_dir, build_root=self.build_root, build_configuration=self.build_config, executor=_EXECUTOR, execution_options=ExecutionOptions.from_options(options, self.environment), ca_certs_path=ca_certs_path, native_engine_visualize_to=None, ).new_session( build_id="buildid_for_test", session_values=SessionValues( { OptionsBootstrapper: self.options_bootstrapper, CompleteEnvironment: self.environment, } ), ) self.scheduler = graph_session.scheduler_session def __repr__(self) -> str: return f"RuleRunner(build_root={self.build_root})" @property def pants_workdir(self) -> str: return os.path.join(self.build_root, ".pants.d") @property def rules(self) -> FrozenOrderedSet[Rule]: return self.build_config.rules @property def target_types(self) -> FrozenOrderedSet[Type[Target]]: return self.build_config.target_types @property def union_membership(self) -> UnionMembership: """An instance of `UnionMembership` with all the test's registered `UnionRule`s.""" return self.request(UnionMembership, []) def new_session(self, build_id: str) -> None: """Mutates this RuleRunner to begin a new Session with the same Scheduler.""" self.scheduler = self.scheduler.scheduler.new_session(build_id) def request(self, output_type: Type[_O], inputs: Iterable[Any]) -> _O: result = assert_single_element( self.scheduler.product_request(output_type, [Params(*inputs)]) ) return cast(_O, result) def run_goal_rule( self, goal: Type[Goal], *, global_args: Iterable[str] | None = None, args: Iterable[str] | None = None, env: Mapping[str, str] | None = None, env_inherit: set[str] | None = None, ) -> GoalRuleResult: merged_args = (*(global_args or []), goal.name, *(args or [])) self.set_options(merged_args, env=env, env_inherit=env_inherit) raw_specs = self.options_bootstrapper.full_options_for_scopes( [*GlobalOptions.known_scope_infos(), *goal.subsystem_cls.known_scope_infos()] ).specs specs = SpecsParser(self.build_root).parse_specs(raw_specs) stdout, stderr = StringIO(), StringIO() console = Console(stdout=stdout, stderr=stderr) exit_code = self.scheduler.run_goal_rule( goal, Params( specs, console, Workspace(self.scheduler), InteractiveRunner(self.scheduler), ), ) console.flush() return GoalRuleResult(exit_code, stdout.getvalue(), stderr.getvalue()) def set_options( self, args: Iterable[str], *, env: Mapping[str, str] | None = None, env_inherit: set[str] | None = None, ) -> None: """Update the engine session with new options and/or environment variables. The environment variables will be used to set the `CompleteEnvironment`, which is the environment variables captured by the parent Pants process. Some rules use this to be able to read arbitrary env vars. Any options that start with `PANTS_` will also be used to set options. Environment variables listed in `env_inherit` and not in `env` will be inherited from the test runner's environment (os.environ) This will override any previously configured values. """ env = { **{k: os.environ[k] for k in (env_inherit or set()) if k in os.environ}, **(env or {}), } self.options_bootstrapper = create_options_bootstrapper(args=args, env=env) self.environment = CompleteEnvironment(env) self.scheduler = self.scheduler.scheduler.new_session( build_id="buildid_for_test", session_values=SessionValues( { OptionsBootstrapper: self.options_bootstrapper, CompleteEnvironment: self.environment, } ), ) def _invalidate_for(self, *relpaths): """Invalidates all files from the relpath, recursively up to the root. Many python operations implicitly create parent directories, so we assume that touching a file located below directories that do not currently exist will result in their creation. """ files = {f for relpath in relpaths for f in recursive_dirname(relpath)} return self.scheduler.invalidate_files(files) def create_dir(self, relpath: str) -> str: """Creates a directory under the buildroot. :API: public relpath: The relative path to the directory from the build root. """ path = os.path.join(self.build_root, relpath) safe_mkdir(path) self._invalidate_for(relpath) return path def create_file(self, relpath: str, contents: bytes | str = "", mode: str = "w") -> str: """Writes to a file under the buildroot. :API: public relpath: The relative path to the file from the build root. contents: A string containing the contents of the file - '' by default.. mode: The mode to write to the file in - over-write by default. """ path = os.path.join(self.build_root, relpath) with safe_open(path, mode=mode) as fp: fp.write(contents) self._invalidate_for(relpath) return path def create_files(self, path: str, files: Iterable[str]) -> None: """Writes to a file under the buildroot with contents same as file name. :API: public path: The relative path to the file from the build root. files: List of file names. """ for f in files: self.create_file(os.path.join(path, f), contents=f) def add_to_build_file( self, relpath: str | PurePath, target: str, *, overwrite: bool = False ) -> str: """Adds the given target specification to the BUILD file at relpath. :API: public relpath: The relative path to the BUILD file from the build root. target: A string containing the target definition as it would appear in a BUILD file. overwrite: Whether to overwrite vs. append to the BUILD file. """ build_path = ( relpath if PurePath(relpath).name.startswith("BUILD") else PurePath(relpath, "BUILD") ) mode = "w" if overwrite else "a" return self.create_file(str(build_path), target, mode=mode) def make_snapshot(self, files: Mapping[str, str | bytes]) -> Snapshot: """Makes a snapshot from a map of file name to file content.""" with temporary_dir() as temp_dir: for file_name, content in files.items(): mode = "wb" if isinstance(content, bytes) else "w" safe_file_dump(os.path.join(temp_dir, file_name), content, mode=mode) return self.scheduler.capture_snapshots( (PathGlobsAndRoot(PathGlobs(("**",)), temp_dir),) )[0] def make_snapshot_of_empty_files(self, files: Iterable[str]) -> Snapshot: """Makes a snapshot with empty content for each file. This is a convenience around `TestBase.make_snapshot`, which allows specifying the content for each file. """ return self.make_snapshot({fp: "" for fp in files}) def get_target(self, address: Address) -> Target: """Find the target for a given address. This requires that the target actually exists, i.e. that you called `rule_runner.add_to_build_file()`. """ return self.request(WrappedTarget, [address]).target # ----------------------------------------------------------------------------------------------- # `run_rule_with_mocks()` # ----------------------------------------------------------------------------------------------- # TODO(#6742): Improve the type signature by using generics and type vars. `mock` should be # `Callable[[InputType], OutputType]`. @dataclass(frozen=True) class MockGet: output_type: Type input_type: Type mock: Callable[[Any], Any] # TODO: Improve the type hints so that the return type can be inferred. def run_rule_with_mocks( rule: Callable, *, rule_args: Sequence[Any] | None = None, mock_gets: Sequence[MockGet] | None = None, union_membership: UnionMembership | None = None, ): """A test helper function that runs an @rule with a set of arguments and mocked Get providers. An @rule named `my_rule` that takes one argument and makes no `Get` requests can be invoked like so: ``` return_value = run_rule_with_mocks(my_rule, rule_args=[arg1]) ``` In the case of an @rule that makes Get requests, things get more interesting: the `mock_gets` argument must be provided as a sequence of `MockGet`s. Each MockGet takes the Product and Subject type, along with a one-argument function that takes a subject value and returns a product value. So in the case of an @rule named `my_co_rule` that takes one argument and makes Get requests for a product type `Listing` with subject type `Dir`, the invoke might look like: ``` return_value = run_rule_with_mocks( my_co_rule, rule_args=[arg1], mock_gets=[ MockGet( output_type=Listing, input_type=Dir, mock=lambda dir_subject: Listing(..), ), ], ) ``` If any of the @rule's Get requests involve union members, you should pass a `UnionMembership` mapping the union base to any union members you'd like to test. For example, if your rule has `await Get(TestResult, TargetAdaptor, target_adaptor)`, you may pass `UnionMembership({TargetAdaptor: PythonTestsTargetAdaptor})` to this function. :returns: The return value of the completed @rule. """ task_rule = getattr(rule, "rule", None) if task_rule is None: raise TypeError(f"Expected to receive a decorated `@rule`; got: {rule}") if rule_args is not None and len(rule_args) != len(task_rule.input_selectors): raise ValueError( f"Rule expected to receive arguments of the form: {task_rule.input_selectors}; got: {rule_args}" ) if mock_gets is not None and len(mock_gets) != len(task_rule.input_gets): raise ValueError( f"Rule expected to receive Get providers for {task_rule.input_gets}; got: {mock_gets}" ) res = rule(*(rule_args or ())) if not isinstance(res, (CoroutineType, GeneratorType)): return res def get(product, subject): provider = next( ( mock_get.mock for mock_get in mock_gets if mock_get.output_type == product and ( mock_get.input_type == type(subject) or ( union_membership and union_membership.is_member(mock_get.input_type, subject) ) ) ), None, ) if provider is None: raise AssertionError( f"Rule requested: Get{(product, type(subject), subject)}, which cannot be satisfied." ) return provider(subject) rule_coroutine = res rule_input = None while True: try: res = rule_coroutine.send(rule_input) if isinstance(res, Get): rule_input = get(res.output_type, res.input) elif type(res) in (tuple, list): rule_input = [get(g.output_type, g.input) for g in res] else: return res except StopIteration as e: if e.args: return e.value @contextmanager def mock_console( options_bootstrapper: OptionsBootstrapper, *, stdin_content: bytes | str | None = None, ) -> Iterator[Tuple[Console, StdioReader]]: global_bootstrap_options = options_bootstrapper.bootstrap_options.for_global_scope() @contextmanager def stdin_context(): if stdin_content is None: yield open("/dev/null", "r") else: with temporary_file(binary_mode=isinstance(stdin_content, bytes)) as stdin_file: stdin_file.write(stdin_content) stdin_file.close() yield open(stdin_file.name, "r") with initialize_stdio(global_bootstrap_options), stdin_context() as stdin, temporary_file( binary_mode=False ) as stdout, temporary_file(binary_mode=False) as stderr, stdio_destination( stdin_fileno=stdin.fileno(), stdout_fileno=stdout.fileno(), stderr_fileno=stderr.fileno(), ): # NB: We yield a Console without overriding the destination argument, because we have # already done a sys.std* level replacement. The replacement is necessary in order for # InteractiveProcess to have native file handles to interact with. yield Console(use_colors=global_bootstrap_options.colors), StdioReader( _stdout=Path(stdout.name), _stderr=Path(stderr.name) ) @dataclass class StdioReader: _stdout: Path _stderr: Path def get_stdout(self) -> str: """Return all data that has been flushed to stdout so far.""" return self._stdout.read_text() def get_stderr(self) -> str: """Return all data that has been flushed to stderr so far.""" return self._stderr.read_text() class MockConsole: """An implementation of pants.engine.console.Console which captures output.""" @deprecated("2.5.0.dev0", hint_message="Use the mock_console contextmanager instead.") def __init__(self, use_colors=True): self.stdout = StringIO() self.stderr = StringIO() self.use_colors = use_colors def write_stdout(self, payload): self.stdout.write(payload) def write_stderr(self, payload): self.stderr.write(payload) def print_stdout(self, payload): print(payload, file=self.stdout) def print_stderr(self, payload): print(payload, file=self.stderr) def _safe_color(self, text: str, color: Callable[[str], str]) -> str: return color(text) if self.use_colors else text def blue(self, text: str) -> str: return self._safe_color(text, blue) def cyan(self, text: str) -> str: return self._safe_color(text, cyan) def green(self, text: str) -> str: return self._safe_color(text, green) def magenta(self, text: str) -> str: return self._safe_color(text, magenta) def red(self, text: str) -> str: return self._safe_color(text, red) def yellow(self, text: str) -> str: return self._safe_color(text, yellow)
jsirois/pants
src/python/pants/goal/run_tracker.py
<gh_stars>0 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import annotations import getpass import logging import os import socket import sys import time import uuid from collections import OrderedDict from pathlib import Path from typing import Any, Dict, List, Optional from pants.base.build_environment import get_buildroot from pants.base.exiter import PANTS_SUCCEEDED_EXIT_CODE, ExitCode from pants.engine.internals import native_engine from pants.option.config import Config from pants.option.options import Options from pants.option.options_fingerprinter import CoercingOptionEncoder from pants.option.scope import GLOBAL_SCOPE, GLOBAL_SCOPE_CONFIG_SECTION from pants.util.dirutil import safe_mkdir_for from pants.version import VERSION logger = logging.getLogger(__name__) class RunTrackerOptionEncoder(CoercingOptionEncoder): """Use the json encoder we use for making options hashable to support datatypes. This encoder also explicitly allows OrderedDict inputs, as we accept more than just option values when encoding stats to json. """ def default(self, o): if isinstance(o, OrderedDict): return o return super().default(o) class RunTracker: """Tracks and times the execution of a single Pants run.""" def __init__(self, options: Options): """ :API: public """ self._has_started: bool = False self._has_ended: bool = False # Select a globally unique ID for the run, that sorts by time. run_timestamp = time.time() run_uuid = uuid.uuid4().hex str_time = time.strftime("%Y_%m_%d_%H_%M_%S", time.localtime(run_timestamp)) millis = int((run_timestamp * 1000) % 1000) self.run_id = f"pants_run_{str_time}_{millis}_{run_uuid}" self._all_options = options info_dir = os.path.join(self._all_options.for_global_scope().pants_workdir, "run-tracker") self._run_info: Dict[str, Any] = {} # pantsd stats. self._pantsd_metrics: Dict[str, int] = dict() self.run_logs_file = Path(info_dir, self.run_id, "logs") safe_mkdir_for(str(self.run_logs_file)) native_engine.set_per_run_log_path(str(self.run_logs_file)) # Initialized in `start()`. self._run_start_time: Optional[float] = None self._run_total_duration: Optional[float] = None @property def goals(self) -> List[str]: return self._all_options.goals if self._all_options else [] def start(self, run_start_time: float, specs: List[str]) -> None: """Start tracking this pants run.""" if self._has_started: raise AssertionError("RunTracker.start must not be called multiple times.") self._has_started = True # Initialize the run. self._run_start_time = run_start_time datetime = time.strftime("%A %b %d, %Y %H:%M:%S", time.localtime(run_start_time)) cmd_line = " ".join(["pants"] + sys.argv[1:]) self._run_info.update( { "id": self.run_id, "timestamp": run_start_time, "datetime": datetime, "user": getpass.getuser(), "machine": socket.gethostname(), "buildroot": get_buildroot(), "path": get_buildroot(), "version": VERSION, "cmd_line": cmd_line, "specs_from_command_line": specs, } ) def set_pantsd_scheduler_metrics(self, metrics: Dict[str, int]) -> None: self._pantsd_metrics = metrics @property def pantsd_scheduler_metrics(self) -> Dict[str, int]: return dict(self._pantsd_metrics) # defensive copy def run_information(self) -> Dict[str, Any]: """Basic information about this run.""" return self._run_info def has_ended(self) -> bool: return self._has_ended def end_run(self, exit_code: ExitCode) -> None: """This pants run is over, so stop tracking it. Note: If end_run() has been called once, subsequent calls are no-ops. """ if self.has_ended(): return self._has_ended = True if self._run_start_time is None: raise Exception("RunTracker.end_run() called without calling .start()") duration = time.time() - self._run_start_time self._total_run_time = duration outcome_str = "SUCCESS" if exit_code == PANTS_SUCCEEDED_EXIT_CODE else "FAILURE" self._run_info["outcome"] = outcome_str native_engine.set_per_run_log_path(None) def get_cumulative_timings(self) -> List[Dict[str, Any]]: return [{"label": "main", "timing": self._total_run_time}] def get_options_to_record(self) -> dict: recorded_options = {} scopes = self._all_options.for_global_scope().stats_record_option_scopes if "*" in scopes: scopes = self._all_options.known_scope_to_info.keys() if self._all_options else [] for scope in scopes: scope_and_maybe_option = scope.split("^") if scope == GLOBAL_SCOPE: scope = GLOBAL_SCOPE_CONFIG_SECTION recorded_options[scope] = self._get_option_to_record(*scope_and_maybe_option) return recorded_options def _get_option_to_record(self, scope, option=None): """Looks up an option scope (and optionally option therein) in the options parsed by Pants. Returns a dict of of all options in the scope, if option is None. Returns the specific option if option is not None. Raises ValueError if scope or option could not be found. """ scope_to_look_up = scope if scope != GLOBAL_SCOPE_CONFIG_SECTION else "" try: value = self._all_options.for_scope( scope_to_look_up, inherit_from_enclosing_scope=False ).as_dict() if option is None: return value else: return value[option] except (Config.ConfigValidationError, AttributeError) as e: option_str = "" if option is None else f" option {option}" raise ValueError( f"Couldn't find option scope {scope}{option_str} for recording ({e!r})" ) def retrieve_logs(self) -> List[str]: """Get a list of every log entry recorded during this run.""" if not self.run_logs_file: return [] output = [] try: with open(self.run_logs_file, "r") as f: output = f.readlines() except OSError as e: logger.warning("Error retrieving per-run logs from RunTracker.", exc_info=e) return output @property def counter_names(self) -> tuple[str, ...]: return tuple(native_engine.all_counter_names())
Bonder-liang/007
test/login.py
num1=10 num2=20 num3=300 num3=30 num4=40
sunyymq/crawlers
txsp/encrypt.py
<filename>txsp/encrypt.py #!/usr/bin/env python import struct DELTA = 0x9e3779b9 ROUNDS = 16 SALT_LEN = 2 ZERO_LEN = 7 SEED = 0xdead def rand(): global SEED if SEED == 0: SEED = 123459876 k1 = 0xffffffff & (-2836 * (SEED / 127773)) k2 = 0xffffffff & (16807 * (SEED % 127773)) SEED = 0xffffffff & (k1 + k2) if SEED < 0: SEED = SEED + 2147483647 return SEED def pack(data): target = [] for i in data: target.extend(struct.pack('>I', i)) target = [ord(c) for c in target] return target def unpack(data): data = ''.join([chr(b) for b in data]) target = [] for i in range(0, len(data), 4): target.extend(struct.unpack('>I', data[i:i+4])) return target def tea_encrypt(v, key): s = 0 key = unpack(key) v = unpack(v) for i in range(ROUNDS): s += DELTA s &= 0xffffffff v[0] += (v[1]+s) ^ ((v[1]>>5)+key[1]) ^ ((v[1]<<4)+key[0]) v[0] &= 0xffffffff v[1] += (v[0]+s) ^ ((v[0]>>5)+key[3]) ^ ((v[0]<<4)+key[2]) v[1] &= 0xffffffff return pack(v) def oi_symmetry_encrypt2(raw_data, key): pad_salt_body_zero_len = 1 + SALT_LEN + len(raw_data) + ZERO_LEN pad_len = pad_salt_body_zero_len % 8 if pad_len: pad_len = 8 - pad_len data = [] data.append(rand() & 0xf8 | pad_len) while pad_len + SALT_LEN: data.append(rand() & 0xff) pad_len = pad_len - 1 data.extend(raw_data) data.extend([0x00] * ZERO_LEN) temp = [0x00] * 8 enc = tea_encrypt(data[:8], key) for i in range(8, len(data), 8): d1 = data[i:] for j in range(8): d1[j] = d1[j] ^ enc[i-8+j] d1 = tea_encrypt(d1, key) for j in range(8): d1[j] = d1[j] ^ data[i-8+j] ^ temp[j] enc.append(d1[j]) temp[j] = enc[i-8+j] return enc if __name__ == '__main__': def print_hex(d): for i in range(len(d)): print '0x%02X,' % d[i], if i and not (i+1) % 16: print print data = [ 0x00, 0x70, 0x00, 0x00, 0x54, 0x03, 0xBC, 0xDB, 0x40, 0xBA, 0x00, 0x00, 0x2A, 0x96, 0x00, 0x0D, 0xF8, 0x9B, 0x56, 0x03, 0xC1, 0x97, 0x00, 0x04, 0x62, 0x63, 0x6E, 0x67, 0x00, 0x00, 0x00, 0x0A, 0x33, 0x2E, 0x32, 0x2E, 0x31, 0x39, 0x2E, 0x33, 0x33, 0x34, 0x00, 0x0B, 0x35, 0x4F, 0x30, 0x55, 0x35, 0x74, 0x76, 0x36, 0x74, 0x75, 0x56, 0x00, 0x29, 0x32, 0x39, 0x34, 0x33, 0x39, 0x38, 0x45, 0x39, 0x44, 0x36, 0x30, 0x30, 0x45, 0x44, 0x34, 0x34, 0x35, 0x32, 0x45, 0x41, 0x44, 0x34, 0x41, 0x39, 0x33, 0x35, 0x37, 0x34, 0x41, 0x31, 0x31, 0x38, 0x39, 0x39, 0x34, 0x43, 0x30, 0x31, 0x32, 0x43, 0x35, 0x1F, 0xA5, 0x3B, 0xDB, 0x1F, 0xA5, 0x3B, 0xDB, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00 ] key = [ 0xfa, 0x82, 0xde, 0xb5, 0x2d, 0x4b, 0xba, 0x31, 0x39, 0x6, 0x33, 0xee, 0xfb, 0xbf, 0xf3, 0xb6 ] print_hex(key) print_hex(data) enc = oi_symmetry_encrypt2(data, key) print_hex(enc)
sunyymq/crawlers
xlkk/kkdl.py
<gh_stars>1-10 #!/usr/bin/env python from mechanize import Browser from lxml import etree, html import hashlib import os import re import random import sys import time USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.10; rv:33.0) Gecko/20100101 Firefox/33.0' AGENT_VER = '5050' def md5(data): m = hashlib.md5() m.update(data) return m.hexdigest() def get_url(browser, page_url, working_dir=None): page_data = None if working_dir: filehash = md5(page_url) page_file = os.path.join(working_dir, filehash) if os.path.exists(page_file): page_data = open(page_file, 'rb').read() if not page_data: resp = browser.open(page_url) page_data = resp.read() if working_dir: open(page_file, 'wb').write(page_data) return html.fromstring(page_data) def to_dict(json_object): class global_dict(dict): def __getitem__(self, key): return key return eval(json_object, global_dict()) def random1(length): chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' selected = [] while len(selected) < length: selected.append(chars[random.randint(0, len(chars)-1)]) return ''.join(selected).upper() def random2(length): chars = '689XL' selected = [] while len(selected) < length: selected.append(chars[random.randint(0, len(chars)-1)]) return ''.join(selected).upper() def generate_referer(): referer = 'KKVPVOD-%s-%s-%s-%s-%s%s-%s' % (AGENT_VER, random1(8), random1(4), random1(4), random2(1), random1(3), random1(12)) return referer def download_video(browser, video_url, target): size = 0 resp = browser.open(video_url) while True: data = resp.read(4096) if not data: break target.write(data) size = size + len(data) return size def download_movie(surl, video_size, target): referer = generate_referer() browser = Browser() browser.set_handle_robots(False) browser.addheaders = [('User-Agent', USER_AGENT)] gcid = surl.split('/')[4].upper() cid = surl.split('/')[5] cdn_url = 'http://p2s.cl.kankan.com/getCdnresource_flv?gcid=%s&bid=21' % gcid page = get_url(browser, cdn_url) scripts = page.xpath('/html/head/script') isp = None json_obj = None check_out_obj = None for script in scripts: for s in script.text.split('var'): s = s.strip() if s.startswith('isp'): match = re.match('isp\s?=\s?"([^"]+)";', s) isp = match.group(1) elif s.startswith('jsonObj'): match = re.match('jsonObj\s?=\s?([^$]+)', s) json_obj = to_dict(match.group(1)) elif s.startswith('jsCheckOutObj'): match = re.match('jsCheckOutObj\s?=\s?([^$]+)', s) check_out_obj = to_dict(match.group(1)) if not isp or not json_obj or not check_out_obj: raise Exception('Page may be updated') cdn = json_obj['cdnlist1'][0] key = md5('<KEY> (check_out_obj['param1'], check_out_obj['param2'])) key1 = check_out_obj['param2'] stream_url = 'http://%s:80/%s?key=%s&key1=%s' % (cdn['ip'], cdn['path'], key, key1) ts = int(1000*time.time()) flash_ver = 'id=sotester&client=FLASH%20WIN%2010,0,45,2&version=6.13.60' stream_url = '%s&ts=%d&%s' % (stream_url, ts, flash_ver) print 'Save to', target start_time = time.time() if os.path.exists(target): download_size = os.path.getsize(target) else: download_size = 0 of = open(target, 'wb+') trunk_size = 0x20000 while download_size < video_size: from_pos = download_size to_pos = download_size + trunk_size - 1 if to_pos >= video_size: to_pos = video_size - 1 tfn = '%d-%d' % (from_pos, to_pos) # path = os.path.join(target_dir, tfn) browser.addheaders = [('User-Agent', USER_AGENT), ('Referer', referer), ('Range', 'bytes=%s' % tfn)] keya = md5('<KEY>d%s' % (cid, from_pos, to_pos, ts)) download_url = '%s&keya=%s&keyb=%d&ver=%s' % (stream_url, keya, ts, AGENT_VER) trunk_start_time = time.time() real_size = download_video(browser, download_url, of) trunk_time = time.time() - trunk_start_time download_size = download_size + real_size print '[%%%02d] %d/%d in %dKB/s\r' % (download_size*100/video_size, download_size, video_size, int((real_size/trunk_time)/1024)), sys.stdout.flush() of.close() end_time = time.time() print '\nTime:%d Speed:%dKB/s' % (int(end_time - start_time), (video_size/1024.0)/(end_time - start_time)) def get_suburl(browser, page_url, target_dir): print 'GET', page_url page = get_url(browser, page_url) scripts = page.xpath('/html/script') movie_title = None movie_id = None submovie_id = None for line in scripts[0].text.split('\n'): line = line.strip() match = re.match('var\s+G_MOVIEID\s?=\s?\'(\d+)\';', line) if match: movie_id = int(match.group(1)) match = re.match('var\s+G_MOVIE_TITLE\s?=\s?\'([^\']+)\';', line) if match: movie_title = match.group(1) match = re.match('var\s+G_SUBMOVIEID\s?=\s?\'(\d+)\';', line) if match: submovie_id = int(match.group(1)) if movie_id and movie_title and submovie_id: break movie_data = None submovie_data = None for line in scripts[2].text.split('\n'): line = line.strip() match = re.match('var\s+G_MOVIE_DATA\s?=\s?([^;]+);', line) if match: movie_data = to_dict(match.group(1)) match = re.match('var\s+G_SUBMOVIE_DATA\s?=\s?([^;]+);', line) if match: submovie_data = to_dict(match.group(1)) if movie_data and submovie_data: break if submovie_id is None or movie_data is None or submovie_data is None: raise Exception('Page may be updated') # print movie_data subids = movie_data['subids'] new_movie_data = {} for i in range(len(subids)): new_movie_data[subids[i]] = {} for key in movie_data.keys(): if not movie_data[key]: continue new_movie_data[subids[i]][key] = movie_data[key][i] surl_keys = ['sids', 'surls', 'length_r', 'size'] for item in submovie_data: submovieid = item.get('submovieid') if not submovieid: continue sids = item['sids'] surls = {} for i in range(len(sids)): surls[sids[i]] = {} for k in surl_keys: surls[sids[i]][k] = item[k][i] for k in surl_keys: item.pop(k) item['surls'] = surls new_movie_data[submovieid].update(item) submovie_data = new_movie_data.get(submovie_id) print movie_title, submovie_data['subnames'], submovie_data['attracts'] print 'Length:', submovie_data['length'] surls = submovie_data['surls'].values() max_size_surl = surls[0] print 'Avaliable Sizes:', for surl in surls: if surl['size'] == 0: continue if surl['size'] > max_size_surl['size']: max_size_surl = surl print surl['size'], print print 'Size:', max_size_surl['size'] extname = os.path.splitext(max_size_surl['surls'])[1] target_name = '%s_%s_%s%s' % (movie_id, submovie_id, max_size_surl['sids'], extname) target_file = os.path.join(target_dir, target_name) download_movie(max_size_surl['surls'], max_size_surl['size'], target_file) def kkdl(page_url, target_dir): browser = Browser() browser.set_handle_robots(False) browser.addheaders = [('User-Agent', USER_AGENT)] get_suburl(browser, page_url, target_dir) if __name__ == '__main__': page_url = sys.argv[1] target_dir = sys.argv[2] kkdl(page_url, target_dir)
sunyymq/crawlers
letv/letv.py
<filename>letv/letv.py #!/usr/bin/env python from mechanize import Browser from lxml import html, etree import json import os import random import re import sys import time import urllib import urlparse USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.10; rv:33.0) Gecko/20100101 Firefox/33.0' OSTYPE = 'MacOS10.10.1' def to_dict(dict_str): class _dict(dict): def __getitem__(self, key): return key return eval(dict_str, _dict()) def ror(a, b): c = 0 while c < b: a = (0x7fffffff & (a >> 1)) + (0x80000000 & (a << 31)) c += 1 return a def get_tkey(tm=None): l2 = 773625421 if not tm: tm = int(time.time()) l3 = ror(tm, l2 % 13) l3 ^= l2 l3 = ror(l3, l2 % 17) if l3 & 0x80000000: return l3 - 0x100000000 return l3 def download_m3u8(browser, playlist, target_file, duration): of = open(target_file, 'wb') resp = browser.open(playlist) ddu = 0 dsz = 0 start_time = time.time() for line in resp.readlines(): line = line.strip() if not line: continue if line.startswith('#'): if line.startswith('#EXTINF:'): ddu += float(line[8:-1]) continue ts = time.time() resp = browser.open(line) data = resp.read() of.write(data) dsz += len(data) ts = time.time() - ts speed = (len(data)/1024)/ts print "[%%%d] %dKB/s %d/%s\r" % (ddu*100/duration, speed, dsz, '??'), sys.stdout.flush() total_time = time.time() - start_time of.close() print 'Total Size: %d' % dsz print 'Download in %ds, speed %dKB/s' % (total_time, (dsz/1024)/total_time) def get_playjson(vid, nextvid, target_dir): browser = Browser() browser.set_handle_robots(False) browser.addheaders = [ ('User-Agent', USER_AGENT), ('Referer', 'http://player.letvcdn.com/p/201411/14/10/newplayer/LetvPlayer.swf') ] param_dict = { 'id': vid, 'platid': 1, 'splatid': 101, 'format': 1, 'nextvid': nextvid, 'tkey': get_tkey(), 'domain': 'www.letv.com' } url = 'http://api.letv.com/mms/out/video/playJson?%s' % urllib.urlencode(param_dict) resp = browser.open(url) resp_body = resp.read() resp_dict = json.loads(resp_body) assert resp_dict['statuscode'] == '1001' assert resp_dict['playstatus']['status'] == '1' playurls = resp_dict['playurl']['dispatch'] domains = resp_dict['playurl']['domain'] duration = int(resp_dict['playurl']['duration']) print 'Avaliable Size:', ' '.join(playurls.keys()) keys = ['1080p', '720p', '1300', '1000', '350'] for key in keys: playurl = playurls.get(key) if playurl: break print 'Select %s' % key assert playurl tn = random.random() url = domains[0] + playurl[0] + '&ctv=pc&m3v=1&termid=1&format=1&hwtype=un&ostype=%s&tag=letv&sign=letv&expect=3&tn=%s&pay=0&rateid=%s' % (OSTYPE, tn, key) resp = browser.open(url) gslb_data = json.loads(resp.read()) # import pprint # pprint.pprint(resp_dict) # pprint.pprint(gslb_data) play_url = gslb_data.get('location') file_name_m3u8 = os.path.basename(urlparse.urlsplit(play_url).path) file_name = '%s.ts' % os.path.splitext(file_name_m3u8)[0] target_file = os.path.join(target_dir, file_name) print 'Save to %s' % target_file download_m3u8(browser, play_url, target_file, duration) return resp_dict def letv(page_url, target_dir): browser = Browser() browser.set_handle_robots(False) browser.set_handle_gzip(True) browser.addheaders = [('User-Agent', USER_AGENT)] resp = browser.open(page_url) resp_body = resp.read() tree = html.fromstring(resp_body) for script in tree.xpath('/html/head/script'): match_info = [] start = False if not script.text: continue for line in script.text.split('\n'): if not start: match = re.match('var\s+__INFO__\s?=(.+)', line) if match: start = True match_info.append(match.group(1)) else: if line.startswith('var'): start = False break hp = line.find('://') p = line.rfind('//') if p != -1 and p != hp+1: match_info.append(line[:p]) else: match_info.append(line) if match_info: break match_info = '\n'.join(match_info) match_info = to_dict(match_info) vid = match_info['video']['vid'] nextvid = match_info['video']['nextvid'] print '%s' % match_info['video']['title'] play_json = get_playjson(vid, nextvid, target_dir) if __name__ == '__main__': page_url = sys.argv[1] target_dir = sys.argv[2] letv(page_url, target_dir)